cross-state 0.55.2 → 0.55.4
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 +3 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -7
- package/dist/index.d.ts +7 -7
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -69,8 +69,9 @@ async function loadPage(cache, helpers, oldPages) {
|
|
|
69
69
|
}
|
|
70
70
|
function createPaged(definition, options) {
|
|
71
71
|
return require_scope.internalCreate((args, options$1) => {
|
|
72
|
-
|
|
73
|
-
|
|
72
|
+
let currentDefinition = definition;
|
|
73
|
+
if (currentDefinition instanceof Function) currentDefinition = currentDefinition(...args);
|
|
74
|
+
return new PagedCache(currentDefinition, args, options$1);
|
|
74
75
|
}, options);
|
|
75
76
|
}
|
|
76
77
|
const createPagedCache = /* @__PURE__ */ Object.assign(createPaged, { defaultOptions: require_scope.defaultCacheOptions });
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["Cache","definition: PagedCacheDefinition<T, Args>","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<
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["Cache","definition: PagedCacheDefinition<T, Args>","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<PagedCacheState<T>>> {\n /**\n * Previously fetched pages (in order).\n */\n pages: T[];\n /**\n * Last fetched page or null if there are no previously fetched pages.\n */\n prevPage: T | null;\n}\n\nexport interface PageCacheFunction<T> {\n (props: PageCacheFunctionProps<T>): Promise<T | null>;\n}\n\nexport interface PagedCacheDefinition<T, Args extends any[]> {\n /**\n * Function to fetch a page.\n * The function receives the current state of the cache, including previously fetched pages.\n */\n fetchPage: (this: PagedCache<T, Args>, props: PageCacheFunctionProps<T>) => Promise<T | null>;\n /**\n * Optional function to determine the total number of pages - usually based on data in the fetched pages.\n */\n getPageCount?: (this: PagedCache<T, Args>, pages: T[]) => number | null;\n /**\n * Optional function to determine if there are more pages to fetch - usually based on data in the fetched pages.\n * If not provided, it will be assumed there are more pages until getPageCount is provided and the number of fetched pages equals the page count or until fetchPage returns null.\n */\n hasMorePages?: (this: PagedCache<T, Args>, pages: T[]) => boolean;\n}\n\nexport interface PagedCacheDefinitionFunction<T, Args extends any[]> {\n (...args: Args): PagedCacheDefinition<T, Args>;\n}\n\nexport interface PagedCacheState<T> {\n pages: T[];\n hasMore: boolean;\n pageCount: number | null;\n}\n\nexport interface FetchNextPageOptions {\n /**\n * If true, will throw if the cache is in an error state or if another page is being fetched.\n */\n throwOnError?: boolean;\n}\n\nexport class PagedCache<T, Args extends any[] = []> extends Cache<PagedCacheState<T>, Args> {\n constructor(\n public readonly definition: PagedCacheDefinition<T, Args>,\n args: Args,\n options: CacheOptions<PagedCacheState<T>, Args> = {},\n ) {\n super(async (helpers) => loadPage(this, helpers, []), args, options, undefined);\n autobind(PagedCache);\n }\n\n async fetchNextPage({ throwOnError }: FetchNextPageOptions = {}): Promise<void> {\n const { status, isStale, isUpdating, value } = this.state.get();\n\n if (status === 'error') {\n if (!throwOnError) return;\n throw new Error('Cannot fetch next page while cache is in error state');\n }\n\n if (isUpdating) {\n if (!throwOnError) return;\n throw new Error('Cannot fetch next page while another page is being fetched');\n }\n\n if (status === 'pending' || isStale) {\n await this.get().catch(() => {});\n return;\n }\n\n if (!value.hasMore) {\n if (!throwOnError) return;\n throw new Error('No more pages to fetch');\n }\n\n this.stalePromise = this.calculatedValue?.value;\n\n const ac = new AbortController();\n const promise = loadPage(\n this,\n {\n use() {\n throw new Error('Not implemented');\n },\n connect() {\n throw new Error('Not implemented');\n },\n signal: ac.signal,\n },\n value.pages,\n );\n\n this.updateValue(promise);\n\n try {\n await promise;\n } catch (error) {\n if (!throwOnError) return;\n throw error;\n }\n }\n}\n\nasync function loadPage<T, Args extends any[]>(\n cache: PagedCache<T, Args>,\n helpers: CalculationActions<Promise<PagedCacheState<T>>>,\n oldPages: T[],\n) {\n const { fetchPage, hasMorePages, getPageCount } = cache.definition;\n\n const page = await fetchPage.call(cache, {\n ...helpers,\n pages: oldPages,\n prevPage: oldPages.length > 0 ? oldPages[oldPages.length - 1]! : null,\n });\n\n const pages = page === null ? oldPages : oldPages.concat(page);\n const pageCount = getPageCount?.call(cache, pages) ?? null;\n const hasMore = hasMorePages\n ? hasMorePages.call(cache, pages)\n : pageCount !== null\n ? pages.length < pageCount\n : page !== null;\n\n return { pages, hasMore, pageCount };\n}\n\nfunction createPaged<T, Args extends any[] = []>(\n definition: PagedCacheDefinitionFunction<T, Args>,\n options?: CacheOptions<PagedCacheState<T>, Args>,\n): CreateCacheResult<PagedCacheState<T>, Args, PagedCache<T, Args>>;\n\nfunction createPaged<T>(\n definition: PagedCacheDefinition<T, []>,\n options?: CacheOptions<PagedCacheState<T>, []>,\n): CreateCacheResult<PagedCacheState<T>, [], PagedCache<T, []>>;\n\nfunction createPaged<T, Args extends any[] = []>(\n definition: PagedCacheDefinitionFunction<T, Args> | PagedCacheDefinition<T, Args>,\n options?: CacheOptions<PagedCacheState<T>, Args>,\n): CreateCacheResult<PagedCacheState<T>, Args, PagedCache<T, Args>> {\n return internalCreate<PagedCacheState<T>, Args, PagedCache<T, Args>>((args, options) => {\n let currentDefinition = definition;\n if (currentDefinition instanceof Function) {\n currentDefinition = currentDefinition(...args);\n }\n return new PagedCache(currentDefinition, 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":";;;;;;;;;AA2DA,IAAa,aAAb,MAAa,mBAA+CA,oBAAgC;CAC1F,YACE,AAAgBC,YAChB,MACA,UAAkD,IAClD;AACA,QAAM,OAAO,YAAY,SAAS,MAAM,SAAS,KAAK,MAAM,SAAS;EAJrD;AAKhB,yBAAS;;CAGX,MAAM,cAAc,EAAE,iBAAuC,IAAmB;EAC9E,MAAM,EAAE,QAAQ,SAAS,YAAY,UAAU,KAAK,MAAM;AAE1D,MAAI,WAAW,SAAS;AACtB,OAAI,CAAC,aAAc;AACnB,SAAM,IAAI,MAAM;;AAGlB,MAAI,YAAY;AACd,OAAI,CAAC,aAAc;AACnB,SAAM,IAAI,MAAM;;AAGlB,MAAI,WAAW,aAAa,SAAS;AACnC,SAAM,KAAK,MAAM,YAAY;AAC7B;;AAGF,MAAI,CAAC,MAAM,SAAS;AAClB,OAAI,CAAC,aAAc;AACnB,SAAM,IAAI,MAAM;;AAGlB,OAAK,eAAe,KAAK,iBAAiB;EAE1C,MAAM,KAAK,IAAI;EACf,MAAM,UAAU,SACd,MACA;GACE,MAAM;AACJ,UAAM,IAAI,MAAM;;GAElB,UAAU;AACR,UAAM,IAAI,MAAM;;GAElB,QAAQ,GAAG;KAEb,MAAM;AAGR,OAAK,YAAY;AAEjB,MAAI;AACF,SAAM;WACC,OAAO;AACd,OAAI,CAAC,aAAc;AACnB,SAAM;;;;AAKZ,eAAe,SACb,OACA,SACA,UACA;CACA,MAAM,EAAE,WAAW,cAAc,iBAAiB,MAAM;CAExD,MAAM,OAAO,MAAM,UAAU,KAAK,OAAO;EACvC,GAAG;EACH,OAAO;EACP,UAAU,SAAS,SAAS,IAAI,SAAS,SAAS,SAAS,KAAM;;CAGnE,MAAM,QAAQ,SAAS,OAAO,WAAW,SAAS,OAAO;CACzD,MAAM,YAAY,cAAc,KAAK,OAAO,UAAU;CACtD,MAAM,UAAU,eACZ,aAAa,KAAK,OAAO,SACzB,cAAc,OACZ,MAAM,SAAS,YACf,SAAS;AAEf,QAAO;EAAE;EAAO;EAAS;;;AAa3B,SAAS,YACP,YACA,SACkE;AAClE,QAAOC,8BAA+D,MAAM,cAAY;EACtF,IAAI,oBAAoB;AACxB,MAAI,6BAA6B,SAC/B,qBAAoB,kBAAkB,GAAG;AAE3C,SAAO,IAAI,WAAW,mBAAmB,MAAMC;IAC9C;;AAGL,MAAaC,mBACK,uBAAO,OAAO,aAAa,EACzC,gBAAgBC;;;;ACzKpB,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
|
@@ -4,7 +4,7 @@ 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
6
|
//#region src/core/pagedCache.d.ts
|
|
7
|
-
interface PageCacheFunctionProps<T> extends CalculationActions<Promise<
|
|
7
|
+
interface PageCacheFunctionProps<T> extends CalculationActions<Promise<PagedCacheState<T>>> {
|
|
8
8
|
/**
|
|
9
9
|
* Previously fetched pages (in order).
|
|
10
10
|
*/
|
|
@@ -36,7 +36,7 @@ interface PagedCacheDefinition<T, Args extends any[]> {
|
|
|
36
36
|
interface PagedCacheDefinitionFunction<T, Args extends any[]> {
|
|
37
37
|
(...args: Args): PagedCacheDefinition<T, Args>;
|
|
38
38
|
}
|
|
39
|
-
interface
|
|
39
|
+
interface PagedCacheState<T> {
|
|
40
40
|
pages: T[];
|
|
41
41
|
hasMore: boolean;
|
|
42
42
|
pageCount: number | null;
|
|
@@ -47,15 +47,15 @@ interface FetchNextPageOptions {
|
|
|
47
47
|
*/
|
|
48
48
|
throwOnError?: boolean;
|
|
49
49
|
}
|
|
50
|
-
declare class PagedCache<T, Args extends any[] = []> extends Cache<
|
|
50
|
+
declare class PagedCache<T, Args extends any[] = []> extends Cache<PagedCacheState<T>, Args> {
|
|
51
51
|
readonly definition: PagedCacheDefinition<T, Args>;
|
|
52
|
-
constructor(definition: PagedCacheDefinition<T, Args>, args: Args, options?: CacheOptions<
|
|
52
|
+
constructor(definition: PagedCacheDefinition<T, Args>, args: Args, options?: CacheOptions<PagedCacheState<T>, Args>);
|
|
53
53
|
fetchNextPage({
|
|
54
54
|
throwOnError
|
|
55
55
|
}?: FetchNextPageOptions): Promise<void>;
|
|
56
56
|
}
|
|
57
|
-
declare function createPaged<T, Args extends any[] = []>(definition: PagedCacheDefinitionFunction<T, Args>, options?: CacheOptions<
|
|
58
|
-
declare function createPaged<T>(definition: PagedCacheDefinition<T, []>, options?: CacheOptions<
|
|
57
|
+
declare function createPaged<T, Args extends any[] = []>(definition: PagedCacheDefinitionFunction<T, Args>, options?: CacheOptions<PagedCacheState<T>, Args>): CreateCacheResult<PagedCacheState<T>, Args, PagedCache<T, Args>>;
|
|
58
|
+
declare function createPaged<T>(definition: PagedCacheDefinition<T, []>, options?: CacheOptions<PagedCacheState<T>, []>): CreateCacheResult<PagedCacheState<T>, [], PagedCache<T, []>>;
|
|
59
59
|
declare const createPagedCache: typeof createPaged & {
|
|
60
60
|
defaultOptions: CacheOptions<any, any>;
|
|
61
61
|
};
|
|
@@ -118,5 +118,5 @@ declare function set<T, const P>(object: T, path: Constrain<P, SettablePath<T>>,
|
|
|
118
118
|
//#region src/lib/updateHelpers.d.ts
|
|
119
119
|
declare function findOrDefault<T>(array: T[], predicate: (item: T) => boolean, defaultValue: T | (() => T)): T;
|
|
120
120
|
//#endregion
|
|
121
|
-
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 };
|
|
121
|
+
export { AsyncConnectionActions, AsyncUpdateFunction, BaseConnectionActions, BoundStoreMethods, Cache, CacheBundle, CacheFunction, CacheGetOptions, CacheOptions, CacheState, CalculationActions, Cancel, Connection, ConnectionActions, CreateCacheResult, DisposableCancel, Duration, Effect, ErrorState, FetchNextPageOptions, type Hashable, InstanceCache, Listener, PageCacheFunction, PageCacheFunctionProps, PagedCache, PagedCacheDefinition, PagedCacheDefinitionFunction, PagedCacheState, 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 };
|
|
122
122
|
//# sourceMappingURL=index.d.cts.map
|
package/dist/index.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ 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
6
|
//#region src/core/pagedCache.d.ts
|
|
7
|
-
interface PageCacheFunctionProps<T> extends CalculationActions<Promise<
|
|
7
|
+
interface PageCacheFunctionProps<T> extends CalculationActions<Promise<PagedCacheState<T>>> {
|
|
8
8
|
/**
|
|
9
9
|
* Previously fetched pages (in order).
|
|
10
10
|
*/
|
|
@@ -36,7 +36,7 @@ interface PagedCacheDefinition<T, Args extends any[]> {
|
|
|
36
36
|
interface PagedCacheDefinitionFunction<T, Args extends any[]> {
|
|
37
37
|
(...args: Args): PagedCacheDefinition<T, Args>;
|
|
38
38
|
}
|
|
39
|
-
interface
|
|
39
|
+
interface PagedCacheState<T> {
|
|
40
40
|
pages: T[];
|
|
41
41
|
hasMore: boolean;
|
|
42
42
|
pageCount: number | null;
|
|
@@ -47,15 +47,15 @@ interface FetchNextPageOptions {
|
|
|
47
47
|
*/
|
|
48
48
|
throwOnError?: boolean;
|
|
49
49
|
}
|
|
50
|
-
declare class PagedCache<T, Args extends any[] = []> extends Cache<
|
|
50
|
+
declare class PagedCache<T, Args extends any[] = []> extends Cache<PagedCacheState<T>, Args> {
|
|
51
51
|
readonly definition: PagedCacheDefinition<T, Args>;
|
|
52
|
-
constructor(definition: PagedCacheDefinition<T, Args>, args: Args, options?: CacheOptions<
|
|
52
|
+
constructor(definition: PagedCacheDefinition<T, Args>, args: Args, options?: CacheOptions<PagedCacheState<T>, Args>);
|
|
53
53
|
fetchNextPage({
|
|
54
54
|
throwOnError
|
|
55
55
|
}?: FetchNextPageOptions): Promise<void>;
|
|
56
56
|
}
|
|
57
|
-
declare function createPaged<T, Args extends any[] = []>(definition: PagedCacheDefinitionFunction<T, Args>, options?: CacheOptions<
|
|
58
|
-
declare function createPaged<T>(definition: PagedCacheDefinition<T, []>, options?: CacheOptions<
|
|
57
|
+
declare function createPaged<T, Args extends any[] = []>(definition: PagedCacheDefinitionFunction<T, Args>, options?: CacheOptions<PagedCacheState<T>, Args>): CreateCacheResult<PagedCacheState<T>, Args, PagedCache<T, Args>>;
|
|
58
|
+
declare function createPaged<T>(definition: PagedCacheDefinition<T, []>, options?: CacheOptions<PagedCacheState<T>, []>): CreateCacheResult<PagedCacheState<T>, [], PagedCache<T, []>>;
|
|
59
59
|
declare const createPagedCache: typeof createPaged & {
|
|
60
60
|
defaultOptions: CacheOptions<any, any>;
|
|
61
61
|
};
|
|
@@ -118,5 +118,5 @@ declare function set<T, const P>(object: T, path: Constrain<P, SettablePath<T>>,
|
|
|
118
118
|
//#region src/lib/updateHelpers.d.ts
|
|
119
119
|
declare function findOrDefault<T>(array: T[], predicate: (item: T) => boolean, defaultValue: T | (() => T)): T;
|
|
120
120
|
//#endregion
|
|
121
|
-
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 };
|
|
121
|
+
export { AsyncConnectionActions, AsyncUpdateFunction, BaseConnectionActions, BoundStoreMethods, Cache, CacheBundle, CacheFunction, CacheGetOptions, CacheOptions, CacheState, CalculationActions, Cancel, Connection, ConnectionActions, CreateCacheResult, DisposableCancel, Duration, Effect, ErrorState, FetchNextPageOptions, type Hashable, InstanceCache, Listener, PageCacheFunction, PageCacheFunctionProps, PagedCache, PagedCacheDefinition, PagedCacheDefinitionFunction, PagedCacheState, 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 };
|
|
122
122
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
@@ -69,8 +69,9 @@ async function loadPage(cache, helpers, oldPages) {
|
|
|
69
69
|
}
|
|
70
70
|
function createPaged(definition, options) {
|
|
71
71
|
return internalCreate((args, options$1) => {
|
|
72
|
-
|
|
73
|
-
|
|
72
|
+
let currentDefinition = definition;
|
|
73
|
+
if (currentDefinition instanceof Function) currentDefinition = currentDefinition(...args);
|
|
74
|
+
return new PagedCache(currentDefinition, args, options$1);
|
|
74
75
|
}, options);
|
|
75
76
|
}
|
|
76
77
|
const createPagedCache = /* @__PURE__ */ Object.assign(createPaged, { defaultOptions: defaultCacheOptions });
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["definition: PagedCacheDefinition<T, Args>","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<
|
|
1
|
+
{"version":3,"file":"index.js","names":["definition: PagedCacheDefinition<T, Args>","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<PagedCacheState<T>>> {\n /**\n * Previously fetched pages (in order).\n */\n pages: T[];\n /**\n * Last fetched page or null if there are no previously fetched pages.\n */\n prevPage: T | null;\n}\n\nexport interface PageCacheFunction<T> {\n (props: PageCacheFunctionProps<T>): Promise<T | null>;\n}\n\nexport interface PagedCacheDefinition<T, Args extends any[]> {\n /**\n * Function to fetch a page.\n * The function receives the current state of the cache, including previously fetched pages.\n */\n fetchPage: (this: PagedCache<T, Args>, props: PageCacheFunctionProps<T>) => Promise<T | null>;\n /**\n * Optional function to determine the total number of pages - usually based on data in the fetched pages.\n */\n getPageCount?: (this: PagedCache<T, Args>, pages: T[]) => number | null;\n /**\n * Optional function to determine if there are more pages to fetch - usually based on data in the fetched pages.\n * If not provided, it will be assumed there are more pages until getPageCount is provided and the number of fetched pages equals the page count or until fetchPage returns null.\n */\n hasMorePages?: (this: PagedCache<T, Args>, pages: T[]) => boolean;\n}\n\nexport interface PagedCacheDefinitionFunction<T, Args extends any[]> {\n (...args: Args): PagedCacheDefinition<T, Args>;\n}\n\nexport interface PagedCacheState<T> {\n pages: T[];\n hasMore: boolean;\n pageCount: number | null;\n}\n\nexport interface FetchNextPageOptions {\n /**\n * If true, will throw if the cache is in an error state or if another page is being fetched.\n */\n throwOnError?: boolean;\n}\n\nexport class PagedCache<T, Args extends any[] = []> extends Cache<PagedCacheState<T>, Args> {\n constructor(\n public readonly definition: PagedCacheDefinition<T, Args>,\n args: Args,\n options: CacheOptions<PagedCacheState<T>, Args> = {},\n ) {\n super(async (helpers) => loadPage(this, helpers, []), args, options, undefined);\n autobind(PagedCache);\n }\n\n async fetchNextPage({ throwOnError }: FetchNextPageOptions = {}): Promise<void> {\n const { status, isStale, isUpdating, value } = this.state.get();\n\n if (status === 'error') {\n if (!throwOnError) return;\n throw new Error('Cannot fetch next page while cache is in error state');\n }\n\n if (isUpdating) {\n if (!throwOnError) return;\n throw new Error('Cannot fetch next page while another page is being fetched');\n }\n\n if (status === 'pending' || isStale) {\n await this.get().catch(() => {});\n return;\n }\n\n if (!value.hasMore) {\n if (!throwOnError) return;\n throw new Error('No more pages to fetch');\n }\n\n this.stalePromise = this.calculatedValue?.value;\n\n const ac = new AbortController();\n const promise = loadPage(\n this,\n {\n use() {\n throw new Error('Not implemented');\n },\n connect() {\n throw new Error('Not implemented');\n },\n signal: ac.signal,\n },\n value.pages,\n );\n\n this.updateValue(promise);\n\n try {\n await promise;\n } catch (error) {\n if (!throwOnError) return;\n throw error;\n }\n }\n}\n\nasync function loadPage<T, Args extends any[]>(\n cache: PagedCache<T, Args>,\n helpers: CalculationActions<Promise<PagedCacheState<T>>>,\n oldPages: T[],\n) {\n const { fetchPage, hasMorePages, getPageCount } = cache.definition;\n\n const page = await fetchPage.call(cache, {\n ...helpers,\n pages: oldPages,\n prevPage: oldPages.length > 0 ? oldPages[oldPages.length - 1]! : null,\n });\n\n const pages = page === null ? oldPages : oldPages.concat(page);\n const pageCount = getPageCount?.call(cache, pages) ?? null;\n const hasMore = hasMorePages\n ? hasMorePages.call(cache, pages)\n : pageCount !== null\n ? pages.length < pageCount\n : page !== null;\n\n return { pages, hasMore, pageCount };\n}\n\nfunction createPaged<T, Args extends any[] = []>(\n definition: PagedCacheDefinitionFunction<T, Args>,\n options?: CacheOptions<PagedCacheState<T>, Args>,\n): CreateCacheResult<PagedCacheState<T>, Args, PagedCache<T, Args>>;\n\nfunction createPaged<T>(\n definition: PagedCacheDefinition<T, []>,\n options?: CacheOptions<PagedCacheState<T>, []>,\n): CreateCacheResult<PagedCacheState<T>, [], PagedCache<T, []>>;\n\nfunction createPaged<T, Args extends any[] = []>(\n definition: PagedCacheDefinitionFunction<T, Args> | PagedCacheDefinition<T, Args>,\n options?: CacheOptions<PagedCacheState<T>, Args>,\n): CreateCacheResult<PagedCacheState<T>, Args, PagedCache<T, Args>> {\n return internalCreate<PagedCacheState<T>, Args, PagedCache<T, Args>>((args, options) => {\n let currentDefinition = definition;\n if (currentDefinition instanceof Function) {\n currentDefinition = currentDefinition(...args);\n }\n return new PagedCache(currentDefinition, 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":";;;;;;;;;AA2DA,IAAa,aAAb,MAAa,mBAA+C,MAAgC;CAC1F,YACE,AAAgBA,YAChB,MACA,UAAkD,IAClD;AACA,QAAM,OAAO,YAAY,SAAS,MAAM,SAAS,KAAK,MAAM,SAAS;EAJrD;AAKhB,WAAS;;CAGX,MAAM,cAAc,EAAE,iBAAuC,IAAmB;EAC9E,MAAM,EAAE,QAAQ,SAAS,YAAY,UAAU,KAAK,MAAM;AAE1D,MAAI,WAAW,SAAS;AACtB,OAAI,CAAC,aAAc;AACnB,SAAM,IAAI,MAAM;;AAGlB,MAAI,YAAY;AACd,OAAI,CAAC,aAAc;AACnB,SAAM,IAAI,MAAM;;AAGlB,MAAI,WAAW,aAAa,SAAS;AACnC,SAAM,KAAK,MAAM,YAAY;AAC7B;;AAGF,MAAI,CAAC,MAAM,SAAS;AAClB,OAAI,CAAC,aAAc;AACnB,SAAM,IAAI,MAAM;;AAGlB,OAAK,eAAe,KAAK,iBAAiB;EAE1C,MAAM,KAAK,IAAI;EACf,MAAM,UAAU,SACd,MACA;GACE,MAAM;AACJ,UAAM,IAAI,MAAM;;GAElB,UAAU;AACR,UAAM,IAAI,MAAM;;GAElB,QAAQ,GAAG;KAEb,MAAM;AAGR,OAAK,YAAY;AAEjB,MAAI;AACF,SAAM;WACC,OAAO;AACd,OAAI,CAAC,aAAc;AACnB,SAAM;;;;AAKZ,eAAe,SACb,OACA,SACA,UACA;CACA,MAAM,EAAE,WAAW,cAAc,iBAAiB,MAAM;CAExD,MAAM,OAAO,MAAM,UAAU,KAAK,OAAO;EACvC,GAAG;EACH,OAAO;EACP,UAAU,SAAS,SAAS,IAAI,SAAS,SAAS,SAAS,KAAM;;CAGnE,MAAM,QAAQ,SAAS,OAAO,WAAW,SAAS,OAAO;CACzD,MAAM,YAAY,cAAc,KAAK,OAAO,UAAU;CACtD,MAAM,UAAU,eACZ,aAAa,KAAK,OAAO,SACzB,cAAc,OACZ,MAAM,SAAS,YACf,SAAS;AAEf,QAAO;EAAE;EAAO;EAAS;;;AAa3B,SAAS,YACP,YACA,SACkE;AAClE,QAAO,gBAA+D,MAAM,cAAY;EACtF,IAAI,oBAAoB;AACxB,MAAI,6BAA6B,SAC/B,qBAAoB,kBAAkB,GAAG;AAE3C,SAAO,IAAI,WAAW,mBAAmB,MAAMC;IAC9C;;AAGL,MAAaC,mBACK,uBAAO,OAAO,aAAa,EACzC,gBAAgB;;;;ACzKpB,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"}
|