cross-state 0.6.6 → 0.6.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/dist/cjs/_virtual/use-sync-external-store-with-selector.development.cjs +103 -0
  2. package/dist/cjs/_virtual/use-sync-external-store-with-selector.development.cjs.map +1 -0
  3. package/dist/cjs/_virtual/use-sync-external-store-with-selector.development2.cjs +5 -0
  4. package/dist/cjs/_virtual/use-sync-external-store-with-selector.development2.cjs.map +1 -0
  5. package/dist/cjs/_virtual/use-sync-external-store-with-selector.production.min.cjs +71 -0
  6. package/dist/cjs/_virtual/use-sync-external-store-with-selector.production.min.cjs.map +1 -0
  7. package/dist/cjs/_virtual/use-sync-external-store-with-selector.production.min2.cjs +5 -0
  8. package/dist/cjs/_virtual/use-sync-external-store-with-selector.production.min2.cjs.map +1 -0
  9. package/dist/cjs/_virtual/with-selector.cjs +12 -0
  10. package/dist/cjs/_virtual/with-selector.cjs.map +1 -0
  11. package/dist/cjs/_virtual/with-selector2.cjs +13 -0
  12. package/dist/cjs/_virtual/with-selector2.cjs.map +1 -0
  13. package/dist/cjs/core/cache.cjs +227 -0
  14. package/dist/cjs/core/cache.cjs.map +1 -0
  15. package/dist/cjs/core/resourceGroup.cjs +53 -0
  16. package/dist/cjs/core/resourceGroup.cjs.map +1 -0
  17. package/dist/cjs/core/store.cjs +259 -0
  18. package/dist/cjs/core/store.cjs.map +1 -0
  19. package/dist/cjs/immer/immerActions.cjs +10 -0
  20. package/dist/cjs/immer/immerActions.cjs.map +1 -0
  21. package/dist/cjs/immer.cjs +2 -7
  22. package/dist/cjs/immer.cjs.map +1 -1
  23. package/dist/cjs/index.cjs +19 -299
  24. package/dist/cjs/index.cjs.map +1 -1
  25. package/dist/cjs/lib/calcDuration.cjs +9 -0
  26. package/dist/cjs/lib/calcDuration.cjs.map +1 -0
  27. package/dist/cjs/lib/calculationHelper.cjs +140 -0
  28. package/dist/cjs/lib/calculationHelper.cjs.map +1 -0
  29. package/dist/cjs/lib/callable.cjs +11 -0
  30. package/dist/cjs/lib/callable.cjs.map +1 -0
  31. package/dist/cjs/lib/clone.cjs +19 -0
  32. package/dist/cjs/lib/clone.cjs.map +1 -0
  33. package/dist/cjs/lib/debounce.cjs +28 -0
  34. package/dist/cjs/lib/debounce.cjs.map +1 -0
  35. package/dist/cjs/lib/equals.cjs +5 -0
  36. package/dist/cjs/lib/equals.cjs.map +1 -0
  37. package/dist/cjs/lib/forwardError.cjs +9 -0
  38. package/dist/cjs/lib/forwardError.cjs.map +1 -0
  39. package/dist/cjs/lib/hash.cjs +19 -0
  40. package/dist/cjs/lib/hash.cjs.map +1 -0
  41. package/dist/cjs/lib/instanceCache.cjs +68 -0
  42. package/dist/cjs/lib/instanceCache.cjs.map +1 -0
  43. package/dist/cjs/lib/makeSelector.cjs +14 -0
  44. package/dist/cjs/lib/makeSelector.cjs.map +1 -0
  45. package/dist/cjs/lib/propAccess.cjs +66 -0
  46. package/dist/cjs/lib/propAccess.cjs.map +1 -0
  47. package/dist/cjs/lib/queue.cjs +61 -0
  48. package/dist/cjs/lib/queue.cjs.map +1 -0
  49. package/dist/cjs/lib/standardMethods.cjs +78 -0
  50. package/dist/cjs/lib/standardMethods.cjs.map +1 -0
  51. package/dist/cjs/lib/throttle.cjs +25 -0
  52. package/dist/cjs/lib/throttle.cjs.map +1 -0
  53. package/dist/cjs/lib/trackingProxy.cjs +39 -0
  54. package/dist/cjs/lib/trackingProxy.cjs.map +1 -0
  55. package/dist/cjs/react/read.cjs +15 -0
  56. package/dist/cjs/react/read.cjs.map +1 -0
  57. package/dist/cjs/react/storeScope.cjs +31 -0
  58. package/dist/cjs/react/storeScope.cjs.map +1 -0
  59. package/dist/cjs/react/useCache.cjs +31 -0
  60. package/dist/cjs/react/useCache.cjs.map +1 -0
  61. package/dist/cjs/react/useProp.cjs +9 -0
  62. package/dist/cjs/react/useProp.cjs.map +1 -0
  63. package/dist/cjs/react/useStore.cjs +51 -0
  64. package/dist/cjs/react/useStore.cjs.map +1 -0
  65. package/dist/cjs/react.cjs +11 -289
  66. package/dist/cjs/react.cjs.map +1 -1
  67. package/dist/es/_virtual/use-sync-external-store-with-selector.development.js +103 -0
  68. package/dist/es/_virtual/use-sync-external-store-with-selector.development.js.map +1 -0
  69. package/dist/es/_virtual/use-sync-external-store-with-selector.development2.js +5 -0
  70. package/dist/es/_virtual/use-sync-external-store-with-selector.development2.js.map +1 -0
  71. package/dist/es/_virtual/use-sync-external-store-with-selector.production.min.js +71 -0
  72. package/dist/es/_virtual/use-sync-external-store-with-selector.production.min.js.map +1 -0
  73. package/dist/es/_virtual/use-sync-external-store-with-selector.production.min2.js +5 -0
  74. package/dist/es/_virtual/use-sync-external-store-with-selector.production.min2.js.map +1 -0
  75. package/dist/es/_virtual/with-selector.js +11 -0
  76. package/dist/es/_virtual/with-selector.js.map +1 -0
  77. package/dist/es/_virtual/with-selector2.js +14 -0
  78. package/dist/es/_virtual/with-selector2.js.map +1 -0
  79. package/dist/es/core/cache.js +227 -0
  80. package/dist/es/core/cache.js.map +1 -0
  81. package/dist/es/core/resourceGroup.js +53 -0
  82. package/dist/es/core/resourceGroup.js.map +1 -0
  83. package/dist/es/core/store.js +259 -0
  84. package/dist/es/core/store.js.map +1 -0
  85. package/dist/es/{immer.mjs → immer/immerActions.js} +1 -1
  86. package/dist/es/immer/immerActions.js.map +1 -0
  87. package/dist/es/immer.js +5 -0
  88. package/dist/es/immer.js.map +1 -0
  89. package/dist/es/index.js +22 -0
  90. package/dist/es/index.js.map +1 -0
  91. package/dist/es/lib/calcDuration.js +9 -0
  92. package/dist/es/lib/calcDuration.js.map +1 -0
  93. package/dist/es/lib/calculationHelper.js +140 -0
  94. package/dist/es/lib/calculationHelper.js.map +1 -0
  95. package/dist/es/lib/callable.js +11 -0
  96. package/dist/es/lib/callable.js.map +1 -0
  97. package/dist/es/lib/clone.js +19 -0
  98. package/dist/es/lib/clone.js.map +1 -0
  99. package/dist/es/lib/debounce.js +28 -0
  100. package/dist/es/lib/debounce.js.map +1 -0
  101. package/dist/es/lib/equals.js +5 -0
  102. package/dist/es/lib/equals.js.map +1 -0
  103. package/dist/es/lib/forwardError.js +9 -0
  104. package/dist/es/lib/forwardError.js.map +1 -0
  105. package/dist/es/lib/hash.js +19 -0
  106. package/dist/es/lib/hash.js.map +1 -0
  107. package/dist/es/lib/instanceCache.js +68 -0
  108. package/dist/es/lib/instanceCache.js.map +1 -0
  109. package/dist/es/lib/makeSelector.js +14 -0
  110. package/dist/es/lib/makeSelector.js.map +1 -0
  111. package/dist/es/lib/propAccess.js +66 -0
  112. package/dist/es/lib/propAccess.js.map +1 -0
  113. package/dist/es/lib/queue.js +61 -0
  114. package/dist/es/lib/queue.js.map +1 -0
  115. package/dist/es/lib/standardMethods.js +78 -0
  116. package/dist/es/lib/standardMethods.js.map +1 -0
  117. package/dist/es/lib/throttle.js +25 -0
  118. package/dist/es/lib/throttle.js.map +1 -0
  119. package/dist/es/lib/trackingProxy.js +39 -0
  120. package/dist/es/lib/trackingProxy.js.map +1 -0
  121. package/dist/es/react/read.js +15 -0
  122. package/dist/es/react/read.js.map +1 -0
  123. package/dist/es/react/storeScope.js +31 -0
  124. package/dist/es/react/storeScope.js.map +1 -0
  125. package/dist/es/react/useCache.js +31 -0
  126. package/dist/es/react/useCache.js.map +1 -0
  127. package/dist/es/react/useProp.js +9 -0
  128. package/dist/es/react/useProp.js.map +1 -0
  129. package/dist/es/react/useStore.js +51 -0
  130. package/dist/es/react/useStore.js.map +1 -0
  131. package/dist/es/react.js +14 -0
  132. package/dist/es/react.js.map +1 -0
  133. package/dist/types/core/cache.d.ts +13 -11
  134. package/dist/types/core/store.d.ts +5 -3
  135. package/dist/types/lib/callable.d.ts +4 -0
  136. package/dist/types/lib/instanceCache.d.ts +2 -2
  137. package/package.json +8 -8
  138. package/dist/cjs/hash.cjs +0 -718
  139. package/dist/cjs/hash.cjs.map +0 -1
  140. package/dist/es/hash.mjs +0 -719
  141. package/dist/es/hash.mjs.map +0 -1
  142. package/dist/es/immer.mjs.map +0 -1
  143. package/dist/es/index.mjs +0 -303
  144. package/dist/es/index.mjs.map +0 -1
  145. package/dist/es/react.mjs +0 -292
  146. package/dist/es/react.mjs.map +0 -1
  147. package/dist/types/lib/bind.d.ts +0 -1
