atom.io 0.25.6 → 0.26.0

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 (52) hide show
  1. package/data/dist/index.js +33 -25
  2. package/data/package.json +1 -4
  3. package/dist/{chunk-HYXKCFVY.js → chunk-IBTHB2PI.js} +59 -60
  4. package/dist/{chunk-MR5NETHW.js → chunk-IW6WYRS7.js} +4 -5
  5. package/dist/chunk-XWL6SNVU.js +7 -0
  6. package/dist/index.js +33 -21
  7. package/ephemeral/dist/index.js +1 -1
  8. package/ephemeral/package.json +1 -4
  9. package/eslint-plugin/dist/index.js +7 -8
  10. package/eslint-plugin/package.json +1 -4
  11. package/immortal/dist/index.js +1 -1
  12. package/immortal/package.json +1 -4
  13. package/internal/dist/index.js +173 -160
  14. package/internal/package.json +1 -4
  15. package/introspection/dist/index.js +32 -30
  16. package/introspection/package.json +1 -4
  17. package/json/dist/index.js +1 -1
  18. package/json/package.json +1 -4
  19. package/package.json +18 -50
  20. package/react/dist/index.js +2 -2
  21. package/react/package.json +1 -4
  22. package/react-devtools/dist/index.js +75 -68
  23. package/react-devtools/package.json +1 -4
  24. package/realtime/dist/index.js +8 -9
  25. package/realtime/package.json +1 -4
  26. package/realtime-client/dist/index.js +6 -6
  27. package/realtime-client/package.json +1 -4
  28. package/realtime-react/dist/index.js +9 -11
  29. package/realtime-react/package.json +1 -4
  30. package/realtime-server/dist/index.js +59 -54
  31. package/realtime-server/package.json +1 -4
  32. package/realtime-testing/dist/index.js +3 -3
  33. package/realtime-testing/package.json +1 -4
  34. package/transceivers/set-rtx/dist/index.js +11 -11
  35. package/transceivers/set-rtx/package.json +1 -4
  36. package/data/dist/index.cjs +0 -953
  37. package/dist/chunk-S4N6XNPH.js +0 -38
  38. package/dist/index.cjs +0 -215
  39. package/ephemeral/dist/index.cjs +0 -11
  40. package/eslint-plugin/dist/index.cjs +0 -388
  41. package/immortal/dist/index.cjs +0 -14
  42. package/internal/dist/index.cjs +0 -3405
  43. package/introspection/dist/index.cjs +0 -449
  44. package/json/dist/index.cjs +0 -128
  45. package/react/dist/index.cjs +0 -118
  46. package/react-devtools/dist/index.cjs +0 -2191
  47. package/realtime/dist/index.cjs +0 -120
  48. package/realtime-client/dist/index.cjs +0 -569
  49. package/realtime-react/dist/index.cjs +0 -189
  50. package/realtime-server/dist/index.cjs +0 -965
  51. package/realtime-testing/dist/index.cjs +0 -201
  52. package/transceivers/set-rtx/dist/index.cjs +0 -215
