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