@@ -0,0 +1,259 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const calcDuration = require("../lib/calcDuration.cjs");
4
+ const calculationHelper = require("../lib/calculationHelper.cjs");
5
+ const callable = require("../lib/callable.cjs");
6
+ const debounce = require("../lib/debounce.cjs");
7
+ const equals = require("../lib/equals.cjs");
8
+ const forwardError = require("../lib/forwardError.cjs");
9
+ const makeSelector = require("../lib/makeSelector.cjs");
10
+ const propAccess = require("../lib/propAccess.cjs");
11
+ const standardMethods = require("../lib/standardMethods.cjs");
12
+ const throttle = require("../lib/throttle.cjs");
13
+ const noop = () => void 0;
14
+ class Store extends callable.Callable {
15
+ constructor(getter, options = {}, derivedFrom, _call = () => void 0) {
16
+ super(_call);
17
+ this.getter = getter;
18
+ this.options = options;
19
+ this.derivedFrom = derivedFrom;
20
+ this._call = _call;
21
+ this.listeners = /* @__PURE__ */ new Map();
22
+ this.effects = /* @__PURE__ */ new Map();
23
+ this.notifyId = {};
24
+ this.calculationHelper = new calculationHelper.CalculationHelper({
25
+ calculate: ({ use }) => {
26
+ if (this.getter instanceof Function) {
27
+ const value = this.getter.apply({ use }, [{ use }]);
28
+ this._value = { v: value };
29
+ this.notify();
30
+ }
31
+ },
32
+ addEffect: this.addEffect.bind(this),
33
+ onInvalidate: this.reset.bind(this)
34
+ });
35
+ this.get = this.get.bind(this);
36
+ this.set = this.set.bind(this);
37
+ this.sub = this.sub.bind(this);
38
+ this.once = this.once.bind(this);
39
+ this.map = this.map.bind(this);
40
+ this.addEffect = this.addEffect.bind(this);
41
+ this.isActive = this.isActive.bind(this);
42
+ if (!(getter instanceof Function)) {
43
+ this._value = { v: getter };
44
+ }
45
+ }
46
+ get() {
47
+ this.calculationHelper.check();
48
+ if (!this._value) {
49
+ this.calculationHelper.execute();
50
+ return this.get();
51
+ }
52
+ return this._value.v;
53
+ }
54
+ set(...args) {
55
+ const path = args.length > 1 ? args[0] : [];
56
+ let update = args.length > 1 ? args[1] : args[0];
57
+ if (update instanceof Function) {
58
+ const before = this.get();
59
+ const valueBefore = propAccess.get(before, path);
60
+ const valueAfter = update(valueBefore);
61
+ update = propAccess.set(before, path, valueAfter);
62
+ } else if (path.length > 0) {
63
+ update = propAccess.set(this.get(), path, update);
64
+ }
65
+ if (this.derivedFrom && this.derivedFrom.selectors.every((selector) => typeof selector === "string")) {
66
+ const derivationPath = this.derivedFrom.selectors.join(".");
67
+ this.derivedFrom.store.set((before) => propAccess.set(before, derivationPath, update));
68
+ return;
69
+ }
70
+ if (this.derivedFrom) {
71
+ throw new TypeError(
72
+ "Can only updated computed stores that are derived from other stores using string selectors"
73
+ );
74
+ }
75
+ this._value = { v: update };
76
+ this.notify();
77
+ }
78
+ reset() {
79
+ this._value = void 0;
80
+ if (this.isActive()) {
81
+ this.calculationHelper.execute();
82
+ }
83
+ }
84
+ sub(listener, options) {
85
+ var _a;
86
+ const {
87
+ passive,
88
+ runNow = true,
89
+ throttle: throttleOption,
90
+ debounce: debounceOption,
91
+ equals: equals$1 = equals.defaultEquals
92
+ } = options ?? {};
93
+ let compareToValue = (_a = this._value) == null ? void 0 : _a.v;
94
+ let previousValue;
95
+ let hasRun = false;
96
+ let innerListener = (force) => {
97
+ if (!this._value) {
98
+ return;
99
+ }
100
+ const value = this._value.v;
101
+ if (!force && equals$1(value, compareToValue)) {
102
+ return;
103
+ }
104
+ compareToValue = value;
105
+ const _previousValue = previousValue;
106
+ previousValue = value;
107
+ hasRun = true;
108
+ try {
109
+ listener(value, _previousValue);
110
+ } catch (error) {
111
+ forwardError.forwardError(error);
112
+ }
113
+ };
114
+ if (throttleOption) {
115
+ innerListener = throttle.throttle(innerListener, throttleOption);
116
+ } else if (debounceOption) {
117
+ innerListener = debounce.debounce(innerListener, debounceOption);
118
+ }
119
+ this.listeners.set(innerListener, !passive);
120
+ if (!passive) {
121
+ this.onSubscribe();
122
+ }
123
+ if (runNow && !hasRun) {
124
+ innerListener(true);
125
+ }
126
+ return () => {
127
+ this.listeners.delete(innerListener);
128
+ if (!passive) {
129
+ this.onUnsubscribe();
130
+ }
131
+ };
132
+ }
133
+ once(condition = (value) => !!value) {
134
+ return new Promise((resolve) => {
135
+ let stopped = false;
136
+ const cancel = this.sub(
137
+ (value) => {
138
+ if (stopped || condition && !condition(value)) {
139
+ return;
140
+ }
141
+ resolve(value);
142
+ stopped = true;
143
+ setTimeout(() => cancel());
144
+ },
145
+ {
146
+ runNow: !!condition
147
+ }
148
+ );
149
+ });
150
+ }
151
+ map(_selector, options) {
152
+ const selector = makeSelector.makeSelector(_selector);
153
+ const derivedFrom = {
154
+ store: this.derivedFrom ? this.derivedFrom.store : this,
155
+ selectors: this.derivedFrom ? [...this.derivedFrom.selectors, _selector] : [_selector]
156
+ };
157
+ return new Store(
158
+ ({ use }) => {
159
+ return selector(use(this, options));
160
+ },
161
+ this.options,
162
+ derivedFrom
163
+ );
164
+ }
165
+ /** Add an effect that will be executed when the store becomes active, which means when it has at least one subscriber.
166
+ * @param effect
167
+ * If there is already a subscriber, the effect will be executed immediately.
168
+ * Otherweise it will be executed as soon as the first subscription is created.
169
+ * Every time all subscriptions are removed and the first is created again, the effect will be executed again.
170
+ * @param retain
171
+ * If provided, delay tearing down effects when the last subscriber is removed. This is useful if a short gap in subscriber coverage is supposed to be ignored. E.g. when switching pages, the old page might unsubscribe, while the new page subscribes immediately after.
172
+ * @returns
173
+ * The effect can return a teardown callback, which will be executed when the last subscription is removed and potentially the ratain time has passed.
174
+ */
175
+ addEffect(effect, retain) {
176
+ this.effects.set(effect, {
177
+ handle: this.isActive() ? effect() ?? noop : void 0,
178
+ retain: retain !== void 0 ? calcDuration.calcDuration(retain) : void 0
179
+ });
180
+ return () => {
181
+ const { handle, timeout } = this.effects.get(effect) ?? {};
182
+ handle == null ? void 0 : handle();
183
+ if (timeout !== void 0) {
184
+ clearTimeout(timeout);
185
+ }
186
+ this.effects.delete(effect);
187
+ };
188
+ }
189
+ /** Return whether the store is currently active, which means whether it has at least one subscriber. */
190
+ isActive() {
191
+ return [...this.listeners.values()].some(Boolean);
192
+ }
193
+ onSubscribe() {
194
+ if ([...this.listeners.values()].filter(Boolean).length > 1)
195
+ return;
196
+ for (const [effect, { handle, retain, timeout }] of this.effects.entries()) {
197
+ if (timeout !== void 0) {
198
+ clearTimeout(timeout);
199
+ }
200
+ this.effects.set(effect, {
201
+ handle: handle ?? effect() ?? noop,
202
+ retain,
203
+ timeout: void 0
204
+ });
205
+ }
206
+ }
207
+ onUnsubscribe() {
208
+ if ([...this.listeners.values()].some(Boolean))
209
+ return;
210
+ for (const [effect, { handle, retain, timeout }] of this.effects.entries()) {
211
+ if (!retain) {
212
+ handle == null ? void 0 : handle();
213
+ }
214
+ if (timeout !== void 0) {
215
+ clearTimeout(timeout);
216
+ }
217
+ this.effects.set(effect, {
218
+ handle: retain ? handle : void 0,
219
+ retain,
220
+ timeout: retain && handle ? setTimeout(handle, retain) : void 0
221
+ });
222
+ }
223
+ }
224
+ notify() {
225
+ const n = {};
226
+ this.notifyId = n;
227
+ const snapshot = [...this.listeners.keys()];
228
+ for (const listener of snapshot) {
229
+ listener();
230
+ if (n !== this.notifyId)
231
+ break;
232
+ }
233
+ }
234
+ }
235
+ const defaultOptions = {};
236
+ function create(initialState, options) {
237
+ const store = new Store(initialState, options);
238
+ if (initialState instanceof Function) {
239
+ return store;
240
+ }
241
+ let methods = options == null ? void 0 : options.methods;
242
+ if (initialState instanceof Map) {
243
+ methods = { ...standardMethods.mapMethods, ...methods };
244
+ } else if (initialState instanceof Set) {
245
+ methods = { ...standardMethods.setMethods, ...methods };
246
+ } else if (Array.isArray(initialState)) {
247
+ methods = { ...standardMethods.arrayMethods, ...methods };
248
+ } else if (initialState instanceof Object) {
249
+ methods = { ...standardMethods.recordMethods, ...methods };
250
+ }
251
+ const boundMethods = Object.fromEntries(
252
+ Object.entries(methods ?? {}).filter(([name]) => !(name in store)).map(([name, action]) => [name, action.bind(store)])
253
+ );
254
+ return Object.assign(store, boundMethods);
255
+ }
256
+ const createStore = Object.assign(create, { defaultOptions });
257
+ exports.Store = Store;
258
+ exports.createStore = createStore;
259
+ //# sourceMappingURL=store.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.cjs","sources":["../../../src/core/store.ts"],"sourcesContent":["import type {\n Cancel,\n Duration,\n Effect,\n Listener,\n Selector,\n SubscribeOptions,\n Update,\n Use,\n UseOptions,\n} from './commonTypes';\nimport { calcDuration } from '@lib/calcDuration';\nimport { CalculationHelper } from '@lib/calculationHelper';\nimport { Callable } from '@lib/callable';\nimport { debounce } from '@lib/debounce';\nimport { defaultEquals } from '@lib/equals';\nimport { forwardError } from '@lib/forwardError';\nimport { makeSelector } from '@lib/makeSelector';\nimport type { Path, Value } from '@lib/path';\nimport { get, set } from '@lib/propAccess';\nimport { arrayMethods, mapMethods, recordMethods, setMethods } from '@lib/standardMethods';\nimport { throttle } from '@lib/throttle';\n\nexport type StoreMethods = Record<string, (...args: any[]) => any>;\n\nexport type BoundStoreMethods<T, Methods extends StoreMethods> = Methods &\n ThisType<Store<T> & Methods>;\n\nexport interface StoreOptions {\n retain?: number;\n}\n\nexport interface StoreOptionsWithMethods<T, Methods extends StoreMethods> extends StoreOptions {\n methods?: Methods & ThisType<Store<T> & Methods & StandardMethods<T>>;\n}\n\nexport type Calculate<T> = (this: { use: Use }, fns: { use: Use }) => T;\n\ntype StandardMethods<T> = T extends Map<any, any>\n ? typeof mapMethods\n : T extends Set<any>\n ? typeof setMethods\n : T extends Array<any>\n ? typeof arrayMethods\n : T extends Record<any, any>\n ? typeof recordMethods\n : Record<string, never>;\n\ntype StoreWithMethods<T, Methods extends StoreMethods> = Store<T> &\n Omit<BoundStoreMethods<T, Methods>, keyof Store<T>> &\n StandardMethods<T>;\n\nconst noop = () => undefined;\n\nexport class Store<T> extends Callable<any, any> {\n protected _value?: { v: T };\n\n protected listeners = new Map<Listener, boolean>();\n\n protected effects = new Map<\n Effect,\n { handle?: Cancel; retain?: number; timeout?: ReturnType<typeof setTimeout> }\n >();\n\n protected notifyId = {};\n\n protected calculationHelper = new CalculationHelper({\n calculate: ({ use }) => {\n if (this.getter instanceof Function) {\n const value = this.getter.apply({ use }, [{ use }]);\n this._value = { v: value };\n this.notify();\n }\n },\n\n addEffect: this.addEffect.bind(this),\n onInvalidate: this.reset.bind(this),\n });\n\n constructor(\n public readonly getter: T | Calculate<T>,\n public readonly options: StoreOptions = {},\n public readonly derivedFrom?: {\n store: Store<any>;\n selectors: (Selector<any, any> | Path<any>)[];\n },\n protected readonly _call: (...args: any[]) => any = () => undefined,\n ) {\n super(_call);\n this.get = this.get.bind(this);\n this.set = this.set.bind(this);\n this.sub = this.sub.bind(this);\n this.once = this.once.bind(this);\n this.map = this.map.bind(this);\n this.addEffect = this.addEffect.bind(this);\n this.isActive = this.isActive.bind(this);\n\n if (!(getter instanceof Function)) {\n this._value = { v: getter };\n }\n }\n\n get(): T {\n this.calculationHelper.check();\n\n if (!this._value) {\n this.calculationHelper.execute();\n return this.get();\n }\n\n return this._value.v;\n }\n\n set(update: Update<T>): void;\n\n set<P extends Path<T>>(path: P, update: Update<Value<T, P>>): void;\n\n set(...args: any[]): void {\n const path: any = args.length > 1 ? args[0] : [];\n let update: Update<any> = args.length > 1 ? args[1] : args[0];\n\n if (update instanceof Function) {\n const before = this.get();\n const valueBefore = get(before, path);\n const valueAfter = update(valueBefore);\n update = set(before, path, valueAfter);\n } else if (path.length > 0) {\n update = set(this.get(), path, update);\n }\n\n if (\n this.derivedFrom &&\n this.derivedFrom.selectors.every((selector) => typeof selector === 'string')\n ) {\n const derivationPath = this.derivedFrom.selectors.join('.');\n this.derivedFrom.store.set((before: any) => set<any, any>(before, derivationPath, update));\n return;\n }\n\n if (this.derivedFrom) {\n throw new TypeError(\n 'Can only updated computed stores that are derived from other stores using string selectors',\n );\n }\n\n this._value = { v: update };\n this.notify();\n }\n\n protected reset() {\n this._value = undefined;\n\n if (this.isActive()) {\n this.calculationHelper.execute();\n }\n }\n\n sub(listener: Listener<T>, options?: SubscribeOptions): Cancel {\n const {\n passive,\n runNow = true,\n throttle: throttleOption,\n debounce: debounceOption,\n equals = defaultEquals,\n } = options ?? {};\n\n let compareToValue = this._value?.v;\n let previousValue: T | undefined;\n let hasRun = false;\n\n let innerListener = (force?: boolean | void) => {\n if (!this._value) {\n return;\n }\n\n const value = this._value.v;\n\n if (!force && equals(value, compareToValue)) {\n return;\n }\n\n compareToValue = value;\n const _previousValue = previousValue;\n previousValue = value;\n hasRun = true;\n\n try {\n listener(value, _previousValue);\n } catch (error) {\n forwardError(error);\n }\n };\n\n if (throttleOption) {\n innerListener = throttle(innerListener, throttleOption);\n } else if (debounceOption) {\n innerListener = debounce(innerListener, debounceOption);\n }\n\n this.listeners.set(innerListener, !passive);\n if (!passive) {\n this.onSubscribe();\n }\n\n if (runNow && !hasRun) {\n innerListener(true);\n }\n\n return () => {\n this.listeners.delete(innerListener);\n if (!passive) {\n this.onUnsubscribe();\n }\n };\n }\n\n once<S extends T>(condition: (value: T) => value is S): Promise<S>;\n\n once(condition?: (value: T) => boolean): Promise<T>;\n\n once(condition: (value: T) => boolean = (value) => !!value): Promise<any> {\n return new Promise<T>((resolve) => {\n let stopped = false;\n const cancel = this.sub(\n (value) => {\n if (stopped || (condition && !condition(value))) {\n return;\n }\n\n resolve(value);\n stopped = true;\n setTimeout(() => cancel());\n },\n {\n runNow: !!condition,\n },\n );\n });\n }\n\n map<S>(selector: Selector<T, S>, options?: UseOptions): Store<S>;\n\n map<P extends Path<T>>(selector: P, options?: UseOptions): Store<Value<T, P>>;\n\n map(_selector: Selector<T, any> | Path<any>, options?: UseOptions): Store<any> {\n const selector = makeSelector(_selector);\n const derivedFrom = {\n store: this.derivedFrom ? this.derivedFrom.store : this,\n selectors: this.derivedFrom ? [...this.derivedFrom.selectors, _selector] : [_selector],\n };\n\n return new Store(\n ({ use }) => {\n return selector(use(this, options));\n },\n this.options,\n derivedFrom,\n );\n }\n\n /** Add an effect that will be executed when the store becomes active, which means when it has at least one subscriber.\n * @param effect\n * If there is already a subscriber, the effect will be executed immediately.\n * Otherweise it will be executed as soon as the first subscription is created.\n * Every time all subscriptions are removed and the first is created again, the effect will be executed again.\n * @param retain\n * If provided, delay tearing down effects when the last subscriber is removed. This is useful if a short gap in subscriber coverage is supposed to be ignored. E.g. when switching pages, the old page might unsubscribe, while the new page subscribes immediately after.\n * @returns\n * The effect can return a teardown callback, which will be executed when the last subscription is removed and potentially the ratain time has passed.\n */\n addEffect(effect: Effect, retain?: Duration) {\n this.effects.set(effect, {\n handle: this.isActive() ? effect() ?? noop : undefined,\n retain: retain !== undefined ? calcDuration(retain) : undefined,\n });\n\n return () => {\n const { handle, timeout } = this.effects.get(effect) ?? {};\n handle?.();\n\n if (timeout !== undefined) {\n clearTimeout(timeout);\n }\n\n this.effects.delete(effect);\n };\n }\n\n /** Return whether the store is currently active, which means whether it has at least one subscriber. */\n isActive() {\n return [...this.listeners.values()].some(Boolean);\n }\n\n protected onSubscribe() {\n if ([...this.listeners.values()].filter(Boolean).length > 1) return;\n\n for (const [effect, { handle, retain, timeout }] of this.effects.entries()) {\n if (timeout !== undefined) {\n clearTimeout(timeout);\n }\n\n this.effects.set(effect, {\n handle: handle ?? effect() ?? noop,\n retain,\n timeout: undefined,\n });\n }\n }\n\n protected onUnsubscribe() {\n if ([...this.listeners.values()].some(Boolean)) return;\n\n for (const [effect, { handle, retain, timeout }] of this.effects.entries()) {\n if (!retain) {\n handle?.();\n }\n\n if (timeout !== undefined) {\n clearTimeout(timeout);\n }\n\n this.effects.set(effect, {\n handle: retain ? handle : undefined,\n retain,\n timeout: retain && handle ? setTimeout(handle, retain) : undefined,\n });\n }\n }\n\n protected notify() {\n const n = {};\n this.notifyId = n;\n\n const snapshot = [...this.listeners.keys()];\n for (const listener of snapshot) {\n listener();\n if (n !== this.notifyId) break;\n }\n }\n}\n\nconst defaultOptions: StoreOptions = {};\n\nfunction create<T>(\n calculate: (this: { use: Use }, fns: { use: Use }) => T,\n options?: StoreOptions,\n): Store<T>;\nfunction create<T, Methods extends StoreMethods = {}>(\n initialState: T,\n options?: StoreOptionsWithMethods<T, Methods>,\n): StoreWithMethods<T, Methods>;\nfunction create<T, Methods extends StoreMethods>(\n initialState: T | ((this: { use: Use }, fns: { use: Use }) => T),\n options?: StoreOptionsWithMethods<T, Methods>,\n): StoreWithMethods<T, Methods> | Store<T> {\n const store = new Store(initialState, options);\n\n if (initialState instanceof Function) {\n return store;\n }\n\n let methods: StoreMethods | undefined = options?.methods;\n\n if (initialState instanceof Map) {\n methods = { ...mapMethods, ...methods };\n } else if (initialState instanceof Set) {\n methods = { ...setMethods, ...methods };\n } else if (Array.isArray(initialState)) {\n methods = { ...arrayMethods, ...methods };\n } else if (initialState instanceof Object) {\n methods = { ...recordMethods, ...methods };\n }\n\n const boundMethods = Object.fromEntries(\n Object.entries(methods ?? ({} as BoundStoreMethods<T, any>))\n .filter(([name]) => !(name in store))\n .map(([name, action]) => [name, (action as any).bind(store)]),\n ) as BoundStoreMethods<T, any>;\n\n return Object.assign(store, boundMethods);\n}\n\nexport const createStore = Object.assign(create, { defaultOptions });\n"],"names":["Callable","CalculationHelper","get","set","equals","defaultEquals","forwardError","throttle","debounce","makeSelector","calcDuration","mapMethods","setMethods","arrayMethods","recordMethods"],"mappings":";;;;;;;;;;;;AAoDA,MAAM,OAAO,MAAM;AAEZ,MAAM,cAAiBA,SAAAA,SAAmB;AAAA,EAyB/C,YACkB,QACA,UAAwB,CAAA,GACxB,aAIG,QAAiC,MAAM,QAC1D;AACA,UAAM,KAAK;AARK,SAAA,SAAA;AACA,SAAA,UAAA;AACA,SAAA,cAAA;AAIG,SAAA,QAAA;AA7BX,SAAA,gCA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) {
6
+ this.set(immer.produce(recipe));
7
+ }
8
+ };
9
+ exports.immerActions = immerActions;
10
+ //# sourceMappingURL=immerActions.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"immerActions.cjs","sources":["../../../src/immer/immerActions.ts"],"sourcesContent":["import type { Draft, nothing } from 'immer';\nimport { produce } from 'immer';\nimport type { Store } from '@core/store';\n\nexport const immerActions = {\n immerUpdate<T>(\n this: Store<T>,\n recipe: (\n draft: Draft<T>,\n ) => void | Draft<T> | (Draft<T> extends undefined ? typeof nothing : never) | undefined,\n ) {\n this.set(produce(recipe));\n },\n};\n"],"names":["produce"],"mappings":";;;AAIO,MAAM,eAAe;AAAA,EAC1B,YAEE,QAGA;AACK,SAAA,IAAIA,cAAQ,MAAM,CAAC;AAAA,EAC1B;AACF;;"}
@@ -1,10 +1,5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const immer = require("immer");
4
- const immerActions = {
5
- immerUpdate(recipe) {
6
- this.set(immer.produce(recipe));
7
- }
8
- };
9
- exports.immerActions = immerActions;
3
+ const immerActions = require("./immer/immerActions.cjs");
4
+ exports.immerActions = immerActions.immerActions;
10
5
  //# sourceMappingURL=immer.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"immer.cjs","sources":["../../src/immer/immerActions.ts"],"sourcesContent":["import type { Draft, nothing } from 'immer';\nimport { produce } from 'immer';\nimport type { Store } from '@core/store';\n\nexport const immerActions = {\n immerUpdate<T>(\n this: Store<T>,\n recipe: (\n draft: Draft<T>,\n ) => void | Draft<T> | (Draft<T> extends undefined ? typeof nothing : never) | undefined,\n ) {\n this.set(produce(recipe));\n },\n};\n"],"names":["produce"],"mappings":";;;AAIO,MAAM,eAAe;AAAA,EAC1B,YAEE,QAGA;AACK,SAAA,IAAIA,cAAQ,MAAM,CAAC;AAAA,EAC1B;AACF;;"}
