atom.io 0.14.4 → 0.14.5

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