@@ -1,3405 +0,0 @@
1
- 'use strict';
2
-
3
- var json = require('atom.io/json');
4
- var atom_io = require('atom.io');
5
- var data = require('atom.io/data');
6
-
7
- var __defProp = Object.defineProperty;
8
- var __defProps = Object.defineProperties;
9
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
10
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
11
- var __hasOwnProp = Object.prototype.hasOwnProperty;
12
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
13
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
14
- var __spreadValues = (a, b) => {
15
- for (var prop in b || (b = {}))
16
- if (__hasOwnProp.call(b, prop))
17
- __defNormalProp(a, prop, b[prop]);
18
- if (__getOwnPropSymbols)
19
- for (var prop of __getOwnPropSymbols(b)) {
20
- if (__propIsEnum.call(b, prop))
21
- __defNormalProp(a, prop, b[prop]);
22
- }
23
- return a;
24
- };
25
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
26
-
27
- // internal/src/arbitrary.ts
28
- function arbitrary(random = Math.random) {
29
- return random().toString(36).slice(2);
30
- }
31
-
32
- // internal/src/future.ts
33
- var Future = class extends Promise {
34
- constructor(executor) {
35
- let superResolve;
36
- let superReject;
37
- super((resolve, reject) => {
38
- superResolve = resolve;
39
- superReject = reject;
40
- });
41
- this.resolve = superResolve;
42
- this.reject = superReject;
43
- this.use(executor instanceof Promise ? executor : new Promise(executor));
44
- }
45
- pass(promise, value) {
46
- if (promise === this.fate) {
47
- this.resolve(value);
48
- }
49
- }
50
- fail(promise, reason) {
51
- if (promise === this.fate) {
52
- this.reject(reason);
53
- }
54
- }
55
- use(value) {
56
- if (value instanceof Promise) {
57
- const promise = value;
58
- this.fate = promise;
59
- promise.then(
60
- (resolved) => {
61
- this.pass(promise, resolved);
62
- },
63
- (reason) => {
64
- this.fail(promise, reason);
65
- }
66
- );
67
- } else {
68
- this.resolve(value);
69
- this.fate = void 0;
70
- }
71
- }
72
- };
73
-
74
- // internal/src/lineage.ts
75
- function newest(scion) {
76
- while (scion.child !== null) {
77
- scion = scion.child;
78
- }
79
- return scion;
80
- }
81
- function eldest(scion) {
82
- while (scion.parent !== null) {
83
- scion = scion.parent;
84
- }
85
- return scion;
86
- }
87
-
88
- // internal/src/store/deposit.ts
89
- function deposit(state) {
90
- const token = {
91
- key: state.key,
92
- type: state.type
93
- };
94
- if (`family` in state) {
95
- token.family = state.family;
96
- }
97
- return token;
98
- }
99
-
100
- // ../rel8/junction/src/junction.ts
101
- var Junction = class {
102
- constructor(data, config) {
103
- this.relations = /* @__PURE__ */ new Map();
104
- this.contents = /* @__PURE__ */ new Map();
105
- this.makeContentKey = (a, b) => `${a}:${b}`;
106
- var _a, _b, _c, _d;
107
- this.a = data.between[0];
108
- this.b = data.between[1];
109
- this.cardinality = data.cardinality;
110
- if (!(config == null ? void 0 : config.externalStore)) {
111
- this.relations = new Map((_a = data.relations) == null ? void 0 : _a.map(([a, b]) => [a, new Set(b)]));
112
- this.contents = new Map(data.contents);
113
- }
114
- this.isContent = (_b = config == null ? void 0 : config.isContent) != null ? _b : null;
115
- if (config == null ? void 0 : config.makeContentKey) {
116
- this.makeContentKey = config.makeContentKey;
117
- }
118
- if (config == null ? void 0 : config.externalStore) {
119
- const externalStore = config.externalStore;
120
- this.has = (a, b) => externalStore.has(a, b);
121
- this.addRelation = (a, b) => {
122
- externalStore.addRelation(a, b);
123
- };
124
- this.deleteRelation = (a, b) => {
125
- externalStore.deleteRelation(a, b);
126
- };
127
- this.replaceRelationsSafely = (a, bs) => {
128
- externalStore.replaceRelationsSafely(a, bs);
129
- };
130
- this.replaceRelationsUnsafely = (a, bs) => {
131
- externalStore.replaceRelationsUnsafely(a, bs);
132
- };
133
- this.getRelatedKeys = (key) => externalStore.getRelatedKeys(key);
134
- if (externalStore.getContent) {
135
- this.getContentInternal = (contentKey) => {
136
- return externalStore.getContent(contentKey);
137
- };
138
- this.setContent = (contentKey, content) => {
139
- externalStore.setContent(contentKey, content);
140
- };
141
- this.deleteContent = (contentKey) => {
142
- externalStore.deleteContent(contentKey);
143
- };
144
- }
145
- for (const [x, ys] of (_c = data.relations) != null ? _c : []) {
146
- for (const y of ys) this.addRelation(x, y);
147
- }
148
- for (const [contentKey, content] of (_d = data.contents) != null ? _d : []) {
149
- this.setContent(contentKey, content);
150
- }
151
- }
152
- }
153
- getRelatedKeys(key) {
154
- return this.relations.get(key);
155
- }
156
- addRelation(a, b) {
157
- let aRelations = this.relations.get(a);
158
- let bRelations = this.relations.get(b);
159
- if (aRelations) {
160
- aRelations.add(b);
161
- } else {
162
- aRelations = /* @__PURE__ */ new Set([b]);
163
- this.relations.set(a, aRelations);
164
- }
165
- if (bRelations) {
166
- bRelations.add(a);
167
- } else {
168
- bRelations = /* @__PURE__ */ new Set([a]);
169
- this.relations.set(b, bRelations);
170
- }
171
- }
172
- deleteRelation(a, b) {
173
- const aRelations = this.relations.get(a);
174
- if (aRelations) {
175
- aRelations.delete(b);
176
- if (aRelations.size === 0) {
177
- this.relations.delete(a);
178
- }
179
- const bRelations = this.relations.get(b);
180
- if (bRelations) {
181
- bRelations.delete(a);
182
- if (bRelations.size === 0) {
183
- this.relations.delete(b);
184
- }
185
- }
186
- }
187
- }
188
- replaceRelationsUnsafely(a, bs) {
189
- this.relations.set(a, new Set(bs));
190
- for (const b of bs) {
191
- const bRelations = /* @__PURE__ */ new Set([a]);
192
- this.relations.set(b, bRelations);
193
- }
194
- }
195
- replaceRelationsSafely(a, bs) {
196
- const aRelationsPrev = this.relations.get(a);
197
- if (aRelationsPrev) {
198
- for (const b of aRelationsPrev) {
199
- const bRelations = this.relations.get(b);
200
- if (bRelations) {
201
- if (bRelations.size === 1) {
202
- this.relations.delete(b);
203
- } else {
204
- bRelations.delete(a);
205
- }
206
- this.contents.delete(this.makeContentKey(a, b));
207
- }
208
- }
209
- }
210
- this.relations.set(a, new Set(bs));
211
- for (const b of bs) {
212
- let bRelations = this.relations.get(b);
213
- if (bRelations) {
214
- bRelations.add(a);
215
- } else {
216
- bRelations = /* @__PURE__ */ new Set([a]);
217
- this.relations.set(b, bRelations);
218
- }
219
- }
220
- }
221
- getContentInternal(contentKey) {
222
- return this.contents.get(contentKey);
223
- }
224
- setContent(contentKey, content) {
225
- this.contents.set(contentKey, content);
226
- }
227
- deleteContent(contentKey) {
228
- this.contents.delete(contentKey);
229
- }
230
- toJSON() {
231
- return {
232
- between: [this.a, this.b],
233
- cardinality: this.cardinality,
234
- relations: [...this.relations.entries()].map(([a, b]) => [a, [...b]]),
235
- contents: [...this.contents.entries()]
236
- };
237
- }
238
- set(a, ...rest) {
239
- var _a;
240
- const b = typeof rest[0] === `string` ? rest[0] : a[this.b];
241
- const content = ((_a = rest[1]) != null ? _a : typeof rest[0] === `string`) ? void 0 : rest[0];
242
- a = typeof a === `string` ? a : a[this.a];
243
- switch (this.cardinality) {
244
- case `1:1`: {
245
- const bPrev = this.getRelatedKey(a);
246
- if (bPrev && bPrev !== b) this.delete(bPrev, a);
247
- }
248
- case `1:n`: {
249
- const aPrev = this.getRelatedKey(b);
250
- if (aPrev && aPrev !== a) this.delete(aPrev, b);
251
- }
252
- }
253
- if (content) {
254
- const contentKey = this.makeContentKey(a, b);
255
- this.setContent(contentKey, content);
256
- }
257
- this.addRelation(a, b);
258
- return this;
259
- }
260
- delete(x, b) {
261
- b = typeof b === `string` ? b : x[this.b];
262
- const a = typeof x === `string` ? x : x[this.a];
263
- if (a === void 0 && typeof b === `string`) {
264
- const bRelations = this.getRelatedKeys(b);
265
- if (bRelations) {
266
- for (const bRelation of bRelations) {
267
- this.delete(bRelation, b);
268
- }
269
- }
270
- }
271
- if (typeof a === `string` && b === void 0) {
272
- const aRelations = this.getRelatedKeys(a);
273
- if (aRelations) {
274
- for (const aRelation of aRelations) {
275
- this.delete(a, aRelation);
276
- }
277
- }
278
- }
279
- if (typeof a === `string` && typeof b === `string`) {
280
- this.deleteRelation(a, b);
281
- const contentKey = this.makeContentKey(a, b);
282
- this.deleteContent(contentKey);
283
- }
284
- return this;
285
- }
286
- getRelatedKey(key) {
287
- const relations = this.getRelatedKeys(key);
288
- if (relations) {
289
- if (relations.size > 1) {
290
- console.warn(
291
- `${relations.size} related keys were found for key "${key}": (${[
292
- ...relations
293
- ].map((k) => `"${k}"`).join(`, `)}). Only one related key was expected.`
294
- );
295
- }
296
- for (const relation of relations) {
297
- return relation;
298
- }
299
- }
300
- }
301
- replaceRelations(a, relations, config) {
302
- const hasContent = !Array.isArray(relations);
303
- const bs = hasContent ? Object.keys(relations) : relations;
304
- if (config == null ? void 0 : config.reckless) {
305
- this.replaceRelationsUnsafely(a, bs);
306
- } else {
307
- this.replaceRelationsSafely(a, bs);
308
- }
309
- if (hasContent) {
310
- for (const b of bs) {
311
- const contentKey = this.makeContentKey(a, b);
312
- const content = relations[b];
313
- this.setContent(contentKey, content);
314
- }
315
- }
316
- return this;
317
- }
318
- getContent(a, b) {
319
- const contentKey = this.makeContentKey(a, b);
320
- return this.getContentInternal(contentKey);
321
- }
322
- getRelationEntries(input) {
323
- const a = input[this.a];
324
- const b = input[this.b];
325
- if (a !== void 0 && b === void 0) {
326
- const aRelations = this.getRelatedKeys(a);
327
- if (aRelations) {
328
- return [...aRelations].map((aRelation) => {
329
- var _a;
330
- return [aRelation, (_a = this.getContent(a, aRelation)) != null ? _a : null];
331
- });
332
- }
333
- }
334
- if (a === void 0 && b !== void 0) {
335
- const bRelations = this.getRelatedKeys(b);
336
- if (bRelations) {
337
- return [...bRelations].map((bRelation) => {
338
- var _a;
339
- return [bRelation, (_a = this.getContent(bRelation, b)) != null ? _a : null];
340
- });
341
- }
342
- }
343
- return [];
344
- }
345
- has(a, b) {
346
- var _a;
347
- if (b) {
348
- const setA = this.getRelatedKeys(a);
349
- return (_a = setA == null ? void 0 : setA.has(b)) != null ? _a : false;
350
- }
351
- return this.relations.has(a);
352
- }
353
- };
354
-
355
- // internal/src/subject.ts
356
- var Subject = class {
357
- constructor() {
358
- this.subscribers = /* @__PURE__ */ new Map();
359
- }
360
- subscribe(key, subscriber) {
361
- this.subscribers.set(key, subscriber);
362
- const unsubscribe = () => {
363
- this.unsubscribe(key);
364
- };
365
- return unsubscribe;
366
- }
367
- unsubscribe(key) {
368
- this.subscribers.delete(key);
369
- }
370
- next(value) {
371
- const subscribers = this.subscribers.values();
372
- for (const subscriber of subscribers) {
373
- subscriber(value);
374
- }
375
- }
376
- };
377
- var StatefulSubject = class extends Subject {
378
- constructor(initialState) {
379
- super();
380
- this.state = initialState;
381
- }
382
- next(value) {
383
- this.state = value;
384
- super.next(value);
385
- }
386
- };
387
-
388
- // internal/src/transaction/is-root-store.ts
389
- function isRootStore(store) {
390
- return `epoch` in store.transactionMeta;
391
- }
392
- function isChildStore(store) {
393
- return `phase` in store.transactionMeta;
394
- }
395
-
396
- // internal/src/transaction/abort-transaction.ts
397
- var abortTransaction = (store) => {
398
- const target = newest(store);
399
- if (!isChildStore(target)) {
400
- store.logger.warn(
401
- `\u{1F41E}`,
402
- `transaction`,
403
- `???`,
404
- `abortTransaction called outside of a transaction. This is probably a bug in AtomIO.`
405
- );
406
- return;
407
- }
408
- store.logger.info(
409
- `\u{1FA82}`,
410
- `transaction`,
411
- target.transactionMeta.update.key,
412
- `Aborting transaction`
413
- );
414
- target.parent.child = null;
415
- };
416
- var capitalize = (str) => str[0].toUpperCase() + str.slice(1);
417
- function prettyPrintTokenType(token) {
418
- switch (token.type) {
419
- case `atom_family`:
420
- return `Atom Family`;
421
- case `molecule_family`:
422
- return `Molecule Family`;
423
- case `readonly_selector`:
424
- return `Readonly Selector`;
425
- case `readonly_selector_family`:
426
- return `Readonly Selector Family`;
427
- case `selector_family`:
428
- return `Selector Family`;
429
- default:
430
- return capitalize(token.type);
431
- }
432
- }
433
- var NotFoundError = class extends Error {
434
- constructor(...params) {
435
- const token = params[0];
436
- const store = params.length === 2 ? params[1] : params[2];
437
- if (params.length === 2) {
438
- super(
439
- `${prettyPrintTokenType(token)} ${json.stringifyJson(token.key)} not found in store "${store.config.name}".`
440
- );
441
- } else {
442
- const key = params[1];
443
- super(
444
- `${prettyPrintTokenType(token)} "${token.key}" member ${json.stringifyJson(key)} not found in store "${store.config.name}".`
445
- );
446
- }
447
- }
448
- };
449
-
450
- // internal/src/transaction/act-upon-store.ts
451
- function actUponStore(token, id, store) {
452
- return (...parameters) => {
453
- const tx = withdraw(token, store);
454
- if (tx) {
455
- return tx.run(parameters, id);
456
- }
457
- throw new NotFoundError(token, store);
458
- };
459
- }
460
-
461
- // internal/src/set-state/become.ts
462
- var become = (nextVersionOfThing) => (originalThing) => nextVersionOfThing instanceof Function ? nextVersionOfThing(
463
- originalThing instanceof Function ? originalThing() : originalThing
464
- ) : nextVersionOfThing;
465
-
466
- // internal/src/get-state/read-or-compute-value.ts
467
- var readOrComputeValue = (state, target) => {
468
- if (target.valueMap.has(state.key)) {
469
- target.logger.info(`\u{1F4D6}`, state.type, state.key, `reading cached value`);
470
- return readCachedValue(state, target);
471
- }
472
- if (state.type !== `atom` && state.type !== `mutable_atom`) {
473
- target.logger.info(`\u{1F9EE}`, state.type, state.key, `computing value`);
474
- return state.get();
475
- }
476
- const fallback = state.default instanceof Function ? state.default() : state.default;
477
- target.logger.info(
478
- `\u{1F481}`,
479
- `atom`,
480
- state.key,
481
- `could not find cached value; using default`,
482
- fallback
483
- );
484
- return state.default instanceof Function ? state.default() : state.default;
485
- };
486
-
487
- // internal/src/operation.ts
488
- var openOperation = (token, store) => {
489
- if (store.operation.open) {
490
- const rejectionTime = performance.now();
491
- store.logger.info(
492
- `\u2757`,
493
- token.type,
494
- token.key,
495
- `deferring setState at T-${rejectionTime} until setState for "${store.operation.token.key}" is done`
496
- );
497
- return rejectionTime;
498
- }
499
- store.operation = {
500
- open: true,
501
- done: /* @__PURE__ */ new Set(),
502
- prev: /* @__PURE__ */ new Map(),
503
- time: Date.now(),
504
- token
505
- };
506
- store.logger.info(
507
- `\u2B55`,
508
- token.type,
509
- token.key,
510
- `operation start in store "${store.config.name}"${!isChildStore(store) ? `` : ` ${store.transactionMeta.phase} "${store.transactionMeta.update.key}"`}`
511
- );
512
- };
513
- var closeOperation = (store) => {
514
- if (store.operation.open) {
515
- store.logger.info(
516
- `\u{1F534}`,
517
- store.operation.token.type,
518
- store.operation.token.key,
519
- `operation done in store "${store.config.name}"`
520
- );
521
- }
522
- store.operation = { open: false };
523
- store.on.operationClose.next(store.operation);
524
- };
525
- var isDone = (key, store) => {
526
- if (!store.operation.open) {
527
- store.logger.warn(
528
- `\u{1F41E}`,
529
- `unknown`,
530
- key,
531
- `isDone called outside of an operation. This is probably a bug.`
532
- );
533
- return true;
534
- }
535
- return store.operation.done.has(key);
536
- };
537
- var markDone = (key, store) => {
538
- if (!store.operation.open) {
539
- store.logger.warn(
540
- `\u{1F41E}`,
541
- `unknown`,
542
- key,
543
- `markDone called outside of an operation. This is probably a bug.`
544
- );
545
- return;
546
- }
547
- store.operation.done.add(key);
548
- };
549
-
550
- // internal/src/set-state/emit-update.ts
551
- var emitUpdate = (state, update, store) => {
552
- switch (state.type) {
553
- case `mutable_atom`:
554
- store.logger.info(
555
- `\u{1F4E2}`,
556
- state.type,
557
- state.key,
558
- `is now (`,
559
- update.newValue,
560
- `) subscribers:`,
561
- state.subject.subscribers
562
- );
563
- break;
564
- default:
565
- store.logger.info(
566
- `\u{1F4E2}`,
567
- state.type,
568
- state.key,
569
- `went (`,
570
- update.oldValue,
571
- `->`,
572
- update.newValue,
573
- `) subscribers:`,
574
- state.subject.subscribers
575
- );
576
- }
577
- state.subject.next(update);
578
- };
579
-
580
- // internal/src/set-state/evict-downstream.ts
581
- var evictDownStream = (atom, store) => {
582
- const target = newest(store);
583
- const downstreamKeys = target.selectorAtoms.getRelatedKeys(atom.key);
584
- target.logger.info(
585
- `\u{1F9F9}`,
586
- atom.type,
587
- atom.key,
588
- downstreamKeys ? `evicting ${downstreamKeys.size} states downstream:` : `no downstream states`,
589
- downstreamKeys != null ? downstreamKeys : `to evict`
590
- );
591
- if (downstreamKeys) {
592
- if (target.operation.open) {
593
- target.logger.info(
594
- `\u{1F9F9}`,
595
- atom.type,
596
- atom.key,
597
- `[ ${[...target.operation.done].join(`, `)} ] already done`
598
- );
599
- }
600
- for (const key of downstreamKeys) {
601
- if (isDone(key, target)) {
602
- continue;
603
- }
604
- evictCachedValue(key, target);
605
- markDone(key, target);
606
- }
607
- }
608
- };
609
-
610
- // internal/src/set-state/stow-update.ts
611
- function shouldUpdateBeStowed(key, update) {
612
- if (isTransceiver(update.newValue)) {
613
- return false;
614
- }
615
- if (key.includes(`\u{1F441}\u200D\u{1F5E8}`)) {
616
- return false;
617
- }
618
- return true;
619
- }
620
- var stowUpdate = (state, update, store) => {
621
- const { key } = state;
622
- const target = newest(store);
623
- if (!isChildStore(target) || target.transactionMeta.phase !== `building`) {
624
- store.logger.error(
625
- `\u{1F41E}`,
626
- `atom`,
627
- key,
628
- `stowUpdate called outside of a transaction. This is probably a bug.`
629
- );
630
- return;
631
- }
632
- const shouldStow = shouldUpdateBeStowed(key, update);
633
- if (!shouldStow) {
634
- return;
635
- }
636
- const atomUpdate = __spreadValues({
637
- type: `atom_update`,
638
- key
639
- }, update);
640
- if (state.family) {
641
- atomUpdate.family = state.family;
642
- }
643
- target.transactionMeta.update.updates.push(atomUpdate);
644
- store.logger.info(
645
- `\u{1F4C1}`,
646
- `atom`,
647
- key,
648
- `stowed (`,
649
- update.oldValue,
650
- `->`,
651
- update.newValue,
652
- `)`
653
- );
654
- };
655
-
656
- // internal/src/set-state/set-atom.ts
657
- var setAtom = (atom, next, target) => {
658
- const oldValue = readOrComputeValue(atom, target);
659
- let newValue = oldValue;
660
- if (atom.type === `mutable_atom` && isChildStore(target)) {
661
- const { parent } = target;
662
- const copiedValue = copyMutableIfNeeded(atom, parent, target);
663
- newValue = copiedValue;
664
- }
665
- newValue = become(next)(newValue);
666
- target.logger.info(`\u{1F4DD}`, `atom`, atom.key, `set to`, newValue);
667
- newValue = cacheValue(atom.key, newValue, atom.subject, target);
668
- if (isAtomDefault(atom.key, target)) {
669
- markAtomAsNotDefault(atom.key, target);
670
- }
671
- markDone(atom.key, target);
672
- evictDownStream(atom, target);
673
- const update = { oldValue, newValue };
674
- if (isRootStore(target)) {
675
- emitUpdate(atom, update, target);
676
- } else if (target.parent) {
677
- if (target.on.transactionApplying.state === null) {
678
- stowUpdate(atom, update, target);
679
- } else if (atom.key.startsWith(`*`)) {
680
- const mutableKey = atom.key.slice(1);
681
- const mutableAtom = target.atoms.get(mutableKey);
682
- let transceiver = target.valueMap.get(mutableKey);
683
- if (mutableAtom.type === `mutable_atom` && isChildStore(target)) {
684
- const { parent } = target;
685
- const copiedValue = copyMutableIfNeeded(mutableAtom, parent, target);
686
- transceiver = copiedValue;
687
- }
688
- const accepted = transceiver.do(update.newValue) === null;
689
- if (accepted) evictDownStream(mutableAtom, target);
690
- }
691
- }
692
- };
693
-
694
- // internal/src/set-state/set-atom-or-selector.ts
695
- var setAtomOrSelector = (state, value, store) => {
696
- switch (state.type) {
697
- case `atom`:
698
- case `mutable_atom`:
699
- setAtom(state, value, store);
700
- break;
701
- case `selector`:
702
- state.set(value);
703
- break;
704
- }
705
- };
706
- function createRegularAtomFamily(options, store) {
707
- const subject = new Subject();
708
- const atomFamily = Object.assign(
709
- (key) => {
710
- const subKey = json.stringifyJson(key);
711
- const family = { key: options.key, subKey };
712
- const fullKey = `${options.key}(${subKey})`;
713
- const target = newest(store);
714
- const def = options.default;
715
- const individualOptions = {
716
- key: fullKey,
717
- default: def instanceof Function ? def(key) : def
718
- };
719
- if (options.effects) {
720
- individualOptions.effects = options.effects(key);
721
- }
722
- const token = createRegularAtom(individualOptions, family, target);
723
- subject.next({ type: `state_creation`, token });
724
- return token;
725
- },
726
- {
727
- key: options.key,
728
- type: `atom_family`,
729
- subject,
730
- install: (s) => createRegularAtomFamily(options, s)
731
- }
732
- );
733
- store.families.set(options.key, atomFamily);
734
- return atomFamily;
735
- }
736
-
737
- // internal/src/families/create-atom-family.ts
738
- function createAtomFamily(options, store) {
739
- const isMutable2 = `mutable` in options;
740
- if (isMutable2) {
741
- return createMutableAtomFamily(options, store);
742
- }
743
- return createRegularAtomFamily(options, store);
744
- }
745
-
746
- // internal/src/get-state/get-from-store.ts
747
- function getFromStore(...params) {
748
- let token;
749
- let store;
750
- if (params.length === 2) {
751
- token = params[0];
752
- store = params[1];
753
- } else {
754
- const family = params[0];
755
- const key = params[1];
756
- store = params[2];
757
- const maybeToken = family.type === `molecule_family` ? seekInStore(family, key, store) : store.config.lifespan === `immortal` ? seekInStore(family, key, store) : findInStore(family, key, store);
758
- if (!maybeToken) {
759
- throw new NotFoundError(family, key, store);
760
- }
761
- token = maybeToken;
762
- }
763
- switch (token.type) {
764
- case `atom`:
765
- case `mutable_atom`:
766
- case `selector`:
767
- case `readonly_selector`:
768
- return readOrComputeValue(withdraw(token, store), store);
769
- case `molecule`:
770
- return withdraw(token, store).instance;
771
- }
772
- }
773
-
774
- // internal/src/keys.ts
775
- var isAtomKey = (key, store) => newest(store).atoms.has(key);
776
- var isSelectorKey = (key, store) => newest(store).selectors.has(key);
777
- var isReadonlySelectorKey = (key, store) => newest(store).readonlySelectors.has(key);
778
- var isStateKey = (key, store) => isAtomKey(key, store) || isSelectorKey(key, store) || isReadonlySelectorKey(key, store);
779
-
780
- // internal/src/selector/get-selector-dependency-keys.ts
781
- var getSelectorDependencyKeys = (key, store) => {
782
- const sources = newest(store).selectorGraph.getRelationEntries({ downstreamSelectorKey: key }).filter(([_, { source }]) => source !== key).map(([_, { source }]) => source).filter((source) => isStateKey(source, store));
783
- return sources;
784
- };
785
-
786
- // internal/src/selector/trace-selector-atoms.ts
787
- var traceSelectorAtoms = (directDependencyKey, covered, store) => {
788
- const rootKeys = [];
789
- const indirectDependencyKeys = getSelectorDependencyKeys(
790
- directDependencyKey,
791
- store
792
- );
793
- while (indirectDependencyKeys.length > 0) {
794
- const indirectDependencyKey = indirectDependencyKeys.shift();
795
- if (covered.has(indirectDependencyKey)) {
796
- continue;
797
- }
798
- covered.add(indirectDependencyKey);
799
- if (!isAtomKey(indirectDependencyKey, store)) {
800
- indirectDependencyKeys.push(
801
- ...getSelectorDependencyKeys(indirectDependencyKey, store)
802
- );
803
- } else if (!rootKeys.includes(indirectDependencyKey)) {
804
- rootKeys.push(indirectDependencyKey);
805
- }
806
- }
807
- return rootKeys;
808
- };
809
- var traceAllSelectorAtoms = (selector, store) => {
810
- const selectorKey = selector.key;
811
- const directDependencyKeys = getSelectorDependencyKeys(selectorKey, store);
812
- const covered = /* @__PURE__ */ new Set();
813
- return directDependencyKeys.flatMap(
814
- (depKey) => isAtomKey(depKey, store) ? depKey : traceSelectorAtoms(depKey, covered, store)
815
- );
816
- };
817
-
818
- // internal/src/selector/update-selector-atoms.ts
819
- var updateSelectorAtoms = (selectorKey, dependency, covered, store) => {
820
- const target = newest(store);
821
- if (dependency.type === `atom` || dependency.type === `mutable_atom`) {
822
- target.selectorAtoms.set({
823
- selectorKey,
824
- atomKey: dependency.key
825
- });
826
- store.logger.info(
827
- `\u{1F50D}`,
828
- `selector`,
829
- selectorKey,
830
- `discovers root atom "${dependency.key}"`
831
- );
832
- } else {
833
- const rootKeys = traceSelectorAtoms(dependency.key, covered, store);
834
- store.logger.info(
835
- `\u{1F50D}`,
836
- `selector`,
837
- selectorKey,
838
- `discovers root atoms: [ ${rootKeys.map((key) => `"${key}"`).join(`, `)} ]`
839
- );
840
- for (const atomKey of rootKeys) {
841
- target.selectorAtoms = target.selectorAtoms.set({
842
- selectorKey,
843
- atomKey
844
- });
845
- }
846
- }
847
- covered.add(dependency.key);
848
- };
849
-
850
- // internal/src/selector/register-selector.ts
851
- var registerSelector = (selectorKey, covered, store) => ({
852
- get: (...params) => {
853
- const target = newest(store);
854
- let dependency;
855
- if (params.length === 2) {
856
- const [family, key] = params;
857
- switch (family.type) {
858
- case `molecule_family`:
859
- return getFromStore(family, key, store);
860
- default:
861
- if (store.config.lifespan === `ephemeral`) {
862
- dependency = findInStore(family, key, store);
863
- } else {
864
- const maybeDependency = seekInStore(family, key, store);
865
- if (maybeDependency) {
866
- dependency = maybeDependency;
867
- } else {
868
- throw new NotFoundError(family, key, store);
869
- }
870
- }
871
- }
872
- } else {
873
- [dependency] = params;
874
- }
875
- if (dependency.type === `molecule`) {
876
- return getFromStore(dependency, store);
877
- }
878
- const dependencyState = withdraw(dependency, store);
879
- const dependencyValue = readOrComputeValue(dependencyState, store);
880
- store.logger.info(
881
- `\u{1F50C}`,
882
- `selector`,
883
- selectorKey,
884
- `registers dependency ( "${dependency.key}" =`,
885
- dependencyValue,
886
- `)`
887
- );
888
- target.selectorGraph.set(
889
- {
890
- upstreamSelectorKey: dependency.key,
891
- downstreamSelectorKey: selectorKey
892
- },
893
- {
894
- source: dependency.key
895
- }
896
- );
897
- updateSelectorAtoms(selectorKey, dependency, covered, store);
898
- return dependencyValue;
899
- },
900
- set: (...params) => {
901
- let token;
902
- let value;
903
- if (params.length === 2) {
904
- token = params[0];
905
- value = params[1];
906
- } else {
907
- const family = params[0];
908
- const key = params[1];
909
- value = params[2];
910
- const maybeToken = store.config.lifespan === `ephemeral` ? findInStore(family, key, store) : seekInStore(family, key, store);
911
- if (!maybeToken) {
912
- throw new NotFoundError(family, key, store);
913
- }
914
- token = maybeToken;
915
- }
916
- const target = newest(store);
917
- const state = withdraw(token, target);
918
- setAtomOrSelector(state, value, target);
919
- },
920
- find: (token, key) => findInStore(token, key, store),
921
- seek: (token, key) => seekInStore(token, key, store),
922
- json: (token) => getJsonToken(token, store)
923
- });
924
-
925
- // internal/src/selector/create-readonly-selector.ts
926
- var createReadonlySelector = (options, family, store) => {
927
- const target = newest(store);
928
- const subject = new Subject();
929
- const covered = /* @__PURE__ */ new Set();
930
- const { get, find, seek, json } = registerSelector(
931
- options.key,
932
- covered,
933
- target
934
- );
935
- const getSelf = () => {
936
- const value = options.get({ get, find, seek, json });
937
- cacheValue(options.key, value, subject, newest(store));
938
- covered.clear();
939
- return value;
940
- };
941
- const readonlySelector = __spreadValues(__spreadProps(__spreadValues({}, options), {
942
- subject,
943
- install: (s) => createReadonlySelector(options, family, s),
944
- get: getSelf,
945
- type: `readonly_selector`
946
- }), family && { family });
947
- target.readonlySelectors.set(options.key, readonlySelector);
948
- const initialValue = getSelf();
949
- store.logger.info(
950
- `\u2728`,
951
- readonlySelector.type,
952
- readonlySelector.key,
953
- `=`,
954
- initialValue
955
- );
956
- const token = {
957
- key: options.key,
958
- type: `readonly_selector`
959
- };
960
- if (family) {
961
- token.family = family;
962
- }
963
- return token;
964
- };
965
-
966
- // internal/src/selector/create-writable-selector.ts
967
- var createWritableSelector = (options, family, store) => {
968
- const target = newest(store);
969
- const subject = new Subject();
970
- const covered = /* @__PURE__ */ new Set();
971
- const toolkit = registerSelector(options.key, covered, target);
972
- const { find, get, seek, json } = toolkit;
973
- const getterToolkit = { find, get, seek, json };
974
- const getSelf = (innerTarget = newest(store)) => {
975
- const value = options.get(getterToolkit);
976
- cacheValue(options.key, value, subject, innerTarget);
977
- covered.clear();
978
- return value;
979
- };
980
- const setSelf = (next) => {
981
- const innerTarget = newest(store);
982
- const oldValue = getSelf(innerTarget);
983
- const newValue = become(next)(oldValue);
984
- store.logger.info(
985
- `\u{1F4DD}`,
986
- `selector`,
987
- options.key,
988
- `set (`,
989
- oldValue,
990
- `->`,
991
- newValue,
992
- `)`
993
- );
994
- cacheValue(options.key, newValue, subject, innerTarget);
995
- markDone(options.key, innerTarget);
996
- if (isRootStore(innerTarget)) {
997
- subject.next({ newValue, oldValue });
998
- }
999
- options.set(toolkit, newValue);
1000
- };
1001
- const mySelector = __spreadValues(__spreadProps(__spreadValues({}, options), {
1002
- subject,
1003
- install: (s) => createWritableSelector(options, family, s),
1004
- get: getSelf,
1005
- set: setSelf,
1006
- type: `selector`
1007
- }), family && { family });
1008
- target.selectors.set(options.key, mySelector);
1009
- const initialValue = getSelf();
1010
- store.logger.info(`\u2728`, mySelector.type, mySelector.key, `=`, initialValue);
1011
- const token = {
1012
- key: options.key,
1013
- type: `selector`
1014
- };
1015
- if (family) {
1016
- token.family = family;
1017
- }
1018
- return token;
1019
- };
1020
-
1021
- // internal/src/selector/create-standalone-selector.ts
1022
- function createStandaloneSelector(options, store) {
1023
- const isWritable = `set` in options;
1024
- if (isWritable) {
1025
- const state2 = createWritableSelector(options, void 0, store);
1026
- store.on.selectorCreation.next(state2);
1027
- return state2;
1028
- }
1029
- const state = createReadonlySelector(options, void 0, store);
1030
- store.on.selectorCreation.next(state);
1031
- return state;
1032
- }
1033
-
1034
- // internal/src/selector/dispose-selector.ts
1035
- function disposeSelector(selectorToken, store) {
1036
- var _a;
1037
- const target = newest(store);
1038
- const { key } = selectorToken;
1039
- const selector = (_a = target.selectors.get(key)) != null ? _a : target.readonlySelectors.get(key);
1040
- if (!selector) {
1041
- store.logger.info(
1042
- `\u274C`,
1043
- `selector`,
1044
- key,
1045
- `Tried to dispose selector, but it does not exist in the store.`
1046
- );
1047
- } else if (!selector.family) {
1048
- store.logger.error(
1049
- `\u274C`,
1050
- `selector`,
1051
- key,
1052
- `Standalone selectors cannot be disposed.`
1053
- );
1054
- } else {
1055
- const molecule = target.molecules.get(selector.family.subKey);
1056
- if (molecule) {
1057
- molecule.tokens.delete(key);
1058
- }
1059
- switch (selectorToken.type) {
1060
- case `selector`:
1061
- {
1062
- target.selectors.delete(key);
1063
- const family = withdraw(
1064
- { key: selector.family.key, type: `selector_family` },
1065
- store
1066
- );
1067
- family.subject.next({
1068
- type: `state_disposal`,
1069
- token: selectorToken
1070
- });
1071
- }
1072
- break;
1073
- case `readonly_selector`:
1074
- {
1075
- target.readonlySelectors.delete(key);
1076
- const family = withdraw(
1077
- { key: selector.family.key, type: `readonly_selector_family` },
1078
- store
1079
- );
1080
- family.subject.next({
1081
- type: `state_disposal`,
1082
- token: selectorToken
1083
- });
1084
- }
1085
- break;
1086
- }
1087
- target.valueMap.delete(key);
1088
- target.selectorAtoms.delete(key);
1089
- const downstreamTokens = target.selectorGraph.getRelationEntries({ upstreamSelectorKey: key }).filter(([_, { source }]) => source === key).map(
1090
- ([downstreamSelectorKey]) => {
1091
- var _a2;
1092
- return (_a2 = target.selectors.get(downstreamSelectorKey)) != null ? _a2 : target.readonlySelectors.get(downstreamSelectorKey);
1093
- }
1094
- );
1095
- for (const downstreamToken of downstreamTokens) {
1096
- if (downstreamToken) {
1097
- disposeSelector(downstreamToken, store);
1098
- }
1099
- }
1100
- target.selectorGraph.delete(key);
1101
- store.logger.info(`\u{1F525}`, selectorToken.type, key, `deleted`);
1102
- if (isChildStore(target) && target.transactionMeta.phase === `building`) {
1103
- target.transactionMeta.update.updates.push({
1104
- type: `state_disposal`,
1105
- token: selectorToken
1106
- });
1107
- } else {
1108
- store.on.selectorDisposal.next(selectorToken);
1109
- }
1110
- }
1111
- }
1112
-
1113
- // internal/src/families/create-readonly-selector-family.ts
1114
- function createReadonlySelectorFamily(options, store) {
1115
- const subject = new Subject();
1116
- const readonlySelectorFamily = Object.assign(
1117
- (key) => {
1118
- const subKey = json.stringifyJson(key);
1119
- const family = { key: options.key, subKey };
1120
- const fullKey = `${options.key}(${subKey})`;
1121
- const target = newest(store);
1122
- const token = createReadonlySelector(
1123
- {
1124
- key: fullKey,
1125
- get: options.get(key)
1126
- },
1127
- family,
1128
- target
1129
- );
1130
- subject.next({ type: `state_creation`, token });
1131
- return token;
1132
- },
1133
- {
1134
- key: options.key,
1135
- type: `readonly_selector_family`,
1136
- subject,
1137
- install: (s) => createReadonlySelectorFamily(options, s)
1138
- }
1139
- );
1140
- store.families.set(options.key, readonlySelectorFamily);
1141
- return readonlySelectorFamily;
1142
- }
1143
- function createWritableSelectorFamily(options, store) {
1144
- const subject = new Subject();
1145
- const selectorFamily = Object.assign(
1146
- (key) => {
1147
- const subKey = json.stringifyJson(key);
1148
- const family = { key: options.key, subKey };
1149
- const fullKey = `${options.key}(${subKey})`;
1150
- const target = newest(store);
1151
- const token = createWritableSelector(
1152
- {
1153
- key: fullKey,
1154
- get: options.get(key),
1155
- set: options.set(key)
1156
- },
1157
- family,
1158
- target
1159
- );
1160
- subject.next({ type: `state_creation`, token });
1161
- return token;
1162
- },
1163
- {
1164
- key: options.key,
1165
- type: `selector_family`,
1166
- subject,
1167
- install: (s) => createWritableSelectorFamily(options, s)
1168
- }
1169
- );
1170
- store.families.set(options.key, selectorFamily);
1171
- return selectorFamily;
1172
- }
1173
-
1174
- // internal/src/families/create-selector-family.ts
1175
- function createSelectorFamily(options, store) {
1176
- const isWritable = `set` in options;
1177
- if (isWritable) {
1178
- return createWritableSelectorFamily(options, store);
1179
- }
1180
- return createReadonlySelectorFamily(options, store);
1181
- }
1182
-
1183
- // internal/src/molecule/dispose-molecule.ts
1184
- function disposeMolecule(token, store) {
1185
- var _a;
1186
- let molecule;
1187
- try {
1188
- molecule = withdraw(token, store);
1189
- } catch (thrown) {
1190
- if (thrown instanceof Error) {
1191
- store.logger.error(
1192
- `\u{1F41E}`,
1193
- `molecule`,
1194
- JSON.stringify(token.key),
1195
- `Failed to dispose molecule, because it was not found in the store.`,
1196
- thrown.message
1197
- );
1198
- }
1199
- return;
1200
- }
1201
- const { family } = token;
1202
- const context = [];
1203
- for (const above of molecule.above.values()) {
1204
- context.push(deposit(above));
1205
- }
1206
- const values = [];
1207
- for (const stateToken of molecule.tokens.values()) {
1208
- const tokenFamily = stateToken.family;
1209
- values.push([tokenFamily.key, store.valueMap.get(stateToken.key)]);
1210
- }
1211
- if (family) {
1212
- const Formula = withdraw(family, store);
1213
- const disposalEvent = {
1214
- type: `molecule_disposal`,
1215
- token,
1216
- family,
1217
- context,
1218
- values
1219
- };
1220
- if (token.family) {
1221
- disposalEvent.family = token.family;
1222
- }
1223
- for (const state of molecule.tokens.values()) {
1224
- disposeFromStore(state, store);
1225
- }
1226
- for (const child of molecule.below.values()) {
1227
- if (((_a = child.family) == null ? void 0 : _a.dependsOn) === `all`) {
1228
- disposeMolecule(child, store);
1229
- } else {
1230
- child.above.delete(molecule.stringKey);
1231
- if (child.above.size === 0) {
1232
- disposeMolecule(child, store);
1233
- }
1234
- }
1235
- }
1236
- molecule.below.clear();
1237
- const isTransaction = isChildStore(store) && store.transactionMeta.phase === `building`;
1238
- if (isTransaction) {
1239
- store.transactionMeta.update.updates.push(disposalEvent);
1240
- } else {
1241
- Formula.subject.next(disposalEvent);
1242
- }
1243
- store.molecules.delete(molecule.stringKey);
1244
- }
1245
- for (const join of molecule.joins.values()) {
1246
- join.molecules.delete(molecule.stringKey);
1247
- }
1248
- for (const parent of molecule.above.values()) {
1249
- parent.below.delete(molecule.stringKey);
1250
- }
1251
- }
1252
-
1253
- // internal/src/families/init-family-member.ts
1254
- function initFamilyMemberInStore(token, key, store) {
1255
- const familyKey = token.key;
1256
- const family = store.families.get(familyKey);
1257
- if (family === void 0) {
1258
- throw new NotFoundError(token, store);
1259
- }
1260
- const state = family(key);
1261
- const target = newest(store);
1262
- if (state.family && target.moleculeInProgress === null) {
1263
- if (isRootStore(target)) {
1264
- switch (state.type) {
1265
- case `atom`:
1266
- case `mutable_atom`:
1267
- store.on.atomCreation.next(state);
1268
- break;
1269
- case `selector`:
1270
- case `readonly_selector`:
1271
- store.on.selectorCreation.next(state);
1272
- break;
1273
- }
1274
- } else if (isChildStore(target) && target.on.transactionApplying.state === null) {
1275
- target.transactionMeta.update.updates.push({
1276
- type: `state_creation`,
1277
- token: state
1278
- });
1279
- }
1280
- }
1281
- return state;
1282
- }
1283
- function seekInStore(token, key, store) {
1284
- const subKey = json.stringifyJson(key);
1285
- const fullKey = `${token.key}(${subKey})`;
1286
- const target = newest(store);
1287
- let state;
1288
- switch (token.type) {
1289
- case `atom_family`:
1290
- case `mutable_atom_family`:
1291
- state = target.atoms.get(fullKey);
1292
- break;
1293
- case `selector_family`:
1294
- state = target.selectors.get(fullKey);
1295
- break;
1296
- case `readonly_selector_family`:
1297
- state = target.readonlySelectors.get(fullKey);
1298
- break;
1299
- case `molecule_family`:
1300
- state = target.molecules.get(json.stringifyJson(key));
1301
- if (state) {
1302
- return deposit(state);
1303
- }
1304
- }
1305
- if (state) {
1306
- return deposit(state);
1307
- }
1308
- return state;
1309
- }
1310
-
1311
- // internal/src/families/find-in-store.ts
1312
- function findInStore(token, key, store) {
1313
- if (store.config.lifespan === `immortal`) {
1314
- throw new Error(
1315
- `Do not use \`find\` or \`findState\` in an immortal store. Prefer \`seek\` or \`seekState\`.`
1316
- );
1317
- }
1318
- let state = seekInStore(token, key, store);
1319
- if (state) {
1320
- return state;
1321
- }
1322
- state = initFamilyMemberInStore(token, key, store);
1323
- return state;
1324
- }
1325
-
1326
- // internal/src/families/dispose-from-store.ts
1327
- function disposeFromStore(...params) {
1328
- let token;
1329
- let store;
1330
- if (params.length === 2) {
1331
- token = params[0];
1332
- store = params[1];
1333
- } else {
1334
- const family = params[0];
1335
- const key = params[1];
1336
- store = params[2];
1337
- const maybeToken = family.type === `molecule_family` ? seekInStore(family, key, store) : store.config.lifespan === `immortal` ? seekInStore(family, key, store) : findInStore(family, key, store);
1338
- if (!maybeToken) {
1339
- throw new NotFoundError(family, key, store);
1340
- }
1341
- token = maybeToken;
1342
- }
1343
- switch (token.type) {
1344
- case `atom`:
1345
- case `mutable_atom`:
1346
- disposeAtom(token, store);
1347
- break;
1348
- case `selector`:
1349
- case `readonly_selector`:
1350
- disposeSelector(token, store);
1351
- break;
1352
- case `molecule`:
1353
- disposeMolecule(token, store);
1354
- break;
1355
- }
1356
- }
1357
-
1358
- // internal/src/set-state/set-into-store.ts
1359
- function setIntoStore(...params) {
1360
- let token;
1361
- let value;
1362
- let store;
1363
- if (params.length === 3) {
1364
- token = params[0];
1365
- value = params[1];
1366
- store = params[2];
1367
- } else {
1368
- const family = params[0];
1369
- const key = params[1];
1370
- value = params[2];
1371
- store = params[3];
1372
- const maybeToken = store.config.lifespan === `ephemeral` ? findInStore(family, key, store) : seekInStore(family, key, store);
1373
- if (!maybeToken) {
1374
- throw new NotFoundError(family, key, store);
1375
- }
1376
- token = maybeToken;
1377
- }
1378
- const rejectionTime = openOperation(token, store);
1379
- if (rejectionTime) {
1380
- const unsubscribe = store.on.operationClose.subscribe(
1381
- `waiting to set "${token.key}" at T-${rejectionTime}`,
1382
- () => {
1383
- unsubscribe();
1384
- store.logger.info(
1385
- `\u{1F7E2}`,
1386
- token.type,
1387
- token.key,
1388
- `resuming deferred setState from T-${rejectionTime}`
1389
- );
1390
- setIntoStore(token, value, store);
1391
- }
1392
- );
1393
- return;
1394
- }
1395
- const state = withdraw(token, store);
1396
- setAtomOrSelector(state, value, store);
1397
- closeOperation(store);
1398
- }
1399
-
1400
- // internal/src/ingest-updates/ingest-atom-update.ts
1401
- function ingestAtomUpdate(applying, atomUpdate, store) {
1402
- const { key, newValue, oldValue } = atomUpdate;
1403
- const value = applying === `newValue` ? newValue : oldValue;
1404
- const token = { key, type: `atom` };
1405
- if (atomUpdate.family) {
1406
- Object.assign(token, { family: atomUpdate.family });
1407
- }
1408
- setIntoStore(token, value, store);
1409
- }
1410
-
1411
- // internal/src/molecule/create-molecule-family.ts
1412
- function createMoleculeFamily(options, store) {
1413
- var _a;
1414
- const subject = new Subject();
1415
- const token = {
1416
- type: `molecule_family`,
1417
- key: options.key,
1418
- dependsOn: (_a = options.dependsOn) != null ? _a : `all`
1419
- };
1420
- const family = __spreadProps(__spreadValues({}, token), {
1421
- subject,
1422
- new: options.new
1423
- });
1424
- store.moleculeFamilies.set(options.key, family);
1425
- return token;
1426
- }
1427
-
1428
- // internal/src/molecule/grow-molecule-in-store.ts
1429
- function growMoleculeInStore(molecule, family, store) {
1430
- const stateToken = initFamilyMemberInStore(family, molecule.key, store);
1431
- molecule.tokens.set(stateToken.key, stateToken);
1432
- const isTransaction = isChildStore(store) && store.transactionMeta.phase === `building`;
1433
- const moleculeInProgress = store.moleculeInProgress === molecule.key;
1434
- if (!isTransaction && !moleculeInProgress) {
1435
- molecule.subject.next({ type: `state_creation`, token: stateToken });
1436
- }
1437
- return stateToken;
1438
- }
1439
-
1440
- // internal/src/get-environment-data.ts
1441
- function getEnvironmentData(store) {
1442
- return {
1443
- store
1444
- };
1445
- }
1446
- var Molecule = class {
1447
- constructor(ctx, key, family) {
1448
- this.key = key;
1449
- this.type = `molecule`;
1450
- this.subject = new Subject();
1451
- this.tokens = /* @__PURE__ */ new Map();
1452
- this.above = /* @__PURE__ */ new Map();
1453
- this.below = /* @__PURE__ */ new Map();
1454
- this.joins = /* @__PURE__ */ new Map();
1455
- this.stringKey = json.stringifyJson(key);
1456
- if (family) {
1457
- this.family = family;
1458
- }
1459
- if (ctx) {
1460
- if (Array.isArray(ctx)) {
1461
- for (const molecule of ctx) {
1462
- this.above.set(molecule.stringKey, molecule);
1463
- }
1464
- } else {
1465
- this.above.set(ctx.stringKey, ctx);
1466
- }
1467
- }
1468
- }
1469
- };
1470
-
1471
- // internal/src/molecule/make-molecule-in-store.ts
1472
- function capitalize2(string) {
1473
- return string[0].toUpperCase() + string.slice(1);
1474
- }
1475
- function makeMoleculeInStore(store, context, familyToken, key, ...params) {
1476
- const rootStore = eldest(store);
1477
- const target = newest(store);
1478
- const stringKey = json.stringifyJson(key);
1479
- target.moleculeInProgress = stringKey;
1480
- const contextArray = Array.isArray(context) ? context : [context];
1481
- const owners = contextArray.map((ctx) => {
1482
- if (ctx instanceof Molecule) {
1483
- return ctx;
1484
- }
1485
- const ctxStringKey = json.stringifyJson(ctx.key);
1486
- const molecule2 = store.molecules.get(ctxStringKey);
1487
- if (!molecule2) {
1488
- throw new Error(
1489
- `Molecule ${ctxStringKey} not found in store "${store.config.name}"`
1490
- );
1491
- }
1492
- return molecule2;
1493
- });
1494
- const molecule = new Molecule(owners, key, familyToken);
1495
- target.molecules.set(stringKey, molecule);
1496
- for (const owner of owners) {
1497
- owner.below.set(molecule.stringKey, molecule);
1498
- }
1499
- const toolkit = {
1500
- get: (...ps) => getFromStore(...ps, newest(rootStore)),
1501
- set: (...ps) => {
1502
- setIntoStore(...ps, newest(rootStore));
1503
- },
1504
- seek: (t, k) => seekInStore(t, k, newest(rootStore)),
1505
- json: (t) => getJsonToken(t, newest(rootStore)),
1506
- run: (t, i = arbitrary()) => actUponStore(t, i, newest(store)),
1507
- make: (ctx, f, k, ...args) => makeMoleculeInStore(newest(rootStore), ctx, f, k, ...args),
1508
- dispose: (t) => {
1509
- disposeFromStore(t, newest(rootStore));
1510
- },
1511
- env: () => getEnvironmentData(newest(rootStore)),
1512
- bond: (token2, maybeRole) => {
1513
- if (token2.type === `join`) {
1514
- const { as: role } = maybeRole;
1515
- const join = data.getJoin(token2, rootStore);
1516
- join.molecules.set(stringKey, molecule);
1517
- molecule.joins.set(token2.key, join);
1518
- const unsubFromFamily = family.subject.subscribe(
1519
- `join:${token2.key}-${stringKey}`,
1520
- (event) => {
1521
- if (event.type === `molecule_disposal` && json.stringifyJson(event.token.key) === stringKey) {
1522
- unsubFromFamily();
1523
- join.molecules.delete(stringKey);
1524
- }
1525
- }
1526
- );
1527
- if (role === null) {
1528
- return;
1529
- }
1530
- const otherRole = token2.a === role ? token2.b : token2.a;
1531
- const relations = data.findRelations(token2, key);
1532
- const relatedKeys = relations[`${otherRole}KeysOf${capitalize2(role)}`];
1533
- const relatedEntries = relations[`${otherRole}EntriesOf${capitalize2(role)}`];
1534
- let tokens = { relatedKeys };
1535
- if (relatedEntries) {
1536
- tokens = Object.assign(tokens, { relatedEntries });
1537
- }
1538
- return tokens;
1539
- }
1540
- return growMoleculeInStore(
1541
- molecule,
1542
- withdraw(token2, rootStore),
1543
- newest(rootStore)
1544
- );
1545
- },
1546
- claim: (below, options) => {
1547
- const { exclusive } = options;
1548
- const belowMolecule = newest(store).molecules.get(json.stringifyJson(below.key));
1549
- if (belowMolecule) {
1550
- if (exclusive) {
1551
- for (const value of belowMolecule.above.values()) {
1552
- value.below.delete(belowMolecule.stringKey);
1553
- }
1554
- belowMolecule.above.clear();
1555
- belowMolecule.above.set(molecule.stringKey, molecule);
1556
- molecule.below.set(belowMolecule.stringKey, belowMolecule);
1557
- } else {
1558
- belowMolecule.above.set(molecule.stringKey, molecule);
1559
- molecule.below.set(belowMolecule.stringKey, belowMolecule);
1560
- }
1561
- }
1562
- },
1563
- spawn: (f, k, ...p) => makeMoleculeInStore(
1564
- newest(store),
1565
- [molecule],
1566
- withdraw(f, store),
1567
- k,
1568
- ...p
1569
- )
1570
- };
1571
- const family = withdraw(familyToken, store);
1572
- const Constructor = family.new;
1573
- molecule.instance = new Constructor(toolkit, key, ...params);
1574
- const token = {
1575
- type: `molecule`,
1576
- key,
1577
- family: familyToken
1578
- };
1579
- const update = {
1580
- type: `molecule_creation`,
1581
- token,
1582
- family: familyToken,
1583
- context: contextArray,
1584
- params
1585
- };
1586
- if (isRootStore(target)) {
1587
- family.subject.next(update);
1588
- } else if (isChildStore(target) && target.on.transactionApplying.state === null) {
1589
- target.transactionMeta.update.updates.push(update);
1590
- }
1591
- target.moleculeInProgress = null;
1592
- return token;
1593
- }
1594
-
1595
- // internal/src/ingest-updates/ingest-creation-disposal.ts
1596
- function ingestCreationEvent(update, applying, store) {
1597
- switch (applying) {
1598
- case `newValue`: {
1599
- createInStore(update.token, store);
1600
- break;
1601
- }
1602
- case `oldValue`: {
1603
- disposeFromStore(update.token, store);
1604
- break;
1605
- }
1606
- }
1607
- }
1608
- function ingestDisposalEvent(update, applying, store) {
1609
- switch (applying) {
1610
- case `newValue`: {
1611
- disposeFromStore(update.token, store);
1612
- break;
1613
- }
1614
- case `oldValue`: {
1615
- createInStore(update.token, store);
1616
- store.valueMap.set(update.token.key, update.value);
1617
- break;
1618
- }
1619
- }
1620
- }
1621
- function createInStore(token, store) {
1622
- if (token.family) {
1623
- const family = store.families.get(token.family.key);
1624
- if (family) {
1625
- const molecule = store.molecules.get(token.family.subKey);
1626
- if (molecule) {
1627
- growMoleculeInStore(molecule, family, store);
1628
- return;
1629
- }
1630
- if (store.config.lifespan === `immortal`) {
1631
- throw new Error(`No molecule found for key "${token.family.subKey}"`);
1632
- }
1633
- initFamilyMemberInStore(family, json.parseJson(token.family.subKey), store);
1634
- }
1635
- }
1636
- }
1637
- function ingestMoleculeCreationEvent(update, applying, store) {
1638
- switch (applying) {
1639
- case `newValue`:
1640
- makeMoleculeInStore(
1641
- store,
1642
- update.context,
1643
- update.family,
1644
- update.token.key,
1645
- ...update.params
1646
- );
1647
- break;
1648
- case `oldValue`:
1649
- disposeFromStore(update.token, store);
1650
- break;
1651
- }
1652
- }
1653
- function ingestMoleculeDisposalEvent(update, applying, store) {
1654
- switch (applying) {
1655
- case `newValue`:
1656
- disposeFromStore(update.token, store);
1657
- break;
1658
- case `oldValue`:
1659
- {
1660
- const moleculeToken = makeMoleculeInStore(
1661
- store,
1662
- update.context,
1663
- update.family,
1664
- update.token.key
1665
- );
1666
- for (const [familyKey, value] of update.values) {
1667
- const memberKey = `${familyKey}(${json.stringifyJson(moleculeToken.key)})`;
1668
- const molecule = withdraw(moleculeToken, store);
1669
- const alreadyCreated = molecule.tokens.has(memberKey);
1670
- const family = store.families.get(familyKey);
1671
- if (family && !alreadyCreated) {
1672
- growMoleculeInStore(molecule, family, store);
1673
- }
1674
- store.valueMap.set(memberKey, value);
1675
- }
1676
- }
1677
- break;
1678
- }
1679
- }
1680
-
1681
- // internal/src/ingest-updates/ingest-selector-update.ts
1682
- function ingestSelectorUpdate(applying, selectorUpdate, store) {
1683
- const updates = applying === `newValue` ? selectorUpdate.atomUpdates : [...selectorUpdate.atomUpdates].reverse();
1684
- for (const atomUpdate of updates) {
1685
- ingestAtomUpdate(applying, atomUpdate, store);
1686
- }
1687
- }
1688
-
1689
- // internal/src/ingest-updates/ingest-transaction-update.ts
1690
- function ingestTransactionUpdate(applying, transactionUpdate, store) {
1691
- const updates = applying === `newValue` ? transactionUpdate.updates : [...transactionUpdate.updates].reverse();
1692
- for (const updateFromTransaction of updates) {
1693
- switch (updateFromTransaction.type) {
1694
- case `atom_update`:
1695
- case `selector_update`:
1696
- ingestAtomUpdate(applying, updateFromTransaction, store);
1697
- break;
1698
- case `state_creation`:
1699
- ingestCreationEvent(updateFromTransaction, applying, store);
1700
- break;
1701
- case `state_disposal`:
1702
- ingestDisposalEvent(updateFromTransaction, applying, store);
1703
- break;
1704
- case `molecule_creation`:
1705
- ingestMoleculeCreationEvent(updateFromTransaction, applying, store);
1706
- break;
1707
- case `molecule_disposal`:
1708
- ingestMoleculeDisposalEvent(updateFromTransaction, applying, store);
1709
- break;
1710
- case `transaction_update`:
1711
- ingestTransactionUpdate(applying, updateFromTransaction, store);
1712
- break;
1713
- }
1714
- }
1715
- }
1716
-
1717
- // internal/src/transaction/set-epoch-number.ts
1718
- function setEpochNumberOfContinuity(continuityKey, newEpoch, store) {
1719
- const isRoot = isRootStore(store);
1720
- if (isRoot && continuityKey) {
1721
- store.transactionMeta.epoch.set(continuityKey, newEpoch);
1722
- }
1723
- }
1724
- function setEpochNumberOfAction(transactionKey, newEpoch, store) {
1725
- const isRoot = isRootStore(store);
1726
- if (!isRoot) {
1727
- return;
1728
- }
1729
- const continuityKey = store.transactionMeta.actionContinuities.getRelatedKey(transactionKey);
1730
- if (continuityKey !== void 0) {
1731
- store.transactionMeta.epoch.set(continuityKey, newEpoch);
1732
- }
1733
- }
1734
-
1735
- // internal/src/transaction/apply-transaction.ts
1736
- var applyTransaction = (output, store) => {
1737
- var _a;
1738
- const child = newest(store);
1739
- const { parent } = child;
1740
- if (parent === null || !isChildStore(child) || ((_a = child.transactionMeta) == null ? void 0 : _a.phase) !== `building`) {
1741
- store.logger.warn(
1742
- `\u{1F41E}`,
1743
- `transaction`,
1744
- `???`,
1745
- `applyTransaction called outside of a transaction. This is probably a bug in AtomIO.`
1746
- );
1747
- return;
1748
- }
1749
- child.transactionMeta.phase = `applying`;
1750
- child.transactionMeta.update.output = output;
1751
- parent.child = null;
1752
- parent.on.transactionApplying.next(child.transactionMeta);
1753
- const { updates } = child.transactionMeta.update;
1754
- store.logger.info(
1755
- `\u{1F6C4}`,
1756
- `transaction`,
1757
- child.transactionMeta.update.key,
1758
- `Applying transaction with ${updates.length} updates:`,
1759
- updates
1760
- );
1761
- ingestTransactionUpdate(`newValue`, child.transactionMeta.update, parent);
1762
- if (isRootStore(parent)) {
1763
- setEpochNumberOfAction(
1764
- child.transactionMeta.update.key,
1765
- child.transactionMeta.update.epoch,
1766
- parent
1767
- );
1768
- const myTransaction = withdraw(
1769
- { key: child.transactionMeta.update.key, type: `transaction` },
1770
- store
1771
- );
1772
- myTransaction == null ? void 0 : myTransaction.subject.next(child.transactionMeta.update);
1773
- store.logger.info(
1774
- `\u{1F6EC}`,
1775
- `transaction`,
1776
- child.transactionMeta.update.key,
1777
- `Finished applying transaction.`
1778
- );
1779
- } else if (isChildStore(parent)) {
1780
- parent.transactionMeta.update.updates.push(child.transactionMeta.update);
1781
- }
1782
- parent.on.transactionApplying.next(null);
1783
- };
1784
-
1785
- // internal/src/transaction/assign-transaction-to-continuity.ts
1786
- function assignTransactionToContinuity(continuityKey, transactionKey, store) {
1787
- const isRoot = isRootStore(store);
1788
- if (!isRoot) {
1789
- return;
1790
- }
1791
- const { epoch, actionContinuities } = store.transactionMeta;
1792
- actionContinuities.set(continuityKey, transactionKey);
1793
- if (!epoch.has(continuityKey)) {
1794
- epoch.set(continuityKey, -1);
1795
- }
1796
- }
1797
-
1798
- // internal/src/lazy-map.ts
1799
- var LazyMap = class extends Map {
1800
- constructor(source) {
1801
- super();
1802
- this.source = source;
1803
- this.deleted = /* @__PURE__ */ new Set();
1804
- }
1805
- get(key) {
1806
- const has = super.has(key);
1807
- if (has) {
1808
- return super.get(key);
1809
- }
1810
- if (!this.deleted.has(key) && this.source.has(key)) {
1811
- const value = this.source.get(key);
1812
- return value;
1813
- }
1814
- return void 0;
1815
- }
1816
- set(key, value) {
1817
- this.deleted.delete(key);
1818
- return super.set(key, value);
1819
- }
1820
- hasOwn(key) {
1821
- return super.has(key);
1822
- }
1823
- has(key) {
1824
- return !this.deleted.has(key) && (super.has(key) || this.source.has(key));
1825
- }
1826
- delete(key) {
1827
- this.deleted.add(key);
1828
- return super.delete(key);
1829
- }
1830
- };
1831
-
1832
- // internal/src/transaction/build-transaction.ts
1833
- var buildTransaction = (key, params, store, id) => {
1834
- const parent = newest(store);
1835
- const childBase = {
1836
- parent,
1837
- child: null,
1838
- on: parent.on,
1839
- loggers: parent.loggers,
1840
- logger: parent.logger,
1841
- config: parent.config,
1842
- atoms: new LazyMap(parent.atoms),
1843
- atomsThatAreDefault: new Set(parent.atomsThatAreDefault),
1844
- families: new LazyMap(parent.families),
1845
- operation: { open: false },
1846
- readonlySelectors: new LazyMap(parent.readonlySelectors),
1847
- timelines: new LazyMap(parent.timelines),
1848
- timelineTopics: new Junction(parent.timelineTopics.toJSON()),
1849
- trackers: /* @__PURE__ */ new Map(),
1850
- transactions: new LazyMap(parent.transactions),
1851
- selectorAtoms: new Junction(parent.selectorAtoms.toJSON()),
1852
- selectorGraph: new Junction(parent.selectorGraph.toJSON(), {
1853
- makeContentKey: (...keys) => keys.sort().join(`:`)
1854
- }),
1855
- selectors: new LazyMap(parent.selectors),
1856
- valueMap: new LazyMap(parent.valueMap),
1857
- molecules: new LazyMap(parent.molecules),
1858
- moleculeFamilies: new LazyMap(parent.moleculeFamilies),
1859
- moleculeInProgress: parent.moleculeInProgress,
1860
- miscResources: new LazyMap(parent.miscResources)
1861
- };
1862
- const epoch = getEpochNumberOfAction(key, store);
1863
- const transactionMeta = {
1864
- phase: `building`,
1865
- update: {
1866
- type: `transaction_update`,
1867
- key,
1868
- id,
1869
- epoch: epoch === void 0 ? Number.NaN : epoch + 1,
1870
- updates: [],
1871
- params,
1872
- output: void 0
1873
- },
1874
- toolkit: {
1875
- get: (...ps) => getFromStore(...ps, child),
1876
- set: (...ps) => {
1877
- setIntoStore(...ps, child);
1878
- },
1879
- run: (token, identifier = arbitrary()) => actUponStore(token, identifier, child),
1880
- find: (token, k) => findInStore(token, k, child),
1881
- seek: (token, k) => seekInStore(token, k, child),
1882
- json: (token) => getJsonToken(token, child),
1883
- make: (context, family, k, ...args) => makeMoleculeInStore(child, context, family, k, ...args),
1884
- dispose: (...ps) => {
1885
- disposeFromStore(...ps, child);
1886
- },
1887
- env: () => getEnvironmentData(child)
1888
- }
1889
- };
1890
- const child = Object.assign(childBase, {
1891
- transactionMeta
1892
- });
1893
- parent.child = child;
1894
- store.logger.info(
1895
- `\u{1F6EB}`,
1896
- `transaction`,
1897
- key,
1898
- `Building transaction with params:`,
1899
- params
1900
- );
1901
- return child;
1902
- };
1903
-
1904
- // internal/src/transaction/create-transaction.ts
1905
- function createTransaction(options, store) {
1906
- const newTransaction = {
1907
- key: options.key,
1908
- type: `transaction`,
1909
- run: (params, id) => {
1910
- const childStore = buildTransaction(options.key, params, store, id);
1911
- try {
1912
- const target2 = newest(store);
1913
- const { toolkit } = childStore.transactionMeta;
1914
- const output = options.do(toolkit, ...params);
1915
- applyTransaction(output, target2);
1916
- return output;
1917
- } catch (thrown) {
1918
- abortTransaction(target);
1919
- store.logger.warn(`\u{1F4A5}`, `transaction`, options.key, `caught:`, thrown);
1920
- throw thrown;
1921
- }
1922
- },
1923
- install: (s) => createTransaction(options, s),
1924
- subject: new Subject()
1925
- };
1926
- const target = newest(store);
1927
- target.transactions.set(newTransaction.key, newTransaction);
1928
- const token = deposit(newTransaction);
1929
- store.on.transactionCreation.next(token);
1930
- return token;
1931
- }
1932
-
1933
- // internal/src/transaction/get-epoch-number.ts
1934
- function getContinuityKey(transactionKey, store) {
1935
- const isRoot = isRootStore(store);
1936
- const continuity = isRoot ? store.transactionMeta.actionContinuities.getRelatedKey(transactionKey) : void 0;
1937
- return continuity;
1938
- }
1939
- function getEpochNumberOfContinuity(continuityKey, store) {
1940
- const isRoot = isRootStore(store);
1941
- const epoch = isRoot && continuityKey ? store.transactionMeta.epoch.get(continuityKey) : void 0;
1942
- return epoch;
1943
- }
1944
- function getEpochNumberOfAction(transactionKey, store) {
1945
- const isRoot = isRootStore(store);
1946
- const continuity = isRoot ? store.transactionMeta.actionContinuities.getRelatedKey(transactionKey) : void 0;
1947
- const epoch = isRoot && continuity !== void 0 ? store.transactionMeta.epoch.get(continuity) : void 0;
1948
- return epoch;
1949
- }
1950
-
1951
- // internal/src/transaction/index.ts
1952
- var TRANSACTION_PHASES = [`idle`, `building`, `applying`];
1953
-
1954
- // internal/src/store/store.ts
1955
- var Store = class {
1956
- constructor(config, store = null) {
1957
- this.parent = null;
1958
- this.child = null;
1959
- this.valueMap = /* @__PURE__ */ new Map();
1960
- this.atoms = /* @__PURE__ */ new Map();
1961
- this.selectors = /* @__PURE__ */ new Map();
1962
- this.readonlySelectors = /* @__PURE__ */ new Map();
1963
- this.atomsThatAreDefault = /* @__PURE__ */ new Set();
1964
- this.selectorAtoms = new Junction({
1965
- between: [`selectorKey`, `atomKey`],
1966
- cardinality: `n:n`
1967
- });
1968
- this.selectorGraph = new Junction(
1969
- {
1970
- between: [`upstreamSelectorKey`, `downstreamSelectorKey`],
1971
- cardinality: `n:n`
1972
- },
1973
- {
1974
- makeContentKey: (...keys) => keys.sort().join(`:`)
1975
- }
1976
- );
1977
- this.trackers = /* @__PURE__ */ new Map();
1978
- this.families = /* @__PURE__ */ new Map();
1979
- this.transactions = /* @__PURE__ */ new Map();
1980
- this.transactionMeta = {
1981
- epoch: /* @__PURE__ */ new Map(),
1982
- actionContinuities: new Junction({
1983
- between: [`continuity`, `action`],
1984
- cardinality: `1:n`
1985
- })
1986
- };
1987
- this.timelines = /* @__PURE__ */ new Map();
1988
- this.timelineTopics = new Junction({
1989
- between: [`timelineKey`, `topicKey`],
1990
- cardinality: `1:n`
1991
- });
1992
- this.molecules = /* @__PURE__ */ new Map();
1993
- this.moleculeFamilies = /* @__PURE__ */ new Map();
1994
- this.moleculeInProgress = null;
1995
- this.miscResources = /* @__PURE__ */ new Map();
1996
- this.on = {
1997
- atomCreation: new Subject(),
1998
- atomDisposal: new Subject(),
1999
- selectorCreation: new Subject(),
2000
- selectorDisposal: new Subject(),
2001
- timelineCreation: new Subject(),
2002
- transactionCreation: new Subject(),
2003
- transactionApplying: new StatefulSubject(
2004
- null
2005
- ),
2006
- operationClose: new Subject(),
2007
- moleculeCreationStart: new Subject(),
2008
- moleculeCreationDone: new Subject(),
2009
- moleculeDisposal: new Subject()
2010
- };
2011
- this.operation = { open: false };
2012
- this.config = {
2013
- name: `IMPLICIT_STORE`,
2014
- lifespan: `ephemeral`
2015
- };
2016
- this.loggers = [
2017
- new atom_io.AtomIOLogger(`warn`, (_, __, key) => !key.includes(`\u{1F441}\u200D\u{1F5E8}`))
2018
- ];
2019
- this.logger = {
2020
- error: (...messages) => {
2021
- for (const logger of this.loggers) logger.error(...messages);
2022
- },
2023
- info: (...messages) => {
2024
- for (const logger of this.loggers) logger.info(...messages);
2025
- },
2026
- warn: (...messages) => {
2027
- for (const logger of this.loggers) logger.warn(...messages);
2028
- }
2029
- };
2030
- this.config = __spreadValues(__spreadValues({}, store == null ? void 0 : store.config), config);
2031
- if (store !== null) {
2032
- this.valueMap = new Map(store == null ? void 0 : store.valueMap);
2033
- this.operation = __spreadValues({}, store == null ? void 0 : store.operation);
2034
- if (isRootStore(store)) {
2035
- this.transactionMeta = {
2036
- epoch: new Map(store == null ? void 0 : store.transactionMeta.epoch),
2037
- actionContinuities: new Junction(
2038
- store == null ? void 0 : store.transactionMeta.actionContinuities.toJSON()
2039
- )
2040
- };
2041
- }
2042
- for (const [, family] of store.families) {
2043
- family.install(this);
2044
- }
2045
- const mutableHelpers = /* @__PURE__ */ new Set();
2046
- for (const [, atom] of store.atoms) {
2047
- if (mutableHelpers.has(atom.key)) {
2048
- continue;
2049
- }
2050
- atom.install(this);
2051
- if (atom.type === `mutable_atom`) {
2052
- const originalJsonToken = getJsonToken(atom, store);
2053
- const originalUpdateToken = getUpdateToken(atom);
2054
- mutableHelpers.add(originalJsonToken.key);
2055
- mutableHelpers.add(originalUpdateToken.key);
2056
- }
2057
- }
2058
- for (const [, selector] of store.readonlySelectors) {
2059
- selector.install(this);
2060
- }
2061
- for (const [, selector] of store.selectors) {
2062
- if (mutableHelpers.has(selector.key)) {
2063
- continue;
2064
- }
2065
- selector.install(this);
2066
- }
2067
- for (const [, tx] of store.transactions) {
2068
- tx.install(this);
2069
- }
2070
- for (const [, timeline] of store.timelines) {
2071
- timeline.install(this);
2072
- }
2073
- }
2074
- }
2075
- };
2076
- var IMPLICIT = {
2077
- get STORE() {
2078
- if (!globalThis.ATOM_IO_IMPLICIT_STORE) {
2079
- globalThis.ATOM_IO_IMPLICIT_STORE = new Store({
2080
- name: `IMPLICIT_STORE`,
2081
- lifespan: `ephemeral`
2082
- });
2083
- }
2084
- return globalThis.ATOM_IO_IMPLICIT_STORE;
2085
- }
2086
- };
2087
- var clearStore = (store) => {
2088
- const { config } = store;
2089
- for (const disposable of store.miscResources.values()) {
2090
- disposable[Symbol.dispose]();
2091
- }
2092
- Object.assign(store, new Store(config));
2093
- store.config = config;
2094
- };
2095
- function withdraw(token, store) {
2096
- let withdrawn;
2097
- let target = store;
2098
- while (target !== null) {
2099
- switch (token.type) {
2100
- case `atom`:
2101
- case `mutable_atom`:
2102
- withdrawn = target.atoms.get(token.key);
2103
- break;
2104
- case `selector`:
2105
- withdrawn = target.selectors.get(token.key);
2106
- break;
2107
- case `readonly_selector`:
2108
- withdrawn = target.readonlySelectors.get(token.key);
2109
- break;
2110
- case `atom_family`:
2111
- case `mutable_atom_family`:
2112
- case `selector_family`:
2113
- case `readonly_selector_family`:
2114
- withdrawn = target.families.get(token.key);
2115
- break;
2116
- case `timeline`:
2117
- withdrawn = target.timelines.get(token.key);
2118
- break;
2119
- case `transaction`:
2120
- withdrawn = target.transactions.get(token.key);
2121
- break;
2122
- case `molecule`:
2123
- withdrawn = target.molecules.get(json.stringifyJson(token.key));
2124
- break;
2125
- case `molecule_family`:
2126
- withdrawn = target.moleculeFamilies.get(token.key);
2127
- break;
2128
- }
2129
- if (withdrawn) {
2130
- return withdrawn;
2131
- }
2132
- target = target.child;
2133
- }
2134
- throw new NotFoundError(token, store);
2135
- }
2136
-
2137
- // internal/src/subscribe/recall-state.ts
2138
- var recallState = (state, store) => {
2139
- const target = newest(store);
2140
- if (target.operation.open) {
2141
- return target.operation.prev.get(state.key);
2142
- }
2143
- return target.valueMap.get(state.key);
2144
- };
2145
-
2146
- // internal/src/subscribe/subscribe-to-root-atoms.ts
2147
- var subscribeToRootAtoms = (selector, store) => {
2148
- const target = newest(store);
2149
- const dependencySubscriptions = traceAllSelectorAtoms(selector, store).map(
2150
- (atomKey) => {
2151
- const atom = target.atoms.get(atomKey);
2152
- if (atom === void 0) {
2153
- throw new Error(
2154
- `Atom "${atomKey}", a dependency of selector "${selector.key}", not found in store "${store.config.name}".`
2155
- );
2156
- }
2157
- return atom.subject.subscribe(
2158
- `${selector.type}:${selector.key}`,
2159
- (atomChange) => {
2160
- store.logger.info(
2161
- `\u{1F4E2}`,
2162
- selector.type,
2163
- selector.key,
2164
- `root`,
2165
- atomKey,
2166
- `went`,
2167
- atomChange.oldValue,
2168
- `->`,
2169
- atomChange.newValue
2170
- );
2171
- const oldValue = recallState(selector, target);
2172
- const newValue = readOrComputeValue(selector, target);
2173
- store.logger.info(
2174
- `\u2728`,
2175
- selector.type,
2176
- selector.key,
2177
- `went`,
2178
- oldValue,
2179
- `->`,
2180
- newValue
2181
- );
2182
- selector.subject.next({ newValue, oldValue });
2183
- }
2184
- );
2185
- }
2186
- );
2187
- return dependencySubscriptions;
2188
- };
2189
-
2190
- // internal/src/subscribe/subscribe-to-state.ts
2191
- function subscribeToState(token, handleUpdate, key, store) {
2192
- function safelyHandleUpdate(update) {
2193
- if (store.operation.open) {
2194
- const unsubscribe2 = store.on.operationClose.subscribe(
2195
- `state subscription ${key}`,
2196
- () => {
2197
- unsubscribe2();
2198
- handleUpdate(update);
2199
- }
2200
- );
2201
- } else {
2202
- handleUpdate(update);
2203
- }
2204
- }
2205
- const state = withdraw(token, store);
2206
- store.logger.info(`\u{1F440}`, state.type, state.key, `Adding subscription "${key}"`);
2207
- const isSelector = state.type === `selector` || state.type === `readonly_selector`;
2208
- let dependencyUnsubFunctions = null;
2209
- let updateHandler = safelyHandleUpdate;
2210
- if (isSelector) {
2211
- dependencyUnsubFunctions = subscribeToRootAtoms(state, store);
2212
- updateHandler = (update) => {
2213
- if (dependencyUnsubFunctions) {
2214
- dependencyUnsubFunctions.length = 0;
2215
- dependencyUnsubFunctions.push(...subscribeToRootAtoms(state, store));
2216
- }
2217
- safelyHandleUpdate(update);
2218
- };
2219
- }
2220
- const mainUnsubFunction = state.subject.subscribe(key, updateHandler);
2221
- const unsubscribe = () => {
2222
- store.logger.info(
2223
- `\u{1F648}`,
2224
- state.type,
2225
- state.key,
2226
- `Removing subscription "${key}"`
2227
- );
2228
- mainUnsubFunction();
2229
- if (dependencyUnsubFunctions) {
2230
- for (const unsubFromDependency of dependencyUnsubFunctions) {
2231
- unsubFromDependency();
2232
- }
2233
- }
2234
- };
2235
- return unsubscribe;
2236
- }
2237
-
2238
- // internal/src/subscribe/subscribe-to-timeline.ts
2239
- var subscribeToTimeline = (token, handleUpdate, key, store) => {
2240
- const tl = withdraw(token, store);
2241
- store.logger.info(`\u{1F440}`, `timeline`, token.key, `Adding subscription "${key}"`);
2242
- const unsubscribe = tl.subject.subscribe(key, handleUpdate);
2243
- return () => {
2244
- store.logger.info(
2245
- `\u{1F648}`,
2246
- `timeline`,
2247
- token.key,
2248
- `Removing subscription "${key}" from timeline`
2249
- );
2250
- unsubscribe();
2251
- };
2252
- };
2253
-
2254
- // internal/src/subscribe/subscribe-to-transaction.ts
2255
- var subscribeToTransaction = (token, handleUpdate, key, store) => {
2256
- const tx = withdraw(token, store);
2257
- store.logger.info(
2258
- `\u{1F440}`,
2259
- `transaction`,
2260
- token.key,
2261
- `Adding subscription "${key}"`
2262
- );
2263
- const unsubscribe = tx.subject.subscribe(key, handleUpdate);
2264
- return () => {
2265
- store.logger.info(
2266
- `\u{1F648}`,
2267
- `transaction`,
2268
- token.key,
2269
- `Removing subscription "${key}"`
2270
- );
2271
- unsubscribe();
2272
- };
2273
- };
2274
-
2275
- // internal/src/mutable/tracker.ts
2276
- var Tracker = class {
2277
- initializeState(mutableState, store) {
2278
- var _a;
2279
- const latestUpdateStateKey = `*${mutableState.key}`;
2280
- store.atoms.delete(latestUpdateStateKey);
2281
- store.valueMap.delete(latestUpdateStateKey);
2282
- const familyMetaData = mutableState.family ? {
2283
- key: `*${mutableState.family.key}`,
2284
- subKey: mutableState.family.subKey
2285
- } : void 0;
2286
- const latestUpdateState = createRegularAtom(
2287
- {
2288
- key: latestUpdateStateKey,
2289
- default: null
2290
- },
2291
- familyMetaData,
2292
- store
2293
- );
2294
- if ((_a = store.parent) == null ? void 0 : _a.valueMap.has(latestUpdateStateKey)) {
2295
- const parentValue = store.parent.valueMap.get(latestUpdateStateKey);
2296
- store.valueMap.set(latestUpdateStateKey, parentValue);
2297
- }
2298
- return latestUpdateState;
2299
- }
2300
- observeCore(mutableState, latestUpdateState, target) {
2301
- const subscriptionKey = `tracker:${target.config.name}:${isChildStore(target) ? target.transactionMeta.update.key : `main`}:${mutableState.key}`;
2302
- const originalInnerValue = getFromStore(mutableState, target);
2303
- this.unsubscribeFromInnerValue = originalInnerValue.subscribe(
2304
- subscriptionKey,
2305
- (update) => {
2306
- setIntoStore(latestUpdateState, update, target);
2307
- }
2308
- );
2309
- this.unsubscribeFromState = subscribeToState(
2310
- mutableState,
2311
- (update) => {
2312
- if (update.newValue !== update.oldValue) {
2313
- this.unsubscribeFromInnerValue();
2314
- this.unsubscribeFromInnerValue = update.newValue.subscribe(
2315
- subscriptionKey,
2316
- (transceiverUpdate) => {
2317
- setIntoStore(latestUpdateState, transceiverUpdate, target);
2318
- }
2319
- );
2320
- }
2321
- },
2322
- subscriptionKey,
2323
- target
2324
- );
2325
- }
2326
- updateCore(mutableState, latestUpdateState, target) {
2327
- const subscriptionKey = `tracker:${target.config.name}:${isChildStore(target) ? target.transactionMeta.update.key : `main`}:${mutableState.key}`;
2328
- subscribeToState(
2329
- latestUpdateState,
2330
- ({ newValue, oldValue }) => {
2331
- const timelineId = target.timelineTopics.getRelatedKey(
2332
- latestUpdateState.key
2333
- );
2334
- if (timelineId) {
2335
- const timelineData = target.timelines.get(timelineId);
2336
- if (timelineData == null ? void 0 : timelineData.timeTraveling) {
2337
- const unsubscribe2 = subscribeToTimeline(
2338
- { key: timelineId, type: `timeline` },
2339
- (update) => {
2340
- unsubscribe2();
2341
- setIntoStore(
2342
- mutableState,
2343
- (transceiver) => {
2344
- if (update === `redo` && newValue) {
2345
- transceiver.do(newValue);
2346
- } else if (update === `undo` && oldValue) {
2347
- transceiver.undo(oldValue);
2348
- }
2349
- return transceiver;
2350
- },
2351
- target
2352
- );
2353
- },
2354
- subscriptionKey,
2355
- target
2356
- );
2357
- return;
2358
- }
2359
- }
2360
- const unsubscribe = target.on.operationClose.subscribe(
2361
- subscriptionKey,
2362
- () => {
2363
- unsubscribe();
2364
- const mutable = getFromStore(mutableState, target);
2365
- const updateNumber = newValue === null ? -1 : mutable.getUpdateNumber(newValue);
2366
- const eventOffset = updateNumber - mutable.cacheUpdateNumber;
2367
- if (newValue && eventOffset === 1) {
2368
- setIntoStore(
2369
- mutableState,
2370
- (transceiver) => (transceiver.do(newValue), transceiver),
2371
- target
2372
- );
2373
- } else {
2374
- target.logger.info(
2375
- `\u274C`,
2376
- `mutable_atom`,
2377
- mutableState.key,
2378
- `could not be updated. Expected update number ${mutable.cacheUpdateNumber + 1}, but got ${updateNumber}`
2379
- );
2380
- }
2381
- }
2382
- );
2383
- },
2384
- subscriptionKey,
2385
- target
2386
- );
2387
- }
2388
- constructor(mutableState, store) {
2389
- this.mutableState = mutableState;
2390
- const target = newest(store);
2391
- this.latestUpdateState = this.initializeState(mutableState, target);
2392
- this.observeCore(mutableState, this.latestUpdateState, target);
2393
- this.updateCore(mutableState, this.latestUpdateState, target);
2394
- target.trackers.set(mutableState.key, this);
2395
- this.dispose = () => {
2396
- this.unsubscribeFromInnerValue();
2397
- this.unsubscribeFromState();
2398
- target.trackers.delete(mutableState.key);
2399
- };
2400
- }
2401
- };
2402
-
2403
- // internal/src/mutable/create-mutable-atom.ts
2404
- function createMutableAtom(options, family, store) {
2405
- store.logger.info(
2406
- `\u{1F528}`,
2407
- `atom`,
2408
- options.key,
2409
- `creating in store "${store.config.name}"`
2410
- );
2411
- const target = newest(store);
2412
- const existing = target.atoms.get(options.key);
2413
- if (existing && existing.type === `mutable_atom`) {
2414
- store.logger.error(
2415
- `\u274C`,
2416
- `atom`,
2417
- options.key,
2418
- `Tried to create atom, but it already exists in the store.`
2419
- );
2420
- return deposit(existing);
2421
- }
2422
- const subject = new Subject();
2423
- const newAtom = __spreadProps(__spreadValues({}, options), {
2424
- type: `mutable_atom`,
2425
- install: (s) => {
2426
- s.logger.info(
2427
- `\u{1F6E0}\uFE0F`,
2428
- `atom`,
2429
- options.key,
2430
- `installing in store "${s.config.name}"`
2431
- );
2432
- return createMutableAtom(options, family, s);
2433
- },
2434
- subject
2435
- });
2436
- if (family) {
2437
- newAtom.family = family;
2438
- }
2439
- const initialValue = options.default();
2440
- target.atoms.set(newAtom.key, newAtom);
2441
- markAtomAsDefault(options.key, store);
2442
- cacheValue(options.key, initialValue, subject, target);
2443
- const token = deposit(newAtom);
2444
- if (options.effects) {
2445
- let effectIndex = 0;
2446
- const cleanupFunctions = [];
2447
- for (const effect of options.effects) {
2448
- const cleanup = effect({
2449
- setSelf: (next) => {
2450
- setIntoStore(token, next, store);
2451
- },
2452
- onSet: (handle) => subscribeToState(token, handle, `effect[${effectIndex}]`, store)
2453
- });
2454
- if (cleanup) {
2455
- cleanupFunctions.push(cleanup);
2456
- }
2457
- ++effectIndex;
2458
- }
2459
- newAtom.cleanup = () => {
2460
- for (const cleanup of cleanupFunctions) {
2461
- cleanup();
2462
- }
2463
- };
2464
- }
2465
- new Tracker(token, store);
2466
- if (!family) {
2467
- json.selectJson(token, options, store);
2468
- }
2469
- return token;
2470
- }
2471
- var FamilyTracker = class {
2472
- constructor(mutableAtoms, store) {
2473
- this.latestUpdateAtoms = createRegularAtomFamily(
2474
- {
2475
- key: `*${mutableAtoms.key}`,
2476
- default: null
2477
- },
2478
- store
2479
- );
2480
- this.mutableAtoms = mutableAtoms;
2481
- this.mutableAtoms.subject.subscribe(
2482
- `store=${store.config.name}::tracker-atom-family`,
2483
- (event) => {
2484
- if (event.token.family) {
2485
- const key = json.parseJson(event.token.family.subKey);
2486
- seekInStore(this.latestUpdateAtoms, key, store);
2487
- new Tracker(event.token, store);
2488
- }
2489
- }
2490
- );
2491
- this.latestUpdateAtoms.subject.subscribe(
2492
- `store=${store.config.name}::tracker-atom-family`,
2493
- (event) => {
2494
- if (event.token.family) {
2495
- const key = json.parseJson(event.token.family.subKey);
2496
- const mutableAtomToken = seekInStore(this.mutableAtoms, key, store);
2497
- if (mutableAtomToken) {
2498
- new Tracker(mutableAtomToken, store);
2499
- }
2500
- }
2501
- }
2502
- );
2503
- }
2504
- };
2505
-
2506
- // internal/src/mutable/create-mutable-atom-family.ts
2507
- function createMutableAtomFamily(options, store) {
2508
- const subject = new Subject();
2509
- const atomFamily = Object.assign(
2510
- (key) => {
2511
- const subKey = json.stringifyJson(key);
2512
- const family = { key: options.key, subKey };
2513
- const fullKey = `${options.key}(${subKey})`;
2514
- const target = newest(store);
2515
- const individualOptions = {
2516
- key: fullKey,
2517
- default: () => options.default(key),
2518
- toJson: options.toJson,
2519
- fromJson: options.fromJson,
2520
- mutable: true
2521
- };
2522
- if (options.effects) {
2523
- individualOptions.effects = options.effects(key);
2524
- }
2525
- const token = createMutableAtom(individualOptions, family, target);
2526
- subject.next({ type: `state_creation`, token });
2527
- return token;
2528
- },
2529
- {
2530
- key: options.key,
2531
- type: `mutable_atom_family`,
2532
- subject,
2533
- install: (s) => createMutableAtomFamily(options, s),
2534
- toJson: options.toJson,
2535
- fromJson: options.fromJson
2536
- }
2537
- );
2538
- store.families.set(options.key, atomFamily);
2539
- json.selectJsonFamily(atomFamily, options, store);
2540
- new FamilyTracker(atomFamily, store);
2541
- return atomFamily;
2542
- }
2543
-
2544
- // internal/src/mutable/get-json-family.ts
2545
- var getJsonFamily = (mutableAtomFamily, store) => {
2546
- const target = newest(store);
2547
- const key = `${mutableAtomFamily.key}:JSON`;
2548
- const jsonFamily = target.families.get(key);
2549
- return jsonFamily;
2550
- };
2551
-
2552
- // internal/src/mutable/get-json-token.ts
2553
- var getJsonToken = (mutableAtomToken, store) => {
2554
- if (mutableAtomToken.family) {
2555
- const target = newest(store);
2556
- const jsonFamilyKey = `${mutableAtomToken.family.key}:JSON`;
2557
- const jsonFamilyToken = {
2558
- key: jsonFamilyKey,
2559
- type: `selector_family`
2560
- };
2561
- const family = withdraw(jsonFamilyToken, target);
2562
- const subKey = JSON.parse(mutableAtomToken.family.subKey);
2563
- const jsonToken = findInStore(family, subKey, store);
2564
- return jsonToken;
2565
- }
2566
- const token = {
2567
- type: `selector`,
2568
- key: `${mutableAtomToken.key}:JSON`
2569
- };
2570
- return token;
2571
- };
2572
-
2573
- // internal/src/mutable/get-update-token.ts
2574
- var getUpdateToken = (mutableAtomToken) => {
2575
- const key = `*${mutableAtomToken.key}`;
2576
- const updateToken = { type: `atom`, key };
2577
- if (mutableAtomToken.family) {
2578
- updateToken.family = {
2579
- key: `*${mutableAtomToken.family.key}`,
2580
- subKey: mutableAtomToken.family.subKey
2581
- };
2582
- }
2583
- return updateToken;
2584
- };
2585
-
2586
- // internal/src/mutable/is-mutable.ts
2587
- function isMutable(atomOrTokenOrFamily) {
2588
- return atomOrTokenOrFamily.type === `mutable_atom` || atomOrTokenOrFamily.type === `mutable_atom_family`;
2589
- }
2590
-
2591
- // internal/src/mutable/transceiver.ts
2592
- function isTransceiver(value) {
2593
- return typeof value === `object` && value !== null && `do` in value && `undo` in value && `subscribe` in value;
2594
- }
2595
-
2596
- // internal/src/set-state/copy-mutable-if-needed.ts
2597
- function copyMutableIfNeeded(atom, origin, target) {
2598
- const originValue = origin.valueMap.get(atom.key);
2599
- const targetValue = target.valueMap.get(atom.key);
2600
- if (originValue === targetValue) {
2601
- if (originValue === void 0) {
2602
- return typeof atom.default === `function` ? atom.default() : atom.default;
2603
- }
2604
- origin.logger.info(`\u{1F4C3}`, `atom`, atom.key, `copying`);
2605
- const jsonValue = atom.toJson(originValue);
2606
- const copiedValue = atom.fromJson(jsonValue);
2607
- target.valueMap.set(atom.key, copiedValue);
2608
- new Tracker(atom, origin);
2609
- return copiedValue;
2610
- }
2611
- return targetValue;
2612
- }
2613
-
2614
- // internal/src/caching.ts
2615
- function cacheValue(key, value, subject, target) {
2616
- const currentValue = target.valueMap.get(key);
2617
- if (currentValue instanceof Future) {
2618
- const future = currentValue;
2619
- future.use(value);
2620
- }
2621
- if (value instanceof Promise) {
2622
- const future = new Future(value);
2623
- target.valueMap.set(key, future);
2624
- future.then((resolved) => {
2625
- cacheValue(key, resolved, subject, target);
2626
- subject.next({ newValue: resolved, oldValue: future });
2627
- }).catch((thrown) => {
2628
- target.logger.error(`\u{1F4A5}`, `state`, key, `rejected:`, thrown);
2629
- });
2630
- return future;
2631
- }
2632
- target.valueMap.set(key, value);
2633
- return value;
2634
- }
2635
- var readCachedValue = (token, target) => {
2636
- let value = target.valueMap.get(token.key);
2637
- if (token.type === `mutable_atom` && isChildStore(target)) {
2638
- const { parent } = target;
2639
- const copiedValue = copyMutableIfNeeded(token, parent, target);
2640
- value = copiedValue;
2641
- }
2642
- return value;
2643
- };
2644
- var evictCachedValue = (key, target) => {
2645
- var _a;
2646
- const currentValue = target.valueMap.get(key);
2647
- if (currentValue instanceof Future) {
2648
- const future = currentValue;
2649
- const selector = (_a = target.selectors.get(key)) != null ? _a : target.readonlySelectors.get(key);
2650
- if (selector) {
2651
- future.use(selector.get());
2652
- }
2653
- return;
2654
- }
2655
- if (target.operation.open) {
2656
- target.operation.prev.set(key, currentValue);
2657
- }
2658
- target.valueMap.delete(key);
2659
- target.logger.info(`\u{1F5D1}`, `state`, key, `evicted`);
2660
- };
2661
-
2662
- // internal/src/atom/is-default.ts
2663
- var isAtomDefault = (key, store) => {
2664
- const core = newest(store);
2665
- return core.atomsThatAreDefault.has(key);
2666
- };
2667
- var markAtomAsDefault = (key, store) => {
2668
- const core = newest(store);
2669
- core.atomsThatAreDefault = new Set(core.atomsThatAreDefault).add(key);
2670
- };
2671
- var markAtomAsNotDefault = (key, store) => {
2672
- const core = newest(store);
2673
- core.atomsThatAreDefault = new Set(newest(store).atomsThatAreDefault);
2674
- core.atomsThatAreDefault.delete(key);
2675
- };
2676
-
2677
- // internal/src/atom/create-regular-atom.ts
2678
- function createRegularAtom(options, family, store) {
2679
- store.logger.info(
2680
- `\u{1F528}`,
2681
- `atom`,
2682
- options.key,
2683
- `creating in store "${store.config.name}"`
2684
- );
2685
- const target = newest(store);
2686
- const existing = target.atoms.get(options.key);
2687
- if (existing && existing.type === `atom`) {
2688
- store.logger.error(
2689
- `\u274C`,
2690
- `atom`,
2691
- options.key,
2692
- `Tried to create atom, but it already exists in the store.`
2693
- );
2694
- return deposit(existing);
2695
- }
2696
- const subject = new Subject();
2697
- const newAtom = __spreadProps(__spreadValues({}, options), {
2698
- type: `atom`,
2699
- install: (s) => {
2700
- s.logger.info(
2701
- `\u{1F6E0}\uFE0F`,
2702
- `atom`,
2703
- options.key,
2704
- `installing in store "${s.config.name}"`
2705
- );
2706
- return createRegularAtom(options, family, s);
2707
- },
2708
- subject
2709
- });
2710
- if (family) {
2711
- newAtom.family = family;
2712
- }
2713
- let initialValue = options.default;
2714
- if (options.default instanceof Function) {
2715
- initialValue = options.default();
2716
- }
2717
- target.atoms.set(newAtom.key, newAtom);
2718
- markAtomAsDefault(options.key, store);
2719
- cacheValue(options.key, initialValue, subject, target);
2720
- const token = deposit(newAtom);
2721
- if (options.effects) {
2722
- let effectIndex = 0;
2723
- const cleanupFunctions = [];
2724
- for (const effect of options.effects) {
2725
- const cleanup = effect({
2726
- setSelf: (next) => {
2727
- setIntoStore(token, next, store);
2728
- },
2729
- onSet: (handle) => subscribeToState(token, handle, `effect[${effectIndex}]`, store)
2730
- });
2731
- if (cleanup) {
2732
- cleanupFunctions.push(cleanup);
2733
- }
2734
- ++effectIndex;
2735
- }
2736
- newAtom.cleanup = () => {
2737
- for (const cleanup of cleanupFunctions) {
2738
- cleanup();
2739
- }
2740
- };
2741
- }
2742
- return token;
2743
- }
2744
-
2745
- // internal/src/atom/create-standalone-atom.ts
2746
- function createStandaloneAtom(options, store) {
2747
- const isMutable2 = `mutable` in options;
2748
- if (isMutable2) {
2749
- const state2 = createMutableAtom(options, void 0, store);
2750
- store.on.atomCreation.next(state2);
2751
- return state2;
2752
- }
2753
- const state = createRegularAtom(options, void 0, store);
2754
- store.on.atomCreation.next(state);
2755
- return state;
2756
- }
2757
-
2758
- // internal/src/atom/dispose-atom.ts
2759
- function disposeAtom(atomToken, store) {
2760
- var _a, _b;
2761
- const target = newest(store);
2762
- const { key } = atomToken;
2763
- const atom = target.atoms.get(key);
2764
- if (!atom) {
2765
- store.logger.error(
2766
- `\u274C`,
2767
- `atom`,
2768
- key,
2769
- `Tried to dispose atom, but it does not exist in the store.`
2770
- );
2771
- } else if (!atom.family) {
2772
- store.logger.error(`\u274C`, `atom`, key, `Standalone atoms cannot be disposed.`);
2773
- } else {
2774
- (_a = atom.cleanup) == null ? void 0 : _a.call(atom);
2775
- const lastValue = store.valueMap.get(atom.key);
2776
- const family = withdraw({ key: atom.family.key, type: `atom_family` }, store);
2777
- family.subject.next({
2778
- type: `state_disposal`,
2779
- token: atomToken,
2780
- value: lastValue
2781
- });
2782
- const molecule = target.molecules.get(atom.family.subKey);
2783
- if (molecule) {
2784
- molecule.tokens.delete(key);
2785
- }
2786
- target.atoms.delete(key);
2787
- target.valueMap.delete(key);
2788
- const selectorKeys = target.selectorAtoms.getRelatedKeys(key);
2789
- if (selectorKeys) {
2790
- for (const selectorKey of selectorKeys) {
2791
- const token = (_b = target.selectors.get(selectorKey)) != null ? _b : target.readonlySelectors.get(selectorKey);
2792
- if (token) {
2793
- disposeSelector(token, store);
2794
- }
2795
- }
2796
- }
2797
- target.selectorAtoms.delete(key);
2798
- target.atomsThatAreDefault.delete(key);
2799
- target.timelineTopics.delete(key);
2800
- if (atomToken.type === `mutable_atom`) {
2801
- const updateToken = getUpdateToken(atomToken);
2802
- disposeAtom(updateToken, store);
2803
- store.trackers.delete(key);
2804
- }
2805
- store.logger.info(`\u{1F525}`, `atom`, key, `deleted`);
2806
- if (isChildStore(target) && target.transactionMeta.phase === `building`) {
2807
- target.transactionMeta.update.updates.push({
2808
- type: `state_disposal`,
2809
- token: atomToken
2810
- });
2811
- } else {
2812
- store.on.atomDisposal.next(atomToken);
2813
- }
2814
- }
2815
- }
2816
- function createTimeline(options, store, data) {
2817
- var _a;
2818
- const tl = __spreadProps(__spreadValues({
2819
- type: `timeline`,
2820
- key: options.key,
2821
- at: 0,
2822
- timeTraveling: null,
2823
- selectorTime: null,
2824
- transactionKey: null
2825
- }, data), {
2826
- history: (_a = data == null ? void 0 : data.history.map((update) => __spreadValues({}, update))) != null ? _a : [],
2827
- install: (s) => createTimeline(options, s, tl),
2828
- subject: new Subject(),
2829
- subscriptions: /* @__PURE__ */ new Map()
2830
- });
2831
- if (options.shouldCapture) {
2832
- tl.shouldCapture = options.shouldCapture;
2833
- }
2834
- const timelineKey = options.key;
2835
- const target = newest(store);
2836
- for (const initialTopic of options.scope) {
2837
- switch (initialTopic.type) {
2838
- case `atom`:
2839
- case `mutable_atom`:
2840
- {
2841
- const atomToken = initialTopic;
2842
- const atomKey = atomToken.key;
2843
- let existingTimelineKey = target.timelineTopics.getRelatedKey(atomKey);
2844
- if (`family` in atomToken) {
2845
- const familyKey = atomToken.family.key;
2846
- existingTimelineKey = target.timelineTopics.getRelatedKey(familyKey);
2847
- if (existingTimelineKey) {
2848
- store.logger.error(
2849
- `\u274C`,
2850
- `timeline`,
2851
- options.key,
2852
- `Failed to add atom "${atomKey}" because its family "${familyKey}" already belongs to timeline "${existingTimelineKey}"`
2853
- );
2854
- continue;
2855
- }
2856
- }
2857
- if (existingTimelineKey) {
2858
- store.logger.error(
2859
- `\u274C`,
2860
- `timeline`,
2861
- options.key,
2862
- `Failed to add atom "${atomKey}" because it already belongs to timeline "${existingTimelineKey}"`
2863
- );
2864
- continue;
2865
- }
2866
- addAtomToTimeline(atomToken, tl, store);
2867
- }
2868
- break;
2869
- case `atom_family`:
2870
- case `mutable_atom_family`:
2871
- {
2872
- const familyToken = initialTopic;
2873
- const familyKey = familyToken.key;
2874
- const existingTimelineKey = target.timelineTopics.getRelatedKey(familyKey);
2875
- if (existingTimelineKey) {
2876
- store.logger.error(
2877
- `\u274C`,
2878
- `timeline`,
2879
- options.key,
2880
- `Failed to add atom family "${familyKey}" because it already belongs to timeline "${existingTimelineKey}"`
2881
- );
2882
- continue;
2883
- }
2884
- addAtomFamilyToTimeline(familyToken, tl, store);
2885
- }
2886
- break;
2887
- case `molecule_family`:
2888
- {
2889
- const familyToken = initialTopic;
2890
- const familyKey = familyToken.key;
2891
- const existingTimelineKey = target.timelineTopics.getRelatedKey(familyKey);
2892
- if (existingTimelineKey) {
2893
- store.logger.error(
2894
- `\u274C`,
2895
- `timeline`,
2896
- options.key,
2897
- `Failed to add molecule family "${familyKey}" because it already belongs to timeline "${existingTimelineKey}"`
2898
- );
2899
- continue;
2900
- }
2901
- addMoleculeFamilyToTimeline(familyToken, tl, store);
2902
- }
2903
- break;
2904
- }
2905
- }
2906
- store.timelines.set(options.key, tl);
2907
- const token = {
2908
- key: timelineKey,
2909
- type: `timeline`
2910
- };
2911
- store.on.timelineCreation.next(token);
2912
- return token;
2913
- }
2914
- function addAtomToTimeline(atomToken, tl, store) {
2915
- let maybeAtom = withdraw(atomToken, store);
2916
- if (maybeAtom.type === `mutable_atom`) {
2917
- const updateToken = getUpdateToken(maybeAtom);
2918
- maybeAtom = withdraw(updateToken, store);
2919
- }
2920
- const atom = maybeAtom;
2921
- store.timelineTopics.set(
2922
- { topicKey: atom.key, timelineKey: tl.key },
2923
- { topicType: `atom` }
2924
- );
2925
- tl.subscriptions.set(
2926
- atom.key,
2927
- atom.subject.subscribe(`timeline`, (update) => {
2928
- var _a, _b, _c, _d, _e;
2929
- const target = newest(store);
2930
- const currentSelectorKey = store.operation.open && store.operation.token.type === `selector` ? store.operation.token.key : null;
2931
- const currentSelectorTime = store.operation.open && store.operation.token.type === `selector` ? store.operation.time : null;
2932
- const txUpdateInProgress = (_a = target.on.transactionApplying.state) == null ? void 0 : _a.update;
2933
- store.logger.info(
2934
- `\u23F3`,
2935
- `timeline`,
2936
- tl.key,
2937
- `atom`,
2938
- atomToken.key,
2939
- `went`,
2940
- update.oldValue,
2941
- `->`,
2942
- update.newValue,
2943
- txUpdateInProgress ? `in transaction "${txUpdateInProgress.key}"` : currentSelectorKey ? `in selector "${currentSelectorKey}"` : ``
2944
- );
2945
- if (tl.timeTraveling === null) {
2946
- if (txUpdateInProgress) {
2947
- joinTransaction(tl, txUpdateInProgress, store);
2948
- } else if (currentSelectorKey && currentSelectorTime) {
2949
- let latestUpdate = tl.history.at(-1);
2950
- if (currentSelectorTime !== tl.selectorTime) {
2951
- latestUpdate = {
2952
- type: `selector_update`,
2953
- timestamp: currentSelectorTime,
2954
- key: currentSelectorKey,
2955
- atomUpdates: []
2956
- };
2957
- latestUpdate.atomUpdates.push(__spreadValues({
2958
- key: atom.key,
2959
- type: `atom_update`
2960
- }, update));
2961
- if (tl.at !== tl.history.length) {
2962
- tl.history.splice(tl.at);
2963
- }
2964
- tl.history.push(latestUpdate);
2965
- store.logger.info(
2966
- `\u231B`,
2967
- `timeline`,
2968
- tl.key,
2969
- `got a selector_update "${currentSelectorKey}" with`,
2970
- latestUpdate.atomUpdates.map((atomUpdate) => atomUpdate.key)
2971
- );
2972
- tl.at = tl.history.length;
2973
- tl.selectorTime = currentSelectorTime;
2974
- } else {
2975
- if ((latestUpdate == null ? void 0 : latestUpdate.type) === `selector_update`) {
2976
- latestUpdate.atomUpdates.push(__spreadValues({
2977
- key: atom.key,
2978
- type: `atom_update`
2979
- }, update));
2980
- store.logger.info(
2981
- `\u231B`,
2982
- `timeline`,
2983
- tl.key,
2984
- `set selector_update "${currentSelectorKey}" to`,
2985
- latestUpdate == null ? void 0 : latestUpdate.atomUpdates.map((atomUpdate) => atomUpdate.key)
2986
- );
2987
- }
2988
- }
2989
- if (latestUpdate) {
2990
- const willCaptureSelectorUpdate = (_c = (_b = tl.shouldCapture) == null ? void 0 : _b.call(tl, latestUpdate, tl)) != null ? _c : true;
2991
- if (willCaptureSelectorUpdate) {
2992
- tl.subject.next(latestUpdate);
2993
- } else {
2994
- tl.history.pop();
2995
- tl.at = tl.history.length;
2996
- }
2997
- }
2998
- } else {
2999
- const timestamp = Date.now();
3000
- tl.selectorTime = null;
3001
- if (tl.at !== tl.history.length) {
3002
- tl.history.splice(tl.at);
3003
- }
3004
- const atomUpdate = {
3005
- type: `atom_update`,
3006
- timestamp,
3007
- key: atom.key,
3008
- oldValue: update.oldValue,
3009
- newValue: update.newValue
3010
- };
3011
- if (atom.family) {
3012
- atomUpdate.family = atom.family;
3013
- }
3014
- const willCapture = (_e = (_d = tl.shouldCapture) == null ? void 0 : _d.call(tl, atomUpdate, tl)) != null ? _e : true;
3015
- store.logger.info(
3016
- `\u231B`,
3017
- `timeline`,
3018
- tl.key,
3019
- `got an atom_update to "${atom.key}"`
3020
- );
3021
- if (willCapture) {
3022
- tl.history.push(atomUpdate);
3023
- tl.at = tl.history.length;
3024
- tl.subject.next(atomUpdate);
3025
- }
3026
- }
3027
- }
3028
- })
3029
- );
3030
- }
3031
- function addAtomFamilyToTimeline(atomFamilyToken, tl, store) {
3032
- var _a;
3033
- const family = withdraw(atomFamilyToken, store);
3034
- store.timelineTopics.set(
3035
- { topicKey: family.key, timelineKey: tl.key },
3036
- { topicType: `atom_family` }
3037
- );
3038
- tl.subscriptions.set(
3039
- family.key,
3040
- family.subject.subscribe(`timeline`, (creationOrDisposal) => {
3041
- handleStateLifecycleEvent(creationOrDisposal, tl, store);
3042
- })
3043
- );
3044
- for (const atom of store.atoms.values()) {
3045
- if (((_a = atom.family) == null ? void 0 : _a.key) === family.key) {
3046
- addAtomToTimeline(atom, tl, store);
3047
- }
3048
- }
3049
- }
3050
- function addMoleculeFamilyToTimeline(familyToken, tl, store) {
3051
- store.timelineTopics.set(
3052
- { topicKey: familyToken.key, timelineKey: tl.key },
3053
- { topicType: `molecule_family` }
3054
- );
3055
- const family = store.moleculeFamilies.get(familyToken.key);
3056
- if (family) {
3057
- tl.subscriptions.set(
3058
- familyToken.key,
3059
- family.subject.subscribe(`timeline:${tl.key}`, (creationOrDisposal) => {
3060
- var _a, _b, _c, _d;
3061
- store.logger.info(
3062
- `\u{1F41E}`,
3063
- `timeline`,
3064
- tl.key,
3065
- `got a molecule creation or disposal`,
3066
- creationOrDisposal
3067
- );
3068
- switch (creationOrDisposal.type) {
3069
- case `molecule_creation`:
3070
- {
3071
- store.timelineTopics.set(
3072
- {
3073
- topicKey: creationOrDisposal.token.key,
3074
- timelineKey: tl.key
3075
- },
3076
- { topicType: `molecule` }
3077
- );
3078
- const txUpdateInProgress = (_a = newest(store).on.transactionApplying.state) == null ? void 0 : _a.update;
3079
- if (txUpdateInProgress) {
3080
- joinTransaction(tl, txUpdateInProgress, store);
3081
- } else if (tl.timeTraveling === null) {
3082
- const event = Object.assign(creationOrDisposal, {
3083
- timestamp: Date.now()
3084
- });
3085
- tl.history.push(event);
3086
- tl.at = tl.history.length;
3087
- tl.subject.next(event);
3088
- }
3089
- const molecule = withdraw(creationOrDisposal.token, store);
3090
- for (const token of molecule.tokens.values()) {
3091
- switch (token.type) {
3092
- case `atom`:
3093
- case `mutable_atom`:
3094
- addAtomToTimeline(token, tl, store);
3095
- break;
3096
- }
3097
- }
3098
- tl.subscriptions.set(
3099
- molecule.key,
3100
- molecule.subject.subscribe(
3101
- `timeline:${tl.key}`,
3102
- (stateCreationOrDisposal) => {
3103
- handleStateLifecycleEvent(stateCreationOrDisposal, tl, store);
3104
- }
3105
- )
3106
- );
3107
- }
3108
- break;
3109
- case `molecule_disposal`:
3110
- {
3111
- const txUpdateInProgress = (_b = newest(store).on.transactionApplying.state) == null ? void 0 : _b.update;
3112
- if (txUpdateInProgress) {
3113
- joinTransaction(tl, txUpdateInProgress, store);
3114
- } else if (tl.timeTraveling === null) {
3115
- const event = Object.assign(creationOrDisposal, {
3116
- timestamp: Date.now()
3117
- });
3118
- tl.history.push(event);
3119
- tl.at = tl.history.length;
3120
- tl.subject.next(event);
3121
- }
3122
- const moleculeKey = creationOrDisposal.token.key;
3123
- (_c = tl.subscriptions.get(moleculeKey)) == null ? void 0 : _c();
3124
- tl.subscriptions.delete(moleculeKey);
3125
- for (const [familyKey] of creationOrDisposal.values) {
3126
- const stateKey = `${familyKey}(${json.stringifyJson(moleculeKey)})`;
3127
- (_d = tl.subscriptions.get(stateKey)) == null ? void 0 : _d();
3128
- tl.subscriptions.delete(stateKey);
3129
- store.timelineTopics.delete(stateKey);
3130
- }
3131
- }
3132
- break;
3133
- }
3134
- })
3135
- );
3136
- }
3137
- }
3138
- function joinTransaction(tl, txUpdateInProgress, store) {
3139
- const currentTxKey = txUpdateInProgress.key;
3140
- const currentTxInstanceId = txUpdateInProgress.id;
3141
- const currentTxToken = {
3142
- key: currentTxKey,
3143
- type: `transaction`
3144
- };
3145
- const currentTransaction = withdraw(currentTxToken, store);
3146
- if (currentTxKey && tl.transactionKey === null) {
3147
- tl.transactionKey = currentTxKey;
3148
- const unsubscribe = currentTransaction.subject.subscribe(
3149
- `timeline:${tl.key}`,
3150
- (transactionUpdate) => {
3151
- var _a, _b;
3152
- unsubscribe();
3153
- tl.transactionKey = null;
3154
- if (tl.timeTraveling === null && currentTxInstanceId) {
3155
- if (tl.at !== tl.history.length) {
3156
- tl.history.splice(tl.at);
3157
- }
3158
- const timelineTopics = store.timelineTopics.getRelatedKeys(tl.key);
3159
- const updates = filterTransactionUpdates(
3160
- transactionUpdate.updates,
3161
- timelineTopics
3162
- );
3163
- const timelineTransactionUpdate = __spreadProps(__spreadValues({
3164
- timestamp: Date.now()
3165
- }, transactionUpdate), {
3166
- updates
3167
- });
3168
- const willCapture = (_b = (_a = tl.shouldCapture) == null ? void 0 : _a.call(tl, timelineTransactionUpdate, tl)) != null ? _b : true;
3169
- if (willCapture) {
3170
- tl.history.push(timelineTransactionUpdate);
3171
- tl.at = tl.history.length;
3172
- tl.subject.next(timelineTransactionUpdate);
3173
- }
3174
- }
3175
- }
3176
- );
3177
- }
3178
- }
3179
- function filterTransactionUpdates(updates, timelineTopics) {
3180
- return updates.filter((updateFromTx) => {
3181
- if (updateFromTx.type === `transaction_update`) {
3182
- return true;
3183
- }
3184
- let key;
3185
- switch (updateFromTx.type) {
3186
- case `state_creation`:
3187
- case `state_disposal`:
3188
- case `molecule_creation`:
3189
- case `molecule_disposal`:
3190
- key = updateFromTx.token.key;
3191
- break;
3192
- default:
3193
- key = updateFromTx.key;
3194
- break;
3195
- }
3196
- return timelineTopics.has(key);
3197
- }).map((updateFromTx) => {
3198
- if (`updates` in updateFromTx) {
3199
- return __spreadProps(__spreadValues({}, updateFromTx), {
3200
- updates: filterTransactionUpdates(
3201
- updateFromTx.updates,
3202
- timelineTopics
3203
- )
3204
- });
3205
- }
3206
- return updateFromTx;
3207
- });
3208
- }
3209
- function handleStateLifecycleEvent(event, tl, store) {
3210
- var _a, _b;
3211
- const timestamp = Date.now();
3212
- const timelineEvent = Object.assign(event, {
3213
- timestamp
3214
- });
3215
- if (!tl.timeTraveling) {
3216
- const txUpdateInProgress = (_a = newest(store).on.transactionApplying.state) == null ? void 0 : _a.update;
3217
- if (txUpdateInProgress) {
3218
- joinTransaction(tl, txUpdateInProgress, store);
3219
- } else {
3220
- tl.history.push(timelineEvent);
3221
- tl.at = tl.history.length;
3222
- tl.subject.next(timelineEvent);
3223
- }
3224
- }
3225
- switch (event.type) {
3226
- case `state_creation`:
3227
- addAtomToTimeline(event.token, tl, store);
3228
- break;
3229
- case `state_disposal`:
3230
- (_b = tl.subscriptions.get(event.token.key)) == null ? void 0 : _b();
3231
- tl.subscriptions.delete(event.token.key);
3232
- break;
3233
- }
3234
- }
3235
-
3236
- // internal/src/timeline/time-travel.ts
3237
- var timeTravel = (action, token, store) => {
3238
- store.logger.info(
3239
- action === `redo` ? `\u23E9` : `\u23EA`,
3240
- `timeline`,
3241
- token.key,
3242
- action
3243
- );
3244
- const timelineData = store.timelines.get(token.key);
3245
- if (!timelineData) {
3246
- store.logger.error(
3247
- `\u{1F41E}`,
3248
- `timeline`,
3249
- token.key,
3250
- `Failed to ${action}. This timeline has not been initialized.`
3251
- );
3252
- return;
3253
- }
3254
- if (action === `redo` && timelineData.at === timelineData.history.length || action === `undo` && timelineData.at === 0) {
3255
- store.logger.warn(
3256
- `\u{1F481}`,
3257
- `timeline`,
3258
- token.key,
3259
- `Failed to ${action} at the ${action === `redo` ? `end` : `beginning`} of timeline "${token.key}". There is nothing to ${action}.`
3260
- );
3261
- return;
3262
- }
3263
- timelineData.timeTraveling = action === `redo` ? `into_future` : `into_past`;
3264
- if (action === `undo`) {
3265
- --timelineData.at;
3266
- }
3267
- const update = timelineData.history[timelineData.at];
3268
- const applying = action === `redo` ? `newValue` : `oldValue`;
3269
- switch (update.type) {
3270
- case `atom_update`: {
3271
- ingestAtomUpdate(applying, update, store);
3272
- break;
3273
- }
3274
- case `selector_update`: {
3275
- ingestSelectorUpdate(applying, update, store);
3276
- break;
3277
- }
3278
- case `transaction_update`: {
3279
- ingestTransactionUpdate(applying, update, store);
3280
- break;
3281
- }
3282
- case `state_creation`: {
3283
- ingestCreationEvent(update, applying, store);
3284
- break;
3285
- }
3286
- case `state_disposal`: {
3287
- ingestDisposalEvent(update, applying, store);
3288
- break;
3289
- }
3290
- case `molecule_creation`: {
3291
- ingestMoleculeCreationEvent(update, applying, store);
3292
- break;
3293
- }
3294
- case `molecule_disposal`: {
3295
- ingestMoleculeDisposalEvent(update, applying, store);
3296
- break;
3297
- }
3298
- }
3299
- if (action === `redo`) {
3300
- ++timelineData.at;
3301
- }
3302
- timelineData.subject.next(action);
3303
- timelineData.timeTraveling = null;
3304
- store.logger.info(
3305
- `\u23F9\uFE0F`,
3306
- `timeline`,
3307
- token.key,
3308
- `"${token.key}" is now at ${timelineData.at} / ${timelineData.history.length}`
3309
- );
3310
- };
3311
-
3312
- exports.FamilyTracker = FamilyTracker;
3313
- exports.Future = Future;
3314
- exports.IMPLICIT = IMPLICIT;
3315
- exports.LazyMap = LazyMap;
3316
- exports.Molecule = Molecule;
3317
- exports.NotFoundError = NotFoundError;
3318
- exports.StatefulSubject = StatefulSubject;
3319
- exports.Store = Store;
3320
- exports.Subject = Subject;
3321
- exports.TRANSACTION_PHASES = TRANSACTION_PHASES;
3322
- exports.Tracker = Tracker;
3323
- exports.abortTransaction = abortTransaction;
3324
- exports.actUponStore = actUponStore;
3325
- exports.applyTransaction = applyTransaction;
3326
- exports.arbitrary = arbitrary;
3327
- exports.assignTransactionToContinuity = assignTransactionToContinuity;
3328
- exports.become = become;
3329
- exports.buildTransaction = buildTransaction;
3330
- exports.cacheValue = cacheValue;
3331
- exports.clearStore = clearStore;
3332
- exports.closeOperation = closeOperation;
3333
- exports.createAtomFamily = createAtomFamily;
3334
- exports.createMoleculeFamily = createMoleculeFamily;
3335
- exports.createMutableAtom = createMutableAtom;
3336
- exports.createMutableAtomFamily = createMutableAtomFamily;
3337
- exports.createReadonlySelector = createReadonlySelector;
3338
- exports.createReadonlySelectorFamily = createReadonlySelectorFamily;
3339
- exports.createRegularAtom = createRegularAtom;
3340
- exports.createRegularAtomFamily = createRegularAtomFamily;
3341
- exports.createSelectorFamily = createSelectorFamily;
3342
- exports.createStandaloneAtom = createStandaloneAtom;
3343
- exports.createStandaloneSelector = createStandaloneSelector;
3344
- exports.createTimeline = createTimeline;
3345
- exports.createTransaction = createTransaction;
3346
- exports.createWritableSelector = createWritableSelector;
3347
- exports.deposit = deposit;
3348
- exports.disposeAtom = disposeAtom;
3349
- exports.disposeFromStore = disposeFromStore;
3350
- exports.disposeMolecule = disposeMolecule;
3351
- exports.disposeSelector = disposeSelector;
3352
- exports.eldest = eldest;
3353
- exports.evictCachedValue = evictCachedValue;
3354
- exports.findInStore = findInStore;
3355
- exports.getContinuityKey = getContinuityKey;
3356
- exports.getEnvironmentData = getEnvironmentData;
3357
- exports.getEpochNumberOfAction = getEpochNumberOfAction;
3358
- exports.getEpochNumberOfContinuity = getEpochNumberOfContinuity;
3359
- exports.getFromStore = getFromStore;
3360
- exports.getJsonFamily = getJsonFamily;
3361
- exports.getJsonToken = getJsonToken;
3362
- exports.getSelectorDependencyKeys = getSelectorDependencyKeys;
3363
- exports.getUpdateToken = getUpdateToken;
3364
- exports.growMoleculeInStore = growMoleculeInStore;
3365
- exports.ingestAtomUpdate = ingestAtomUpdate;
3366
- exports.ingestCreationEvent = ingestCreationEvent;
3367
- exports.ingestDisposalEvent = ingestDisposalEvent;
3368
- exports.ingestMoleculeCreationEvent = ingestMoleculeCreationEvent;
3369
- exports.ingestMoleculeDisposalEvent = ingestMoleculeDisposalEvent;
3370
- exports.ingestSelectorUpdate = ingestSelectorUpdate;
3371
- exports.ingestTransactionUpdate = ingestTransactionUpdate;
3372
- exports.initFamilyMemberInStore = initFamilyMemberInStore;
3373
- exports.isAtomDefault = isAtomDefault;
3374
- exports.isAtomKey = isAtomKey;
3375
- exports.isChildStore = isChildStore;
3376
- exports.isDone = isDone;
3377
- exports.isMutable = isMutable;
3378
- exports.isReadonlySelectorKey = isReadonlySelectorKey;
3379
- exports.isRootStore = isRootStore;
3380
- exports.isSelectorKey = isSelectorKey;
3381
- exports.isStateKey = isStateKey;
3382
- exports.isTransceiver = isTransceiver;
3383
- exports.makeMoleculeInStore = makeMoleculeInStore;
3384
- exports.markAtomAsDefault = markAtomAsDefault;
3385
- exports.markAtomAsNotDefault = markAtomAsNotDefault;
3386
- exports.markDone = markDone;
3387
- exports.newest = newest;
3388
- exports.openOperation = openOperation;
3389
- exports.readCachedValue = readCachedValue;
3390
- exports.readOrComputeValue = readOrComputeValue;
3391
- exports.registerSelector = registerSelector;
3392
- exports.seekInStore = seekInStore;
3393
- exports.setAtomOrSelector = setAtomOrSelector;
3394
- exports.setEpochNumberOfAction = setEpochNumberOfAction;
3395
- exports.setEpochNumberOfContinuity = setEpochNumberOfContinuity;
3396
- exports.setIntoStore = setIntoStore;
3397
- exports.subscribeToRootAtoms = subscribeToRootAtoms;
3398
- exports.subscribeToState = subscribeToState;
3399
- exports.subscribeToTimeline = subscribeToTimeline;
3400
- exports.subscribeToTransaction = subscribeToTransaction;
3401
- exports.timeTravel = timeTravel;
3402
- exports.traceAllSelectorAtoms = traceAllSelectorAtoms;
3403
- exports.traceSelectorAtoms = traceSelectorAtoms;
3404
- exports.updateSelectorAtoms = updateSelectorAtoms;
3405
- exports.withdraw = withdraw;