1
+ {"version":3,"file":"immer.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;"}
@@ -1,302 +1,22 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const hash = require("./hash.cjs");
4
- class ResourceGroup {
5
- constructor(name) {
6
- this.name = name;
7
- this.refMap = /* @__PURE__ */ new WeakMap();
8
- this.refSet = /* @__PURE__ */ new Set();
9
- hash.bind(this);
10
- }
11
- add(resource) {
12
- const ref = new WeakRef(resource);
13
- this.refMap.set(resource, ref);
14
- this.refSet.add(ref);
15
- }
16
- delete(resource) {
17
- const ref = this.refMap.get(resource);
18
- if (ref) {
19
- this.refMap.delete(resource);
20
- this.refSet.delete(ref);
21
- }
22
- }
23
- invalidateAll() {
24
- for (const ref of this.refSet) {
25
- const resource = ref.deref();
26
- if (resource) {
27
- resource.invalidate();
28
- } else {
29
- this.refSet.delete(ref);
30
- }
31
- }
32
- }
33
- clearAll() {
34
- for (const ref of this.refSet) {
35
- const resource = ref.deref();
36
- if (resource) {
37
- resource.clear();
38
- } else {
39
- this.refSet.delete(ref);
40
- }
41
- }
42
- }
43
- }
44
- const allResources = new ResourceGroup();
45
- function createResourceGroup(name) {
46
- return new ResourceGroup(name);
47
- }
48
- class InstanceCache {
49
- constructor(factory, cacheTime) {
50
- this.factory = factory;
51
- this.cacheTime = cacheTime;
52
- this.cache = /* @__PURE__ */ new Map();
53
- this.interval = this.cacheTime ? setInterval(() => this.cleanup(), Math.max(this.cacheTime / 10, 1)) : void 0;
54
- }
55
- cleanup() {
56
- var _a;
57
- const cutoff = this.now() - (this.cacheTime ?? 0);
58
- for (const [key, entry] of this.cache.entries()) {
59
- if (entry.ref && entry.t <= cutoff) {
60
- delete entry.ref;
61
- }
62
- if (!entry.ref && !((_a = entry.weakRef) == null ? void 0 : _a.deref())) {
63
- this.cache.delete(key);
64
- }
65
- }
66
- }
67
- get(...args) {
68
- var _a;
69
- const key = hash.hash(args);
70
- let entry = this.cache.get(key);
71
- let value = (entry == null ? void 0 : entry.ref) ?? ((_a = entry == null ? void 0 : entry.weakRef) == null ? void 0 : _a.deref());
72
- if (!entry || !value) {
73
- value = this.factory(...args);
74
- entry = {
75
- t: this.now(),
76
- ref: value,
77
- weakRef: new WeakRef(value)
78
- };
79
- this.cache.set(key, entry);
80
- } else {
81
- entry.t = this.now();
82
- entry.ref ?? (entry.ref = value);
83
- }
84
- return value;
85
- }
86
- values() {
87
- return [...this.cache.values()].map((entry) => {
88
- var _a;
89
- return entry.ref ?? ((_a = entry.weakRef) == null ? void 0 : _a.deref());
90
- }).filter((value) => !!value);
91
- }
92
- stop() {
93
- if (this.interval) {
94
- clearInterval(this.interval);
95
- }
96
- }
97
- stats() {
98
- return {
99
- count: this.cache.size,
100
- withRef: [...this.cache.values()].filter((x) => !!x.ref).length,
101
- withWeakRef: [...this.cache.values()].filter((x) => {
102
- var _a;
103
- return !!((_a = x.weakRef) == null ? void 0 : _a.deref());
104
- }).length
105
- };
106
- }
107
- now() {
108
- return performance.now();
109
- }
110
- }
111
- class Cache extends hash.Store {
112
- constructor(getter, options = {}, derivedFromCache) {
113
- super(getter, options);
114
- this.options = options;
115
- this.derivedFromCache = derivedFromCache;
116
- this.state = hash.createStore({
117
- status: "pending",
118
- isStale: true,
119
- isUpdating: false
120
- });
121
- this.timers = /* @__PURE__ */ new Set();
122
- this.watchPromise();
123
- }
124
- get({ update = "whenStale", backgroundUpdate = false } = {}) {
125
- var _a;
126
- const promise = (_a = this._value) == null ? void 0 : _a.v;
127
- const stalePromise = this.stalePromise;
128
- if (update === "whenMissing" && !promise && !stalePromise || update === "whenStale" && !promise || update === "force") {
129
- this.calculationHelper.execute();
130
- if (!promise && !stalePromise || !backgroundUpdate) {
131
- return super.get();
132
- }
133
- }
134
- if (!promise || stalePromise && backgroundUpdate) {
135
- return stalePromise;
136
- }
137
- return promise;
138
- }
139
- invalidate({ invalidateDependencies = true } = {}) {
140
- var _a;
141
- if (invalidateDependencies) {
142
- this.calculationHelper.invalidateDependencies();
143
- }
144
- const { status, isStale, isUpdating } = this.state.get();
145
- if (status !== "pending" && !isStale && !isUpdating) {
146
- this.stalePromise = (_a = this._value) == null ? void 0 : _a.v;
147
- }
148
- this.state.set((state) => ({
149
- ...state,
150
- isStale: true,
151
- isUpdating: false
152
- }));
153
- super.reset();
154
- }
155
- clear({ invalidateDependencies = true } = {}) {
156
- if (invalidateDependencies) {
157
- this.calculationHelper.invalidateDependencies();
158
- }
159
- this.state.set({
160
- status: "pending",
161
- isStale: true,
162
- isUpdating: false
163
- });
164
- delete this.stalePromise;
165
- super.reset();
166
- }
167
- mapValue(_selector) {
168
- const selector = hash.makeSelector(_selector);
169
- const derivedFromCache = {
170
- cache: this.derivedFromCache ? this.derivedFromCache.cache : this,
171
- selectors: this.derivedFromCache ? [...this.derivedFromCache.selectors, _selector] : [_selector]
172
- };
173
- const that = this;
174
- return new Cache(
175
- async function() {
176
- const value = await this.use(that);
177
- return selector(value);
178
- },
179
- {},
180
- derivedFromCache
181
- );
182
- }
183
- watchPromise() {
184
- this.sub(
185
- async (promise) => {
186
- var _a, _b;
187
- this.state.set((state) => ({
188
- ...state,
189
- isUpdating: true
190
- }));
191
- this.setTimers();
192
- try {
193
- const value = await promise;
194
- if (promise !== ((_a = this._value) == null ? void 0 : _a.v)) {
195
- return;
196
- }
197
- this.state.set({
198
- status: "value",
199
- value,
200
- isStale: false,
201
- isUpdating: false
202
- });
203
- delete this.stalePromise;
204
- this.setTimers();
205
- } catch (error) {
206
- if (promise !== ((_b = this._value) == null ? void 0 : _b.v)) {
207
- return;
208
- }
209
- this.state.set({
210
- status: "error",
211
- error,
212
- isStale: false,
213
- isUpdating: false
214
- });
215
- delete this.stalePromise;
216
- this.setTimers();
217
- }
218
- },
219
- { passive: true }
220
- );
221
- }
222
- setTimers() {
223
- for (const timer of this.timers) {
224
- clearTimeout(timer);
225
- }
226
- this.timers.clear();
227
- const state = this.state.get();
228
- let { invalidateAfter, clearAfter } = this.options;
229
- const ref = new WeakRef(this);
230
- if (state.status === "pending") {
231
- return;
232
- }
233
- if (invalidateAfter instanceof Function) {
234
- invalidateAfter = invalidateAfter(state);
235
- }
236
- if (invalidateAfter) {
237
- this.timers.add(setTimeout(() => {
238
- var _a;
239
- return (_a = ref == null ? void 0 : ref.deref()) == null ? void 0 : _a.invalidate();
240
- }, hash.calcDuration(invalidateAfter)));
241
- }
242
- if (clearAfter instanceof Function) {
243
- clearAfter = clearAfter(state);
244
- }
245
- if (clearAfter) {
246
- this.timers.add(setTimeout(() => {
247
- var _a;
248
- return (_a = ref == null ? void 0 : ref.deref()) == null ? void 0 : _a.clear();
249
- }, hash.calcDuration(clearAfter)));
250
- }
251
- }
252
- }
253
- const defaultOptions = {};
254
- function create(cacheFunction, options) {
255
- return withArgs(cacheFunction, options)();
256
- }
257
- function withArgs(cacheFunction, options) {
258
- const { clearUnusedAfter = defaultOptions.clearUnusedAfter ?? 0, resourceGroup } = options ?? {};
259
- const cache = new InstanceCache(
260
- (...args) => new Cache(function() {
261
- return cacheFunction.apply(this, args);
262
- }, options),
263
- hash.calcDuration(clearUnusedAfter)
264
- );
265
- const get = (...args) => {
266
- return cache.get(...args);
267
- };
268
- const invalidate = () => {
269
- for (const instance of cache.values()) {
270
- instance.invalidate();
271
- }
272
- };
273
- const clear = () => {
274
- for (const instance of cache.values()) {
275
- instance.clear();
276
- }
277
- };
278
- const resource = { invalidate, clear };
279
- const groups = Array.isArray(resourceGroup) ? resourceGroup : resourceGroup ? [resourceGroup] : [];
280
- for (const group of groups.concat(allResources)) {
281
- group.add(resource);
282
- }
283
- return Object.assign(get, resource);
284
- }
285
- const createCache = Object.assign(create, {
286
- withArgs,
287
- defaultOptions
288
- });
289
- exports.Store = hash.Store;
290
- exports.arrayMethods = hash.arrayMethods;
291
- exports.calcDuration = hash.calcDuration;
292
- exports.createStore = hash.createStore;
293
- exports.mapMethods = hash.mapMethods;
294
- exports.recordMethods = hash.recordMethods;
295
- exports.setMethods = hash.setMethods;
296
- exports.Cache = Cache;
297
- exports.InstanceCache = InstanceCache;
298
- exports.ResourceGroup = ResourceGroup;
299
- exports.allResources = allResources;
300
- exports.createCache = createCache;
301
- exports.createResourceGroup = createResourceGroup;
3
+ const instanceCache = require("./lib/instanceCache.cjs");
4
+ const calcDuration = require("./lib/calcDuration.cjs");
5
+ const standardMethods = require("./lib/standardMethods.cjs");
6
+ const cache = require("./core/cache.cjs");
7
+ const resourceGroup = require("./core/resourceGroup.cjs");
8
+ const store = require("./core/store.cjs");
9
+ exports.InstanceCache = instanceCache.InstanceCache;
10
+ exports.calcDuration = calcDuration.calcDuration;
11
+ exports.arrayMethods = standardMethods.arrayMethods;
12
+ exports.mapMethods = standardMethods.mapMethods;
13
+ exports.recordMethods = standardMethods.recordMethods;
14
+ exports.setMethods = standardMethods.setMethods;
15
+ exports.Cache = cache.Cache;
16
+ exports.createCache = cache.createCache;
17
+ exports.ResourceGroup = resourceGroup.ResourceGroup;
18
+ exports.allResources = resourceGroup.allResources;
19
+ exports.createResourceGroup = resourceGroup.createResourceGroup;
20
+ exports.Store = store.Store;
21
+ exports.createStore = store.createStore;
302
22
  //# sourceMappingURL=index.cjs.map