atom.io 0.14.4 → 0.14.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/data/dist/index.cjs +47 -1416
  2. package/data/dist/index.cjs.map +1 -1
  3. package/data/dist/index.d.cts +16 -317
  4. package/data/dist/index.d.ts +16 -317
  5. package/data/dist/index.js +4 -6
  6. package/data/dist/index.js.map +1 -1
  7. package/dist/chunk-NYTGCPHB.js +261 -0
  8. package/dist/chunk-NYTGCPHB.js.map +1 -0
  9. package/dist/chunk-PZLG2HP3.js +36 -0
  10. package/dist/chunk-PZLG2HP3.js.map +1 -0
  11. package/dist/chunk-XACXFU3B.js +46 -0
  12. package/dist/chunk-XACXFU3B.js.map +1 -0
  13. package/dist/index.cjs +55 -2330
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.d.cts +21 -269
  16. package/dist/index.d.ts +21 -269
  17. package/dist/index.js +152 -1
  18. package/dist/index.js.map +1 -1
  19. package/dist/metafile-cjs.json +1 -1
  20. package/dist/metafile-esm.json +1 -1
  21. package/internal/dist/index.cjs +30 -159
  22. package/internal/dist/index.cjs.map +1 -1
  23. package/internal/dist/index.d.cts +28 -229
  24. package/internal/dist/index.d.ts +28 -229
  25. package/internal/dist/index.js +2027 -1
  26. package/internal/dist/index.js.map +1 -1
  27. package/introspection/dist/index.cjs +45 -1565
  28. package/introspection/dist/index.cjs.map +1 -1
  29. package/introspection/dist/index.d.cts +4 -376
  30. package/introspection/dist/index.d.ts +4 -376
  31. package/introspection/dist/index.js +298 -2
  32. package/introspection/dist/index.js.map +1 -1
  33. package/json/dist/index.cjs +5 -1502
  34. package/json/dist/index.cjs.map +1 -1
  35. package/json/dist/index.d.cts +7 -373
  36. package/json/dist/index.d.ts +7 -373
  37. package/json/dist/index.js +37 -1
  38. package/json/dist/index.js.map +1 -1
  39. package/package.json +1 -1
  40. package/react/dist/index.cjs +14 -1549
  41. package/react/dist/index.cjs.map +1 -1
  42. package/react/dist/index.d.cts +4 -377
  43. package/react/dist/index.d.ts +4 -377
  44. package/react/dist/index.js +62 -2
  45. package/react/dist/index.js.map +1 -1
  46. package/react-devtools/dist/index.cjs +135 -2153
  47. package/react-devtools/dist/index.cjs.map +1 -1
  48. package/react-devtools/dist/index.d.cts +24 -149
  49. package/react-devtools/dist/index.d.ts +24 -149
  50. package/react-devtools/dist/index.js +5 -3
  51. package/react-devtools/dist/index.js.map +1 -1
  52. package/realtime-client/dist/index.cjs +34 -1529
  53. package/realtime-client/dist/index.cjs.map +1 -1
  54. package/realtime-client/dist/index.d.cts +12 -384
  55. package/realtime-client/dist/index.d.ts +12 -384
  56. package/realtime-client/dist/index.js +165 -2
  57. package/realtime-client/dist/index.js.map +1 -1
  58. package/realtime-react/dist/index.cjs +35 -1727
  59. package/realtime-react/dist/index.cjs.map +1 -1
  60. package/realtime-react/dist/index.d.cts +9 -49
  61. package/realtime-react/dist/index.d.ts +9 -49
  62. package/realtime-react/dist/index.js +66 -4
  63. package/realtime-react/dist/index.js.map +1 -1
  64. package/realtime-server/dist/index.cjs +57 -1548
  65. package/realtime-server/dist/index.cjs.map +1 -1
  66. package/realtime-server/dist/index.d.cts +11 -394
  67. package/realtime-server/dist/index.d.ts +11 -394
  68. package/realtime-server/dist/index.js +21 -27
  69. package/realtime-server/dist/index.js.map +1 -1
  70. package/realtime-testing/dist/index.cjs +15 -2376
  71. package/realtime-testing/dist/index.cjs.map +1 -1
  72. package/realtime-testing/dist/index.d.cts +3 -489
  73. package/realtime-testing/dist/index.d.ts +3 -489
  74. package/realtime-testing/dist/index.js +10 -9
  75. package/realtime-testing/dist/index.js.map +1 -1
  76. package/transceivers/set-rtx/dist/index.cjs +9 -31
  77. package/transceivers/set-rtx/dist/index.cjs.map +1 -1
  78. package/transceivers/set-rtx/dist/index.d.cts +3 -29
  79. package/transceivers/set-rtx/dist/index.d.ts +3 -29
  80. package/transceivers/set-rtx/dist/index.js +3 -2
  81. package/transceivers/set-rtx/dist/index.js.map +1 -1
  82. package/dist/chunk-GMN5KH6A.js +0 -309
  83. package/dist/chunk-GMN5KH6A.js.map +0 -1
  84. package/dist/chunk-HQWWV67P.js +0 -62
  85. package/dist/chunk-HQWWV67P.js.map +0 -1
  86. package/dist/chunk-MK4OJD24.js +0 -67
  87. package/dist/chunk-MK4OJD24.js.map +0 -1
  88. package/dist/chunk-N7ADBQJG.js +0 -176
  89. package/dist/chunk-N7ADBQJG.js.map +0 -1
  90. package/dist/chunk-PURABO5G.js +0 -2581
  91. package/dist/chunk-PURABO5G.js.map +0 -1
