cross-state 0.54.8 → 0.55.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +51 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +27 -2
- package/dist/index.d.ts +27 -2
- package/dist/index.js +52 -3
- package/dist/index.js.map +1 -1
- package/dist/react/index.d.cts +2 -2
- package/dist/react/index.d.ts +2 -2
- package/dist/react/register.cjs +1 -1
- package/dist/react/register.d.cts +2 -2
- package/dist/react/register.d.ts +2 -2
- package/dist/react/register.js +1 -1
- package/dist/{scope-DZVNkeCy.d.cts → scope-6B7-8lwa.d.cts} +12 -12
- package/dist/{scope-DkCUDAD1.d.ts → scope-BbUXgNW_.d.ts} +12 -12
- package/dist/{scope-6P87zGw6.js → scope-CKXL9xoi.js} +13 -18
- package/dist/scope-CKXL9xoi.js.map +1 -0
- package/dist/{scope-BfYAP7hS.cjs → scope-CoDFmhxK.cjs} +24 -17
- package/dist/scope-CoDFmhxK.cjs.map +1 -0
- package/dist/{storeMethods-HhjDEc7D.d.cts → storeMethods-Bg8nMBrf.d.cts} +2 -2
- package/dist/{storeMethods-CABq4ehi.d.ts → storeMethods-DWKSveN0.d.ts} +2 -2
- package/package.json +1 -1
- package/dist/scope-6P87zGw6.js.map +0 -1
- package/dist/scope-BfYAP7hS.cjs.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,11 +1,60 @@
|
|
|
1
1
|
const require_store = require('./store-1TGlSyq4.cjs');
|
|
2
2
|
const require_propAccess = require('./propAccess-BdLsqViO.cjs');
|
|
3
3
|
const require_hash = require('./hash-Dv3XlmHn.cjs');
|
|
4
|
-
const require_scope = require('./scope-
|
|
4
|
+
const require_scope = require('./scope-CoDFmhxK.cjs');
|
|
5
5
|
const require_patchMethods = require('./patchMethods-hhlLwtqE.cjs');
|
|
6
6
|
const require_extendedJson = require('./extendedJson-Dn2F7Edo.cjs');
|
|
7
7
|
const require_persist = require('./persist-CGLe7YUX.cjs');
|
|
8
8
|
|
|
9
|
+
//#region src/core/pagedCache.ts
|
|
10
|
+
var PagedCache = class PagedCache extends require_scope.Cache {
|
|
11
|
+
constructor(definition, args, options = {}) {
|
|
12
|
+
super(async (helpers) => {
|
|
13
|
+
const { fetchPage } = definition;
|
|
14
|
+
const page = await fetchPage({
|
|
15
|
+
...helpers,
|
|
16
|
+
pages: [],
|
|
17
|
+
prevPage: null
|
|
18
|
+
});
|
|
19
|
+
return page === null ? [] : [page];
|
|
20
|
+
}, args, options, void 0);
|
|
21
|
+
this.definition = definition;
|
|
22
|
+
require_store.autobind(PagedCache);
|
|
23
|
+
}
|
|
24
|
+
async fetchNextPage() {
|
|
25
|
+
const { fetchPage } = this.definition;
|
|
26
|
+
const { status, isStale, isUpdating, value } = this.state.get();
|
|
27
|
+
if (status !== "value" || isStale || isUpdating) throw new Error("Cannot fetch next page while cache is not in a stable state");
|
|
28
|
+
this.stalePromise = this.calculatedValue?.value;
|
|
29
|
+
const ac = new AbortController();
|
|
30
|
+
const pagePromise = fetchPage({
|
|
31
|
+
use() {
|
|
32
|
+
throw new Error("Not implemented");
|
|
33
|
+
},
|
|
34
|
+
connect() {
|
|
35
|
+
throw new Error("Not implemented");
|
|
36
|
+
},
|
|
37
|
+
signal: ac.signal,
|
|
38
|
+
pages: value,
|
|
39
|
+
prevPage: value.length > 0 ? value[value.length - 1] : null
|
|
40
|
+
});
|
|
41
|
+
const valuePromise = pagePromise.then((page) => {
|
|
42
|
+
if (page === null) return value;
|
|
43
|
+
return [...value, page];
|
|
44
|
+
});
|
|
45
|
+
this.updateValue(valuePromise);
|
|
46
|
+
return pagePromise;
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
function createPaged(definition, options) {
|
|
50
|
+
return require_scope.internalCreate((args, options$1) => {
|
|
51
|
+
if (definition instanceof Function) definition = definition(...args);
|
|
52
|
+
return new PagedCache(definition, args, options$1);
|
|
53
|
+
}, options);
|
|
54
|
+
}
|
|
55
|
+
const createPagedCache = /* @__PURE__ */ Object.assign(createPaged, { defaultOptions: require_scope.defaultCacheOptions });
|
|
56
|
+
|
|
57
|
+
//#endregion
|
|
9
58
|
//#region src/lib/updateHelpers.ts
|
|
10
59
|
function findOrDefault(array, predicate, defaultValue) {
|
|
11
60
|
const index = array.findIndex(predicate);
|
|
@@ -26,6 +75,7 @@ exports.applyPatches = require_patchMethods.applyPatches;
|
|
|
26
75
|
exports.arrayMethods = require_store.arrayMethods;
|
|
27
76
|
exports.calcDuration = require_store.calcDuration;
|
|
28
77
|
exports.createCache = require_scope.createCache;
|
|
78
|
+
exports.createPagedCache = createPagedCache;
|
|
29
79
|
exports.createResourceGroup = require_scope.createResourceGroup;
|
|
30
80
|
exports.createScope = require_scope.createScope;
|
|
31
81
|
exports.createStore = require_store.createStore;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../src/lib/updateHelpers.ts"],"sourcesContent":["export function findOrDefault<T>(\n array: T[],\n predicate: (item: T) => boolean,\n defaultValue: T | (() => T),\n): T {\n const index = array.findIndex(predicate);\n\n if (index >= 0) {\n return array[index]!;\n }\n\n const value = defaultValue instanceof Function ? defaultValue() : defaultValue;\n array.push(value);\n return value;\n}\n"],"mappings":";;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["Cache","definition: PagedCacheDefinition<T>","internalCreate","options","createPagedCache: typeof createPaged & { defaultOptions: CacheOptions<any, any> }","defaultCacheOptions"],"sources":["../src/core/pagedCache.ts","../src/lib/updateHelpers.ts"],"sourcesContent":["import {\n Cache,\n defaultCacheOptions,\n internalCreate,\n type CacheOptions,\n type CreateCacheResult,\n} from '@core/cache';\nimport type { CalculationActions } from '@core/commonTypes';\nimport { autobind } from '@lib/autobind';\n\nexport interface PageCacheFunctionProps<T> extends CalculationActions<Promise<T[]>> {\n pages: T[];\n prevPage: T | null;\n}\n\nexport interface PageCacheFunction<T> {\n (props: PageCacheFunctionProps<T>): Promise<T | null>;\n}\n\nexport interface PagedCacheDefinition<T> {\n fetchPage: (props: PageCacheFunctionProps<T>) => Promise<T | null>;\n}\n\nexport interface PagedCacheDefinitionFunction<T, Args extends any[]> {\n (...args: Args): PagedCacheDefinition<T>;\n}\n\nexport class PagedCache<T, Args extends any[] = []> extends Cache<T[], Args> {\n constructor(\n public readonly definition: PagedCacheDefinition<T>,\n args: Args,\n options: CacheOptions<T[], Args> = {},\n ) {\n super(\n async (helpers) => {\n const { fetchPage } = definition;\n\n const page = await fetchPage({\n ...helpers,\n pages: [],\n prevPage: null,\n });\n\n return page === null ? [] : [page];\n },\n args,\n options,\n undefined,\n );\n autobind(PagedCache);\n }\n\n async fetchNextPage(): Promise<T | null> {\n const { fetchPage } = this.definition;\n const { status, isStale, isUpdating, value } = this.state.get();\n\n if (status !== 'value' || isStale || isUpdating) {\n throw new Error('Cannot fetch next page while cache is not in a stable state');\n }\n\n this.stalePromise = this.calculatedValue?.value;\n\n const ac = new AbortController();\n const pagePromise = fetchPage({\n use() {\n throw new Error('Not implemented');\n },\n connect() {\n throw new Error('Not implemented');\n },\n signal: ac.signal,\n pages: value,\n prevPage: value.length > 0 ? value[value.length - 1]! : null,\n });\n\n const valuePromise = pagePromise.then((page) => {\n if (page === null) {\n return value;\n }\n return [...value, page];\n });\n\n this.updateValue(valuePromise);\n return pagePromise;\n }\n}\n\nfunction createPaged<T, Args extends any[] = []>(\n definition: PagedCacheDefinitionFunction<T, Args>,\n options?: CacheOptions<T[], Args>,\n): CreateCacheResult<T[], Args, PagedCache<T, Args>>;\n\nfunction createPaged<T>(\n definition: PagedCacheDefinition<T>,\n options?: CacheOptions<T[], []>,\n): CreateCacheResult<T[], [], PagedCache<T, []>>;\n\nfunction createPaged<T, Args extends any[] = []>(\n definition: PagedCacheDefinitionFunction<T, Args> | PagedCacheDefinition<T>,\n options?: CacheOptions<T[], Args>,\n): CreateCacheResult<T[], Args, PagedCache<T, Args>> {\n return internalCreate<T[], Args, PagedCache<T, Args>>((args, options) => {\n if (definition instanceof Function) {\n definition = definition(...args);\n }\n return new PagedCache(definition, args, options);\n }, options);\n}\n\nexport const createPagedCache: typeof createPaged & { defaultOptions: CacheOptions<any, any> } =\n /* @__PURE__ */ Object.assign(createPaged, {\n defaultOptions: defaultCacheOptions,\n });\n","export function findOrDefault<T>(\n array: T[],\n predicate: (item: T) => boolean,\n defaultValue: T | (() => T),\n): T {\n const index = array.findIndex(predicate);\n\n if (index >= 0) {\n return array[index]!;\n }\n\n const value = defaultValue instanceof Function ? defaultValue() : defaultValue;\n array.push(value);\n return value;\n}\n"],"mappings":";;;;;;;;;AA2BA,IAAa,aAAb,MAAa,mBAA+CA,oBAAiB;CAC3E,YACE,AAAgBC,YAChB,MACA,UAAmC,IACnC;AACA,QACE,OAAO,YAAY;GACjB,MAAM,EAAE,cAAc;GAEtB,MAAM,OAAO,MAAM,UAAU;IAC3B,GAAG;IACH,OAAO;IACP,UAAU;;AAGZ,UAAO,SAAS,OAAO,KAAK,CAAC;KAE/B,MACA,SACA;EAlBc;AAoBhB,yBAAS;;CAGX,MAAM,gBAAmC;EACvC,MAAM,EAAE,cAAc,KAAK;EAC3B,MAAM,EAAE,QAAQ,SAAS,YAAY,UAAU,KAAK,MAAM;AAE1D,MAAI,WAAW,WAAW,WAAW,WACnC,OAAM,IAAI,MAAM;AAGlB,OAAK,eAAe,KAAK,iBAAiB;EAE1C,MAAM,KAAK,IAAI;EACf,MAAM,cAAc,UAAU;GAC5B,MAAM;AACJ,UAAM,IAAI,MAAM;;GAElB,UAAU;AACR,UAAM,IAAI,MAAM;;GAElB,QAAQ,GAAG;GACX,OAAO;GACP,UAAU,MAAM,SAAS,IAAI,MAAM,MAAM,SAAS,KAAM;;EAG1D,MAAM,eAAe,YAAY,MAAM,SAAS;AAC9C,OAAI,SAAS,KACX,QAAO;AAET,UAAO,CAAC,GAAG,OAAO;;AAGpB,OAAK,YAAY;AACjB,SAAO;;;AAcX,SAAS,YACP,YACA,SACmD;AACnD,QAAOC,8BAAgD,MAAM,cAAY;AACvE,MAAI,sBAAsB,SACxB,cAAa,WAAW,GAAG;AAE7B,SAAO,IAAI,WAAW,YAAY,MAAMC;IACvC;;AAGL,MAAaC,mBACK,uBAAO,OAAO,aAAa,EACzC,gBAAgBC;;;;AC/GpB,SAAgB,cACd,OACA,WACA,cACG;CACH,MAAM,QAAQ,MAAM,UAAU;AAE9B,KAAI,SAAS,EACX,QAAO,MAAM;CAGf,MAAM,QAAQ,wBAAwB,WAAW,iBAAiB;AAClE,OAAM,KAAK;AACX,QAAO"}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,8 +1,33 @@
|
|
|
1
|
-
import { Cache, CacheBundle, CacheFunction, CacheGetOptions, CacheOptions, CacheState, CreateCacheResult, ErrorState, PendingState, Resource, ResourceGroup, Scope, ValueState, allResources, createCache, createResourceGroup, createScope } from "./scope-
|
|
1
|
+
import { Cache, CacheBundle, CacheFunction, CacheGetOptions, CacheOptions, CacheState, CreateCacheResult, ErrorState, PendingState, Resource, ResourceGroup, Scope, ValueState, allResources, createCache, createResourceGroup, createScope } from "./scope-6B7-8lwa.cjs";
|
|
2
2
|
import { AsyncConnectionActions, AsyncUpdateFunction, BaseConnectionActions, BoundStoreMethods, CalculationActions, Cancel, Connection, ConnectionActions, Constrain, DisposableCancel, Duration, Effect, KeyType, Listener, Path, PathAsArray, PathAsString, Selector, SettablePath, SettablePathAsArray, SettablePathAsString, SettableValue, Store, StoreMethods, StoreOptions, StoreOptionsWithMethods, SubscribeOptions, Update, UpdateFrom, UpdateFunction, Use, Value, arrayMethods, createStore, mapMethods, recordMethods, setMethods } from "./store-BEsiS8y7.cjs";
|
|
3
3
|
import { Patch, diff } from "./diff-BQ8bB3Wk.cjs";
|
|
4
4
|
import { Persist, PersistOptions, PersistStorage, PersistStorageBase, PersistStorageWithKeys, PersistStorageWithLength, PersistStorageWithListItems, persist } from "./persist-D7MAsyyW.cjs";
|
|
5
5
|
|
|
6
|
+
//#region src/core/pagedCache.d.ts
|
|
7
|
+
interface PageCacheFunctionProps<T> extends CalculationActions<Promise<T[]>> {
|
|
8
|
+
pages: T[];
|
|
9
|
+
prevPage: T | null;
|
|
10
|
+
}
|
|
11
|
+
interface PageCacheFunction<T> {
|
|
12
|
+
(props: PageCacheFunctionProps<T>): Promise<T | null>;
|
|
13
|
+
}
|
|
14
|
+
interface PagedCacheDefinition<T> {
|
|
15
|
+
fetchPage: (props: PageCacheFunctionProps<T>) => Promise<T | null>;
|
|
16
|
+
}
|
|
17
|
+
interface PagedCacheDefinitionFunction<T, Args extends any[]> {
|
|
18
|
+
(...args: Args): PagedCacheDefinition<T>;
|
|
19
|
+
}
|
|
20
|
+
declare class PagedCache<T, Args extends any[] = []> extends Cache<T[], Args> {
|
|
21
|
+
readonly definition: PagedCacheDefinition<T>;
|
|
22
|
+
constructor(definition: PagedCacheDefinition<T>, args: Args, options?: CacheOptions<T[], Args>);
|
|
23
|
+
fetchNextPage(): Promise<T | null>;
|
|
24
|
+
}
|
|
25
|
+
declare function createPaged<T, Args extends any[] = []>(definition: PagedCacheDefinitionFunction<T, Args>, options?: CacheOptions<T[], Args>): CreateCacheResult<T[], Args, PagedCache<T, Args>>;
|
|
26
|
+
declare function createPaged<T>(definition: PagedCacheDefinition<T>, options?: CacheOptions<T[], []>): CreateCacheResult<T[], [], PagedCache<T, []>>;
|
|
27
|
+
declare const createPagedCache: typeof createPaged & {
|
|
28
|
+
defaultOptions: CacheOptions<any, any>;
|
|
29
|
+
};
|
|
30
|
+
//#endregion
|
|
6
31
|
//#region src/lib/applyPatches.d.ts
|
|
7
32
|
declare function applyPatches<T>(target: T, ...patches: Patch[]): T;
|
|
8
33
|
//#endregion
|
|
@@ -61,5 +86,5 @@ declare function set<T, const P>(object: T, path: Constrain<P, SettablePath<T>>,
|
|
|
61
86
|
//#region src/lib/updateHelpers.d.ts
|
|
62
87
|
declare function findOrDefault<T>(array: T[], predicate: (item: T) => boolean, defaultValue: T | (() => T)): T;
|
|
63
88
|
//#endregion
|
|
64
|
-
export { AsyncConnectionActions, AsyncUpdateFunction, BaseConnectionActions, BoundStoreMethods, Cache, CacheBundle, CacheFunction, CacheGetOptions, CacheOptions, CacheState, CalculationActions, Cancel, Connection, ConnectionActions, CreateCacheResult, DisposableCancel, Duration, Effect, ErrorState, type Hashable, InstanceCache, Listener, type Patch, type Path, type PathAsArray, type PathAsString, PendingState, Persist, PersistOptions, PersistStorage, PersistStorageBase, PersistStorageWithKeys, PersistStorageWithLength, PersistStorageWithListItems, Resource, ResourceGroup, Scope, Selector, type SettablePath, type SettablePathAsArray, type SettablePathAsString, Store, StoreMethods, StoreOptions, StoreOptionsWithMethods, SubscribeOptions, Update, UpdateFrom, UpdateFunction, Use, type Value, ValueState, allResources, applyPatches, arrayMethods, calcDuration, createCache, createResourceGroup, createScope, createStore, deepEqual, diff, findOrDefault, fromExtendedJson, fromExtendedJsonString, get, hash, mapMethods, persist, recordMethods, set, setMethods, shallowEqual, simpleHash, strictEqual, toExtendedJson, toExtendedJsonString };
|
|
89
|
+
export { AsyncConnectionActions, AsyncUpdateFunction, BaseConnectionActions, BoundStoreMethods, Cache, CacheBundle, CacheFunction, CacheGetOptions, CacheOptions, CacheState, CalculationActions, Cancel, Connection, ConnectionActions, CreateCacheResult, DisposableCancel, Duration, Effect, ErrorState, type Hashable, InstanceCache, Listener, PageCacheFunction, PageCacheFunctionProps, PagedCache, PagedCacheDefinition, PagedCacheDefinitionFunction, type Patch, type Path, type PathAsArray, type PathAsString, PendingState, Persist, PersistOptions, PersistStorage, PersistStorageBase, PersistStorageWithKeys, PersistStorageWithLength, PersistStorageWithListItems, Resource, ResourceGroup, Scope, Selector, type SettablePath, type SettablePathAsArray, type SettablePathAsString, Store, StoreMethods, StoreOptions, StoreOptionsWithMethods, SubscribeOptions, Update, UpdateFrom, UpdateFunction, Use, type Value, ValueState, allResources, applyPatches, arrayMethods, calcDuration, createCache, createPagedCache, createResourceGroup, createScope, createStore, deepEqual, diff, findOrDefault, fromExtendedJson, fromExtendedJsonString, get, hash, mapMethods, persist, recordMethods, set, setMethods, shallowEqual, simpleHash, strictEqual, toExtendedJson, toExtendedJsonString };
|
|
65
90
|
//# sourceMappingURL=index.d.cts.map
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,33 @@
|
|
|
1
|
-
import { Cache, CacheBundle, CacheFunction, CacheGetOptions, CacheOptions, CacheState, CreateCacheResult, ErrorState, PendingState, Resource, ResourceGroup, Scope, ValueState, allResources, createCache, createResourceGroup, createScope } from "./scope-
|
|
1
|
+
import { Cache, CacheBundle, CacheFunction, CacheGetOptions, CacheOptions, CacheState, CreateCacheResult, ErrorState, PendingState, Resource, ResourceGroup, Scope, ValueState, allResources, createCache, createResourceGroup, createScope } from "./scope-BbUXgNW_.js";
|
|
2
2
|
import { AsyncConnectionActions, AsyncUpdateFunction, BaseConnectionActions, BoundStoreMethods, CalculationActions, Cancel, Connection, ConnectionActions, Constrain, DisposableCancel, Duration, Effect, KeyType, Listener, Path, PathAsArray, PathAsString, Selector, SettablePath, SettablePathAsArray, SettablePathAsString, SettableValue, Store, StoreMethods, StoreOptions, StoreOptionsWithMethods, SubscribeOptions, Update, UpdateFrom, UpdateFunction, Use, Value, arrayMethods, createStore, mapMethods, recordMethods, setMethods } from "./store-DKaeE840.js";
|
|
3
3
|
import { Patch, diff } from "./diff-gZezL04N.js";
|
|
4
4
|
import { Persist, PersistOptions, PersistStorage, PersistStorageBase, PersistStorageWithKeys, PersistStorageWithLength, PersistStorageWithListItems, persist } from "./persist-CPjpg6D0.js";
|
|
5
5
|
|
|
6
|
+
//#region src/core/pagedCache.d.ts
|
|
7
|
+
interface PageCacheFunctionProps<T> extends CalculationActions<Promise<T[]>> {
|
|
8
|
+
pages: T[];
|
|
9
|
+
prevPage: T | null;
|
|
10
|
+
}
|
|
11
|
+
interface PageCacheFunction<T> {
|
|
12
|
+
(props: PageCacheFunctionProps<T>): Promise<T | null>;
|
|
13
|
+
}
|
|
14
|
+
interface PagedCacheDefinition<T> {
|
|
15
|
+
fetchPage: (props: PageCacheFunctionProps<T>) => Promise<T | null>;
|
|
16
|
+
}
|
|
17
|
+
interface PagedCacheDefinitionFunction<T, Args extends any[]> {
|
|
18
|
+
(...args: Args): PagedCacheDefinition<T>;
|
|
19
|
+
}
|
|
20
|
+
declare class PagedCache<T, Args extends any[] = []> extends Cache<T[], Args> {
|
|
21
|
+
readonly definition: PagedCacheDefinition<T>;
|
|
22
|
+
constructor(definition: PagedCacheDefinition<T>, args: Args, options?: CacheOptions<T[], Args>);
|
|
23
|
+
fetchNextPage(): Promise<T | null>;
|
|
24
|
+
}
|
|
25
|
+
declare function createPaged<T, Args extends any[] = []>(definition: PagedCacheDefinitionFunction<T, Args>, options?: CacheOptions<T[], Args>): CreateCacheResult<T[], Args, PagedCache<T, Args>>;
|
|
26
|
+
declare function createPaged<T>(definition: PagedCacheDefinition<T>, options?: CacheOptions<T[], []>): CreateCacheResult<T[], [], PagedCache<T, []>>;
|
|
27
|
+
declare const createPagedCache: typeof createPaged & {
|
|
28
|
+
defaultOptions: CacheOptions<any, any>;
|
|
29
|
+
};
|
|
30
|
+
//#endregion
|
|
6
31
|
//#region src/lib/applyPatches.d.ts
|
|
7
32
|
declare function applyPatches<T>(target: T, ...patches: Patch[]): T;
|
|
8
33
|
//#endregion
|
|
@@ -61,5 +86,5 @@ declare function set<T, const P>(object: T, path: Constrain<P, SettablePath<T>>,
|
|
|
61
86
|
//#region src/lib/updateHelpers.d.ts
|
|
62
87
|
declare function findOrDefault<T>(array: T[], predicate: (item: T) => boolean, defaultValue: T | (() => T)): T;
|
|
63
88
|
//#endregion
|
|
64
|
-
export { AsyncConnectionActions, AsyncUpdateFunction, BaseConnectionActions, BoundStoreMethods, Cache, CacheBundle, CacheFunction, CacheGetOptions, CacheOptions, CacheState, CalculationActions, Cancel, Connection, ConnectionActions, CreateCacheResult, DisposableCancel, Duration, Effect, ErrorState, type Hashable, InstanceCache, Listener, type Patch, type Path, type PathAsArray, type PathAsString, PendingState, Persist, PersistOptions, PersistStorage, PersistStorageBase, PersistStorageWithKeys, PersistStorageWithLength, PersistStorageWithListItems, Resource, ResourceGroup, Scope, Selector, type SettablePath, type SettablePathAsArray, type SettablePathAsString, Store, StoreMethods, StoreOptions, StoreOptionsWithMethods, SubscribeOptions, Update, UpdateFrom, UpdateFunction, Use, type Value, ValueState, allResources, applyPatches, arrayMethods, calcDuration, createCache, createResourceGroup, createScope, createStore, deepEqual, diff, findOrDefault, fromExtendedJson, fromExtendedJsonString, get, hash, mapMethods, persist, recordMethods, set, setMethods, shallowEqual, simpleHash, strictEqual, toExtendedJson, toExtendedJsonString };
|
|
89
|
+
export { AsyncConnectionActions, AsyncUpdateFunction, BaseConnectionActions, BoundStoreMethods, Cache, CacheBundle, CacheFunction, CacheGetOptions, CacheOptions, CacheState, CalculationActions, Cancel, Connection, ConnectionActions, CreateCacheResult, DisposableCancel, Duration, Effect, ErrorState, type Hashable, InstanceCache, Listener, PageCacheFunction, PageCacheFunctionProps, PagedCache, PagedCacheDefinition, PagedCacheDefinitionFunction, type Patch, type Path, type PathAsArray, type PathAsString, PendingState, Persist, PersistOptions, PersistStorage, PersistStorageBase, PersistStorageWithKeys, PersistStorageWithLength, PersistStorageWithListItems, Resource, ResourceGroup, Scope, Selector, type SettablePath, type SettablePathAsArray, type SettablePathAsString, Store, StoreMethods, StoreOptions, StoreOptionsWithMethods, SubscribeOptions, Update, UpdateFrom, UpdateFunction, Use, type Value, ValueState, allResources, applyPatches, arrayMethods, calcDuration, createCache, createPagedCache, createResourceGroup, createScope, createStore, deepEqual, diff, findOrDefault, fromExtendedJson, fromExtendedJsonString, get, hash, mapMethods, persist, recordMethods, set, setMethods, shallowEqual, simpleHash, strictEqual, toExtendedJson, toExtendedJsonString };
|
|
65
90
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
@@ -1,11 +1,60 @@
|
|
|
1
|
-
import { Store, arrayMethods, calcDuration, createStore, mapMethods, recordMethods, setMethods } from "./store-BpMJxIHt.js";
|
|
1
|
+
import { Store, arrayMethods, autobind, calcDuration, createStore, mapMethods, recordMethods, setMethods } from "./store-BpMJxIHt.js";
|
|
2
2
|
import { deepEqual, get, set, shallowEqual, strictEqual } from "./propAccess-B260LXN1.js";
|
|
3
3
|
import { hash, simpleHash } from "./hash-DNFM5y_h.js";
|
|
4
|
-
import { Cache, InstanceCache, ResourceGroup, Scope, allResources, createCache, createResourceGroup, createScope } from "./scope-
|
|
4
|
+
import { Cache, InstanceCache, ResourceGroup, Scope, allResources, createCache, createResourceGroup, createScope, defaultCacheOptions, internalCreate } from "./scope-CKXL9xoi.js";
|
|
5
5
|
import { applyPatches, diff } from "./patchMethods-C_f3PORQ.js";
|
|
6
6
|
import { fromExtendedJson, fromExtendedJsonString, toExtendedJson, toExtendedJsonString } from "./extendedJson-BZkQBXEv.js";
|
|
7
7
|
import { persist } from "./persist-Btgg3qGU.js";
|
|
8
8
|
|
|
9
|
+
//#region src/core/pagedCache.ts
|
|
10
|
+
var PagedCache = class PagedCache extends Cache {
|
|
11
|
+
constructor(definition, args, options = {}) {
|
|
12
|
+
super(async (helpers) => {
|
|
13
|
+
const { fetchPage } = definition;
|
|
14
|
+
const page = await fetchPage({
|
|
15
|
+
...helpers,
|
|
16
|
+
pages: [],
|
|
17
|
+
prevPage: null
|
|
18
|
+
});
|
|
19
|
+
return page === null ? [] : [page];
|
|
20
|
+
}, args, options, void 0);
|
|
21
|
+
this.definition = definition;
|
|
22
|
+
autobind(PagedCache);
|
|
23
|
+
}
|
|
24
|
+
async fetchNextPage() {
|
|
25
|
+
const { fetchPage } = this.definition;
|
|
26
|
+
const { status, isStale, isUpdating, value } = this.state.get();
|
|
27
|
+
if (status !== "value" || isStale || isUpdating) throw new Error("Cannot fetch next page while cache is not in a stable state");
|
|
28
|
+
this.stalePromise = this.calculatedValue?.value;
|
|
29
|
+
const ac = new AbortController();
|
|
30
|
+
const pagePromise = fetchPage({
|
|
31
|
+
use() {
|
|
32
|
+
throw new Error("Not implemented");
|
|
33
|
+
},
|
|
34
|
+
connect() {
|
|
35
|
+
throw new Error("Not implemented");
|
|
36
|
+
},
|
|
37
|
+
signal: ac.signal,
|
|
38
|
+
pages: value,
|
|
39
|
+
prevPage: value.length > 0 ? value[value.length - 1] : null
|
|
40
|
+
});
|
|
41
|
+
const valuePromise = pagePromise.then((page) => {
|
|
42
|
+
if (page === null) return value;
|
|
43
|
+
return [...value, page];
|
|
44
|
+
});
|
|
45
|
+
this.updateValue(valuePromise);
|
|
46
|
+
return pagePromise;
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
function createPaged(definition, options) {
|
|
50
|
+
return internalCreate((args, options$1) => {
|
|
51
|
+
if (definition instanceof Function) definition = definition(...args);
|
|
52
|
+
return new PagedCache(definition, args, options$1);
|
|
53
|
+
}, options);
|
|
54
|
+
}
|
|
55
|
+
const createPagedCache = /* @__PURE__ */ Object.assign(createPaged, { defaultOptions: defaultCacheOptions });
|
|
56
|
+
|
|
57
|
+
//#endregion
|
|
9
58
|
//#region src/lib/updateHelpers.ts
|
|
10
59
|
function findOrDefault(array, predicate, defaultValue) {
|
|
11
60
|
const index = array.findIndex(predicate);
|
|
@@ -16,5 +65,5 @@ function findOrDefault(array, predicate, defaultValue) {
|
|
|
16
65
|
}
|
|
17
66
|
|
|
18
67
|
//#endregion
|
|
19
|
-
export { Cache, InstanceCache, ResourceGroup, Scope, Store, allResources, applyPatches, arrayMethods, calcDuration, createCache, createResourceGroup, createScope, createStore, deepEqual, diff, findOrDefault, fromExtendedJson, fromExtendedJsonString, get, hash, mapMethods, persist, recordMethods, set, setMethods, shallowEqual, simpleHash, strictEqual, toExtendedJson, toExtendedJsonString };
|
|
68
|
+
export { Cache, InstanceCache, ResourceGroup, Scope, Store, allResources, applyPatches, arrayMethods, calcDuration, createCache, createPagedCache, createResourceGroup, createScope, createStore, deepEqual, diff, findOrDefault, fromExtendedJson, fromExtendedJsonString, get, hash, mapMethods, persist, recordMethods, set, setMethods, shallowEqual, simpleHash, strictEqual, toExtendedJson, toExtendedJsonString };
|
|
20
69
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/lib/updateHelpers.ts"],"sourcesContent":["export function findOrDefault<T>(\n array: T[],\n predicate: (item: T) => boolean,\n defaultValue: T | (() => T),\n): T {\n const index = array.findIndex(predicate);\n\n if (index >= 0) {\n return array[index]!;\n }\n\n const value = defaultValue instanceof Function ? defaultValue() : defaultValue;\n array.push(value);\n return value;\n}\n"],"mappings":";;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.js","names":["definition: PagedCacheDefinition<T>","options","createPagedCache: typeof createPaged & { defaultOptions: CacheOptions<any, any> }"],"sources":["../src/core/pagedCache.ts","../src/lib/updateHelpers.ts"],"sourcesContent":["import {\n Cache,\n defaultCacheOptions,\n internalCreate,\n type CacheOptions,\n type CreateCacheResult,\n} from '@core/cache';\nimport type { CalculationActions } from '@core/commonTypes';\nimport { autobind } from '@lib/autobind';\n\nexport interface PageCacheFunctionProps<T> extends CalculationActions<Promise<T[]>> {\n pages: T[];\n prevPage: T | null;\n}\n\nexport interface PageCacheFunction<T> {\n (props: PageCacheFunctionProps<T>): Promise<T | null>;\n}\n\nexport interface PagedCacheDefinition<T> {\n fetchPage: (props: PageCacheFunctionProps<T>) => Promise<T | null>;\n}\n\nexport interface PagedCacheDefinitionFunction<T, Args extends any[]> {\n (...args: Args): PagedCacheDefinition<T>;\n}\n\nexport class PagedCache<T, Args extends any[] = []> extends Cache<T[], Args> {\n constructor(\n public readonly definition: PagedCacheDefinition<T>,\n args: Args,\n options: CacheOptions<T[], Args> = {},\n ) {\n super(\n async (helpers) => {\n const { fetchPage } = definition;\n\n const page = await fetchPage({\n ...helpers,\n pages: [],\n prevPage: null,\n });\n\n return page === null ? [] : [page];\n },\n args,\n options,\n undefined,\n );\n autobind(PagedCache);\n }\n\n async fetchNextPage(): Promise<T | null> {\n const { fetchPage } = this.definition;\n const { status, isStale, isUpdating, value } = this.state.get();\n\n if (status !== 'value' || isStale || isUpdating) {\n throw new Error('Cannot fetch next page while cache is not in a stable state');\n }\n\n this.stalePromise = this.calculatedValue?.value;\n\n const ac = new AbortController();\n const pagePromise = fetchPage({\n use() {\n throw new Error('Not implemented');\n },\n connect() {\n throw new Error('Not implemented');\n },\n signal: ac.signal,\n pages: value,\n prevPage: value.length > 0 ? value[value.length - 1]! : null,\n });\n\n const valuePromise = pagePromise.then((page) => {\n if (page === null) {\n return value;\n }\n return [...value, page];\n });\n\n this.updateValue(valuePromise);\n return pagePromise;\n }\n}\n\nfunction createPaged<T, Args extends any[] = []>(\n definition: PagedCacheDefinitionFunction<T, Args>,\n options?: CacheOptions<T[], Args>,\n): CreateCacheResult<T[], Args, PagedCache<T, Args>>;\n\nfunction createPaged<T>(\n definition: PagedCacheDefinition<T>,\n options?: CacheOptions<T[], []>,\n): CreateCacheResult<T[], [], PagedCache<T, []>>;\n\nfunction createPaged<T, Args extends any[] = []>(\n definition: PagedCacheDefinitionFunction<T, Args> | PagedCacheDefinition<T>,\n options?: CacheOptions<T[], Args>,\n): CreateCacheResult<T[], Args, PagedCache<T, Args>> {\n return internalCreate<T[], Args, PagedCache<T, Args>>((args, options) => {\n if (definition instanceof Function) {\n definition = definition(...args);\n }\n return new PagedCache(definition, args, options);\n }, options);\n}\n\nexport const createPagedCache: typeof createPaged & { defaultOptions: CacheOptions<any, any> } =\n /* @__PURE__ */ Object.assign(createPaged, {\n defaultOptions: defaultCacheOptions,\n });\n","export function findOrDefault<T>(\n array: T[],\n predicate: (item: T) => boolean,\n defaultValue: T | (() => T),\n): T {\n const index = array.findIndex(predicate);\n\n if (index >= 0) {\n return array[index]!;\n }\n\n const value = defaultValue instanceof Function ? defaultValue() : defaultValue;\n array.push(value);\n return value;\n}\n"],"mappings":";;;;;;;;;AA2BA,IAAa,aAAb,MAAa,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scope-
|
|
1
|
+
import "../scope-6B7-8lwa.cjs";
|
|
2
2
|
import { Constrain, Duration, GetKeys, Join, MaybePromise, Object_, Path as Path$1, PathAsString, Selector, Store, Update, UpdateFunction, Value, WildcardPathAsString, WildcardValue } from "../store-BEsiS8y7.cjs";
|
|
3
|
-
import { ScopeProps, ScopeProvider, UseCacheArray, UseCacheValue, UseStoreOptions, cacheMethods, scopeMethods, storeMethods, useCache, useScope, useStore } from "../storeMethods-
|
|
3
|
+
import { ScopeProps, ScopeProvider, UseCacheArray, UseCacheValue, UseStoreOptions, cacheMethods, scopeMethods, storeMethods, useCache, useScope, useStore } from "../storeMethods-Bg8nMBrf.cjs";
|
|
4
4
|
import React$1, { Component, ComponentPropsWithoutRef, Context, FormEvent, FunctionComponent, HTMLProps, ReactNode } from "react";
|
|
5
5
|
|
|
6
6
|
//#region src/react/form/customInput.d.ts
|
package/dist/react/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import "../scope-
|
|
1
|
+
import "../scope-BbUXgNW_.js";
|
|
2
2
|
import { Constrain, Duration, GetKeys, Join, MaybePromise, Object_, Path as Path$1, PathAsString, Selector, Store, Update, UpdateFunction, Value, WildcardPathAsString, WildcardValue } from "../store-DKaeE840.js";
|
|
3
|
-
import { ScopeProps, ScopeProvider, UseCacheArray, UseCacheValue, UseStoreOptions, cacheMethods, scopeMethods, storeMethods, useCache, useScope, useStore } from "../storeMethods-
|
|
3
|
+
import { ScopeProps, ScopeProvider, UseCacheArray, UseCacheValue, UseStoreOptions, cacheMethods, scopeMethods, storeMethods, useCache, useScope, useStore } from "../storeMethods-DWKSveN0.js";
|
|
4
4
|
import React$1, { Component, ComponentPropsWithoutRef, Context, FormEvent, FunctionComponent, HTMLProps, ReactNode } from "react";
|
|
5
5
|
|
|
6
6
|
//#region src/react/form/customInput.d.ts
|
package/dist/react/register.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
const require_store = require('../store-1TGlSyq4.cjs');
|
|
2
2
|
require('../propAccess-BdLsqViO.cjs');
|
|
3
3
|
require('../hash-Dv3XlmHn.cjs');
|
|
4
|
-
const require_scope = require('../scope-
|
|
4
|
+
const require_scope = require('../scope-CoDFmhxK.cjs');
|
|
5
5
|
const require_storeMethods = require('../storeMethods-C_RzHBQL.cjs');
|
|
6
6
|
|
|
7
7
|
//#region src/react/register.ts
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import "../scope-
|
|
1
|
+
import "../scope-6B7-8lwa.cjs";
|
|
2
2
|
import "../store-BEsiS8y7.cjs";
|
|
3
|
-
import { cacheMethods, scopeMethods, storeMethods } from "../storeMethods-
|
|
3
|
+
import { cacheMethods, scopeMethods, storeMethods } from "../storeMethods-Bg8nMBrf.cjs";
|
|
4
4
|
|
|
5
5
|
//#region src/react/register.d.ts
|
|
6
6
|
type StoreMethods = typeof storeMethods;
|
package/dist/react/register.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import "../scope-
|
|
1
|
+
import "../scope-BbUXgNW_.js";
|
|
2
2
|
import "../store-DKaeE840.js";
|
|
3
|
-
import { cacheMethods, scopeMethods, storeMethods } from "../storeMethods-
|
|
3
|
+
import { cacheMethods, scopeMethods, storeMethods } from "../storeMethods-DWKSveN0.js";
|
|
4
4
|
|
|
5
5
|
//#region src/react/register.d.ts
|
|
6
6
|
type StoreMethods = typeof storeMethods;
|
package/dist/react/register.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Store, autobind } from "../store-BpMJxIHt.js";
|
|
2
2
|
import "../propAccess-B260LXN1.js";
|
|
3
3
|
import "../hash-DNFM5y_h.js";
|
|
4
|
-
import { Cache, Scope } from "../scope-
|
|
4
|
+
import { Cache, Scope } from "../scope-CKXL9xoi.js";
|
|
5
5
|
import { cacheMethods, scopeMethods, storeMethods } from "../storeMethods-CkvcMFoL.js";
|
|
6
6
|
|
|
7
7
|
//#region src/react/register.ts
|
|
@@ -139,19 +139,19 @@ declare class Cache<T, Args extends any[] = []> extends Store<Promise<T>> {
|
|
|
139
139
|
protected setTimers(): void;
|
|
140
140
|
protected watchFocus(): void;
|
|
141
141
|
}
|
|
142
|
-
type CreateCacheResult<T, Args extends any[]
|
|
143
|
-
interface InvalidationOptions<T, Args extends any[]
|
|
144
|
-
filter?: (cache:
|
|
142
|
+
type CreateCacheResult<T, Args extends any[], TCache extends Cache<T, Args>> = [] extends Args ? CacheBundle<T, Args, TCache> & TCache : CacheBundle<T, Args, TCache>;
|
|
143
|
+
interface InvalidationOptions<T, Args extends any[], TCache extends Cache<T, Args>> {
|
|
144
|
+
filter?: (cache: TCache) => boolean;
|
|
145
145
|
}
|
|
146
|
-
type CacheBundle<T, Args extends any[]
|
|
147
|
-
(...args: Args):
|
|
148
|
-
mapCache<S>(selector: Selector<T, S>): CreateCacheResult<S, Args
|
|
149
|
-
mapValue<const P>(selector: Constrain<P, Path<T>>): CreateCacheResult<Value<T, P>, Args
|
|
150
|
-
invalidateAll: (options?: InvalidationOptions<T, Args>) => void;
|
|
151
|
-
clearAll: (options?: InvalidationOptions<T, Args>) => void;
|
|
152
|
-
getInstances: () =>
|
|
146
|
+
type CacheBundle<T, Args extends any[], TCache extends Cache<T, Args>> = {
|
|
147
|
+
(...args: Args): TCache;
|
|
148
|
+
mapCache<S>(selector: Selector<T, S>): CreateCacheResult<S, Args, Cache<S, Args>>;
|
|
149
|
+
mapValue<const P>(selector: Constrain<P, Path<T>>): CreateCacheResult<Value<T, P>, Args, Cache<Value<T, P>, Args>>;
|
|
150
|
+
invalidateAll: (options?: InvalidationOptions<T, Args, TCache>) => void;
|
|
151
|
+
clearAll: (options?: InvalidationOptions<T, Args, TCache>) => void;
|
|
152
|
+
getInstances: () => TCache[];
|
|
153
153
|
};
|
|
154
|
-
declare function create<T, Args extends any[] = []>(cacheFunction: CacheFunction<T, Args>, options?: CacheOptions<T, Args>): CreateCacheResult<T, Args
|
|
154
|
+
declare function create<T, Args extends any[] = []>(cacheFunction: CacheFunction<T, Args>, options?: CacheOptions<T, Args>): CreateCacheResult<T, Args, Cache<T, Args>>;
|
|
155
155
|
declare const createCache: typeof create & {
|
|
156
156
|
defaultOptions: CacheOptions<any, any>;
|
|
157
157
|
};
|
|
@@ -164,4 +164,4 @@ declare class Scope<T> {
|
|
|
164
164
|
declare function createScope<T>(defaultValue: T): Scope<T>;
|
|
165
165
|
//#endregion
|
|
166
166
|
export { Cache, CacheBundle, CacheFunction, CacheGetOptions, CacheOptions, CacheState, CreateCacheResult, ErrorState, PendingState, Resource, ResourceGroup, Scope, ValueState, allResources, createCache, createResourceGroup, createScope };
|
|
167
|
-
//# sourceMappingURL=scope-
|
|
167
|
+
//# sourceMappingURL=scope-6B7-8lwa.d.cts.map
|
|
@@ -139,19 +139,19 @@ declare class Cache<T, Args extends any[] = []> extends Store<Promise<T>> {
|
|
|
139
139
|
protected setTimers(): void;
|
|
140
140
|
protected watchFocus(): void;
|
|
141
141
|
}
|
|
142
|
-
type CreateCacheResult<T, Args extends any[]
|
|
143
|
-
interface InvalidationOptions<T, Args extends any[]
|
|
144
|
-
filter?: (cache:
|
|
142
|
+
type CreateCacheResult<T, Args extends any[], TCache extends Cache<T, Args>> = [] extends Args ? CacheBundle<T, Args, TCache> & TCache : CacheBundle<T, Args, TCache>;
|
|
143
|
+
interface InvalidationOptions<T, Args extends any[], TCache extends Cache<T, Args>> {
|
|
144
|
+
filter?: (cache: TCache) => boolean;
|
|
145
145
|
}
|
|
146
|
-
type CacheBundle<T, Args extends any[]
|
|
147
|
-
(...args: Args):
|
|
148
|
-
mapCache<S>(selector: Selector<T, S>): CreateCacheResult<S, Args
|
|
149
|
-
mapValue<const P>(selector: Constrain<P, Path<T>>): CreateCacheResult<Value<T, P>, Args
|
|
150
|
-
invalidateAll: (options?: InvalidationOptions<T, Args>) => void;
|
|
151
|
-
clearAll: (options?: InvalidationOptions<T, Args>) => void;
|
|
152
|
-
getInstances: () =>
|
|
146
|
+
type CacheBundle<T, Args extends any[], TCache extends Cache<T, Args>> = {
|
|
147
|
+
(...args: Args): TCache;
|
|
148
|
+
mapCache<S>(selector: Selector<T, S>): CreateCacheResult<S, Args, Cache<S, Args>>;
|
|
149
|
+
mapValue<const P>(selector: Constrain<P, Path<T>>): CreateCacheResult<Value<T, P>, Args, Cache<Value<T, P>, Args>>;
|
|
150
|
+
invalidateAll: (options?: InvalidationOptions<T, Args, TCache>) => void;
|
|
151
|
+
clearAll: (options?: InvalidationOptions<T, Args, TCache>) => void;
|
|
152
|
+
getInstances: () => TCache[];
|
|
153
153
|
};
|
|
154
|
-
declare function create<T, Args extends any[] = []>(cacheFunction: CacheFunction<T, Args>, options?: CacheOptions<T, Args>): CreateCacheResult<T, Args
|
|
154
|
+
declare function create<T, Args extends any[] = []>(cacheFunction: CacheFunction<T, Args>, options?: CacheOptions<T, Args>): CreateCacheResult<T, Args, Cache<T, Args>>;
|
|
155
155
|
declare const createCache: typeof create & {
|
|
156
156
|
defaultOptions: CacheOptions<any, any>;
|
|
157
157
|
};
|
|
@@ -164,4 +164,4 @@ declare class Scope<T> {
|
|
|
164
164
|
declare function createScope<T>(defaultValue: T): Scope<T>;
|
|
165
165
|
//#endregion
|
|
166
166
|
export { Cache, CacheBundle, CacheFunction, CacheGetOptions, CacheOptions, CacheState, CreateCacheResult, ErrorState, PendingState, Resource, ResourceGroup, Scope, ValueState, allResources, createCache, createResourceGroup, createScope };
|
|
167
|
-
//# sourceMappingURL=scope-
|
|
167
|
+
//# sourceMappingURL=scope-BbUXgNW_.d.ts.map
|
|
@@ -241,26 +241,20 @@ function mapValue(cache, _selector) {
|
|
|
241
241
|
}, cache.args, { equals: cache.options.equals }, derivedFromCache);
|
|
242
242
|
}
|
|
243
243
|
function create(cacheFunction, options) {
|
|
244
|
-
return internalCreate(
|
|
244
|
+
return internalCreate((args, options$1) => new Cache((helpers) => {
|
|
245
|
+
const result = cacheFunction.apply(helpers, args);
|
|
246
|
+
if (result instanceof Function) return result(helpers);
|
|
247
|
+
return result;
|
|
248
|
+
}, args, options$1, void 0), options);
|
|
245
249
|
}
|
|
246
|
-
function internalCreate(
|
|
250
|
+
function internalCreate(factory, options) {
|
|
247
251
|
options = {
|
|
248
252
|
...createCache.defaultOptions,
|
|
249
253
|
...options
|
|
250
254
|
};
|
|
251
255
|
const { clearUnusedAfter, resourceGroup } = options ?? {};
|
|
252
256
|
let baseInstance;
|
|
253
|
-
const instanceCache = new InstanceCache((...args) =>
|
|
254
|
-
if (Array.isArray(source)) {
|
|
255
|
-
const [cache, selector] = source;
|
|
256
|
-
return mapValue(cache(...args), selector);
|
|
257
|
-
}
|
|
258
|
-
return new Cache((helpers) => {
|
|
259
|
-
const result = source.apply(helpers, args);
|
|
260
|
-
if (result instanceof Function) return result(helpers);
|
|
261
|
-
return result;
|
|
262
|
-
}, args, options, void 0);
|
|
263
|
-
}, clearUnusedAfter ? calcDuration(clearUnusedAfter) : void 0);
|
|
257
|
+
const instanceCache = new InstanceCache((...args) => factory(args, options), clearUnusedAfter ? calcDuration(clearUnusedAfter) : void 0);
|
|
264
258
|
function get(...args) {
|
|
265
259
|
const sliceAfter = args.lastIndexOf(void 0);
|
|
266
260
|
if (sliceAfter !== -1) args = args.slice(0, sliceAfter);
|
|
@@ -268,7 +262,7 @@ function internalCreate(source, options) {
|
|
|
268
262
|
return instanceCache.getWithKey(args, cacheKey);
|
|
269
263
|
}
|
|
270
264
|
const mapCache = (selector) => {
|
|
271
|
-
return internalCreate(
|
|
265
|
+
return internalCreate((args) => mapValue(baseInstance(...args), selector));
|
|
272
266
|
};
|
|
273
267
|
const invalidateAll = ({ filter = () => true } = {}) => {
|
|
274
268
|
for (const instance of instanceCache.values()) if (filter(instance)) instance.invalidate();
|
|
@@ -298,12 +292,13 @@ function internalCreate(source, options) {
|
|
|
298
292
|
for (const group of groups.concat(allResources)) group.add(baseInstance);
|
|
299
293
|
return baseInstance;
|
|
300
294
|
}
|
|
301
|
-
const
|
|
295
|
+
const defaultCacheOptions = {
|
|
302
296
|
invalidateOnWindowFocus: true,
|
|
303
297
|
clearUnusedAfter: { days: 1 },
|
|
304
298
|
retain: { milliseconds: 1 },
|
|
305
299
|
equals: deepEqual
|
|
306
|
-
}
|
|
300
|
+
};
|
|
301
|
+
const createCache = /* @__PURE__ */ Object.assign(create, { defaultOptions: defaultCacheOptions });
|
|
307
302
|
|
|
308
303
|
//#endregion
|
|
309
304
|
//#region src/core/scope.ts
|
|
@@ -318,5 +313,5 @@ function createScope(defaultValue) {
|
|
|
318
313
|
}
|
|
319
314
|
|
|
320
315
|
//#endregion
|
|
321
|
-
export { Cache, InstanceCache, ResourceGroup, Scope, allResources, createCache, createResourceGroup, createScope };
|
|
322
|
-
//# sourceMappingURL=scope-
|
|
316
|
+
export { Cache, InstanceCache, ResourceGroup, Scope, allResources, createCache, createResourceGroup, createScope, defaultCacheOptions, internalCreate };
|
|
317
|
+
//# sourceMappingURL=scope-CKXL9xoi.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scope-CKXL9xoi.js","names":["factory: (...args: Args) => T","cacheTime?: number","name?: string","allResources: ResourceGroup","args: Args","options: CacheOptions<T, Args>","derivedFromCache?: {\n cache: Cache<any, any>;\n selectors: (Selector<any, any> | AnyPath)[];\n }","options","baseInstance: CacheBundle<T, Args, TCache> & TCache","defaultCacheOptions: CacheOptions<any, any>","createCache: typeof create & { defaultOptions: CacheOptions<any, any> }","defaultValue: T"],"sources":["../src/lib/instanceCache.ts","../src/core/resourceGroup.ts","../src/core/cache.ts","../src/core/scope.ts"],"sourcesContent":["import { simpleHash } from './hash';\n\nexport class InstanceCache<Args extends any[], T extends object> {\n private cache = new Map<string, { t: number; ref?: T; weakRef: WeakRef<T> }>();\n\n private interval = this.cacheTime\n ? setInterval(() => this.cleanup(), Math.max(this.cacheTime / 10, 1))\n : undefined;\n\n constructor(\n public readonly factory: (...args: Args) => T,\n public readonly cacheTime?: number,\n ) {}\n\n cleanup(): void {\n const cutoff = this.now() - (this.cacheTime ?? 0);\n\n for (const [key, entry] of this.cache.entries()) {\n if (entry.ref && entry.t <= cutoff) {\n delete entry.ref;\n }\n\n if (!entry.ref && !entry.weakRef?.deref()) {\n this.cache.delete(key);\n }\n }\n }\n\n get(...args: Args): T {\n return this.getWithKey(args, args);\n }\n\n getWithKey(args: Args, cacheKey: unknown): T {\n const key = simpleHash(cacheKey);\n let entry = this.cache.get(key);\n let value = entry?.ref ?? entry?.weakRef?.deref();\n\n if (!entry || !value) {\n value = this.factory(...args);\n entry = {\n t: this.now(),\n ref: value,\n weakRef: new WeakRef(value),\n };\n\n this.cache.set(key, entry);\n } else {\n entry.t = this.now();\n entry.ref ??= value;\n }\n\n return value;\n }\n\n values(): T[] {\n return [...this.cache.values()]\n .map((entry) => entry.ref ?? entry.weakRef?.deref())\n .filter((value): value is T => !!value);\n }\n\n stop(): void {\n if (this.interval) {\n clearInterval(this.interval);\n }\n }\n\n stats(): { count: number; withRef: number; withWeakRef: number } {\n return {\n count: this.cache.size,\n withRef: [...this.cache.values()].filter((x) => !!x.ref).length,\n withWeakRef: [...this.cache.values()].filter((x) => !!x.weakRef?.deref()).length,\n };\n }\n\n private now() {\n return performance.now();\n }\n}\n","import { autobind } from '@lib/autobind';\n\nexport interface Resource {\n invalidateAll(): void;\n clearAll(): void;\n}\n\nexport class ResourceGroup {\n private refMap = new WeakMap<Resource, WeakRef<Resource>>();\n\n private refSet = new Set<WeakRef<Resource>>();\n\n constructor(public readonly name?: string) {\n autobind(ResourceGroup);\n }\n\n add(resource: Resource): void {\n const ref = new WeakRef(resource);\n this.refMap.set(resource, ref);\n this.refSet.add(ref);\n }\n\n delete(resource: Resource): void {\n const ref = this.refMap.get(resource);\n if (ref) {\n this.refMap.delete(resource);\n this.refSet.delete(ref);\n }\n }\n\n invalidateAll(): void {\n for (const ref of this.refSet) {\n const resource = ref.deref();\n if (resource) {\n resource.invalidateAll();\n } else {\n this.refSet.delete(ref);\n }\n }\n }\n\n clearAll(): void {\n for (const ref of this.refSet) {\n const resource = ref.deref();\n if (resource) {\n resource.clearAll();\n } else {\n this.refSet.delete(ref);\n }\n }\n }\n}\n\nexport const allResources: ResourceGroup = /* @__PURE__ */ new ResourceGroup();\n\nexport function createResourceGroup(name?: string): ResourceGroup {\n return new ResourceGroup(name);\n}\n","import { autobind } from '@lib/autobind';\nimport type { CacheState, ErrorState, ValueState } from '@lib/cacheState';\nimport { calcDuration } from '@lib/calcDuration';\nimport { calculatedValue } from '@lib/calculatedValue';\nimport type { Constrain } from '@lib/constrain';\nimport { deepEqual } from '@lib/equals';\nimport { InstanceCache } from '@lib/instanceCache';\nimport { makeSelector } from '@lib/makeSelector';\nimport { type MaybePromise } from '@lib/maybePromise';\nimport type { AnyPath, Path, Value } from '@lib/path';\nimport { PromiseWithState } from '@lib/promiseWithState';\nimport type { Duration, Selector } from './commonTypes';\nimport { allResources, type ResourceGroup } from './resourceGroup';\nimport { Store, createStore, type Calculate, type StoreOptions } from './store';\n\nexport interface CacheGetOptions {\n /**\n * How to handle the cache when getting the value.\n * - `whenMissing`: Only fetch a new value if there is no cached value.\n * - `whenStale`: Fetch a new value if there is no cached value or if the cached value is stale.\n * - `force`: Always fetch a new value, regardless of the cache state.\n */\n update?: 'whenMissing' | 'whenStale' | 'force';\n\n /**\n * If set to `true`, the cache will be updated in the background.\n * This means that a stale value will be returned immediately, if available, while the new value is being fetched.\n */\n backgroundUpdate?: boolean;\n}\n\nexport interface CacheFunction<T, Args extends any[] = []> {\n (...args: Args): Promise<T> | Calculate<Promise<T>>;\n}\n\nexport interface CacheOptions<T, Args extends any[]> extends StoreOptions<Promise<T>> {\n /**\n * How long to keep the cache entry before it is considered stale.\n * If set to `undefined` or `null`, the cache entry will never be invalidated automatically.\n *\n * @example\n * ```typescript\n * createCache(fetchData, {\n * invalidateAfter: { seconds: 10 },\n * });\n * ```\n */\n invalidateAfter?: Duration | ((state: ValueState<T> | ErrorState) => Duration | null) | null;\n\n /**\n * If set, the cache will be invalidated when the window gets focused.\n * This is useful for caches that are used in a browser environment and might become stale when the user switches tabs.\n */\n invalidateOnWindowFocus?: boolean;\n\n /**\n * If set, the cached value will be cleared when the cache is invalidated.\n * Without this option, the cache will keep the last value as stale until a new value becomes available.\n */\n clearOnInvalidate?: boolean;\n\n /**\n * If set, cache entries will be cleared after approximately the specified duration.\n * This is useful for long lived pages or applications and helps to prevent memory leaks.\n * The exact time when the entry is cleared is not guaranteed, since it will be cleared during garbage collection.\n */\n clearUnusedAfter?: Duration | null;\n\n /**\n * Add the cache to the specified resource group(s).\n * This allows you to invalidate or clear multiple caches that belong to the same group.\n * All caches are always added to the `allResources` group.\n */\n resourceGroup?: ResourceGroup | ResourceGroup[];\n\n /**\n * Function to generate a custom cache key based on the provided arguments.\n * This allows you to control how cache entries are identified and reused.\n * By default, the arguments array is used as the cache key.\n *\n * @example\n * ```typescript\n * // Will use the same instance when provided with `undefined`, `{ num: 0 }`, `{ bool: false }`, etc.\n * createCache((filter?: { num?: number, bool?: boolean }) => fetchData(filter), {\n * getCacheKey: (filter?) => ({\n * num: filter?.num ?? 0,\n * bool: filter?.bool ?? false,\n * }),\n * });\n * ```\n */\n getCacheKey?: (...args: NoInfer<Args>) => unknown;\n}\n\nexport class Cache<T, Args extends any[] = []> extends Store<Promise<T>> {\n readonly state: Store<CacheState<T>> = createStore<CacheState<T>>({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n isConnected: false,\n });\n\n protected stalePromise?: Promise<T>;\n\n protected invalidationTimer?: ReturnType<typeof setTimeout>;\n\n constructor(\n getter: Calculate<Promise<T>>,\n public readonly args: Args,\n public readonly options: CacheOptions<T, Args> = {},\n public readonly derivedFromCache?: {\n cache: Cache<any, any>;\n selectors: (Selector<any, any> | AnyPath)[];\n },\n ) {\n super(getter, options, undefined);\n autobind(Cache);\n\n this.watchPromise();\n this.watchFocus();\n }\n\n get({ update = 'whenStale', backgroundUpdate = false }: CacheGetOptions = {}): Promise<T> {\n this.calculatedValue?.check();\n const promise = this.calculatedValue?.value;\n const stalePromise = this.stalePromise;\n\n if (\n (update === 'whenMissing' && !promise && !stalePromise) ||\n (update === 'whenStale' && !promise) ||\n update === 'force'\n ) {\n this.calculatedValue = calculatedValue(this, this.notify);\n this.notify();\n\n if ((!promise && !stalePromise) || !backgroundUpdate) {\n return this.calculatedValue.value;\n }\n }\n\n if (!promise || (stalePromise && backgroundUpdate)) {\n return stalePromise!;\n }\n\n return promise;\n }\n\n updateValue(value: MaybePromise<T> | ((value: T | undefined) => T)): void {\n if (value instanceof Function) {\n value = value(this.state.get().value);\n }\n this.set(PromiseWithState.resolve(value));\n }\n\n updateError(error: unknown): void {\n this.set(PromiseWithState.reject(error));\n }\n\n invalidate(recursive?: boolean): void {\n const { clearOnInvalidate } = this.options;\n\n if (clearOnInvalidate) {\n return this.clear(recursive);\n }\n\n const { status, isStale, isUpdating } = this.state.get();\n if (status !== 'pending' && !isStale && !isUpdating) {\n this.stalePromise = this.calculatedValue?.value;\n }\n\n this.state.set((state) => ({\n ...state,\n isStale: true,\n isUpdating: false,\n }));\n\n super.invalidate(recursive);\n }\n\n clear(recursive?: boolean): void {\n this.state.set({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n isConnected: false,\n });\n delete this.stalePromise;\n\n super.invalidate(recursive);\n }\n\n mapValue<S>(selector: Selector<T, S>): Cache<S, Args>;\n\n mapValue<const P extends AnyPath>(\n selector: P extends Path<T> ? P : Path<T>,\n ): Cache<Value<T, P>, Args>;\n\n mapValue(selector: Selector<any, any> | AnyPath) {\n return mapValue(this, selector);\n }\n\n protected watchPromise(): void {\n this.subscribe(\n async (promise) => {\n if (promise instanceof PromiseWithState && promise.state.status !== 'pending') {\n promise.catch(() => undefined);\n\n this.state.set((state) => ({\n ...promise.state,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n\n delete this.stalePromise;\n this.setTimers();\n return;\n }\n\n this.state.set((state) => ({\n ...state,\n isUpdating: true,\n }));\n\n this.setTimers();\n\n try {\n const value = await promise;\n\n if (promise !== this.calculatedValue?.value) {\n return;\n }\n\n this.state.set((state) => ({\n status: 'value',\n value,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n delete this.stalePromise;\n this.setTimers();\n } catch (error) {\n if (promise !== this.calculatedValue?.value) {\n return;\n }\n\n this.state.set((state) => ({\n status: 'error',\n error,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n delete this.stalePromise;\n this.setTimers();\n }\n },\n { passive: true },\n );\n }\n\n protected setTimers(): void {\n if (this.invalidationTimer) {\n clearTimeout(this.invalidationTimer);\n }\n this.invalidationTimer = undefined;\n\n const state = this.state.get();\n let { invalidateAfter } = this.options;\n const ref = new WeakRef(this);\n\n if (state.status === 'pending') {\n return;\n }\n\n if (invalidateAfter instanceof Function) {\n invalidateAfter = invalidateAfter(state);\n }\n\n if (invalidateAfter !== null && invalidateAfter !== undefined) {\n this.invalidationTimer = setTimeout(\n () => ref?.deref()?.invalidate(),\n calcDuration(invalidateAfter),\n );\n }\n }\n\n protected watchFocus(): void {\n const { invalidateOnWindowFocus } = this.options;\n\n if (\n !invalidateOnWindowFocus ||\n typeof document === 'undefined' ||\n typeof document.addEventListener === 'undefined'\n ) {\n return;\n }\n\n const ref = new WeakRef(this);\n\n const onFocus = () => {\n const that = ref?.deref();\n if (!that) {\n document.removeEventListener('visibilitychange', onFocus);\n return;\n }\n\n if (!document.hidden && !that.state.get().isConnected) {\n that.invalidate();\n }\n };\n\n document.addEventListener('visibilitychange', onFocus);\n }\n}\n\nfunction mapValue<T, S, Args extends any[]>(\n cache: Cache<T, Args>,\n _selector: Selector<T, S> | AnyPath,\n): Cache<S, Args> {\n const selector = makeSelector(_selector);\n const derivedFromCache = {\n cache: cache.derivedFromCache ? cache.derivedFromCache.cache : cache,\n selectors: cache.derivedFromCache\n ? [...cache.derivedFromCache.selectors, _selector]\n : [_selector],\n };\n\n return new Cache<S, Args>(\n async ({ use }) => {\n const value = await use(cache);\n return selector(value);\n },\n cache.args,\n {\n equals: cache.options.equals,\n },\n derivedFromCache,\n );\n}\n\nexport type CreateCacheResult<\n T,\n Args extends any[],\n TCache extends Cache<T, Args>,\n> = [] extends Args ? CacheBundle<T, Args, TCache> & TCache : CacheBundle<T, Args, TCache>;\n\nexport interface InvalidationOptions<T, Args extends any[], TCache extends Cache<T, Args>> {\n filter?: (cache: TCache) => boolean;\n}\n\nexport type CacheBundle<T, Args extends any[], TCache extends Cache<T, Args>> = {\n (...args: Args): TCache;\n mapCache<S>(selector: Selector<T, S>): CreateCacheResult<S, Args, Cache<S, Args>>;\n mapValue<const P>(\n selector: Constrain<P, Path<T>>,\n ): CreateCacheResult<Value<T, P>, Args, Cache<Value<T, P>, Args>>;\n invalidateAll: (options?: InvalidationOptions<T, Args, TCache>) => void;\n clearAll: (options?: InvalidationOptions<T, Args, TCache>) => void;\n getInstances: () => TCache[];\n};\n\nfunction create<T, Args extends any[] = []>(\n cacheFunction: CacheFunction<T, Args>,\n options?: CacheOptions<T, Args>,\n): CreateCacheResult<T, Args, Cache<T, Args>> {\n return internalCreate<T, Args, Cache<T, Args>>(\n (args, options) =>\n new Cache(\n (helpers) => {\n const result = cacheFunction.apply(helpers, args);\n\n if (result instanceof Function) {\n return result(helpers);\n }\n\n return result;\n },\n args,\n options,\n undefined,\n ),\n options,\n );\n}\n\nexport function internalCreate<T, Args extends any[], TCache extends Cache<T, Args>>(\n factory: (args: Args, options: CacheOptions<T, Args>) => TCache,\n options?: CacheOptions<T, Args>,\n): CreateCacheResult<T, Args, TCache> {\n options = { ...createCache.defaultOptions, ...options };\n const { clearUnusedAfter, resourceGroup } = options ?? {};\n\n let baseInstance: CacheBundle<T, Args, TCache> & TCache;\n\n const instanceCache = new InstanceCache<Args, TCache>(\n (...args) => factory(args, options),\n clearUnusedAfter ? calcDuration(clearUnusedAfter) : undefined,\n );\n\n function get(...args: Args) {\n const sliceAfter = args.lastIndexOf(undefined);\n if (sliceAfter !== -1) {\n args = args.slice(0, sliceAfter) as Args;\n }\n\n const cacheKey = options?.getCacheKey ? options.getCacheKey(...args) : args;\n return instanceCache.getWithKey(args, cacheKey);\n }\n\n const mapCache = (selector: any) => {\n return internalCreate<any, Args, Cache<any, Args>>((args: Args) =>\n mapValue(baseInstance(...args), selector),\n );\n };\n\n const invalidateAll = ({ filter = () => true }: InvalidationOptions<T, Args, TCache> = {}) => {\n for (const instance of instanceCache.values()) {\n if (filter(instance)) {\n instance.invalidate();\n }\n }\n };\n\n const clearAll = ({ filter = () => true }: InvalidationOptions<T, Args, TCache> = {}) => {\n for (const instance of instanceCache.values()) {\n if (filter(instance)) {\n instance.clear();\n }\n }\n };\n\n const getInstances = () => {\n return instanceCache.values();\n };\n\n baseInstance = new Proxy(\n Object.assign(() => undefined, {\n mapCache,\n invalidateAll,\n clearAll,\n getInstances,\n }),\n {\n apply(_target, _thisArg, argArray) {\n return get(...(argArray as unknown as Args));\n },\n get(target, p, receiver) {\n if (Reflect.has(target, p)) {\n return Reflect.get(target, p, receiver);\n }\n\n const baseCache = get(...([] as unknown as Args));\n return Reflect.get(baseCache, p, baseCache);\n },\n },\n ) as unknown as CacheBundle<T, Args, TCache> & TCache;\n\n const groups = Array.isArray(resourceGroup)\n ? resourceGroup\n : resourceGroup\n ? [resourceGroup]\n : [];\n\n for (const group of groups.concat(allResources)) {\n group.add(baseInstance);\n }\n\n return baseInstance;\n}\n\nexport const defaultCacheOptions: CacheOptions<any, any> = {\n invalidateOnWindowFocus: true,\n clearUnusedAfter: { days: 1 },\n retain: { milliseconds: 1 },\n equals: deepEqual,\n};\n\nexport const createCache: typeof create & { defaultOptions: CacheOptions<any, any> } =\n /* @__PURE__ */ Object.assign(create, {\n defaultOptions: defaultCacheOptions,\n });\n","import { autobind } from '@lib/autobind';\n\nexport class Scope<T> {\n constructor(public readonly defaultValue: T) {\n autobind(Scope);\n }\n}\n\nexport function createScope<T>(defaultValue: T): Scope<T> {\n return new Scope(defaultValue);\n}\n"],"mappings":";;;;;AAEA,IAAa,gBAAb,MAAiE;C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AAO,QAAQ,IAAI,WAAW,GAAG;;;CAKvC,MAAM,SAAS,MAAM,QAAQ,iBACzB,gBACA,gBACE,CAAC,iBACD;AAEN,MAAK,MAAM,SAAS,OAAO,OAAO,cAChC,OAAM,IAAI;AAGZ,QAAO;;AAGT,MAAaC,sBAA8C;CACzD,yBAAyB;CACzB,kBAAkB,EAAE,MAAM;CAC1B,QAAQ,EAAE,cAAc;CACxB,QAAQ;;AAGV,MAAaC,cACK,uBAAO,OAAO,QAAQ,EACpC,gBAAgB;;;;AC/dpB,IAAa,QAAb,MAAa,MAAS;CACpB,YAAY,AAAgBC,cAAiB;EAAjB;AAC1B,WAAS;;;AAIb,SAAgB,YAAe,cAA2B;AACxD,QAAO,IAAI,MAAM"}
|
|
@@ -241,26 +241,20 @@ function mapValue(cache, _selector) {
|
|
|
241
241
|
}, cache.args, { equals: cache.options.equals }, derivedFromCache);
|
|
242
242
|
}
|
|
243
243
|
function create(cacheFunction, options) {
|
|
244
|
-
return internalCreate(
|
|
244
|
+
return internalCreate((args, options$1) => new Cache((helpers) => {
|
|
245
|
+
const result = cacheFunction.apply(helpers, args);
|
|
246
|
+
if (result instanceof Function) return result(helpers);
|
|
247
|
+
return result;
|
|
248
|
+
}, args, options$1, void 0), options);
|
|
245
249
|
}
|
|
246
|
-
function internalCreate(
|
|
250
|
+
function internalCreate(factory, options) {
|
|
247
251
|
options = {
|
|
248
252
|
...createCache.defaultOptions,
|
|
249
253
|
...options
|
|
250
254
|
};
|
|
251
255
|
const { clearUnusedAfter, resourceGroup } = options ?? {};
|
|
252
256
|
let baseInstance;
|
|
253
|
-
const instanceCache = new InstanceCache((...args) =>
|
|
254
|
-
if (Array.isArray(source)) {
|
|
255
|
-
const [cache, selector] = source;
|
|
256
|
-
return mapValue(cache(...args), selector);
|
|
257
|
-
}
|
|
258
|
-
return new Cache((helpers) => {
|
|
259
|
-
const result = source.apply(helpers, args);
|
|
260
|
-
if (result instanceof Function) return result(helpers);
|
|
261
|
-
return result;
|
|
262
|
-
}, args, options, void 0);
|
|
263
|
-
}, clearUnusedAfter ? require_store.calcDuration(clearUnusedAfter) : void 0);
|
|
257
|
+
const instanceCache = new InstanceCache((...args) => factory(args, options), clearUnusedAfter ? require_store.calcDuration(clearUnusedAfter) : void 0);
|
|
264
258
|
function get(...args) {
|
|
265
259
|
const sliceAfter = args.lastIndexOf(void 0);
|
|
266
260
|
if (sliceAfter !== -1) args = args.slice(0, sliceAfter);
|
|
@@ -268,7 +262,7 @@ function internalCreate(source, options) {
|
|
|
268
262
|
return instanceCache.getWithKey(args, cacheKey);
|
|
269
263
|
}
|
|
270
264
|
const mapCache = (selector) => {
|
|
271
|
-
return internalCreate(
|
|
265
|
+
return internalCreate((args) => mapValue(baseInstance(...args), selector));
|
|
272
266
|
};
|
|
273
267
|
const invalidateAll = ({ filter = () => true } = {}) => {
|
|
274
268
|
for (const instance of instanceCache.values()) if (filter(instance)) instance.invalidate();
|
|
@@ -298,12 +292,13 @@ function internalCreate(source, options) {
|
|
|
298
292
|
for (const group of groups.concat(allResources)) group.add(baseInstance);
|
|
299
293
|
return baseInstance;
|
|
300
294
|
}
|
|
301
|
-
const
|
|
295
|
+
const defaultCacheOptions = {
|
|
302
296
|
invalidateOnWindowFocus: true,
|
|
303
297
|
clearUnusedAfter: { days: 1 },
|
|
304
298
|
retain: { milliseconds: 1 },
|
|
305
299
|
equals: require_propAccess.deepEqual
|
|
306
|
-
}
|
|
300
|
+
};
|
|
301
|
+
const createCache = /* @__PURE__ */ Object.assign(create, { defaultOptions: defaultCacheOptions });
|
|
307
302
|
|
|
308
303
|
//#endregion
|
|
309
304
|
//#region src/core/scope.ts
|
|
@@ -366,4 +361,16 @@ Object.defineProperty(exports, 'createScope', {
|
|
|
366
361
|
return createScope;
|
|
367
362
|
}
|
|
368
363
|
});
|
|
369
|
-
|
|
364
|
+
Object.defineProperty(exports, 'defaultCacheOptions', {
|
|
365
|
+
enumerable: true,
|
|
366
|
+
get: function () {
|
|
367
|
+
return defaultCacheOptions;
|
|
368
|
+
}
|
|
369
|
+
});
|
|
370
|
+
Object.defineProperty(exports, 'internalCreate', {
|
|
371
|
+
enumerable: true,
|
|
372
|
+
get: function () {
|
|
373
|
+
return internalCreate;
|
|
374
|
+
}
|
|
375
|
+
});
|
|
376
|
+
//# sourceMappingURL=scope-CoDFmhxK.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scope-CoDFmhxK.cjs","names":["factory: (...args: Args) => T","cacheTime?: number","simpleHash","name?: string","allResources: ResourceGroup","Store","args: Args","options: CacheOptions<T, Args>","derivedFromCache?: {\n cache: Cache<any, any>;\n selectors: (Selector<any, any> | AnyPath)[];\n }","createStore","calculatedValue","PromiseWithState","calcDuration","makeSelector","options","baseInstance: CacheBundle<T, Args, TCache> & TCache","defaultCacheOptions: CacheOptions<any, any>","deepEqual","createCache: typeof create & { defaultOptions: CacheOptions<any, any> }","defaultValue: T"],"sources":["../src/lib/instanceCache.ts","../src/core/resourceGroup.ts","../src/core/cache.ts","../src/core/scope.ts"],"sourcesContent":["import { simpleHash } from './hash';\n\nexport class InstanceCache<Args extends any[], T extends object> {\n private cache = new Map<string, { t: number; ref?: T; weakRef: WeakRef<T> }>();\n\n private interval = this.cacheTime\n ? setInterval(() => this.cleanup(), Math.max(this.cacheTime / 10, 1))\n : undefined;\n\n constructor(\n public readonly factory: (...args: Args) => T,\n public readonly cacheTime?: number,\n ) {}\n\n cleanup(): void {\n const cutoff = this.now() - (this.cacheTime ?? 0);\n\n for (const [key, entry] of this.cache.entries()) {\n if (entry.ref && entry.t <= cutoff) {\n delete entry.ref;\n }\n\n if (!entry.ref && !entry.weakRef?.deref()) {\n this.cache.delete(key);\n }\n }\n }\n\n get(...args: Args): T {\n return this.getWithKey(args, args);\n }\n\n getWithKey(args: Args, cacheKey: unknown): T {\n const key = simpleHash(cacheKey);\n let entry = this.cache.get(key);\n let value = entry?.ref ?? entry?.weakRef?.deref();\n\n if (!entry || !value) {\n value = this.factory(...args);\n entry = {\n t: this.now(),\n ref: value,\n weakRef: new WeakRef(value),\n };\n\n this.cache.set(key, entry);\n } else {\n entry.t = this.now();\n entry.ref ??= value;\n }\n\n return value;\n }\n\n values(): T[] {\n return [...this.cache.values()]\n .map((entry) => entry.ref ?? entry.weakRef?.deref())\n .filter((value): value is T => !!value);\n }\n\n stop(): void {\n if (this.interval) {\n clearInterval(this.interval);\n }\n }\n\n stats(): { count: number; withRef: number; withWeakRef: number } {\n return {\n count: this.cache.size,\n withRef: [...this.cache.values()].filter((x) => !!x.ref).length,\n withWeakRef: [...this.cache.values()].filter((x) => !!x.weakRef?.deref()).length,\n };\n }\n\n private now() {\n return performance.now();\n }\n}\n","import { autobind } from '@lib/autobind';\n\nexport interface Resource {\n invalidateAll(): void;\n clearAll(): void;\n}\n\nexport class ResourceGroup {\n private refMap = new WeakMap<Resource, WeakRef<Resource>>();\n\n private refSet = new Set<WeakRef<Resource>>();\n\n constructor(public readonly name?: string) {\n autobind(ResourceGroup);\n }\n\n add(resource: Resource): void {\n const ref = new WeakRef(resource);\n this.refMap.set(resource, ref);\n this.refSet.add(ref);\n }\n\n delete(resource: Resource): void {\n const ref = this.refMap.get(resource);\n if (ref) {\n this.refMap.delete(resource);\n this.refSet.delete(ref);\n }\n }\n\n invalidateAll(): void {\n for (const ref of this.refSet) {\n const resource = ref.deref();\n if (resource) {\n resource.invalidateAll();\n } else {\n this.refSet.delete(ref);\n }\n }\n }\n\n clearAll(): void {\n for (const ref of this.refSet) {\n const resource = ref.deref();\n if (resource) {\n resource.clearAll();\n } else {\n this.refSet.delete(ref);\n }\n }\n }\n}\n\nexport const allResources: ResourceGroup = /* @__PURE__ */ new ResourceGroup();\n\nexport function createResourceGroup(name?: string): ResourceGroup {\n return new ResourceGroup(name);\n}\n","import { autobind } from '@lib/autobind';\nimport type { CacheState, ErrorState, ValueState } from '@lib/cacheState';\nimport { calcDuration } from '@lib/calcDuration';\nimport { calculatedValue } from '@lib/calculatedValue';\nimport type { Constrain } from '@lib/constrain';\nimport { deepEqual } from '@lib/equals';\nimport { InstanceCache } from '@lib/instanceCache';\nimport { makeSelector } from '@lib/makeSelector';\nimport { type MaybePromise } from '@lib/maybePromise';\nimport type { AnyPath, Path, Value } from '@lib/path';\nimport { PromiseWithState } from '@lib/promiseWithState';\nimport type { Duration, Selector } from './commonTypes';\nimport { allResources, type ResourceGroup } from './resourceGroup';\nimport { Store, createStore, type Calculate, type StoreOptions } from './store';\n\nexport interface CacheGetOptions {\n /**\n * How to handle the cache when getting the value.\n * - `whenMissing`: Only fetch a new value if there is no cached value.\n * - `whenStale`: Fetch a new value if there is no cached value or if the cached value is stale.\n * - `force`: Always fetch a new value, regardless of the cache state.\n */\n update?: 'whenMissing' | 'whenStale' | 'force';\n\n /**\n * If set to `true`, the cache will be updated in the background.\n * This means that a stale value will be returned immediately, if available, while the new value is being fetched.\n */\n backgroundUpdate?: boolean;\n}\n\nexport interface CacheFunction<T, Args extends any[] = []> {\n (...args: Args): Promise<T> | Calculate<Promise<T>>;\n}\n\nexport interface CacheOptions<T, Args extends any[]> extends StoreOptions<Promise<T>> {\n /**\n * How long to keep the cache entry before it is considered stale.\n * If set to `undefined` or `null`, the cache entry will never be invalidated automatically.\n *\n * @example\n * ```typescript\n * createCache(fetchData, {\n * invalidateAfter: { seconds: 10 },\n * });\n * ```\n */\n invalidateAfter?: Duration | ((state: ValueState<T> | ErrorState) => Duration | null) | null;\n\n /**\n * If set, the cache will be invalidated when the window gets focused.\n * This is useful for caches that are used in a browser environment and might become stale when the user switches tabs.\n */\n invalidateOnWindowFocus?: boolean;\n\n /**\n * If set, the cached value will be cleared when the cache is invalidated.\n * Without this option, the cache will keep the last value as stale until a new value becomes available.\n */\n clearOnInvalidate?: boolean;\n\n /**\n * If set, cache entries will be cleared after approximately the specified duration.\n * This is useful for long lived pages or applications and helps to prevent memory leaks.\n * The exact time when the entry is cleared is not guaranteed, since it will be cleared during garbage collection.\n */\n clearUnusedAfter?: Duration | null;\n\n /**\n * Add the cache to the specified resource group(s).\n * This allows you to invalidate or clear multiple caches that belong to the same group.\n * All caches are always added to the `allResources` group.\n */\n resourceGroup?: ResourceGroup | ResourceGroup[];\n\n /**\n * Function to generate a custom cache key based on the provided arguments.\n * This allows you to control how cache entries are identified and reused.\n * By default, the arguments array is used as the cache key.\n *\n * @example\n * ```typescript\n * // Will use the same instance when provided with `undefined`, `{ num: 0 }`, `{ bool: false }`, etc.\n * createCache((filter?: { num?: number, bool?: boolean }) => fetchData(filter), {\n * getCacheKey: (filter?) => ({\n * num: filter?.num ?? 0,\n * bool: filter?.bool ?? false,\n * }),\n * });\n * ```\n */\n getCacheKey?: (...args: NoInfer<Args>) => unknown;\n}\n\nexport class Cache<T, Args extends any[] = []> extends Store<Promise<T>> {\n readonly state: Store<CacheState<T>> = createStore<CacheState<T>>({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n isConnected: false,\n });\n\n protected stalePromise?: Promise<T>;\n\n protected invalidationTimer?: ReturnType<typeof setTimeout>;\n\n constructor(\n getter: Calculate<Promise<T>>,\n public readonly args: Args,\n public readonly options: CacheOptions<T, Args> = {},\n public readonly derivedFromCache?: {\n cache: Cache<any, any>;\n selectors: (Selector<any, any> | AnyPath)[];\n },\n ) {\n super(getter, options, undefined);\n autobind(Cache);\n\n this.watchPromise();\n this.watchFocus();\n }\n\n get({ update = 'whenStale', backgroundUpdate = false }: CacheGetOptions = {}): Promise<T> {\n this.calculatedValue?.check();\n const promise = this.calculatedValue?.value;\n const stalePromise = this.stalePromise;\n\n if (\n (update === 'whenMissing' && !promise && !stalePromise) ||\n (update === 'whenStale' && !promise) ||\n update === 'force'\n ) {\n this.calculatedValue = calculatedValue(this, this.notify);\n this.notify();\n\n if ((!promise && !stalePromise) || !backgroundUpdate) {\n return this.calculatedValue.value;\n }\n }\n\n if (!promise || (stalePromise && backgroundUpdate)) {\n return stalePromise!;\n }\n\n return promise;\n }\n\n updateValue(value: MaybePromise<T> | ((value: T | undefined) => T)): void {\n if (value instanceof Function) {\n value = value(this.state.get().value);\n }\n this.set(PromiseWithState.resolve(value));\n }\n\n updateError(error: unknown): void {\n this.set(PromiseWithState.reject(error));\n }\n\n invalidate(recursive?: boolean): void {\n const { clearOnInvalidate } = this.options;\n\n if (clearOnInvalidate) {\n return this.clear(recursive);\n }\n\n const { status, isStale, isUpdating } = this.state.get();\n if (status !== 'pending' && !isStale && !isUpdating) {\n this.stalePromise = this.calculatedValue?.value;\n }\n\n this.state.set((state) => ({\n ...state,\n isStale: true,\n isUpdating: false,\n }));\n\n super.invalidate(recursive);\n }\n\n clear(recursive?: boolean): void {\n this.state.set({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n isConnected: false,\n });\n delete this.stalePromise;\n\n super.invalidate(recursive);\n }\n\n mapValue<S>(selector: Selector<T, S>): Cache<S, Args>;\n\n mapValue<const P extends AnyPath>(\n selector: P extends Path<T> ? P : Path<T>,\n ): Cache<Value<T, P>, Args>;\n\n mapValue(selector: Selector<any, any> | AnyPath) {\n return mapValue(this, selector);\n }\n\n protected watchPromise(): void {\n this.subscribe(\n async (promise) => {\n if (promise instanceof PromiseWithState && promise.state.status !== 'pending') {\n promise.catch(() => undefined);\n\n this.state.set((state) => ({\n ...promise.state,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n\n delete this.stalePromise;\n this.setTimers();\n return;\n }\n\n this.state.set((state) => ({\n ...state,\n isUpdating: true,\n }));\n\n this.setTimers();\n\n try {\n const value = await promise;\n\n if (promise !== this.calculatedValue?.value) {\n return;\n }\n\n this.state.set((state) => ({\n status: 'value',\n value,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n delete this.stalePromise;\n this.setTimers();\n } catch (error) {\n if (promise !== this.calculatedValue?.value) {\n return;\n }\n\n this.state.set((state) => ({\n status: 'error',\n error,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n delete this.stalePromise;\n this.setTimers();\n }\n },\n { passive: true },\n );\n }\n\n protected setTimers(): void {\n if (this.invalidationTimer) {\n clearTimeout(this.invalidationTimer);\n }\n this.invalidationTimer = undefined;\n\n const state = this.state.get();\n let { invalidateAfter } = this.options;\n const ref = new WeakRef(this);\n\n if (state.status === 'pending') {\n return;\n }\n\n if (invalidateAfter instanceof Function) {\n invalidateAfter = invalidateAfter(state);\n }\n\n if (invalidateAfter !== null && invalidateAfter !== undefined) {\n this.invalidationTimer = setTimeout(\n () => ref?.deref()?.invalidate(),\n calcDuration(invalidateAfter),\n );\n }\n }\n\n protected watchFocus(): void {\n const { invalidateOnWindowFocus } = this.options;\n\n if (\n !invalidateOnWindowFocus ||\n typeof document === 'undefined' ||\n typeof document.addEventListener === 'undefined'\n ) {\n return;\n }\n\n const ref = new WeakRef(this);\n\n const onFocus = () => {\n const that = ref?.deref();\n if (!that) {\n document.removeEventListener('visibilitychange', onFocus);\n return;\n }\n\n if (!document.hidden && !that.state.get().isConnected) {\n that.invalidate();\n }\n };\n\n document.addEventListener('visibilitychange', onFocus);\n }\n}\n\nfunction mapValue<T, S, Args extends any[]>(\n cache: Cache<T, Args>,\n _selector: Selector<T, S> | AnyPath,\n): Cache<S, Args> {\n const selector = makeSelector(_selector);\n const derivedFromCache = {\n cache: cache.derivedFromCache ? cache.derivedFromCache.cache : cache,\n selectors: cache.derivedFromCache\n ? [...cache.derivedFromCache.selectors, _selector]\n : [_selector],\n };\n\n return new Cache<S, Args>(\n async ({ use }) => {\n const value = await use(cache);\n return selector(value);\n },\n cache.args,\n {\n equals: cache.options.equals,\n },\n derivedFromCache,\n );\n}\n\nexport type CreateCacheResult<\n T,\n Args extends any[],\n TCache extends Cache<T, Args>,\n> = [] extends Args ? CacheBundle<T, Args, TCache> & TCache : CacheBundle<T, Args, TCache>;\n\nexport interface InvalidationOptions<T, Args extends any[], TCache extends Cache<T, Args>> {\n filter?: (cache: TCache) => boolean;\n}\n\nexport type CacheBundle<T, Args extends any[], TCache extends Cache<T, Args>> = {\n (...args: Args): TCache;\n mapCache<S>(selector: Selector<T, S>): CreateCacheResult<S, Args, Cache<S, Args>>;\n mapValue<const P>(\n selector: Constrain<P, Path<T>>,\n ): CreateCacheResult<Value<T, P>, Args, Cache<Value<T, P>, Args>>;\n invalidateAll: (options?: InvalidationOptions<T, Args, TCache>) => void;\n clearAll: (options?: InvalidationOptions<T, Args, TCache>) => void;\n getInstances: () => TCache[];\n};\n\nfunction create<T, Args extends any[] = []>(\n cacheFunction: CacheFunction<T, Args>,\n options?: CacheOptions<T, Args>,\n): CreateCacheResult<T, Args, Cache<T, Args>> {\n return internalCreate<T, Args, Cache<T, Args>>(\n (args, options) =>\n new Cache(\n (helpers) => {\n const result = cacheFunction.apply(helpers, args);\n\n if (result instanceof Function) {\n return result(helpers);\n }\n\n return result;\n },\n args,\n options,\n undefined,\n ),\n options,\n );\n}\n\nexport function internalCreate<T, Args extends any[], TCache extends Cache<T, Args>>(\n factory: (args: Args, options: CacheOptions<T, Args>) => TCache,\n options?: CacheOptions<T, Args>,\n): CreateCacheResult<T, Args, TCache> {\n options = { ...createCache.defaultOptions, ...options };\n const { clearUnusedAfter, resourceGroup } = options ?? {};\n\n let baseInstance: CacheBundle<T, Args, TCache> & TCache;\n\n const instanceCache = new InstanceCache<Args, TCache>(\n (...args) => factory(args, options),\n clearUnusedAfter ? calcDuration(clearUnusedAfter) : undefined,\n );\n\n function get(...args: Args) {\n const sliceAfter = args.lastIndexOf(undefined);\n if (sliceAfter !== -1) {\n args = args.slice(0, sliceAfter) as Args;\n }\n\n const cacheKey = options?.getCacheKey ? options.getCacheKey(...args) : args;\n return instanceCache.getWithKey(args, cacheKey);\n }\n\n const mapCache = (selector: any) => {\n return internalCreate<any, Args, Cache<any, Args>>((args: Args) =>\n mapValue(baseInstance(...args), selector),\n );\n };\n\n const invalidateAll = ({ filter = () => true }: InvalidationOptions<T, Args, TCache> = {}) => {\n for (const instance of instanceCache.values()) {\n if (filter(instance)) {\n instance.invalidate();\n }\n }\n };\n\n const clearAll = ({ filter = () => true }: InvalidationOptions<T, Args, TCache> = {}) => {\n for (const instance of instanceCache.values()) {\n if (filter(instance)) {\n instance.clear();\n }\n }\n };\n\n const getInstances = () => {\n return instanceCache.values();\n };\n\n baseInstance = new Proxy(\n Object.assign(() => undefined, {\n mapCache,\n invalidateAll,\n clearAll,\n getInstances,\n }),\n {\n apply(_target, _thisArg, argArray) {\n return get(...(argArray as unknown as Args));\n },\n get(target, p, receiver) {\n if (Reflect.has(target, p)) {\n return Reflect.get(target, p, receiver);\n }\n\n const baseCache = get(...([] as unknown as Args));\n return Reflect.get(baseCache, p, baseCache);\n },\n },\n ) as unknown as CacheBundle<T, Args, TCache> & TCache;\n\n const groups = Array.isArray(resourceGroup)\n ? resourceGroup\n : resourceGroup\n ? [resourceGroup]\n : [];\n\n for (const group of groups.concat(allResources)) {\n group.add(baseInstance);\n }\n\n return baseInstance;\n}\n\nexport const defaultCacheOptions: CacheOptions<any, any> = {\n invalidateOnWindowFocus: true,\n clearUnusedAfter: { days: 1 },\n retain: { milliseconds: 1 },\n equals: deepEqual,\n};\n\nexport const createCache: typeof create & { defaultOptions: CacheOptions<any, any> } =\n /* @__PURE__ */ Object.assign(create, {\n defaultOptions: defaultCacheOptions,\n });\n","import { autobind } from '@lib/autobind';\n\nexport class Scope<T> {\n constructor(public readonly defaultValue: T) {\n autobind(Scope);\n }\n}\n\nexport function createScope<T>(defaultValue: T): Scope<T> {\n return new Scope(defaultValue);\n}\n"],"mappings":";;;;;AAEA,IAAa,gBAAb,MAAiE;CAO/D,YACE,AAAgBA,SAChB,AAAgBC,WAChB;EAFgB;EACA;+BARF,IAAI;kBAED,KAAK,YACpB,kBAAkB,KAAK,WAAW,KAAK,IAAI,KAAK,YAAY,IAAI,MAChE;;CAOJ,UAAgB;EACd,MAAM,SAAS,KAAK,SAAS,KAAK,aAAa;AAE/C,OAAK,MAAM,CAAC,KAAK,UAAU,KAAK,MAAM,WAAW;AAC/C,OAAI,MAAM,OAAO,MAAM,KAAK,OAC1B,QAAO,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C,cACK,uBAAO,OAAO,QAAQ,EACpC,gBAAgB;;;;AC/dpB,IAAa,QAAb,MAAa,MAAS;CACpB,YAAY,AAAgBC,cAAiB;EAAjB;AAC1B,yBAAS;;;AAIb,SAAgB,YAAe,cAA2B;AACxD,QAAO,IAAI,MAAM"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Cache, CacheState, Scope } from "./scope-
|
|
1
|
+
import { Cache, CacheState, Scope } from "./scope-6B7-8lwa.cjs";
|
|
2
2
|
import { Constrain, Path, Selector, Store, SubscribeOptions, Update, Value } from "./store-BEsiS8y7.cjs";
|
|
3
3
|
import { Context, ReactNode } from "react";
|
|
4
4
|
|
|
@@ -104,4 +104,4 @@ declare const storeMethods: {
|
|
|
104
104
|
};
|
|
105
105
|
//#endregion
|
|
106
106
|
export { ScopeProps, ScopeProvider, UseCacheArray, UseCacheValue, UseStoreOptions, cacheMethods, scopeMethods, storeMethods, useCache, useScope, useStore };
|
|
107
|
-
//# sourceMappingURL=storeMethods-
|
|
107
|
+
//# sourceMappingURL=storeMethods-Bg8nMBrf.d.cts.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Cache, CacheState, Scope } from "./scope-
|
|
1
|
+
import { Cache, CacheState, Scope } from "./scope-BbUXgNW_.js";
|
|
2
2
|
import { Constrain, Path, Selector, Store, SubscribeOptions, Update, Value } from "./store-DKaeE840.js";
|
|
3
3
|
import { Context, ReactNode } from "react";
|
|
4
4
|
|
|
@@ -104,4 +104,4 @@ declare const storeMethods: {
|
|
|
104
104
|
};
|
|
105
105
|
//#endregion
|
|
106
106
|
export { ScopeProps, ScopeProvider, UseCacheArray, UseCacheValue, UseStoreOptions, cacheMethods, scopeMethods, storeMethods, useCache, useScope, useStore };
|
|
107
|
-
//# sourceMappingURL=storeMethods-
|
|
107
|
+
//# sourceMappingURL=storeMethods-DWKSveN0.d.ts.map
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"scope-6P87zGw6.js","names":["factory: (...args: Args) => T","cacheTime?: number","name?: string","allResources: ResourceGroup","args: Args","options: CacheOptions<T, Args>","derivedFromCache?: {\n cache: Cache<any, any>;\n selectors: (Selector<any, any> | AnyPath)[];\n }","baseInstance: CacheBundle<T, Args> & Cache<T, Args>","createCache: typeof create & { defaultOptions: CacheOptions<any, any> }","defaultValue: T"],"sources":["../src/lib/instanceCache.ts","../src/core/resourceGroup.ts","../src/core/cache.ts","../src/core/scope.ts"],"sourcesContent":["import { simpleHash } from './hash';\n\nexport class InstanceCache<Args extends any[], T extends object> {\n private cache = new Map<string, { t: number; ref?: T; weakRef: WeakRef<T> }>();\n\n private interval = this.cacheTime\n ? setInterval(() => this.cleanup(), Math.max(this.cacheTime / 10, 1))\n : undefined;\n\n constructor(\n public readonly factory: (...args: Args) => T,\n public readonly cacheTime?: number,\n ) {}\n\n cleanup(): void {\n const cutoff = this.now() - (this.cacheTime ?? 0);\n\n for (const [key, entry] of this.cache.entries()) {\n if (entry.ref && entry.t <= cutoff) {\n delete entry.ref;\n }\n\n if (!entry.ref && !entry.weakRef?.deref()) {\n this.cache.delete(key);\n }\n }\n }\n\n get(...args: Args): T {\n return this.getWithKey(args, args);\n }\n\n getWithKey(args: Args, cacheKey: unknown): T {\n const key = simpleHash(cacheKey);\n let entry = this.cache.get(key);\n let value = entry?.ref ?? entry?.weakRef?.deref();\n\n if (!entry || !value) {\n value = this.factory(...args);\n entry = {\n t: this.now(),\n ref: value,\n weakRef: new WeakRef(value),\n };\n\n this.cache.set(key, entry);\n } else {\n entry.t = this.now();\n entry.ref ??= value;\n }\n\n return value;\n }\n\n values(): T[] {\n return [...this.cache.values()]\n .map((entry) => entry.ref ?? entry.weakRef?.deref())\n .filter((value): value is T => !!value);\n }\n\n stop(): void {\n if (this.interval) {\n clearInterval(this.interval);\n }\n }\n\n stats(): { count: number; withRef: number; withWeakRef: number } {\n return {\n count: this.cache.size,\n withRef: [...this.cache.values()].filter((x) => !!x.ref).length,\n withWeakRef: [...this.cache.values()].filter((x) => !!x.weakRef?.deref()).length,\n };\n }\n\n private now() {\n return performance.now();\n }\n}\n","import { autobind } from '@lib/autobind';\n\nexport interface Resource {\n invalidateAll(): void;\n clearAll(): void;\n}\n\nexport class ResourceGroup {\n private refMap = new WeakMap<Resource, WeakRef<Resource>>();\n\n private refSet = new Set<WeakRef<Resource>>();\n\n constructor(public readonly name?: string) {\n autobind(ResourceGroup);\n }\n\n add(resource: Resource): void {\n const ref = new WeakRef(resource);\n this.refMap.set(resource, ref);\n this.refSet.add(ref);\n }\n\n delete(resource: Resource): void {\n const ref = this.refMap.get(resource);\n if (ref) {\n this.refMap.delete(resource);\n this.refSet.delete(ref);\n }\n }\n\n invalidateAll(): void {\n for (const ref of this.refSet) {\n const resource = ref.deref();\n if (resource) {\n resource.invalidateAll();\n } else {\n this.refSet.delete(ref);\n }\n }\n }\n\n clearAll(): void {\n for (const ref of this.refSet) {\n const resource = ref.deref();\n if (resource) {\n resource.clearAll();\n } else {\n this.refSet.delete(ref);\n }\n }\n }\n}\n\nexport const allResources: ResourceGroup = /* @__PURE__ */ new ResourceGroup();\n\nexport function createResourceGroup(name?: string): ResourceGroup {\n return new ResourceGroup(name);\n}\n","import { autobind } from '@lib/autobind';\nimport type { CacheState, ErrorState, ValueState } from '@lib/cacheState';\nimport { calcDuration } from '@lib/calcDuration';\nimport { calculatedValue } from '@lib/calculatedValue';\nimport type { Constrain } from '@lib/constrain';\nimport { deepEqual } from '@lib/equals';\nimport { InstanceCache } from '@lib/instanceCache';\nimport { makeSelector } from '@lib/makeSelector';\nimport { type MaybePromise } from '@lib/maybePromise';\nimport type { AnyPath, Path, Value } from '@lib/path';\nimport { PromiseWithState } from '@lib/promiseWithState';\nimport type { Duration, Selector } from './commonTypes';\nimport { allResources, type ResourceGroup } from './resourceGroup';\nimport { Store, createStore, type Calculate, type StoreOptions } from './store';\n\nexport interface CacheGetOptions {\n /**\n * How to handle the cache when getting the value.\n * - `whenMissing`: Only fetch a new value if there is no cached value.\n * - `whenStale`: Fetch a new value if there is no cached value or if the cached value is stale.\n * - `force`: Always fetch a new value, regardless of the cache state.\n */\n update?: 'whenMissing' | 'whenStale' | 'force';\n\n /**\n * If set to `true`, the cache will be updated in the background.\n * This means that a stale value will be returned immediately, if available, while the new value is being fetched.\n */\n backgroundUpdate?: boolean;\n}\n\nexport interface CacheFunction<T, Args extends any[] = []> {\n (...args: Args): Promise<T> | Calculate<Promise<T>>;\n}\n\nexport interface CacheOptions<T, Args extends any[]> extends StoreOptions<Promise<T>> {\n /**\n * How long to keep the cache entry before it is considered stale.\n * If set to `undefined` or `null`, the cache entry will never be invalidated automatically.\n *\n * @example\n * ```typescript\n * createCache(fetchData, {\n * invalidateAfter: { seconds: 10 },\n * });\n * ```\n */\n invalidateAfter?: Duration | ((state: ValueState<T> | ErrorState) => Duration | null) | null;\n\n /**\n * If set, the cache will be invalidated when the window gets focused.\n * This is useful for caches that are used in a browser environment and might become stale when the user switches tabs.\n */\n invalidateOnWindowFocus?: boolean;\n\n /**\n * If set, the cached value will be cleared when the cache is invalidated.\n * Without this option, the cache will keep the last value as stale until a new value becomes available.\n */\n clearOnInvalidate?: boolean;\n\n /**\n * If set, cache entries will be cleared after approximately the specified duration.\n * This is useful for long lived pages or applications and helps to prevent memory leaks.\n * The exact time when the entry is cleared is not guaranteed, since it will be cleared during garbage collection.\n */\n clearUnusedAfter?: Duration | null;\n\n /**\n * Add the cache to the specified resource group(s).\n * This allows you to invalidate or clear multiple caches that belong to the same group.\n * All caches are always added to the `allResources` group.\n */\n resourceGroup?: ResourceGroup | ResourceGroup[];\n\n /**\n * Function to generate a custom cache key based on the provided arguments.\n * This allows you to control how cache entries are identified and reused.\n * By default, the arguments array is used as the cache key.\n *\n * @example\n * ```typescript\n * // Will use the same instance when provided with `undefined`, `{ num: 0 }`, `{ bool: false }`, etc.\n * createCache((filter?: { num?: number, bool?: boolean }) => fetchData(filter), {\n * getCacheKey: (filter?) => ({\n * num: filter?.num ?? 0,\n * bool: filter?.bool ?? false,\n * }),\n * });\n * ```\n */\n getCacheKey?: (...args: NoInfer<Args>) => unknown;\n}\n\nexport class Cache<T, Args extends any[] = []> extends Store<Promise<T>> {\n readonly state: Store<CacheState<T>> = createStore<CacheState<T>>({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n isConnected: false,\n });\n\n protected stalePromise?: Promise<T>;\n\n protected invalidationTimer?: ReturnType<typeof setTimeout>;\n\n constructor(\n getter: Calculate<Promise<T>>,\n public readonly args: Args,\n public readonly options: CacheOptions<T, Args> = {},\n public readonly derivedFromCache?: {\n cache: Cache<any, any>;\n selectors: (Selector<any, any> | AnyPath)[];\n },\n ) {\n super(getter, options, undefined);\n autobind(Cache);\n\n this.watchPromise();\n this.watchFocus();\n }\n\n get({ update = 'whenStale', backgroundUpdate = false }: CacheGetOptions = {}): Promise<T> {\n this.calculatedValue?.check();\n const promise = this.calculatedValue?.value;\n const stalePromise = this.stalePromise;\n\n if (\n (update === 'whenMissing' && !promise && !stalePromise) ||\n (update === 'whenStale' && !promise) ||\n update === 'force'\n ) {\n this.calculatedValue = calculatedValue(this, this.notify);\n this.notify();\n\n if ((!promise && !stalePromise) || !backgroundUpdate) {\n return this.calculatedValue.value;\n }\n }\n\n if (!promise || (stalePromise && backgroundUpdate)) {\n return stalePromise!;\n }\n\n return promise;\n }\n\n updateValue(value: MaybePromise<T> | ((value: T | undefined) => T)): void {\n if (value instanceof Function) {\n value = value(this.state.get().value);\n }\n this.set(PromiseWithState.resolve(value));\n }\n\n updateError(error: unknown): void {\n this.set(PromiseWithState.reject(error));\n }\n\n invalidate(recursive?: boolean): void {\n const { clearOnInvalidate } = this.options;\n\n if (clearOnInvalidate) {\n return this.clear(recursive);\n }\n\n const { status, isStale, isUpdating } = this.state.get();\n if (status !== 'pending' && !isStale && !isUpdating) {\n this.stalePromise = this.calculatedValue?.value;\n }\n\n this.state.set((state) => ({\n ...state,\n isStale: true,\n isUpdating: false,\n }));\n\n super.invalidate(recursive);\n }\n\n clear(recursive?: boolean): void {\n this.state.set({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n isConnected: false,\n });\n delete this.stalePromise;\n\n super.invalidate(recursive);\n }\n\n mapValue<S>(selector: Selector<T, S>): Cache<S, Args>;\n\n mapValue<const P extends AnyPath>(\n selector: P extends Path<T> ? P : Path<T>,\n ): Cache<Value<T, P>, Args>;\n\n mapValue(selector: Selector<any, any> | AnyPath) {\n return mapValue(this, selector);\n }\n\n protected watchPromise(): void {\n this.subscribe(\n async (promise) => {\n if (promise instanceof PromiseWithState && promise.state.status !== 'pending') {\n promise.catch(() => undefined);\n\n this.state.set((state) => ({\n ...promise.state,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n\n delete this.stalePromise;\n this.setTimers();\n return;\n }\n\n this.state.set((state) => ({\n ...state,\n isUpdating: true,\n }));\n\n this.setTimers();\n\n try {\n const value = await promise;\n\n if (promise !== this.calculatedValue?.value) {\n return;\n }\n\n this.state.set((state) => ({\n status: 'value',\n value,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n delete this.stalePromise;\n this.setTimers();\n } catch (error) {\n if (promise !== this.calculatedValue?.value) {\n return;\n }\n\n this.state.set((state) => ({\n status: 'error',\n error,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n delete this.stalePromise;\n this.setTimers();\n }\n },\n { passive: true },\n );\n }\n\n protected setTimers(): void {\n if (this.invalidationTimer) {\n clearTimeout(this.invalidationTimer);\n }\n this.invalidationTimer = undefined;\n\n const state = this.state.get();\n let { invalidateAfter } = this.options;\n const ref = new WeakRef(this);\n\n if (state.status === 'pending') {\n return;\n }\n\n if (invalidateAfter instanceof Function) {\n invalidateAfter = invalidateAfter(state);\n }\n\n if (invalidateAfter !== null && invalidateAfter !== undefined) {\n this.invalidationTimer = setTimeout(\n () => ref?.deref()?.invalidate(),\n calcDuration(invalidateAfter),\n );\n }\n }\n\n protected watchFocus(): void {\n const { invalidateOnWindowFocus } = this.options;\n\n if (\n !invalidateOnWindowFocus ||\n typeof document === 'undefined' ||\n typeof document.addEventListener === 'undefined'\n ) {\n return;\n }\n\n const ref = new WeakRef(this);\n\n const onFocus = () => {\n const that = ref?.deref();\n if (!that) {\n document.removeEventListener('visibilitychange', onFocus);\n return;\n }\n\n if (!document.hidden && !that.state.get().isConnected) {\n that.invalidate();\n }\n };\n\n document.addEventListener('visibilitychange', onFocus);\n }\n}\n\nfunction mapValue<T, S, Args extends any[]>(\n cache: Cache<T, Args>,\n _selector: Selector<T, S> | AnyPath,\n): Cache<S, Args> {\n const selector = makeSelector(_selector);\n const derivedFromCache = {\n cache: cache.derivedFromCache ? cache.derivedFromCache.cache : cache,\n selectors: cache.derivedFromCache\n ? [...cache.derivedFromCache.selectors, _selector]\n : [_selector],\n };\n\n return new Cache<S, Args>(\n async ({ use }) => {\n const value = await use(cache);\n return selector(value);\n },\n cache.args,\n {\n equals: cache.options.equals,\n },\n derivedFromCache,\n );\n}\n\nexport type CreateCacheResult<T, Args extends any[]> = [] extends Args\n ? CacheBundle<T, Args> & Cache<T, Args>\n : CacheBundle<T, Args>;\n\nexport interface InvalidationOptions<T, Args extends any[]> {\n filter?: (cache: Cache<T, Args>) => boolean;\n}\n\nexport type CacheBundle<T, Args extends any[]> = {\n (...args: Args): Cache<T, Args>;\n mapCache<S>(selector: Selector<T, S>): CreateCacheResult<S, Args>;\n mapValue<const P>(selector: Constrain<P, Path<T>>): CreateCacheResult<Value<T, P>, Args>;\n invalidateAll: (options?: InvalidationOptions<T, Args>) => void;\n clearAll: (options?: InvalidationOptions<T, Args>) => void;\n getInstances: () => Cache<T, Args>[];\n};\n\nfunction create<T, Args extends any[] = []>(\n cacheFunction: CacheFunction<T, Args>,\n options?: CacheOptions<T, Args>,\n): CreateCacheResult<T, Args> {\n return internalCreate<T, Args>(cacheFunction, options);\n}\n\nfunction internalCreate<T, Args extends any[] = []>(\n source:\n | CacheFunction<T, Args>\n | [cache: CacheBundle<any, Args>, selector: Selector<any, T> | AnyPath],\n options?: CacheOptions<T, Args>,\n): CreateCacheResult<T, Args> {\n options = { ...createCache.defaultOptions, ...options };\n const { clearUnusedAfter, resourceGroup } = options ?? {};\n\n let baseInstance: CacheBundle<T, Args> & Cache<T, Args>;\n\n const instanceCache = new InstanceCache<Args, Cache<T, Args>>(\n (...args: Args): Cache<T, Args> => {\n if (Array.isArray(source)) {\n const [cache, selector] = source;\n return mapValue(cache(...args), selector);\n }\n\n return new Cache(\n (helpers) => {\n const result = source.apply(helpers, args);\n\n if (result instanceof Function) {\n return result(helpers);\n }\n\n return result;\n },\n args,\n options,\n undefined,\n );\n },\n clearUnusedAfter ? calcDuration(clearUnusedAfter) : undefined,\n );\n\n function get(...args: Args) {\n const sliceAfter = args.lastIndexOf(undefined);\n if (sliceAfter !== -1) {\n args = args.slice(0, sliceAfter) as Args;\n }\n\n const cacheKey = options?.getCacheKey ? options.getCacheKey(...args) : args;\n return instanceCache.getWithKey(args, cacheKey);\n }\n\n const mapCache = (selector: any) => {\n return internalCreate([baseInstance, selector]);\n };\n\n const invalidateAll = ({ filter = () => true }: InvalidationOptions<T, Args> = {}) => {\n for (const instance of instanceCache.values()) {\n if (filter(instance)) {\n instance.invalidate();\n }\n }\n };\n\n const clearAll = ({ filter = () => true }: InvalidationOptions<T, Args> = {}) => {\n for (const instance of instanceCache.values()) {\n if (filter(instance)) {\n instance.clear();\n }\n }\n };\n\n const getInstances = () => {\n return instanceCache.values();\n };\n\n baseInstance = new Proxy(\n Object.assign(() => undefined, {\n mapCache,\n invalidateAll,\n clearAll,\n getInstances,\n }),\n {\n apply(_target, _thisArg, argArray) {\n return get(...(argArray as unknown as Args));\n },\n get(target, p, receiver) {\n if (Reflect.has(target, p)) {\n return Reflect.get(target, p, receiver);\n }\n\n const baseCache = get(...([] as unknown as Args));\n return Reflect.get(baseCache, p, baseCache);\n },\n },\n ) as unknown as CacheBundle<T, Args> & Cache<T, Args>;\n\n const groups = Array.isArray(resourceGroup)\n ? resourceGroup\n : resourceGroup\n ? [resourceGroup]\n : [];\n\n for (const group of groups.concat(allResources)) {\n group.add(baseInstance);\n }\n\n return baseInstance;\n}\n\nexport const createCache: typeof create & { defaultOptions: CacheOptions<any, any> } =\n /* @__PURE__ */ Object.assign(create, {\n defaultOptions: {\n invalidateOnWindowFocus: true,\n clearUnusedAfter: { days: 1 },\n retain: { milliseconds: 1 },\n equals: deepEqual,\n } as CacheOptions<any, any>,\n });\n","import { autobind } from '@lib/autobind';\n\nexport class Scope<T> {\n constructor(public readonly defaultValue: T) {\n autobind(Scope);\n }\n}\n\nexport function createScope<T>(defaultValue: T): Scope<T> {\n return new Scope(defaultValue);\n}\n"],"mappings":";;;;;AAEA,IAAa,gBAAb,MAAiE;CAO/D,YACE,AAAgBA,SAChB,AAAgBC,WAChB;EAFgB;EACA;+BARF,IAAI;kBAED,KAAK,YACpB,kBAAkB,KAAK,WAAW,KAAK,IAAI,KAAK,YAAY,IAAI,MAChE;;CAOJ,UAAgB;EACd,MAAM,SAAS,KAAK,SAAS,KAAK,aAAa;AAE/C,OAAK,MAAM,CAAC,KAAK,UAAU,KAAK,MAAM,WAAW;AAC/C,OAAI,MAAM,OAAO,MAAM,KAAK,OAC1B,QAAO,MAAM;AAGf,OAAI,CAAC,MAAM,OAAO,CAAC,MAAM,SAAS,QAChC,MAAK,MAAM,OAAO;;;CAKxB,IAAI,GAAG,MAAe;AACpB,SAAO,KAAK,WAAW,MAAM;;CAG/B,WAAW,MAAY,UAAsB;EAC3C,MAAM,MAAM,WAAW;EACvB,IAAI,QAAQ,KAAK,MAAM,IAAI;EAC3B,IAAI,QAAQ,OAAO,OAAO,OAAO,SAAS;AAE1C,MAAI,CAAC,SAAS,CAAC,OAAO;AACpB,WAAQ,KAAK,QAAQ,GAAG;AACxB,WAAQ;IACN,GAAG,KAAK;IACR,KAAK;IACL,SAAS,IAAI,QAAQ;;AAGvB,QAAK,MAAM,IAAI,KAAK;SACf;AACL,SAAM,IAAI,K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AAe,CAAC,cAAc;;CAGvC,MAAM,iBAAiB,EAAE,eAAe,SAAuC,OAAO;AACpF,OAAK,MAAM,YAAY,cAAc,SACnC,KAAI,OAAO,UACT,UAAS;;CAKf,MAAM,YAAY,EAAE,eAAe,SAAuC,OAAO;AAC/E,OAAK,MAAM,YAAY,cAAc,SACnC,KAAI,OAAO,UACT,UAAS;;CAKf,MAAM,qBAAqB;AACzB,SAAO,cAAc;;AAGvB,gBAAe,IAAI,MACjB,OAAO,aAAa,QAAW;EAC7B;EACA;EACA;EACA;KAEF;EACE,MAAM,SAAS,UAAU,UAAU;AACjC,UAAO,IAAI,GAAI;;EAEjB,IAAI,QAAQ,GAAG,UAAU;AACvB,OAAI,QAAQ,IAAI,QAAQ,GACtB,QAAO,QAAQ,IAAI,QAAQ,GAAG;GAGhC,MAAM,YAAY,IAAI,GAAI;AAC1B,UAAO,QAAQ,IAAI,WAAW,GAAG;;;CAKvC,MAAM,SAAS,MAAM,QAAQ,iBACzB,gBACA,gBACE,CAAC,iBACD;AAEN,MAAK,MAAM,SAAS,OAAO,OAAO,cAChC,OAAM,IAAI;AAGZ,QAAO;;AAGT,MAAaC,cACK,uBAAO,OAAO,QAAQ,EACpC,gBAAgB;CACd,yBAAyB;CACzB,kBAAkB,EAAE,MAAM;CAC1B,QAAQ,EAAE,cAAc;CACxB,QAAQ;;;;;AC3dd,IAAa,QAAb,MAAa,MAAS;CACpB,YAAY,AAAgBC,cAAiB;EAAjB;AAC1B,WAAS;;;AAIb,SAAgB,YAAe,cAA2B;AACxD,QAAO,IAAI,MAAM"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"scope-BfYAP7hS.cjs","names":["factory: (...args: Args) => T","cacheTime?: number","simpleHash","name?: string","allResources: ResourceGroup","Store","args: Args","options: CacheOptions<T, Args>","derivedFromCache?: {\n cache: Cache<any, any>;\n selectors: (Selector<any, any> | AnyPath)[];\n }","createStore","calculatedValue","PromiseWithState","calcDuration","makeSelector","baseInstance: CacheBundle<T, Args> & Cache<T, Args>","createCache: typeof create & { defaultOptions: CacheOptions<any, any> }","deepEqual","defaultValue: T"],"sources":["../src/lib/instanceCache.ts","../src/core/resourceGroup.ts","../src/core/cache.ts","../src/core/scope.ts"],"sourcesContent":["import { simpleHash } from './hash';\n\nexport class InstanceCache<Args extends any[], T extends object> {\n private cache = new Map<string, { t: number; ref?: T; weakRef: WeakRef<T> }>();\n\n private interval = this.cacheTime\n ? setInterval(() => this.cleanup(), Math.max(this.cacheTime / 10, 1))\n : undefined;\n\n constructor(\n public readonly factory: (...args: Args) => T,\n public readonly cacheTime?: number,\n ) {}\n\n cleanup(): void {\n const cutoff = this.now() - (this.cacheTime ?? 0);\n\n for (const [key, entry] of this.cache.entries()) {\n if (entry.ref && entry.t <= cutoff) {\n delete entry.ref;\n }\n\n if (!entry.ref && !entry.weakRef?.deref()) {\n this.cache.delete(key);\n }\n }\n }\n\n get(...args: Args): T {\n return this.getWithKey(args, args);\n }\n\n getWithKey(args: Args, cacheKey: unknown): T {\n const key = simpleHash(cacheKey);\n let entry = this.cache.get(key);\n let value = entry?.ref ?? entry?.weakRef?.deref();\n\n if (!entry || !value) {\n value = this.factory(...args);\n entry = {\n t: this.now(),\n ref: value,\n weakRef: new WeakRef(value),\n };\n\n this.cache.set(key, entry);\n } else {\n entry.t = this.now();\n entry.ref ??= value;\n }\n\n return value;\n }\n\n values(): T[] {\n return [...this.cache.values()]\n .map((entry) => entry.ref ?? entry.weakRef?.deref())\n .filter((value): value is T => !!value);\n }\n\n stop(): void {\n if (this.interval) {\n clearInterval(this.interval);\n }\n }\n\n stats(): { count: number; withRef: number; withWeakRef: number } {\n return {\n count: this.cache.size,\n withRef: [...this.cache.values()].filter((x) => !!x.ref).length,\n withWeakRef: [...this.cache.values()].filter((x) => !!x.weakRef?.deref()).length,\n };\n }\n\n private now() {\n return performance.now();\n }\n}\n","import { autobind } from '@lib/autobind';\n\nexport interface Resource {\n invalidateAll(): void;\n clearAll(): void;\n}\n\nexport class ResourceGroup {\n private refMap = new WeakMap<Resource, WeakRef<Resource>>();\n\n private refSet = new Set<WeakRef<Resource>>();\n\n constructor(public readonly name?: string) {\n autobind(ResourceGroup);\n }\n\n add(resource: Resource): void {\n const ref = new WeakRef(resource);\n this.refMap.set(resource, ref);\n this.refSet.add(ref);\n }\n\n delete(resource: Resource): void {\n const ref = this.refMap.get(resource);\n if (ref) {\n this.refMap.delete(resource);\n this.refSet.delete(ref);\n }\n }\n\n invalidateAll(): void {\n for (const ref of this.refSet) {\n const resource = ref.deref();\n if (resource) {\n resource.invalidateAll();\n } else {\n this.refSet.delete(ref);\n }\n }\n }\n\n clearAll(): void {\n for (const ref of this.refSet) {\n const resource = ref.deref();\n if (resource) {\n resource.clearAll();\n } else {\n this.refSet.delete(ref);\n }\n }\n }\n}\n\nexport const allResources: ResourceGroup = /* @__PURE__ */ new ResourceGroup();\n\nexport function createResourceGroup(name?: string): ResourceGroup {\n return new ResourceGroup(name);\n}\n","import { autobind } from '@lib/autobind';\nimport type { CacheState, ErrorState, ValueState } from '@lib/cacheState';\nimport { calcDuration } from '@lib/calcDuration';\nimport { calculatedValue } from '@lib/calculatedValue';\nimport type { Constrain } from '@lib/constrain';\nimport { deepEqual } from '@lib/equals';\nimport { InstanceCache } from '@lib/instanceCache';\nimport { makeSelector } from '@lib/makeSelector';\nimport { type MaybePromise } from '@lib/maybePromise';\nimport type { AnyPath, Path, Value } from '@lib/path';\nimport { PromiseWithState } from '@lib/promiseWithState';\nimport type { Duration, Selector } from './commonTypes';\nimport { allResources, type ResourceGroup } from './resourceGroup';\nimport { Store, createStore, type Calculate, type StoreOptions } from './store';\n\nexport interface CacheGetOptions {\n /**\n * How to handle the cache when getting the value.\n * - `whenMissing`: Only fetch a new value if there is no cached value.\n * - `whenStale`: Fetch a new value if there is no cached value or if the cached value is stale.\n * - `force`: Always fetch a new value, regardless of the cache state.\n */\n update?: 'whenMissing' | 'whenStale' | 'force';\n\n /**\n * If set to `true`, the cache will be updated in the background.\n * This means that a stale value will be returned immediately, if available, while the new value is being fetched.\n */\n backgroundUpdate?: boolean;\n}\n\nexport interface CacheFunction<T, Args extends any[] = []> {\n (...args: Args): Promise<T> | Calculate<Promise<T>>;\n}\n\nexport interface CacheOptions<T, Args extends any[]> extends StoreOptions<Promise<T>> {\n /**\n * How long to keep the cache entry before it is considered stale.\n * If set to `undefined` or `null`, the cache entry will never be invalidated automatically.\n *\n * @example\n * ```typescript\n * createCache(fetchData, {\n * invalidateAfter: { seconds: 10 },\n * });\n * ```\n */\n invalidateAfter?: Duration | ((state: ValueState<T> | ErrorState) => Duration | null) | null;\n\n /**\n * If set, the cache will be invalidated when the window gets focused.\n * This is useful for caches that are used in a browser environment and might become stale when the user switches tabs.\n */\n invalidateOnWindowFocus?: boolean;\n\n /**\n * If set, the cached value will be cleared when the cache is invalidated.\n * Without this option, the cache will keep the last value as stale until a new value becomes available.\n */\n clearOnInvalidate?: boolean;\n\n /**\n * If set, cache entries will be cleared after approximately the specified duration.\n * This is useful for long lived pages or applications and helps to prevent memory leaks.\n * The exact time when the entry is cleared is not guaranteed, since it will be cleared during garbage collection.\n */\n clearUnusedAfter?: Duration | null;\n\n /**\n * Add the cache to the specified resource group(s).\n * This allows you to invalidate or clear multiple caches that belong to the same group.\n * All caches are always added to the `allResources` group.\n */\n resourceGroup?: ResourceGroup | ResourceGroup[];\n\n /**\n * Function to generate a custom cache key based on the provided arguments.\n * This allows you to control how cache entries are identified and reused.\n * By default, the arguments array is used as the cache key.\n *\n * @example\n * ```typescript\n * // Will use the same instance when provided with `undefined`, `{ num: 0 }`, `{ bool: false }`, etc.\n * createCache((filter?: { num?: number, bool?: boolean }) => fetchData(filter), {\n * getCacheKey: (filter?) => ({\n * num: filter?.num ?? 0,\n * bool: filter?.bool ?? false,\n * }),\n * });\n * ```\n */\n getCacheKey?: (...args: NoInfer<Args>) => unknown;\n}\n\nexport class Cache<T, Args extends any[] = []> extends Store<Promise<T>> {\n readonly state: Store<CacheState<T>> = createStore<CacheState<T>>({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n isConnected: false,\n });\n\n protected stalePromise?: Promise<T>;\n\n protected invalidationTimer?: ReturnType<typeof setTimeout>;\n\n constructor(\n getter: Calculate<Promise<T>>,\n public readonly args: Args,\n public readonly options: CacheOptions<T, Args> = {},\n public readonly derivedFromCache?: {\n cache: Cache<any, any>;\n selectors: (Selector<any, any> | AnyPath)[];\n },\n ) {\n super(getter, options, undefined);\n autobind(Cache);\n\n this.watchPromise();\n this.watchFocus();\n }\n\n get({ update = 'whenStale', backgroundUpdate = false }: CacheGetOptions = {}): Promise<T> {\n this.calculatedValue?.check();\n const promise = this.calculatedValue?.value;\n const stalePromise = this.stalePromise;\n\n if (\n (update === 'whenMissing' && !promise && !stalePromise) ||\n (update === 'whenStale' && !promise) ||\n update === 'force'\n ) {\n this.calculatedValue = calculatedValue(this, this.notify);\n this.notify();\n\n if ((!promise && !stalePromise) || !backgroundUpdate) {\n return this.calculatedValue.value;\n }\n }\n\n if (!promise || (stalePromise && backgroundUpdate)) {\n return stalePromise!;\n }\n\n return promise;\n }\n\n updateValue(value: MaybePromise<T> | ((value: T | undefined) => T)): void {\n if (value instanceof Function) {\n value = value(this.state.get().value);\n }\n this.set(PromiseWithState.resolve(value));\n }\n\n updateError(error: unknown): void {\n this.set(PromiseWithState.reject(error));\n }\n\n invalidate(recursive?: boolean): void {\n const { clearOnInvalidate } = this.options;\n\n if (clearOnInvalidate) {\n return this.clear(recursive);\n }\n\n const { status, isStale, isUpdating } = this.state.get();\n if (status !== 'pending' && !isStale && !isUpdating) {\n this.stalePromise = this.calculatedValue?.value;\n }\n\n this.state.set((state) => ({\n ...state,\n isStale: true,\n isUpdating: false,\n }));\n\n super.invalidate(recursive);\n }\n\n clear(recursive?: boolean): void {\n this.state.set({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n isConnected: false,\n });\n delete this.stalePromise;\n\n super.invalidate(recursive);\n }\n\n mapValue<S>(selector: Selector<T, S>): Cache<S, Args>;\n\n mapValue<const P extends AnyPath>(\n selector: P extends Path<T> ? P : Path<T>,\n ): Cache<Value<T, P>, Args>;\n\n mapValue(selector: Selector<any, any> | AnyPath) {\n return mapValue(this, selector);\n }\n\n protected watchPromise(): void {\n this.subscribe(\n async (promise) => {\n if (promise instanceof PromiseWithState && promise.state.status !== 'pending') {\n promise.catch(() => undefined);\n\n this.state.set((state) => ({\n ...promise.state,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n\n delete this.stalePromise;\n this.setTimers();\n return;\n }\n\n this.state.set((state) => ({\n ...state,\n isUpdating: true,\n }));\n\n this.setTimers();\n\n try {\n const value = await promise;\n\n if (promise !== this.calculatedValue?.value) {\n return;\n }\n\n this.state.set((state) => ({\n status: 'value',\n value,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n delete this.stalePromise;\n this.setTimers();\n } catch (error) {\n if (promise !== this.calculatedValue?.value) {\n return;\n }\n\n this.state.set((state) => ({\n status: 'error',\n error,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n delete this.stalePromise;\n this.setTimers();\n }\n },\n { passive: true },\n );\n }\n\n protected setTimers(): void {\n if (this.invalidationTimer) {\n clearTimeout(this.invalidationTimer);\n }\n this.invalidationTimer = undefined;\n\n const state = this.state.get();\n let { invalidateAfter } = this.options;\n const ref = new WeakRef(this);\n\n if (state.status === 'pending') {\n return;\n }\n\n if (invalidateAfter instanceof Function) {\n invalidateAfter = invalidateAfter(state);\n }\n\n if (invalidateAfter !== null && invalidateAfter !== undefined) {\n this.invalidationTimer = setTimeout(\n () => ref?.deref()?.invalidate(),\n calcDuration(invalidateAfter),\n );\n }\n }\n\n protected watchFocus(): void {\n const { invalidateOnWindowFocus } = this.options;\n\n if (\n !invalidateOnWindowFocus ||\n typeof document === 'undefined' ||\n typeof document.addEventListener === 'undefined'\n ) {\n return;\n }\n\n const ref = new WeakRef(this);\n\n const onFocus = () => {\n const that = ref?.deref();\n if (!that) {\n document.removeEventListener('visibilitychange', onFocus);\n return;\n }\n\n if (!document.hidden && !that.state.get().isConnected) {\n that.invalidate();\n }\n };\n\n document.addEventListener('visibilitychange', onFocus);\n }\n}\n\nfunction mapValue<T, S, Args extends any[]>(\n cache: Cache<T, Args>,\n _selector: Selector<T, S> | AnyPath,\n): Cache<S, Args> {\n const selector = makeSelector(_selector);\n const derivedFromCache = {\n cache: cache.derivedFromCache ? cache.derivedFromCache.cache : cache,\n selectors: cache.derivedFromCache\n ? [...cache.derivedFromCache.selectors, _selector]\n : [_selector],\n };\n\n return new Cache<S, Args>(\n async ({ use }) => {\n const value = await use(cache);\n return selector(value);\n },\n cache.args,\n {\n equals: cache.options.equals,\n },\n derivedFromCache,\n );\n}\n\nexport type CreateCacheResult<T, Args extends any[]> = [] extends Args\n ? CacheBundle<T, Args> & Cache<T, Args>\n : CacheBundle<T, Args>;\n\nexport interface InvalidationOptions<T, Args extends any[]> {\n filter?: (cache: Cache<T, Args>) => boolean;\n}\n\nexport type CacheBundle<T, Args extends any[]> = {\n (...args: Args): Cache<T, Args>;\n mapCache<S>(selector: Selector<T, S>): CreateCacheResult<S, Args>;\n mapValue<const P>(selector: Constrain<P, Path<T>>): CreateCacheResult<Value<T, P>, Args>;\n invalidateAll: (options?: InvalidationOptions<T, Args>) => void;\n clearAll: (options?: InvalidationOptions<T, Args>) => void;\n getInstances: () => Cache<T, Args>[];\n};\n\nfunction create<T, Args extends any[] = []>(\n cacheFunction: CacheFunction<T, Args>,\n options?: CacheOptions<T, Args>,\n): CreateCacheResult<T, Args> {\n return internalCreate<T, Args>(cacheFunction, options);\n}\n\nfunction internalCreate<T, Args extends any[] = []>(\n source:\n | CacheFunction<T, Args>\n | [cache: CacheBundle<any, Args>, selector: Selector<any, T> | AnyPath],\n options?: CacheOptions<T, Args>,\n): CreateCacheResult<T, Args> {\n options = { ...createCache.defaultOptions, ...options };\n const { clearUnusedAfter, resourceGroup } = options ?? {};\n\n let baseInstance: CacheBundle<T, Args> & Cache<T, Args>;\n\n const instanceCache = new InstanceCache<Args, Cache<T, Args>>(\n (...args: Args): Cache<T, Args> => {\n if (Array.isArray(source)) {\n const [cache, selector] = source;\n return mapValue(cache(...args), selector);\n }\n\n return new Cache(\n (helpers) => {\n const result = source.apply(helpers, args);\n\n if (result instanceof Function) {\n return result(helpers);\n }\n\n return result;\n },\n args,\n options,\n undefined,\n );\n },\n clearUnusedAfter ? calcDuration(clearUnusedAfter) : undefined,\n );\n\n function get(...args: Args) {\n const sliceAfter = args.lastIndexOf(undefined);\n if (sliceAfter !== -1) {\n args = args.slice(0, sliceAfter) as Args;\n }\n\n const cacheKey = options?.getCacheKey ? options.getCacheKey(...args) : args;\n return instanceCache.getWithKey(args, cacheKey);\n }\n\n const mapCache = (selector: any) => {\n return internalCreate([baseInstance, selector]);\n };\n\n const invalidateAll = ({ filter = () => true }: InvalidationOptions<T, Args> = {}) => {\n for (const instance of instanceCache.values()) {\n if (filter(instance)) {\n instance.invalidate();\n }\n }\n };\n\n const clearAll = ({ filter = () => true }: InvalidationOptions<T, Args> = {}) => {\n for (const instance of instanceCache.values()) {\n if (filter(instance)) {\n instance.clear();\n }\n }\n };\n\n const getInstances = () => {\n return instanceCache.values();\n };\n\n baseInstance = new Proxy(\n Object.assign(() => undefined, {\n mapCache,\n invalidateAll,\n clearAll,\n getInstances,\n }),\n {\n apply(_target, _thisArg, argArray) {\n return get(...(argArray as unknown as Args));\n },\n get(target, p, receiver) {\n if (Reflect.has(target, p)) {\n return Reflect.get(target, p, receiver);\n }\n\n const baseCache = get(...([] as unknown as Args));\n return Reflect.get(baseCache, p, baseCache);\n },\n },\n ) as unknown as CacheBundle<T, Args> & Cache<T, Args>;\n\n const groups = Array.isArray(resourceGroup)\n ? resourceGroup\n : resourceGroup\n ? [resourceGroup]\n : [];\n\n for (const group of groups.concat(allResources)) {\n group.add(baseInstance);\n }\n\n return baseInstance;\n}\n\nexport const createCache: typeof create & { defaultOptions: CacheOptions<any, any> } =\n /* @__PURE__ */ Object.assign(create, {\n defaultOptions: {\n invalidateOnWindowFocus: true,\n clearUnusedAfter: { days: 1 },\n retain: { milliseconds: 1 },\n equals: deepEqual,\n } as CacheOptions<any, any>,\n });\n","import { autobind } from '@lib/autobind';\n\nexport class Scope<T> {\n constructor(public readonly defaultValue: T) {\n autobind(Scope);\n }\n}\n\nexport function createScope<T>(defaultValue: T): Scope<T> {\n return new Scope(defaultValue);\n}\n"],"mappings":";;;;;AAEA,IAAa,gBAAb,MAAiE;CAO/D,YACE,AAAgBA,SAChB,AAAgBC,WAChB;EAFgB;EACA;+BARF,IAAI;kBAED,KAAK,YACpB,kBAAkB,KAAK,WAAW,KAAK,IAAI,KAAK,YAAY,IAAI,MAChE;;CAOJ,UAAgB;EACd,MAAM,SAAS,KAAK,SAAS,KAAK,aAAa;AAE/C,OAAK,MAAM,CAAC,KAAK,UAAU,KAAK,MAAM,WAAW;AAC/C,OAAI,MAAM,OAAO,MAAM,KAAK,OAC1B,QAAO,MAAM;AAGf,OAAI,CAAC,MAAM,OAAO,CAAC,MAAM,SAAS,QAChC,MAAK,MAAM,OAAO;;;CAKxB,IAAI,GAAG,MAAe;AACpB,SAAO,KAAK,WAAW,MAAM;;CAG/B,WAAW,MAAY,UAAsB;EAC3C,MAAM,MAAMC,wBAAW;EACvB,IAAI,QAAQ,KAAK,MAAM,IAAI;EAC3B,IAAI,QAAQ,OAAO,OAAO,OAAO,SAAS;AAE1C,MAAI,CAAC,SAAS,CAAC,OAAO;AACpB,WAAQ,KAAK,QAAQ,GAAG;AACxB,WAAQ;IACN,GAAG,KAAK;IACR,KAAK;IACL,SAAS,IAAI,QAAQ;;AAGvB,QAAK,MAAM,IAAI,KAAK;SACf;AACL,SAAM,IAAI,KAAK;AACf,SAAM,QAAQ;;AAGhB,SAAO;;CAGT,SAAc;AACZ,SAAO,CAAC,GAAG,KAAK,MAAM,UACnB,KAAK,UAAU,MAAM,OAAO,MAAM,SAAS,SAC3C,QAAQ,UAA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