flightdeck 0.2.27 → 0.2.29

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.
@@ -1,4780 +0,0 @@
1
- import { spawn, execSync } from 'node:child_process';
2
- import { createServer } from 'node:http';
3
- import { homedir } from 'node:os';
4
- import { resolve } from 'node:path';
5
- import { inspect } from 'node:util';
6
- import { CronJob } from 'cron';
7
- import { FilesystemStorage } from 'safedeposit';
8
- import { z } from 'zod';
9
- import { createEnv } from '@t3-oss/env-core';
10
-
11
- // src/flightdeck.lib.ts
12
-
13
- // ../atom.io/internal/src/arbitrary.ts
14
- function arbitrary(random = Math.random) {
15
- return random().toString(36).slice(2);
16
- }
17
-
18
- // ../atom.io/internal/src/future.ts
19
- var Future = class extends Promise {
20
- fate;
21
- resolve;
22
- reject;
23
- done = false;
24
- constructor(executor) {
25
- let superResolve;
26
- let superReject;
27
- super((resolve2, reject) => {
28
- superResolve = resolve2;
29
- superReject = reject;
30
- });
31
- this.resolve = superResolve;
32
- this.reject = superReject;
33
- this.use(executor instanceof Promise ? executor : new Promise(executor));
34
- }
35
- pass(promise, value) {
36
- if (promise === this.fate) {
37
- this.resolve(value);
38
- this.done = true;
39
- }
40
- }
41
- fail(promise, reason) {
42
- if (promise === this.fate) {
43
- this.reject(reason);
44
- this.done = true;
45
- }
46
- }
47
- use(value) {
48
- if (value instanceof Promise) {
49
- const promise = value;
50
- this.fate = promise;
51
- promise.then(
52
- (resolved) => {
53
- this.pass(promise, resolved);
54
- },
55
- (reason) => {
56
- this.fail(promise, reason);
57
- }
58
- );
59
- } else {
60
- this.resolve(value);
61
- this.fate = void 0;
62
- }
63
- }
64
- };
65
-
66
- // ../atom.io/json/src/entries.ts
67
- function fromEntries(entries) {
68
- return Object.fromEntries(entries);
69
- }
70
- function toEntries(obj) {
71
- return Object.entries(obj);
72
- }
73
-
74
- // ../atom.io/json/src/select-json.ts
75
- var selectJson = (atom2, transform, store = IMPLICIT.STORE) => {
76
- return createStandaloneSelector(store, {
77
- key: `${atom2.key}:JSON`,
78
- get: ({ get }) => transform.toJson(get(atom2)),
79
- set: ({ set }, newValue) => {
80
- set(atom2, transform.fromJson(newValue));
81
- }
82
- });
83
- };
84
-
85
- // ../atom.io/internal/src/lineage.ts
86
- function newest(scion) {
87
- while (scion.child !== null) {
88
- scion = scion.child;
89
- }
90
- return scion;
91
- }
92
-
93
- // ../atom.io/internal/src/subject.ts
94
- var Subject = class {
95
- Subscriber;
96
- subscribers = /* @__PURE__ */ new Map();
97
- subscribe(key, subscriber) {
98
- this.subscribers.set(key, subscriber);
99
- const unsubscribe = () => {
100
- this.unsubscribe(key);
101
- };
102
- return unsubscribe;
103
- }
104
- unsubscribe(key) {
105
- this.subscribers.delete(key);
106
- }
107
- next(value) {
108
- const subscribers = this.subscribers.values();
109
- for (const subscriber of subscribers) {
110
- subscriber(value);
111
- }
112
- }
113
- };
114
- var StatefulSubject = class extends Subject {
115
- state;
116
- constructor(initialState) {
117
- super();
118
- this.state = initialState;
119
- }
120
- next(value) {
121
- this.state = value;
122
- super.next(value);
123
- }
124
- };
125
-
126
- // ../atom.io/internal/src/families/create-regular-atom-family.ts
127
- function createRegularAtomFamily(store, options, internalRoles) {
128
- const familyToken = {
129
- key: options.key,
130
- type: `atom_family`
131
- };
132
- const existing = store.families.get(options.key);
133
- if (existing) {
134
- store.logger.error(
135
- `\u2757`,
136
- `atom_family`,
137
- options.key,
138
- `Overwriting an existing ${prettyPrintTokenType(
139
- existing
140
- )} "${existing.key}" in store "${store.config.name}". You can safely ignore this warning if it is due to hot module replacement.`
141
- );
142
- }
143
- const subject = new Subject();
144
- const familyFunction = (key) => {
145
- const subKey = stringifyJson(key);
146
- const family = { key: options.key, subKey };
147
- const fullKey = `${options.key}(${subKey})`;
148
- const target = newest(store);
149
- const def = options.default;
150
- const individualOptions = {
151
- key: fullKey,
152
- default: def instanceof Function ? def(key) : def
153
- };
154
- if (options.effects) {
155
- individualOptions.effects = options.effects(key);
156
- }
157
- const token = createRegularAtom(target, individualOptions, family);
158
- subject.next({ type: `state_creation`, token });
159
- return token;
160
- };
161
- const atomFamily2 = Object.assign(familyFunction, familyToken, {
162
- subject,
163
- install: (s) => createRegularAtomFamily(s, options),
164
- internalRoles
165
- });
166
- store.families.set(options.key, atomFamily2);
167
- store.defaults.set(options.key, options.default);
168
- return familyToken;
169
- }
170
-
171
- // ../atom.io/internal/src/families/create-atom-family.ts
172
- function createAtomFamily(store, options) {
173
- const isMutable = `mutable` in options;
174
- if (isMutable) {
175
- return createMutableAtomFamily(store, options);
176
- }
177
- return createRegularAtomFamily(store, options);
178
- }
179
-
180
- // ../atom.io/internal/src/families/create-readonly-selector-family.ts
181
- function createReadonlySelectorFamily(store, options, internalRoles) {
182
- const familyToken = {
183
- key: options.key,
184
- type: `readonly_selector_family`
185
- };
186
- const existing = store.families.get(options.key);
187
- if (existing) {
188
- store.logger.error(
189
- `\u2757`,
190
- `readonly_selector_family`,
191
- options.key,
192
- `Overwriting an existing ${prettyPrintTokenType(
193
- existing
194
- )} "${existing.key}" in store "${store.config.name}". You can safely ignore this warning if it is due to hot module replacement.`
195
- );
196
- }
197
- const subject = new Subject();
198
- const familyFunction = (key) => {
199
- const subKey = stringifyJson(key);
200
- const family = { key: options.key, subKey };
201
- const fullKey = `${options.key}(${subKey})`;
202
- const target = newest(store);
203
- const token = createReadonlySelector(
204
- target,
205
- {
206
- key: fullKey,
207
- get: options.get(key)
208
- },
209
- family
210
- );
211
- subject.next({ type: `state_creation`, token });
212
- return token;
213
- };
214
- const readonlySelectorFamily = Object.assign(familyFunction, familyToken, {
215
- internalRoles,
216
- subject,
217
- install: (s) => createReadonlySelectorFamily(s, options),
218
- default: (key) => {
219
- const getFn = options.get(key);
220
- return getFn({
221
- get: (...args) => getFromStore(store, ...args),
222
- find: (...args) => findInStore(store, ...args),
223
- json: (token) => getJsonToken(store, token)
224
- });
225
- }
226
- });
227
- store.families.set(options.key, readonlySelectorFamily);
228
- return familyToken;
229
- }
230
-
231
- // ../atom.io/internal/src/families/create-selector-family.ts
232
- function createSelectorFamily(store, options) {
233
- const isWritable = `set` in options;
234
- if (isWritable) {
235
- return createWritableSelectorFamily(store, options);
236
- }
237
- return createReadonlySelectorFamily(store, options);
238
- }
239
-
240
- // ../atom.io/internal/src/store/circular-buffer.ts
241
- var CircularBuffer = class _CircularBuffer {
242
- _buffer;
243
- _index = 0;
244
- constructor(lengthOrArray) {
245
- let length;
246
- if (typeof lengthOrArray === `number`) {
247
- length = lengthOrArray;
248
- } else {
249
- length = lengthOrArray.length;
250
- }
251
- this._buffer = Array.from({ length });
252
- }
253
- get buffer() {
254
- return this._buffer;
255
- }
256
- get index() {
257
- return this._index;
258
- }
259
- add(item) {
260
- this._buffer[this._index] = item;
261
- this._index = (this._index + 1) % this._buffer.length;
262
- }
263
- copy() {
264
- const copy = new _CircularBuffer([...this._buffer]);
265
- copy._index = this._index;
266
- return copy;
267
- }
268
- };
269
-
270
- // ../atom.io/internal/src/store/counterfeit.ts
271
- var FAMILY_MEMBER_TOKEN_TYPES = {
272
- atom_family: `atom`,
273
- mutable_atom_family: `mutable_atom`,
274
- selector_family: `selector`,
275
- readonly_selector_family: `readonly_selector`,
276
- molecule_family: `molecule`
277
- };
278
- function counterfeit(token, key) {
279
- const subKey = stringifyJson(key);
280
- const fullKey = `${token.key}(${subKey})`;
281
- const type = FAMILY_MEMBER_TOKEN_TYPES[token.type];
282
- const stateToken = {
283
- key: fullKey,
284
- type
285
- };
286
- Object.assign(stateToken, {
287
- family: {
288
- key: token.key,
289
- subKey
290
- }
291
- });
292
- Object.assign(stateToken, { counterfeit: true });
293
- return stateToken;
294
- }
295
-
296
- // ../atom.io/internal/src/store/deposit.ts
297
- function deposit(state) {
298
- const token = {
299
- key: state.key,
300
- type: state.type
301
- };
302
- if (`family` in state) {
303
- token.family = state.family;
304
- }
305
- return token;
306
- }
307
-
308
- // ../atom.io/src/atom.ts
309
- function atom(options) {
310
- return createStandaloneAtom(IMPLICIT.STORE, options);
311
- }
312
- function atomFamily(options) {
313
- return createAtomFamily(IMPLICIT.STORE, options);
314
- }
315
-
316
- // ../atom.io/src/join.ts
317
- function join(options, defaultContent, store = IMPLICIT.STORE) {
318
- store.joins.set(options.key, new Join(options, defaultContent, store));
319
- const token = {
320
- key: options.key,
321
- type: `join`,
322
- a: options.between[0],
323
- b: options.between[1],
324
- cardinality: options.cardinality
325
- };
326
- return token;
327
- }
328
- function getInternalRelations(token) {
329
- return getInternalRelationsFromStore(token, IMPLICIT.STORE);
330
- }
331
-
332
- // ../atom.io/src/logger.ts
333
- var simpleLog = (logLevel) => (icon, denomination, tokenKey, message, ...rest) => {
334
- console[logLevel](
335
- `${icon} ${denomination} "${tokenKey}" ${message}`,
336
- ...rest
337
- );
338
- };
339
- var simpleLogger = {
340
- error: simpleLog(`error`),
341
- info: simpleLog(`info`),
342
- warn: simpleLog(`warn`)
343
- };
344
- var AtomIOLogger = class {
345
- logLevel;
346
- filter;
347
- logger;
348
- constructor(logLevel, filter, logger = simpleLogger) {
349
- this.logLevel = logLevel;
350
- this.filter = filter;
351
- this.logger = logger;
352
- }
353
- error = (...args) => {
354
- if ((this.filter?.(...args) ?? true) && this.logLevel !== null) {
355
- this.logger.error(...args);
356
- }
357
- };
358
- info = (...args) => {
359
- if ((this.filter?.(...args) ?? true) && this.logLevel === `info`) {
360
- this.logger.info(...args);
361
- }
362
- };
363
- warn = (...args) => {
364
- if ((this.filter?.(...args) ?? true) && this.logLevel !== `error` && this.logLevel !== null) {
365
- this.logger.warn(...args);
366
- }
367
- };
368
- };
369
- var Realm = class {
370
- store;
371
- constructor(store = IMPLICIT.STORE) {
372
- this.store = store;
373
- makeRootMoleculeInStore(`root`, store);
374
- }
375
- allocate(provenance, key, attachmentStyle) {
376
- return allocateIntoStore(
377
- this.store,
378
- provenance,
379
- key,
380
- attachmentStyle
381
- );
382
- }
383
- fuse(type, reagentA, reagentB) {
384
- return fuseWithinStore(this.store, type, reagentA, reagentB);
385
- }
386
- deallocate(claim) {
387
- deallocateFromStore(this.store, claim);
388
- }
389
- claim(newProvenance, claim, exclusive) {
390
- return claimWithinStore(this.store, newProvenance, claim, exclusive);
391
- }
392
- };
393
- var Anarchy = class {
394
- store;
395
- realm;
396
- constructor(store = IMPLICIT.STORE) {
397
- this.store = store;
398
- this.realm = new Realm(store);
399
- }
400
- allocate(provenance, key, attachmentStyle) {
401
- allocateIntoStore(
402
- this.store,
403
- provenance,
404
- key,
405
- attachmentStyle
406
- );
407
- }
408
- deallocate(key) {
409
- deallocateFromStore(this.store, key);
410
- }
411
- claim(newProvenance, key, exclusive) {
412
- claimWithinStore(this.store, newProvenance, key, exclusive);
413
- }
414
- };
415
-
416
- // ../atom.io/src/selector.ts
417
- function selectorFamily(options) {
418
- return createSelectorFamily(IMPLICIT.STORE, options);
419
- }
420
-
421
- // ../atom.io/internal/src/transaction/is-root-store.ts
422
- function isRootStore(store) {
423
- return `epoch` in store.transactionMeta;
424
- }
425
- function isChildStore(store) {
426
- return `phase` in store.transactionMeta;
427
- }
428
-
429
- // ../atom.io/internal/src/transaction/abort-transaction.ts
430
- var abortTransaction = (store) => {
431
- const target = newest(store);
432
- if (!isChildStore(target)) {
433
- store.logger.warn(
434
- `\u{1F41E}`,
435
- `transaction`,
436
- `???`,
437
- `abortTransaction called outside of a transaction. This is probably a bug in AtomIO.`
438
- );
439
- return;
440
- }
441
- store.logger.info(
442
- `\u{1FA82}`,
443
- `transaction`,
444
- target.transactionMeta.update.key,
445
- `Aborting transaction`
446
- );
447
- target.parent.child = null;
448
- };
449
-
450
- // ../atom.io/internal/src/capitalize.ts
451
- function capitalize(string) {
452
- return string[0].toUpperCase() + string.slice(1);
453
- }
454
-
455
- // ../atom.io/internal/src/pretty-print.ts
456
- function prettyPrintTokenType(token) {
457
- return token.type.split(`_`).map(capitalize).join(` `);
458
- }
459
-
460
- // ../atom.io/internal/src/not-found-error.ts
461
- var NotFoundError = class extends Error {
462
- constructor(token, store) {
463
- super(
464
- `${prettyPrintTokenType(token)} ${stringifyJson(token.key)} not found in store "${store.config.name}".`
465
- );
466
- }
467
- };
468
-
469
- // ../atom.io/internal/src/transaction/act-upon-store.ts
470
- function actUponStore(store, token, id) {
471
- return (...parameters) => {
472
- const tx = withdraw(store, token);
473
- if (tx) {
474
- return tx.run(parameters, id);
475
- }
476
- throw new NotFoundError(token, store);
477
- };
478
- }
479
-
480
- // ../atom.io/internal/src/set-state/become.ts
481
- var become = (nextVersionOfThing) => (originalThing) => nextVersionOfThing instanceof Function ? nextVersionOfThing(originalThing) : nextVersionOfThing;
482
-
483
- // ../atom.io/internal/src/get-state/read-or-compute-value.ts
484
- var readOrComputeValue = (target, state) => {
485
- if (target.valueMap.has(state.key)) {
486
- target.logger.info(`\u{1F4D6}`, state.type, state.key, `reading cached value`);
487
- return readCachedValue(state, target);
488
- }
489
- switch (state.type) {
490
- case `selector`:
491
- case `readonly_selector`:
492
- target.logger.info(`\u{1F9EE}`, state.type, state.key, `computing value`);
493
- return state.get();
494
- case `atom`:
495
- case `mutable_atom`: {
496
- const def = state.default;
497
- let fallback;
498
- if (def instanceof Function) {
499
- fallback = def();
500
- } else {
501
- fallback = def;
502
- }
503
- target.logger.info(
504
- `\u{1F481}`,
505
- `atom`,
506
- state.key,
507
- `could not find cached value; using default`,
508
- fallback
509
- );
510
- return fallback;
511
- }
512
- }
513
- };
514
-
515
- // ../atom.io/internal/src/operation.ts
516
- var openOperation = (store, token) => {
517
- if (store.operation.open) {
518
- const rejectionTime = performance.now();
519
- store.logger.info(
520
- `\u2757`,
521
- token.type,
522
- token.key,
523
- `deferring setState at T-${rejectionTime} until setState for "${store.operation.token.key}" is done`
524
- );
525
- return rejectionTime;
526
- }
527
- store.operation = {
528
- open: true,
529
- done: /* @__PURE__ */ new Set(),
530
- prev: /* @__PURE__ */ new Map(),
531
- time: Date.now(),
532
- token
533
- };
534
- store.logger.info(
535
- `\u2B55`,
536
- token.type,
537
- token.key,
538
- `operation start in store "${store.config.name}"${!isChildStore(store) ? `` : ` ${store.transactionMeta.phase} "${store.transactionMeta.update.key}"`}`
539
- );
540
- };
541
- var closeOperation = (store) => {
542
- if (store.operation.open) {
543
- store.logger.info(
544
- `\u{1F534}`,
545
- store.operation.token.type,
546
- store.operation.token.key,
547
- `operation done in store "${store.config.name}"`
548
- );
549
- }
550
- store.operation = { open: false };
551
- store.on.operationClose.next(store.operation);
552
- };
553
- var isDone = (store, key) => {
554
- if (!store.operation.open) {
555
- store.logger.error(
556
- `\u{1F41E}`,
557
- `unknown`,
558
- key,
559
- `isDone called outside of an operation. This is probably a bug in AtomIO.`
560
- );
561
- return true;
562
- }
563
- return store.operation.done.has(key);
564
- };
565
- var markDone = (store, key) => {
566
- if (!store.operation.open) {
567
- store.logger.error(
568
- `\u{1F41E}`,
569
- `unknown`,
570
- key,
571
- `markDone called outside of an operation. This is probably a bug in AtomIO.`
572
- );
573
- return;
574
- }
575
- store.operation.done.add(key);
576
- };
577
-
578
- // ../atom.io/internal/src/set-state/emit-update.ts
579
- var emitUpdate = (store, state, update) => {
580
- switch (state.type) {
581
- case `mutable_atom`:
582
- store.logger.info(
583
- `\u{1F4E2}`,
584
- state.type,
585
- state.key,
586
- `is now (`,
587
- update.newValue,
588
- `) subscribers:`,
589
- state.subject.subscribers
590
- );
591
- break;
592
- case `atom`:
593
- case `selector`:
594
- case `readonly_selector`:
595
- store.logger.info(
596
- `\u{1F4E2}`,
597
- state.type,
598
- state.key,
599
- `went (`,
600
- update.oldValue,
601
- `->`,
602
- update.newValue,
603
- `) subscribers:`,
604
- state.subject.subscribers
605
- );
606
- }
607
- state.subject.next(update);
608
- };
609
-
610
- // ../atom.io/internal/src/set-state/evict-downstream.ts
611
- var evictDownStream = (store, atom2) => {
612
- const target = newest(store);
613
- const downstreamKeys = target.selectorAtoms.getRelatedKeys(atom2.key);
614
- target.logger.info(
615
- `\u{1F9F9}`,
616
- atom2.type,
617
- atom2.key,
618
- downstreamKeys ? `evicting ${downstreamKeys.size} states downstream:` : `no downstream states`,
619
- downstreamKeys ?? `to evict`
620
- );
621
- if (downstreamKeys) {
622
- if (target.operation.open) {
623
- target.logger.info(
624
- `\u{1F9F9}`,
625
- atom2.type,
626
- atom2.key,
627
- `[ ${[...target.operation.done].join(`, `)} ] already done`
628
- );
629
- }
630
- for (const key of downstreamKeys) {
631
- if (isDone(target, key)) {
632
- continue;
633
- }
634
- evictCachedValue(key, target);
635
- markDone(target, key);
636
- }
637
- }
638
- };
639
-
640
- // ../atom.io/internal/src/set-state/set-atom.ts
641
- var setAtom = (target, atom2, next) => {
642
- const oldValue = readOrComputeValue(target, atom2);
643
- let newValue = oldValue;
644
- if (atom2.type === `mutable_atom` && isChildStore(target)) {
645
- const { parent } = target;
646
- const copiedValue = copyMutableIfNeeded(target, atom2, parent);
647
- newValue = copiedValue;
648
- }
649
- newValue = become(next)(newValue);
650
- target.logger.info(`\u{1F4DD}`, `atom`, atom2.key, `set to`, newValue);
651
- newValue = cacheValue(target, atom2.key, newValue, atom2.subject);
652
- if (isAtomDefault(target, atom2.key)) {
653
- markAtomAsNotDefault(target, atom2.key);
654
- }
655
- markDone(target, atom2.key);
656
- evictDownStream(target, atom2);
657
- const update = { oldValue, newValue };
658
- if (!isChildStore(target)) {
659
- emitUpdate(target, atom2, update);
660
- return;
661
- }
662
- if (target.on.transactionApplying.state === null) {
663
- const { key } = atom2;
664
- if (isTransceiver(update.newValue)) {
665
- return;
666
- }
667
- const atomUpdate = {
668
- type: `atom_update`,
669
- key,
670
- ...update
671
- };
672
- if (atom2.family) {
673
- atomUpdate.family = atom2.family;
674
- }
675
- target.transactionMeta.update.updates.push(atomUpdate);
676
- target.logger.info(
677
- `\u{1F4C1}`,
678
- `atom`,
679
- key,
680
- `stowed (`,
681
- update.oldValue,
682
- `->`,
683
- update.newValue,
684
- `)`
685
- );
686
- } else if (atom2.key.startsWith(`*`)) {
687
- const mutableKey = atom2.key.slice(1);
688
- const mutableAtom = target.atoms.get(mutableKey);
689
- let transceiver = target.valueMap.get(mutableKey);
690
- if (mutableAtom.type === `mutable_atom` && isChildStore(target)) {
691
- const { parent } = target;
692
- const copiedValue = copyMutableIfNeeded(target, mutableAtom, parent);
693
- transceiver = copiedValue;
694
- }
695
- const accepted = transceiver.do(update.newValue) === null;
696
- if (accepted) evictDownStream(target, mutableAtom);
697
- }
698
- };
699
-
700
- // ../atom.io/internal/src/set-state/set-atom-or-selector.ts
701
- var setAtomOrSelector = (store, state, value) => {
702
- switch (state.type) {
703
- case `atom`:
704
- case `mutable_atom`:
705
- setAtom(store, state, value);
706
- break;
707
- case `selector`:
708
- state.set(value);
709
- break;
710
- }
711
- };
712
-
713
- // ../atom.io/internal/src/families/get-family-of-token.ts
714
- function getFamilyOfToken(store, token) {
715
- if (token.family) {
716
- const family = store.families.get(token.family.key);
717
- if (family) {
718
- return family;
719
- }
720
- }
721
- }
722
-
723
- // ../atom.io/internal/src/set-state/set-into-store.ts
724
- function setIntoStore(store, ...params) {
725
- let token;
726
- let family;
727
- let key;
728
- let value;
729
- if (params.length === 2) {
730
- token = params[0];
731
- value = params[1];
732
- family = getFamilyOfToken(store, token) ?? null;
733
- if (family) {
734
- key = token.family ? parseJson(token.family.subKey) : null;
735
- token = findInStore(store, family, key);
736
- }
737
- } else {
738
- family = params[0];
739
- key = params[1];
740
- value = params[2];
741
- token = findInStore(store, family, key);
742
- }
743
- if (`counterfeit` in token && `family` in token) {
744
- const subKey = token.family.subKey;
745
- const disposal = store.disposalTraces.buffer.find(
746
- (item) => item?.key === subKey
747
- );
748
- store.logger.error(
749
- `\u274C`,
750
- token.type,
751
- token.key,
752
- `could not be set because it was not found in the store "${store.config.name}".`,
753
- disposal ? `This state was previously disposed:
754
- ${disposal.trace}` : `No previous disposal trace was found.`
755
- );
756
- return;
757
- }
758
- const rejectionTime = openOperation(store, token);
759
- if (rejectionTime) {
760
- const unsubscribe = store.on.operationClose.subscribe(
761
- `waiting to set "${token.key}" at T-${rejectionTime}`,
762
- () => {
763
- unsubscribe();
764
- store.logger.info(
765
- `\u{1F7E2}`,
766
- token.type,
767
- token.key,
768
- `resuming deferred setState from T-${rejectionTime}`
769
- );
770
- setIntoStore(store, token, value);
771
- }
772
- );
773
- return;
774
- }
775
- const state = withdraw(store, token);
776
- setAtomOrSelector(store, state, value);
777
- closeOperation(store);
778
- }
779
-
780
- // ../atom.io/internal/src/ingest-updates/ingest-atom-update.ts
781
- function ingestAtomUpdate(applying, atomUpdate, store) {
782
- const { key, newValue, oldValue } = atomUpdate;
783
- const value = newValue ;
784
- const token = { key, type: `atom` };
785
- if (atomUpdate.family) {
786
- Object.assign(token, { family: atomUpdate.family });
787
- }
788
- setIntoStore(store, token, value);
789
- }
790
-
791
- // ../atom.io/internal/src/get-trace.ts
792
- function getTrace(error) {
793
- const { stack } = error;
794
- if (stack) {
795
- return `
796
- ` + stack.split(`
797
- `)?.slice(1)?.join(`
798
- `);
799
- }
800
- return ``;
801
- }
802
-
803
- // ../atom.io/internal/src/molecule.ts
804
- function makeRootMoleculeInStore(key, store = IMPLICIT.STORE) {
805
- const molecule = {
806
- key,
807
- stringKey: stringifyJson(key),
808
- dependsOn: `any`
809
- };
810
- store.molecules.set(stringifyJson(key), molecule);
811
- return key;
812
- }
813
- function allocateIntoStore(store, provenance, key, dependsOn = `any`) {
814
- const origin = provenance;
815
- const stringKey = stringifyJson(key);
816
- const invalidKeys = [];
817
- const target = newest(store);
818
- if (Array.isArray(origin)) {
819
- for (const formerClaim of origin) {
820
- const claimString = stringifyJson(formerClaim);
821
- const claim = target.molecules.get(claimString);
822
- if (claim) {
823
- store.moleculeGraph.set(claimString, stringKey, { source: claimString });
824
- } else {
825
- invalidKeys.push(claimString);
826
- }
827
- }
828
- } else {
829
- const claimString = stringifyJson(origin);
830
- const claim = target.molecules.get(claimString);
831
- if (claim) {
832
- store.moleculeGraph.set(claimString, stringKey, { source: claimString });
833
- } else {
834
- invalidKeys.push(claimString);
835
- }
836
- }
837
- if (invalidKeys.length === 0) {
838
- target.molecules.set(stringKey, { key, stringKey, dependsOn });
839
- }
840
- const creationEvent = {
841
- type: `molecule_creation`,
842
- key,
843
- provenance: origin
844
- };
845
- const isTransaction = isChildStore(target) && target.transactionMeta.phase === `building`;
846
- if (isTransaction) {
847
- target.transactionMeta.update.updates.push(creationEvent);
848
- } else {
849
- target.on.moleculeCreation.next(creationEvent);
850
- }
851
- for (const claim of invalidKeys) {
852
- const disposal = store.disposalTraces.buffer.find(
853
- (item) => item?.key === claim
854
- );
855
- store.logger.error(
856
- `\u274C`,
857
- `molecule`,
858
- key,
859
- `allocation failed:`,
860
- `Could not allocate to ${claim} in store "${store.config.name}".`,
861
- disposal ? `
862
- ${claim} was most recently disposed
863
- ${disposal.trace}` : `No previous disposal trace for ${claim} was found.`
864
- );
865
- }
866
- return key;
867
- }
868
- function fuseWithinStore(store, type, sideA, sideB) {
869
- const compoundKey = `T$--${type}==${sideA}++${sideB}`;
870
- const above = [sideA, sideB];
871
- allocateIntoStore(
872
- store,
873
- above,
874
- compoundKey,
875
- `all`
876
- );
877
- return compoundKey;
878
- }
879
- function deallocateFromStore(store, claim) {
880
- const stringKey = stringifyJson(claim);
881
- const molecule = store.molecules.get(stringKey);
882
- if (!molecule) {
883
- const disposal = store.disposalTraces.buffer.find(
884
- (item) => item?.key === stringKey
885
- );
886
- store.logger.error(
887
- `\u274C`,
888
- `molecule`,
889
- claim,
890
- `deallocation failed:`,
891
- `Could not find allocation for ${stringKey} in store "${store.config.name}".`,
892
- disposal ? `
893
- This state was most recently deallocated
894
- ${disposal.trace}` : `No previous disposal trace for ${stringKey} was found.`
895
- );
896
- return;
897
- }
898
- const joinKeys = store.moleculeJoins.getRelatedKeys(
899
- molecule.key
900
- );
901
- if (joinKeys) {
902
- for (const joinKey of joinKeys) {
903
- const join2 = store.joins.get(joinKey);
904
- if (join2) {
905
- join2.relations.delete(molecule.key);
906
- join2.molecules.delete(molecule.stringKey);
907
- }
908
- }
909
- }
910
- store.moleculeJoins.delete(molecule.stringKey);
911
- const provenance = [];
912
- const values = [];
913
- const disposalEvent = {
914
- type: `molecule_disposal`,
915
- key: molecule.key,
916
- values,
917
- provenance
918
- };
919
- const target = newest(store);
920
- target.molecules.delete(stringKey);
921
- const isTransaction = isChildStore(target) && target.transactionMeta.phase === `building`;
922
- if (isTransaction) {
923
- target.transactionMeta.update.updates.push(disposalEvent);
924
- }
925
- const relatedMolecules = store.moleculeGraph.getRelationEntries({
926
- downstreamMoleculeKey: molecule.stringKey
927
- });
928
- if (relatedMolecules) {
929
- for (const [relatedStringKey, { source }] of relatedMolecules) {
930
- if (source === molecule.stringKey) {
931
- const relatedKey = parseJson(relatedStringKey);
932
- deallocateFromStore(store, relatedKey);
933
- } else {
934
- provenance.push(source);
935
- }
936
- }
937
- }
938
- const familyKeys = target.moleculeData.getRelatedKeys(molecule.stringKey);
939
- if (familyKeys) {
940
- for (const familyKey of familyKeys) {
941
- const family = target.families.get(familyKey);
942
- const token = findInStore(store, family, molecule.key);
943
- values.push([family.key, token]);
944
- disposeFromStore(store, token);
945
- }
946
- }
947
- target.moleculeGraph.delete(molecule.stringKey);
948
- target.moleculeJoins.delete(molecule.stringKey);
949
- target.moleculeData.delete(molecule.stringKey);
950
- if (!isTransaction) {
951
- target.on.moleculeDisposal.next(disposalEvent);
952
- }
953
- target.molecules.delete(molecule.stringKey);
954
- const trace = getTrace(new Error());
955
- store.disposalTraces.add({ key: stringKey, trace });
956
- }
957
- function claimWithinStore(store, newProvenance, claim, exclusive) {
958
- const stringKey = stringifyJson(claim);
959
- const target = newest(store);
960
- const molecule = target.molecules.get(stringKey);
961
- if (!molecule) {
962
- const disposal = store.disposalTraces.buffer.find(
963
- (item) => item?.key === stringKey
964
- );
965
- store.logger.error(
966
- `\u274C`,
967
- `molecule`,
968
- claim,
969
- `claim failed:`,
970
- `Could not allocate to ${stringKey} in store "${store.config.name}".`,
971
- disposal ? `
972
- ${stringKey} was most recently disposed
973
- ${disposal.trace}` : `No previous disposal trace for ${stringKey} was found.`
974
- );
975
- return claim;
976
- }
977
- const newProvenanceKey = stringifyJson(newProvenance);
978
- const newProvenanceMolecule = target.molecules.get(newProvenanceKey);
979
- if (!newProvenanceMolecule) {
980
- const disposal = store.disposalTraces.buffer.find(
981
- (item) => item?.key === newProvenanceKey
982
- );
983
- store.logger.error(
984
- `\u274C`,
985
- `molecule`,
986
- claim,
987
- `claim failed:`,
988
- `Could not allocate to ${newProvenanceKey} in store "${store.config.name}".`,
989
- disposal ? `
990
- ${newProvenanceKey} was most recently disposed
991
- ${disposal.trace}` : `No previous disposal trace for ${newProvenanceKey} was found.`
992
- );
993
- return claim;
994
- }
995
- const priorProvenance = store.moleculeGraph.getRelationEntries({
996
- downstreamMoleculeKey: molecule.stringKey
997
- }).filter(([, { source }]) => source !== stringKey).map(([key]) => parseJson(key));
998
- if (exclusive) {
999
- target.moleculeGraph.delete(stringKey);
1000
- }
1001
- target.moleculeGraph.set(
1002
- {
1003
- upstreamMoleculeKey: newProvenanceMolecule.stringKey,
1004
- downstreamMoleculeKey: molecule.stringKey
1005
- },
1006
- {
1007
- source: newProvenanceMolecule.stringKey
1008
- }
1009
- );
1010
- const transferEvent = {
1011
- type: `molecule_transfer`,
1012
- key: molecule.key,
1013
- from: priorProvenance,
1014
- to: [newProvenanceMolecule.key]
1015
- };
1016
- const isTransaction = isChildStore(target) && target.transactionMeta.phase === `building`;
1017
- if (isTransaction) {
1018
- target.transactionMeta.update.updates.push(transferEvent);
1019
- }
1020
- return claim;
1021
- }
1022
-
1023
- // ../atom.io/internal/src/ingest-updates/ingest-creation-disposal.ts
1024
- function ingestCreationEvent(update, applying, store) {
1025
- switch (applying) {
1026
- case `newValue`: {
1027
- createInStore(update, store);
1028
- break;
1029
- }
1030
- case `oldValue`: {
1031
- disposeFromStore(store, update.token);
1032
- break;
1033
- }
1034
- }
1035
- }
1036
- function ingestDisposalEvent(update, applying, store) {
1037
- switch (applying) {
1038
- case `newValue`: {
1039
- disposeFromStore(store, update.token);
1040
- break;
1041
- }
1042
- case `oldValue`: {
1043
- createInStore(update, store);
1044
- if (update.subType === `atom`) {
1045
- store.valueMap.set(update.token.key, update.value);
1046
- }
1047
- break;
1048
- }
1049
- }
1050
- }
1051
- function createInStore(update, store) {
1052
- const { family: familyMeta } = update.token;
1053
- if (familyMeta) {
1054
- const family = store.families.get(familyMeta.key);
1055
- if (family) {
1056
- findInStore(store, family, parseJson(familyMeta.subKey));
1057
- }
1058
- }
1059
- }
1060
- function ingestMoleculeCreationEvent(update, applying, store) {
1061
- switch (applying) {
1062
- case `newValue`:
1063
- allocateIntoStore(store, update.provenance, update.key);
1064
- break;
1065
- case `oldValue`:
1066
- deallocateFromStore(store, update.key);
1067
- break;
1068
- }
1069
- }
1070
- function ingestMoleculeDisposalEvent(update, applying, store) {
1071
- switch (applying) {
1072
- case `newValue`:
1073
- deallocateFromStore(store, update.key);
1074
- break;
1075
- case `oldValue`:
1076
- {
1077
- const provenanceJson = update.provenance.map(parseJson);
1078
- allocateIntoStore(store, provenanceJson, update.key);
1079
- for (const [familyKey, value] of update.values) {
1080
- const family = store.families.get(familyKey);
1081
- if (family) {
1082
- findInStore(store, family, update.key);
1083
- const memberKey = `${familyKey}(${stringifyJson(update.key)})`;
1084
- store.valueMap.set(memberKey, value);
1085
- }
1086
- }
1087
- }
1088
- break;
1089
- }
1090
- }
1091
- function ingestMoleculeTransferEvent(update, applying, store) {
1092
- switch (applying) {
1093
- case `newValue`:
1094
- {
1095
- const provenance = update.to.length === 1 ? update.to[0] : update.to;
1096
- claimWithinStore(
1097
- store,
1098
- provenance,
1099
- update.key,
1100
- `exclusive`
1101
- );
1102
- }
1103
- break;
1104
- case `oldValue`:
1105
- {
1106
- const provenance = update.from.length === 1 ? update.from[0] : update.from;
1107
- claimWithinStore(
1108
- store,
1109
- provenance,
1110
- update.key,
1111
- `exclusive`
1112
- );
1113
- }
1114
- break;
1115
- }
1116
- }
1117
-
1118
- // ../atom.io/internal/src/ingest-updates/ingest-transaction-update.ts
1119
- function ingestTransactionUpdate(applying, transactionUpdate, store) {
1120
- const updates = transactionUpdate.updates ;
1121
- for (const updateFromTransaction of updates) {
1122
- switch (updateFromTransaction.type) {
1123
- case `atom_update`:
1124
- case `selector_update`:
1125
- ingestAtomUpdate(applying, updateFromTransaction, store);
1126
- break;
1127
- case `state_creation`:
1128
- ingestCreationEvent(updateFromTransaction, applying, store);
1129
- break;
1130
- case `state_disposal`:
1131
- ingestDisposalEvent(updateFromTransaction, applying, store);
1132
- break;
1133
- case `molecule_creation`:
1134
- ingestMoleculeCreationEvent(updateFromTransaction, applying, store);
1135
- break;
1136
- case `molecule_disposal`:
1137
- ingestMoleculeDisposalEvent(updateFromTransaction, applying, store);
1138
- break;
1139
- case `molecule_transfer`:
1140
- ingestMoleculeTransferEvent(updateFromTransaction, applying, store);
1141
- break;
1142
- case `transaction_update`:
1143
- ingestTransactionUpdate(applying, updateFromTransaction, store);
1144
- break;
1145
- }
1146
- }
1147
- }
1148
-
1149
- // ../atom.io/internal/src/transaction/get-epoch-number.ts
1150
- function getContinuityKey(store, transactionKey) {
1151
- const continuity = store.transactionMeta.actionContinuities.getRelatedKey(transactionKey);
1152
- return continuity;
1153
- }
1154
- function getEpochNumberOfContinuity(store, continuityKey) {
1155
- const epoch = store.transactionMeta.epoch.get(continuityKey);
1156
- return epoch;
1157
- }
1158
- function getEpochNumberOfAction(store, transactionKey) {
1159
- const isRoot = isRootStore(store);
1160
- if (!isRoot) {
1161
- return void 0;
1162
- }
1163
- const continuityKey = getContinuityKey(store, transactionKey);
1164
- if (continuityKey === void 0) {
1165
- return void 0;
1166
- }
1167
- return getEpochNumberOfContinuity(store, continuityKey);
1168
- }
1169
-
1170
- // ../atom.io/internal/src/transaction/set-epoch-number.ts
1171
- function setEpochNumberOfAction(store, transactionKey, newEpoch) {
1172
- const isRoot = isRootStore(store);
1173
- if (!isRoot) {
1174
- return;
1175
- }
1176
- const continuityKey = getContinuityKey(store, transactionKey);
1177
- if (continuityKey !== void 0) {
1178
- store.transactionMeta.epoch.set(continuityKey, newEpoch);
1179
- }
1180
- }
1181
-
1182
- // ../atom.io/internal/src/transaction/apply-transaction.ts
1183
- var applyTransaction = (output, store) => {
1184
- const child = newest(store);
1185
- const { parent } = child;
1186
- if (parent === null || !isChildStore(child) || child.transactionMeta?.phase !== `building`) {
1187
- store.logger.warn(
1188
- `\u{1F41E}`,
1189
- `transaction`,
1190
- `???`,
1191
- `applyTransaction called outside of a transaction. This is probably a bug in AtomIO.`
1192
- );
1193
- return;
1194
- }
1195
- child.transactionMeta.phase = `applying`;
1196
- child.transactionMeta.update.output = output;
1197
- parent.child = null;
1198
- parent.on.transactionApplying.next(child.transactionMeta);
1199
- const { updates } = child.transactionMeta.update;
1200
- store.logger.info(
1201
- `\u{1F6C4}`,
1202
- `transaction`,
1203
- child.transactionMeta.update.key,
1204
- `Applying transaction with ${updates.length} updates:`,
1205
- updates
1206
- );
1207
- ingestTransactionUpdate(`newValue`, child.transactionMeta.update, parent);
1208
- if (isRootStore(parent)) {
1209
- setEpochNumberOfAction(
1210
- parent,
1211
- child.transactionMeta.update.key,
1212
- child.transactionMeta.update.epoch
1213
- );
1214
- const myTransaction = withdraw(store, {
1215
- key: child.transactionMeta.update.key,
1216
- type: `transaction`
1217
- });
1218
- myTransaction?.subject.next(child.transactionMeta.update);
1219
- store.logger.info(
1220
- `\u{1F6EC}`,
1221
- `transaction`,
1222
- child.transactionMeta.update.key,
1223
- `Finished applying transaction.`
1224
- );
1225
- } else if (isChildStore(parent)) {
1226
- parent.transactionMeta.update.updates.push(child.transactionMeta.update);
1227
- }
1228
- parent.on.transactionApplying.next(null);
1229
- };
1230
-
1231
- // ../atom.io/internal/src/get-environment-data.ts
1232
- function getEnvironmentData(store) {
1233
- return {
1234
- store
1235
- };
1236
- }
1237
-
1238
- // ../atom.io/internal/src/get-state/get-from-store.ts
1239
- function getFromStore(store, ...params) {
1240
- let token;
1241
- let family;
1242
- let key;
1243
- if (params.length === 1) {
1244
- token = params[0];
1245
- } else {
1246
- family = params[0];
1247
- key = params[1];
1248
- token = findInStore(store, family, key);
1249
- }
1250
- if (`counterfeit` in token && `family` in token) {
1251
- family = store.families.get(token.family.key);
1252
- const subKey = token.family.subKey;
1253
- const disposal = store.disposalTraces.buffer.find(
1254
- (item) => item?.key === subKey
1255
- );
1256
- store.logger.error(
1257
- `\u274C`,
1258
- token.type,
1259
- token.key,
1260
- `could not be retrieved because it was not found in the store "${store.config.name}".`,
1261
- disposal ? `This state was previously disposed:
1262
- ${disposal.trace}` : `No previous disposal trace was found.`
1263
- );
1264
- switch (family.type) {
1265
- case `atom_family`:
1266
- case `mutable_atom_family`:
1267
- return store.defaults.get(family.key);
1268
- case `selector_family`:
1269
- case `readonly_selector_family`: {
1270
- if (store.defaults.has(family.key)) {
1271
- return store.defaults.get(token.family.key);
1272
- }
1273
- const defaultValue = withdraw(store, family).default(subKey);
1274
- store.defaults.set(family.key, defaultValue);
1275
- return defaultValue;
1276
- }
1277
- }
1278
- }
1279
- return readOrComputeValue(store, withdraw(store, token));
1280
- }
1281
-
1282
- // ../atom.io/internal/src/junction.ts
1283
- var Junction = class {
1284
- a;
1285
- b;
1286
- cardinality;
1287
- relations = /* @__PURE__ */ new Map();
1288
- contents = /* @__PURE__ */ new Map();
1289
- isAType;
1290
- isBType;
1291
- isContent;
1292
- makeContentKey = (a, b) => `${a}:${b}`;
1293
- warn;
1294
- getRelatedKeys(key) {
1295
- return this.relations.get(key);
1296
- }
1297
- addRelation(a, b) {
1298
- let aRelations = this.relations.get(a);
1299
- let bRelations = this.relations.get(b);
1300
- if (aRelations) {
1301
- aRelations.add(b);
1302
- } else {
1303
- aRelations = /* @__PURE__ */ new Set([b]);
1304
- this.relations.set(a, aRelations);
1305
- }
1306
- if (bRelations) {
1307
- bRelations.add(a);
1308
- } else {
1309
- bRelations = /* @__PURE__ */ new Set([a]);
1310
- this.relations.set(b, bRelations);
1311
- }
1312
- }
1313
- deleteRelation(a, b) {
1314
- const aRelations = this.relations.get(a);
1315
- if (aRelations) {
1316
- aRelations.delete(b);
1317
- if (aRelations.size === 0) {
1318
- this.relations.delete(a);
1319
- }
1320
- const bRelations = this.relations.get(b);
1321
- if (bRelations) {
1322
- bRelations.delete(a);
1323
- if (bRelations.size === 0) {
1324
- this.relations.delete(b);
1325
- }
1326
- }
1327
- }
1328
- }
1329
- replaceRelationsUnsafely(x, ys) {
1330
- this.relations.set(x, new Set(ys));
1331
- for (const y of ys) {
1332
- const yRelations = (/* @__PURE__ */ new Set()).add(x);
1333
- this.relations.set(y, yRelations);
1334
- }
1335
- }
1336
- replaceRelationsSafely(x, ys) {
1337
- const xRelationsPrev = this.relations.get(x);
1338
- let a = this.isAType?.(x) ? x : void 0;
1339
- let b = a === void 0 ? x : void 0;
1340
- if (xRelationsPrev) {
1341
- for (const y of xRelationsPrev) {
1342
- a ??= y;
1343
- b ??= y;
1344
- const yRelations = this.relations.get(y);
1345
- if (yRelations) {
1346
- if (yRelations.size === 1) {
1347
- this.relations.delete(y);
1348
- } else {
1349
- yRelations.delete(x);
1350
- }
1351
- this.contents.delete(this.makeContentKey(a, b));
1352
- }
1353
- }
1354
- }
1355
- this.relations.set(x, new Set(ys));
1356
- for (const y of ys) {
1357
- let yRelations = this.relations.get(y);
1358
- if (yRelations) {
1359
- yRelations.add(x);
1360
- } else {
1361
- yRelations = (/* @__PURE__ */ new Set()).add(x);
1362
- this.relations.set(y, yRelations);
1363
- }
1364
- }
1365
- }
1366
- getContentInternal(contentKey) {
1367
- return this.contents.get(contentKey);
1368
- }
1369
- setContent(contentKey, content) {
1370
- this.contents.set(contentKey, content);
1371
- }
1372
- deleteContent(contentKey) {
1373
- this.contents.delete(contentKey);
1374
- }
1375
- constructor(data, config) {
1376
- this.a = data.between[0];
1377
- this.b = data.between[1];
1378
- this.cardinality = data.cardinality;
1379
- if (!config?.externalStore) {
1380
- this.relations = new Map(
1381
- data.relations?.map(([x, ys]) => [x, new Set(ys)])
1382
- );
1383
- this.contents = new Map(data.contents);
1384
- }
1385
- this.isAType = config?.isAType ?? null;
1386
- this.isBType = config?.isBType ?? null;
1387
- this.isContent = config?.isContent ?? null;
1388
- if (config?.makeContentKey) {
1389
- this.makeContentKey = config.makeContentKey;
1390
- }
1391
- if (config?.externalStore) {
1392
- const externalStore = config.externalStore;
1393
- this.has = (a, b) => externalStore.has(a, b);
1394
- this.addRelation = (a, b) => {
1395
- externalStore.addRelation(a, b);
1396
- };
1397
- this.deleteRelation = (a, b) => {
1398
- externalStore.deleteRelation(a, b);
1399
- };
1400
- this.replaceRelationsSafely = (a, bs) => {
1401
- externalStore.replaceRelationsSafely(a, bs);
1402
- };
1403
- this.replaceRelationsUnsafely = (a, bs) => {
1404
- externalStore.replaceRelationsUnsafely(a, bs);
1405
- };
1406
- this.getRelatedKeys = (key) => externalStore.getRelatedKeys(
1407
- key
1408
- );
1409
- if (externalStore.getContent) {
1410
- this.getContentInternal = (contentKey) => {
1411
- return externalStore.getContent(contentKey);
1412
- };
1413
- this.setContent = (contentKey, content) => {
1414
- externalStore.setContent(contentKey, content);
1415
- };
1416
- this.deleteContent = (contentKey) => {
1417
- externalStore.deleteContent(contentKey);
1418
- };
1419
- }
1420
- for (const [x, ys] of data.relations ?? []) {
1421
- let a = this.isAType?.(x) ? x : void 0;
1422
- let b = a === void 0 ? x : void 0;
1423
- for (const y of ys) {
1424
- a ??= y;
1425
- b ??= y;
1426
- this.addRelation(a, b);
1427
- }
1428
- }
1429
- for (const [contentKey, content] of data.contents ?? []) {
1430
- this.setContent(contentKey, content);
1431
- }
1432
- }
1433
- if (config?.warn) {
1434
- this.warn = config.warn;
1435
- }
1436
- }
1437
- toJSON() {
1438
- return {
1439
- between: [this.a, this.b],
1440
- cardinality: this.cardinality,
1441
- relations: [...this.relations.entries()].map(
1442
- ([a, b]) => [a, [...b]]
1443
- ),
1444
- contents: [...this.contents.entries()]
1445
- };
1446
- }
1447
- set(...params) {
1448
- let a;
1449
- let b;
1450
- let content;
1451
- switch (params.length) {
1452
- case 1: {
1453
- const relation = params[0];
1454
- a = relation[this.a];
1455
- b = relation[this.b];
1456
- content = void 0;
1457
- break;
1458
- }
1459
- case 2: {
1460
- const zeroth = params[0];
1461
- if (typeof zeroth === `string`) {
1462
- [a, b] = params;
1463
- } else {
1464
- a = zeroth[this.a];
1465
- b = zeroth[this.b];
1466
- content = params[1];
1467
- }
1468
- break;
1469
- }
1470
- default: {
1471
- a = params[0];
1472
- b = params[1];
1473
- content = params[2];
1474
- break;
1475
- }
1476
- }
1477
- switch (this.cardinality) {
1478
- // biome-ignore lint/suspicious/noFallthroughSwitchClause: perfect here
1479
- case `1:1`: {
1480
- const bPrev = this.getRelatedKey(a);
1481
- if (bPrev && bPrev !== b) this.delete(a, bPrev);
1482
- }
1483
- case `1:n`:
1484
- {
1485
- const aPrev = this.getRelatedKey(b);
1486
- if (aPrev && aPrev !== a) this.delete(aPrev, b);
1487
- }
1488
- break;
1489
- }
1490
- if (content) {
1491
- const contentKey = this.makeContentKey(a, b);
1492
- this.setContent(contentKey, content);
1493
- }
1494
- this.addRelation(a, b);
1495
- return this;
1496
- }
1497
- delete(x, b) {
1498
- b = typeof b === `string` ? b : x[this.b];
1499
- const a = (
1500
- // @ts-expect-error we deduce that this.a may index x
1501
- typeof x === `string` ? x : x[this.a]
1502
- );
1503
- if (a === void 0 && typeof b === `string`) {
1504
- const bRelations = this.getRelatedKeys(b);
1505
- if (bRelations) {
1506
- for (const bRelation of bRelations) {
1507
- this.delete(bRelation, b);
1508
- }
1509
- }
1510
- }
1511
- if (typeof a === `string` && b === void 0) {
1512
- const aRelations = this.getRelatedKeys(a);
1513
- if (aRelations) {
1514
- for (const aRelation of aRelations) {
1515
- this.delete(a, aRelation);
1516
- }
1517
- }
1518
- }
1519
- if (typeof a === `string` && typeof b === `string`) {
1520
- this.deleteRelation(a, b);
1521
- const contentKey = this.makeContentKey(a, b);
1522
- this.deleteContent(contentKey);
1523
- }
1524
- return this;
1525
- }
1526
- getRelatedKey(key) {
1527
- const relations = this.getRelatedKeys(key);
1528
- if (relations) {
1529
- if (relations.size > 1) {
1530
- this.warn?.(
1531
- `${relations.size} related keys were found for key "${key}": (${[
1532
- ...relations
1533
- ].map((k) => `"${k}"`).join(`, `)}). Only one related key was expected.`
1534
- );
1535
- }
1536
- let singleRelation;
1537
- for (const relation of relations) {
1538
- singleRelation = relation;
1539
- break;
1540
- }
1541
- return singleRelation;
1542
- }
1543
- }
1544
- replaceRelations(x, relations, config) {
1545
- const hasContent = !Array.isArray(relations);
1546
- const ys = hasContent ? Object.keys(relations) : relations;
1547
- if (config?.reckless) {
1548
- this.replaceRelationsUnsafely(x, ys);
1549
- } else {
1550
- this.replaceRelationsSafely(x, ys);
1551
- }
1552
- if (hasContent) {
1553
- for (const y of ys) {
1554
- const contentKey = this.makeContentKey(x, y);
1555
- const content = relations[y];
1556
- this.setContent(contentKey, content);
1557
- }
1558
- }
1559
- return this;
1560
- }
1561
- getContent(a, b) {
1562
- const contentKey = this.makeContentKey(a, b);
1563
- return this.getContentInternal(contentKey);
1564
- }
1565
- getRelationEntries(input) {
1566
- const a = input[this.a];
1567
- const b = input[this.b];
1568
- if (a !== void 0 && b === void 0) {
1569
- const aRelations = this.getRelatedKeys(a);
1570
- if (aRelations) {
1571
- return [...aRelations].map((aRelation) => {
1572
- return [aRelation, this.getContent(a, aRelation)];
1573
- });
1574
- }
1575
- }
1576
- if (a === void 0 && b !== void 0) {
1577
- const bRelations = this.getRelatedKeys(b);
1578
- if (bRelations) {
1579
- return [...bRelations].map((bRelation) => {
1580
- return [bRelation, this.getContent(bRelation, b)];
1581
- });
1582
- }
1583
- }
1584
- return [];
1585
- }
1586
- has(a, b) {
1587
- if (b) {
1588
- const setA = this.getRelatedKeys(a);
1589
- return setA?.has(b) ?? false;
1590
- }
1591
- return this.relations.has(a);
1592
- }
1593
- };
1594
-
1595
- // ../atom.io/internal/src/lazy-map.ts
1596
- var LazyMap = class extends Map {
1597
- deleted = /* @__PURE__ */ new Set();
1598
- source;
1599
- constructor(source) {
1600
- super();
1601
- this.source = source;
1602
- }
1603
- get(key) {
1604
- const has = super.has(key);
1605
- if (has) {
1606
- return super.get(key);
1607
- }
1608
- if (!this.deleted.has(key) && this.source.has(key)) {
1609
- const value = this.source.get(key);
1610
- return value;
1611
- }
1612
- return void 0;
1613
- }
1614
- set(key, value) {
1615
- this.deleted.delete(key);
1616
- return super.set(key, value);
1617
- }
1618
- hasOwn(key) {
1619
- return super.has(key);
1620
- }
1621
- has(key) {
1622
- return !this.deleted.has(key) && (super.has(key) || this.source.has(key));
1623
- }
1624
- delete(key) {
1625
- this.deleted.add(key);
1626
- return super.delete(key);
1627
- }
1628
- };
1629
-
1630
- // ../atom.io/internal/src/transaction/build-transaction.ts
1631
- var buildTransaction = (store, key, params, id) => {
1632
- const parent = newest(store);
1633
- const childBase = {
1634
- parent,
1635
- child: null,
1636
- on: parent.on,
1637
- loggers: parent.loggers,
1638
- logger: parent.logger,
1639
- config: parent.config,
1640
- atoms: new LazyMap(parent.atoms),
1641
- atomsThatAreDefault: new Set(parent.atomsThatAreDefault),
1642
- families: new LazyMap(parent.families),
1643
- joins: new LazyMap(parent.joins),
1644
- operation: { open: false },
1645
- readonlySelectors: new LazyMap(parent.readonlySelectors),
1646
- timelines: new LazyMap(parent.timelines),
1647
- timelineTopics: new Junction(parent.timelineTopics.toJSON()),
1648
- trackers: /* @__PURE__ */ new Map(),
1649
- transactions: new LazyMap(parent.transactions),
1650
- selectorAtoms: new Junction(parent.selectorAtoms.toJSON()),
1651
- selectorGraph: new Junction(parent.selectorGraph.toJSON(), {
1652
- makeContentKey: (...keys) => keys.sort().join(`:`)
1653
- }),
1654
- selectors: new LazyMap(parent.selectors),
1655
- valueMap: new LazyMap(parent.valueMap),
1656
- defaults: parent.defaults,
1657
- disposalTraces: store.disposalTraces.copy(),
1658
- molecules: new LazyMap(parent.molecules),
1659
- moleculeGraph: new Junction(parent.moleculeGraph.toJSON(), {
1660
- makeContentKey: parent.moleculeGraph.makeContentKey
1661
- }),
1662
- moleculeData: new Junction(parent.moleculeData.toJSON(), {
1663
- makeContentKey: parent.moleculeData.makeContentKey
1664
- }),
1665
- moleculeJoins: new Junction(parent.moleculeJoins.toJSON(), {
1666
- makeContentKey: parent.moleculeJoins.makeContentKey
1667
- }),
1668
- miscResources: new LazyMap(parent.miscResources)
1669
- };
1670
- const epoch = getEpochNumberOfAction(store, key);
1671
- const transactionMeta = {
1672
- phase: `building`,
1673
- update: {
1674
- type: `transaction_update`,
1675
- key,
1676
- id,
1677
- epoch: epoch === void 0 ? Number.NaN : epoch + 1,
1678
- updates: [],
1679
- params,
1680
- output: void 0
1681
- },
1682
- toolkit: {
1683
- get: (...ps) => getFromStore(child, ...ps),
1684
- set: (...ps) => {
1685
- setIntoStore(child, ...ps);
1686
- },
1687
- run: (token, identifier = arbitrary()) => actUponStore(child, token, identifier),
1688
- find: (...ps) => findInStore(store, ...ps),
1689
- json: (token) => getJsonToken(child, token),
1690
- dispose: (...ps) => {
1691
- disposeFromStore(child, ...ps);
1692
- },
1693
- env: () => getEnvironmentData(child)
1694
- }
1695
- };
1696
- const child = Object.assign(childBase, {
1697
- transactionMeta
1698
- });
1699
- parent.child = child;
1700
- store.logger.info(
1701
- `\u{1F6EB}`,
1702
- `transaction`,
1703
- key,
1704
- `Building transaction with params:`,
1705
- params
1706
- );
1707
- return child;
1708
- };
1709
-
1710
- // ../atom.io/internal/src/transaction/create-transaction.ts
1711
- function createTransaction(store, options) {
1712
- const newTransaction = {
1713
- key: options.key,
1714
- type: `transaction`,
1715
- run: (params, id) => {
1716
- const childStore = buildTransaction(store, options.key, params, id);
1717
- try {
1718
- const target2 = newest(store);
1719
- const { toolkit } = childStore.transactionMeta;
1720
- const output = options.do(toolkit, ...params);
1721
- applyTransaction(output, target2);
1722
- return output;
1723
- } catch (thrown) {
1724
- abortTransaction(target);
1725
- store.logger.warn(`\u{1F4A5}`, `transaction`, options.key, `caught:`, thrown);
1726
- throw thrown;
1727
- }
1728
- },
1729
- install: (s) => createTransaction(s, options),
1730
- subject: new Subject()
1731
- };
1732
- const target = newest(store);
1733
- target.transactions.set(newTransaction.key, newTransaction);
1734
- const token = deposit(newTransaction);
1735
- store.on.transactionCreation.next(token);
1736
- return token;
1737
- }
1738
-
1739
- // ../atom.io/src/transaction.ts
1740
- function transaction(options) {
1741
- return createTransaction(IMPLICIT.STORE, options);
1742
- }
1743
-
1744
- // ../atom.io/internal/src/store/store.ts
1745
- var Store = class {
1746
- parent = null;
1747
- child = null;
1748
- valueMap = /* @__PURE__ */ new Map();
1749
- defaults = /* @__PURE__ */ new Map();
1750
- atoms = /* @__PURE__ */ new Map();
1751
- selectors = /* @__PURE__ */ new Map();
1752
- readonlySelectors = /* @__PURE__ */ new Map();
1753
- atomsThatAreDefault = /* @__PURE__ */ new Set();
1754
- selectorAtoms = new Junction({
1755
- between: [`selectorKey`, `atomKey`],
1756
- cardinality: `n:n`
1757
- });
1758
- selectorGraph = new Junction(
1759
- {
1760
- between: [`upstreamSelectorKey`, `downstreamSelectorKey`],
1761
- cardinality: `n:n`
1762
- },
1763
- {
1764
- makeContentKey: (...keys) => keys.sort().join(`:`)
1765
- }
1766
- );
1767
- trackers = /* @__PURE__ */ new Map();
1768
- families = /* @__PURE__ */ new Map();
1769
- joins = /* @__PURE__ */ new Map();
1770
- transactions = /* @__PURE__ */ new Map();
1771
- transactionMeta = {
1772
- epoch: /* @__PURE__ */ new Map(),
1773
- actionContinuities: new Junction({
1774
- between: [`continuity`, `action`],
1775
- cardinality: `1:n`
1776
- })
1777
- };
1778
- timelines = /* @__PURE__ */ new Map();
1779
- timelineTopics = new Junction({
1780
- between: [`timelineKey`, `topicKey`],
1781
- cardinality: `1:n`
1782
- });
1783
- disposalTraces = new CircularBuffer(100);
1784
- molecules = /* @__PURE__ */ new Map();
1785
- moleculeJoins = new Junction(
1786
- {
1787
- between: [`moleculeKey`, `joinKey`],
1788
- cardinality: `n:n`
1789
- },
1790
- {
1791
- makeContentKey: (...keys) => keys.sort().join(`:`)
1792
- }
1793
- );
1794
- moleculeGraph = new Junction(
1795
- {
1796
- between: [`upstreamMoleculeKey`, `downstreamMoleculeKey`],
1797
- cardinality: `n:n`
1798
- },
1799
- {
1800
- makeContentKey: (...keys) => keys.sort().join(`:`)
1801
- }
1802
- );
1803
- moleculeData = new Junction(
1804
- {
1805
- between: [`moleculeKey`, `stateFamilyKey`],
1806
- cardinality: `n:n`
1807
- },
1808
- {
1809
- makeContentKey: (...keys) => keys.sort().join(`:`)
1810
- }
1811
- );
1812
- miscResources = /* @__PURE__ */ new Map();
1813
- on = {
1814
- atomCreation: new Subject(),
1815
- atomDisposal: new Subject(),
1816
- selectorCreation: new Subject(),
1817
- selectorDisposal: new Subject(),
1818
- timelineCreation: new Subject(),
1819
- transactionCreation: new Subject(),
1820
- transactionApplying: new StatefulSubject(
1821
- null
1822
- ),
1823
- operationClose: new Subject(),
1824
- moleculeCreation: new Subject(),
1825
- moleculeDisposal: new Subject()
1826
- };
1827
- operation = { open: false };
1828
- config = {
1829
- name: `IMPLICIT_STORE`,
1830
- lifespan: `ephemeral`
1831
- };
1832
- loggers = [
1833
- new AtomIOLogger(`warn`, (_, __, key) => !isReservedIntrospectionKey(key))
1834
- ];
1835
- logger = {
1836
- error: (...messages) => {
1837
- for (const logger of this.loggers) logger.error(...messages);
1838
- },
1839
- info: (...messages) => {
1840
- for (const logger of this.loggers) logger.info(...messages);
1841
- },
1842
- warn: (...messages) => {
1843
- for (const logger of this.loggers) logger.warn(...messages);
1844
- }
1845
- };
1846
- constructor(config, store = null) {
1847
- this.config = {
1848
- ...store?.config,
1849
- ...config
1850
- };
1851
- if (store !== null) {
1852
- this.valueMap = new Map(store?.valueMap);
1853
- this.operation = { ...store?.operation };
1854
- if (isRootStore(store)) {
1855
- this.transactionMeta = {
1856
- epoch: new Map(store?.transactionMeta.epoch),
1857
- actionContinuities: new Junction(
1858
- store?.transactionMeta.actionContinuities.toJSON()
1859
- )
1860
- };
1861
- }
1862
- for (const [, family] of store.families) {
1863
- if (family.internalRoles?.includes(`mutable`) || family.internalRoles?.includes(`join`)) {
1864
- continue;
1865
- }
1866
- family.install(this);
1867
- }
1868
- const mutableHelpers = /* @__PURE__ */ new Set();
1869
- for (const [, atom2] of store.atoms) {
1870
- if (mutableHelpers.has(atom2.key)) {
1871
- continue;
1872
- }
1873
- atom2.install(this);
1874
- if (atom2.type === `mutable_atom`) {
1875
- const originalJsonToken = getJsonToken(store, atom2);
1876
- const originalUpdateToken = getUpdateToken(atom2);
1877
- mutableHelpers.add(originalJsonToken.key);
1878
- mutableHelpers.add(originalUpdateToken.key);
1879
- }
1880
- }
1881
- for (const [, selector] of store.readonlySelectors) {
1882
- selector.install(this);
1883
- }
1884
- for (const [, selector] of store.selectors) {
1885
- if (mutableHelpers.has(selector.key)) {
1886
- continue;
1887
- }
1888
- selector.install(this);
1889
- }
1890
- for (const [, tx] of store.transactions) {
1891
- tx.install(this);
1892
- }
1893
- for (const [, timeline] of store.timelines) {
1894
- timeline.install(this);
1895
- }
1896
- }
1897
- }
1898
- };
1899
- var IMPLICIT = {
1900
- get STORE() {
1901
- globalThis.ATOM_IO_IMPLICIT_STORE ??= new Store({
1902
- name: `IMPLICIT_STORE`,
1903
- lifespan: `ephemeral`
1904
- });
1905
- return globalThis.ATOM_IO_IMPLICIT_STORE;
1906
- }
1907
- };
1908
-
1909
- // ../atom.io/internal/src/store/withdraw.ts
1910
- function withdraw(store, token) {
1911
- let withdrawn;
1912
- let target = store;
1913
- while (target !== null) {
1914
- switch (token.type) {
1915
- case `atom`:
1916
- case `mutable_atom`:
1917
- withdrawn = target.atoms.get(token.key);
1918
- break;
1919
- case `selector`:
1920
- withdrawn = target.selectors.get(token.key);
1921
- break;
1922
- case `readonly_selector`:
1923
- withdrawn = target.readonlySelectors.get(token.key);
1924
- break;
1925
- case `atom_family`:
1926
- case `mutable_atom_family`:
1927
- case `selector_family`:
1928
- case `readonly_selector_family`:
1929
- withdrawn = target.families.get(token.key);
1930
- break;
1931
- case `timeline`:
1932
- withdrawn = target.timelines.get(token.key);
1933
- break;
1934
- case `transaction`:
1935
- withdrawn = target.transactions.get(token.key);
1936
- break;
1937
- }
1938
- if (withdrawn) {
1939
- return withdrawn;
1940
- }
1941
- target = target.child;
1942
- }
1943
- throw new NotFoundError(token, store);
1944
- }
1945
-
1946
- // ../atom.io/internal/src/families/init-family-member.ts
1947
- function initFamilyMemberInStore(store, token, key) {
1948
- const family = store.families.get(token.key);
1949
- if (family === void 0) {
1950
- throw new NotFoundError(token, store);
1951
- }
1952
- const state = family(key);
1953
- const target = newest(store);
1954
- if (state.family) {
1955
- if (isRootStore(target)) {
1956
- switch (state.type) {
1957
- case `atom`:
1958
- case `mutable_atom`:
1959
- store.on.atomCreation.next(state);
1960
- break;
1961
- case `selector`:
1962
- case `readonly_selector`:
1963
- store.on.selectorCreation.next(state);
1964
- break;
1965
- }
1966
- } else if (isChildStore(target) && target.on.transactionApplying.state === null) {
1967
- target.transactionMeta.update.updates.push({
1968
- type: `state_creation`,
1969
- token: state
1970
- });
1971
- }
1972
- }
1973
- return state;
1974
- }
1975
-
1976
- // ../atom.io/internal/src/families/seek-in-store.ts
1977
- function seekInStore(store, token, key) {
1978
- const subKey = stringifyJson(key);
1979
- const fullKey = `${token.key}(${subKey})`;
1980
- const target = newest(store);
1981
- let state;
1982
- switch (token.type) {
1983
- case `atom_family`:
1984
- case `mutable_atom_family`:
1985
- state = target.atoms.get(fullKey);
1986
- break;
1987
- case `selector_family`:
1988
- state = target.selectors.get(fullKey);
1989
- break;
1990
- case `readonly_selector_family`:
1991
- state = target.readonlySelectors.get(fullKey);
1992
- break;
1993
- }
1994
- if (state) {
1995
- return deposit(state);
1996
- }
1997
- return state;
1998
- }
1999
-
2000
- // ../atom.io/internal/src/families/find-in-store.ts
2001
- function findInStore(store, token, key) {
2002
- let state = seekInStore(store, token, key);
2003
- if (state) {
2004
- return state;
2005
- }
2006
- const stringKey = stringifyJson(key);
2007
- const molecule = store.molecules.get(stringKey);
2008
- if (!molecule && store.config.lifespan === `immortal`) {
2009
- const fakeToken = counterfeit(token, key);
2010
- store.logger.error(
2011
- `\u274C`,
2012
- fakeToken.type,
2013
- fakeToken.key,
2014
- `was not found in store "${store.config.name}"; returned a counterfeit token.`
2015
- );
2016
- return fakeToken;
2017
- }
2018
- state = initFamilyMemberInStore(store, token, key);
2019
- if (molecule) {
2020
- const target = newest(store);
2021
- target.moleculeData.set(stringKey, token.key);
2022
- }
2023
- return state;
2024
- }
2025
-
2026
- // ../atom.io/internal/src/families/dispose-from-store.ts
2027
- function disposeFromStore(store, ...params) {
2028
- let token;
2029
- if (params.length === 1) {
2030
- token = params[0];
2031
- } else {
2032
- const family = params[0];
2033
- const key = params[1];
2034
- const maybeToken = findInStore(store, family, key);
2035
- token = maybeToken;
2036
- }
2037
- try {
2038
- withdraw(store, token);
2039
- } catch (thrown) {
2040
- store.logger.error(
2041
- `\u274C`,
2042
- token.type,
2043
- token.key,
2044
- `could not be disposed because it was not found in the store "${store.config.name}".`
2045
- );
2046
- return;
2047
- }
2048
- switch (token.type) {
2049
- case `atom`:
2050
- case `mutable_atom`:
2051
- disposeAtom(store, token);
2052
- break;
2053
- case `selector`:
2054
- case `readonly_selector`:
2055
- disposeSelector(store, token);
2056
- break;
2057
- }
2058
- }
2059
-
2060
- // ../atom.io/internal/src/keys.ts
2061
- var isAtomKey = (store, key) => newest(store).atoms.has(key);
2062
- var isSelectorKey = (store, key) => newest(store).selectors.has(key);
2063
- var isReadonlySelectorKey = (store, key) => newest(store).readonlySelectors.has(key);
2064
- var isStateKey = (store, key) => isAtomKey(store, key) || isSelectorKey(store, key) || isReadonlySelectorKey(store, key);
2065
-
2066
- // ../atom.io/internal/src/selector/get-selector-dependency-keys.ts
2067
- var getSelectorDependencyKeys = (key, store) => {
2068
- const sources = newest(store).selectorGraph.getRelationEntries({ downstreamSelectorKey: key }).filter(([_, { source }]) => source !== key).map(([_, { source }]) => source).filter((source) => isStateKey(store, source));
2069
- return sources;
2070
- };
2071
-
2072
- // ../atom.io/internal/src/selector/trace-selector-atoms.ts
2073
- var traceSelectorAtoms = (directDependencyKey, covered, store) => {
2074
- const rootKeys = [];
2075
- const indirectDependencyKeys = getSelectorDependencyKeys(
2076
- directDependencyKey,
2077
- store
2078
- );
2079
- while (indirectDependencyKeys.length > 0) {
2080
- const indirectDependencyKey = indirectDependencyKeys.shift();
2081
- if (covered.has(indirectDependencyKey)) {
2082
- continue;
2083
- }
2084
- covered.add(indirectDependencyKey);
2085
- if (!isAtomKey(store, indirectDependencyKey)) {
2086
- indirectDependencyKeys.push(
2087
- ...getSelectorDependencyKeys(indirectDependencyKey, store)
2088
- );
2089
- } else if (!rootKeys.includes(indirectDependencyKey)) {
2090
- rootKeys.push(indirectDependencyKey);
2091
- }
2092
- }
2093
- return rootKeys;
2094
- };
2095
- var traceAllSelectorAtoms = (selector, store) => {
2096
- const selectorKey = selector.key;
2097
- const directDependencyKeys = getSelectorDependencyKeys(selectorKey, store);
2098
- const covered = /* @__PURE__ */ new Set();
2099
- return directDependencyKeys.flatMap(
2100
- (depKey) => isAtomKey(store, depKey) ? depKey : traceSelectorAtoms(depKey, covered, store)
2101
- );
2102
- };
2103
-
2104
- // ../atom.io/internal/src/selector/update-selector-atoms.ts
2105
- var updateSelectorAtoms = (selectorKey, dependency, covered, store) => {
2106
- const target = newest(store);
2107
- if (dependency.type === `atom` || dependency.type === `mutable_atom`) {
2108
- target.selectorAtoms.set({
2109
- selectorKey,
2110
- atomKey: dependency.key
2111
- });
2112
- store.logger.info(
2113
- `\u{1F50D}`,
2114
- `selector`,
2115
- selectorKey,
2116
- `discovers root atom "${dependency.key}"`
2117
- );
2118
- } else {
2119
- const rootKeys = traceSelectorAtoms(dependency.key, covered, store);
2120
- store.logger.info(
2121
- `\u{1F50D}`,
2122
- `selector`,
2123
- selectorKey,
2124
- `discovers root atoms: [ ${rootKeys.map((key) => `"${key}"`).join(`, `)} ]`
2125
- );
2126
- for (const atomKey of rootKeys) {
2127
- target.selectorAtoms = target.selectorAtoms.set({
2128
- selectorKey,
2129
- atomKey
2130
- });
2131
- }
2132
- }
2133
- covered.add(dependency.key);
2134
- };
2135
-
2136
- // ../atom.io/internal/src/selector/register-selector.ts
2137
- var registerSelector = (selectorKey, covered, store) => ({
2138
- get: (...params) => {
2139
- const target = newest(store);
2140
- let dependency;
2141
- if (params.length === 2) {
2142
- const [family, key] = params;
2143
- dependency = findInStore(store, family, key);
2144
- } else {
2145
- [dependency] = params;
2146
- }
2147
- const dependencyState = withdraw(store, dependency);
2148
- const dependencyValue = readOrComputeValue(store, dependencyState);
2149
- store.logger.info(
2150
- `\u{1F50C}`,
2151
- `selector`,
2152
- selectorKey,
2153
- `registers dependency ( "${dependency.key}" =`,
2154
- dependencyValue,
2155
- `)`
2156
- );
2157
- target.selectorGraph.set(
2158
- {
2159
- upstreamSelectorKey: dependency.key,
2160
- downstreamSelectorKey: selectorKey
2161
- },
2162
- {
2163
- source: dependency.key
2164
- }
2165
- );
2166
- updateSelectorAtoms(selectorKey, dependency, covered, store);
2167
- return dependencyValue;
2168
- },
2169
- set: (...params) => {
2170
- let token;
2171
- let value;
2172
- if (params.length === 2) {
2173
- token = params[0];
2174
- value = params[1];
2175
- } else {
2176
- const family = params[0];
2177
- const key = params[1];
2178
- value = params[2];
2179
- token = findInStore(store, family, key);
2180
- }
2181
- const target = newest(store);
2182
- const state = withdraw(target, token);
2183
- setAtomOrSelector(target, state, value);
2184
- },
2185
- find: (...args) => findInStore(store, ...args),
2186
- json: (token) => getJsonToken(store, token)
2187
- });
2188
-
2189
- // ../atom.io/internal/src/selector/create-readonly-selector.ts
2190
- var createReadonlySelector = (store, options, family) => {
2191
- const target = newest(store);
2192
- const subject = new Subject();
2193
- const covered = /* @__PURE__ */ new Set();
2194
- const { get, find, json } = registerSelector(options.key, covered, target);
2195
- const getSelf = () => {
2196
- const value = options.get({ get, find, json });
2197
- cacheValue(newest(store), options.key, value, subject);
2198
- covered.clear();
2199
- return value;
2200
- };
2201
- const readonlySelector = {
2202
- ...options,
2203
- subject,
2204
- install: (s) => createReadonlySelector(s, options, family),
2205
- get: getSelf,
2206
- type: `readonly_selector`,
2207
- ...family && { family }
2208
- };
2209
- target.readonlySelectors.set(options.key, readonlySelector);
2210
- const initialValue = getSelf();
2211
- store.logger.info(
2212
- `\u2728`,
2213
- readonlySelector.type,
2214
- readonlySelector.key,
2215
- `=`,
2216
- initialValue
2217
- );
2218
- const token = {
2219
- key: options.key,
2220
- type: `readonly_selector`
2221
- };
2222
- if (family) {
2223
- token.family = family;
2224
- }
2225
- return token;
2226
- };
2227
-
2228
- // ../atom.io/internal/src/selector/create-writable-selector.ts
2229
- var createWritableSelector = (store, options, family) => {
2230
- const target = newest(store);
2231
- const subject = new Subject();
2232
- const covered = /* @__PURE__ */ new Set();
2233
- const setterToolkit = registerSelector(options.key, covered, target);
2234
- const { find, get, json } = setterToolkit;
2235
- const getterToolkit = { find, get, json };
2236
- const getSelf = (getFn = options.get, innerTarget = newest(store)) => {
2237
- const value = getFn(getterToolkit);
2238
- cacheValue(innerTarget, options.key, value, subject);
2239
- covered.clear();
2240
- return value;
2241
- };
2242
- const setSelf = (next) => {
2243
- const innerTarget = newest(store);
2244
- const oldValue = getSelf(options.get, innerTarget);
2245
- const newValue = become(next)(oldValue);
2246
- store.logger.info(
2247
- `\u{1F4DD}`,
2248
- `selector`,
2249
- options.key,
2250
- `set (`,
2251
- oldValue,
2252
- `->`,
2253
- newValue,
2254
- `)`
2255
- );
2256
- cacheValue(innerTarget, options.key, newValue, subject);
2257
- markDone(innerTarget, options.key);
2258
- if (isRootStore(innerTarget)) {
2259
- subject.next({ newValue, oldValue });
2260
- }
2261
- options.set(setterToolkit, newValue);
2262
- };
2263
- const mySelector = {
2264
- ...options,
2265
- subject,
2266
- install: (s) => createWritableSelector(s, options, family),
2267
- get: getSelf,
2268
- set: setSelf,
2269
- type: `selector`,
2270
- ...family && { family }
2271
- };
2272
- target.selectors.set(options.key, mySelector);
2273
- const initialValue = getSelf();
2274
- store.logger.info(`\u2728`, mySelector.type, mySelector.key, `=`, initialValue);
2275
- const token = {
2276
- key: options.key,
2277
- type: `selector`
2278
- };
2279
- if (family) {
2280
- token.family = family;
2281
- }
2282
- return token;
2283
- };
2284
-
2285
- // ../atom.io/internal/src/selector/create-standalone-selector.ts
2286
- function createStandaloneSelector(store, options) {
2287
- const isWritable = `set` in options;
2288
- if (isWritable) {
2289
- const state2 = createWritableSelector(store, options, void 0);
2290
- store.on.selectorCreation.next(state2);
2291
- return state2;
2292
- }
2293
- const state = createReadonlySelector(store, options, void 0);
2294
- store.on.selectorCreation.next(state);
2295
- return state;
2296
- }
2297
-
2298
- // ../atom.io/internal/src/selector/dispose-selector.ts
2299
- function disposeSelector(store, selectorToken) {
2300
- const target = newest(store);
2301
- const { key } = selectorToken;
2302
- const selector = withdraw(target, selectorToken);
2303
- if (!selector.family) {
2304
- store.logger.error(
2305
- `\u274C`,
2306
- `selector`,
2307
- key,
2308
- `Standalone selectors cannot be disposed.`
2309
- );
2310
- } else {
2311
- const molecule = target.molecules.get(selector.family.subKey);
2312
- if (molecule) {
2313
- target.moleculeData.delete(selector.family.subKey, selector.family.key);
2314
- }
2315
- let familyToken;
2316
- switch (selectorToken.type) {
2317
- case `selector`:
2318
- {
2319
- target.selectors.delete(key);
2320
- familyToken = {
2321
- key: selector.family.key,
2322
- type: `selector_family`
2323
- };
2324
- const family = withdraw(store, familyToken);
2325
- family.subject.next({
2326
- type: `state_disposal`,
2327
- subType: `selector`,
2328
- token: selectorToken
2329
- });
2330
- }
2331
- break;
2332
- case `readonly_selector`:
2333
- {
2334
- target.readonlySelectors.delete(key);
2335
- familyToken = {
2336
- key: selector.family.key,
2337
- type: `readonly_selector_family`
2338
- };
2339
- const family = withdraw(store, familyToken);
2340
- family.subject.next({
2341
- type: `state_disposal`,
2342
- subType: `selector`,
2343
- token: selectorToken
2344
- });
2345
- }
2346
- break;
2347
- }
2348
- target.valueMap.delete(key);
2349
- target.selectorAtoms.delete(key);
2350
- target.selectorGraph.delete(key);
2351
- store.logger.info(`\u{1F525}`, selectorToken.type, key, `deleted`);
2352
- if (isChildStore(target) && target.transactionMeta.phase === `building`) {
2353
- target.transactionMeta.update.updates.push({
2354
- type: `state_disposal`,
2355
- subType: `selector`,
2356
- token: selectorToken
2357
- });
2358
- } else {
2359
- store.on.selectorDisposal.next(selectorToken);
2360
- }
2361
- }
2362
- }
2363
-
2364
- // ../atom.io/internal/src/families/create-writable-selector-family.ts
2365
- function createWritableSelectorFamily(store, options, internalRoles) {
2366
- const familyToken = {
2367
- key: options.key,
2368
- type: `selector_family`
2369
- };
2370
- const existing = store.families.get(options.key);
2371
- if (existing) {
2372
- store.logger.error(
2373
- `\u2757`,
2374
- `selector_family`,
2375
- options.key,
2376
- `Overwriting an existing ${prettyPrintTokenType(
2377
- existing
2378
- )} "${existing.key}" in store "${store.config.name}". You can safely ignore this warning if it is due to hot module replacement.`
2379
- );
2380
- }
2381
- const subject = new Subject();
2382
- const familyFunction = (key) => {
2383
- const subKey = stringifyJson(key);
2384
- const family = { key: options.key, subKey };
2385
- const fullKey = `${options.key}(${subKey})`;
2386
- const target = newest(store);
2387
- const token = createWritableSelector(
2388
- target,
2389
- {
2390
- key: fullKey,
2391
- get: options.get(key),
2392
- set: options.set(key)
2393
- },
2394
- family
2395
- );
2396
- subject.next({ type: `state_creation`, token });
2397
- return token;
2398
- };
2399
- const selectorFamily2 = Object.assign(familyFunction, familyToken, {
2400
- internalRoles,
2401
- subject,
2402
- install: (s) => createWritableSelectorFamily(s, options),
2403
- default: (key) => {
2404
- const getFn = options.get(key);
2405
- return getFn({
2406
- get: (...args) => getFromStore(store, ...args),
2407
- find: (...args) => findInStore(store, ...args),
2408
- json: (token) => getJsonToken(store, token)
2409
- });
2410
- }
2411
- });
2412
- store.families.set(options.key, selectorFamily2);
2413
- return familyToken;
2414
- }
2415
-
2416
- // ../atom.io/json/src/select-json-family.ts
2417
- function selectJsonFamily(store, atomFamilyToken, transform) {
2418
- const jsonFamily = createWritableSelectorFamily(
2419
- store,
2420
- {
2421
- key: `${atomFamilyToken.key}:JSON`,
2422
- get: (key) => ({ get }) => {
2423
- const baseState = get(atomFamilyToken, key);
2424
- return transform.toJson(baseState);
2425
- },
2426
- set: (key) => ({ set }, newValue) => {
2427
- set(atomFamilyToken, key, transform.fromJson(newValue));
2428
- }
2429
- },
2430
- [`mutable`, `json`]
2431
- );
2432
- return jsonFamily;
2433
- }
2434
-
2435
- // ../atom.io/json/src/index.ts
2436
- var parseJson = (str) => JSON.parse(str);
2437
- var stringifyJson = (json) => JSON.stringify(json);
2438
-
2439
- // ../atom.io/internal/src/subscribe/recall-state.ts
2440
- var recallState = (store, state) => {
2441
- const target = newest(store);
2442
- if (target.operation.open) {
2443
- return target.operation.prev.get(state.key);
2444
- }
2445
- return target.valueMap.get(state.key);
2446
- };
2447
-
2448
- // ../atom.io/internal/src/subscribe/subscribe-to-root-atoms.ts
2449
- var subscribeToRootAtoms = (store, selector) => {
2450
- const target = newest(store);
2451
- const dependencySubscriptions = traceAllSelectorAtoms(selector, store).map(
2452
- (atomKey) => {
2453
- const atom2 = target.atoms.get(atomKey);
2454
- if (atom2 === void 0) {
2455
- throw new Error(
2456
- `Atom "${atomKey}", a dependency of selector "${selector.key}", not found in store "${store.config.name}".`
2457
- );
2458
- }
2459
- return atom2.subject.subscribe(
2460
- `${selector.type}:${selector.key}`,
2461
- (atomChange) => {
2462
- store.logger.info(
2463
- `\u{1F4E2}`,
2464
- selector.type,
2465
- selector.key,
2466
- `root`,
2467
- atomKey,
2468
- `went`,
2469
- atomChange.oldValue,
2470
- `->`,
2471
- atomChange.newValue
2472
- );
2473
- const oldValue = recallState(target, selector);
2474
- const newValue = readOrComputeValue(target, selector);
2475
- store.logger.info(
2476
- `\u2728`,
2477
- selector.type,
2478
- selector.key,
2479
- `went`,
2480
- oldValue,
2481
- `->`,
2482
- newValue
2483
- );
2484
- selector.subject.next({ newValue, oldValue });
2485
- }
2486
- );
2487
- }
2488
- );
2489
- return dependencySubscriptions;
2490
- };
2491
-
2492
- // ../atom.io/internal/src/subscribe/subscribe-to-state.ts
2493
- function subscribeToState(store, token, key, handleUpdate) {
2494
- function safelyHandleUpdate(update) {
2495
- if (store.operation.open) {
2496
- const unsubscribe2 = store.on.operationClose.subscribe(
2497
- `state subscription ${key}`,
2498
- () => {
2499
- unsubscribe2();
2500
- handleUpdate(update);
2501
- }
2502
- );
2503
- } else {
2504
- handleUpdate(update);
2505
- }
2506
- }
2507
- const state = withdraw(store, token);
2508
- store.logger.info(`\u{1F440}`, state.type, state.key, `Adding subscription "${key}"`);
2509
- const isSelector = state.type === `selector` || state.type === `readonly_selector`;
2510
- let dependencyUnsubFunctions = null;
2511
- let updateHandler = safelyHandleUpdate;
2512
- if (isSelector) {
2513
- dependencyUnsubFunctions = subscribeToRootAtoms(store, state);
2514
- updateHandler = (update) => {
2515
- if (dependencyUnsubFunctions) {
2516
- dependencyUnsubFunctions.length = 0;
2517
- dependencyUnsubFunctions.push(...subscribeToRootAtoms(store, state));
2518
- }
2519
- safelyHandleUpdate(update);
2520
- };
2521
- }
2522
- const mainUnsubFunction = state.subject.subscribe(key, updateHandler);
2523
- const unsubscribe = () => {
2524
- store.logger.info(
2525
- `\u{1F648}`,
2526
- state.type,
2527
- state.key,
2528
- `Removing subscription "${key}"`
2529
- );
2530
- mainUnsubFunction();
2531
- if (dependencyUnsubFunctions) {
2532
- for (const unsubFromDependency of dependencyUnsubFunctions) {
2533
- unsubFromDependency();
2534
- }
2535
- }
2536
- };
2537
- return unsubscribe;
2538
- }
2539
-
2540
- // ../atom.io/internal/src/subscribe/subscribe-to-timeline.ts
2541
- var subscribeToTimeline = (store, token, key, handleUpdate) => {
2542
- const tl = withdraw(store, token);
2543
- store.logger.info(`\u{1F440}`, `timeline`, token.key, `Adding subscription "${key}"`);
2544
- const unsubscribe = tl.subject.subscribe(key, handleUpdate);
2545
- return () => {
2546
- store.logger.info(
2547
- `\u{1F648}`,
2548
- `timeline`,
2549
- token.key,
2550
- `Removing subscription "${key}" from timeline`
2551
- );
2552
- unsubscribe();
2553
- };
2554
- };
2555
-
2556
- // ../atom.io/internal/src/mutable/tracker.ts
2557
- var Tracker = class {
2558
- Update;
2559
- initializeState(mutableState, store) {
2560
- const latestUpdateStateKey = `*${mutableState.key}`;
2561
- store.atoms.delete(latestUpdateStateKey);
2562
- store.valueMap.delete(latestUpdateStateKey);
2563
- const familyMetaData = mutableState.family ? {
2564
- key: `*${mutableState.family.key}`,
2565
- subKey: mutableState.family.subKey
2566
- } : void 0;
2567
- const latestUpdateState = createRegularAtom(
2568
- store,
2569
- {
2570
- key: latestUpdateStateKey,
2571
- default: null
2572
- },
2573
- familyMetaData
2574
- );
2575
- if (store.parent?.valueMap.has(latestUpdateStateKey)) {
2576
- const parentValue = store.parent.valueMap.get(latestUpdateStateKey);
2577
- store.valueMap.set(latestUpdateStateKey, parentValue);
2578
- }
2579
- return latestUpdateState;
2580
- }
2581
- unsubscribeFromInnerValue;
2582
- unsubscribeFromState;
2583
- observeCore(mutableState, latestUpdateState, target) {
2584
- const subscriptionKey = `tracker:${target.config.name}:${isChildStore(target) ? target.transactionMeta.update.key : `main`}:${mutableState.key}`;
2585
- const originalInnerValue = getFromStore(target, mutableState);
2586
- this.unsubscribeFromInnerValue = originalInnerValue.subscribe(
2587
- subscriptionKey,
2588
- (update) => {
2589
- setIntoStore(target, latestUpdateState, update);
2590
- }
2591
- );
2592
- this.unsubscribeFromState = subscribeToState(
2593
- target,
2594
- mutableState,
2595
- subscriptionKey,
2596
- (update) => {
2597
- if (update.newValue !== update.oldValue) {
2598
- this.unsubscribeFromInnerValue();
2599
- this.unsubscribeFromInnerValue = update.newValue.subscribe(
2600
- subscriptionKey,
2601
- (transceiverUpdate) => {
2602
- setIntoStore(target, latestUpdateState, transceiverUpdate);
2603
- }
2604
- );
2605
- }
2606
- }
2607
- );
2608
- }
2609
- updateCore(mutableState, latestUpdateState, target) {
2610
- const subscriptionKey = `tracker:${target.config.name}:${isChildStore(target) ? target.transactionMeta.update.key : `main`}:${mutableState.key}`;
2611
- subscribeToState(
2612
- target,
2613
- latestUpdateState,
2614
- subscriptionKey,
2615
- ({ newValue, oldValue }) => {
2616
- const timelineId = target.timelineTopics.getRelatedKey(
2617
- latestUpdateState.key
2618
- );
2619
- if (timelineId) {
2620
- const timelineData = target.timelines.get(timelineId);
2621
- if (timelineData?.timeTraveling) {
2622
- const unsubscribe2 = subscribeToTimeline(
2623
- target,
2624
- { key: timelineId, type: `timeline` },
2625
- subscriptionKey,
2626
- (update) => {
2627
- unsubscribe2();
2628
- setIntoStore(target, mutableState, (transceiver) => {
2629
- if (update === `redo` && newValue) {
2630
- transceiver.do(newValue);
2631
- } else if (update === `undo` && oldValue) {
2632
- transceiver.undo(oldValue);
2633
- }
2634
- return transceiver;
2635
- });
2636
- }
2637
- );
2638
- return;
2639
- }
2640
- }
2641
- const unsubscribe = target.on.operationClose.subscribe(
2642
- subscriptionKey,
2643
- () => {
2644
- unsubscribe();
2645
- const mutable = getFromStore(target, mutableState);
2646
- const updateNumber = newValue === null ? -1 : mutable.getUpdateNumber(newValue);
2647
- const eventOffset = updateNumber - mutable.cacheUpdateNumber;
2648
- if (newValue && eventOffset === 1) {
2649
- setIntoStore(
2650
- target,
2651
- mutableState,
2652
- (transceiver) => (transceiver.do(newValue), transceiver)
2653
- );
2654
- } else {
2655
- target.logger.info(
2656
- `\u274C`,
2657
- `mutable_atom`,
2658
- mutableState.key,
2659
- `could not be updated. Expected update number ${mutable.cacheUpdateNumber + 1}, but got ${updateNumber}`
2660
- );
2661
- }
2662
- }
2663
- );
2664
- }
2665
- );
2666
- }
2667
- mutableState;
2668
- latestUpdateState;
2669
- [Symbol.dispose];
2670
- constructor(mutableState, store) {
2671
- this.mutableState = mutableState;
2672
- const target = newest(store);
2673
- this.latestUpdateState = this.initializeState(mutableState, target);
2674
- this.observeCore(mutableState, this.latestUpdateState, target);
2675
- this.updateCore(mutableState, this.latestUpdateState, target);
2676
- target.trackers.set(mutableState.key, this);
2677
- this[Symbol.dispose] = () => {
2678
- this.unsubscribeFromInnerValue();
2679
- this.unsubscribeFromState();
2680
- target.trackers.delete(mutableState.key);
2681
- };
2682
- }
2683
- };
2684
-
2685
- // ../atom.io/internal/src/mutable/create-mutable-atom.ts
2686
- function createMutableAtom(store, options, family) {
2687
- store.logger.info(
2688
- `\u{1F528}`,
2689
- `atom`,
2690
- options.key,
2691
- `creating in store "${store.config.name}"`
2692
- );
2693
- const target = newest(store);
2694
- const existing = target.atoms.get(options.key);
2695
- if (existing && existing.type === `mutable_atom`) {
2696
- store.logger.error(
2697
- `\u274C`,
2698
- `atom`,
2699
- options.key,
2700
- `Tried to create atom, but it already exists in the store.`
2701
- );
2702
- return deposit(existing);
2703
- }
2704
- const subject = new Subject();
2705
- const newAtom = {
2706
- ...options,
2707
- type: `mutable_atom`,
2708
- install: (s) => {
2709
- s.logger.info(
2710
- `\u{1F6E0}\uFE0F`,
2711
- `atom`,
2712
- options.key,
2713
- `installing in store "${s.config.name}"`
2714
- );
2715
- return createMutableAtom(s, options, family);
2716
- },
2717
- subject
2718
- };
2719
- if (family) {
2720
- newAtom.family = family;
2721
- }
2722
- const initialValue = options.default();
2723
- target.atoms.set(newAtom.key, newAtom);
2724
- markAtomAsDefault(store, options.key);
2725
- cacheValue(target, options.key, initialValue, subject);
2726
- const token = deposit(newAtom);
2727
- if (options.effects) {
2728
- let effectIndex = 0;
2729
- const cleanupFunctions = [];
2730
- for (const effect of options.effects) {
2731
- const cleanup = effect({
2732
- setSelf: (next) => {
2733
- setIntoStore(store, token, next);
2734
- },
2735
- onSet: (handle) => subscribeToState(store, token, `effect[${effectIndex}]`, handle)
2736
- });
2737
- if (cleanup) {
2738
- cleanupFunctions.push(cleanup);
2739
- }
2740
- ++effectIndex;
2741
- }
2742
- newAtom.cleanup = () => {
2743
- for (const cleanup of cleanupFunctions) {
2744
- cleanup();
2745
- }
2746
- };
2747
- }
2748
- new Tracker(token, store);
2749
- if (!family) {
2750
- selectJson(token, options, store);
2751
- }
2752
- return token;
2753
- }
2754
-
2755
- // ../atom.io/internal/src/mutable/tracker-family.ts
2756
- var FamilyTracker = class {
2757
- trackers = /* @__PURE__ */ new Map();
2758
- Update;
2759
- latestUpdateAtoms;
2760
- mutableAtoms;
2761
- constructor(mutableAtoms, store) {
2762
- const updateAtoms = createRegularAtomFamily(
2763
- store,
2764
- {
2765
- key: `*${mutableAtoms.key}`,
2766
- default: null
2767
- },
2768
- [`mutable`, `updates`]
2769
- );
2770
- this.latestUpdateAtoms = withdraw(store, updateAtoms);
2771
- this.mutableAtoms = mutableAtoms;
2772
- this.mutableAtoms.subject.subscribe(
2773
- `store=${store.config.name}::tracker-atom-family`,
2774
- (event) => {
2775
- const { type, token } = event;
2776
- if (token.family) {
2777
- const key = parseJson(token.family.subKey);
2778
- switch (type) {
2779
- case `state_creation`:
2780
- this.trackers.set(key, new Tracker(token, store));
2781
- break;
2782
- case `state_disposal`:
2783
- {
2784
- const tracker = this.trackers.get(key);
2785
- if (tracker) {
2786
- tracker[Symbol.dispose]();
2787
- this.trackers.delete(key);
2788
- }
2789
- }
2790
- break;
2791
- }
2792
- }
2793
- }
2794
- );
2795
- }
2796
- };
2797
-
2798
- // ../atom.io/internal/src/mutable/create-mutable-atom-family.ts
2799
- function createMutableAtomFamily(store, options, internalRoles) {
2800
- const familyToken = {
2801
- key: options.key,
2802
- type: `mutable_atom_family`
2803
- };
2804
- const existing = store.families.get(options.key);
2805
- if (existing) {
2806
- store.logger.error(
2807
- `\u2757`,
2808
- `mutable_atom_family`,
2809
- options.key,
2810
- `Overwriting an existing ${prettyPrintTokenType(
2811
- existing
2812
- )} "${existing.key}" in store "${store.config.name}". You can safely ignore this warning if it is due to hot module replacement.`
2813
- );
2814
- }
2815
- const subject = new Subject();
2816
- const familyFunction = (key) => {
2817
- const subKey = stringifyJson(key);
2818
- const family = { key: options.key, subKey };
2819
- const fullKey = `${options.key}(${subKey})`;
2820
- const target = newest(store);
2821
- const individualOptions = {
2822
- key: fullKey,
2823
- default: () => options.default(key),
2824
- toJson: options.toJson,
2825
- fromJson: options.fromJson,
2826
- mutable: true
2827
- };
2828
- if (options.effects) {
2829
- individualOptions.effects = options.effects(key);
2830
- }
2831
- const token = createMutableAtom(target, individualOptions, family);
2832
- subject.next({ type: `state_creation`, token });
2833
- return token;
2834
- };
2835
- const atomFamily2 = Object.assign(familyFunction, familyToken, {
2836
- subject,
2837
- install: (s) => createMutableAtomFamily(s, options),
2838
- toJson: options.toJson,
2839
- fromJson: options.fromJson,
2840
- internalRoles
2841
- });
2842
- store.families.set(options.key, atomFamily2);
2843
- selectJsonFamily(store, atomFamily2, options);
2844
- new FamilyTracker(atomFamily2, store);
2845
- return familyToken;
2846
- }
2847
-
2848
- // ../atom.io/internal/src/mutable/get-json-family.ts
2849
- var getJsonFamily = (mutableAtomFamily, store) => {
2850
- const target = newest(store);
2851
- const key = `${mutableAtomFamily.key}:JSON`;
2852
- const jsonFamily = target.families.get(key);
2853
- return jsonFamily;
2854
- };
2855
-
2856
- // ../atom.io/internal/src/mutable/get-json-token.ts
2857
- var getJsonToken = (store, mutableAtomToken) => {
2858
- if (mutableAtomToken.family) {
2859
- const target = newest(store);
2860
- const jsonFamilyKey = `${mutableAtomToken.family.key}:JSON`;
2861
- const jsonFamilyToken = {
2862
- key: jsonFamilyKey,
2863
- type: `selector_family`
2864
- };
2865
- const family = withdraw(target, jsonFamilyToken);
2866
- const subKey = JSON.parse(mutableAtomToken.family.subKey);
2867
- const jsonToken = findInStore(store, family, subKey);
2868
- return jsonToken;
2869
- }
2870
- const token = {
2871
- type: `selector`,
2872
- key: `${mutableAtomToken.key}:JSON`
2873
- };
2874
- return token;
2875
- };
2876
-
2877
- // ../atom.io/internal/src/mutable/get-update-token.ts
2878
- var getUpdateToken = (mutableAtomToken) => {
2879
- const key = `*${mutableAtomToken.key}`;
2880
- const updateToken = { type: `atom`, key };
2881
- if (mutableAtomToken.family) {
2882
- updateToken.family = {
2883
- key: `*${mutableAtomToken.family.key}`,
2884
- subKey: mutableAtomToken.family.subKey
2885
- };
2886
- }
2887
- return updateToken;
2888
- };
2889
-
2890
- // ../atom.io/internal/src/mutable/transceiver.ts
2891
- function isTransceiver(value) {
2892
- return typeof value === `object` && value !== null && `do` in value && `undo` in value && `subscribe` in value;
2893
- }
2894
-
2895
- // ../atom.io/internal/src/set-state/copy-mutable-if-needed.ts
2896
- function copyMutableIfNeeded(target, atom2, origin) {
2897
- const originValue = origin.valueMap.get(atom2.key);
2898
- const targetValue = target.valueMap.get(atom2.key);
2899
- if (originValue !== targetValue) {
2900
- return targetValue;
2901
- }
2902
- if (originValue === void 0) {
2903
- return atom2.default();
2904
- }
2905
- origin.logger.info(`\u{1F4C3}`, `atom`, atom2.key, `copying`);
2906
- const jsonValue = atom2.toJson(originValue);
2907
- const copiedValue = atom2.fromJson(jsonValue);
2908
- target.valueMap.set(atom2.key, copiedValue);
2909
- new Tracker(atom2, origin);
2910
- return copiedValue;
2911
- }
2912
-
2913
- // ../atom.io/internal/src/caching.ts
2914
- function cacheValue(target, key, value, subject) {
2915
- const currentValue = target.valueMap.get(key);
2916
- if (currentValue instanceof Future) {
2917
- const future = currentValue;
2918
- future.use(value);
2919
- }
2920
- if (value instanceof Promise) {
2921
- const future = new Future(value);
2922
- target.valueMap.set(key, future);
2923
- future.then((resolved) => {
2924
- cacheValue(target, key, resolved, subject);
2925
- subject.next({ newValue: resolved, oldValue: future });
2926
- }).catch((thrown) => {
2927
- target.logger.error(`\u{1F4A5}`, `state`, key, `rejected:`, thrown);
2928
- });
2929
- return future;
2930
- }
2931
- target.valueMap.set(key, value);
2932
- return value;
2933
- }
2934
- var readCachedValue = (token, target) => {
2935
- let value = target.valueMap.get(token.key);
2936
- if (token.type === `mutable_atom` && isChildStore(target)) {
2937
- const { parent } = target;
2938
- const copiedValue = copyMutableIfNeeded(target, token, parent);
2939
- value = copiedValue;
2940
- }
2941
- return value;
2942
- };
2943
- var evictCachedValue = (key, target) => {
2944
- const currentValue = target.valueMap.get(key);
2945
- if (currentValue instanceof Future) {
2946
- const future = currentValue;
2947
- const selector = target.selectors.get(key) ?? target.readonlySelectors.get(key);
2948
- if (selector) {
2949
- future.use(selector.get());
2950
- }
2951
- return;
2952
- }
2953
- if (target.operation.open) {
2954
- target.operation.prev.set(key, currentValue);
2955
- }
2956
- target.valueMap.delete(key);
2957
- target.logger.info(`\u{1F5D1}`, `state`, key, `evicted`);
2958
- };
2959
-
2960
- // ../atom.io/internal/src/atom/is-default.ts
2961
- var isAtomDefault = (store, key) => {
2962
- const core = newest(store);
2963
- return core.atomsThatAreDefault.has(key);
2964
- };
2965
- var markAtomAsDefault = (store, key) => {
2966
- const core = newest(store);
2967
- core.atomsThatAreDefault = new Set(core.atomsThatAreDefault).add(key);
2968
- };
2969
- var markAtomAsNotDefault = (store, key) => {
2970
- const core = newest(store);
2971
- core.atomsThatAreDefault = new Set(newest(store).atomsThatAreDefault);
2972
- core.atomsThatAreDefault.delete(key);
2973
- };
2974
-
2975
- // ../atom.io/internal/src/atom/create-regular-atom.ts
2976
- function createRegularAtom(store, options, family) {
2977
- store.logger.info(
2978
- `\u{1F528}`,
2979
- `atom`,
2980
- options.key,
2981
- `creating in store "${store.config.name}"`
2982
- );
2983
- const target = newest(store);
2984
- const existing = target.atoms.get(options.key);
2985
- if (existing && existing.type === `atom`) {
2986
- store.logger.error(
2987
- `\u274C`,
2988
- `atom`,
2989
- options.key,
2990
- `Tried to create atom, but it already exists in the store.`
2991
- );
2992
- return deposit(existing);
2993
- }
2994
- const subject = new Subject();
2995
- const newAtom = {
2996
- ...options,
2997
- type: `atom`,
2998
- install: (s) => {
2999
- s.logger.info(
3000
- `\u{1F6E0}\uFE0F`,
3001
- `atom`,
3002
- options.key,
3003
- `installing in store "${s.config.name}"`
3004
- );
3005
- return createRegularAtom(s, options, family);
3006
- },
3007
- subject
3008
- };
3009
- if (family) {
3010
- newAtom.family = family;
3011
- }
3012
- let initialValue = options.default;
3013
- if (options.default instanceof Function) {
3014
- initialValue = options.default();
3015
- }
3016
- target.atoms.set(newAtom.key, newAtom);
3017
- markAtomAsDefault(store, options.key);
3018
- cacheValue(target, options.key, initialValue, subject);
3019
- const token = deposit(newAtom);
3020
- if (options.effects) {
3021
- let effectIndex = 0;
3022
- const cleanupFunctions = [];
3023
- for (const effect of options.effects) {
3024
- const cleanup = effect({
3025
- setSelf: (next) => {
3026
- setIntoStore(store, token, next);
3027
- },
3028
- onSet: (handle) => subscribeToState(store, token, `effect[${effectIndex}]`, handle)
3029
- });
3030
- if (cleanup) {
3031
- cleanupFunctions.push(cleanup);
3032
- }
3033
- ++effectIndex;
3034
- }
3035
- newAtom.cleanup = () => {
3036
- for (const cleanup of cleanupFunctions) {
3037
- cleanup();
3038
- }
3039
- };
3040
- }
3041
- return token;
3042
- }
3043
-
3044
- // ../atom.io/internal/src/atom/create-standalone-atom.ts
3045
- function createStandaloneAtom(store, options) {
3046
- const isMutable = `mutable` in options;
3047
- if (isMutable) {
3048
- const state2 = createMutableAtom(store, options, void 0);
3049
- store.on.atomCreation.next(state2);
3050
- return state2;
3051
- }
3052
- const state = createRegularAtom(store, options, void 0);
3053
- store.on.atomCreation.next(state);
3054
- return state;
3055
- }
3056
-
3057
- // ../atom.io/internal/src/atom/dispose-atom.ts
3058
- function disposeAtom(store, atomToken) {
3059
- const target = newest(store);
3060
- const { key, family } = atomToken;
3061
- const atom2 = withdraw(target, atomToken);
3062
- if (!family) {
3063
- store.logger.error(`\u274C`, `atom`, key, `Standalone atoms cannot be disposed.`);
3064
- } else {
3065
- atom2.cleanup?.();
3066
- const lastValue = store.valueMap.get(atom2.key);
3067
- const atomFamily2 = withdraw(store, { key: family.key, type: `atom_family` });
3068
- const disposal = {
3069
- type: `state_disposal`,
3070
- subType: `atom`,
3071
- token: atomToken,
3072
- value: lastValue
3073
- };
3074
- atomFamily2.subject.next(disposal);
3075
- const isChild = isChildStore(target);
3076
- target.atoms.delete(key);
3077
- target.valueMap.delete(key);
3078
- target.selectorAtoms.delete(key);
3079
- target.atomsThatAreDefault.delete(key);
3080
- store.timelineTopics.delete(key);
3081
- if (atomToken.type === `mutable_atom`) {
3082
- const updateToken = getUpdateToken(atomToken);
3083
- disposeAtom(store, updateToken);
3084
- store.trackers.delete(key);
3085
- }
3086
- store.logger.info(`\u{1F525}`, `atom`, key, `deleted`);
3087
- if (isChild && target.transactionMeta.phase === `building`) {
3088
- const mostRecentUpdate = target.transactionMeta.update.updates.at(-1);
3089
- const wasMoleculeDisposal = mostRecentUpdate?.type === `molecule_disposal`;
3090
- const updateAlreadyCaptured = wasMoleculeDisposal && mostRecentUpdate.values.some(([k]) => k === atom2.family?.key);
3091
- if (!updateAlreadyCaptured) {
3092
- target.transactionMeta.update.updates.push(disposal);
3093
- }
3094
- } else {
3095
- store.on.atomDisposal.next(atomToken);
3096
- }
3097
- }
3098
- }
3099
-
3100
- // ../atom.io/transceivers/set-rtx/src/set-rtx.ts
3101
- var SetRTX = class _SetRTX extends Set {
3102
- mode = `record`;
3103
- subject = new Subject();
3104
- cacheLimit = 0;
3105
- cache = [];
3106
- cacheIdx = -1;
3107
- cacheUpdateNumber = -1;
3108
- constructor(values, cacheLimit = 0) {
3109
- super(values);
3110
- if (values instanceof _SetRTX) {
3111
- this.parent = values;
3112
- this.cacheUpdateNumber = values.cacheUpdateNumber;
3113
- }
3114
- if (cacheLimit) {
3115
- this.cacheLimit = cacheLimit;
3116
- this.cache = new Array(cacheLimit);
3117
- this.subscribe(`auto cache`, (update) => {
3118
- this.cacheIdx++;
3119
- this.cacheIdx %= this.cacheLimit;
3120
- this.cache[this.cacheIdx] = update;
3121
- });
3122
- }
3123
- }
3124
- toJSON() {
3125
- return {
3126
- members: [...this],
3127
- cache: this.cache,
3128
- cacheLimit: this.cacheLimit,
3129
- cacheIdx: this.cacheIdx,
3130
- cacheUpdateNumber: this.cacheUpdateNumber
3131
- };
3132
- }
3133
- static fromJSON(json) {
3134
- const set = new _SetRTX(json.members, json.cacheLimit);
3135
- set.cache = json.cache;
3136
- set.cacheIdx = json.cacheIdx;
3137
- set.cacheUpdateNumber = json.cacheUpdateNumber;
3138
- return set;
3139
- }
3140
- add(value) {
3141
- const result = super.add(value);
3142
- if (this.mode === `record`) {
3143
- this.cacheUpdateNumber++;
3144
- this.emit(`add:${stringifyJson(value)}`);
3145
- }
3146
- return result;
3147
- }
3148
- clear() {
3149
- const capturedContents = this.mode === `record` ? [...this] : null;
3150
- super.clear();
3151
- if (capturedContents) {
3152
- this.cacheUpdateNumber++;
3153
- this.emit(`clear:${JSON.stringify(capturedContents)}`);
3154
- }
3155
- }
3156
- delete(value) {
3157
- const result = super.delete(value);
3158
- if (this.mode === `record`) {
3159
- this.cacheUpdateNumber++;
3160
- this.emit(`del:${stringifyJson(value)}`);
3161
- }
3162
- return result;
3163
- }
3164
- parent;
3165
- child = null;
3166
- transactionUpdates = null;
3167
- transaction(run) {
3168
- this.mode = `transaction`;
3169
- this.transactionUpdates = [];
3170
- this.child = new _SetRTX(this);
3171
- const unsubscribe = this.child._subscribe(`transaction`, (update) => {
3172
- this.transactionUpdates?.push(update);
3173
- });
3174
- try {
3175
- const shouldCommit = run(this.child);
3176
- if (shouldCommit) {
3177
- for (const update of this.transactionUpdates) {
3178
- this.doStep(update);
3179
- }
3180
- this.cacheUpdateNumber++;
3181
- this.emit(`tx:${this.transactionUpdates.join(`;`)}`);
3182
- }
3183
- } catch (thrown) {
3184
- console.warn(
3185
- `Did not apply transaction to SetRTX; this error was thrown:`,
3186
- thrown
3187
- );
3188
- throw thrown;
3189
- } finally {
3190
- unsubscribe();
3191
- this.child = null;
3192
- this.transactionUpdates = null;
3193
- this.mode = `record`;
3194
- }
3195
- }
3196
- _subscribe(key, fn) {
3197
- return this.subject.subscribe(key, fn);
3198
- }
3199
- subscribe(key, fn) {
3200
- return this.subject.subscribe(key, (update) => {
3201
- fn(`${this.cacheUpdateNumber}=${update}`);
3202
- });
3203
- }
3204
- emit(update) {
3205
- this.subject.next(update);
3206
- }
3207
- doStep(update) {
3208
- const typeValueBreak = update.indexOf(`:`);
3209
- const type = update.substring(0, typeValueBreak);
3210
- const value = update.substring(typeValueBreak + 1);
3211
- switch (type) {
3212
- case `add`:
3213
- this.add(JSON.parse(value));
3214
- break;
3215
- case `clear`:
3216
- this.clear();
3217
- break;
3218
- case `del`:
3219
- this.delete(JSON.parse(value));
3220
- break;
3221
- case `tx`:
3222
- for (const subUpdate of value.split(`;`)) {
3223
- this.doStep(subUpdate);
3224
- }
3225
- }
3226
- }
3227
- getUpdateNumber(update) {
3228
- const breakpoint = update.indexOf(`=`);
3229
- return Number(update.substring(0, breakpoint));
3230
- }
3231
- do(update) {
3232
- const breakpoint = update.indexOf(`=`);
3233
- const updateNumber = Number(update.substring(0, breakpoint));
3234
- const eventOffset = updateNumber - this.cacheUpdateNumber;
3235
- const isFuture = eventOffset > 0;
3236
- if (isFuture) {
3237
- if (eventOffset === 1) {
3238
- this.mode = `playback`;
3239
- const innerUpdate = update.substring(breakpoint + 1);
3240
- this.doStep(innerUpdate);
3241
- this.mode = `record`;
3242
- this.cacheUpdateNumber = updateNumber;
3243
- return null;
3244
- }
3245
- return this.cacheUpdateNumber + 1;
3246
- }
3247
- if (Math.abs(eventOffset) < this.cacheLimit) {
3248
- const eventIdx = this.cacheIdx + eventOffset;
3249
- const cachedUpdate = this.cache[eventIdx];
3250
- if (cachedUpdate === update) {
3251
- return null;
3252
- }
3253
- this.mode = `playback`;
3254
- let done = false;
3255
- while (!done) {
3256
- this.cacheIdx %= this.cacheLimit;
3257
- const u = this.cache[this.cacheIdx];
3258
- this.cacheIdx--;
3259
- if (!u) {
3260
- return `OUT_OF_RANGE`;
3261
- }
3262
- this.undo(u);
3263
- done = this.cacheIdx === eventIdx - 1;
3264
- }
3265
- const innerUpdate = update.substring(breakpoint + 1);
3266
- this.doStep(innerUpdate);
3267
- this.mode = `record`;
3268
- this.cacheUpdateNumber = updateNumber;
3269
- return null;
3270
- }
3271
- return `OUT_OF_RANGE`;
3272
- }
3273
- undoStep(update) {
3274
- const breakpoint = update.indexOf(`:`);
3275
- const type = update.substring(0, breakpoint);
3276
- const value = update.substring(breakpoint + 1);
3277
- switch (type) {
3278
- case `add`:
3279
- this.delete(JSON.parse(value));
3280
- break;
3281
- case `del`:
3282
- this.add(JSON.parse(value));
3283
- break;
3284
- case `clear`: {
3285
- const values = JSON.parse(value);
3286
- for (const v of values) this.add(v);
3287
- break;
3288
- }
3289
- case `tx`: {
3290
- const updates = value.split(`;`);
3291
- for (let i = updates.length - 1; i >= 0; i--) {
3292
- this.undoStep(updates[i]);
3293
- }
3294
- }
3295
- }
3296
- }
3297
- undo(update) {
3298
- const breakpoint = update.indexOf(`=`);
3299
- const updateNumber = Number(update.substring(0, breakpoint));
3300
- if (updateNumber === this.cacheUpdateNumber) {
3301
- this.mode = `playback`;
3302
- const innerUpdate = update.substring(breakpoint + 1);
3303
- this.undoStep(innerUpdate);
3304
- this.mode = `record`;
3305
- this.cacheUpdateNumber--;
3306
- return null;
3307
- }
3308
- return this.cacheUpdateNumber;
3309
- }
3310
- };
3311
-
3312
- // ../atom.io/internal/src/join/join-internal.ts
3313
- var Join = class {
3314
- toolkit;
3315
- options;
3316
- defaultContent;
3317
- molecules = /* @__PURE__ */ new Map();
3318
- relations;
3319
- states;
3320
- core;
3321
- transact(toolkit, run) {
3322
- const originalToolkit = this.toolkit;
3323
- this.toolkit = toolkit;
3324
- run(this);
3325
- this.toolkit = originalToolkit;
3326
- }
3327
- store;
3328
- realm;
3329
- [Symbol.dispose]() {
3330
- }
3331
- constructor(options, defaultContent, store = IMPLICIT.STORE) {
3332
- this.store = store;
3333
- this.realm = new Anarchy(store);
3334
- this.options = options;
3335
- this.defaultContent = defaultContent;
3336
- this.store.miscResources.set(`join:${options.key}`, this);
3337
- this.realm.allocate(`root`, options.key);
3338
- this.toolkit = {
3339
- get: (...ps) => getFromStore(store, ...ps),
3340
- set: (...ps) => {
3341
- setIntoStore(store, ...ps);
3342
- },
3343
- find: (...ps) => findInStore(store, ...ps),
3344
- json: (token) => getJsonToken(store, token)
3345
- };
3346
- const aSide = options.between[0];
3347
- const bSide = options.between[1];
3348
- const relatedKeysAtoms = createMutableAtomFamily(
3349
- store,
3350
- {
3351
- key: `${options.key}/relatedKeys`,
3352
- default: () => new SetRTX(),
3353
- mutable: true,
3354
- fromJson: (json) => SetRTX.fromJSON(json),
3355
- toJson: (set) => set.toJSON()
3356
- },
3357
- [`join`, `relations`]
3358
- );
3359
- this.core = { relatedKeysAtoms };
3360
- const getRelatedKeys = ({ get }, key) => get(relatedKeysAtoms, key);
3361
- const addRelation = ({ set }, a, b) => {
3362
- if (!this.store.molecules.has(stringifyJson(a))) {
3363
- this.realm.allocate(options.key, a);
3364
- }
3365
- set(relatedKeysAtoms, a, (aKeys) => aKeys.add(b));
3366
- set(relatedKeysAtoms, b, (bKeys) => bKeys.add(a));
3367
- };
3368
- const deleteRelation = ({ set }, a, b) => {
3369
- set(relatedKeysAtoms, a, (aKeys) => {
3370
- aKeys.delete(b);
3371
- return aKeys;
3372
- });
3373
- set(relatedKeysAtoms, b, (bKeys) => {
3374
- bKeys.delete(a);
3375
- return bKeys;
3376
- });
3377
- };
3378
- const replaceRelationsSafely = (toolkit, a, newRelationsOfA) => {
3379
- const { find, get, set } = toolkit;
3380
- const relationsOfAState = find(relatedKeysAtoms, a);
3381
- const currentRelationsOfA = get(relationsOfAState);
3382
- for (const currentRelationB of currentRelationsOfA) {
3383
- const remainsRelated = newRelationsOfA.includes(currentRelationB);
3384
- if (remainsRelated) {
3385
- continue;
3386
- }
3387
- set(relatedKeysAtoms, currentRelationB, (relationsOfB) => {
3388
- relationsOfB.delete(a);
3389
- return relationsOfB;
3390
- });
3391
- }
3392
- set(relationsOfAState, (relationsOfA) => {
3393
- relationsOfA.transaction((nextRelationsOfA) => {
3394
- nextRelationsOfA.clear();
3395
- for (const newRelationB of newRelationsOfA) {
3396
- const relationsOfB = getRelatedKeys(toolkit, newRelationB);
3397
- const newRelationBIsAlreadyRelated = relationsOfB.has(a);
3398
- if (this.relations.cardinality === `1:n`) {
3399
- const previousOwnersToDispose = [];
3400
- for (const previousOwner of relationsOfB) {
3401
- if (previousOwner === a) {
3402
- continue;
3403
- }
3404
- const previousOwnerRelations = getRelatedKeys(
3405
- toolkit,
3406
- previousOwner
3407
- );
3408
- previousOwnerRelations.delete(newRelationB);
3409
- if (previousOwnerRelations.size === 0) {
3410
- previousOwnersToDispose.push(previousOwner);
3411
- }
3412
- }
3413
- if (!newRelationBIsAlreadyRelated && relationsOfB.size > 0) {
3414
- relationsOfB.clear();
3415
- }
3416
- for (const previousOwner of previousOwnersToDispose) {
3417
- const sorted = [newRelationB, previousOwner].sort();
3418
- const compositeKey = `"${sorted[0]}:${sorted[1]}"`;
3419
- this.molecules.delete(compositeKey);
3420
- }
3421
- }
3422
- if (!newRelationBIsAlreadyRelated) {
3423
- relationsOfB.add(a);
3424
- }
3425
- nextRelationsOfA.add(newRelationB);
3426
- }
3427
- return true;
3428
- });
3429
- return relationsOfA;
3430
- });
3431
- };
3432
- const replaceRelationsUnsafely = (toolkit, a, newRelationsOfA) => {
3433
- const { set } = toolkit;
3434
- set(relatedKeysAtoms, a, (relationsOfA) => {
3435
- relationsOfA.transaction((nextRelationsOfA) => {
3436
- for (const newRelationB of newRelationsOfA) {
3437
- nextRelationsOfA.add(newRelationB);
3438
- }
3439
- return true;
3440
- });
3441
- return relationsOfA;
3442
- });
3443
- for (const newRelationB of newRelationsOfA) {
3444
- set(relatedKeysAtoms, newRelationB, (newRelationsB) => {
3445
- newRelationsB.add(a);
3446
- return newRelationsB;
3447
- });
3448
- }
3449
- return true;
3450
- };
3451
- const has = (toolkit, a, b) => {
3452
- const aKeys = getRelatedKeys(toolkit, a);
3453
- return b ? aKeys.has(b) : aKeys.size > 0;
3454
- };
3455
- const baseExternalStoreConfiguration = {
3456
- getRelatedKeys: (key) => getRelatedKeys(this.toolkit, key),
3457
- addRelation: (a, b) => {
3458
- this.store.moleculeJoins.set(
3459
- a,
3460
- options.key
3461
- );
3462
- this.store.moleculeJoins.set(
3463
- b,
3464
- options.key
3465
- );
3466
- addRelation(this.toolkit, a, b);
3467
- },
3468
- deleteRelation: (a, b) => {
3469
- deleteRelation(this.toolkit, a, b);
3470
- },
3471
- replaceRelationsSafely: (a, bs) => {
3472
- replaceRelationsSafely(this.toolkit, a, bs);
3473
- },
3474
- replaceRelationsUnsafely: (a, bs) => {
3475
- replaceRelationsUnsafely(this.toolkit, a, bs);
3476
- },
3477
- has: (a, b) => has(this.toolkit, a, b)
3478
- };
3479
- let externalStore;
3480
- let contentAtoms;
3481
- if (defaultContent) {
3482
- contentAtoms = createRegularAtomFamily(
3483
- store,
3484
- {
3485
- key: `${options.key}/content`,
3486
- default: defaultContent
3487
- },
3488
- [`join`, `content`]
3489
- );
3490
- const getContent = ({ get }, key) => get(contentAtoms, key);
3491
- const setContent = ({ set }, key, content) => {
3492
- set(contentAtoms, key, content);
3493
- };
3494
- const externalStoreWithContentConfiguration = {
3495
- getContent: (contentKey) => {
3496
- const content = getContent(this.toolkit, contentKey);
3497
- return content;
3498
- },
3499
- setContent: (contentKey, content) => {
3500
- setContent(this.toolkit, contentKey, content);
3501
- },
3502
- deleteContent: (contentKey) => {
3503
- this.realm.deallocate(contentKey);
3504
- }
3505
- };
3506
- externalStore = Object.assign(
3507
- baseExternalStoreConfiguration,
3508
- externalStoreWithContentConfiguration
3509
- );
3510
- } else {
3511
- externalStore = baseExternalStoreConfiguration;
3512
- }
3513
- const relations = new Junction(
3514
- options,
3515
- {
3516
- externalStore,
3517
- isAType: options.isAType,
3518
- isBType: options.isBType,
3519
- makeContentKey: (...args) => {
3520
- const [a, b] = args;
3521
- const sorted = args.sort();
3522
- const compositeKey = `${sorted[0]}:${sorted[1]}`;
3523
- const aMolecule = store.molecules.get(stringifyJson(a));
3524
- const bMolecule = store.molecules.get(stringifyJson(b));
3525
- if (!aMolecule) {
3526
- this.realm.allocate(options.key, a);
3527
- }
3528
- if (!bMolecule) {
3529
- this.realm.allocate(options.key, b);
3530
- }
3531
- this.realm.allocate(a, compositeKey, `all`);
3532
- this.realm.claim(b, compositeKey);
3533
- this.store.moleculeJoins.set(compositeKey, options.key);
3534
- return compositeKey;
3535
- }
3536
- }
3537
- );
3538
- const createSingleKeySelectorFamily = () => createReadonlySelectorFamily(
3539
- store,
3540
- {
3541
- key: `${options.key}/singleRelatedKey`,
3542
- get: (key) => ({ get }) => {
3543
- const relatedKeys = get(relatedKeysAtoms, key);
3544
- for (const relatedKey of relatedKeys) {
3545
- return relatedKey;
3546
- }
3547
- return null;
3548
- }
3549
- },
3550
- [`join`, `keys`]
3551
- );
3552
- const getMultipleKeySelectorFamily = () => {
3553
- return createReadonlySelectorFamily(
3554
- store,
3555
- {
3556
- key: `${options.key}/multipleRelatedKeys`,
3557
- get: (key) => ({ get }) => {
3558
- const jsonFamily = getJsonFamily(relatedKeysAtoms, store);
3559
- const json = get(jsonFamily, key);
3560
- return json.members;
3561
- }
3562
- },
3563
- [`join`, `keys`]
3564
- );
3565
- };
3566
- const createSingleEntrySelectorFamily = () => createReadonlySelectorFamily(
3567
- store,
3568
- {
3569
- key: `${options.key}/singleRelatedEntry`,
3570
- get: (x) => ({ get }) => {
3571
- const relatedKeys = get(relatedKeysAtoms, x);
3572
- for (const y of relatedKeys) {
3573
- let a = relations.isAType?.(x) ? x : void 0;
3574
- let b = a === void 0 ? x : void 0;
3575
- a ??= y;
3576
- b ??= y;
3577
- const contentKey = relations.makeContentKey(a, b);
3578
- const content = get(contentAtoms, contentKey);
3579
- return [y, content];
3580
- }
3581
- return null;
3582
- }
3583
- },
3584
- [`join`, `entries`]
3585
- );
3586
- const getMultipleEntrySelectorFamily = () => createReadonlySelectorFamily(
3587
- store,
3588
- {
3589
- key: `${options.key}/multipleRelatedEntries`,
3590
- get: (x) => ({ get }) => {
3591
- const jsonFamily = getJsonFamily(relatedKeysAtoms, store);
3592
- const json = get(jsonFamily, x);
3593
- return json.members.map((y) => {
3594
- let a = relations.isAType?.(x) ? x : void 0;
3595
- let b = a === void 0 ? x : void 0;
3596
- a ??= y;
3597
- b ??= y;
3598
- const contentKey = relations.makeContentKey(a, b);
3599
- const content = get(contentAtoms, contentKey);
3600
- return [y, content];
3601
- });
3602
- }
3603
- },
3604
- [`join`, `entries`]
3605
- );
3606
- switch (options.cardinality) {
3607
- case `1:1`: {
3608
- const singleRelatedKeySelectors = createSingleKeySelectorFamily();
3609
- const stateKeyA = `${aSide}KeyOf${capitalize(bSide)}`;
3610
- const stateKeyB = `${bSide}KeyOf${capitalize(aSide)}`;
3611
- const baseStates = {
3612
- [stateKeyA]: singleRelatedKeySelectors,
3613
- [stateKeyB]: singleRelatedKeySelectors
3614
- };
3615
- let states;
3616
- if (defaultContent) {
3617
- const singleEntrySelectors = createSingleEntrySelectorFamily();
3618
- const entriesStateKeyA = `${aSide}EntryOf${capitalize(bSide)}`;
3619
- const entriesStateKeyB = `${bSide}EntryOf${capitalize(aSide)}`;
3620
- const contentStates = {
3621
- [entriesStateKeyA]: singleEntrySelectors,
3622
- [entriesStateKeyB]: singleEntrySelectors
3623
- };
3624
- states = Object.assign(baseStates, contentStates);
3625
- } else {
3626
- states = baseStates;
3627
- }
3628
- this.relations = relations;
3629
- this.states = states;
3630
- break;
3631
- }
3632
- case `1:n`: {
3633
- const singleRelatedKeySelectors = createSingleKeySelectorFamily();
3634
- const multipleRelatedKeysSelectors = getMultipleKeySelectorFamily();
3635
- const stateKeyA = `${aSide}KeyOf${capitalize(bSide)}`;
3636
- const stateKeyB = `${bSide}KeysOf${capitalize(aSide)}`;
3637
- const baseStates = {
3638
- [stateKeyA]: singleRelatedKeySelectors,
3639
- [stateKeyB]: multipleRelatedKeysSelectors
3640
- };
3641
- let states;
3642
- if (defaultContent) {
3643
- const singleRelatedEntrySelectors = createSingleEntrySelectorFamily();
3644
- const multipleRelatedEntriesSelectors = getMultipleEntrySelectorFamily();
3645
- const entriesStateKeyA = `${aSide}EntryOf${capitalize(bSide)}`;
3646
- const entriesStateKeyB = `${bSide}EntriesOf${capitalize(
3647
- aSide
3648
- )}`;
3649
- const contentStates = {
3650
- [entriesStateKeyA]: singleRelatedEntrySelectors,
3651
- [entriesStateKeyB]: multipleRelatedEntriesSelectors
3652
- };
3653
- states = Object.assign(baseStates, contentStates);
3654
- } else {
3655
- states = baseStates;
3656
- }
3657
- this.relations = relations;
3658
- this.states = states;
3659
- break;
3660
- }
3661
- case `n:n`: {
3662
- const multipleRelatedKeysSelectors = getMultipleKeySelectorFamily();
3663
- const stateKeyA = `${aSide}KeysOf${capitalize(bSide)}`;
3664
- const stateKeyB = `${bSide}KeysOf${capitalize(aSide)}`;
3665
- const baseStates = {
3666
- [stateKeyA]: multipleRelatedKeysSelectors,
3667
- [stateKeyB]: multipleRelatedKeysSelectors
3668
- };
3669
- let states;
3670
- if (defaultContent) {
3671
- const multipleRelatedEntriesSelectors = getMultipleEntrySelectorFamily();
3672
- const entriesStateKeyA = `${aSide}EntriesOf${capitalize(
3673
- bSide
3674
- )}`;
3675
- const entriesStateKeyB = `${bSide}EntriesOf${capitalize(
3676
- aSide
3677
- )}`;
3678
- const contentStates = {
3679
- [entriesStateKeyA]: multipleRelatedEntriesSelectors,
3680
- [entriesStateKeyB]: multipleRelatedEntriesSelectors
3681
- };
3682
- states = Object.assign(baseStates, contentStates);
3683
- } else {
3684
- states = baseStates;
3685
- }
3686
- this.relations = relations;
3687
- this.states = states;
3688
- }
3689
- }
3690
- }
3691
- };
3692
-
3693
- // ../atom.io/internal/src/join/get-join.ts
3694
- function getJoin(token, store) {
3695
- let myJoin = store.joins.get(token.key);
3696
- if (myJoin === void 0) {
3697
- const rootJoinMap = IMPLICIT.STORE.joins;
3698
- const rootJoin = rootJoinMap.get(token.key);
3699
- if (rootJoin === void 0) {
3700
- throw new Error(
3701
- `Join "${token.key}" not found in store "${store.config.name}"`
3702
- );
3703
- }
3704
- myJoin = new Join(rootJoin.options, rootJoin.defaultContent, store);
3705
- store.joins.set(token.key, myJoin);
3706
- }
3707
- return myJoin;
3708
- }
3709
-
3710
- // ../atom.io/internal/src/join/edit-relations-in-store.ts
3711
- function editRelationsInStore(token, change, store) {
3712
- const myJoin = getJoin(token, store);
3713
- const target = newest(store);
3714
- if (isChildStore(target)) {
3715
- const { toolkit } = target.transactionMeta;
3716
- myJoin.transact(toolkit, ({ relations }) => {
3717
- change(relations);
3718
- });
3719
- } else {
3720
- change(myJoin.relations);
3721
- }
3722
- }
3723
-
3724
- // ../atom.io/internal/src/join/get-internal-relations-from-store.ts
3725
- function getInternalRelationsFromStore(token, store) {
3726
- const myJoin = getJoin(token, store);
3727
- const family = myJoin.core.relatedKeysAtoms;
3728
- return family;
3729
- }
3730
-
3731
- // ../atom.io/internal/src/reserved-keys.ts
3732
- function isReservedIntrospectionKey(value) {
3733
- return value.startsWith(`\u{1F50D} `);
3734
- }
3735
-
3736
- // ../atom.io/introspection/src/refinery.ts
3737
- var Refinery = class {
3738
- supported;
3739
- constructor(supported) {
3740
- this.supported = supported;
3741
- }
3742
- refine(input) {
3743
- for (const [key, refiner] of Object.entries(this.supported)) {
3744
- try {
3745
- if (
3746
- // @ts-expect-error that's the point
3747
- refiner(input) === true && refiner !== Boolean
3748
- ) {
3749
- return { type: key, data: input };
3750
- }
3751
- } catch (_) {
3752
- try {
3753
- if (input instanceof refiner) {
3754
- return { type: key, data: input };
3755
- }
3756
- } catch (__) {
3757
- }
3758
- }
3759
- }
3760
- return null;
3761
- }
3762
- };
3763
- var primitiveRefinery = new Refinery({
3764
- number: (input) => typeof input === `number`,
3765
- string: (input) => typeof input === `string`,
3766
- boolean: (input) => typeof input === `boolean`,
3767
- null: (input) => input === null
3768
- });
3769
- function isPlainObject(input) {
3770
- if (!input) {
3771
- return false;
3772
- }
3773
- const prototype = Object.getPrototypeOf(input);
3774
- return prototype === Object.prototype;
3775
- }
3776
- var jsonTreeRefinery = new Refinery({
3777
- object: isPlainObject,
3778
- array: (input) => Array.isArray(input)
3779
- });
3780
- var jsonRefinery = new Refinery({
3781
- ...primitiveRefinery.supported,
3782
- ...jsonTreeRefinery.supported
3783
- });
3784
- var discoverType = (input) => {
3785
- if (input === void 0) {
3786
- return `undefined`;
3787
- }
3788
- const refined = jsonRefinery.refine(input);
3789
- if (refined) {
3790
- return refined.type;
3791
- }
3792
- return Object.getPrototypeOf(input).constructor.name;
3793
- };
3794
-
3795
- // ../atom.io/introspection/src/sprawl.ts
3796
- var sprawl = (tree, inspector) => {
3797
- const walk = (path, node) => {
3798
- const inspect2 = (p, n) => {
3799
- const result2 = inspector(p, n);
3800
- if (result2) return result2;
3801
- return null;
3802
- };
3803
- const result = inspect2(path, node);
3804
- if (result?.jobComplete ?? result?.pathComplete) {
3805
- return result;
3806
- }
3807
- const childEntries = Array.isArray(node) ? node.map((v, i) => [i, v]) : isPlainObject(node) ? Object.entries(node) : [];
3808
- for (const [k, v] of childEntries) {
3809
- const subResult = walk([...path, k], v);
3810
- if (subResult?.jobComplete) {
3811
- return subResult;
3812
- }
3813
- }
3814
- return {};
3815
- };
3816
- walk([], tree);
3817
- };
3818
-
3819
- // ../atom.io/introspection/src/differ.ts
3820
- function diffNumber(a, b) {
3821
- const sign = a < b ? `+` : `-`;
3822
- return {
3823
- summary: `${sign}${Math.abs(a - b)} (${a} \u2192 ${b})`
3824
- };
3825
- }
3826
- function diffString(a, b) {
3827
- const sign = a.length < b.length ? `+` : `-`;
3828
- return {
3829
- summary: `${sign}${Math.abs(a.length - b.length)} ("${a}" \u2192 "${b}")`
3830
- };
3831
- }
3832
- function diffBoolean(a, b) {
3833
- return {
3834
- summary: `${a} \u2192 ${b}`
3835
- };
3836
- }
3837
- function diffObject(a, b, recurse) {
3838
- let summary = ``;
3839
- const added = [];
3840
- const removed = [];
3841
- const changed = [];
3842
- sprawl(a, (path, nodeA) => {
3843
- let key;
3844
- for (key of path) {
3845
- const nodeB = b[key];
3846
- if (nodeB === void 0) {
3847
- removed.push([key, JSON.stringify(nodeA)]);
3848
- } else {
3849
- const delta = recurse(nodeA, nodeB);
3850
- if (delta.summary !== `No Change`) {
3851
- changed.push([key, delta]);
3852
- }
3853
- }
3854
- }
3855
- });
3856
- sprawl(b, (path, nodeB) => {
3857
- let key;
3858
- for (key of path) {
3859
- const nodeA = a[key];
3860
- if (nodeA === void 0) {
3861
- added.push([key, JSON.stringify(nodeB)]);
3862
- }
3863
- }
3864
- });
3865
- summary = `\uFF5E${changed.length} \uFF0B${added.length} \uFF0D${removed.length}`;
3866
- return {
3867
- summary,
3868
- added,
3869
- removed,
3870
- changed
3871
- };
3872
- }
3873
- function diffArray(a, b, recurse) {
3874
- return diffObject(a, b, recurse);
3875
- }
3876
- var Differ = class {
3877
- leafRefinery;
3878
- treeRefinery;
3879
- leafDiffers;
3880
- treeDiffers;
3881
- constructor(leafRefinery, treeRefinery, diffFunctions) {
3882
- this.leafRefinery = leafRefinery;
3883
- this.treeRefinery = treeRefinery;
3884
- this.leafDiffers = {};
3885
- this.treeDiffers = {};
3886
- for (const key of Object.keys(leafRefinery.supported)) {
3887
- const diffFunction = diffFunctions[key];
3888
- this.leafDiffers[key] = diffFunction;
3889
- }
3890
- for (const key of Object.keys(treeRefinery.supported)) {
3891
- const diffFunction = diffFunctions[key];
3892
- this.treeDiffers[key] = diffFunction;
3893
- }
3894
- }
3895
- diff(a, b) {
3896
- if (a === b) {
3897
- return { summary: `No Change` };
3898
- }
3899
- const aRefined = this.leafRefinery.refine(a) ?? this.treeRefinery.refine(a);
3900
- const bRefined = this.leafRefinery.refine(b) ?? this.treeRefinery.refine(b);
3901
- if (aRefined !== null && bRefined !== null) {
3902
- if (aRefined.type === bRefined.type) {
3903
- if (aRefined.type in this.leafDiffers) {
3904
- const delta = this.leafDiffers[aRefined.type](
3905
- aRefined.data,
3906
- bRefined.data
3907
- );
3908
- return delta;
3909
- }
3910
- if (aRefined.type in this.treeDiffers) {
3911
- const delta = this.treeDiffers[aRefined.type](
3912
- aRefined.data,
3913
- bRefined.data,
3914
- (x, y) => this.diff(x, y)
3915
- );
3916
- return delta;
3917
- }
3918
- }
3919
- }
3920
- const typeA = discoverType(a);
3921
- const typeB = discoverType(b);
3922
- if (typeA === typeB) {
3923
- return {
3924
- summary: `${typeA} \u2192 ${typeB}`
3925
- };
3926
- }
3927
- return {
3928
- summary: `Type change: ${typeA} \u2192 ${typeB}`
3929
- };
3930
- }
3931
- };
3932
- new Differ(primitiveRefinery, jsonTreeRefinery, {
3933
- number: diffNumber,
3934
- string: diffString,
3935
- boolean: diffBoolean,
3936
- null: () => ({ summary: `No Change` }),
3937
- object: diffObject,
3938
- array: diffArray
3939
- });
3940
-
3941
- // ../atom.io/realtime/src/shared-room-store.ts
3942
- atom({
3943
- key: `usersInRoomIndex`,
3944
- mutable: true,
3945
- default: () => new SetRTX(),
3946
- toJson: (set) => set.toJSON(),
3947
- fromJson: (json) => SetRTX.fromJSON(json)
3948
- });
3949
- var roomIndex = atom({
3950
- key: `roomIndex`,
3951
- default: () => new SetRTX(),
3952
- mutable: true,
3953
- toJson: (set) => set.toJSON(),
3954
- fromJson: (json) => SetRTX.fromJSON(json)
3955
- });
3956
- var DEFAULT_USER_IN_ROOM_META = {
3957
- enteredAtEpoch: 0
3958
- };
3959
- var usersInRooms = join(
3960
- {
3961
- key: `usersInRooms`,
3962
- between: [`room`, `user`],
3963
- cardinality: `1:n`,
3964
- isAType: (input) => typeof input === `string`,
3965
- isBType: (input) => typeof input === `string`
3966
- },
3967
- DEFAULT_USER_IN_ROOM_META
3968
- );
3969
- selectorFamily({
3970
- key: `usersInMyRoomView`,
3971
- get: (myUsername) => ({ find }) => {
3972
- const usersInRoomsAtoms = getInternalRelations(usersInRooms);
3973
- const myRoomIndex = find(usersInRoomsAtoms, myUsername);
3974
- return [myRoomIndex];
3975
- }
3976
- });
3977
-
3978
- // ../atom.io/realtime-server/src/ipc-sockets/custom-socket.ts
3979
- var CustomSocket = class {
3980
- listeners;
3981
- globalListeners;
3982
- handleEvent(event, ...args) {
3983
- for (const listener of this.globalListeners) {
3984
- listener(event, ...args);
3985
- }
3986
- const listeners = this.listeners.get(event);
3987
- if (listeners) {
3988
- for (const listener of listeners) {
3989
- listener(...args);
3990
- }
3991
- }
3992
- }
3993
- id = `no_id_retrieved`;
3994
- emit;
3995
- constructor(emit) {
3996
- this.emit = emit;
3997
- this.listeners = /* @__PURE__ */ new Map();
3998
- this.globalListeners = /* @__PURE__ */ new Set();
3999
- }
4000
- on(event, listener) {
4001
- const listeners = this.listeners.get(event);
4002
- if (listeners) {
4003
- listeners.add(listener);
4004
- } else {
4005
- this.listeners.set(event, /* @__PURE__ */ new Set([listener]));
4006
- }
4007
- return this;
4008
- }
4009
- onAny(listener) {
4010
- this.globalListeners.add(listener);
4011
- return this;
4012
- }
4013
- off(event, listener) {
4014
- const listeners = this.listeners.get(event);
4015
- if (listeners) {
4016
- if (listener) {
4017
- listeners.delete(listener);
4018
- } else {
4019
- this.listeners.delete(event);
4020
- }
4021
- }
4022
- return this;
4023
- }
4024
- offAny(listener) {
4025
- this.globalListeners.delete(listener);
4026
- return this;
4027
- }
4028
- };
4029
-
4030
- // ../atom.io/realtime-server/src/ipc-sockets/child-socket.ts
4031
- var ChildSocket = class extends CustomSocket {
4032
- incompleteData = ``;
4033
- unprocessedEvents = [];
4034
- incompleteLog = ``;
4035
- unprocessedLogs = [];
4036
- id = `#####`;
4037
- process;
4038
- key;
4039
- logger;
4040
- handleLog(arg) {
4041
- if (Array.isArray(arg)) {
4042
- const [level, ...rest] = arg;
4043
- switch (level) {
4044
- case `i`:
4045
- this.logger.info(...rest);
4046
- break;
4047
- case `w`:
4048
- this.logger.warn(...rest);
4049
- break;
4050
- case `e`:
4051
- this.logger.error(...rest);
4052
- break;
4053
- default:
4054
- return;
4055
- }
4056
- }
4057
- }
4058
- constructor(process2, key, logger) {
4059
- super((event, ...args) => {
4060
- const stringifiedEvent = JSON.stringify([event, ...args]) + ``;
4061
- const errorHandler = (err) => {
4062
- if (err.code === `EPIPE`) {
4063
- console.error(`EPIPE error during write`, this.process.stdin);
4064
- }
4065
- this.process.stdin.removeListener(`error`, errorHandler);
4066
- };
4067
- this.process.stdin.once(`error`, errorHandler);
4068
- this.process.stdin.write(stringifiedEvent);
4069
- return this;
4070
- });
4071
- this.process = process2;
4072
- this.key = key;
4073
- this.logger = logger ?? {
4074
- info: (...args) => {
4075
- console.info(this.id, this.key, ...args);
4076
- },
4077
- warn: (...args) => {
4078
- console.warn(this.id, this.key, ...args);
4079
- },
4080
- error: (...args) => {
4081
- console.error(this.id, this.key, ...args);
4082
- }
4083
- };
4084
- this.process.stdout.on(
4085
- `data`,
4086
- (buffer) => {
4087
- const chunk = buffer.toString();
4088
- if (chunk === `ALIVE`) {
4089
- return;
4090
- }
4091
- this.unprocessedEvents.push(...chunk.split(``));
4092
- const newInput = this.unprocessedEvents.shift();
4093
- this.incompleteData += newInput ?? ``;
4094
- try {
4095
- if (this.incompleteData.startsWith(`error`)) {
4096
- console.log(`\u2757`, this.incompleteData);
4097
- }
4098
- let parsedEvent = parseJson(this.incompleteData);
4099
- this.handleEvent(...parsedEvent);
4100
- while (this.unprocessedEvents.length > 0) {
4101
- const event = this.unprocessedEvents.shift();
4102
- if (event) {
4103
- if (this.unprocessedEvents.length === 0) {
4104
- this.incompleteData = event;
4105
- }
4106
- parsedEvent = parseJson(event);
4107
- this.handleEvent(...parsedEvent);
4108
- }
4109
- }
4110
- this.incompleteData = ``;
4111
- } catch (error) {
4112
- console.warn(`\u26A0\uFE0F----------------\u26A0\uFE0F`);
4113
- console.warn(this.incompleteData);
4114
- console.warn(`\u26A0\uFE0F----------------\u26A0\uFE0F`);
4115
- console.error(error);
4116
- }
4117
- }
4118
- );
4119
- this.process.stderr.on(`data`, (buf) => {
4120
- const chunk = buf.toString();
4121
- this.unprocessedLogs.push(...chunk.split(``));
4122
- const newInput = this.unprocessedLogs.shift();
4123
- this.incompleteLog += newInput ?? ``;
4124
- try {
4125
- let parsedLog = parseJson(this.incompleteLog);
4126
- this.handleLog(parsedLog);
4127
- while (this.unprocessedLogs.length > 0) {
4128
- this.incompleteLog = this.unprocessedLogs.shift() ?? ``;
4129
- if (this.incompleteLog) {
4130
- parsedLog = parseJson(this.incompleteLog);
4131
- this.handleLog(parsedLog);
4132
- }
4133
- }
4134
- } catch (error) {
4135
- console.error(`\u274C\u274C\u274C`);
4136
- console.error(this.incompleteLog);
4137
- console.error(error);
4138
- console.error(`\u274C\u274C\u274C\uFE0F`);
4139
- }
4140
- });
4141
- if (process2.pid) {
4142
- this.id = process2.pid.toString();
4143
- }
4144
- }
4145
- };
4146
-
4147
- // ../atom.io/realtime-server/src/realtime-server-stores/server-room-external-store.ts
4148
- var roomArgumentsAtoms = atomFamily({
4149
- key: `roomArguments`,
4150
- default: [`echo`, [`Hello World!`]]
4151
- });
4152
- var roomSelectors = selectorFamily({
4153
- key: `room`,
4154
- get: (roomId) => async ({ get, find }) => {
4155
- const argumentsState = find(roomArgumentsAtoms, roomId);
4156
- const args = get(argumentsState);
4157
- const [script, options] = args;
4158
- const child = await new Promise(
4159
- (resolve2) => {
4160
- const room = spawn(script, options, { env: process.env });
4161
- const resolver = (data) => {
4162
- if (data.toString() === `ALIVE`) {
4163
- room.stdout.off(`data`, resolver);
4164
- resolve2(room);
4165
- }
4166
- };
4167
- room.stdout.on(`data`, resolver);
4168
- }
4169
- );
4170
- return new ChildSocket(child, roomId);
4171
- }
4172
- });
4173
-
4174
- // ../atom.io/realtime-server/src/realtime-server-stores/server-room-external-actions.ts
4175
- transaction({
4176
- key: `createRoom`,
4177
- do: ({ get, set, find }, roomId, script, options) => {
4178
- const args = options ? [script, options] : [script];
4179
- const roomArgumentsState = find(roomArgumentsAtoms, roomId);
4180
- set(roomArgumentsState, args);
4181
- set(roomIndex, (s) => s.add(roomId));
4182
- const roomState = find(roomSelectors, roomId);
4183
- const room = get(roomState);
4184
- return room;
4185
- }
4186
- });
4187
- transaction({
4188
- key: `joinRoom`,
4189
- do: (tools, roomId, userId, enteredAtEpoch) => {
4190
- const meta = { enteredAtEpoch };
4191
- editRelationsInStore(
4192
- usersInRooms,
4193
- (relations) => {
4194
- relations.set({ room: roomId, user: userId }, meta);
4195
- },
4196
- tools.env().store
4197
- );
4198
- return meta;
4199
- }
4200
- });
4201
- transaction({
4202
- key: `leaveRoom`,
4203
- do: (tools, roomId, userId) => {
4204
- editRelationsInStore(
4205
- usersInRooms,
4206
- (relations) => {
4207
- relations.delete({ room: roomId, user: userId });
4208
- },
4209
- tools.env().store
4210
- );
4211
- }
4212
- });
4213
- transaction({
4214
- key: `destroyRoom`,
4215
- do: (tools, roomId) => {
4216
- editRelationsInStore(
4217
- usersInRooms,
4218
- (relations) => {
4219
- relations.delete({ room: roomId });
4220
- },
4221
- tools.env().store
4222
- );
4223
- tools.set(roomIndex, (s) => (s.delete(roomId), s));
4224
- }
4225
- });
4226
-
4227
- // ../atom.io/realtime-server/src/realtime-server-stores/server-sync-store.ts
4228
- atomFamily({
4229
- key: `redactor`,
4230
- default: { occlude: (updates) => updates }
4231
- });
4232
- atomFamily({
4233
- key: `unacknowledgedUpdates`,
4234
- default: () => []
4235
- });
4236
-
4237
- // ../atom.io/realtime-server/src/realtime-server-stores/server-user-store.ts
4238
- atomFamily({
4239
- key: `sockets`,
4240
- default: null
4241
- });
4242
- atom({
4243
- key: `socketsIndex`,
4244
- mutable: true,
4245
- default: () => new SetRTX(),
4246
- toJson: (set) => set.toJSON(),
4247
- fromJson: (json) => SetRTX.fromJSON(json)
4248
- });
4249
- atom({
4250
- key: `usersIndex`,
4251
- mutable: true,
4252
- default: () => new SetRTX(),
4253
- toJson: (set) => set.toJSON(),
4254
- fromJson: (json) => SetRTX.fromJSON(json)
4255
- });
4256
- join({
4257
- key: `usersOfSockets`,
4258
- between: [`user`, `socket`],
4259
- cardinality: `1:1`,
4260
- isAType: (s) => s.startsWith(`user::`),
4261
- isBType: (s) => s.startsWith(`socket::`)
4262
- });
4263
- var env = createEnv({
4264
- server: { FLIGHTDECK_SECRET: z.string().optional() },
4265
- clientPrefix: `NEVER`,
4266
- client: {},
4267
- runtimeEnv: import.meta.env,
4268
- emptyStringAsUndefined: true
4269
- });
4270
-
4271
- // src/flightdeck.lib.ts
4272
- var FLIGHTDECK_SETUP_PHASES = [`downloaded`, `installed`];
4273
- var FLIGHTDECK_UPDATE_PHASES = [`notified`, `confirmed`];
4274
- function isVersionNumber(version) {
4275
- return /^\d+\.\d+\.\d+$/.test(version) || !Number.isNaN(Number.parseFloat(version));
4276
- }
4277
- var FlightDeck = class {
4278
- options;
4279
- safety = 0;
4280
- storage;
4281
- webhookServer;
4282
- services;
4283
- serviceIdx;
4284
- defaultServicesReadyToUpdate;
4285
- servicesReadyToUpdate;
4286
- autoRespawnDeadServices;
4287
- logger;
4288
- serviceLoggers;
4289
- updateAvailabilityChecker = null;
4290
- servicesLive;
4291
- servicesDead;
4292
- live = new Future(() => {
4293
- });
4294
- dead = new Future(() => {
4295
- });
4296
- restartTimes = [];
4297
- constructor(options) {
4298
- this.options = options;
4299
- const { FLIGHTDECK_SECRET } = env;
4300
- const { flightdeckRootDir = resolve(homedir(), `.flightdeck`) } = options;
4301
- const port = options.port ?? 8080;
4302
- const origin = `http://localhost:${port}`;
4303
- const servicesEntries = toEntries(options.services);
4304
- this.services = fromEntries(
4305
- servicesEntries.map(([serviceName]) => [serviceName, null])
4306
- );
4307
- this.serviceIdx = fromEntries(
4308
- servicesEntries.map(([serviceName], idx) => [serviceName, idx])
4309
- );
4310
- this.defaultServicesReadyToUpdate = fromEntries(
4311
- servicesEntries.map(([serviceName, { waitFor }]) => [
4312
- serviceName,
4313
- !waitFor
4314
- ])
4315
- );
4316
- this.servicesReadyToUpdate = { ...this.defaultServicesReadyToUpdate };
4317
- this.autoRespawnDeadServices = true;
4318
- this.logger = new FlightDeckLogger(
4319
- this.options.packageName,
4320
- process.pid,
4321
- void 0,
4322
- { jsonLogging: this.options.jsonLogging ?? false }
4323
- );
4324
- this.serviceLoggers = fromEntries(
4325
- servicesEntries.map(([serviceName]) => [
4326
- serviceName,
4327
- new FlightDeckLogger(
4328
- this.options.packageName,
4329
- process.pid,
4330
- serviceName,
4331
- { jsonLogging: this.options.jsonLogging ?? false }
4332
- )
4333
- ])
4334
- );
4335
- this.servicesLive = servicesEntries.map(() => new Future(() => {
4336
- }));
4337
- this.servicesDead = servicesEntries.map(() => new Future(() => {
4338
- }));
4339
- this.live.use(Promise.all(this.servicesLive));
4340
- this.dead.use(Promise.all(this.servicesDead));
4341
- this.storage = new FilesystemStorage({
4342
- path: resolve(flightdeckRootDir, `storage`, options.packageName)
4343
- });
4344
- if (FLIGHTDECK_SECRET === void 0) {
4345
- this.logger.warn(
4346
- `No FLIGHTDECK_SECRET environment variable found. FlightDeck will not run an update server.`
4347
- );
4348
- } else {
4349
- createServer((req, res) => {
4350
- let data = [];
4351
- req.on(`data`, (chunk) => {
4352
- data.push(chunk instanceof Buffer ? chunk : Buffer.from(chunk));
4353
- }).on(`end`, async () => {
4354
- const authHeader = req.headers.authorization;
4355
- try {
4356
- if (typeof req.url === `undefined`) throw 400;
4357
- const expectedAuthHeader = `Bearer ${FLIGHTDECK_SECRET}`;
4358
- if (authHeader !== `Bearer ${FLIGHTDECK_SECRET}`) {
4359
- this.logger.info(
4360
- `Unauthorized: needed \`${expectedAuthHeader}\`, got \`${authHeader}\``
4361
- );
4362
- throw 401;
4363
- }
4364
- const url = new URL(req.url, origin);
4365
- this.logger.info(req.method, url.pathname);
4366
- const versionForeignInput = Buffer.concat(data).toString();
4367
- if (!isVersionNumber(versionForeignInput)) {
4368
- throw 400;
4369
- }
4370
- res.writeHead(200);
4371
- res.end();
4372
- this.storage.setItem(`updatePhase`, `notified`);
4373
- this.storage.setItem(`updateAwaitedVersion`, versionForeignInput);
4374
- const { checkAvailability } = options.scripts;
4375
- if (checkAvailability) {
4376
- await this.updateAvailabilityChecker?.stop();
4377
- await this.seekUpdate(versionForeignInput);
4378
- const updatePhase = this.storage.getItem(`updatePhase`);
4379
- this.logger.info(`> storage("updatePhase") >`, updatePhase);
4380
- if (updatePhase === `notified`) {
4381
- this.updateAvailabilityChecker = new CronJob(
4382
- `30 * * * * *`,
4383
- async () => {
4384
- await this.seekUpdate(versionForeignInput);
4385
- }
4386
- );
4387
- this.updateAvailabilityChecker.start();
4388
- }
4389
- } else {
4390
- this.downloadPackage();
4391
- }
4392
- } catch (thrown) {
4393
- this.logger.error(thrown, req.url);
4394
- if (typeof thrown === `number`) {
4395
- res.writeHead(thrown);
4396
- res.end();
4397
- }
4398
- } finally {
4399
- data = [];
4400
- }
4401
- });
4402
- }).listen(port, () => {
4403
- this.logger.info(`Server started on port ${port}`);
4404
- });
4405
- }
4406
- this.startAllServices().then(() => {
4407
- this.logger.info(`All services started.`);
4408
- }).catch((thrown) => {
4409
- if (thrown instanceof Error) {
4410
- this.logger.error(`Failed to start all services:`, thrown.message);
4411
- }
4412
- });
4413
- }
4414
- async seekUpdate(version) {
4415
- this.logger.info(`Checking for updates...`);
4416
- const { checkAvailability } = this.options.scripts;
4417
- if (!checkAvailability) {
4418
- this.logger.info(`No checkAvailability script found.`);
4419
- return;
4420
- }
4421
- try {
4422
- const out = execSync(`${checkAvailability} ${version}`);
4423
- this.logger.info(`Check stdout:`, out.toString());
4424
- await this.updateAvailabilityChecker?.stop();
4425
- this.storage.setItem(`updatePhase`, `confirmed`);
4426
- this.downloadPackage();
4427
- this.announceUpdate();
4428
- } catch (thrown) {
4429
- if (thrown instanceof Error) {
4430
- this.logger.error(`Check failed:`, thrown.message);
4431
- } else {
4432
- const thrownType = discoverType(thrown);
4433
- this.logger.error(`Check threw`, thrownType, thrown);
4434
- }
4435
- }
4436
- }
4437
- announceUpdate() {
4438
- for (const entry of toEntries(this.services)) {
4439
- const [serviceName, service] = entry;
4440
- if (service) {
4441
- if (this.options.services[serviceName].waitFor) {
4442
- service.emit(`updatesReady`);
4443
- }
4444
- } else {
4445
- this.startService(serviceName);
4446
- }
4447
- }
4448
- }
4449
- tryUpdate() {
4450
- if (toEntries(this.servicesReadyToUpdate).every(([, isReady]) => isReady)) {
4451
- this.logger.info(`All services are ready to update.`);
4452
- this.stopAllServices().then(() => {
4453
- this.logger.info(`All services stopped; starting up fresh...`);
4454
- this.startAllServices().then(() => {
4455
- this.logger.info(`All services started; we're back online.`);
4456
- }).catch((thrown) => {
4457
- if (thrown instanceof Error) {
4458
- this.logger.error(
4459
- `Failed to start all services:`,
4460
- thrown.message
4461
- );
4462
- }
4463
- });
4464
- }).catch((thrown) => {
4465
- if (thrown instanceof Error) {
4466
- this.logger.error(`Failed to stop all services:`, thrown.message);
4467
- }
4468
- });
4469
- }
4470
- }
4471
- startAllServices() {
4472
- this.logger.info(`Starting all services...`);
4473
- this.autoRespawnDeadServices = true;
4474
- const setupPhase = this.storage.getItem(`setupPhase`);
4475
- this.logger.info(`> storage("setupPhase") >`, setupPhase);
4476
- switch (setupPhase) {
4477
- case null:
4478
- this.logger.info(`Starting from scratch.`);
4479
- this.downloadPackage();
4480
- this.installPackage();
4481
- return this.startAllServices();
4482
- case `downloaded`:
4483
- this.logger.info(`Found package downloaded but not installed.`);
4484
- this.installPackage();
4485
- return this.startAllServices();
4486
- case `installed`: {
4487
- for (const [serviceName] of toEntries(this.services)) {
4488
- this.startService(serviceName);
4489
- }
4490
- return this.live;
4491
- }
4492
- }
4493
- }
4494
- startService(serviceName) {
4495
- this.logger.info(
4496
- `Starting service ${this.options.packageName}::${serviceName}, try ${this.safety}/2...`
4497
- );
4498
- if (this.safety >= 2) {
4499
- throw new Error(`Out of tries...`);
4500
- }
4501
- this.safety++;
4502
- const [exe, ...args] = this.options.services[serviceName].run.split(` `);
4503
- const serviceProcess = spawn(exe, args, {
4504
- cwd: this.options.flightdeckRootDir,
4505
- env: import.meta.env
4506
- });
4507
- const serviceLogger = this.serviceLoggers[serviceName];
4508
- const service = this.services[serviceName] = new ChildSocket(
4509
- serviceProcess,
4510
- `${this.options.packageName}::${serviceName}`,
4511
- serviceLogger
4512
- );
4513
- serviceLogger.processCode = service.process.pid ?? -1;
4514
- this.services[serviceName].onAny((...messages) => {
4515
- serviceLogger.info(`\u{1F4AC}`, ...messages);
4516
- });
4517
- this.services[serviceName].on(`readyToUpdate`, () => {
4518
- this.logger.info(`Service "${serviceName}" is ready to update.`);
4519
- this.servicesReadyToUpdate[serviceName] = true;
4520
- this.tryUpdate();
4521
- });
4522
- this.services[serviceName].on(`alive`, () => {
4523
- this.servicesLive[this.serviceIdx[serviceName]].use(Promise.resolve());
4524
- this.servicesDead[this.serviceIdx[serviceName]] = new Future(() => {
4525
- });
4526
- if (this.dead.done) {
4527
- this.dead = new Future(() => {
4528
- });
4529
- }
4530
- this.dead.use(Promise.all(this.servicesDead));
4531
- });
4532
- this.services[serviceName].process.once(`close`, (exitCode) => {
4533
- this.logger.info(
4534
- `Auto-respawn saw "${serviceName}" exit with code ${exitCode}`
4535
- );
4536
- this.services[serviceName] = null;
4537
- if (!this.autoRespawnDeadServices) {
4538
- this.logger.info(`Auto-respawn is off; "${serviceName}" rests.`);
4539
- return;
4540
- }
4541
- const updatePhase = this.storage.getItem(`updatePhase`);
4542
- this.logger.info(`> storage("updatePhase") >`, updatePhase);
4543
- const updatesAreReady = updatePhase === `confirmed`;
4544
- if (updatesAreReady) {
4545
- this.serviceLoggers[serviceName].info(`Updating before startup...`);
4546
- this.restartTimes = [];
4547
- this.installPackage();
4548
- this.startService(serviceName);
4549
- } else {
4550
- const now = Date.now();
4551
- const fiveMinutesAgo = now - 5 * 60 * 1e3;
4552
- this.restartTimes = this.restartTimes.filter(
4553
- (time) => time > fiveMinutesAgo
4554
- );
4555
- this.restartTimes.push(now);
4556
- if (this.restartTimes.length < 5) {
4557
- this.serviceLoggers[serviceName].info(`Crashed. Restarting...`);
4558
- this.startService(serviceName);
4559
- } else {
4560
- this.serviceLoggers[serviceName].info(
4561
- `Crashed 5 times in 5 minutes. Not restarting.`
4562
- );
4563
- }
4564
- }
4565
- });
4566
- this.safety = 0;
4567
- }
4568
- downloadPackage() {
4569
- this.logger.info(`Downloading...`);
4570
- try {
4571
- const out = execSync(this.options.scripts.download);
4572
- this.logger.info(`Download stdout:`, out.toString());
4573
- this.storage.setItem(`setupPhase`, `downloaded`);
4574
- this.logger.info(`Downloaded!`);
4575
- } catch (thrown) {
4576
- if (thrown instanceof Error) {
4577
- this.logger.error(`Failed to get the latest release: ${thrown.message}`);
4578
- }
4579
- return;
4580
- }
4581
- }
4582
- installPackage() {
4583
- this.logger.info(`Installing...`);
4584
- try {
4585
- const out = execSync(this.options.scripts.install);
4586
- this.logger.info(`Install stdout:`, out.toString());
4587
- this.storage.setItem(`setupPhase`, `installed`);
4588
- this.logger.info(`Installed!`);
4589
- } catch (thrown) {
4590
- if (thrown instanceof Error) {
4591
- this.logger.error(`Failed to get the latest release: ${thrown.message}`);
4592
- }
4593
- return;
4594
- }
4595
- }
4596
- stopAllServices() {
4597
- this.logger.info(`Stopping all services... auto-respawn disabled.`);
4598
- this.autoRespawnDeadServices = false;
4599
- for (const [serviceName] of toEntries(this.services)) {
4600
- this.stopService(serviceName);
4601
- }
4602
- return this.dead;
4603
- }
4604
- stopService(serviceName) {
4605
- const service = this.services[serviceName];
4606
- if (service) {
4607
- this.logger.info(`Stopping service "${serviceName}"...`);
4608
- this.servicesDead[this.serviceIdx[serviceName]].use(
4609
- new Promise((pass) => {
4610
- service.emit(`timeToStop`);
4611
- service.process.once(`close`, (exitCode) => {
4612
- this.logger.info(
4613
- `Stopped service "${serviceName}"; exited with code ${exitCode}`
4614
- );
4615
- this.services[serviceName] = null;
4616
- pass();
4617
- });
4618
- })
4619
- );
4620
- this.dead.use(Promise.all(this.servicesDead));
4621
- this.servicesLive[this.serviceIdx[serviceName]] = new Future(() => {
4622
- });
4623
- if (this.live.done) {
4624
- this.live = new Future(() => {
4625
- });
4626
- }
4627
- this.live.use(Promise.all(this.servicesLive));
4628
- } else {
4629
- this.serviceLoggers[serviceName].error(
4630
- `Tried to stop service, but it wasn't running.`
4631
- );
4632
- }
4633
- }
4634
- };
4635
- var FLIGHTDECK_INFO = `info`;
4636
- var FLIGHTDECK_WARN = `warn`;
4637
- var FLIGHTDECK_ERROR = `ERR!`;
4638
- var flightDeckLogSchema = z.object({
4639
- level: z.union([
4640
- z.literal(FLIGHTDECK_INFO),
4641
- z.literal(FLIGHTDECK_WARN),
4642
- z.literal(FLIGHTDECK_ERROR)
4643
- ]),
4644
- timestamp: z.number(),
4645
- package: z.string(),
4646
- service: z.string().optional(),
4647
- process: z.number(),
4648
- body: z.string()
4649
- });
4650
- var LINE_FORMAT = `line-format`;
4651
- var VALUE = `value`;
4652
- var FLIGHTDECK_LNAV_FORMAT = {
4653
- title: `FlightDeck Log`,
4654
- description: `Format for events logged by the FlightDeck process manager.`,
4655
- "file-type": `json`,
4656
- "timestamp-field": `timestamp`,
4657
- "timestamp-divisor": 1e3,
4658
- "module-field": `package`,
4659
- "opid-field": `service`,
4660
- "level-field": `level`,
4661
- level: {
4662
- info: FLIGHTDECK_INFO,
4663
- warning: FLIGHTDECK_WARN,
4664
- error: FLIGHTDECK_ERROR
4665
- },
4666
- [LINE_FORMAT]: [
4667
- {
4668
- field: `level`
4669
- },
4670
- {
4671
- prefix: ` `,
4672
- field: `__timestamp__`,
4673
- "timestamp-format": `%Y-%m-%dT%H:%M:%S.%L%Z`
4674
- },
4675
- {
4676
- prefix: ` `,
4677
- field: `process`,
4678
- "min-width": 5
4679
- },
4680
- {
4681
- prefix: `:`,
4682
- field: `package`
4683
- },
4684
- {
4685
- prefix: `:`,
4686
- field: `service`,
4687
- "default-value": ``
4688
- },
4689
- {
4690
- prefix: `: `,
4691
- field: `body`
4692
- }
4693
- ],
4694
- [VALUE]: {
4695
- timestamp: {
4696
- kind: `integer`
4697
- },
4698
- level: {
4699
- kind: `string`
4700
- },
4701
- package: {
4702
- kind: `string`
4703
- },
4704
- service: {
4705
- kind: `string`
4706
- },
4707
- process: {
4708
- kind: `integer`
4709
- },
4710
- body: {
4711
- kind: `string`
4712
- }
4713
- }
4714
- };
4715
- var FlightDeckLogger = class {
4716
- packageName;
4717
- serviceName;
4718
- jsonLogging;
4719
- processCode;
4720
- constructor(packageName, processCode, serviceName, options) {
4721
- this.packageName = packageName;
4722
- if (serviceName) {
4723
- this.serviceName = serviceName;
4724
- }
4725
- this.processCode = processCode;
4726
- this.jsonLogging = options?.jsonLogging ?? false;
4727
- }
4728
- log(level, ...messages) {
4729
- if (this.jsonLogging) {
4730
- let body = messages.map(
4731
- (message) => typeof message === `string` ? message : inspect(message, false, null, true)
4732
- ).join(` `);
4733
- if (body.includes(`
4734
- `)) {
4735
- body = `
4736
- ${body.split(`
4737
- `).join(`
4738
- `)}`;
4739
- }
4740
- const log = {
4741
- timestamp: Date.now(),
4742
- level,
4743
- process: this.processCode,
4744
- package: this.packageName,
4745
- body
4746
- };
4747
- if (this.serviceName) {
4748
- log.service = this.serviceName;
4749
- }
4750
- process.stdout.write(JSON.stringify(log) + `
4751
- `);
4752
- } else {
4753
- const source = this.serviceName ? `${this.packageName}:${this.serviceName}` : this.packageName;
4754
- switch (level) {
4755
- case FLIGHTDECK_INFO:
4756
- console.log(`${source}:`, ...messages);
4757
- break;
4758
- case FLIGHTDECK_WARN:
4759
- console.warn(`${source}:`, ...messages);
4760
- break;
4761
- case FLIGHTDECK_ERROR:
4762
- console.error(`${source}:`, ...messages);
4763
- break;
4764
- }
4765
- }
4766
- }
4767
- info(...messages) {
4768
- this.log(FLIGHTDECK_INFO, ...messages);
4769
- }
4770
- warn(...messages) {
4771
- this.log(FLIGHTDECK_WARN, ...messages);
4772
- }
4773
- error(...messages) {
4774
- this.log(FLIGHTDECK_ERROR, ...messages);
4775
- }
4776
- };
4777
-
4778
- export { FLIGHTDECK_ERROR, FLIGHTDECK_INFO, FLIGHTDECK_LNAV_FORMAT, FLIGHTDECK_SETUP_PHASES, FLIGHTDECK_UPDATE_PHASES, FLIGHTDECK_WARN, FlightDeck, FlightDeckLogger, flightDeckLogSchema, isVersionNumber };
4779
- //# sourceMappingURL=chunk-FIIAJE2K.js.map
4780
- //# sourceMappingURL=chunk-FIIAJE2K.js.map