@@ -1,3 +1,2029 @@
1
- export { FamilyTracker, Future, IMPLICIT, LazyMap, NotFoundError, StatefulSubject, Store, Subject, TRANSACTION_PHASES, Tracker, abortTransaction, addAtomToTimeline, applyTransaction, become, buildTransaction, cacheValue, clearStore, closeOperation, createAtom, createAtomFamily, createMutableAtom, createMutableAtomFamily, createReadonlySelectorFamily, createSelector, createSelectorFamily, createTimeline, createTransaction, deleteAtom, deleteSelector, deposit, eldest, evictCachedValue, getJsonFamily, getJsonToken, getSelectorDependencyKeys, getUpdateFamily, getUpdateToken, isAtomDefault, isAtomKey, isDone, isReadonlySelectorKey, isSelectorDefault, isSelectorKey, isStateKey, isTransceiver, isValueCached, markAtomAsDefault, markAtomAsNotDefault, markDone, newest, openOperation, readCachedValue, readOrComputeValue, redoTransactionUpdate, registerSelector, setAtomOrSelector, subscribeToRootAtoms, subscribeToState, subscribeToTimeline, subscribeToTransaction, timeTravel, traceAllSelectorAtoms, traceSelectorAtoms, undoTransactionUpdate, updateSelectorAtoms, withdraw, withdrawNewFamilyMember } from '../../dist/chunk-PURABO5G.js';
1
+ import { Junction } from '../../dist/chunk-NYTGCPHB.js';
2
+ import { __spreadValues, __spreadProps } from '../../dist/chunk-PZLG2HP3.js';
3
+ import { AtomIOLogger, getState, setState, runTransaction } from 'atom.io';
4
+ import { selectJson, stringifyJson, parseJson, selectJsonFamily } from 'atom.io/json';
5
+ import { withdraw as withdraw$1, subscribeToRootAtoms as subscribeToRootAtoms$1 } from 'atom.io/internal';
6
+
7
+ // internal/src/future.ts
8
+ var Future = class extends Promise {
9
+ constructor(executor) {
10
+ super((resolve, reject) => {
11
+ const pass = (value) => this.isCanceled ? reject(`canceled`) : resolve(value);
12
+ const fail = (reason) => this.isCanceled ? reject(`canceled`) : reject(reason);
13
+ if (typeof executor === `function`) {
14
+ executor(pass, fail);
15
+ } else {
16
+ executor.then(pass, fail);
17
+ }
18
+ });
19
+ this.isCanceled = false;
20
+ }
21
+ cancel() {
22
+ this.isCanceled = true;
23
+ }
24
+ };
25
+
26
+ // internal/src/lineage.ts
27
+ function newest(scion) {
28
+ while (scion.child !== null) {
29
+ scion = scion.child;
30
+ }
31
+ return scion;
32
+ }
33
+ function eldest(scion) {
34
+ while (scion.parent !== null) {
35
+ scion = scion.parent;
36
+ }
37
+ return scion;
38
+ }
39
+
40
+ // internal/src/caching.ts
41
+ function cacheValue(key, value, subject, store) {
42
+ const target = newest(store);
43
+ const currentValue = target.valueMap.get(key);
44
+ if (currentValue instanceof Future) {
45
+ currentValue.cancel();
46
+ }
47
+ if (value instanceof Promise) {
48
+ const future = new Future(value);
49
+ newest(store).valueMap.set(key, future);
50
+ future.then((resolved) => {
51
+ if (future.isCanceled) {
52
+ return;
53
+ }
54
+ cacheValue(key, resolved, subject, store);
55
+ subject.next({ newValue: resolved, oldValue: future });
56
+ }).catch((thrown) => {
57
+ if (thrown !== `canceled`) {
58
+ store.logger.error(`\u{1F4A5}`, `state`, key, `rejected:`, thrown);
59
+ }
60
+ });
61
+ return future;
62
+ }
63
+ target.valueMap.set(key, value);
64
+ return value;
65
+ }
66
+ var readCachedValue = (key, store) => {
67
+ return newest(store).valueMap.get(key);
68
+ };
69
+ var isValueCached = (key, store) => {
70
+ return newest(store).valueMap.has(key);
71
+ };
72
+ var evictCachedValue = (key, store) => {
73
+ const core = newest(store);
74
+ const currentValue = core.valueMap.get(key);
75
+ if (currentValue instanceof Future) {
76
+ currentValue.cancel();
77
+ }
78
+ if (core.operation.open) {
79
+ core.operation.prev.set(key, currentValue);
80
+ }
81
+ core.valueMap.delete(key);
82
+ store.logger.info(`\u{1F5D1}`, `state`, key, `evicted`);
83
+ };
84
+
85
+ // internal/src/read-or-compute-value.ts
86
+ var readOrComputeValue = (state, store) => {
87
+ if (isValueCached(state.key, store)) {
88
+ store.logger.info(`\u{1F4D6}`, state.type, state.key, `reading cached value`);
89
+ return readCachedValue(state.key, store);
90
+ }
91
+ if (state.type !== `atom`) {
92
+ store.logger.info(`\u{1F9EE}`, state.type, state.key, `computing value`);
93
+ return state.get();
94
+ }
95
+ const fallback = state.default instanceof Function ? state.default() : state.default;
96
+ store.logger.info(
97
+ `\u{1F481}`,
98
+ `atom`,
99
+ state.key,
100
+ `could not find cached value; using default`,
101
+ fallback
102
+ );
103
+ return state.default instanceof Function ? state.default() : state.default;
104
+ };
105
+
106
+ // internal/src/operation.ts
107
+ var openOperation = (token, store) => {
108
+ const target = newest(store);
109
+ if (target.operation.open) {
110
+ store.logger.error(
111
+ `\u274C`,
112
+ token.type,
113
+ token.key,
114
+ `failed to setState during a setState for "${target.operation.token.key}"`
115
+ );
116
+ return `rejection`;
117
+ }
118
+ target.operation = {
119
+ open: true,
120
+ done: /* @__PURE__ */ new Set(),
121
+ prev: /* @__PURE__ */ new Map(),
122
+ time: Date.now(),
123
+ token
124
+ };
125
+ store.logger.info(
126
+ `\u2B55`,
127
+ token.type,
128
+ token.key,
129
+ `operation start in store "${store.config.name}"${target.transactionMeta === null ? `` : ` ${target.transactionMeta.phase} "${target.transactionMeta.update.key}"`}`
130
+ );
131
+ };
132
+ var closeOperation = (store) => {
133
+ const target = newest(store);
134
+ if (target.operation.open) {
135
+ store.logger.info(
136
+ `\u{1F534}`,
137
+ target.operation.token.type,
138
+ target.operation.token.key,
139
+ `operation done in store "${store.config.name}"`
140
+ );
141
+ }
142
+ target.operation = { open: false };
143
+ store.subject.operationStatus.next(target.operation);
144
+ };
145
+ var isDone = (key, store) => {
146
+ const target = newest(store);
147
+ if (!target.operation.open) {
148
+ store.logger.warn(
149
+ `\u{1F41E}`,
150
+ `unknown`,
151
+ key,
152
+ `isDone called outside of an operation. This is probably a bug.`
153
+ );
154
+ return true;
155
+ }
156
+ return target.operation.done.has(key);
157
+ };
158
+ var markDone = (key, store) => {
159
+ const target = newest(store);
160
+ if (!target.operation.open) {
161
+ store.logger.warn(
162
+ `\u{1F41E}`,
163
+ `unknown`,
164
+ key,
165
+ `markDone called outside of an operation. This is probably a bug.`
166
+ );
167
+ return;
168
+ }
169
+ target.operation.done.add(key);
170
+ };
171
+
172
+ // internal/src/set-state/become.ts
173
+ var become = (nextVersionOfThing) => (originalThing) => nextVersionOfThing instanceof Function ? nextVersionOfThing(
174
+ originalThing instanceof Function ? originalThing() : originalThing
175
+ ) : nextVersionOfThing;
176
+
177
+ // internal/src/subject.ts
178
+ var Subject = class {
179
+ constructor() {
180
+ this.subscribers = /* @__PURE__ */ new Map();
181
+ }
182
+ subscribe(key, subscriber) {
183
+ this.subscribers.set(key, subscriber);
184
+ const unsubscribe = () => this.unsubscribe(key);
185
+ return unsubscribe;
186
+ }
187
+ unsubscribe(key) {
188
+ this.subscribers.delete(key);
189
+ }
190
+ next(value) {
191
+ const subscribers = this.subscribers.values();
192
+ for (const subscriber of subscribers) {
193
+ subscriber(value);
194
+ }
195
+ }
196
+ };
197
+ var StatefulSubject = class extends Subject {
198
+ constructor(initialState) {
199
+ super();
200
+ this.state = initialState;
201
+ }
202
+ next(value) {
203
+ this.state = value;
204
+ super.next(value);
205
+ }
206
+ };
207
+
208
+ // internal/src/set-state/copy-mutable-if-needed.ts
209
+ function copyMutableIfNeeded(atom, transform, origin, target) {
210
+ const originValue = origin.valueMap.get(atom.key);
211
+ const targetValue = target.valueMap.get(atom.key);
212
+ if (originValue === targetValue) {
213
+ origin.logger.info(`\u{1F4C3}`, `atom`, `${atom.key}`, `copying`);
214
+ const jsonValue = transform.toJson(originValue);
215
+ const copiedValue = transform.fromJson(jsonValue);
216
+ target.valueMap.set(atom.key, copiedValue);
217
+ new Tracker(atom, origin);
218
+ return copiedValue;
219
+ }
220
+ return targetValue;
221
+ }
222
+
223
+ // internal/src/set-state/copy-mutable-in-transaction.ts
224
+ function copyMutableIfWithinTransaction(oldValue, atom, store) {
225
+ const target = newest(store);
226
+ const parent = target.parent;
227
+ if (parent !== null) {
228
+ if (`toJson` in atom && `fromJson` in atom) {
229
+ const copiedValue = copyMutableIfNeeded(atom, atom, parent, target);
230
+ return copiedValue;
231
+ }
232
+ if (`family` in atom) {
233
+ const family = parent.families.get(atom.family.key);
234
+ if (family && family.type === `atom_family`) {
235
+ const result = copyMutableFamilyMemberWithinTransaction(
236
+ atom,
237
+ family,
238
+ parent,
239
+ target
240
+ );
241
+ if (result) {
242
+ return result;
243
+ }
244
+ }
245
+ }
246
+ }
247
+ return oldValue;
248
+ }
249
+ function copyMutableFamilyMemberWithinTransaction(atom, family, origin, target) {
250
+ if (`toJson` in family && `fromJson` in family) {
251
+ const copyCreated = copyMutableIfNeeded(atom, family, origin, target);
252
+ return copyCreated;
253
+ }
254
+ return null;
255
+ }
256
+
257
+ // internal/src/set-state/emit-update.ts
258
+ var emitUpdate = (state, update, store) => {
259
+ store.logger.info(
260
+ `\u{1F4E2}`,
261
+ state.type,
262
+ state.key,
263
+ `went (`,
264
+ update.oldValue,
265
+ `->`,
266
+ update.newValue,
267
+ `) subscribers:`,
268
+ state.subject.subscribers
269
+ );
270
+ state.subject.next(update);
271
+ };
272
+
273
+ // internal/src/set-state/evict-downstream.ts
274
+ var evictDownStream = (atom, store) => {
275
+ const target = newest(store);
276
+ const downstreamKeys = target.selectorAtoms.getRelatedKeys(atom.key);
277
+ store.logger.info(
278
+ `\u{1F9F9}`,
279
+ atom.type,
280
+ atom.key,
281
+ downstreamKeys ? `evicting ${downstreamKeys.size} states downstream:` : `no downstream states`,
282
+ downstreamKeys != null ? downstreamKeys : `to evict`
283
+ );
284
+ if (downstreamKeys) {
285
+ if (target.operation.open) {
286
+ store.logger.info(
287
+ `\u{1F9F9}`,
288
+ atom.type,
289
+ atom.key,
290
+ `[ ${[...target.operation.done].join(`, `)} ] already done`
291
+ );
292
+ }
293
+ for (const key of downstreamKeys) {
294
+ if (isDone(key, store)) {
295
+ continue;
296
+ }
297
+ evictCachedValue(key, store);
298
+ markDone(key, store);
299
+ }
300
+ }
301
+ };
302
+
303
+ // internal/src/set-state/stow-update.ts
304
+ function shouldUpdateBeStowed(key, update) {
305
+ if (isTransceiver(update.newValue)) {
306
+ return false;
307
+ }
308
+ if (key.includes(`\u{1F441}\u200D\u{1F5E8}`)) {
309
+ return false;
310
+ }
311
+ return true;
312
+ }
313
+ var stowUpdate = (state, update, store) => {
314
+ const { key } = state;
315
+ const target = newest(store);
316
+ if (target.transactionMeta === null || target.transactionMeta.phase !== `building`) {
317
+ store.logger.error(
318
+ `\u{1F41E}`,
319
+ `atom`,
320
+ key,
321
+ `stowUpdate called outside of a transaction. This is probably a bug.`
322
+ );
323
+ return;
324
+ }
325
+ const shouldStow = shouldUpdateBeStowed(key, update);
326
+ if (!shouldStow) {
327
+ return;
328
+ }
329
+ const atomUpdate = __spreadValues({ key }, update);
330
+ if (state.family) {
331
+ atomUpdate.family = state.family;
332
+ }
333
+ target.transactionMeta.update.updates.push(atomUpdate);
334
+ store.logger.info(
335
+ `\u{1F4C1}`,
336
+ `atom`,
337
+ key,
338
+ `stowed (`,
339
+ update.oldValue,
340
+ `->`,
341
+ update.newValue,
342
+ `)`
343
+ );
344
+ };
345
+
346
+ // internal/src/set-state/set-atom.ts
347
+ var setAtom = (atom, next, store) => {
348
+ const target = newest(store);
349
+ const oldValue = readOrComputeValue(atom, store);
350
+ let newValue = copyMutableIfWithinTransaction(oldValue, atom, store);
351
+ newValue = become(next)(newValue);
352
+ store.logger.info(`\u{1F4DD}`, `atom`, atom.key, `set to`, newValue);
353
+ newValue = cacheValue(atom.key, newValue, atom.subject, store);
354
+ if (isAtomDefault(atom.key, store)) {
355
+ markAtomAsNotDefault(atom.key, store);
356
+ }
357
+ markDone(atom.key, store);
358
+ evictDownStream(atom, store);
359
+ const update = { oldValue, newValue };
360
+ if (target.transactionMeta === null || target.transactionMeta.phase === `applying`) {
361
+ emitUpdate(atom, update, store);
362
+ } else {
363
+ stowUpdate(atom, update, store);
364
+ }
365
+ };
366
+
367
+ // internal/src/set-state/set-atom-or-selector.ts
368
+ var setAtomOrSelector = (state, value, store) => {
369
+ if (state.type === `selector`) {
370
+ state.set(value);
371
+ } else {
372
+ setAtom(state, value, store);
373
+ }
374
+ };
375
+
376
+ // internal/src/store/deposit.ts
377
+ function deposit(state) {
378
+ const token = {
379
+ key: state.key,
380
+ type: state.type
381
+ };
382
+ if (`family` in state) {
383
+ token.family = state.family;
384
+ }
385
+ return token;
386
+ }
387
+ var Store = class {
388
+ constructor(name, store = null) {
389
+ this.parent = null;
390
+ this.child = null;
391
+ this.valueMap = /* @__PURE__ */ new Map();
392
+ this.atoms = /* @__PURE__ */ new Map();
393
+ this.selectors = /* @__PURE__ */ new Map();
394
+ this.readonlySelectors = /* @__PURE__ */ new Map();
395
+ this.trackers = /* @__PURE__ */ new Map();
396
+ this.families = /* @__PURE__ */ new Map();
397
+ this.timelines = /* @__PURE__ */ new Map();
398
+ this.transactions = /* @__PURE__ */ new Map();
399
+ this.atomsThatAreDefault = /* @__PURE__ */ new Set();
400
+ this.timelineAtoms = new Junction({
401
+ between: [`timelineKey`, `atomKey`],
402
+ cardinality: `1:n`
403
+ });
404
+ this.selectorAtoms = new Junction({
405
+ between: [`selectorKey`, `atomKey`],
406
+ cardinality: `n:n`
407
+ });
408
+ this.selectorGraph = new Junction(
409
+ {
410
+ between: [`upstreamSelectorKey`, `downstreamSelectorKey`],
411
+ cardinality: `n:n`
412
+ },
413
+ {
414
+ makeContentKey: (...keys) => keys.sort().join(`:`)
415
+ }
416
+ );
417
+ this.subject = {
418
+ atomCreation: new Subject(),
419
+ selectorCreation: new Subject(),
420
+ transactionCreation: new Subject(),
421
+ timelineCreation: new Subject(),
422
+ transactionApplying: new StatefulSubject(null),
423
+ operationStatus: new Subject()
424
+ };
425
+ this.operation = { open: false };
426
+ this.transactionMeta = null;
427
+ this.config = {
428
+ name: `IMPLICIT_STORE`
429
+ };
430
+ this.loggers = [
431
+ new AtomIOLogger(`warn`, (_, __, key) => !key.includes(`\u{1F441}\u200D\u{1F5E8}`))
432
+ ];
433
+ this.logger = {
434
+ error: (...messages) => {
435
+ for (const logger of this.loggers)
436
+ logger.error(...messages);
437
+ },
438
+ info: (...messages) => {
439
+ for (const logger of this.loggers)
440
+ logger.info(...messages);
441
+ },
442
+ warn: (...messages) => {
443
+ for (const logger of this.loggers)
444
+ logger.warn(...messages);
445
+ }
446
+ };
447
+ if (store !== null) {
448
+ this.valueMap = new Map(store == null ? void 0 : store.valueMap);
449
+ this.operation = __spreadValues({}, store == null ? void 0 : store.operation);
450
+ this.transactionMeta = (store == null ? void 0 : store.transactionMeta) ? __spreadValues({}, store == null ? void 0 : store.transactionMeta) : null;
451
+ this.config = __spreadProps(__spreadValues({}, store == null ? void 0 : store.config), {
452
+ name
453
+ });
454
+ for (const [, atom] of store.atoms) {
455
+ atom.install(this);
456
+ }
457
+ for (const [, selector] of store.readonlySelectors) {
458
+ selector.install(this);
459
+ }
460
+ for (const [, selector] of store.selectors) {
461
+ selector.install(this);
462
+ }
463
+ for (const [, tx] of store.transactions) {
464
+ tx.install(this);
465
+ }
466
+ for (const [, timeline] of store.timelines) {
467
+ timeline.install(this);
468
+ }
469
+ }
470
+ }
471
+ };
472
+ var IMPLICIT = {
473
+ STORE_INTERNAL: void 0,
474
+ get STORE() {
475
+ var _a;
476
+ return (_a = this.STORE_INTERNAL) != null ? _a : this.STORE_INTERNAL = new Store(`IMPLICIT_STORE`);
477
+ }
478
+ };
479
+ var clearStore = (store) => {
480
+ const { config } = store;
481
+ Object.assign(store, new Store(config.name));
482
+ store.config = config;
483
+ };
484
+
485
+ // internal/src/store/withdraw.ts
486
+ function withdraw(token, store) {
487
+ var _a, _b, _c, _d;
488
+ const target = newest(store);
489
+ const state = (_d = (_c = (_b = (_a = target.atoms.get(token.key)) != null ? _a : target.selectors.get(token.key)) != null ? _b : target.readonlySelectors.get(token.key)) != null ? _c : target.transactions.get(token.key)) != null ? _d : target.timelines.get(token.key);
490
+ if (state) {
491
+ return state;
492
+ }
493
+ return void 0;
494
+ }
495
+
496
+ // internal/src/store/withdraw-new-family-member.ts
497
+ function withdrawNewFamilyMember(token, store) {
498
+ if (token.family) {
499
+ store.logger.info(
500
+ `\u{1F46A}`,
501
+ token.type,
502
+ token.key,
503
+ `creating new family member in store "${store.config.name}"`
504
+ );
505
+ const target = newest(store);
506
+ const family = target.families.get(token.family.key);
507
+ if (family) {
508
+ const jsonSubKey = JSON.parse(token.family.subKey);
509
+ family(jsonSubKey);
510
+ const state = withdraw(token, store);
511
+ return state;
512
+ }
513
+ }
514
+ return void 0;
515
+ }
516
+
517
+ // internal/src/keys.ts
518
+ var isAtomKey = (key, store) => newest(store).atoms.has(key);
519
+ var isSelectorKey = (key, store) => newest(store).selectors.has(key);
520
+ var isReadonlySelectorKey = (key, store) => newest(store).readonlySelectors.has(key);
521
+ var isStateKey = (key, store) => isAtomKey(key, store) || isSelectorKey(key, store) || isReadonlySelectorKey(key, store);
522
+
523
+ // internal/src/selector/get-selector-dependency-keys.ts
524
+ var getSelectorDependencyKeys = (key, store) => {
525
+ const sources = newest(store).selectorGraph.getRelationEntries({ downstreamSelectorKey: key }).filter(([_, { source }]) => source !== key).map(([_, { source }]) => source).filter((source) => isStateKey(source, store));
526
+ return sources;
527
+ };
528
+
529
+ // internal/src/selector/trace-selector-atoms.ts
530
+ var traceSelectorAtoms = (selectorKey, directDependencyKey, store) => {
531
+ const rootKeys = [];
532
+ const indirectDependencyKeys = getSelectorDependencyKeys(
533
+ directDependencyKey,
534
+ store
535
+ );
536
+ let depth = 0;
537
+ while (indirectDependencyKeys.length > 0) {
538
+ const indirectDependencyKey = indirectDependencyKeys.shift();
539
+ ++depth;
540
+ if (depth > 99999) {
541
+ throw new Error(
542
+ `Maximum selector dependency depth exceeded (> 99999) in selector "${selectorKey}". This is likely due to a circular dependency.`
543
+ );
544
+ }
545
+ if (!isAtomKey(indirectDependencyKey, store)) {
546
+ indirectDependencyKeys.push(
547
+ ...getSelectorDependencyKeys(indirectDependencyKey, store)
548
+ );
549
+ } else if (!rootKeys.includes(indirectDependencyKey)) {
550
+ rootKeys.push(indirectDependencyKey);
551
+ }
552
+ }
553
+ return rootKeys;
554
+ };
555
+ var traceAllSelectorAtoms = (selectorKey, store) => {
556
+ const directDependencyKeys = getSelectorDependencyKeys(selectorKey, store);
557
+ return directDependencyKeys.flatMap(
558
+ (depKey) => isAtomKey(depKey, store) ? depKey : traceSelectorAtoms(selectorKey, depKey, store)
559
+ );
560
+ };
561
+
562
+ // internal/src/selector/update-selector-atoms.ts
563
+ var updateSelectorAtoms = (selectorKey, dependency, store) => {
564
+ const target = newest(store);
565
+ if (dependency.type === `atom`) {
566
+ target.selectorAtoms.set({
567
+ selectorKey,
568
+ atomKey: dependency.key
569
+ });
570
+ store.logger.info(
571
+ `\u{1F50D}`,
572
+ `selector`,
573
+ selectorKey,
574
+ `discovers root atom "${dependency.key}"`
575
+ );
576
+ } else {
577
+ const rootKeys = traceSelectorAtoms(selectorKey, dependency.key, store);
578
+ store.logger.info(
579
+ `\u{1F50D}`,
580
+ `selector`,
581
+ selectorKey,
582
+ `discovers root atoms: [ ${rootKeys.map((key) => `"${key}"`).join(`, `)} ]`
583
+ );
584
+ for (const atomKey of rootKeys) {
585
+ target.selectorAtoms = target.selectorAtoms.set({
586
+ selectorKey,
587
+ atomKey
588
+ });
589
+ }
590
+ }
591
+ };
592
+
593
+ // internal/src/selector/register-selector.ts
594
+ var registerSelector = (selectorKey, store) => ({
595
+ get: (dependency) => {
596
+ const target = newest(store);
597
+ const alreadyRegistered = target.selectorGraph.getRelationEntries({ downstreamSelectorKey: selectorKey }).some(([_, { source }]) => source === dependency.key);
598
+ const dependencyState = withdraw(dependency, store);
599
+ if (dependencyState === void 0) {
600
+ throw new Error(
601
+ `State "${dependency.key}" not found in this store. Did you forget to initialize with the "atom" or "selector" function?`
602
+ );
603
+ }
604
+ const dependencyValue = readOrComputeValue(dependencyState, store);
605
+ store.logger.info(
606
+ `\u{1F50C}`,
607
+ `selector`,
608
+ selectorKey,
609
+ `registers dependency ( "${dependency.key}" =`,
610
+ dependencyValue,
611
+ `)`
612
+ );
613
+ if (!alreadyRegistered) {
614
+ target.selectorGraph.set(
615
+ {
616
+ upstreamSelectorKey: dependency.key,
617
+ downstreamSelectorKey: selectorKey
618
+ },
619
+ {
620
+ source: dependency.key
621
+ }
622
+ );
623
+ }
624
+ updateSelectorAtoms(selectorKey, dependency, store);
625
+ return dependencyValue;
626
+ },
627
+ set: (stateToken, newValue) => {
628
+ const state = withdraw(stateToken, store);
629
+ if (state === void 0) {
630
+ throw new Error(
631
+ `State "${stateToken.key}" not found in this store. Did you forget to initialize with the "atom" or "selector" function?`
632
+ );
633
+ }
634
+ setAtomOrSelector(state, newValue, store);
635
+ }
636
+ });
637
+
638
+ // internal/src/selector/create-read-write-selector.ts
639
+ var createReadWriteSelector = (options, family, store) => {
640
+ const target = newest(store);
641
+ const subject = new Subject();
642
+ const { get, set } = registerSelector(options.key, store);
643
+ const getSelf = () => {
644
+ const value = options.get({ get });
645
+ cacheValue(options.key, value, subject, store);
646
+ return value;
647
+ };
648
+ const setSelf = (next) => {
649
+ const oldValue = getSelf();
650
+ const newValue = become(next)(oldValue);
651
+ store.logger.info(
652
+ `\u{1F4DD}`,
653
+ `selector`,
654
+ options.key,
655
+ `set (`,
656
+ oldValue,
657
+ `->`,
658
+ newValue,
659
+ `)`
660
+ );
661
+ cacheValue(options.key, newValue, subject, store);
662
+ markDone(options.key, store);
663
+ if (target.transactionMeta === null) {
664
+ subject.next({ newValue, oldValue });
665
+ }
666
+ options.set({ get, set }, newValue);
667
+ };
668
+ const mySelector = __spreadValues(__spreadProps(__spreadValues({}, options), {
669
+ subject,
670
+ install: (s) => createSelector(options, family, s),
671
+ get: getSelf,
672
+ set: setSelf,
673
+ type: `selector`
674
+ }), family && { family });
675
+ target.selectors.set(options.key, mySelector);
676
+ const initialValue = getSelf();
677
+ store.logger.info(`\u2728`, mySelector.type, mySelector.key, `=`, initialValue);
678
+ const token = {
679
+ key: options.key,
680
+ type: `selector`
681
+ };
682
+ if (family) {
683
+ token.family = family;
684
+ }
685
+ store.subject.selectorCreation.next(token);
686
+ return token;
687
+ };
688
+
689
+ // internal/src/selector/create-readonly-selector.ts
690
+ var createReadonlySelector = (options, family, store) => {
691
+ const target = newest(store);
692
+ const subject = new Subject();
693
+ const { get } = registerSelector(options.key, store);
694
+ const getSelf = () => {
695
+ const value = options.get({ get });
696
+ cacheValue(options.key, value, subject, store);
697
+ return value;
698
+ };
699
+ const readonlySelector = __spreadValues(__spreadProps(__spreadValues({}, options), {
700
+ subject,
701
+ install: (s) => createSelector(options, family, s),
702
+ get: getSelf,
703
+ type: `readonly_selector`
704
+ }), family && { family });
705
+ target.readonlySelectors.set(options.key, readonlySelector);
706
+ const initialValue = getSelf();
707
+ store.logger.info(
708
+ `\u2728`,
709
+ readonlySelector.type,
710
+ readonlySelector.key,
711
+ `=`,
712
+ initialValue
713
+ );
714
+ const token = {
715
+ key: options.key,
716
+ type: `readonly_selector`
717
+ };
718
+ if (family) {
719
+ token.family = family;
720
+ }
721
+ store.subject.selectorCreation.next(token);
722
+ return token;
723
+ };
724
+
725
+ // internal/src/selector/create-selector.ts
726
+ function createSelector(options, family, store) {
727
+ const target = newest(store);
728
+ const existingWritable = target.selectors.get(options.key);
729
+ const existingReadonly = target.readonlySelectors.get(options.key);
730
+ if (existingWritable || existingReadonly) {
731
+ store.logger.error(
732
+ `\u274C`,
733
+ existingReadonly ? `readonly_selector` : `selector`,
734
+ options.key,
735
+ `Tried to create selector, but it already exists in the store. (Ignore if you are in development using hot module replacement.)`
736
+ );
737
+ }
738
+ if (`set` in options) {
739
+ return createReadWriteSelector(options, family, store);
740
+ }
741
+ return createReadonlySelector(options, family, store);
742
+ }
743
+
744
+ // internal/src/selector/delete-selector.ts
745
+ function deleteSelector(selectorToken, store) {
746
+ const target = newest(store);
747
+ const { key } = selectorToken;
748
+ switch (selectorToken.type) {
749
+ case `selector`:
750
+ target.selectors.delete(key);
751
+ break;
752
+ case `readonly_selector`:
753
+ target.readonlySelectors.delete(key);
754
+ break;
755
+ }
756
+ target.valueMap.delete(key);
757
+ target.selectorAtoms.delete(key);
758
+ const downstreamTokens = target.selectorGraph.getRelationEntries({ upstreamSelectorKey: key }).filter(([_, { source }]) => source === key).map(
759
+ ([downstreamSelectorKey]) => {
760
+ var _a;
761
+ return (_a = target.selectors.get(downstreamSelectorKey)) != null ? _a : target.readonlySelectors.get(downstreamSelectorKey);
762
+ }
763
+ );
764
+ for (const downstreamToken of downstreamTokens) {
765
+ if (downstreamToken) {
766
+ deleteSelector(downstreamToken, store);
767
+ }
768
+ }
769
+ target.selectorGraph.delete(key);
770
+ store.logger.info(`\u{1F525}`, selectorToken.type, `${key}`, `deleted`);
771
+ }
772
+
773
+ // internal/src/subscribe/recall-state.ts
774
+ var recallState = (state, store) => {
775
+ const target = newest(store);
776
+ if (!target.operation.open) {
777
+ return target.valueMap.get(state.key);
778
+ }
779
+ return target.operation.prev.get(state.key);
780
+ };
781
+
782
+ // internal/src/subscribe/subscribe-to-root-atoms.ts
783
+ var subscribeToRootAtoms = (state, store) => {
784
+ const dependencySubscriptions = `default` in state ? null : traceAllSelectorAtoms(state.key, store).map((atomKey) => {
785
+ const atom = store.atoms.get(atomKey);
786
+ if (atom === void 0) {
787
+ throw new Error(
788
+ `Atom "${atomKey}", a dependency of selector "${state.key}", not found in store "${store.config.name}".`
789
+ );
790
+ }
791
+ return atom.subject.subscribe(
792
+ `${state.type}:${state.key}`,
793
+ (atomChange) => {
794
+ store.logger.info(
795
+ `\u{1F4E2}`,
796
+ state.type,
797
+ state.key,
798
+ `root`,
799
+ atomKey,
800
+ `went`,
801
+ atomChange.oldValue,
802
+ `->`,
803
+ atomChange.newValue
804
+ );
805
+ const oldValue = recallState(state, store);
806
+ const newValue = readOrComputeValue(state, store);
807
+ store.logger.info(
808
+ `\u2728`,
809
+ state.type,
810
+ state.key,
811
+ `went`,
812
+ oldValue,
813
+ `->`,
814
+ newValue
815
+ );
816
+ state.subject.next({ newValue, oldValue });
817
+ }
818
+ );
819
+ });
820
+ return dependencySubscriptions;
821
+ };
822
+ function subscribeToState(token, handleUpdate, key, store) {
823
+ const state = withdraw$1(token, store);
824
+ if (state === void 0) {
825
+ throw new Error(
826
+ `State "${token.key}" not found in this store. Did you forget to initialize with the "atom" or "selector" function?`
827
+ );
828
+ }
829
+ const unsubFunction = state.subject.subscribe(key, handleUpdate);
830
+ store.logger.info(`\u{1F440}`, state.type, state.key, `Adding subscription "${key}"`);
831
+ const dependencyUnsubFunctions = state.type !== `atom` ? subscribeToRootAtoms$1(state, store) : null;
832
+ const unsubscribe = dependencyUnsubFunctions === null ? () => {
833
+ store.logger.info(
834
+ `\u{1F648}`,
835
+ state.type,
836
+ state.key,
837
+ `Removing subscription "${key}"`
838
+ );
839
+ unsubFunction();
840
+ } : () => {
841
+ store.logger.info(
842
+ `\u{1F648}`,
843
+ state.type,
844
+ state.key,
845
+ `Removing subscription "${key}"`
846
+ );
847
+ unsubFunction();
848
+ for (const unsubFromDependency of dependencyUnsubFunctions) {
849
+ unsubFromDependency();
850
+ }
851
+ };
852
+ return unsubscribe;
853
+ }
854
+ var subscribeToTimeline = (token, handleUpdate, key, store) => {
855
+ const tl = withdraw$1(token, store);
856
+ if (tl === void 0) {
857
+ throw new Error(
858
+ `Cannot subscribe to timeline "${token.key}": timeline not found in store "${store.config.name}".`
859
+ );
860
+ }
861
+ store.logger.info(`\u{1F440}`, `timeline`, token.key, `Adding subscription "${key}"`);
862
+ const unsubscribe = tl.subject.subscribe(key, handleUpdate);
863
+ return () => {
864
+ store.logger.info(
865
+ `\u{1F648}`,
866
+ `timeline`,
867
+ token.key,
868
+ `Removing subscription "${key}" from timeline`
869
+ );
870
+ unsubscribe();
871
+ };
872
+ };
873
+ var subscribeToTransaction = (token, handleUpdate, key, store) => {
874
+ const tx = withdraw$1(token, store);
875
+ if (tx === void 0) {
876
+ throw new Error(
877
+ `Cannot subscribe to transaction "${token.key}": transaction not found in store "${store.config.name}".`
878
+ );
879
+ }
880
+ store.logger.info(
881
+ `\u{1F440}`,
882
+ `transaction`,
883
+ token.key,
884
+ `Adding subscription "${key}"`
885
+ );
886
+ const unsubscribe = tx.subject.subscribe(key, handleUpdate);
887
+ return () => {
888
+ store.logger.info(
889
+ `\u{1F648}`,
890
+ `transaction`,
891
+ token.key,
892
+ `Removing subscription "${key}"`
893
+ );
894
+ unsubscribe();
895
+ };
896
+ };
897
+ var Tracker = class {
898
+ constructor(mutableState, store) {
899
+ this.unsubscribeFromInnerValue = null;
900
+ this.mutableState = mutableState;
901
+ const target = newest(store);
902
+ this.latestUpdateState = this.initializeState(mutableState, target);
903
+ this.observeCore(mutableState, this.latestUpdateState, target);
904
+ this.updateCore(mutableState, this.latestUpdateState, target);
905
+ target.trackers.set(mutableState.key, this);
906
+ }
907
+ initializeState(mutableState, store) {
908
+ const latestUpdateStateKey = `*${mutableState.key}`;
909
+ store.atoms.delete(latestUpdateStateKey);
910
+ store.valueMap.delete(latestUpdateStateKey);
911
+ const familyMetaData = mutableState.family ? {
912
+ key: `*${mutableState.family.key}`,
913
+ subKey: mutableState.family.subKey
914
+ } : void 0;
915
+ const latestUpdateState = createAtom(
916
+ {
917
+ key: latestUpdateStateKey,
918
+ default: null
919
+ },
920
+ familyMetaData,
921
+ store
922
+ );
923
+ if (store.parent) {
924
+ const parentValue = store.parent.valueMap.get(latestUpdateStateKey);
925
+ store.valueMap.set(latestUpdateStateKey, parentValue);
926
+ }
927
+ return latestUpdateState;
928
+ }
929
+ observeCore(mutableState, latestUpdateState, store) {
930
+ const originalInnerValue = getState(mutableState, store);
931
+ const target = newest(store);
932
+ this.unsubscribeFromInnerValue = originalInnerValue.subscribe(
933
+ `tracker:${store.config.name}:${target.transactionMeta === null ? `main` : target.transactionMeta.update.key}`,
934
+ (update) => {
935
+ const unsubscribe = store.subject.operationStatus.subscribe(
936
+ mutableState.key,
937
+ () => {
938
+ unsubscribe();
939
+ setState(latestUpdateState, update, store);
940
+ }
941
+ );
942
+ }
943
+ );
944
+ subscribeToState(
945
+ mutableState,
946
+ (update) => {
947
+ var _a;
948
+ if (update.newValue !== update.oldValue) {
949
+ (_a = this.unsubscribeFromInnerValue) == null ? void 0 : _a.call(this);
950
+ const target2 = newest(store);
951
+ this.unsubscribeFromInnerValue = update.newValue.subscribe(
952
+ `tracker:${store.config.name}:${target2.transactionMeta === null ? `main` : target2.transactionMeta.update.key}`,
953
+ (update2) => {
954
+ const unsubscribe = store.subject.operationStatus.subscribe(
955
+ mutableState.key,
956
+ () => {
957
+ unsubscribe();
958
+ setState(latestUpdateState, update2, store);
959
+ }
960
+ );
961
+ }
962
+ );
963
+ }
964
+ },
965
+ `${store.config.name}: tracker observing inner value`,
966
+ store
967
+ );
968
+ }
969
+ updateCore(mutableState, latestUpdateState, store) {
970
+ subscribeToState(
971
+ latestUpdateState,
972
+ ({ newValue, oldValue }) => {
973
+ const timelineId = store.timelineAtoms.getRelatedKey(
974
+ latestUpdateState.key
975
+ );
976
+ if (timelineId) {
977
+ const timelineData = store.timelines.get(timelineId);
978
+ if (timelineData == null ? void 0 : timelineData.timeTraveling) {
979
+ const unsubscribe2 = subscribeToTimeline(
980
+ { key: timelineId, type: `timeline` },
981
+ (update) => {
982
+ unsubscribe2();
983
+ setState(
984
+ mutableState,
985
+ (transceiver) => {
986
+ if (update === `redo` && newValue) {
987
+ transceiver.do(newValue);
988
+ } else if (update === `undo` && oldValue) {
989
+ transceiver.undo(oldValue);
990
+ }
991
+ return transceiver;
992
+ },
993
+ store
994
+ );
995
+ },
996
+ `${mutableState.key}: tracker observing timeline`,
997
+ store
998
+ );
999
+ return;
1000
+ }
1001
+ }
1002
+ const unsubscribe = store.subject.operationStatus.subscribe(
1003
+ latestUpdateState.key,
1004
+ () => {
1005
+ unsubscribe();
1006
+ const mutable = getState(mutableState, store);
1007
+ const updateNumber = newValue === null ? -1 : mutable.getUpdateNumber(newValue);
1008
+ const eventOffset = updateNumber - mutable.cacheUpdateNumber;
1009
+ if (newValue && eventOffset === 1) {
1010
+ setState(
1011
+ mutableState,
1012
+ (transceiver) => (transceiver.do(newValue), transceiver),
1013
+ store
1014
+ );
1015
+ }
1016
+ }
1017
+ );
1018
+ },
1019
+ `${store.config.name}: tracker observing latest update`,
1020
+ store
1021
+ );
1022
+ }
1023
+ };
1024
+
1025
+ // internal/src/mutable/create-mutable-atom.ts
1026
+ function createMutableAtom(options, store) {
1027
+ store.logger.info(
1028
+ `\u{1F527}`,
1029
+ `atom`,
1030
+ options.key,
1031
+ `creating in store "${store.config.name}"`
1032
+ );
1033
+ const coreState = createAtom(options, void 0, store);
1034
+ new Tracker(coreState, store);
1035
+ const jsonState = selectJson(coreState, options, store);
1036
+ const target = newest(store);
1037
+ subscribeToState(
1038
+ jsonState,
1039
+ () => {
1040
+ const trackerHasBeenInitialized = newest(store).trackers.has(coreState.key);
1041
+ if (!trackerHasBeenInitialized) {
1042
+ new Tracker(coreState, store);
1043
+ }
1044
+ },
1045
+ `tracker-initializer:${store == null ? void 0 : store.config.name}:${target.transactionMeta === null ? `main` : `${target.transactionMeta.update.key}`}`,
1046
+ store
1047
+ );
1048
+ return coreState;
1049
+ }
1050
+ function createAtomFamily(options, store) {
1051
+ const subject = new Subject();
1052
+ const atomFamily = Object.assign(
1053
+ (key) => {
1054
+ const subKey = stringifyJson(key);
1055
+ const family = { key: options.key, subKey };
1056
+ const fullKey = `${options.key}(${subKey})`;
1057
+ const existing = withdraw({ key: fullKey, type: `atom` }, store);
1058
+ let token;
1059
+ if (existing) {
1060
+ token = deposit(existing);
1061
+ } else {
1062
+ const individualOptions = {
1063
+ key: fullKey,
1064
+ default: options.default instanceof Function ? options.default(key) : options.default
1065
+ };
1066
+ if (options.effects) {
1067
+ individualOptions.effects = options.effects(key);
1068
+ }
1069
+ token = createAtom(individualOptions, family, store);
1070
+ subject.next(token);
1071
+ }
1072
+ return token;
1073
+ },
1074
+ {
1075
+ key: options.key,
1076
+ type: `atom_family`,
1077
+ subject
1078
+ }
1079
+ );
1080
+ if (`mutable` in options && typeof options.mutable === `boolean`) {
1081
+ Object.assign(atomFamily, { mutable: options.mutable });
1082
+ }
1083
+ const target = newest(store);
1084
+ target.families.set(options.key, atomFamily);
1085
+ return atomFamily;
1086
+ }
1087
+ function createReadonlySelectorFamily(options, store) {
1088
+ const subject = new Subject();
1089
+ return Object.assign(
1090
+ (key) => {
1091
+ const target = newest(store);
1092
+ const subKey = stringifyJson(key);
1093
+ const family = { key: options.key, subKey };
1094
+ const fullKey = `${options.key}(${subKey})`;
1095
+ const existing = target.readonlySelectors.get(fullKey);
1096
+ if (existing) {
1097
+ return deposit(existing);
1098
+ }
1099
+ return createSelector(
1100
+ {
1101
+ key: fullKey,
1102
+ get: options.get(key)
1103
+ },
1104
+ family,
1105
+ store
1106
+ );
1107
+ },
1108
+ {
1109
+ key: options.key,
1110
+ type: `readonly_selector_family`,
1111
+ subject
1112
+ }
1113
+ );
1114
+ }
1115
+ function createSelectorFamily(options, store) {
1116
+ const isReadonly = !(`set` in options);
1117
+ if (isReadonly) {
1118
+ return createReadonlySelectorFamily(options, store);
1119
+ }
1120
+ const target = newest(store);
1121
+ const subject = new Subject();
1122
+ const selectorFamily = Object.assign(
1123
+ (key) => {
1124
+ const subKey = stringifyJson(key);
1125
+ const family = { key: options.key, subKey };
1126
+ const fullKey = `${options.key}(${subKey})`;
1127
+ const existing = target.selectors.get(fullKey);
1128
+ if (existing) {
1129
+ return deposit(existing);
1130
+ }
1131
+ const token = createSelector(
1132
+ {
1133
+ key: fullKey,
1134
+ get: options.get(key),
1135
+ set: options.set(key)
1136
+ },
1137
+ family,
1138
+ store
1139
+ );
1140
+ subject.next(token);
1141
+ return token;
1142
+ },
1143
+ {
1144
+ key: options.key,
1145
+ type: `selector_family`
1146
+ }
1147
+ );
1148
+ target.families.set(options.key, selectorFamily);
1149
+ return selectorFamily;
1150
+ }
1151
+
1152
+ // internal/src/mutable/tracker-family.ts
1153
+ var FamilyTracker = class {
1154
+ constructor(findMutableState, store) {
1155
+ this.findLatestUpdateState = createAtomFamily(
1156
+ {
1157
+ key: `*${findMutableState.key}`,
1158
+ default: null
1159
+ },
1160
+ store
1161
+ );
1162
+ this.findMutableState = findMutableState;
1163
+ this.findMutableState.subject.subscribe(
1164
+ `store=${store.config.name}::tracker-atom-family`,
1165
+ (atomToken) => {
1166
+ if (atomToken.family) {
1167
+ const key = parseJson(atomToken.family.subKey);
1168
+ this.findLatestUpdateState(key);
1169
+ new Tracker(atomToken, store);
1170
+ }
1171
+ }
1172
+ );
1173
+ this.findLatestUpdateState.subject.subscribe(
1174
+ `store=${store.config.name}::tracker-atom-family`,
1175
+ (atomToken) => {
1176
+ if (atomToken.family) {
1177
+ const key = parseJson(atomToken.family.subKey);
1178
+ const mutableAtomToken = this.findMutableState(key);
1179
+ new Tracker(mutableAtomToken, store);
1180
+ }
1181
+ }
1182
+ );
1183
+ }
1184
+ };
1185
+
1186
+ // internal/src/mutable/create-mutable-atom-family.ts
1187
+ function createMutableAtomFamily(options, store) {
1188
+ const coreFamily = Object.assign(
1189
+ createAtomFamily(options, store),
1190
+ options
1191
+ );
1192
+ selectJsonFamily(coreFamily, options);
1193
+ new FamilyTracker(coreFamily, store);
1194
+ return coreFamily;
1195
+ }
1196
+
1197
+ // internal/src/mutable/get-json-family.ts
1198
+ var getJsonFamily = (mutableAtomFamily, store) => {
1199
+ const target = newest(store);
1200
+ const key = `${mutableAtomFamily.key}:JSON`;
1201
+ const jsonFamily = target.families.get(
1202
+ key
1203
+ );
1204
+ return jsonFamily;
1205
+ };
1206
+
1207
+ // internal/src/mutable/get-json-token.ts
1208
+ var getJsonToken = (mutableAtomToken) => {
1209
+ const key = mutableAtomToken.family ? `${mutableAtomToken.family.key}:JSON(${mutableAtomToken.family.subKey})` : `${mutableAtomToken.key}:JSON`;
1210
+ const jsonToken = { type: `selector`, key };
1211
+ if (mutableAtomToken.family) {
1212
+ jsonToken.family = {
1213
+ key: `${mutableAtomToken.family.key}:JSON`,
1214
+ subKey: mutableAtomToken.family.subKey
1215
+ };
1216
+ }
1217
+ return jsonToken;
1218
+ };
1219
+
1220
+ // internal/src/mutable/get-update-token.ts
1221
+ var getUpdateToken = (mutableAtomToken) => {
1222
+ const key = `*${mutableAtomToken.key}`;
1223
+ const updateToken = { type: `atom`, key };
1224
+ if (mutableAtomToken.family) {
1225
+ updateToken.family = {
1226
+ key: `*${mutableAtomToken.family.key}`,
1227
+ subKey: mutableAtomToken.family.subKey
1228
+ };
1229
+ }
1230
+ return updateToken;
1231
+ };
1232
+
1233
+ // internal/src/mutable/get-update-family.ts
1234
+ var getUpdateFamily = (mutableAtomFamily, store) => {
1235
+ const target = newest(store);
1236
+ const key = `*${mutableAtomFamily.key}`;
1237
+ const updateFamily = target.families.get(key);
1238
+ return updateFamily;
1239
+ };
1240
+
1241
+ // internal/src/mutable/transceiver.ts
1242
+ function isTransceiver(value) {
1243
+ return typeof value === `object` && value !== null && `do` in value && `undo` in value && `subscribe` in value;
1244
+ }
1245
+
1246
+ // internal/src/atom/is-default.ts
1247
+ var isAtomDefault = (key, store) => {
1248
+ const core = newest(store);
1249
+ return core.atomsThatAreDefault.has(key);
1250
+ };
1251
+ var markAtomAsDefault = (key, store) => {
1252
+ const core = newest(store);
1253
+ core.atomsThatAreDefault = new Set(core.atomsThatAreDefault).add(key);
1254
+ };
1255
+ var markAtomAsNotDefault = (key, store) => {
1256
+ const core = newest(store);
1257
+ core.atomsThatAreDefault = new Set(newest(store).atomsThatAreDefault);
1258
+ core.atomsThatAreDefault.delete(key);
1259
+ };
1260
+ var isSelectorDefault = (key, store) => {
1261
+ const rootKeys = traceAllSelectorAtoms(key, store);
1262
+ return rootKeys.every((rootKey) => isAtomDefault(rootKey, store));
1263
+ };
1264
+
1265
+ // internal/src/atom/create-atom.ts
1266
+ function createAtom(options, family, store) {
1267
+ store.logger.info(
1268
+ `\u{1F528}`,
1269
+ `atom`,
1270
+ options.key,
1271
+ `creating in store "${store.config.name}"`
1272
+ );
1273
+ const target = newest(store);
1274
+ const existing = target.atoms.get(options.key);
1275
+ if (existing) {
1276
+ store.logger.error(
1277
+ `\u274C`,
1278
+ `atom`,
1279
+ options.key,
1280
+ `Tried to create atom, but it already exists in the store.`,
1281
+ `(Ignore if you are in development using hot module replacement.)`
1282
+ );
1283
+ return deposit(existing);
1284
+ }
1285
+ const subject = new Subject();
1286
+ const newAtom = __spreadValues(__spreadProps(__spreadValues({}, options), {
1287
+ type: `atom`,
1288
+ install: (store2) => {
1289
+ store2.logger.info(
1290
+ `\u{1F6E0}\uFE0F`,
1291
+ `atom`,
1292
+ options.key,
1293
+ `installing in store "${store2.config.name}"`
1294
+ );
1295
+ return `mutable` in options ? createMutableAtom(options, store2) : createAtom(options, void 0, store2);
1296
+ },
1297
+ subject
1298
+ }), family && { family });
1299
+ let initialValue = options.default;
1300
+ if (options.default instanceof Function) {
1301
+ initialValue = options.default();
1302
+ }
1303
+ target.atoms.set(newAtom.key, newAtom);
1304
+ markAtomAsDefault(options.key, store);
1305
+ cacheValue(options.key, initialValue, subject, store);
1306
+ const token = deposit(newAtom);
1307
+ if (options.effects) {
1308
+ let effectIndex = 0;
1309
+ const cleanupFunctions = [];
1310
+ for (const effect of options.effects) {
1311
+ const cleanup = effect({
1312
+ setSelf: (next) => setState(token, next, store),
1313
+ onSet: (handle) => subscribeToState(token, handle, `effect[${effectIndex}]`, store)
1314
+ });
1315
+ if (cleanup) {
1316
+ cleanupFunctions.push(cleanup);
1317
+ }
1318
+ ++effectIndex;
1319
+ }
1320
+ newAtom.cleanup = () => {
1321
+ for (const cleanup of cleanupFunctions) {
1322
+ cleanup();
1323
+ }
1324
+ };
1325
+ }
1326
+ store.subject.atomCreation.next(token);
1327
+ return token;
1328
+ }
1329
+
1330
+ // internal/src/atom/delete-atom.ts
1331
+ function deleteAtom2(atomToken, store) {
1332
+ var _a, _b;
1333
+ const target = newest(store);
1334
+ const { key } = atomToken;
1335
+ const atom = target.atoms.get(key);
1336
+ if (!atom) {
1337
+ store.logger.error(
1338
+ `\u274C`,
1339
+ `atom`,
1340
+ `${key}`,
1341
+ `Tried to delete atom, but it does not exist in the store.`
1342
+ );
1343
+ }
1344
+ (_a = atom == null ? void 0 : atom.cleanup) == null ? void 0 : _a.call(atom);
1345
+ target.atoms.delete(key);
1346
+ target.valueMap.delete(key);
1347
+ const selectorKeys = target.selectorAtoms.getRelatedKeys(key);
1348
+ if (selectorKeys) {
1349
+ for (const selectorKey of selectorKeys) {
1350
+ const token = (_b = target.selectors.get(selectorKey)) != null ? _b : target.readonlySelectors.get(selectorKey);
1351
+ if (token) {
1352
+ deleteSelector(token, store);
1353
+ }
1354
+ }
1355
+ }
1356
+ target.selectorAtoms.delete(key);
1357
+ target.atomsThatAreDefault.delete(key);
1358
+ target.timelineAtoms.delete(key);
1359
+ store.logger.info(`\u{1F525}`, `atom`, `${key}`, `deleted`);
1360
+ }
1361
+
1362
+ // internal/src/lazy-map.ts
1363
+ var LazyMap = class extends Map {
1364
+ constructor(source) {
1365
+ super();
1366
+ this.source = source;
1367
+ this.deleted = /* @__PURE__ */ new Set();
1368
+ }
1369
+ get(key) {
1370
+ const has = super.has(key);
1371
+ if (has) {
1372
+ return super.get(key);
1373
+ }
1374
+ if (!this.deleted.has(key) && this.source.has(key)) {
1375
+ const value = this.source.get(key);
1376
+ return value;
1377
+ }
1378
+ return void 0;
1379
+ }
1380
+ set(key, value) {
1381
+ this.deleted.delete(key);
1382
+ return super.set(key, value);
1383
+ }
1384
+ hasOwn(key) {
1385
+ return super.has(key);
1386
+ }
1387
+ has(key) {
1388
+ return !this.deleted.has(key) && (super.has(key) || this.source.has(key));
1389
+ }
1390
+ delete(key) {
1391
+ this.deleted.add(key);
1392
+ return super.delete(key);
1393
+ }
1394
+ };
1395
+
1396
+ // internal/src/not-found-error.ts
1397
+ var capitalize = (str) => str[0].toUpperCase() + str.slice(1);
1398
+ function prettyPrintTokenType(token) {
1399
+ if (token.type === `readonly_selector`) {
1400
+ return `Readonly Selector`;
1401
+ }
1402
+ return capitalize(token.type);
1403
+ }
1404
+ var NotFoundError = class extends Error {
1405
+ constructor(token, store) {
1406
+ super(
1407
+ `${prettyPrintTokenType(token)} "${token.key}" not found in store "${store.config.name}".`
1408
+ );
1409
+ }
1410
+ };
1411
+
1412
+ // internal/src/timeline/add-atom-to-timeline.ts
1413
+ var addAtomToTimeline = (atomToken, tl, store) => {
1414
+ let maybeAtom = withdraw(atomToken, store);
1415
+ if (maybeAtom == null ? void 0 : maybeAtom.mutable) {
1416
+ console.log(`adding transceiver to timeline`, atomToken.key);
1417
+ const updateToken = getUpdateToken(atomToken);
1418
+ maybeAtom = withdraw(updateToken, store);
1419
+ }
1420
+ const atom = maybeAtom;
1421
+ if (atom === void 0) {
1422
+ throw new Error(
1423
+ `Cannot subscribe to atom "${atomToken.key}" because it has not been initialized in store "${store.config.name}"`
1424
+ );
1425
+ }
1426
+ atom.subject.subscribe(`timeline`, (update) => {
1427
+ var _a, _b, _c, _d, _e, _f;
1428
+ const target = newest(store);
1429
+ const currentSelectorKey = store.operation.open && store.operation.token.type === `selector` ? store.operation.token.key : null;
1430
+ const currentSelectorTime = store.operation.open && store.operation.token.type === `selector` ? store.operation.time : null;
1431
+ const currentTransactionKey = (_a = target.subject.transactionApplying.state) == null ? void 0 : _a.update.key;
1432
+ const currentTransactionTime = (_b = target.subject.transactionApplying.state) == null ? void 0 : _b.time;
1433
+ store.logger.info(
1434
+ `\u23F3`,
1435
+ `timeline`,
1436
+ tl.key,
1437
+ `atom`,
1438
+ atomToken.key,
1439
+ `went`,
1440
+ update.oldValue,
1441
+ `->`,
1442
+ update.newValue,
1443
+ currentTransactionKey ? `in transaction "${currentTransactionKey}"` : currentSelectorKey ? `in selector "${currentSelectorKey}"` : ``
1444
+ );
1445
+ if (tl.timeTraveling === null) {
1446
+ if (tl.selectorTime && tl.selectorTime !== currentSelectorTime) {
1447
+ const mostRecentUpdate = tl.history.at(-1);
1448
+ if (mostRecentUpdate === void 0) {
1449
+ throw new Error(
1450
+ `Timeline "${tl.key}" has a selectorTime, but no history. This is most likely a bug in AtomIO.`
1451
+ );
1452
+ }
1453
+ }
1454
+ if (currentTransactionKey) {
1455
+ const currentTransaction = withdraw(
1456
+ { key: currentTransactionKey, type: `transaction` },
1457
+ store
1458
+ );
1459
+ if (currentTransaction === void 0) {
1460
+ throw new Error(
1461
+ `Transaction "${currentTransactionKey}" not found in store "${store.config.name}". This is surprising, because we are in the application phase of "${currentTransactionKey}".`
1462
+ );
1463
+ }
1464
+ if (tl.transactionKey !== currentTransactionKey) {
1465
+ if (tl.transactionKey) {
1466
+ store.logger.error(
1467
+ `\u{1F41E}`,
1468
+ `timeline`,
1469
+ tl.key,
1470
+ `unable to resolve transaction "${tl.transactionKey}. This is probably a bug in AtomIO.`
1471
+ );
1472
+ }
1473
+ tl.transactionKey = currentTransactionKey;
1474
+ const unsubscribe = currentTransaction.subject.subscribe(
1475
+ `timeline:${tl.key}`,
1476
+ (update2) => {
1477
+ var _a2, _b2;
1478
+ unsubscribe();
1479
+ if (tl.timeTraveling === null && currentTransactionTime) {
1480
+ if (tl.at !== tl.history.length) {
1481
+ tl.history.splice(tl.at);
1482
+ }
1483
+ const filterUpdates = (updates2) => updates2.filter((updateFromTx) => {
1484
+ const target2 = newest(store);
1485
+ if (`updates` in updateFromTx) {
1486
+ return true;
1487
+ }
1488
+ const atomOrFamilyKeys = target2.timelineAtoms.getRelatedKeys(tl.key);
1489
+ return atomOrFamilyKeys ? [...atomOrFamilyKeys].some(
1490
+ (key) => {
1491
+ var _a3;
1492
+ return key === updateFromTx.key || key === ((_a3 = updateFromTx.family) == null ? void 0 : _a3.key);
1493
+ }
1494
+ ) : false;
1495
+ }).map((updateFromTx) => {
1496
+ if (`updates` in updateFromTx) {
1497
+ return __spreadProps(__spreadValues({}, updateFromTx), {
1498
+ updates: filterUpdates(updateFromTx.updates)
1499
+ });
1500
+ }
1501
+ return updateFromTx;
1502
+ });
1503
+ const updates = filterUpdates(update2.updates);
1504
+ const timelineTransactionUpdate = __spreadProps(__spreadValues({
1505
+ type: `transaction_update`,
1506
+ timestamp: currentTransactionTime
1507
+ }, update2), {
1508
+ updates
1509
+ });
1510
+ const willCapture = (_b2 = (_a2 = tl.shouldCapture) == null ? void 0 : _a2.call(tl, timelineTransactionUpdate, tl)) != null ? _b2 : true;
1511
+ if (willCapture) {
1512
+ tl.history.push(timelineTransactionUpdate);
1513
+ tl.at = tl.history.length;
1514
+ tl.subject.next(timelineTransactionUpdate);
1515
+ }
1516
+ }
1517
+ tl.transactionKey = null;
1518
+ store.logger.info(
1519
+ `\u231B`,
1520
+ `timeline`,
1521
+ tl.key,
1522
+ `got a transaction_update "${update2.key}"`
1523
+ );
1524
+ }
1525
+ );
1526
+ }
1527
+ } else if (currentSelectorKey && currentSelectorTime) {
1528
+ let latestUpdate = tl.history.at(-1);
1529
+ if (currentSelectorTime !== tl.selectorTime) {
1530
+ latestUpdate = {
1531
+ type: `selector_update`,
1532
+ timestamp: currentSelectorTime,
1533
+ key: currentSelectorKey,
1534
+ atomUpdates: []
1535
+ };
1536
+ latestUpdate.atomUpdates.push(__spreadValues({
1537
+ key: atom.key,
1538
+ type: `atom_update`
1539
+ }, update));
1540
+ if (tl.at !== tl.history.length) {
1541
+ tl.history.splice(tl.at);
1542
+ }
1543
+ tl.history.push(latestUpdate);
1544
+ store.logger.info(
1545
+ `\u231B`,
1546
+ `timeline`,
1547
+ tl.key,
1548
+ `got a selector_update "${currentSelectorKey}" with`,
1549
+ latestUpdate.atomUpdates.map((atomUpdate) => atomUpdate.key)
1550
+ );
1551
+ tl.at = tl.history.length;
1552
+ tl.selectorTime = currentSelectorTime;
1553
+ } else {
1554
+ if ((latestUpdate == null ? void 0 : latestUpdate.type) === `selector_update`) {
1555
+ latestUpdate.atomUpdates.push(__spreadValues({
1556
+ key: atom.key,
1557
+ type: `atom_update`
1558
+ }, update));
1559
+ store.logger.info(
1560
+ `\u231B`,
1561
+ `timeline`,
1562
+ tl.key,
1563
+ `set selector_update "${currentSelectorKey}" to`,
1564
+ latestUpdate == null ? void 0 : latestUpdate.atomUpdates.map((atomUpdate) => atomUpdate.key)
1565
+ );
1566
+ }
1567
+ }
1568
+ if (latestUpdate) {
1569
+ const willCaptureSelectorUpdate = (_d = (_c = tl.shouldCapture) == null ? void 0 : _c.call(tl, latestUpdate, tl)) != null ? _d : true;
1570
+ if (willCaptureSelectorUpdate) {
1571
+ tl.subject.next(latestUpdate);
1572
+ } else {
1573
+ tl.history.pop();
1574
+ tl.at = tl.history.length;
1575
+ }
1576
+ }
1577
+ } else {
1578
+ const timestamp = Date.now();
1579
+ tl.selectorTime = null;
1580
+ if (tl.at !== tl.history.length) {
1581
+ tl.history.splice(tl.at);
1582
+ }
1583
+ const atomUpdate = {
1584
+ type: `atom_update`,
1585
+ timestamp,
1586
+ key: atom.key,
1587
+ oldValue: update.oldValue,
1588
+ newValue: update.newValue
1589
+ };
1590
+ if (atom.family) {
1591
+ atomUpdate.family = atom.family;
1592
+ }
1593
+ const willCapture = (_f = (_e = tl.shouldCapture) == null ? void 0 : _e.call(tl, atomUpdate, tl)) != null ? _f : true;
1594
+ store.logger.info(
1595
+ `\u231B`,
1596
+ `timeline`,
1597
+ tl.key,
1598
+ `got an atom_update to "${atom.key}"`
1599
+ );
1600
+ if (willCapture) {
1601
+ tl.history.push(atomUpdate);
1602
+ tl.at = tl.history.length;
1603
+ tl.subject.next(atomUpdate);
1604
+ }
1605
+ }
1606
+ }
1607
+ });
1608
+ };
1609
+
1610
+ // internal/src/mutable/is-mutable.ts
1611
+ function isMutable(atomOrTokenOrFamily, store) {
1612
+ if (`mutable` in atomOrTokenOrFamily) {
1613
+ return atomOrTokenOrFamily.mutable;
1614
+ }
1615
+ if (atomOrTokenOrFamily.type === `atom_family`) {
1616
+ return false;
1617
+ }
1618
+ if (`default` in atomOrTokenOrFamily) {
1619
+ return false;
1620
+ }
1621
+ if (!store) {
1622
+ throw new Error(`Cannot check mutability without a store`);
1623
+ }
1624
+ const atom = withdraw(atomOrTokenOrFamily, store);
1625
+ if (!atom) {
1626
+ throw new Error(`Cannot check mutability without an atom`);
1627
+ }
1628
+ if (`mutable` in atom) {
1629
+ return atom.mutable;
1630
+ }
1631
+ return false;
1632
+ }
1633
+
1634
+ // internal/src/timeline/create-timeline.ts
1635
+ function createTimeline(options, store, data) {
1636
+ var _a, _b;
1637
+ const tl = __spreadProps(__spreadValues({
1638
+ type: `timeline`,
1639
+ key: options.key,
1640
+ at: 0,
1641
+ timeTraveling: null,
1642
+ selectorTime: null,
1643
+ transactionKey: null
1644
+ }, data), {
1645
+ history: (_a = data == null ? void 0 : data.history.map((update) => __spreadValues({}, update))) != null ? _a : [],
1646
+ install: (store2) => createTimeline(options, store2, tl),
1647
+ subject: new Subject()
1648
+ });
1649
+ if (options.shouldCapture) {
1650
+ tl.shouldCapture = options.shouldCapture;
1651
+ }
1652
+ const timelineKey = options.key;
1653
+ const target = newest(store);
1654
+ for (const tokenOrFamily of options.atoms) {
1655
+ let atomKey = tokenOrFamily.key;
1656
+ const existingTimelineKey = target.timelineAtoms.getRelatedKey(atomKey);
1657
+ if (existingTimelineKey) {
1658
+ store.logger.error(
1659
+ `\u274C`,
1660
+ `timeline`,
1661
+ options.key,
1662
+ `Failed to add atom "${atomKey}" because it already belongs to timeline "${existingTimelineKey}"`
1663
+ );
1664
+ continue;
1665
+ }
1666
+ if (tokenOrFamily.type === `atom_family`) {
1667
+ let family = tokenOrFamily;
1668
+ if (isMutable(family)) {
1669
+ family = getUpdateFamily(family, store);
1670
+ atomKey = family.key;
1671
+ }
1672
+ family.subject.subscribe(`timeline:${options.key}`, (token2) => {
1673
+ addAtomToTimeline(token2, tl, store);
1674
+ });
1675
+ for (const atom of target.atoms.values()) {
1676
+ if (((_b = atom.family) == null ? void 0 : _b.key) === family.key) {
1677
+ addAtomToTimeline(atom, tl, store);
1678
+ }
1679
+ }
1680
+ } else {
1681
+ let atom = withdraw(tokenOrFamily, store);
1682
+ if (atom === void 0) {
1683
+ store.logger.error(
1684
+ `\u274C`,
1685
+ `timeline`,
1686
+ options.key,
1687
+ `Failed to add atom "${atomKey}" because it does not exist in the store`
1688
+ );
1689
+ continue;
1690
+ }
1691
+ if (isMutable(atom)) {
1692
+ const updateAtom = withdraw(getUpdateToken(atom), store);
1693
+ if (updateAtom === void 0) {
1694
+ store.logger.error(
1695
+ `\u274C`,
1696
+ `timeline`,
1697
+ options.key,
1698
+ `Failed to add update atom "${atomKey}" because it does not exist in the store`
1699
+ );
1700
+ continue;
1701
+ }
1702
+ atom = updateAtom;
1703
+ atomKey = atom.key;
1704
+ }
1705
+ if (`family` in atom) {
1706
+ const familyTimelineKey = target.timelineAtoms.getRelatedKey(
1707
+ atom.family.key
1708
+ );
1709
+ if (familyTimelineKey) {
1710
+ store.logger.error(
1711
+ `\u274C`,
1712
+ `timeline`,
1713
+ options.key,
1714
+ `Failed to add atom "${atom.key}" because its family "${atom.family.key}" already belongs to timeline "${familyTimelineKey}"`
1715
+ );
1716
+ continue;
1717
+ }
1718
+ }
1719
+ addAtomToTimeline(atom, tl, store);
1720
+ }
1721
+ target.timelineAtoms.set({ atomKey, timelineKey });
1722
+ }
1723
+ store.timelines.set(options.key, tl);
1724
+ const token = {
1725
+ key: timelineKey,
1726
+ type: `timeline`
1727
+ };
1728
+ store.subject.timelineCreation.next(token);
1729
+ return token;
1730
+ }
1731
+ var timeTravel = (direction, token, store) => {
1732
+ const action = direction === `forward` ? `redo` : `undo`;
1733
+ store.logger.info(
1734
+ direction === `forward` ? `\u23E9` : `\u23EA`,
1735
+ `timeline`,
1736
+ token.key,
1737
+ action
1738
+ );
1739
+ const timelineData = store.timelines.get(token.key);
1740
+ if (!timelineData) {
1741
+ store.logger.error(
1742
+ `\u{1F41E}`,
1743
+ `timeline`,
1744
+ token.key,
1745
+ `Failed to ${action}. This timeline has not been initialized.`
1746
+ );
1747
+ return;
1748
+ }
1749
+ if (direction === `forward` && timelineData.at === timelineData.history.length || direction === `backward` && timelineData.at === 0) {
1750
+ store.logger.warn(
1751
+ `\u{1F481}`,
1752
+ `timeline`,
1753
+ token.key,
1754
+ `Failed to ${action} at the ${direction === `forward` ? `end` : `beginning`} of timeline "${token.key}". There is nothing to ${action}.`
1755
+ );
1756
+ return;
1757
+ }
1758
+ timelineData.timeTraveling = direction === `forward` ? `into_future` : `into_past`;
1759
+ if (direction === `backward`) {
1760
+ --timelineData.at;
1761
+ }
1762
+ const update = timelineData.history[timelineData.at];
1763
+ const updateValues = (atomUpdate) => {
1764
+ const { key, newValue, oldValue } = atomUpdate;
1765
+ const value = direction === `forward` ? newValue : oldValue;
1766
+ setState({ key, type: `atom` }, value, store);
1767
+ };
1768
+ const updateValuesFromTransactionUpdate = (transactionUpdate) => {
1769
+ const updates = direction === `forward` ? transactionUpdate.updates : [...transactionUpdate.updates].reverse();
1770
+ for (const updateFromTransaction of updates) {
1771
+ if (`newValue` in updateFromTransaction) {
1772
+ updateValues(updateFromTransaction);
1773
+ } else {
1774
+ updateValuesFromTransactionUpdate(updateFromTransaction);
1775
+ }
1776
+ }
1777
+ };
1778
+ switch (update.type) {
1779
+ case `atom_update`: {
1780
+ updateValues(update);
1781
+ break;
1782
+ }
1783
+ case `selector_update`: {
1784
+ const updates = direction === `forward` ? update.atomUpdates : [...update.atomUpdates].reverse();
1785
+ for (const atomUpdate of updates) {
1786
+ updateValues(atomUpdate);
1787
+ }
1788
+ break;
1789
+ }
1790
+ case `transaction_update`: {
1791
+ updateValuesFromTransactionUpdate(update);
1792
+ break;
1793
+ }
1794
+ }
1795
+ if (direction === `forward`) {
1796
+ ++timelineData.at;
1797
+ }
1798
+ timelineData.subject.next(action);
1799
+ timelineData.timeTraveling = null;
1800
+ store.logger.info(
1801
+ `\u23F9\uFE0F`,
1802
+ `timeline`,
1803
+ token.key,
1804
+ `"${token.key}" is now at ${timelineData.at} / ${timelineData.history.length}`
1805
+ );
1806
+ };
1807
+
1808
+ // internal/src/transaction/abort-transaction.ts
1809
+ var abortTransaction = (store) => {
1810
+ const target = newest(store);
1811
+ if (target.transactionMeta === null || target.parent === null) {
1812
+ store.logger.warn(
1813
+ `\u{1F41E}`,
1814
+ `transaction`,
1815
+ `???`,
1816
+ `abortTransaction called outside of a transaction. This is probably a bug in AtomIO.`
1817
+ );
1818
+ return;
1819
+ }
1820
+ store.logger.info(
1821
+ `\u{1FA82}`,
1822
+ `transaction`,
1823
+ target.transactionMeta.update.key,
1824
+ `Aborting transaction`
1825
+ );
1826
+ target.parent.child = null;
1827
+ };
1828
+ function ingestAtomUpdate(update, parent, child) {
1829
+ var _a, _b, _c;
1830
+ const { key, newValue } = update;
1831
+ const token = { key, type: `atom` };
1832
+ if (!parent.valueMap.has(token.key)) {
1833
+ if (token.family) {
1834
+ const family = parent.families.get(token.family.key);
1835
+ if (family) {
1836
+ family(token.family.subKey);
1837
+ }
1838
+ } else {
1839
+ const newAtom = child.atoms.get(token.key);
1840
+ if (!newAtom) {
1841
+ throw new Error(
1842
+ `Absurd Error: Atom "${token.key}" not found while copying updates from transaction "${(_a = child.transactionMeta) == null ? void 0 : _a.update.key}" to store "${parent.config.name}"`
1843
+ );
1844
+ }
1845
+ parent.atoms.set(newAtom.key, newAtom);
1846
+ parent.valueMap.set(newAtom.key, newAtom.default);
1847
+ parent.logger.info(
1848
+ `\u{1F528}`,
1849
+ `transaction`,
1850
+ (_c = (_b = child.transactionMeta) == null ? void 0 : _b.update.key) != null ? _c : `???`,
1851
+ `Adding atom "${newAtom.key}"`
1852
+ );
1853
+ }
1854
+ }
1855
+ setState(token, newValue, parent);
1856
+ }
1857
+ function ingestTransactionUpdate(transactionUpdate, parent, child) {
1858
+ for (const update of transactionUpdate.updates) {
1859
+ if (`newValue` in update) {
1860
+ ingestAtomUpdate(update, parent, child);
1861
+ } else {
1862
+ ingestTransactionUpdate(update, parent, child);
1863
+ }
1864
+ }
1865
+ }
1866
+ var applyTransaction = (output, store) => {
1867
+ var _a;
1868
+ const child = newest(store);
1869
+ const { parent } = child;
1870
+ if (parent === null || child.transactionMeta === null || ((_a = child.transactionMeta) == null ? void 0 : _a.phase) !== `building`) {
1871
+ store.logger.warn(
1872
+ `\u{1F41E}`,
1873
+ `transaction`,
1874
+ `???`,
1875
+ `applyTransaction called outside of a transaction. This is probably a bug in AtomIO.`
1876
+ );
1877
+ return;
1878
+ }
1879
+ child.transactionMeta.phase = `applying`;
1880
+ child.transactionMeta.update.output = output;
1881
+ parent.child = null;
1882
+ parent.subject.transactionApplying.next(child.transactionMeta);
1883
+ const { updates } = child.transactionMeta.update;
1884
+ store.logger.info(
1885
+ `\u{1F6C4}`,
1886
+ `transaction`,
1887
+ child.transactionMeta.update.key,
1888
+ `Applying transaction with ${updates.length} updates:`,
1889
+ updates
1890
+ );
1891
+ if (parent.transactionMeta === null) {
1892
+ ingestTransactionUpdate(child.transactionMeta.update, parent, child);
1893
+ const myTransaction = withdraw(
1894
+ { key: child.transactionMeta.update.key, type: `transaction` },
1895
+ store
1896
+ );
1897
+ myTransaction == null ? void 0 : myTransaction.subject.next(child.transactionMeta.update);
1898
+ store.logger.info(
1899
+ `\u{1F6EC}`,
1900
+ `transaction`,
1901
+ child.transactionMeta.update.key,
1902
+ `Finished applying transaction.`
1903
+ );
1904
+ } else {
1905
+ ingestTransactionUpdate(child.transactionMeta.update, parent, child);
1906
+ parent.transactionMeta.update.updates.push(child.transactionMeta.update);
1907
+ }
1908
+ parent.subject.transactionApplying.next(null);
1909
+ };
1910
+
1911
+ // internal/src/transaction/build-transaction.ts
1912
+ var buildTransaction = (key, params, store) => {
1913
+ const parent = newest(store);
1914
+ parent.child = {
1915
+ parent,
1916
+ child: null,
1917
+ subject: parent.subject,
1918
+ loggers: parent.loggers,
1919
+ logger: parent.logger,
1920
+ config: parent.config,
1921
+ transactionMeta: {
1922
+ phase: `building`,
1923
+ time: Date.now(),
1924
+ update: {
1925
+ key,
1926
+ updates: [],
1927
+ params,
1928
+ output: void 0
1929
+ }
1930
+ },
1931
+ atoms: new LazyMap(parent.atoms),
1932
+ atomsThatAreDefault: new Set(parent.atomsThatAreDefault),
1933
+ families: new LazyMap(parent.families),
1934
+ operation: { open: false },
1935
+ readonlySelectors: new LazyMap(parent.readonlySelectors),
1936
+ timelines: new LazyMap(parent.timelines),
1937
+ timelineAtoms: new Junction(parent.timelineAtoms.toJSON()),
1938
+ trackers: /* @__PURE__ */ new Map(),
1939
+ transactions: new LazyMap(parent.transactions),
1940
+ selectorAtoms: new Junction(parent.selectorAtoms.toJSON()),
1941
+ selectorGraph: new Junction(parent.selectorGraph.toJSON(), {
1942
+ makeContentKey: (...keys) => keys.sort().join(`:`)
1943
+ }),
1944
+ selectors: new LazyMap(parent.selectors),
1945
+ valueMap: new LazyMap(parent.valueMap)
1946
+ };
1947
+ store.logger.info(
1948
+ `\u{1F6EB}`,
1949
+ `transaction`,
1950
+ key,
1951
+ `Building transaction with params:`,
1952
+ params
1953
+ );
1954
+ };
1955
+ function createTransaction(options, store) {
1956
+ const newTransaction = {
1957
+ key: options.key,
1958
+ type: `transaction`,
1959
+ run: (...params) => {
1960
+ buildTransaction(options.key, params, store);
1961
+ try {
1962
+ const output = options.do(
1963
+ {
1964
+ get: (token2) => getState(token2, store),
1965
+ set: (token2, value) => setState(token2, value, store),
1966
+ run: (token2) => runTransaction(token2, store)
1967
+ },
1968
+ ...params
1969
+ );
1970
+ applyTransaction(output, store);
1971
+ return output;
1972
+ } catch (thrown) {
1973
+ abortTransaction(store);
1974
+ store.logger.warn(`\u{1F4A5}`, `transaction`, options.key, `caught:`, thrown);
1975
+ throw thrown;
1976
+ }
1977
+ },
1978
+ install: (store2) => createTransaction(options, store2),
1979
+ subject: new Subject()
1980
+ };
1981
+ const target = newest(store);
1982
+ target.transactions.set(newTransaction.key, newTransaction);
1983
+ const token = deposit(newTransaction);
1984
+ store.subject.transactionCreation.next(token);
1985
+ return token;
1986
+ }
1987
+ var redoTransactionUpdate = (transactionUpdate, store) => {
1988
+ store.logger.info(`\u23ED\uFE0F`, `transaction`, transactionUpdate.key, `Redo`);
1989
+ for (const update of transactionUpdate.updates) {
1990
+ if (`newValue` in update) {
1991
+ const { key, newValue } = update;
1992
+ const token = { key, type: `atom` };
1993
+ const state = withdraw(token, store);
1994
+ if (state === void 0) {
1995
+ throw new Error(
1996
+ `State "${token.key}" not found in this store. This is surprising, because we are navigating the history of the store.`
1997
+ );
1998
+ }
1999
+ setState(state, newValue, store);
2000
+ } else {
2001
+ redoTransactionUpdate(update, store);
2002
+ }
2003
+ }
2004
+ };
2005
+ var undoTransactionUpdate = (transactionUpdate, store) => {
2006
+ store.logger.info(`\u23EE\uFE0F`, `transaction`, transactionUpdate.key, `Undo`);
2007
+ for (const update of transactionUpdate.updates.reverse()) {
2008
+ if (`newValue` in update) {
2009
+ const { key, newValue } = update;
2010
+ const token = { key, type: `atom` };
2011
+ const state = withdraw(token, store);
2012
+ if (state === void 0) {
2013
+ throw new Error(
2014
+ `State "${token.key}" not found in this store. This is surprising, because we are navigating the history of the store.`
2015
+ );
2016
+ }
2017
+ setState(state, newValue, store);
2018
+ } else {
2019
+ undoTransactionUpdate(update, store);
2020
+ }
2021
+ }
2022
+ };
2023
+
2024
+ // internal/src/transaction/index.ts
2025
+ var TRANSACTION_PHASES = [`idle`, `building`, `applying`];
2026
+
2027
+ export { FamilyTracker, Future, IMPLICIT, LazyMap, NotFoundError, StatefulSubject, Store, Subject, TRANSACTION_PHASES, Tracker, abortTransaction, addAtomToTimeline, applyTransaction, become, buildTransaction, cacheValue, clearStore, closeOperation, createAtom, createAtomFamily, createMutableAtom, createMutableAtomFamily, createReadonlySelectorFamily, createSelector, createSelectorFamily, createTimeline, createTransaction, deleteAtom2 as deleteAtom, deleteSelector, deposit, eldest, evictCachedValue, getJsonFamily, getJsonToken, getSelectorDependencyKeys, getUpdateFamily, getUpdateToken, isAtomDefault, isAtomKey, isDone, isReadonlySelectorKey, isSelectorDefault, isSelectorKey, isStateKey, isTransceiver, isValueCached, markAtomAsDefault, markAtomAsNotDefault, markDone, newest, openOperation, readCachedValue, readOrComputeValue, redoTransactionUpdate, registerSelector, setAtomOrSelector, subscribeToRootAtoms, subscribeToState, subscribeToTimeline, subscribeToTransaction, timeTravel, traceAllSelectorAtoms, traceSelectorAtoms, undoTransactionUpdate, updateSelectorAtoms, withdraw, withdrawNewFamilyMember };
2
2028
  //# sourceMappingURL=out.js.map
3
2029
  //# sourceMappingURL=index.js.map