atom.io 0.14.0 → 0.14.1

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