cross-state 0.26.0 → 0.27.1

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,613 +1,392 @@
1
1
  "use strict";
2
2
  const store = require("./store.cjs");
3
- const require$$0 = require("react");
4
- const jsxRuntime = require("react/jsx-runtime");
5
3
  const hash = require("./hash.cjs");
6
- const unwrapProxySymbol = /* @__PURE__ */ Symbol("unwrapProxy");
7
- function isPlainObject(value) {
8
- return typeof value === "object" && value !== null && Object.getPrototypeOf(value) === Object.prototype;
9
- }
10
- function trackingProxy(value, equals = store.deepEqual) {
11
- if (!isPlainObject(value) && !Array.isArray(value)) {
12
- return [value, (other) => equals(value, other)];
4
+ class ResourceGroup {
5
+ constructor(name) {
6
+ this.name = name;
7
+ this.refMap = /* @__PURE__ */ new WeakMap();
8
+ this.refSet = /* @__PURE__ */ new Set();
9
+ store.autobind(ResourceGroup);
13
10
  }
14
- value = value[unwrapProxySymbol] ?? value;
15
- const deps = new Array();
16
- const revokations = new Array();
17
- let revoked = false;
18
- function trackComplexProp(function_, ...args) {
19
- const [proxiedValue, equals2, revoke] = trackingProxy(function_(value, ...args));
20
- deps.push((otherValue) => {
21
- if (!isPlainObject(otherValue) && !Array.isArray(otherValue)) {
22
- return false;
23
- }
24
- return equals2(function_(otherValue, ...args));
25
- });
26
- if (revoke) {
27
- revokations.push(revoke);
28
- }
29
- return proxiedValue;
11
+ add(resource) {
12
+ const ref = new WeakRef(resource);
13
+ this.refMap.set(resource, ref);
14
+ this.refSet.add(ref);
30
15
  }
31
- function trackSimpleProp(function_, ...args) {
32
- const calculatedValue = function_(value, ...args);
33
- deps.push((otherValue) => {
34
- return function_(otherValue, ...args) === calculatedValue;
35
- });
36
- return calculatedValue;
16
+ delete(resource) {
17
+ const ref = this.refMap.get(resource);
18
+ if (ref) {
19
+ this.refMap.delete(resource);
20
+ this.refSet.delete(ref);
21
+ }
37
22
  }
38
- const proxy = new Proxy(value, {
39
- get(target, p, receiver) {
40
- if (p === unwrapProxySymbol) {
41
- return value;
23
+ invalidateAll() {
24
+ for (const ref of this.refSet) {
25
+ const resource = ref.deref();
26
+ if (resource) {
27
+ resource.invalidateAll();
28
+ } else {
29
+ this.refSet.delete(ref);
42
30
  }
43
- if (revoked) {
44
- return target[p];
31
+ }
32
+ }
33
+ clearAll() {
34
+ for (const ref of this.refSet) {
35
+ const resource = ref.deref();
36
+ if (resource) {
37
+ resource.clearAll();
38
+ } else {
39
+ this.refSet.delete(ref);
45
40
  }
46
- const { writable, configurable } = Object.getOwnPropertyDescriptor(target, p) ?? {};
47
- if (writable === false && configurable === false) {
48
- return target[p];
41
+ }
42
+ }
43
+ }
44
+ const allResources = /* @__PURE__ */ 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;
49
61
  }
50
- return trackComplexProp(Reflect.get, p, receiver);
51
- },
52
- getOwnPropertyDescriptor(target, p) {
53
- const { writable, configurable } = Object.getOwnPropertyDescriptor(target, p) ?? {};
54
- if (writable === false && configurable === false) {
55
- return Reflect.getOwnPropertyDescriptor(target, p);
62
+ if (!entry.ref && !((_a = entry.weakRef) == null ? void 0 : _a.deref())) {
63
+ this.cache.delete(key);
56
64
  }
57
- return trackComplexProp(Reflect.getOwnPropertyDescriptor, p);
58
- },
59
- ownKeys() {
60
- return trackComplexProp(Reflect.ownKeys);
61
- },
62
- getPrototypeOf() {
63
- return trackSimpleProp(Reflect.getPrototypeOf);
64
- },
65
- has(_target, p) {
66
- return trackSimpleProp(Reflect.has, p);
67
- },
68
- isExtensible() {
69
- return trackSimpleProp(Reflect.isExtensible);
70
65
  }
71
- });
72
- return [
73
- proxy,
74
- (other) => !!other && deps.every((equals2) => equals2(other)),
75
- () => {
76
- revoked = true;
77
- revokations.forEach((revoke) => revoke());
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);
78
83
  }
79
- ];
80
- }
81
- var withSelector = { exports: {} };
82
- var withSelector_production_min = {};
83
- var shim = { exports: {} };
84
- var useSyncExternalStoreShim_production_min = {};
85
- /**
86
- * @license React
87
- * use-sync-external-store-shim.production.min.js
88
- *
89
- * Copyright (c) Facebook, Inc. and its affiliates.
90
- *
91
- * This source code is licensed under the MIT license found in the
92
- * LICENSE file in the root directory of this source tree.
93
- */
94
- var hasRequiredUseSyncExternalStoreShim_production_min;
95
- function requireUseSyncExternalStoreShim_production_min() {
96
- if (hasRequiredUseSyncExternalStoreShim_production_min)
97
- return useSyncExternalStoreShim_production_min;
98
- hasRequiredUseSyncExternalStoreShim_production_min = 1;
99
- var e = require$$0;
100
- function h(a, b) {
101
- return a === b && (0 !== a || 1 / a === 1 / b) || a !== a && b !== b;
84
+ return value;
102
85
  }
103
- var k = "function" === typeof Object.is ? Object.is : h, l = e.useState, m = e.useEffect, n = e.useLayoutEffect, p = e.useDebugValue;
104
- function q(a, b) {
105
- var d = b(), f = l({ inst: { value: d, getSnapshot: b } }), c = f[0].inst, g = f[1];
106
- n(function() {
107
- c.value = d;
108
- c.getSnapshot = b;
109
- r(c) && g({ inst: c });
110
- }, [a, d, b]);
111
- m(function() {
112
- r(c) && g({ inst: c });
113
- return a(function() {
114
- r(c) && g({ inst: c });
115
- });
116
- }, [a]);
117
- p(d);
118
- return d;
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);
119
91
  }
120
- function r(a) {
121
- var b = a.getSnapshot;
122
- a = a.value;
123
- try {
124
- var d = b();
125
- return !k(a, d);
126
- } catch (f) {
127
- return true;
92
+ stop() {
93
+ if (this.interval) {
94
+ clearInterval(this.interval);
128
95
  }
129
96
  }
130
- function t(a, b) {
131
- return b();
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();
132
109
  }
133
- var u = "undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement ? t : q;
134
- useSyncExternalStoreShim_production_min.useSyncExternalStore = void 0 !== e.useSyncExternalStore ? e.useSyncExternalStore : u;
135
- return useSyncExternalStoreShim_production_min;
136
110
  }
137
- var useSyncExternalStoreShim_development = {};
138
- /**
139
- * @license React
140
- * use-sync-external-store-shim.development.js
141
- *
142
- * Copyright (c) Facebook, Inc. and its affiliates.
143
- *
144
- * This source code is licensed under the MIT license found in the
145
- * LICENSE file in the root directory of this source tree.
146
- */
147
- var hasRequiredUseSyncExternalStoreShim_development;
148
- function requireUseSyncExternalStoreShim_development() {
149
- if (hasRequiredUseSyncExternalStoreShim_development)
150
- return useSyncExternalStoreShim_development;
151
- hasRequiredUseSyncExternalStoreShim_development = 1;
152
- if (process.env.NODE_ENV !== "production") {
153
- (function() {
154
- if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") {
155
- __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
156
- }
157
- var React = require$$0;
158
- var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
159
- function error(format) {
160
- {
161
- {
162
- for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
163
- args[_key2 - 1] = arguments[_key2];
164
- }
165
- printWarning("error", format, args);
166
- }
111
+ class PromiseWithState extends Promise {
112
+ constructor(value, state = { status: "pending" }) {
113
+ super((resolve) => resolve(value));
114
+ this.state = state;
115
+ value.then((value2) => {
116
+ this.state = { status: "value", value: value2 };
117
+ }).catch((error) => {
118
+ this.state = { status: "error", error };
119
+ });
120
+ }
121
+ static resolve(value) {
122
+ return new PromiseWithState(Promise.resolve(value), {
123
+ status: "value",
124
+ value
125
+ });
126
+ }
127
+ static reject(error) {
128
+ return new PromiseWithState(Promise.reject(error), { status: "error", error });
129
+ }
130
+ }
131
+ class Cache extends store.Store {
132
+ constructor(getter, options = {}, derivedFromCache, _call) {
133
+ super(
134
+ function() {
135
+ let result = getter.apply(this);
136
+ if (result instanceof Function) {
137
+ result = result(this);
167
138
  }
139
+ return result;
140
+ },
141
+ options,
142
+ void 0,
143
+ _call
144
+ );
145
+ this.options = options;
146
+ this.derivedFromCache = derivedFromCache;
147
+ this.state = store.createStore({
148
+ status: "pending",
149
+ isStale: true,
150
+ isUpdating: false
151
+ });
152
+ store.autobind(Cache);
153
+ this.calculationHelper.options.onInvalidate = () => this.invalidate({ invalidateDependencies: false });
154
+ this.watchPromise();
155
+ this.watchFocus();
156
+ }
157
+ get({ update = "whenStale", backgroundUpdate = false } = {}) {
158
+ var _a;
159
+ const promise = (_a = this._value) == null ? void 0 : _a.v;
160
+ const stalePromise = this.stalePromise;
161
+ if (update === "whenMissing" && !promise && !stalePromise || update === "whenStale" && !promise || update === "force") {
162
+ this.calculationHelper.execute();
163
+ if (!promise && !stalePromise || !backgroundUpdate) {
164
+ return super.get();
168
165
  }
169
- function printWarning(level, format, args) {
170
- {
171
- var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
172
- var stack = ReactDebugCurrentFrame.getStackAddendum();
173
- if (stack !== "") {
174
- format += "%s";
175
- args = args.concat([stack]);
176
- }
177
- var argsWithFormat = args.map(function(item) {
178
- return String(item);
166
+ }
167
+ if (!promise || stalePromise && backgroundUpdate) {
168
+ return stalePromise;
169
+ }
170
+ return promise;
171
+ }
172
+ updateValue(value) {
173
+ this.set(PromiseWithState.resolve(value));
174
+ }
175
+ updateError(error) {
176
+ this.set(PromiseWithState.reject(error));
177
+ }
178
+ invalidate({ invalidateDependencies = true } = {}) {
179
+ var _a;
180
+ const { clearOnInvalidate = createCache.defaultOptions.clearOnInvalidate } = this.options;
181
+ if (clearOnInvalidate) {
182
+ return this.clear({ invalidateDependencies });
183
+ }
184
+ if (invalidateDependencies) {
185
+ this.calculationHelper.invalidateDependencies();
186
+ }
187
+ const { status, isStale, isUpdating } = this.state.get();
188
+ if (status !== "pending" && !isStale && !isUpdating) {
189
+ this.stalePromise = (_a = this._value) == null ? void 0 : _a.v;
190
+ }
191
+ this.state.set((state) => ({
192
+ ...state,
193
+ isStale: true,
194
+ isUpdating: false
195
+ }));
196
+ this.calculationHelper.stop();
197
+ super.reset();
198
+ }
199
+ clear({ invalidateDependencies = true } = {}) {
200
+ if (invalidateDependencies) {
201
+ this.calculationHelper.invalidateDependencies();
202
+ }
203
+ this.state.set({
204
+ status: "pending",
205
+ isStale: true,
206
+ isUpdating: false
207
+ });
208
+ delete this.stalePromise;
209
+ this.calculationHelper.stop();
210
+ super.reset();
211
+ }
212
+ mapValue(_selector) {
213
+ const selector = store.makeSelector(_selector);
214
+ const derivedFromCache = {
215
+ cache: this.derivedFromCache ? this.derivedFromCache.cache : this,
216
+ selectors: this.derivedFromCache ? [...this.derivedFromCache.selectors, _selector] : [_selector]
217
+ };
218
+ const that = this;
219
+ return new Cache(
220
+ async function() {
221
+ const value = await this.use(that);
222
+ return selector(value);
223
+ },
224
+ {},
225
+ derivedFromCache
226
+ );
227
+ }
228
+ watchPromise() {
229
+ this.subscribe(
230
+ async (promise) => {
231
+ var _a, _b;
232
+ if (promise instanceof PromiseWithState) {
233
+ this.state.set({
234
+ ...promise.state,
235
+ isStale: false,
236
+ isUpdating: false
179
237
  });
180
- argsWithFormat.unshift("Warning: " + format);
181
- Function.prototype.apply.call(console[level], console, argsWithFormat);
238
+ delete this.stalePromise;
239
+ this.setTimers();
240
+ return;
182
241
  }
183
- }
184
- function is(x, y) {
185
- return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y;
186
- }
187
- var objectIs = typeof Object.is === "function" ? Object.is : is;
188
- var useState = React.useState, useEffect = React.useEffect, useLayoutEffect = React.useLayoutEffect, useDebugValue = React.useDebugValue;
189
- var didWarnOld18Alpha = false;
190
- var didWarnUncachedGetSnapshot = false;
191
- function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
192
- {
193
- if (!didWarnOld18Alpha) {
194
- if (React.startTransition !== void 0) {
195
- didWarnOld18Alpha = true;
196
- error("You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release.");
197
- }
198
- }
199
- }
200
- var value = getSnapshot();
201
- {
202
- if (!didWarnUncachedGetSnapshot) {
203
- var cachedValue = getSnapshot();
204
- if (!objectIs(value, cachedValue)) {
205
- error("The result of getSnapshot should be cached to avoid an infinite loop");
206
- didWarnUncachedGetSnapshot = true;
207
- }
242
+ this.state.set((state) => ({
243
+ ...state,
244
+ isUpdating: true
245
+ }));
246
+ this.setTimers();
247
+ try {
248
+ const value = await promise;
249
+ if (promise !== ((_a = this._value) == null ? void 0 : _a.v)) {
250
+ return;
208
251
  }
209
- }
210
- var _useState = useState({
211
- inst: {
252
+ this.state.set({
253
+ status: "value",
212
254
  value,
213
- getSnapshot
214
- }
215
- }), inst = _useState[0].inst, forceUpdate = _useState[1];
216
- useLayoutEffect(function() {
217
- inst.value = value;
218
- inst.getSnapshot = getSnapshot;
219
- if (checkIfSnapshotChanged(inst)) {
220
- forceUpdate({
221
- inst
222
- });
223
- }
224
- }, [subscribe, value, getSnapshot]);
225
- useEffect(function() {
226
- if (checkIfSnapshotChanged(inst)) {
227
- forceUpdate({
228
- inst
229
- });
255
+ isStale: false,
256
+ isUpdating: false
257
+ });
258
+ delete this.stalePromise;
259
+ this.setTimers();
260
+ } catch (error) {
261
+ if (promise !== ((_b = this._value) == null ? void 0 : _b.v)) {
262
+ return;
230
263
  }
231
- var handleStoreChange = function() {
232
- if (checkIfSnapshotChanged(inst)) {
233
- forceUpdate({
234
- inst
235
- });
236
- }
237
- };
238
- return subscribe(handleStoreChange);
239
- }, [subscribe]);
240
- useDebugValue(value);
241
- return value;
242
- }
243
- function checkIfSnapshotChanged(inst) {
244
- var latestGetSnapshot = inst.getSnapshot;
245
- var prevValue = inst.value;
246
- try {
247
- var nextValue = latestGetSnapshot();
248
- return !objectIs(prevValue, nextValue);
249
- } catch (error2) {
250
- return true;
264
+ this.state.set({
265
+ status: "error",
266
+ error,
267
+ isStale: false,
268
+ isUpdating: false
269
+ });
270
+ delete this.stalePromise;
271
+ this.setTimers();
251
272
  }
252
- }
253
- function useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) {
254
- return getSnapshot();
255
- }
256
- var canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined");
257
- var isServerEnvironment = !canUseDOM;
258
- var shim2 = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore;
259
- var useSyncExternalStore$2 = React.useSyncExternalStore !== void 0 ? React.useSyncExternalStore : shim2;
260
- useSyncExternalStoreShim_development.useSyncExternalStore = useSyncExternalStore$2;
261
- if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") {
262
- __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
263
- }
264
- })();
265
- }
266
- return useSyncExternalStoreShim_development;
267
- }
268
- var hasRequiredShim;
269
- function requireShim() {
270
- if (hasRequiredShim)
271
- return shim.exports;
272
- hasRequiredShim = 1;
273
- if (process.env.NODE_ENV === "production") {
274
- shim.exports = requireUseSyncExternalStoreShim_production_min();
275
- } else {
276
- shim.exports = requireUseSyncExternalStoreShim_development();
273
+ },
274
+ { passive: true }
275
+ );
277
276
  }
278
- return shim.exports;
279
- }
280
- /**
281
- * @license React
282
- * use-sync-external-store-shim/with-selector.production.min.js
283
- *
284
- * Copyright (c) Facebook, Inc. and its affiliates.
285
- *
286
- * This source code is licensed under the MIT license found in the
287
- * LICENSE file in the root directory of this source tree.
288
- */
289
- var hasRequiredWithSelector_production_min;
290
- function requireWithSelector_production_min() {
291
- if (hasRequiredWithSelector_production_min)
292
- return withSelector_production_min;
293
- hasRequiredWithSelector_production_min = 1;
294
- var h = require$$0, n = requireShim();
295
- function p(a, b) {
296
- return a === b && (0 !== a || 1 / a === 1 / b) || a !== a && b !== b;
277
+ setTimers() {
278
+ if (this.invalidationTimer) {
279
+ clearTimeout(this.invalidationTimer);
280
+ }
281
+ this.invalidationTimer = void 0;
282
+ const state = this.state.get();
283
+ let { invalidateAfter = createCache.defaultOptions.invalidateAfter } = this.options;
284
+ const ref = new WeakRef(this);
285
+ if (state.status === "pending") {
286
+ return;
287
+ }
288
+ if (invalidateAfter instanceof Function) {
289
+ invalidateAfter = invalidateAfter(state);
290
+ }
291
+ if (invalidateAfter !== null && invalidateAfter !== void 0) {
292
+ this.invalidationTimer = setTimeout(
293
+ () => {
294
+ var _a;
295
+ return (_a = ref == null ? void 0 : ref.deref()) == null ? void 0 : _a.invalidate();
296
+ },
297
+ store.calcDuration(invalidateAfter)
298
+ );
299
+ }
297
300
  }
298
- var q = "function" === typeof Object.is ? Object.is : p, r = n.useSyncExternalStore, t = h.useRef, u = h.useEffect, v = h.useMemo, w = h.useDebugValue;
299
- withSelector_production_min.useSyncExternalStoreWithSelector = function(a, b, e, l, g) {
300
- var c = t(null);
301
- if (null === c.current) {
302
- var f = { hasValue: false, value: null };
303
- c.current = f;
304
- } else
305
- f = c.current;
306
- c = v(function() {
307
- function a2(a3) {
308
- if (!c2) {
309
- c2 = true;
310
- d2 = a3;
311
- a3 = l(a3);
312
- if (void 0 !== g && f.hasValue) {
313
- var b2 = f.value;
314
- if (g(b2, a3))
315
- return k = b2;
316
- }
317
- return k = a3;
318
- }
319
- b2 = k;
320
- if (q(d2, a3))
321
- return b2;
322
- var e2 = l(a3);
323
- if (void 0 !== g && g(b2, e2))
324
- return b2;
325
- d2 = a3;
326
- return k = e2;
327
- }
328
- var c2 = false, d2, k, m = void 0 === e ? null : e;
329
- return [function() {
330
- return a2(b());
331
- }, null === m ? void 0 : function() {
332
- return a2(m());
333
- }];
334
- }, [b, e, l, g]);
335
- var d = r(a, c[0], c[1]);
336
- u(function() {
337
- f.hasValue = true;
338
- f.value = d;
339
- }, [d]);
340
- w(d);
341
- return d;
342
- };
343
- return withSelector_production_min;
344
- }
345
- var withSelector_development = {};
346
- /**
347
- * @license React
348
- * use-sync-external-store-shim/with-selector.development.js
349
- *
350
- * Copyright (c) Facebook, Inc. and its affiliates.
351
- *
352
- * This source code is licensed under the MIT license found in the
353
- * LICENSE file in the root directory of this source tree.
354
- */
355
- var hasRequiredWithSelector_development;
356
- function requireWithSelector_development() {
357
- if (hasRequiredWithSelector_development)
358
- return withSelector_development;
359
- hasRequiredWithSelector_development = 1;
360
- if (process.env.NODE_ENV !== "production") {
361
- (function() {
362
- if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") {
363
- __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
364
- }
365
- var React = require$$0;
366
- var shim2 = requireShim();
367
- function is(x, y) {
368
- return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y;
369
- }
370
- var objectIs = typeof Object.is === "function" ? Object.is : is;
371
- var useSyncExternalStore = shim2.useSyncExternalStore;
372
- var useRef = React.useRef, useEffect = React.useEffect, useMemo = React.useMemo, useDebugValue = React.useDebugValue;
373
- function useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {
374
- var instRef = useRef(null);
375
- var inst;
376
- if (instRef.current === null) {
377
- inst = {
378
- hasValue: false,
379
- value: null
380
- };
381
- instRef.current = inst;
382
- } else {
383
- inst = instRef.current;
384
- }
385
- var _useMemo = useMemo(function() {
386
- var hasMemo = false;
387
- var memoizedSnapshot;
388
- var memoizedSelection;
389
- var memoizedSelector = function(nextSnapshot) {
390
- if (!hasMemo) {
391
- hasMemo = true;
392
- memoizedSnapshot = nextSnapshot;
393
- var _nextSelection = selector(nextSnapshot);
394
- if (isEqual !== void 0) {
395
- if (inst.hasValue) {
396
- var currentSelection = inst.value;
397
- if (isEqual(currentSelection, _nextSelection)) {
398
- memoizedSelection = currentSelection;
399
- return currentSelection;
400
- }
401
- }
402
- }
403
- memoizedSelection = _nextSelection;
404
- return _nextSelection;
405
- }
406
- var prevSnapshot = memoizedSnapshot;
407
- var prevSelection = memoizedSelection;
408
- if (objectIs(prevSnapshot, nextSnapshot)) {
409
- return prevSelection;
410
- }
411
- var nextSelection = selector(nextSnapshot);
412
- if (isEqual !== void 0 && isEqual(prevSelection, nextSelection)) {
413
- return prevSelection;
414
- }
415
- memoizedSnapshot = nextSnapshot;
416
- memoizedSelection = nextSelection;
417
- return nextSelection;
418
- };
419
- var maybeGetServerSnapshot = getServerSnapshot === void 0 ? null : getServerSnapshot;
420
- var getSnapshotWithSelector = function() {
421
- return memoizedSelector(getSnapshot());
422
- };
423
- var getServerSnapshotWithSelector = maybeGetServerSnapshot === null ? void 0 : function() {
424
- return memoizedSelector(maybeGetServerSnapshot());
425
- };
426
- return [getSnapshotWithSelector, getServerSnapshotWithSelector];
427
- }, [getSnapshot, getServerSnapshot, selector, isEqual]), getSelection = _useMemo[0], getServerSelection = _useMemo[1];
428
- var value = useSyncExternalStore(subscribe, getSelection, getServerSelection);
429
- useEffect(function() {
430
- inst.hasValue = true;
431
- inst.value = value;
432
- }, [value]);
433
- useDebugValue(value);
434
- return value;
301
+ watchFocus() {
302
+ const { invalidateOnWindowFocus = createCache.defaultOptions.invalidateOnWindowFocus } = this.options;
303
+ if (!invalidateOnWindowFocus || typeof document === "undefined" || typeof document.addEventListener === "undefined") {
304
+ return;
305
+ }
306
+ const ref = new WeakRef(this);
307
+ const onFocus = () => {
308
+ const that = ref == null ? void 0 : ref.deref();
309
+ if (!that) {
310
+ document.removeEventListener("visibilitychange", onFocus);
311
+ return;
435
312
  }
436
- withSelector_development.useSyncExternalStoreWithSelector = useSyncExternalStoreWithSelector;
437
- if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") {
438
- __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
313
+ if (!document.hidden) {
314
+ that.invalidate();
439
315
  }
440
- })();
316
+ };
317
+ document.addEventListener("visibilitychange", onFocus);
441
318
  }
442
- return withSelector_development;
443
- }
444
- if (process.env.NODE_ENV === "production") {
445
- withSelector.exports = requireWithSelector_production_min();
446
- } else {
447
- withSelector.exports = requireWithSelector_development();
448
319
  }
449
- var withSelectorExports = withSelector.exports;
450
- function useStore(store$1, argument1, argument2) {
451
- const selector = store.makeSelector(
452
- typeof argument1 === "function" || typeof argument1 === "string" ? argument1 : void 0
453
- );
454
- const {
455
- disableTrackingProxy = true,
456
- equals = store.deepEqual,
457
- withViewTransition,
458
- ...options
459
- } = typeof argument1 === "object" ? argument1 : argument2 ?? {};
460
- const lastEqualsRef = require$$0.useRef();
461
- const { rootStore, mappingSelector } = require$$0.useMemo(() => {
462
- var _a;
463
- const rootStore2 = ((_a = store$1.derivedFrom) == null ? void 0 : _a.store) ?? store$1;
464
- let mappingSelector2 = (x) => x;
465
- if (store$1.derivedFrom) {
466
- mappingSelector2 = (value2) => {
467
- for (const s of store$1.derivedFrom.selectors) {
468
- value2 = store.makeSelector(s)(value2);
469
- }
470
- return value2;
471
- };
472
- }
473
- return { rootStore: rootStore2, mappingSelector: mappingSelector2 };
474
- }, [store$1]);
475
- const subOptions = { ...options, runNow: false, passive: false };
476
- const subscribe = require$$0.useCallback(
477
- (listener) => {
478
- let _listener = listener;
479
- if (withViewTransition && document.startViewTransition) {
480
- let lastObservedValue;
481
- _listener = (value2) => {
482
- const observedValue = withViewTransition instanceof Function ? withViewTransition(value2) : value2;
483
- if (equals(lastObservedValue, observedValue)) {
484
- listener();
485
- return;
486
- }
487
- lastObservedValue = observedValue;
488
- let hasChanges = false;
489
- const mutationObserver = new MutationObserver(() => {
490
- hasChanges = true;
491
- mutationObserver.disconnect();
492
- });
493
- mutationObserver.observe(document.body, { childList: true, subtree: true });
494
- document.startViewTransition(() => {
495
- listener();
496
- if (!hasChanges) {
497
- throw new Error("no change");
498
- }
499
- });
500
- };
320
+ function create(cacheFunction, options) {
321
+ const { clearUnusedAfter = createCache.defaultOptions.clearUnusedAfter, resourceGroup } = options ?? {};
322
+ let baseInstance;
323
+ const instanceCache = new InstanceCache(
324
+ (...args) => {
325
+ if (args.length === 0 && baseInstance) {
326
+ return baseInstance;
501
327
  }
502
- return rootStore.subscribe(_listener, subOptions);
328
+ return new Cache(function() {
329
+ return cacheFunction.apply(this, args);
330
+ }, options);
503
331
  },
504
- [rootStore, hash.hash(subOptions)]
332
+ clearUnusedAfter ? store.calcDuration(clearUnusedAfter) : void 0
505
333
  );
506
- let value = withSelectorExports.useSyncExternalStoreWithSelector(
507
- //
508
- subscribe,
509
- rootStore.get,
510
- void 0,
511
- (x) => selector(mappingSelector(x)),
512
- (_v, newValue) => {
513
- var _a;
514
- return ((_a = lastEqualsRef.current) == null ? void 0 : _a.call(lastEqualsRef, newValue)) ?? false;
334
+ const get = (...args) => {
335
+ return instanceCache.get(...args);
336
+ };
337
+ const invalidateAll = () => {
338
+ for (const instance of instanceCache.values()) {
339
+ instance.invalidate();
340
+ }
341
+ };
342
+ const clearAll = () => {
343
+ for (const instance of instanceCache.values()) {
344
+ instance.clear();
345
+ }
346
+ };
347
+ baseInstance = Object.assign(
348
+ new Cache(
349
+ function() {
350
+ return cacheFunction.apply(this);
351
+ },
352
+ options,
353
+ void 0,
354
+ get
355
+ ),
356
+ {
357
+ invalidateAll,
358
+ clearAll
515
359
  }
516
360
  );
517
- let lastEquals = (newValue) => equals(newValue, value);
518
- let revoke;
519
- if (!disableTrackingProxy) {
520
- [value, lastEquals, revoke] = trackingProxy(value, equals);
361
+ const groups = Array.isArray(resourceGroup) ? resourceGroup : resourceGroup ? [resourceGroup] : [];
362
+ for (const group of groups.concat(allResources)) {
363
+ group.add(baseInstance);
521
364
  }
522
- require$$0.useLayoutEffect(() => {
523
- lastEqualsRef.current = lastEquals;
524
- revoke == null ? void 0 : revoke();
525
- });
526
- require$$0.useDebugValue(value);
527
- return value;
365
+ get(...[]);
366
+ return baseInstance;
528
367
  }
529
- function useProp(store2, argument1, argument2, argument3) {
530
- const selector = typeof argument1 === "function" || typeof argument1 === "string" ? argument1 : void 0;
531
- const updater = typeof argument2 === "function" ? argument2 : void 0;
532
- const options = typeof argument1 === "object" ? argument1 : typeof argument2 === "object" ? argument2 : argument3;
533
- if (selector) {
534
- store2 = store2.map(selector, updater);
368
+ const createCache = /* @__PURE__ */ Object.assign(create, {
369
+ defaultOptions: {
370
+ invalidateOnWindowFocus: true,
371
+ invalidateOnActivation: true,
372
+ clearUnusedAfter: { days: 1 }
535
373
  }
536
- const value = useStore(store2, options);
537
- return [value, store2.set];
538
- }
539
- function boundUseStore(...args) {
540
- return useStore(this, ...args);
541
- }
542
- function boundUseProp(...args) {
543
- return useProp(this, ...args);
544
- }
545
- const reactMethods = {
546
- useStore: boundUseStore,
547
- useProp: boundUseProp
548
- };
549
- function useCache(cache, { passive, updateOnMount, withViewTransition, ...options } = {}) {
550
- if (withViewTransition === true) {
551
- withViewTransition = (state) => state.value;
374
+ });
375
+ class Scope {
376
+ constructor(defaultValue) {
377
+ this.defaultValue = defaultValue;
378
+ store.autobind(Scope);
552
379
  }
553
- const mappedState = require$$0.useMemo(() => {
554
- var _a;
555
- const rootCache = ((_a = cache.derivedFromCache) == null ? void 0 : _a.cache) ?? cache;
556
- let selector = (x) => x;
557
- if (cache.derivedFromCache) {
558
- selector = (value) => {
559
- for (const s of cache.derivedFromCache.selectors) {
560
- value = store.makeSelector(s)(value);
561
- }
562
- return value;
563
- };
564
- }
565
- return rootCache.state.map((state) => {
566
- const value = state.status === "value" ? selector(state.value) : void 0;
567
- return Object.assign(
568
- [value, state.error, state.isUpdating, state.isStale],
569
- { ...state, value }
570
- );
571
- });
572
- }, [cache]);
573
- require$$0.useEffect(() => !passive ? cache.subscribe(() => void 0) : void 0, [cache, passive]);
574
- require$$0.useEffect(() => {
575
- if (updateOnMount) {
576
- cache.invalidate();
577
- }
578
- }, []);
579
- return useStore(mappedState, { ...options, withViewTransition });
580
- }
581
- function getScopeContext(scope) {
582
- scope.context ?? (scope.context = require$$0.createContext(store.createStore(scope.defaultValue)));
583
- return scope.context;
584
- }
585
- function ScopeProvider({ scope, store: inputStore, children }) {
586
- const context = getScopeContext(scope);
587
- const currentStore = require$$0.useMemo(
588
- () => inputStore ?? store.createStore(scope.defaultValue),
589
- [scope, inputStore]
590
- );
591
- return /* @__PURE__ */ jsxRuntime.jsx(context.Provider, { value: currentStore, children });
592
- }
593
- function useScope(scope) {
594
- const context = getScopeContext(scope);
595
- return require$$0.useContext(context);
596
- }
597
- function useScopeStore(scope, options) {
598
- const store2 = useScope(scope);
599
- return useStore(store2, options);
600
380
  }
601
- function useScopeProp(scope, options) {
602
- const store2 = useScope(scope);
603
- return useProp(store2, options);
381
+ function createScope(defaultValue) {
382
+ return new Scope(defaultValue);
604
383
  }
605
- exports.ScopeProvider = ScopeProvider;
606
- exports.reactMethods = reactMethods;
607
- exports.useCache = useCache;
608
- exports.useProp = useProp;
609
- exports.useScope = useScope;
610
- exports.useScopeProp = useScopeProp;
611
- exports.useScopeStore = useScopeStore;
612
- exports.useStore = useStore;
384
+ exports.Cache = Cache;
385
+ exports.InstanceCache = InstanceCache;
386
+ exports.ResourceGroup = ResourceGroup;
387
+ exports.Scope = Scope;
388
+ exports.allResources = allResources;
389
+ exports.createCache = createCache;
390
+ exports.createResourceGroup = createResourceGroup;
391
+ exports.createScope = createScope;
613
392
  //# sourceMappingURL=scope.cjs.map