atom.io 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,923 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __spreadValues = (a, b) => {
13
+ for (var prop in b || (b = {}))
14
+ if (__hasOwnProp.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ if (__getOwnPropSymbols)
17
+ for (var prop of __getOwnPropSymbols(b)) {
18
+ if (__propIsEnum.call(b, prop))
19
+ __defNormalProp(a, prop, b[prop]);
20
+ }
21
+ return a;
22
+ };
23
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
+ var __objRest = (source, exclude) => {
25
+ var target = {};
26
+ for (var prop in source)
27
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
28
+ target[prop] = source[prop];
29
+ if (source != null && __getOwnPropSymbols)
30
+ for (var prop of __getOwnPropSymbols(source)) {
31
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
32
+ target[prop] = source[prop];
33
+ }
34
+ return target;
35
+ };
36
+ var __export = (target, all) => {
37
+ for (var name in all)
38
+ __defProp(target, name, { get: all[name], enumerable: true });
39
+ };
40
+ var __copyProps = (to, from, except, desc) => {
41
+ if (from && typeof from === "object" || typeof from === "function") {
42
+ for (let key of __getOwnPropNames(from))
43
+ if (!__hasOwnProp.call(to, key) && key !== except)
44
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
45
+ }
46
+ return to;
47
+ };
48
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
49
+ // If the importer is in node compatibility mode or this is not an ESM
50
+ // file that has been converted to a CommonJS file using a Babel-
51
+ // compatible transform (i.e. "__esModule" has not been set), then set
52
+ // "default" to the CommonJS "module.exports" for node compatibility.
53
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
54
+ mod
55
+ ));
56
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
57
+
58
+ // src/index.ts
59
+ var src_exports = {};
60
+ __export(src_exports, {
61
+ __INTERNAL__: () => internal_exports,
62
+ atom: () => atom,
63
+ atomFamily: () => atomFamily,
64
+ configure: () => configure,
65
+ getState: () => getState,
66
+ registerSelector: () => registerSelector,
67
+ selector: () => selector,
68
+ selectorFamily: () => selectorFamily,
69
+ setState: () => setState,
70
+ subscribe: () => subscribe,
71
+ transaction: () => transaction
72
+ });
73
+ module.exports = __toCommonJS(src_exports);
74
+
75
+ // src/internal/index.ts
76
+ var internal_exports = {};
77
+ __export(internal_exports, {
78
+ IMPLICIT: () => IMPLICIT,
79
+ abortTransaction: () => abortTransaction,
80
+ clearStore: () => clearStore,
81
+ configure: () => configure,
82
+ createStore: () => createStore,
83
+ deposit: () => deposit,
84
+ finishAction: () => finishAction,
85
+ finishTransaction: () => finishTransaction,
86
+ getCachedState: () => getCachedState,
87
+ getSelectorState: () => getSelectorState,
88
+ getState__INTERNAL: () => getState__INTERNAL,
89
+ isDone: () => isDone,
90
+ markDone: () => markDone,
91
+ propagateChanges: () => propagateChanges,
92
+ recall: () => recall,
93
+ setAtomState: () => setAtomState,
94
+ setSelectorState: () => setSelectorState,
95
+ setState__INTERNAL: () => setState__INTERNAL,
96
+ startAction: () => startAction,
97
+ startTransaction: () => startTransaction,
98
+ withdraw: () => withdraw
99
+ });
100
+
101
+ // src/internal/get.ts
102
+ var import_hamt_plus2 = __toESM(require("hamt_plus"));
103
+
104
+ // src/internal/store.ts
105
+ var import_hamt_plus = __toESM(require("hamt_plus"));
106
+
107
+ // ../anvl/src/join/core-relation-data.ts
108
+ var import_string = require("fp-ts/string");
109
+
110
+ // ../anvl/src/array/venn.ts
111
+ var includesAll = (items) => (array) => {
112
+ for (const item of items) {
113
+ if (!array.includes(item))
114
+ return false;
115
+ }
116
+ return true;
117
+ };
118
+ var comprises = (items) => (array) => includesAll(items)(array) && includesAll(array)(items);
119
+
120
+ // ../anvl/src/array/index.ts
121
+ var isArray = (isType) => (input) => Array.isArray(input) && input.every((item) => isType(item));
122
+ var map = (f) => (a) => a.map(f);
123
+ var every = (f = Boolean) => (a) => a.every(f);
124
+ var allTrue = every((x) => x === true);
125
+ var addTo = (a) => (x) => a.includes(x) ? a : [...a, x];
126
+ var isEmptyArray = (input) => Array.isArray(input) && input.length === 0;
127
+ var isOneOf = (...args) => (input) => args.includes(input);
128
+
129
+ // ../anvl/src/object/refinement.ts
130
+ var import_function2 = require("fp-ts/function");
131
+
132
+ // ../anvl/src/object/access.ts
133
+ var access = (k) => Object.assign((obj) => obj[k], {
134
+ in: (obj) => obj[k]
135
+ });
136
+
137
+ // ../anvl/src/object/entries.ts
138
+ var recordToEntries = (obj) => Object.entries(obj);
139
+ var entriesToRecord = (entries) => Object.fromEntries(entries);
140
+
141
+ // ../anvl/src/object/mapObject.ts
142
+ var import_function = require("fp-ts/lib/function");
143
+ var mapObject = (obj, fn) => (0, import_function.pipe)(
144
+ obj,
145
+ recordToEntries,
146
+ map(([key, val]) => [key, fn(val, key)]),
147
+ entriesToRecord
148
+ );
149
+ var mob = (fn) => (obj) => mapObject(obj, fn);
150
+
151
+ // ../anvl/src/function/index.ts
152
+ var become = (nextVersionOfThing) => (originalThing) => nextVersionOfThing instanceof Function ? nextVersionOfThing(
153
+ originalThing instanceof Function ? originalThing() : originalThing
154
+ ) : nextVersionOfThing;
155
+ var pass = (...params) => (fn) => fn(...params);
156
+
157
+ // ../anvl/src/nullish/index.ts
158
+ var isUndefined = (input) => input === void 0;
159
+ var ifNullish = (alt) => (input) => input != null ? input : alt;
160
+
161
+ // ../anvl/src/object/refinement.ts
162
+ var isNonNullObject = (input) => typeof input === `object` && input !== null;
163
+ var isPlainObject = (input) => isNonNullObject(input) && Object.getPrototypeOf(input) === Object.prototype;
164
+ var isEmptyObject = (input) => isPlainObject(input) && Object.keys(input).length === 0;
165
+ var isRecord = (isKey, isValue) => (input) => isPlainObject(input) && Object.entries(input).every(([k, v]) => isKey(k) && isValue(v));
166
+ var hasProperties = (isValue, options = { allowExtraProperties: false }) => {
167
+ const name = `{${recordToEntries(
168
+ isValue
169
+ ).map(([k, v]) => String(k) + `:` + v.name).join(`,`)}}`;
170
+ const _ = {
171
+ [name]: (input) => isPlainObject(input) && (0, import_function2.pipe)(
172
+ isValue,
173
+ Object.entries,
174
+ every(([key, val]) => key in input || val(void 0))
175
+ ) && (0, import_function2.pipe)(
176
+ input,
177
+ mob(
178
+ (val, key) => (0, import_function2.pipe)(
179
+ isValue,
180
+ access(key),
181
+ ifNullish(() => options.allowExtraProperties),
182
+ pass(val)
183
+ )
184
+ ),
185
+ Object.values,
186
+ allTrue
187
+ )
188
+ };
189
+ return _[name];
190
+ };
191
+ var hasExactProperties = (
192
+ /* alias for hasProperties without allowExtraProperties */
193
+ (isValue) => hasProperties(isValue, { allowExtraProperties: false })
194
+ );
195
+
196
+ // ../anvl/src/join/core-relation-data.ts
197
+ var RELATION_TYPES = [`1:1`, `1:n`, `n:n`];
198
+ var isRelationType = (x) => RELATION_TYPES.includes(x);
199
+ var EMPTY_RELATION_DATA = {
200
+ contents: {},
201
+ relations: {},
202
+ relationType: `n:n`
203
+ };
204
+ var isRelationData = (isContent) => (input) => hasExactProperties({
205
+ contents: isContent ? isRecord(import_string.isString, isContent) : hasExactProperties({}),
206
+ relations: isRecord(import_string.isString, isArray(import_string.isString)),
207
+ relationType: isRelationType
208
+ })(input);
209
+
210
+ // ../anvl/src/join/get-related-ids.ts
211
+ var getRelatedIds = (relationMap, id) => {
212
+ var _a;
213
+ return (_a = relationMap.relations[id]) != null ? _a : [];
214
+ };
215
+ var getRelatedId = (relationMap, id) => {
216
+ const relations = getRelatedIds(relationMap, id);
217
+ if (relations.length > 1) {
218
+ console.warn(
219
+ `entry with id ${id} was not expected to have multiple relations`
220
+ );
221
+ }
222
+ return relations[0];
223
+ };
224
+
225
+ // ../anvl/src/join/relation-contents.ts
226
+ var import_function6 = require("fp-ts/function");
227
+
228
+ // ../anvl/src/join/relation-record.ts
229
+ var getRelationEntries = (relationMap, idA) => getRelatedIds(relationMap, idA).map((idB) => [
230
+ idB,
231
+ getContent(relationMap, idA, idB)
232
+ ]);
233
+ var getRelationRecord = (relationMap, id) => Object.fromEntries(getRelationEntries(relationMap, id));
234
+
235
+ // ../anvl/src/join/remove-relation.ts
236
+ var import_function5 = require("fp-ts/function");
237
+ var import_string2 = require("fp-ts/string");
238
+
239
+ // ../anvl/src/object/index.ts
240
+ var import_function4 = require("fp-ts/function");
241
+ var treeShake = (shouldDiscard = isUndefined) => (obj) => {
242
+ const newObj = {};
243
+ const entries = Object.entries(obj);
244
+ entries.forEach(
245
+ ([key, val]) => !shouldDiscard(val, key) ? newObj[key] = val : null
246
+ );
247
+ return newObj;
248
+ };
249
+
250
+ // ../anvl/src/string/split.ts
251
+ var split = (separator) => (str) => str.split(separator);
252
+
253
+ // ../anvl/src/join/remove-relation.ts
254
+ var removeSpecific = (current, idA, idB) => {
255
+ const isIdForRemoval = isOneOf(idA, idB);
256
+ return __spreadProps(__spreadValues({}, current), {
257
+ relations: (0, import_function5.pipe)(
258
+ current.relations,
259
+ recordToEntries,
260
+ map(([id, relations]) => [
261
+ id,
262
+ isIdForRemoval(id) ? relations.filter((relation) => !isIdForRemoval(relation)) : relations
263
+ ]),
264
+ entriesToRecord,
265
+ treeShake(isEmptyArray)
266
+ ),
267
+ contents: (0, import_function5.pipe)(
268
+ current.contents,
269
+ treeShake(
270
+ (_, key) => (0, import_string2.isString)(key) && (0, import_function5.pipe)(key, split(`/`), comprises([idA, idB]))
271
+ )
272
+ )
273
+ });
274
+ };
275
+ var removeAll = (current, idToRemove) => {
276
+ const next = __spreadProps(__spreadValues({}, current), {
277
+ relations: (0, import_function5.pipe)(
278
+ current.relations,
279
+ recordToEntries,
280
+ map(([id, relations]) => [
281
+ id,
282
+ relations.filter((relation) => relation !== idToRemove)
283
+ ]),
284
+ entriesToRecord,
285
+ treeShake((val, key) => key === idToRemove || isEmptyArray(val))
286
+ ),
287
+ contents: (0, import_function5.pipe)(
288
+ current.contents,
289
+ treeShake(
290
+ (_, key) => (0, import_string2.isString)(key) && key.split(`/`).includes(idToRemove)
291
+ )
292
+ )
293
+ });
294
+ return next;
295
+ };
296
+ var removeRelation = (current, idA, idB) => idB ? removeSpecific(current, idA, idB) : removeAll(current, idA);
297
+
298
+ // ../anvl/src/join/set-relation.ts
299
+ var setManyToMany = (map2, idA, idB, ...rest) => {
300
+ var _a, _b;
301
+ const next = __spreadProps(__spreadValues({}, map2), {
302
+ relations: __spreadProps(__spreadValues({}, map2.relations), {
303
+ [idA]: addTo((_a = map2.relations[idA]) != null ? _a : [])(idB),
304
+ [idB]: addTo((_b = map2.relations[idB]) != null ? _b : [])(idA)
305
+ })
306
+ });
307
+ const content = rest[0];
308
+ return content ? setContent(next, idA, idB, content) : next;
309
+ };
310
+ var removeEmpties = treeShake(isEmptyArray);
311
+ var set1ToMany = (current, leaderId, followerId, ...rest) => {
312
+ var _a;
313
+ const relations = __spreadValues({}, current.relations);
314
+ const prevLeaderId = getRelatedId(current, followerId);
315
+ const next = __spreadProps(__spreadValues({}, current), {
316
+ relations: removeEmpties(__spreadProps(__spreadValues(__spreadValues({}, relations), prevLeaderId && prevLeaderId !== leaderId && {
317
+ [prevLeaderId]: relations[prevLeaderId].filter(
318
+ (id) => id !== followerId
319
+ )
320
+ }), {
321
+ [followerId]: [leaderId],
322
+ [leaderId]: addTo((_a = relations[leaderId]) != null ? _a : [])(followerId)
323
+ }))
324
+ });
325
+ const content = rest[0];
326
+ return content ? setContent(next, leaderId, followerId, content) : next;
327
+ };
328
+ var set1To1 = (current, wifeId, husbandId, ...rest) => {
329
+ const prevWifeId = getRelatedId(current, husbandId);
330
+ const prevHusbandId = getRelatedId(current, wifeId);
331
+ const next = __spreadProps(__spreadValues({}, current), {
332
+ relations: removeEmpties(__spreadProps(__spreadValues(__spreadValues(__spreadValues({}, current.relations), prevWifeId && { [prevWifeId]: [] }), prevHusbandId && { [prevHusbandId]: [] }), {
333
+ [wifeId]: [husbandId],
334
+ [husbandId]: [wifeId]
335
+ }))
336
+ });
337
+ const content = rest[0];
338
+ return content ? setContent(next, wifeId, husbandId, content) : next;
339
+ };
340
+ var setRelationWithContent = (current, idA, idB, ...rest) => {
341
+ switch (current.relationType) {
342
+ case `1:1`:
343
+ return set1To1(current, idA, idB, ...rest);
344
+ case `1:n`:
345
+ return set1ToMany(current, idA, idB, ...rest);
346
+ case `n:n`:
347
+ return setManyToMany(current, idA, idB, ...rest);
348
+ }
349
+ };
350
+
351
+ // ../anvl/src/join/relation-contents.ts
352
+ var makeContentId = (idA, idB) => [idA, idB].sort().join(`/`);
353
+ var getContent = (relationMap, idA, idB) => relationMap.contents[makeContentId(idA, idB)];
354
+ var setContent = (map2, idA, idB, content) => __spreadProps(__spreadValues({}, map2), {
355
+ contents: __spreadProps(__spreadValues({}, map2.contents), {
356
+ [makeContentId(idA, idB)]: content
357
+ })
358
+ });
359
+ var getRelations = (relationMap, id) => getRelationEntries(relationMap, id).map(
360
+ ([id2, content]) => __spreadValues({
361
+ id: id2
362
+ }, content)
363
+ );
364
+ var setRelations = (current, idA, relations) => (0, import_function6.pipe)(
365
+ current,
366
+ (relationData) => {
367
+ const relatedIds = getRelatedIds(current, idA);
368
+ const removedIds = relatedIds.filter(
369
+ (id) => !relations.some((r) => r.id === id)
370
+ );
371
+ let step = relationData;
372
+ for (const idB of removedIds)
373
+ step = removeRelation(step, idA, idB);
374
+ return step;
375
+ },
376
+ (relationData) => {
377
+ let step = relationData;
378
+ for (const _a of relations) {
379
+ const _b = _a, { id: idB } = _b, rest = __objRest(_b, ["id"]);
380
+ const content = isEmptyObject(rest) ? void 0 : rest;
381
+ step = setRelationWithContent(step, idA, idB, content);
382
+ }
383
+ return step;
384
+ },
385
+ (relationData) => {
386
+ const newlyOrderedIds = relations.map((r) => r.id);
387
+ return __spreadProps(__spreadValues({}, relationData), {
388
+ relations: __spreadProps(__spreadValues({}, relationData.relations), {
389
+ [idA]: newlyOrderedIds
390
+ })
391
+ });
392
+ }
393
+ );
394
+
395
+ // ../anvl/src/refinement/index.ts
396
+ var canExist = (_) => true;
397
+ var cannotExist = (_) => false;
398
+ var couldBe = (isTypeA, logging = false, refinements = [isTypeA]) => {
399
+ const name = `(${refinements.map((r) => r.name || `anon`).join(` | `)})`;
400
+ const _ = {
401
+ [name]: (input) => refinements.some(
402
+ (refinement) => {
403
+ var _a;
404
+ return logging && console.log(
405
+ refinements.map((r) => r.name || `anon`).join(` | `),
406
+ `>`,
407
+ (_a = refinement.name) != null ? _a : `anon`,
408
+ `:`,
409
+ refinement(input)
410
+ ), refinement(input);
411
+ }
412
+ )
413
+ };
414
+ const checkTypes = Object.assign(_[name], {
415
+ or: (isTypeB) => couldBe(isTypeB, logging, [...refinements, isTypeB])
416
+ });
417
+ return checkTypes;
418
+ };
419
+ var isUnion = couldBe(cannotExist);
420
+ var mustBe = (isTypeA, logging = false, refinements = [isTypeA]) => {
421
+ const name = `(${refinements.map((r) => r.name || `anon`).join(` & `)})`;
422
+ const _ = {
423
+ [name]: (input) => refinements.every(
424
+ (refinement) => (logging && console.log(
425
+ refinements.map((r) => r.name || `anon`).join(` & `),
426
+ `>`,
427
+ refinement.name || `anon`,
428
+ `:`,
429
+ refinement(input)
430
+ ), refinement(input))
431
+ )
432
+ };
433
+ const checkTypes = Object.assign(_[name], {
434
+ and: (isTypeB) => mustBe(isTypeB, logging, [...refinements, isTypeB])
435
+ });
436
+ return checkTypes;
437
+ };
438
+ var isIntersection = mustBe(canExist);
439
+
440
+ // ../anvl/src/join/index.ts
441
+ var Join = class {
442
+ constructor(json) {
443
+ Object.assign(this, __spreadValues(__spreadValues({}, EMPTY_RELATION_DATA), json));
444
+ }
445
+ toJSON() {
446
+ return {
447
+ relationType: this.relationType,
448
+ relations: this.relations,
449
+ contents: this.contents
450
+ };
451
+ }
452
+ static fromJSON(json, isContent = cannotExist) {
453
+ const isValid = isRelationData(isContent)(json);
454
+ if (isValid) {
455
+ return new Join(json);
456
+ }
457
+ throw new Error(
458
+ `Saved JSON for this Join is invalid: ${JSON.stringify(json)}`
459
+ );
460
+ }
461
+ getRelatedId(id) {
462
+ return getRelatedId(this, id);
463
+ }
464
+ getRelatedIds(id) {
465
+ return getRelatedIds(this, id);
466
+ }
467
+ getContent(idA, idB) {
468
+ return getContent(this, idA, idB);
469
+ }
470
+ getRelationEntries(id) {
471
+ return getRelationEntries(this, id);
472
+ }
473
+ getRelationRecord(id) {
474
+ return getRelationRecord(this, id);
475
+ }
476
+ getRelation(id) {
477
+ return getRelations(this, id)[0];
478
+ }
479
+ getRelations(id) {
480
+ return getRelations(this, id);
481
+ }
482
+ setRelations(id, relations) {
483
+ return new Join(setRelations(this, id, relations));
484
+ }
485
+ set(idA, idB, ...rest) {
486
+ return new Join(setRelationWithContent(this, idA, idB, ...rest));
487
+ }
488
+ remove(idA, idB) {
489
+ return new Join(removeRelation(this, idA, idB));
490
+ }
491
+ };
492
+
493
+ // src/internal/store.ts
494
+ var createStore = (name) => ({
495
+ valueMap: import_hamt_plus.default.make(),
496
+ selectorGraph: new Join({ relationType: `n:n` }),
497
+ atoms: import_hamt_plus.default.make(),
498
+ selectors: import_hamt_plus.default.make(),
499
+ readonlySelectors: import_hamt_plus.default.make(),
500
+ operation: {
501
+ open: false
502
+ },
503
+ transaction: {
504
+ open: false
505
+ },
506
+ config: {
507
+ name,
508
+ logger: null
509
+ }
510
+ });
511
+ var IMPLICIT = {
512
+ STORE_INTERNAL: void 0,
513
+ get STORE() {
514
+ var _a;
515
+ return (_a = this.STORE_INTERNAL) != null ? _a : this.STORE_INTERNAL = createStore(`DEFAULT`);
516
+ }
517
+ };
518
+ var configure = (config, store = IMPLICIT.STORE) => {
519
+ Object.assign(store.config, config);
520
+ };
521
+ var clearStore = (store = IMPLICIT.STORE) => {
522
+ const { config } = store;
523
+ Object.assign(store, createStore(config.name));
524
+ store.config = config;
525
+ };
526
+
527
+ // src/internal/get.ts
528
+ var getCachedState = (state, store = IMPLICIT.STORE) => {
529
+ const value = import_hamt_plus2.default.get(state.key, store.valueMap);
530
+ return value;
531
+ };
532
+ var getSelectorState = (selector2) => selector2.get();
533
+ function withdraw(token, store) {
534
+ var _a, _b;
535
+ return (_b = (_a = import_hamt_plus2.default.get(token.key, store.atoms)) != null ? _a : import_hamt_plus2.default.get(token.key, store.selectors)) != null ? _b : import_hamt_plus2.default.get(token.key, store.readonlySelectors);
536
+ }
537
+ function deposit(state) {
538
+ if (`get` in state) {
539
+ if (`set` in state) {
540
+ return { key: state.key, type: `selector` };
541
+ }
542
+ return { key: state.key, type: `readonly_selector` };
543
+ }
544
+ return { key: state.key, type: `atom` };
545
+ }
546
+ var getState__INTERNAL = (state, store = IMPLICIT.STORE) => {
547
+ var _a;
548
+ if (import_hamt_plus2.default.has(state.key, store.valueMap)) {
549
+ return getCachedState(state, store);
550
+ }
551
+ if (`get` in state) {
552
+ return getSelectorState(state);
553
+ }
554
+ (_a = store.config.logger) == null ? void 0 : _a.error(
555
+ `Attempted to get atom "${state.key}", which was never initialized in store "${store.config.name}".`
556
+ );
557
+ return state.default;
558
+ };
559
+
560
+ // src/internal/set.ts
561
+ var import_hamt_plus4 = __toESM(require("hamt_plus"));
562
+
563
+ // src/internal/operation.ts
564
+ var import_hamt_plus3 = __toESM(require("hamt_plus"));
565
+ var finishAction = (store) => {
566
+ var _a;
567
+ store.operation = { open: false };
568
+ (_a = store.config.logger) == null ? void 0 : _a.info(` \u2705`, `operation complete`);
569
+ };
570
+ var startAction = (store) => {
571
+ var _a;
572
+ store.operation = {
573
+ open: true,
574
+ done: /* @__PURE__ */ new Set(),
575
+ prev: store.valueMap
576
+ };
577
+ (_a = store.config.logger) == null ? void 0 : _a.info(` \u26A0\uFE0F`, `action started`);
578
+ };
579
+ var isDone = (key, store = IMPLICIT.STORE) => {
580
+ var _a;
581
+ if (!store.operation.open) {
582
+ (_a = store.config.logger) == null ? void 0 : _a.warn(
583
+ `isDone called outside of an action. This is probably a bug.`
584
+ );
585
+ return true;
586
+ }
587
+ return store.operation.done.has(key);
588
+ };
589
+ var markDone = (key, store = IMPLICIT.STORE) => {
590
+ var _a;
591
+ if (!store.operation.open) {
592
+ (_a = store.config.logger) == null ? void 0 : _a.warn(
593
+ `markDone called outside of an action. This is probably a bug.`
594
+ );
595
+ return;
596
+ }
597
+ store.operation.done.add(key);
598
+ };
599
+ var recall = (state, store = IMPLICIT.STORE) => {
600
+ var _a;
601
+ if (!store.operation.open) {
602
+ (_a = store.config.logger) == null ? void 0 : _a.warn(
603
+ `recall called outside of an action. This is probably a bug.`
604
+ );
605
+ return import_hamt_plus3.default.get(state.key, store.valueMap);
606
+ }
607
+ return import_hamt_plus3.default.get(state.key, store.operation.prev);
608
+ };
609
+
610
+ // src/internal/set.ts
611
+ var propagateChanges = (state, store = IMPLICIT.STORE) => {
612
+ var _a, _b;
613
+ const relatedStateKeys = store.selectorGraph.getRelations(state.key);
614
+ (_a = store.config.logger) == null ? void 0 : _a.info(
615
+ ` ||`,
616
+ `bumping`,
617
+ relatedStateKeys.length,
618
+ `states:`,
619
+ relatedStateKeys.map(({ id }) => id)
620
+ );
621
+ if (store.operation.open) {
622
+ (_b = store.config.logger) == null ? void 0 : _b.info(` ||`, `done:`, store.operation.done);
623
+ }
624
+ relatedStateKeys.forEach(({ id: stateKey }) => {
625
+ var _a2, _b2, _c, _d;
626
+ if (isDone(stateKey, store)) {
627
+ (_a2 = store.config.logger) == null ? void 0 : _a2.info(` ||`, stateKey, `already done`);
628
+ return;
629
+ }
630
+ (_b2 = store.config.logger) == null ? void 0 : _b2.info(`->`, `bumping`, stateKey);
631
+ store.valueMap = import_hamt_plus4.default.remove(stateKey, store.valueMap);
632
+ const state2 = (_c = import_hamt_plus4.default.get(stateKey, store.selectors)) != null ? _c : import_hamt_plus4.default.get(stateKey, store.readonlySelectors);
633
+ const newValue = getState__INTERNAL(state2, store);
634
+ (_d = store.config.logger) == null ? void 0 : _d.info(` <-`, stateKey, `became`, newValue);
635
+ const oldValue = recall(state2, store);
636
+ state2.subject.next({ newValue, oldValue });
637
+ markDone(stateKey, store);
638
+ if (`set` in state2)
639
+ propagateChanges(state2, store);
640
+ });
641
+ };
642
+ var setAtomState = (atom2, next, store = IMPLICIT.STORE) => {
643
+ var _a, _b;
644
+ const oldValue = getState__INTERNAL(atom2, store);
645
+ const newValue = become(next)(oldValue);
646
+ (_a = store.config.logger) == null ? void 0 : _a.info(
647
+ `->`,
648
+ `setting atom`,
649
+ `"${atom2.key}"`,
650
+ `to`,
651
+ newValue
652
+ );
653
+ store.valueMap = import_hamt_plus4.default.set(atom2.key, newValue, store.valueMap);
654
+ markDone(atom2.key, store);
655
+ atom2.subject.next({ newValue, oldValue });
656
+ (_b = store.config.logger) == null ? void 0 : _b.info(` ||`, `propagating change to`, `"${atom2.key}"`);
657
+ propagateChanges(atom2, store);
658
+ };
659
+ var setSelectorState = (selector2, next, store = IMPLICIT.STORE) => {
660
+ var _a, _b;
661
+ const oldValue = getState__INTERNAL(selector2, store);
662
+ const newValue = become(next)(oldValue);
663
+ (_a = store.config.logger) == null ? void 0 : _a.info(
664
+ `->`,
665
+ `setting selector`,
666
+ `"${selector2.key}"`,
667
+ `to`,
668
+ newValue
669
+ );
670
+ (_b = store.config.logger) == null ? void 0 : _b.info(
671
+ ` ||`,
672
+ `propagating change to`,
673
+ `"${selector2.key}"`
674
+ );
675
+ selector2.set(newValue);
676
+ markDone(selector2.key, store);
677
+ propagateChanges(selector2, store);
678
+ };
679
+ var setState__INTERNAL = (token, value, store = IMPLICIT.STORE) => {
680
+ const state = withdraw(token, store);
681
+ if (`set` in state) {
682
+ setSelectorState(state, value, store);
683
+ } else {
684
+ setAtomState(state, value, store);
685
+ }
686
+ };
687
+
688
+ // src/internal/transaction-internal.ts
689
+ var finishTransaction = (store) => {
690
+ var _a;
691
+ store.transaction = { open: false };
692
+ (_a = store.config.logger) == null ? void 0 : _a.info(`\u{1F4B8}`, `transaction done`);
693
+ };
694
+ var startTransaction = (store) => {
695
+ var _a;
696
+ store.transaction = {
697
+ open: true,
698
+ prev: {
699
+ atoms: store.atoms,
700
+ readonlySelectors: store.readonlySelectors,
701
+ selectorGraph: store.selectorGraph,
702
+ selectors: store.selectors,
703
+ valueMap: store.valueMap
704
+ }
705
+ };
706
+ (_a = store.config.logger) == null ? void 0 : _a.info(`\u{1F3E6}`, `transaction start`);
707
+ };
708
+ var abortTransaction = (store) => {
709
+ var _a, _b;
710
+ if (!store.transaction.open) {
711
+ (_a = store.config.logger) == null ? void 0 : _a.warn(
712
+ `abortTransaction called outside of a transaction. This is probably a bug.`
713
+ );
714
+ return;
715
+ }
716
+ store.atoms = store.transaction.prev.atoms;
717
+ store.readonlySelectors = store.transaction.prev.readonlySelectors;
718
+ store.selectorGraph = store.transaction.prev.selectorGraph;
719
+ store.selectors = store.transaction.prev.selectors;
720
+ store.valueMap = store.transaction.prev.valueMap;
721
+ store.transaction = { open: false };
722
+ (_b = store.config.logger) == null ? void 0 : _b.info(`\u{1FA82}`, `transaction fail`);
723
+ };
724
+
725
+ // src/atom.ts
726
+ var import_hamt_plus5 = __toESM(require("hamt_plus"));
727
+ var Rx = __toESM(require("rxjs"));
728
+
729
+ // ../anvl/src/json/index.ts
730
+ var import_function8 = require("fp-ts/function");
731
+ var stringifyJson = (json) => JSON.stringify(json);
732
+
733
+ // src/atom.ts
734
+ var atom = (options, store = IMPLICIT.STORE) => {
735
+ var _a, _b, _c;
736
+ if (import_hamt_plus5.default.has(options.key, store.atoms)) {
737
+ (_b = (_a = store.config.logger) == null ? void 0 : _a.error) == null ? void 0 : _b.call(
738
+ _a,
739
+ `Key "${options.key}" already exists in the store.`
740
+ );
741
+ return deposit(store.atoms.get(options.key));
742
+ }
743
+ const subject = new Rx.Subject();
744
+ const newAtom = __spreadProps(__spreadValues({}, options), { subject });
745
+ store.atoms = import_hamt_plus5.default.set(options.key, newAtom, store.atoms);
746
+ store.valueMap = import_hamt_plus5.default.set(options.key, options.default, store.valueMap);
747
+ const token = deposit(newAtom);
748
+ const setSelf = (next) => setState(token, next, store);
749
+ const onSet = (observe) => subscribe(token, observe, store);
750
+ setSelf(options.default);
751
+ (_c = options.effects) == null ? void 0 : _c.forEach((effect) => effect({ setSelf, onSet }));
752
+ return token;
753
+ };
754
+ var atomFamily = (options, store = IMPLICIT.STORE) => (key) => {
755
+ var _a;
756
+ const fullKey = `${options.key}__${stringifyJson(key)}`;
757
+ const existing = store.atoms.get(fullKey);
758
+ if (existing) {
759
+ return deposit(existing);
760
+ }
761
+ return atom(
762
+ {
763
+ key: fullKey,
764
+ default: options.default instanceof Function ? options.default(key) : options.default,
765
+ effects: (_a = options.effects) == null ? void 0 : _a.call(options, key)
766
+ },
767
+ store
768
+ );
769
+ };
770
+
771
+ // src/selector.ts
772
+ var import_hamt_plus6 = __toESM(require("hamt_plus"));
773
+ var Rx2 = __toESM(require("rxjs"));
774
+ function selector(options, store = IMPLICIT.STORE) {
775
+ var _a, _b;
776
+ if (import_hamt_plus6.default.has(options.key, store.selectors)) {
777
+ throw new Error(`Key "${options.key}" already exists in the store.`);
778
+ }
779
+ const subject = new Rx2.Subject();
780
+ const { get, set } = registerSelector(options.key, store);
781
+ const getSelf = () => {
782
+ const value = options.get({ get });
783
+ store.valueMap = import_hamt_plus6.default.set(options.key, value, store.valueMap);
784
+ return value;
785
+ };
786
+ if (!(`set` in options)) {
787
+ const readonlySelector = __spreadProps(__spreadValues({}, options), {
788
+ subject,
789
+ get: getSelf
790
+ });
791
+ store.readonlySelectors = import_hamt_plus6.default.set(
792
+ options.key,
793
+ readonlySelector,
794
+ store.readonlySelectors
795
+ );
796
+ const initialValue2 = getSelf();
797
+ (_a = store.config.logger) == null ? void 0 : _a.info(` \u2728`, options.key, `=`, initialValue2);
798
+ return __spreadProps(__spreadValues({}, readonlySelector), { type: `readonly_selector` });
799
+ }
800
+ const setSelf = (next) => {
801
+ var _a2;
802
+ (_a2 = store.config.logger) == null ? void 0 : _a2.info(`${options.key}.set`, next);
803
+ const oldValue = getSelf();
804
+ const newValue = become(next)(oldValue);
805
+ store.valueMap = import_hamt_plus6.default.set(options.key, newValue, store.valueMap);
806
+ console.error({ oldValue });
807
+ subject.next({ newValue, oldValue });
808
+ options.set({ get, set }, newValue);
809
+ };
810
+ const mySelector = __spreadProps(__spreadValues({}, options), {
811
+ subject,
812
+ get: getSelf,
813
+ set: setSelf
814
+ });
815
+ store.selectors = import_hamt_plus6.default.set(options.key, mySelector, store.selectors);
816
+ const initialValue = getSelf();
817
+ (_b = store.config.logger) == null ? void 0 : _b.info(` \u2728`, options.key, `=`, initialValue);
818
+ return __spreadProps(__spreadValues({}, mySelector), { type: `selector` });
819
+ }
820
+ function selectorFamily(options, store = IMPLICIT.STORE) {
821
+ return (key) => {
822
+ var _a;
823
+ const fullKey = `${options.key}__${stringifyJson(key)}`;
824
+ const existing = (_a = store.selectors.get(fullKey)) != null ? _a : store.readonlySelectors.get(fullKey);
825
+ if (existing) {
826
+ return deposit(existing);
827
+ }
828
+ const readonlySelectorOptions = {
829
+ key: fullKey,
830
+ get: options.get(key)
831
+ };
832
+ if (!(`set` in options)) {
833
+ return selector(
834
+ __spreadValues({}, readonlySelectorOptions),
835
+ store
836
+ );
837
+ }
838
+ return selector(
839
+ __spreadProps(__spreadValues({}, readonlySelectorOptions), {
840
+ set: options.set(key)
841
+ }),
842
+ store
843
+ );
844
+ };
845
+ }
846
+ var registerSelector = (selectorKey, store = IMPLICIT.STORE) => ({
847
+ get: (state) => {
848
+ var _a, _b, _c;
849
+ const isRegistered = store.selectorGraph.getRelatedIds(selectorKey).includes(state.key);
850
+ if (isRegistered) {
851
+ (_a = store.config.logger) == null ? void 0 : _a.info(` ||`, selectorKey, `<-`, state.key);
852
+ } else {
853
+ (_b = store.config.logger) == null ? void 0 : _b.info(
854
+ `\u{1F50C} registerSelector`,
855
+ state.key,
856
+ `->`,
857
+ selectorKey
858
+ );
859
+ store.selectorGraph = store.selectorGraph.set(selectorKey, state.key);
860
+ }
861
+ const currentValue = getState(state, store);
862
+ (_c = store.config.logger) == null ? void 0 : _c.info(` ||`, state.key, `=`, currentValue);
863
+ return currentValue;
864
+ },
865
+ set: (token, newValue) => {
866
+ store.selectorGraph.set(token.key, selectorKey);
867
+ setState__INTERNAL(token, newValue, store);
868
+ }
869
+ });
870
+
871
+ // src/transaction.ts
872
+ var transaction = (options, store = IMPLICIT.STORE) => Object.assign(
873
+ (...parameters) => {
874
+ var _a;
875
+ startTransaction(store);
876
+ try {
877
+ const result = options.do(
878
+ {
879
+ get: (token) => getState(token, store),
880
+ set: (token, value) => setState(token, value, store)
881
+ },
882
+ ...parameters
883
+ );
884
+ finishTransaction(store);
885
+ return result;
886
+ } catch (thrown) {
887
+ abortTransaction(store);
888
+ (_a = store.config.logger) == null ? void 0 : _a.error(`Transaction ${options.key} failed`, thrown);
889
+ throw thrown;
890
+ }
891
+ },
892
+ { key: options.key }
893
+ );
894
+
895
+ // src/index.ts
896
+ var getState = (token, store = IMPLICIT.STORE) => {
897
+ const state = withdraw(token, store);
898
+ return getState__INTERNAL(state, store);
899
+ };
900
+ var setState = (state, value, store = IMPLICIT.STORE) => {
901
+ startAction(store);
902
+ setState__INTERNAL(state, value, store);
903
+ finishAction(store);
904
+ };
905
+ var subscribe = (token, observe, store = IMPLICIT.STORE) => {
906
+ const state = withdraw(token, store);
907
+ const subscription = state.subject.subscribe(observe);
908
+ return () => subscription.unsubscribe();
909
+ };
910
+ // Annotate the CommonJS export names for ESM import in node:
911
+ 0 && (module.exports = {
912
+ __INTERNAL__,
913
+ atom,
914
+ atomFamily,
915
+ configure,
916
+ getState,
917
+ registerSelector,
918
+ selector,
919
+ selectorFamily,
920
+ setState,
921
+ subscribe,
922
+ transaction
923
+ });