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