cross-state 0.6.1 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/es/hash.mjs CHANGED
@@ -273,15 +273,6 @@ function set(obj, path, value, rootPath = path) {
273
273
  [key]: update
274
274
  };
275
275
  }
276
- function makeSelector(selector) {
277
- if (!selector) {
278
- return (x) => x;
279
- }
280
- if (selector instanceof Function) {
281
- return selector;
282
- }
283
- return (x) => get(x, selector);
284
- }
285
276
  const getAllProperties = (object) => {
286
277
  const properties = /* @__PURE__ */ new Set();
287
278
  do {
@@ -330,6 +321,15 @@ function forwardError(error) {
330
321
  throw error;
331
322
  });
332
323
  }
324
+ function makeSelector(selector) {
325
+ if (!selector) {
326
+ return (x) => x;
327
+ }
328
+ if (selector instanceof Function) {
329
+ return selector;
330
+ }
331
+ return (x) => get(x, selector);
332
+ }
333
333
  const arrMod = (prop) => function(...args) {
334
334
  const newArr = this.get().slice();
335
335
  const result = newArr[prop](...args);
@@ -473,9 +473,13 @@ class Store {
473
473
  map(_selector, options) {
474
474
  const selector = makeSelector(_selector);
475
475
  const derivedFrom = { store: this, selectors: [_selector] };
476
- return new DerivedStore(({ use }) => {
477
- return selector(use(this, options));
478
- }, derivedFrom);
476
+ return new DerivedStore(
477
+ ({ use }) => {
478
+ return selector(use(this, options));
479
+ },
480
+ this.options,
481
+ derivedFrom
482
+ );
479
483
  }
480
484
  addEffect(effect, retain) {
481
485
  this.effects.set(effect, {
@@ -529,7 +533,7 @@ class Store {
529
533
  const defaultOptions = {};
530
534
  function _store(initialState, options) {
531
535
  if (initialState instanceof Function) {
532
- return new DerivedStore(initialState);
536
+ return derivedStore(initialState, options);
533
537
  }
534
538
  let methods = options == null ? void 0 : options.methods;
535
539
  if (initialState instanceof Map) {
@@ -549,9 +553,10 @@ function _store(initialState, options) {
549
553
  }
550
554
  const store = Object.assign(_store, { defaultOptions });
551
555
  class DerivedStore extends Store {
552
- constructor(calculate, derivedFrom) {
556
+ constructor(calculate, options = {}, derivedFrom) {
553
557
  super(void 0);
554
558
  this.calculate = calculate;
559
+ this.options = options;
555
560
  this.derivedFrom = derivedFrom;
556
561
  this.calculationHelper = new CalculationHelper({
557
562
  calculate: ({ use }) => {
@@ -566,6 +571,7 @@ class DerivedStore extends Store {
566
571
  this.valid = false;
567
572
  }
568
573
  get() {
574
+ this.calculationHelper.check();
569
575
  if (!this.valid) {
570
576
  this.calculationHelper.execute();
571
577
  }
@@ -575,7 +581,7 @@ class DerivedStore extends Store {
575
581
  if (this.derivedFrom && this.derivedFrom.selectors.every((selector) => typeof selector === "string")) {
576
582
  const path = this.derivedFrom.selectors.join(".");
577
583
  if (update instanceof Function) {
578
- const before = get(this.derivedFrom.store, path);
584
+ const before = this.get();
579
585
  update = update(before);
580
586
  }
581
587
  this.derivedFrom.store.update((before) => set(before, path, update));
@@ -583,14 +589,6 @@ class DerivedStore extends Store {
583
589
  throw new Error("Can only updated computed stores that are derived from other stores using string selectors");
584
590
  }
585
591
  }
586
- map(_selector) {
587
- const selector = makeSelector(_selector);
588
- const derivedFrom = this.derivedFrom ?? { store: this, selectors: [] };
589
- const newDerivedFrom = { ...derivedFrom, selectors: derivedFrom.selectors.concat(_selector) };
590
- return new DerivedStore(({ use }) => {
591
- return selector(use(this));
592
- }, newDerivedFrom);
593
- }
594
592
  invalidate() {
595
593
  this.valid = false;
596
594
  if (this.isActive) {
@@ -598,8 +596,8 @@ class DerivedStore extends Store {
598
596
  }
599
597
  }
600
598
  }
601
- function _derivedStore(calculate) {
602
- return new DerivedStore(calculate);
599
+ function _derivedStore(calculate, options) {
600
+ return new DerivedStore(calculate, options);
603
601
  }
604
602
  const derivedStore = Object.assign(_derivedStore, {});
605
603
  function hash(value) {
@@ -1 +1 @@
1
- {"version":3,"file":"hash.mjs","sources":["../../src/lib/queue.ts","../../src/lib/trackingProxy.ts","../../src/lib/calculationHelper.ts","../../src/lib/propAccess.ts","../../src/lib/makeSelector.ts","../../src/lib/bind.ts","../../src/lib/calcDuration.ts","../../src/lib/equals.ts","../../src/lib/forwardError.ts","../../src/lib/storeActions.ts","../../src/lib/throttle.ts","../../src/core/store.ts","../../src/core/derivedStore.ts","../../src/lib/hash.ts"],"sourcesContent":["import type { MaybePromise } from './maybePromise';\n\ntype Action<T> = () => MaybePromise<T>;\n\nexport interface Queue {\n <T>(action: Action<T>): Promise<T>;\n clear: () => void;\n whenDone: Promise<void>;\n}\n\nexport function queue(): Queue {\n const q: { action: Action<any>; resolve: (value: any) => void; reject: (error: unknown) => void }[] = [];\n let promise: Promise<void> | undefined, resolve: (() => void) | undefined;\n let active = false;\n\n const run = async () => {\n if (!active) {\n active = true;\n\n let next;\n while ((next = q.shift())) {\n try {\n let result = next.action();\n if (result instanceof Promise) {\n result = await result;\n }\n next.resolve(result);\n } catch (e) {\n next.reject(e);\n }\n }\n\n active = false;\n resolve?.();\n }\n };\n\n return Object.assign(\n <T>(action: Action<T>) => {\n return new Promise<T>((resolve, reject) => {\n q.push({ action, resolve, reject });\n run();\n });\n },\n {\n clear() {\n q.length = 0;\n resolve?.();\n },\n\n get whenDone() {\n if (!promise) {\n promise = new Promise<void>((r) => {\n resolve = () => {\n promise = undefined;\n resolve = undefined;\n r();\n };\n });\n }\n\n return promise;\n },\n }\n );\n}\n","export type TrackingProxy<T> = [value: T, equals: (newValue: T) => boolean];\ntype Obj = Record<string | symbol, unknown>;\n\nconst ProxyKeys = ['get', 'getOwnPropertyDescriptor', 'getPrototypeOf', 'has', 'isExtensible', 'ownKeys'] as const;\n\nconst isPlainObject = (value: unknown) => typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === Object.prototype;\n\nexport function trackingProxy<T>(value: T): TrackingProxy<T> {\n if (!isPlainObject(value) && !Array.isArray(value)) {\n return [value, (other) => other === value];\n }\n\n const deps = new Array<TrackingProxy<any>[1]>();\n\n const proxy = new Proxy(\n value as T & Obj,\n Object.fromEntries(\n ProxyKeys.map((key) => [\n key,\n (value: T & Obj, ...args: any[]) => {\n const fn = Reflect[key] as any;\n const [proxiedValue, equals] = trackingProxy(fn(value, ...args));\n\n deps.push((otherValue) => {\n if (!isPlainObject(otherValue) && !Array.isArray(otherValue)) {\n return false;\n }\n\n return equals(fn(otherValue, ...args));\n });\n\n return proxiedValue;\n },\n ])\n )\n );\n\n return [proxy, (other) => !!other && deps.every((equals) => equals(other))];\n}\n","import type { Cancel, UpdateFrom, Use, UseFetch } from '@core/commonTypes';\nimport type { Store } from '@core/store';\nimport type { MaybePromise } from './maybePromise';\nimport { queue } from './queue';\nimport { trackingProxy } from './trackingProxy';\n\nexport class CalculationHelper<T> {\n private current?: {\n cancel: Cancel;\n check: () => void;\n };\n\n constructor(\n private options: {\n calculate: (fns: {\n use: Use;\n useFetch: UseFetch;\n updateValue: (update: UpdateFrom<MaybePromise<T>, [T | undefined]>) => void;\n updateError: (error: unknown) => void;\n }) => Cancel | void;\n addEffect: (effect: () => Cancel | void) => Cancel;\n getValue: () => T | undefined;\n setValue?: (value: T) => void;\n setError?: (error: unknown) => void;\n onInvalidate?: () => void;\n }\n ) {\n options.addEffect(() => {\n if (this.current) {\n this.current.check();\n } else {\n this.execute();\n }\n });\n }\n\n execute() {\n this.stop();\n\n const { calculate, addEffect, getValue, setValue, setError, onInvalidate } = this.options;\n const checks = new Array<() => boolean>();\n const deps = new Map<Store<any>, { on: () => void; off: () => void }>();\n const q = queue();\n let isActive = false;\n let isCancled = false;\n\n const cancelEffect = addEffect(() => {\n isActive = true;\n\n for (const dep of deps.values()) {\n dep.on();\n }\n\n return () => {\n isActive = false;\n\n for (const dep of deps.values()) {\n dep.off();\n }\n };\n });\n\n const cancel = () => {\n isCancled = true;\n cancelSubscription?.();\n cancelEffect();\n delete this.current;\n };\n\n const check = () => {\n if (!checks.every((check) => check())) {\n cancel();\n onInvalidate?.();\n }\n };\n\n const use: Use = (store, { disableProxy } = {}) => {\n if (isCancled) {\n return store.get();\n }\n\n let value = store.get();\n let equals = (newValue: any) => {\n return newValue === value;\n };\n\n if (!disableProxy) {\n [value, equals] = trackingProxy(value);\n }\n\n let sub: Cancel | undefined;\n\n const dep = {\n on() {\n this.off();\n\n sub = store.sub(check, { runNow: false });\n },\n off() {\n sub?.();\n sub = undefined;\n },\n };\n\n if (isActive) {\n dep.on();\n }\n\n checks.push(() => equals(store.get()));\n deps.set(store, dep);\n\n return value;\n };\n\n const useFetch: UseFetch = (store) => {\n if (isCancled) {\n return store.fetch();\n }\n\n const value = store.fetch();\n const ref = store.get().ref;\n\n let sub: Cancel | undefined;\n\n const dep = {\n on() {\n this.off();\n sub = store.sub(check, { runNow: false });\n },\n off() {\n sub?.();\n sub = undefined;\n },\n };\n\n if (isActive) {\n dep.on();\n }\n\n checks.push(() => {\n return store.get().ref === ref;\n });\n deps.set(store, dep);\n\n return value;\n };\n\n const updateValue = (update: UpdateFrom<MaybePromise<T>, [T | undefined]>) =>\n q(async () => {\n if (isCancled) {\n return;\n }\n\n if (update instanceof Function) {\n try {\n update = update(getValue());\n } catch (error) {\n setError?.(error);\n return;\n }\n }\n\n if (update instanceof Promise) {\n try {\n update = await update;\n } catch (error) {\n if (!isCancled) {\n setError?.(error);\n }\n return;\n }\n }\n\n if (!isCancled) {\n setValue?.(update);\n }\n });\n\n const updateError = (error: unknown) =>\n q(() => {\n if (!isCancled) {\n setError?.(error);\n }\n });\n\n let cancelSubscription: Cancel | void;\n try {\n cancelSubscription = calculate({ use, useFetch, updateValue, updateError });\n } catch (error) {\n setError?.(error);\n }\n\n this.current = { cancel, check };\n }\n\n stop() {\n this.current?.cancel();\n }\n\n check() {\n this.current?.check();\n }\n}\n","import type { Update } from '../core/commonTypes';\n\ntype FilterKey<T> = T extends string | number ? T : never;\ntype FilterString<T> = T extends string ? T : never;\n\nexport type Obj = Record<string | number, unknown>;\nexport type Arr = readonly unknown[];\n\ntype GetKeys<T> = T extends Arr\n ? T extends readonly [] // special case empty tuple => no keys\n ? never\n : '0' extends keyof T // any tuple with at least one element\n ? keyof T & `${number}`\n : number // other array\n : keyof T; // not an array\n\nexport type Path<T> = 0 extends 1 & T\n ? string\n : T extends never\n ? never\n : T extends Obj | Arr\n ? FilterString<\n keyof {\n [K in FilterKey<GetKeys<T>> as `${K}` | (T[K] extends Obj | Arr | undefined | null ? `${K}.${Path<NonNullable<T[K]>>}` : never)]: 0;\n }\n >\n : never;\n\nexport type Value<T, P extends string> = P extends `${infer K}.${infer Rest}`\n ? T[K & keyof T] extends Obj | Arr\n ? Value<T[K & keyof T], Rest>\n : T[K & keyof T] extends Obj | Arr | undefined | null\n ? Value<NonNullable<T[K & keyof T]>, Rest> | undefined\n : never\n : T[P & keyof T];\n\nexport function get<T, P extends Path<T>>(obj: T, path: P): Value<T, P> {\n if (path === '') {\n return obj as any;\n }\n\n if (!(obj instanceof Object)) {\n throw new Error(`Could not get ${path} of ${obj}`);\n }\n\n const index = path.indexOf('.');\n\n if (index >= 0) {\n const key = path.slice(0, index);\n const rest = path.slice(index + 1);\n const subObj = (obj as Obj | Arr)[key as any];\n\n if (!subObj) {\n return undefined as any;\n }\n\n return get(subObj as Record<string, unknown>, rest) as any;\n }\n\n return (obj as Obj | Arr)[path as any] as any;\n}\n\nexport function set<T, P extends Path<T>>(obj: T, path: P, value: Update<Value<T, P>>, rootPath = path): T {\n if (path === '') {\n return value as any;\n }\n\n if (!(obj instanceof Object)) {\n throw new Error(`Could not set ${path} of ${obj}`);\n }\n\n const index = path.indexOf('.');\n let key, update;\n\n if (index >= 0) {\n key = path.slice(0, index);\n const rest = path.slice(index + 1);\n const subObj = (obj as Obj | Arr)[key as any];\n\n if (!subObj) {\n const prefix = rootPath.slice(0, -rest.length - 1);\n throw Error(`Cannot set ${rootPath} because ${prefix} is ${subObj}`);\n }\n\n update = set(subObj as Record<string, unknown>, rest, value, rootPath);\n } else {\n key = path;\n update = value instanceof Function ? value((obj as any)[key]) : value;\n }\n\n if (Array.isArray(obj)) {\n const copy = Array.from(obj);\n copy[key as any] = update;\n return copy as any;\n }\n\n return {\n ...obj,\n [key]: update,\n };\n}\n","import { get } from './propAccess';\n\nexport function makeSelector<T, S>(selector?: ((value: T) => S) | string): (value: T) => S {\n if (!selector) {\n return (x) => x as any;\n }\n\n if (selector instanceof Function) {\n return selector;\n }\n\n return (x) => get(x, selector as any) as any;\n}\n","const getAllProperties = (object: any) => {\n const properties = new Set<[any, string | symbol]>();\n\n do {\n for (const key of Reflect.ownKeys(object)) {\n properties.add([object, key]);\n }\n } while ((object = Reflect.getPrototypeOf(object)) && object !== Object.prototype);\n\n return properties;\n};\n\nexport function bind(self: any) {\n for (const [object, key] of getAllProperties(self.constructor.prototype)) {\n if (key === 'constructor') {\n continue;\n }\n\n const descriptor = Reflect.getOwnPropertyDescriptor(object, key);\n if (descriptor && typeof descriptor.value === 'function') {\n self[key] = self[key].bind(self);\n }\n }\n}\n","import type { Duration } from '../core/commonTypes';\n\nexport const calcDuration = (t: Duration) => {\n if (typeof t === 'number') return t;\n return (\n (t.milliseconds ?? 0) +\n (t.seconds ?? 0) * 1000 +\n (t.minutes ?? 0) * 60 * 1000 +\n (t.hours ?? 0) * 60 * 60 * 1000 +\n (t.days ?? 0) * 24 * 60 * 60 * 1000\n );\n};\n","export const defaultEquals = (a: any, b: any) => a === b;\n\nexport const simpleShallowEquals = (a: any, b: any): boolean => {\n if (a === b) {\n return true;\n }\n\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((value, i) => value === b[i]);\n }\n\n if (typeof a === 'object' && typeof b === 'object') {\n if (a === null || b === null) {\n return false;\n }\n\n const e1 = Object.entries(a);\n const e2 = Object.entries(b);\n return e1.length === e2.length && e1.every(([key, value]) => value === b[key]);\n }\n\n return false;\n};\n\nexport const simpleDeepEquals = (a: any, b: any): boolean => {\n if (a === b) {\n return true;\n }\n\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((value, i) => simpleDeepEquals(value, b[i]));\n }\n\n if (typeof a === 'object' && typeof b === 'object') {\n if (a === null || b === null) {\n return false;\n }\n\n const e1 = Object.entries(a);\n const e2 = Object.entries(b);\n return e1.length === e2.length && e1.every(([key, value]) => simpleDeepEquals(value, b[key]));\n }\n\n return false;\n};\n","export function forwardError(error: unknown) {\n setTimeout(() => {\n throw error;\n });\n}\n","import type { Update, UpdateFrom } from '@core/commonTypes';\nimport type { Store } from '../core/store';\n\ntype Fn = (...args: any) => any;\n\ntype OptionalPropertyOf<T> = Exclude<\n {\n [K in keyof T]: T extends Record<K, T[K]> ? never : K;\n }[keyof T],\n undefined\n>;\n\nconst arrMod = <P extends keyof Array<any>>(prop: P) =>\n function <V>(\n this: Store<Array<V>>,\n ...args: Array<V>[P] extends Fn ? Parameters<Array<V>[P]> : never\n ): Array<V>[P] extends Fn ? ReturnType<Array<V>[P]> : never {\n const newArr = this.get().slice();\n const result = (newArr[prop] as Fn)(...(args as any));\n this.update(newArr);\n return result;\n };\n\nexport const arrayActions = {\n splice: arrMod('splice'),\n push: arrMod('push'),\n pop: arrMod('pop'),\n shift: arrMod('shift'),\n unshift: arrMod('unshift'),\n reverse: arrMod('reverse'),\n sort: arrMod('sort'),\n};\n\nexport const recordActions = {\n set<T extends Record<any, any>, K extends keyof T>(this: Store<T>, key: K, value: Update<T[K]>) {\n if (value instanceof Function) {\n value = value(this.get()[key]);\n }\n\n this.update({ ...this.get(), [key]: value });\n return this;\n },\n\n delete<T extends Record<any, any>, K extends OptionalPropertyOf<T>>(this: Store<T>, key: K) {\n const copy = { ...this.get() };\n delete copy[key];\n this.update(copy);\n },\n\n clear<T extends Record<any, any>>(this: Store<Partial<T>>) {\n this.update({} as T);\n },\n};\n\nexport const mapActions = {\n set<K, V>(this: Store<Map<K, V>>, key: K, value: UpdateFrom<V, [V | undefined]>) {\n if (value instanceof Function) {\n value = value(this.get().get(key));\n }\n\n const newMap = new Map(this.get());\n newMap.set(key, value);\n this.update(newMap);\n return this;\n },\n\n delete<K, V>(this: Store<Map<K, V>>, key: K) {\n const newMap = new Map(this.get());\n const result = newMap.delete(key);\n this.update(newMap);\n return result;\n },\n\n clear<K, V>(this: Store<Map<K, V>>) {\n this.update(new Map());\n },\n};\n\nexport const setActions = {\n add<T>(this: Store<Set<T>>, value: T) {\n const newSet = new Set(this.get());\n newSet.add(value);\n this.update(newSet);\n },\n\n delete<T>(this: Store<Set<T>>, value: T) {\n const newSet = new Set(this.get());\n newSet.delete(value);\n this.update(newSet);\n },\n\n clear<T>(this: Store<Set<T>>) {\n this.update(new Set());\n },\n};\n","export function throttle<Args extends any[]>(fn: (...args: Args) => void, ms: number): (...args: Args) => void {\n let t = 0;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n\n return (...args: Args) => {\n if (timeout !== undefined) {\n clearTimeout(timeout);\n }\n\n const dt = t + ms - Date.now();\n if (dt <= 0) {\n fn(...args);\n t = Date.now();\n return;\n }\n\n timeout = setTimeout(() => {\n fn(...args);\n t = Date.now();\n }, dt);\n };\n}\n","import { bind } from '@lib/bind';\nimport { calcDuration } from '@lib/calcDuration';\nimport { defaultEquals } from '@lib/equals';\nimport { forwardError } from '@lib/forwardError';\nimport { makeSelector } from '@lib/makeSelector';\nimport type { Path, Value } from '@lib/propAccess';\nimport { arrayActions, mapActions, recordActions, setActions } from '@lib/storeActions';\nimport { throttle } from '@lib/throttle';\nimport type { Cancel, Duration, Effect, Listener, Selector, SubscribeOptions, Update, Use, UseOptions } from './commonTypes';\nimport { DerivedStore } from './derivedStore';\n\nexport type StoreActions = Record<string, (...args: any[]) => any>;\n\nexport type BoundStoreActions<T, Actions extends StoreActions> = Actions & ThisType<Store<T> & Actions>;\n\nexport interface StoreOptions {\n retain?: number;\n}\n\nexport interface StoreOptionsWithActions<T, Actions extends StoreActions> extends StoreOptions {\n methods?: Actions & ThisType<Store<T> & Actions & StandardActions<T>>;\n}\n\ntype StandardActions<T> = T extends Map<any, any>\n ? typeof mapActions\n : T extends Set<any>\n ? typeof setActions\n : T extends Array<any>\n ? typeof arrayActions\n : T extends Record<any, any>\n ? typeof recordActions\n : Record<string, never>;\n\ntype StoreWithActions<T, Actions extends StoreActions> = Store<T> &\n Omit<BoundStoreActions<T, Actions>, keyof Store<T>> &\n StandardActions<T>;\n\nconst noop = () => undefined;\n\nexport class Store<T> {\n protected value = this.initialValue;\n protected listeners = new Set<Listener>();\n protected effects = new Map<Effect, { handle?: Cancel; retain?: number; timeout?: ReturnType<typeof setTimeout> }>();\n protected notifyId = {};\n\n constructor(protected readonly initialValue: T, protected readonly options: StoreOptions = {}) {\n bind(this);\n }\n\n get(): T {\n return this.value;\n }\n\n update(update: Update<T>): void {\n if (update instanceof Function) {\n update = update(this.get());\n }\n\n this.value = update;\n this.notify();\n }\n\n sub(listener: Listener<T>, options?: SubscribeOptions): Cancel {\n const { runNow = true, throttle: throttleOption, equals = defaultEquals } = options ?? {};\n\n let compareToValue = this.get();\n let previousValue: T | undefined;\n let hasRun = false;\n\n let innerListener = (force?: boolean | void) => {\n const value = this.get();\n\n if (!force && equals(value, compareToValue)) {\n return;\n }\n\n compareToValue = value;\n const _previousValue = previousValue;\n previousValue = value;\n hasRun = true;\n\n try {\n listener(value, _previousValue);\n } catch (error) {\n forwardError(error);\n }\n };\n\n if (throttleOption) {\n innerListener = throttle(innerListener, calcDuration(throttleOption));\n }\n\n this.listeners.add(innerListener);\n this.onSubscribe();\n\n if (runNow && !hasRun) {\n innerListener(true);\n }\n\n return () => {\n this.listeners.delete(innerListener);\n this.onUnsubscribe();\n };\n }\n\n map<S>(selector: Selector<T, S>, options?: UseOptions): DerivedStore<S>;\n map<P extends Path<T>>(selector: P, options?: UseOptions): DerivedStore<Value<T, P>>;\n map(_selector: Selector<T, any> | string, options?: UseOptions): DerivedStore<any> {\n const selector = makeSelector(_selector);\n const derivedFrom = { store: this, selectors: [_selector] };\n\n return new DerivedStore(({ use }) => {\n return selector(use(this, options));\n }, derivedFrom);\n }\n\n /** Add an effect that will be executed when the store becomes active, which means when it has at least one subscriber.\n * @param effect\n * If there is already a subscriber, the effect will be executed immediately.\n * Otherweise it will be executed as soon as the first subscription is created.\n * Every time all subscriptions are removed and the first is created again, the effect will be executed again.\n * @param retain\n * If provided, delay tearing down effects when the last subscriber is removed. This is useful if a short gap in subscriber coverage is supposed to be ignored. E.g. when switching pages, the old page might unsubscribe, while the new page subscribes immediately after.\n * @returns\n * The effect can return a teardown callback, which will be executed when the last subscription is removed and potentially the ratain time has passed.\n */\n addEffect(effect: Effect, retain?: Duration) {\n this.effects.set(effect, {\n handle: this.listeners.size > 0 ? effect() ?? noop : undefined,\n retain: retain !== undefined ? calcDuration(retain) : undefined,\n });\n\n return () => {\n const { handle, timeout } = this.effects.get(effect) ?? {};\n handle?.();\n timeout !== undefined && clearTimeout(timeout);\n this.effects.delete(effect);\n };\n }\n\n /** Return whether the store is currently active, which means whether it has at least one subscriber. */\n get isActive() {\n return this.listeners.size > 0;\n }\n\n protected onSubscribe() {\n if (this.listeners.size > 1) return;\n\n for (const [effect, { handle, retain, timeout }] of this.effects.entries()) {\n timeout !== undefined && clearTimeout(timeout);\n\n this.effects.set(effect, {\n handle: handle ?? effect() ?? noop,\n retain,\n timeout: undefined,\n });\n }\n }\n\n protected onUnsubscribe() {\n if (this.listeners.size > 0) return;\n\n for (const [effect, { handle, retain, timeout }] of this.effects.entries()) {\n !retain && handle?.();\n timeout !== undefined && clearTimeout(timeout);\n\n this.effects.set(effect, {\n handle: retain ? handle : undefined,\n retain,\n timeout: retain && handle ? setTimeout(handle, retain) : undefined,\n });\n }\n }\n\n protected notify() {\n const n = (this.notifyId = {});\n for (const listener of [...this.listeners]) {\n listener();\n if (n !== this.notifyId) break;\n }\n }\n}\n\nconst defaultOptions: StoreOptions = {};\n\nfunction _store<T>(calculate: (this: { use: Use }, fns: { use: Use }) => T, options?: StoreOptions): DerivedStore<T>;\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction _store<T, Actions extends StoreActions = {}>(\n initialState: T,\n options?: StoreOptionsWithActions<T, Actions>\n): StoreWithActions<T, Actions>;\nfunction _store<T, Actions extends StoreActions>(\n initialState: T | ((this: { use: Use }, fns: { use: Use }) => T),\n options?: StoreOptionsWithActions<T, Actions>\n): StoreWithActions<T, Actions> | DerivedStore<T> {\n if (initialState instanceof Function) {\n return new DerivedStore(initialState);\n }\n\n let methods: StoreActions | undefined = options?.methods;\n\n if (initialState instanceof Map) {\n methods = { ...mapActions, ...methods };\n } else if (initialState instanceof Set) {\n methods = { ...setActions, ...methods };\n } else if (Array.isArray(initialState)) {\n methods = { ...arrayActions, ...methods };\n } else if (initialState instanceof Object) {\n methods = { ...recordActions, ...methods };\n }\n\n const store = new Store(initialState, options);\n\n const boundActions = Object.fromEntries(\n Object.entries(methods ?? ({} as BoundStoreActions<T, any>))\n .filter(([name]) => !(name in store))\n .map(([name, fn]) => [name, (fn as any).bind(store)])\n ) as BoundStoreActions<T, any>;\n\n return Object.assign(store, boundActions);\n}\n\nexport const store = Object.assign(_store, { defaultOptions });\n","import { CalculationHelper } from '@lib/calculationHelper';\nimport { makeSelector } from '@lib/makeSelector';\nimport type { Path, Value } from '@lib/propAccess';\nimport { get, set } from '@lib/propAccess';\nimport type { Cancel, Selector, Update, Use } from './commonTypes';\nimport { Store } from './store';\n\nexport class DerivedStore<T> extends Store<T> {\n calculationHelper = new CalculationHelper({\n calculate: ({ use }) => {\n const value = this.calculate.apply({ use }, [{ use }]);\n this.valid = true;\n super.update(value);\n },\n\n addEffect: this.addEffect,\n getValue: () => this.value,\n onInvalidate: this.invalidate,\n });\n\n protected valid = false;\n protected check?: () => void;\n protected cancel?: Cancel;\n\n constructor(\n protected calculate: (this: { use: Use }, fns: { use: Use }) => T,\n protected derivedFrom?: { store: Store<any>; selectors: (Selector<any, any> | string)[] }\n ) {\n super(undefined as T);\n }\n\n get(): T {\n if (!this.valid) {\n this.calculationHelper.execute();\n }\n\n return super.get();\n }\n\n update(update: Update<T>): void {\n if (this.derivedFrom && this.derivedFrom.selectors.every((selector) => typeof selector === 'string')) {\n const path = this.derivedFrom.selectors.join('.');\n\n if (update instanceof Function) {\n const before = get<any, any>(this.derivedFrom.store, path) as T;\n update = update(before);\n }\n\n this.derivedFrom.store.update((before: any) => set<any, any>(before, path, update));\n } else {\n throw new Error('Can only updated computed stores that are derived from other stores using string selectors');\n }\n }\n\n map<S>(selector: Selector<T, S>): DerivedStore<S>;\n map<P extends Path<T>>(selector: P): DerivedStore<Value<T, P>>;\n map(_selector: string | Selector<T, any>): DerivedStore<any> {\n const selector = makeSelector(_selector);\n\n const derivedFrom = this.derivedFrom ?? { store: this, selectors: [] };\n const newDerivedFrom = { ...derivedFrom, selectors: derivedFrom.selectors.concat(_selector) };\n\n return new DerivedStore(({ use }) => {\n return selector(use(this));\n }, newDerivedFrom);\n }\n\n protected invalidate() {\n this.valid = false;\n\n if (this.isActive) {\n this.calculationHelper.execute();\n }\n }\n}\n\nfunction _derivedStore<T>(calculate: (this: { use: Use }, fns: { use: Use }) => T) {\n return new DerivedStore(calculate);\n}\n\nexport const derivedStore = Object.assign(_derivedStore, {});\n","export function hash(value: unknown): string {\n if (value instanceof Set) {\n return `s[${[...value].map(hash).sort().join(',')}]`;\n }\n\n if (value instanceof Map) {\n return `m[${[...value.entries()].map(hash).sort().join(',')}]`;\n }\n\n if (value instanceof Array) {\n return `[${value.map(hash).join(',')}]`;\n }\n\n if (value instanceof Object) {\n return `o[${Object.entries(value).map(hash).sort().join(',')}]`;\n }\n\n return JSON.stringify(value);\n}\n"],"names":["resolve","value","check","store"],"mappings":"AAUO,SAAS,QAAe;AAC7B,QAAM,IAAgG,CAAA;AACtG,MAAI,SAAoC;AACxC,MAAI,SAAS;AAEb,QAAM,MAAM,YAAY;AACtB,QAAI,CAAC,QAAQ;AACF,eAAA;AAEL,UAAA;AACI,aAAA,OAAO,EAAE,SAAU;AACrB,YAAA;AACE,cAAA,SAAS,KAAK;AAClB,cAAI,kBAAkB,SAAS;AAC7B,qBAAS,MAAM;AAAA,UACjB;AACA,eAAK,QAAQ,MAAM;AAAA,iBACZ;AACP,eAAK,OAAO,CAAC;AAAA,QACf;AAAA,MACF;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AA,IAAI,MAAM,4FAA4F;AAAA,IAC9G;AAAA,EACF;AAAA,EAIA,IAAI,WAAyD;AACrD,UAAA,WAAW,aAAa,SAAS;AAEjC,UAAA,cAAc,KAAK,eAAe,EAAE,OAAO,MAAM,WAAW,CAAA;AAC5D,UAAA,iBAAiB,EAAE,GAAG,aAAa,WAAW,YAAY,UAAU,OAAO,SAAS;AAE1F,WAAO,IAAI,aAAa,CAAC,EAAE,UAAU;AAC5B,aAAA,SAAS,IAAI,IAAI,CAAC;AAAA,OACxB,cAAc;AAAA,EACnB;AAAA,EAEU,aAAa;AACrB,SAAK,QAAQ;AAEb,QAAI,KAAK,UAAU;AACjB,WAAK,kBAAkB;IACzB;AAAA,EACF;AACF;AAEA,SAAS,cAAiB,WAAyD;AAC1E,SAAA,IAAI,aAAa,SAAS;AACnC;AAEO,MAAM,eAAe,OAAO,OAAO,eAAe,CAAE,CAAA;AChFpD,SAAS,KAAK,OAAwB;AAC3C,MAAI,iBAAiB,KAAK;AACjB,WAAA,KAAK,CAAC,GAAG,KAAK,EAAE,IAAI,IAAI,EAAE,KAAO,EAAA,KAAK,GAAG;AAAA,EAClD;AAEA,MAAI,iBAAiB,KAAK;AACxB,WAAO,KAAK,CAAC,GAAG,MAAM,QAAS,CAAA,EAAE,IAAI,IAAI,EAAE,KAAK,EAAE,KAAK,GAAG;AAAA,EAC5D;AAEA,MAAI,iBAAiB,OAAO;AAC1B,WAAO,IAAI,MAAM,IAAI,IAAI,EAAE,KAAK,GAAG;AAAA,EACrC;AAEA,MAAI,iBAAiB,QAAQ;AACpB,WAAA,KAAK,OAAO,QAAQ,KAAK,EAAE,IAAI,IAAI,EAAE,KAAA,EAAO,KAAK,GAAG;AAAA,EAC7D;AAEO,SAAA,KAAK,UAAU,KAAK;AAC7B;"}
1
+ {"version":3,"file":"hash.mjs","sources":["../../src/lib/queue.ts","../../src/lib/trackingProxy.ts","../../src/lib/calculationHelper.ts","../../src/lib/propAccess.ts","../../src/lib/bind.ts","../../src/lib/calcDuration.ts","../../src/lib/equals.ts","../../src/lib/forwardError.ts","../../src/lib/makeSelector.ts","../../src/lib/storeActions.ts","../../src/lib/throttle.ts","../../src/core/store.ts","../../src/core/derivedStore.ts","../../src/lib/hash.ts"],"sourcesContent":["import type { MaybePromise } from './maybePromise';\n\ntype Action<T> = () => MaybePromise<T>;\n\nexport interface Queue {\n <T>(action: Action<T>): Promise<T>;\n clear: () => void;\n whenDone: Promise<void>;\n}\n\nexport function queue(): Queue {\n const q: { action: Action<any>; resolve: (value: any) => void; reject: (error: unknown) => void }[] = [];\n let promise: Promise<void> | undefined, resolve: (() => void) | undefined;\n let active = false;\n\n const run = async () => {\n if (!active) {\n active = true;\n\n let next;\n while ((next = q.shift())) {\n try {\n let result = next.action();\n if (result instanceof Promise) {\n result = await result;\n }\n next.resolve(result);\n } catch (e) {\n next.reject(e);\n }\n }\n\n active = false;\n resolve?.();\n }\n };\n\n return Object.assign(\n <T>(action: Action<T>) => {\n return new Promise<T>((resolve, reject) => {\n q.push({ action, resolve, reject });\n run();\n });\n },\n {\n clear() {\n q.length = 0;\n resolve?.();\n },\n\n get whenDone() {\n if (!promise) {\n promise = new Promise<void>((r) => {\n resolve = () => {\n promise = undefined;\n resolve = undefined;\n r();\n };\n });\n }\n\n return promise;\n },\n }\n );\n}\n","export type TrackingProxy<T> = [value: T, equals: (newValue: T) => boolean];\ntype Obj = Record<string | symbol, unknown>;\n\nconst ProxyKeys = ['get', 'getOwnPropertyDescriptor', 'getPrototypeOf', 'has', 'isExtensible', 'ownKeys'] as const;\n\nconst isPlainObject = (value: unknown) => typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === Object.prototype;\n\nexport function trackingProxy<T>(value: T): TrackingProxy<T> {\n if (!isPlainObject(value) && !Array.isArray(value)) {\n return [value, (other) => other === value];\n }\n\n const deps = new Array<TrackingProxy<any>[1]>();\n\n const proxy = new Proxy(\n value as T & Obj,\n Object.fromEntries(\n ProxyKeys.map((key) => [\n key,\n (value: T & Obj, ...args: any[]) => {\n const fn = Reflect[key] as any;\n const [proxiedValue, equals] = trackingProxy(fn(value, ...args));\n\n deps.push((otherValue) => {\n if (!isPlainObject(otherValue) && !Array.isArray(otherValue)) {\n return false;\n }\n\n return equals(fn(otherValue, ...args));\n });\n\n return proxiedValue;\n },\n ])\n )\n );\n\n return [proxy, (other) => !!other && deps.every((equals) => equals(other))];\n}\n","import type { Cancel, UpdateFrom, Use, UseFetch } from '@core/commonTypes';\nimport type { Store } from '@core/store';\nimport type { MaybePromise } from './maybePromise';\nimport { queue } from './queue';\nimport { trackingProxy } from './trackingProxy';\n\nexport class CalculationHelper<T> {\n private current?: {\n cancel: Cancel;\n check: () => void;\n };\n\n constructor(\n private options: {\n calculate: (fns: {\n use: Use;\n useFetch: UseFetch;\n updateValue: (update: UpdateFrom<MaybePromise<T>, [T | undefined]>) => void;\n updateError: (error: unknown) => void;\n }) => Cancel | void;\n addEffect: (effect: () => Cancel | void) => Cancel;\n getValue: () => T | undefined;\n setValue?: (value: T) => void;\n setError?: (error: unknown) => void;\n onInvalidate?: () => void;\n }\n ) {\n options.addEffect(() => {\n if (this.current) {\n this.current.check();\n } else {\n this.execute();\n }\n });\n }\n\n execute() {\n this.stop();\n\n const { calculate, addEffect, getValue, setValue, setError, onInvalidate } = this.options;\n const checks = new Array<() => boolean>();\n const deps = new Map<Store<any>, { on: () => void; off: () => void }>();\n const q = queue();\n let isActive = false;\n let isCancled = false;\n\n const cancelEffect = addEffect(() => {\n isActive = true;\n\n for (const dep of deps.values()) {\n dep.on();\n }\n\n return () => {\n isActive = false;\n\n for (const dep of deps.values()) {\n dep.off();\n }\n };\n });\n\n const cancel = () => {\n isCancled = true;\n cancelSubscription?.();\n cancelEffect();\n delete this.current;\n };\n\n const check = () => {\n if (!checks.every((check) => check())) {\n cancel();\n onInvalidate?.();\n }\n };\n\n const use: Use = (store, { disableProxy } = {}) => {\n if (isCancled) {\n return store.get();\n }\n\n let value = store.get();\n let equals = (newValue: any) => {\n return newValue === value;\n };\n\n if (!disableProxy) {\n [value, equals] = trackingProxy(value);\n }\n\n let sub: Cancel | undefined;\n\n const dep = {\n on() {\n this.off();\n\n sub = store.sub(check, { runNow: false });\n },\n off() {\n sub?.();\n sub = undefined;\n },\n };\n\n if (isActive) {\n dep.on();\n }\n\n checks.push(() => equals(store.get()));\n deps.set(store, dep);\n\n return value;\n };\n\n const useFetch: UseFetch = (store) => {\n if (isCancled) {\n return store.fetch();\n }\n\n const value = store.fetch();\n const ref = store.get().ref;\n\n let sub: Cancel | undefined;\n\n const dep = {\n on() {\n this.off();\n sub = store.sub(check, { runNow: false });\n },\n off() {\n sub?.();\n sub = undefined;\n },\n };\n\n if (isActive) {\n dep.on();\n }\n\n checks.push(() => {\n return store.get().ref === ref;\n });\n deps.set(store, dep);\n\n return value;\n };\n\n const updateValue = (update: UpdateFrom<MaybePromise<T>, [T | undefined]>) =>\n q(async () => {\n if (isCancled) {\n return;\n }\n\n if (update instanceof Function) {\n try {\n update = update(getValue());\n } catch (error) {\n setError?.(error);\n return;\n }\n }\n\n if (update instanceof Promise) {\n try {\n update = await update;\n } catch (error) {\n if (!isCancled) {\n setError?.(error);\n }\n return;\n }\n }\n\n if (!isCancled) {\n setValue?.(update);\n }\n });\n\n const updateError = (error: unknown) =>\n q(() => {\n if (!isCancled) {\n setError?.(error);\n }\n });\n\n let cancelSubscription: Cancel | void;\n try {\n cancelSubscription = calculate({ use, useFetch, updateValue, updateError });\n } catch (error) {\n setError?.(error);\n }\n\n this.current = { cancel, check };\n }\n\n stop() {\n this.current?.cancel();\n }\n\n check() {\n this.current?.check();\n }\n}\n","import type { Update } from '../core/commonTypes';\n\ntype FilterKey<T> = T extends string | number ? T : never;\ntype FilterString<T> = T extends string ? T : never;\n\nexport type Obj = Record<string | number, unknown>;\nexport type Arr = readonly unknown[];\n\ntype GetKeys<T> = T extends Arr\n ? T extends readonly [] // special case empty tuple => no keys\n ? never\n : '0' extends keyof T // any tuple with at least one element\n ? keyof T & `${number}`\n : number // other array\n : keyof T; // not an array\n\nexport type Path<T> = 0 extends 1 & T\n ? string\n : T extends never\n ? never\n : T extends Obj | Arr\n ? FilterString<\n keyof {\n [K in FilterKey<GetKeys<T>> as `${K}` | (T[K] extends Obj | Arr | undefined | null ? `${K}.${Path<NonNullable<T[K]>>}` : never)]: 0;\n }\n >\n : never;\n\nexport type Value<T, P extends string> = P extends `${infer K}.${infer Rest}`\n ? T[K & keyof T] extends Obj | Arr\n ? Value<T[K & keyof T], Rest>\n : T[K & keyof T] extends Obj | Arr | undefined | null\n ? Value<NonNullable<T[K & keyof T]>, Rest> | undefined\n : never\n : T[P & keyof T];\n\nexport function get<T, P extends Path<T>>(obj: T, path: P): Value<T, P> {\n if (path === '') {\n return obj as any;\n }\n\n if (!(obj instanceof Object)) {\n throw new Error(`Could not get ${path} of ${obj}`);\n }\n\n const index = path.indexOf('.');\n\n if (index >= 0) {\n const key = path.slice(0, index);\n const rest = path.slice(index + 1);\n const subObj = (obj as Obj | Arr)[key as any];\n\n if (!subObj) {\n return undefined as any;\n }\n\n return get(subObj as Record<string, unknown>, rest) as any;\n }\n\n return (obj as Obj | Arr)[path as any] as any;\n}\n\nexport function set<T, P extends Path<T>>(obj: T, path: P, value: Update<Value<T, P>>, rootPath = path): T {\n if (path === '') {\n return value as any;\n }\n\n if (!(obj instanceof Object)) {\n throw new Error(`Could not set ${path} of ${obj}`);\n }\n\n const index = path.indexOf('.');\n let key, update;\n\n if (index >= 0) {\n key = path.slice(0, index);\n const rest = path.slice(index + 1);\n const subObj = (obj as Obj | Arr)[key as any];\n\n if (!subObj) {\n const prefix = rootPath.slice(0, -rest.length - 1);\n throw Error(`Cannot set ${rootPath} because ${prefix} is ${subObj}`);\n }\n\n update = set(subObj as Record<string, unknown>, rest, value, rootPath);\n } else {\n key = path;\n update = value instanceof Function ? value((obj as any)[key]) : value;\n }\n\n if (Array.isArray(obj)) {\n const copy = Array.from(obj);\n copy[key as any] = update;\n return copy as any;\n }\n\n return {\n ...obj,\n [key]: update,\n };\n}\n","const getAllProperties = (object: any) => {\n const properties = new Set<[any, string | symbol]>();\n\n do {\n for (const key of Reflect.ownKeys(object)) {\n properties.add([object, key]);\n }\n } while ((object = Reflect.getPrototypeOf(object)) && object !== Object.prototype);\n\n return properties;\n};\n\nexport function bind(self: any) {\n for (const [object, key] of getAllProperties(self.constructor.prototype)) {\n if (key === 'constructor') {\n continue;\n }\n\n const descriptor = Reflect.getOwnPropertyDescriptor(object, key);\n if (descriptor && typeof descriptor.value === 'function') {\n self[key] = self[key].bind(self);\n }\n }\n}\n","import type { Duration } from '../core/commonTypes';\n\nexport const calcDuration = (t: Duration) => {\n if (typeof t === 'number') return t;\n return (\n (t.milliseconds ?? 0) +\n (t.seconds ?? 0) * 1000 +\n (t.minutes ?? 0) * 60 * 1000 +\n (t.hours ?? 0) * 60 * 60 * 1000 +\n (t.days ?? 0) * 24 * 60 * 60 * 1000\n );\n};\n","export const defaultEquals = (a: any, b: any) => a === b;\n\nexport const simpleShallowEquals = (a: any, b: any): boolean => {\n if (a === b) {\n return true;\n }\n\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((value, i) => value === b[i]);\n }\n\n if (typeof a === 'object' && typeof b === 'object') {\n if (a === null || b === null) {\n return false;\n }\n\n const e1 = Object.entries(a);\n const e2 = Object.entries(b);\n return e1.length === e2.length && e1.every(([key, value]) => value === b[key]);\n }\n\n return false;\n};\n\nexport const simpleDeepEquals = (a: any, b: any): boolean => {\n if (a === b) {\n return true;\n }\n\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((value, i) => simpleDeepEquals(value, b[i]));\n }\n\n if (typeof a === 'object' && typeof b === 'object') {\n if (a === null || b === null) {\n return false;\n }\n\n const e1 = Object.entries(a);\n const e2 = Object.entries(b);\n return e1.length === e2.length && e1.every(([key, value]) => simpleDeepEquals(value, b[key]));\n }\n\n return false;\n};\n","export function forwardError(error: unknown) {\n setTimeout(() => {\n throw error;\n });\n}\n","import { get } from './propAccess';\n\nexport function makeSelector<T, S>(selector?: ((value: T) => S) | string): (value: T) => S {\n if (!selector) {\n return (x) => x as any;\n }\n\n if (selector instanceof Function) {\n return selector;\n }\n\n return (x) => get(x, selector as any) as any;\n}\n","import type { Update, UpdateFrom } from '@core/commonTypes';\nimport type { Store } from '../core/store';\n\ntype Fn = (...args: any) => any;\n\ntype OptionalPropertyOf<T> = Exclude<\n {\n [K in keyof T]: T extends Record<K, T[K]> ? never : K;\n }[keyof T],\n undefined\n>;\n\nconst arrMod = <P extends keyof Array<any>>(prop: P) =>\n function <T extends Array<any>>(\n this: Store<T>,\n ...args: T[P] extends Fn ? Parameters<T[P]> : never\n ): T[P] extends Fn ? ReturnType<T[P]> : never {\n const newArr = this.get().slice() as T;\n const result = (newArr[prop] as Fn)(...(args as any));\n this.update(newArr);\n return result;\n };\n\nexport const arrayActions = {\n splice: arrMod('splice'),\n push: arrMod('push'),\n pop: arrMod('pop'),\n shift: arrMod('shift'),\n unshift: arrMod('unshift'),\n reverse: arrMod('reverse'),\n sort: arrMod('sort'),\n};\n\nexport const recordActions = {\n set<T extends Record<any, any>, K extends keyof T>(this: Store<T>, key: K, value: Update<T[K]>) {\n if (value instanceof Function) {\n value = value(this.get()[key]);\n }\n\n this.update({ ...this.get(), [key]: value });\n return this;\n },\n\n delete<T extends Record<any, any>, K extends OptionalPropertyOf<T>>(this: Store<T>, key: K) {\n const copy = { ...this.get() };\n delete copy[key];\n this.update(copy);\n },\n\n clear<T extends Record<any, any>>(this: Store<Partial<T>>) {\n this.update({} as T);\n },\n};\n\nexport const mapActions = {\n set<K, V>(this: Store<Map<K, V>>, key: K, value: UpdateFrom<V, [V | undefined]>) {\n if (value instanceof Function) {\n value = value(this.get().get(key));\n }\n\n const newMap = new Map(this.get());\n newMap.set(key, value);\n this.update(newMap);\n return this;\n },\n\n delete<K, V>(this: Store<Map<K, V>>, key: K) {\n const newMap = new Map(this.get());\n const result = newMap.delete(key);\n this.update(newMap);\n return result;\n },\n\n clear<K, V>(this: Store<Map<K, V>>) {\n this.update(new Map());\n },\n};\n\nexport const setActions = {\n add<T>(this: Store<Set<T>>, value: T) {\n const newSet = new Set(this.get());\n newSet.add(value);\n this.update(newSet);\n },\n\n delete<T>(this: Store<Set<T>>, value: T) {\n const newSet = new Set(this.get());\n newSet.delete(value);\n this.update(newSet);\n },\n\n clear<T>(this: Store<Set<T>>) {\n this.update(new Set());\n },\n};\n","export function throttle<Args extends any[]>(fn: (...args: Args) => void, ms: number): (...args: Args) => void {\n let t = 0;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n\n return (...args: Args) => {\n if (timeout !== undefined) {\n clearTimeout(timeout);\n }\n\n const dt = t + ms - Date.now();\n if (dt <= 0) {\n fn(...args);\n t = Date.now();\n return;\n }\n\n timeout = setTimeout(() => {\n fn(...args);\n t = Date.now();\n }, dt);\n };\n}\n","import { bind } from '@lib/bind';\nimport { calcDuration } from '@lib/calcDuration';\nimport { defaultEquals } from '@lib/equals';\nimport { forwardError } from '@lib/forwardError';\nimport { makeSelector } from '@lib/makeSelector';\nimport type { Path, Value } from '@lib/propAccess';\nimport { arrayActions, mapActions, recordActions, setActions } from '@lib/storeActions';\nimport { throttle } from '@lib/throttle';\nimport type { Cancel, Duration, Effect, Listener, Selector, SubscribeOptions, Update, Use, UseOptions } from './commonTypes';\nimport { derivedStore, DerivedStore } from './derivedStore';\n\nexport type StoreActions = Record<string, (...args: any[]) => any>;\n\nexport type BoundStoreActions<T, Actions extends StoreActions> = Actions & ThisType<Store<T> & Actions>;\n\nexport interface StoreOptions {\n retain?: number;\n}\n\nexport interface StoreOptionsWithActions<T, Actions extends StoreActions> extends StoreOptions {\n methods?: Actions & ThisType<Store<T> & Actions & StandardActions<T>>;\n}\n\ntype StandardActions<T> = T extends Map<any, any>\n ? typeof mapActions\n : T extends Set<any>\n ? typeof setActions\n : T extends Array<any>\n ? typeof arrayActions\n : T extends Record<any, any>\n ? typeof recordActions\n : Record<string, never>;\n\ntype StoreWithActions<T, Actions extends StoreActions> = Store<T> &\n Omit<BoundStoreActions<T, Actions>, keyof Store<T>> &\n StandardActions<T>;\n\nconst noop = () => undefined;\n\nexport class Store<T> {\n protected value = this.initialValue;\n protected listeners = new Set<Listener>();\n protected effects = new Map<Effect, { handle?: Cancel; retain?: number; timeout?: ReturnType<typeof setTimeout> }>();\n protected notifyId = {};\n\n constructor(protected readonly initialValue: T, protected readonly options: StoreOptions = {}) {\n bind(this);\n }\n\n get(): T {\n return this.value;\n }\n\n update(update: Update<T>): void {\n if (update instanceof Function) {\n update = update(this.get());\n }\n\n this.value = update;\n this.notify();\n }\n\n sub(listener: Listener<T>, options?: SubscribeOptions): Cancel {\n const { runNow = true, throttle: throttleOption, equals = defaultEquals } = options ?? {};\n\n let compareToValue = this.get();\n let previousValue: T | undefined;\n let hasRun = false;\n\n let innerListener = (force?: boolean | void) => {\n const value = this.get();\n\n if (!force && equals(value, compareToValue)) {\n return;\n }\n\n compareToValue = value;\n const _previousValue = previousValue;\n previousValue = value;\n hasRun = true;\n\n try {\n listener(value, _previousValue);\n } catch (error) {\n forwardError(error);\n }\n };\n\n if (throttleOption) {\n innerListener = throttle(innerListener, calcDuration(throttleOption));\n }\n\n this.listeners.add(innerListener);\n this.onSubscribe();\n\n if (runNow && !hasRun) {\n innerListener(true);\n }\n\n return () => {\n this.listeners.delete(innerListener);\n this.onUnsubscribe();\n };\n }\n\n map<S>(selector: Selector<T, S>, options?: UseOptions): DerivedStore<S>;\n map<P extends Path<T>>(selector: P, options?: UseOptions): DerivedStore<Value<T, P>>;\n map(_selector: Selector<T, any> | string, options?: UseOptions): DerivedStore<any> {\n const selector = makeSelector(_selector);\n const derivedFrom = { store: this, selectors: [_selector] };\n\n return new DerivedStore(\n ({ use }) => {\n return selector(use(this, options));\n },\n this.options,\n derivedFrom\n );\n }\n\n /** Add an effect that will be executed when the store becomes active, which means when it has at least one subscriber.\n * @param effect\n * If there is already a subscriber, the effect will be executed immediately.\n * Otherweise it will be executed as soon as the first subscription is created.\n * Every time all subscriptions are removed and the first is created again, the effect will be executed again.\n * @param retain\n * If provided, delay tearing down effects when the last subscriber is removed. This is useful if a short gap in subscriber coverage is supposed to be ignored. E.g. when switching pages, the old page might unsubscribe, while the new page subscribes immediately after.\n * @returns\n * The effect can return a teardown callback, which will be executed when the last subscription is removed and potentially the ratain time has passed.\n */\n addEffect(effect: Effect, retain?: Duration) {\n this.effects.set(effect, {\n handle: this.listeners.size > 0 ? effect() ?? noop : undefined,\n retain: retain !== undefined ? calcDuration(retain) : undefined,\n });\n\n return () => {\n const { handle, timeout } = this.effects.get(effect) ?? {};\n handle?.();\n timeout !== undefined && clearTimeout(timeout);\n this.effects.delete(effect);\n };\n }\n\n /** Return whether the store is currently active, which means whether it has at least one subscriber. */\n get isActive() {\n return this.listeners.size > 0;\n }\n\n protected onSubscribe() {\n if (this.listeners.size > 1) return;\n\n for (const [effect, { handle, retain, timeout }] of this.effects.entries()) {\n timeout !== undefined && clearTimeout(timeout);\n\n this.effects.set(effect, {\n handle: handle ?? effect() ?? noop,\n retain,\n timeout: undefined,\n });\n }\n }\n\n protected onUnsubscribe() {\n if (this.listeners.size > 0) return;\n\n for (const [effect, { handle, retain, timeout }] of this.effects.entries()) {\n !retain && handle?.();\n timeout !== undefined && clearTimeout(timeout);\n\n this.effects.set(effect, {\n handle: retain ? handle : undefined,\n retain,\n timeout: retain && handle ? setTimeout(handle, retain) : undefined,\n });\n }\n }\n\n protected notify() {\n const n = (this.notifyId = {});\n for (const listener of [...this.listeners]) {\n listener();\n if (n !== this.notifyId) break;\n }\n }\n}\n\nconst defaultOptions: StoreOptions = {};\n\nfunction _store<T>(calculate: (this: { use: Use }, fns: { use: Use }) => T, options?: StoreOptions): DerivedStore<T>;\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction _store<T, Actions extends StoreActions = {}>(\n initialState: T,\n options?: StoreOptionsWithActions<T, Actions>\n): StoreWithActions<T, Actions>;\nfunction _store<T, Actions extends StoreActions>(\n initialState: T | ((this: { use: Use }, fns: { use: Use }) => T),\n options?: StoreOptionsWithActions<T, Actions>\n): StoreWithActions<T, Actions> | DerivedStore<T> {\n if (initialState instanceof Function) {\n return derivedStore(initialState, options);\n }\n\n let methods: StoreActions | undefined = options?.methods;\n\n if (initialState instanceof Map) {\n methods = { ...mapActions, ...methods };\n } else if (initialState instanceof Set) {\n methods = { ...setActions, ...methods };\n } else if (Array.isArray(initialState)) {\n methods = { ...arrayActions, ...methods };\n } else if (initialState instanceof Object) {\n methods = { ...recordActions, ...methods };\n }\n\n const store = new Store(initialState, options);\n\n const boundActions = Object.fromEntries(\n Object.entries(methods ?? ({} as BoundStoreActions<T, any>))\n .filter(([name]) => !(name in store))\n .map(([name, fn]) => [name, (fn as any).bind(store)])\n ) as BoundStoreActions<T, any>;\n\n return Object.assign(store, boundActions);\n}\n\nexport const store = Object.assign(_store, { defaultOptions });\n","import { CalculationHelper } from '@lib/calculationHelper';\nimport { makeSelector } from '@lib/makeSelector';\nimport type { Path, Value } from '@lib/propAccess';\nimport { set } from '@lib/propAccess';\nimport type { Cancel, Selector, Update, Use } from './commonTypes';\nimport type { StoreOptions } from './store';\nimport { Store } from './store';\n\nexport class DerivedStore<T> extends Store<T> {\n calculationHelper = new CalculationHelper({\n calculate: ({ use }) => {\n const value = this.calculate.apply({ use }, [{ use }]);\n this.valid = true;\n super.update(value);\n },\n\n addEffect: this.addEffect,\n getValue: () => this.value,\n onInvalidate: this.invalidate,\n });\n\n protected valid = false;\n protected check?: () => void;\n protected cancel?: Cancel;\n\n constructor(\n protected calculate: (this: { use: Use }, fns: { use: Use }) => T,\n protected readonly options: StoreOptions = {},\n protected derivedFrom?: { store: Store<any>; selectors: (Selector<any, any> | string)[] }\n ) {\n super(undefined as T);\n }\n\n get(): T {\n this.calculationHelper.check();\n\n if (!this.valid) {\n this.calculationHelper.execute();\n }\n\n return super.get();\n }\n\n update(update: Update<T>): void {\n if (this.derivedFrom && this.derivedFrom.selectors.every((selector) => typeof selector === 'string')) {\n const path = this.derivedFrom.selectors.join('.');\n\n if (update instanceof Function) {\n const before = this.get();\n update = update(before);\n }\n\n this.derivedFrom.store.update((before: any) => set<any, any>(before, path, update));\n } else {\n throw new Error('Can only updated computed stores that are derived from other stores using string selectors');\n }\n }\n\n protected invalidate() {\n this.valid = false;\n\n if (this.isActive) {\n this.calculationHelper.execute();\n }\n }\n}\n\nfunction _derivedStore<T>(calculate: (this: { use: Use }, fns: { use: Use }) => T, options?: StoreOptions) {\n return new DerivedStore(calculate, options);\n}\n\nexport const derivedStore = Object.assign(_derivedStore, {});\n","export function hash(value: unknown): string {\n if (value instanceof Set) {\n return `s[${[...value].map(hash).sort().join(',')}]`;\n }\n\n if (value instanceof Map) {\n return `m[${[...value.entries()].map(hash).sort().join(',')}]`;\n }\n\n if (value instanceof Array) {\n return `[${value.map(hash).join(',')}]`;\n }\n\n if (value instanceof Object) {\n return `o[${Object.entries(value).map(hash).sort().join(',')}]`;\n }\n\n return JSON.stringify(value);\n}\n"],"names":["resolve","value","check","store"],"mappings":"AAUO,SAAS,QAAe;AAC7B,QAAM,IAAgG,CAAA;AACtG,MAAI,SAAoC;AACxC,MAAI,SAAS;AAEb,QAAM,MAAM,YAAY;AACtB,QAAI,CAAC,QAAQ;AACF,eAAA;AAEL,UAAA;AACI,aAAA,OAAO,EAAE,SAAU;AACrB,YAAA;AACE,cAAA,SAAS,KAAK;AAClB,cAAI,kBAAkB,SAAS;AAC7B,qBAAS,MAAM;AAAA,UACjB;AACA,eAAK,QAAQ,MAAM;AAAA,iBACZ;AACP,eAAK,OAAO,CAAC;AAAA,QACf;AAAA,MACF;AAES,eAAA;AACC;AAAA,IACZ;AAAA,EAAA;AAGF,SAAO,OAAO;AAAA,IACZ,CAAI,WAAsB;AACxB,aAAO,IAAI,QAAW,CAACA,UAAS,WAAW;AACzC,UAAE,KAAK,EAAE,QAAQ,SAAAA,UAAS,QAAQ;AAC9B;MAAA,CACL;AAAA,IACH;AAAA,IACA;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AAAA,EACF;AACF;AAEA,SAAS,cAAiB,WAAyD,SAAwB;AAClG,SAAA,IAAI,aAAa,WAAW,OAAO;AAC5C;AAEO,MAAM,eAAe,OAAO,OAAO,eAAe,CAAE,CAAA;ACvEpD,SAAS,KAAK,OAAwB;AAC3C,MAAI,iBAAiB,KAAK;AACjB,WAAA,KAAK,CAAC,GAAG,KAAK,EAAE,IAAI,IAAI,EAAE,KAAO,EAAA,KAAK,GAAG;AAAA,EAClD;AAEA,MAAI,iBAAiB,KAAK;AACxB,WAAO,KAAK,CAAC,GAAG,MAAM,QAAS,CAAA,EAAE,IAAI,IAAI,EAAE,KAAK,EAAE,KAAK,GAAG;AAAA,EAC5D;AAEA,MAAI,iBAAiB,OAAO;AAC1B,WAAO,IAAI,MAAM,IAAI,IAAI,EAAE,KAAK,GAAG;AAAA,EACrC;AAEA,MAAI,iBAAiB,QAAQ;AACpB,WAAA,KAAK,OAAO,QAAQ,KAAK,EAAE,IAAI,IAAI,EAAE,KAAA,EAAO,KAAK,GAAG;AAAA,EAC7D;AAEO,SAAA,KAAK,UAAU,KAAK;AAC7B;"}
package/dist/es/index.mjs CHANGED
@@ -64,18 +64,22 @@ class Cache {
64
64
  }
65
65
  }
66
66
  class ResourceGroup extends Set {
67
- invalidate() {
67
+ invalidateAll() {
68
68
  for (const resource of this) {
69
69
  resource.invalidate();
70
70
  }
71
71
  }
72
- clear() {
72
+ clearAll() {
73
73
  for (const resource of this) {
74
74
  resource.clear();
75
75
  }
76
76
  }
77
77
  }
78
- const allResources = new ResourceGroup();
78
+ const _allResources = new ResourceGroup();
79
+ const allResources = {
80
+ invalidateAll: _allResources.invalidateAll.bind(_allResources),
81
+ clearAll: _allResources.clearAll.bind(_allResources)
82
+ };
79
83
  const fetchStoreStateEquals = (equals = defaultEquals) => (a2, b2) => {
80
84
  const { value: av, ...ar } = a2;
81
85
  const { value: bv, ...br } = b2;
@@ -243,7 +247,7 @@ function withArgs(fetch, options) {
243
247
  };
244
248
  const resource = { invalidate, clear };
245
249
  const groups = Array.isArray(resourceGroup) ? resourceGroup : resourceGroup ? [resourceGroup] : [];
246
- for (const group of groups.concat(allResources)) {
250
+ for (const group of groups.concat(_allResources)) {
247
251
  group.add(resource);
248
252
  }
249
253
  return Object.assign(get, resource);
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../../src/lib/cache.ts","../../src/core/resourceGroup.ts","../../src/core/fetchStore.ts","../../src/core/once.ts"],"sourcesContent":["import { hash } from './hash';\n\nexport class Cache<Args extends any[], T extends object> {\n private cache = new Map<string, { t: number; ref?: T; weakRef?: WeakRef<T> }>();\n private interval = this.cacheTime ? setInterval(() => this.cleanup(), Math.max(this.cacheTime / 10, 1)) : undefined;\n\n constructor(private factory: (...args: Args) => T, private cacheTime?: number) {}\n\n cleanup() {\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) {\n const key = hash(args);\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: typeof WeakRef !== 'undefined' ? new WeakRef(value) : undefined,\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() {\n return [...this.cache.values()].map((entry) => entry.ref ?? entry.weakRef?.deref()).filter((value): value is T => !!value);\n }\n\n stop() {\n if (this.interval) {\n clearInterval(this.interval);\n }\n }\n\n stats() {\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","export interface Resource {\n invalidate(): void;\n clear(): void;\n}\n\nexport class ResourceGroup extends Set<Resource> {\n invalidate() {\n for (const resource of this) {\n resource.invalidate();\n }\n }\n\n clear() {\n for (const resource of this) {\n resource.clear();\n }\n }\n}\n\nexport const allResources = new ResourceGroup();\n","import { Cache } from '@lib/cache';\nimport { calcDuration } from '@lib/calcDuration';\nimport { CalculationHelper } from '@lib/calculationHelper';\nimport { defaultEquals, simpleShallowEquals } from '@lib/equals';\nimport { makeSelector } from '@lib/makeSelector';\nimport type { Path, Value } from '@lib/propAccess';\nimport type { Cancel, Duration, Listener, Selector, SubscribeOptions, Update, Use, UseFetch } from './commonTypes';\nimport type { ResourceGroup } from './resourceGroup';\nimport { allResources } from './resourceGroup';\nimport { Store } from './store';\n\ntype Common<T> = { isUpdating: false; update?: undefined; ref: unknown } | { isUpdating: true; update: Promise<T>; ref: unknown };\ntype WithValue<T> = { status: 'value'; value: T; error?: undefined; isStale: boolean } & Common<T>;\ntype WithError<T> = { status: 'error'; value?: undefined; error: unknown; isStale: boolean } & Common<T>;\ntype Pending<T> = { status: 'pending'; value?: undefined; error?: undefined; isStale: true } & Common<T>;\nexport type FetchStoreState<T> = WithValue<T> | WithError<T> | Pending<T>;\n\nexport interface FetchOptions {\n cache?: 'updateWhenStale' | 'backgroundUpdate' | 'forceUpdate';\n}\n\nexport interface FetchFn<T, Args extends any[] = []> {\n (this: { use: Use; useFetch: UseFetch }, ...args: Args): Promise<T>;\n}\n\nexport interface FetchStoreOptions<T> {\n invalidateAfter?: Duration | ((state: FetchStoreState<T>) => Duration);\n clearAfter?: Duration | ((state: FetchStoreState<T>) => Duration);\n resourceGroup?: ResourceGroup | ResourceGroup[];\n retain?: number;\n clearUnusedAfter?: Duration;\n // parentStore?: { store: Store<any>; selectors: (Selector<any, any> | string)[] };\n}\n\nconst fetchStoreStateEquals =\n (equals = defaultEquals) =>\n (a: FetchStoreState<any>, b: FetchStoreState<any>) => {\n const { value: av, ...ar } = a;\n const { value: bv, ...br } = b;\n return simpleShallowEquals(ar, br) && (ar.status !== 'value' || equals(av, bv));\n };\n\nconst createRef = () => Math.random().toString(36).slice(2);\n\nexport class FetchStore<T> extends Store<FetchStoreState<T>> {\n calculationHelper = new CalculationHelper({\n calculate: ({ use, useFetch }) => {\n const promise = this.fetchFn.apply({ use, useFetch });\n this.setPromise(promise);\n },\n\n addEffect: this.addEffect,\n getValue: () => this.value.value,\n setValue: this.setValue,\n setError: this.setError,\n onInvalidate: this.invalidate,\n });\n\n constructor(protected fetchFn: FetchFn<T>, protected options: FetchStoreOptions<T> = {}) {\n super({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n ref: createRef(),\n });\n }\n\n update(value: Update<FetchStoreState<T>>): void {\n this.calculationHelper.stop();\n super.update(value);\n }\n\n async fetch(options?: FetchOptions): Promise<T> {\n this.calculationHelper.check();\n\n const { cache = 'updateWhenStale' } = options ?? {};\n const { status, value, error, update, isStale } = this.value;\n\n if (((status === 'pending' || isStale) && !update) || cache === 'forceUpdate') {\n this.calculationHelper.execute();\n\n if (status === 'pending' || cache !== 'backgroundUpdate') {\n return this.value.update!;\n }\n }\n\n if (status === 'value') {\n return value;\n }\n\n if (status === 'error') {\n throw error;\n }\n\n return update;\n }\n\n setValue(value: T | Promise<T>): void {\n if (value instanceof Promise) {\n this.calculationHelper.stop();\n this.setPromise(value);\n } else {\n this.update({\n status: 'value',\n value,\n isStale: false,\n isUpdating: false,\n ref: createRef(),\n });\n }\n }\n\n protected setPromise(promise: Promise<T>) {\n const ref = createRef();\n\n super.update({\n ...this.value,\n isUpdating: true,\n update: promise,\n ref,\n });\n\n promise\n .then((value) => {\n if (promise === this.value.update) {\n super.update({\n status: 'value',\n value,\n isStale: false,\n isUpdating: false,\n ref,\n });\n }\n })\n .catch((error) => {\n if (promise === this.value.update) {\n super.update({\n status: 'error',\n error,\n isStale: false,\n isUpdating: false,\n ref,\n });\n }\n });\n }\n\n setError(error: unknown): void {\n this.update({\n status: 'error',\n error,\n isStale: false,\n isUpdating: false,\n ref: createRef(),\n });\n }\n\n invalidate(): void {\n this.update({\n ...this.value,\n isStale: true,\n isUpdating: false,\n update: undefined,\n });\n\n if (this.isActive) {\n this.calculationHelper.execute();\n }\n }\n\n clear(): void {\n this.update({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n ref: createRef(),\n });\n\n if (this.isActive) {\n this.calculationHelper.execute();\n }\n }\n\n sub(listener: Listener<FetchStoreState<T>>, options?: SubscribeOptions): Cancel {\n return super.sub(listener, {\n ...options,\n equals: fetchStoreStateEquals(options?.equals),\n });\n }\n\n mapValue<S>(selector: Selector<T, S>): FetchStore<S>;\n mapValue<P extends Path<T>>(selector: P): FetchStore<Value<T, P>>;\n mapValue<S>(_selector: Selector<T, S> | string): FetchStore<S> {\n const selector = makeSelector(_selector);\n const that = this;\n\n return new FetchStore(async function () {\n const value: T = await this.useFetch(that);\n return selector(value);\n });\n }\n}\n\nconst defaultOptions: FetchStoreOptions<unknown> = {};\n\nfunction create<T>(fetch: FetchFn<T>, options?: FetchStoreOptions<T>): FetchStore<T> {\n return withArgs(fetch, options)();\n}\n\nfunction withArgs<T, Args extends any[]>(\n fetch: FetchFn<T, Args>,\n options?: FetchStoreOptions<T>\n): {\n (...args: Args): FetchStore<T>;\n invalidate: () => void;\n clear: () => void;\n} {\n const { clearUnusedAfter = defaultOptions.clearUnusedAfter ?? 0, resourceGroup } = options ?? {};\n\n const cache = new Cache(\n (...args: Args) =>\n new FetchStore(function () {\n return fetch.apply(this, args);\n }, options),\n calcDuration(clearUnusedAfter)\n );\n\n const get = (...args: Args) => {\n return cache.get(...args);\n };\n\n const invalidate = () => {\n for (const instance of cache.values()) {\n instance.invalidate();\n }\n };\n\n const clear = () => {\n for (const instance of cache.values()) {\n instance.clear();\n }\n };\n\n const resource = { invalidate, clear };\n const groups = Array.isArray(resourceGroup) ? resourceGroup : resourceGroup ? [resourceGroup] : [];\n for (const group of groups.concat(allResources)) {\n group.add(resource);\n }\n\n return Object.assign(get, resource);\n}\n\nexport const fetchStore = Object.assign(create, {\n withArgs,\n defaultOptions,\n});\n","import type { Cancel, Listener } from './commonTypes';\n\ninterface Subscribe<T> {\n (listener: Listener<T>, options?: { runNow?: boolean }): Cancel;\n}\n\nexport function once<T, S extends T>(subscribe: Subscribe<T>, condition: (value: T) => value is S): Promise<S>;\nexport function once<T>(subscribe: Subscribe<T>, condition?: (value: T) => boolean): Promise<T>;\nexport function once<T>(subscribe: Subscribe<T>, condition?: (value: T) => boolean) {\n return new Promise<T>((resolve) => {\n let stopped = false;\n const cancel = subscribe(\n (value) => {\n if (stopped || (condition && !condition(value))) {\n return;\n }\n\n resolve(value);\n stopped = true;\n setTimeout(() => cancel());\n },\n {\n runNow: !!condition,\n }\n );\n });\n}\n\nexport function onceValue<T>(subscribe: Subscribe<{ value?: T; error?: unknown }>): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n let stopped = false;\n const cancel = subscribe(({ value, error }) => {\n if (stopped || (value === undefined && error === undefined)) {\n return;\n }\n\n if (value !== undefined) {\n resolve(value);\n } else {\n reject(error);\n }\n\n stopped = true;\n setTimeout(() => cancel());\n });\n });\n}\n"],"names":["a","b"],"mappings":";;AAEO,MAAM,MAA4C;AAAA,EAIvD,YAAoB,SAAuC,WAAoB;AAA3D,SAAA,UAAA;AAAuC,SAAA,YAAA;AAHnD,SAAA,4BAAY;AACpB,SAAQ,WAAW,KAAK,YAAY,YAAY,MAAM,KAAK,QAAW,GAAA,KAAK,IAAI,KAAK,YAAY,IAAI,CAAC,CAAC,IAAI;AAAA,EAE1B;AAAA,EAEhF,UAAU;;AACR,UAAM,SAAS,KAAK,IAAI,KAAK,KAAK,aAAa;AAEpC,eAAA,CAAC,KAAK,KAAK,KAAK,CAAC,GAAG,KAAK,MAAM,QAAQ,CAAC,GAAG;AACpD,UAAI,MAAM,OAAO,MAAM,KAAK,QAAQ;AAClC,eAAO,MAAM;AAAA,MACf;AAEA,UAAI,CAAC,MAAM,OAAO,GAAC,WAAM,YAAN,mBAAe,UAAS;AACpC,aAAA,MAAM,OAAO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AM,aAAa,MAAM;AACZ,eAAA,YAAY,MAAM,UAAU;AACrC,eAAS,WAAW;AAAA,IACtB;AAAA,EAAA;AAGF,QAAM,QAAQ,MAAM;AACP,eAAA,YAAY,MAAM,UAAU;AACrC,eAAS,MAAM;AAAA,IACjB;AAAA,EAAA;AAGI,QAAA,WAAW,EAAE,YAAY;AACzB,QAAA,SAAS,MAAM,QAAQ,aAAa,IAAI,gBAAgB,gBAAgB,CAAC,aAAa,IAAI;AAChG,aAAW,SAAS,OAAO,OAAO,YAAY,GAAG;AAC/C,UAAM,IAAI,QAAQ;AAAA,EACpB;AAEO,SAAA,OAAO,OAAO,KAAK,QAAQ;AACpC;AAEa,MAAA,aAAa,OAAO,OAAO,QAAQ;AAAA,EAC9C;AAAA,EACA;AACF,CAAC;ACvPe,SAAA,KAAQ,WAAyB,WAAmC;AAC3E,SAAA,IAAI,QAAW,CAAC,YAAY;AACjC,QAAI,UAAU;AACd,UAAM,SAAS;AAAA,MACb,CAAC,UAAU;AACT,YAAI,WAAY,aAAa,CAAC,UAAU,KAAK,GAAI;AAC/C;AAAA,QACF;AAEA,gBAAQ,KAAK;AACH,kBAAA;AACC,mBAAA,MAAM,QAAQ;AAAA,MAC3B;AAAA,MACA;AAAA,QACE,QAAQ,CAAC,CAAC;AAAA,MACZ;AAAA,IAAA;AAAA,EACF,CACD;AACH;"}
1
+ {"version":3,"file":"index.mjs","sources":["../../src/lib/cache.ts","../../src/core/resourceGroup.ts","../../src/core/fetchStore.ts","../../src/core/once.ts"],"sourcesContent":["import { hash } from './hash';\n\nexport class Cache<Args extends any[], T extends object> {\n private cache = new Map<string, { t: number; ref?: T; weakRef?: WeakRef<T> }>();\n private interval = this.cacheTime ? setInterval(() => this.cleanup(), Math.max(this.cacheTime / 10, 1)) : undefined;\n\n constructor(private factory: (...args: Args) => T, private cacheTime?: number) {}\n\n cleanup() {\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) {\n const key = hash(args);\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: typeof WeakRef !== 'undefined' ? new WeakRef(value) : undefined,\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() {\n return [...this.cache.values()].map((entry) => entry.ref ?? entry.weakRef?.deref()).filter((value): value is T => !!value);\n }\n\n stop() {\n if (this.interval) {\n clearInterval(this.interval);\n }\n }\n\n stats() {\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","export interface Resource {\n invalidate(): void;\n clear(): void;\n}\n\nexport class ResourceGroup extends Set<Resource> {\n invalidateAll() {\n for (const resource of this) {\n resource.invalidate();\n }\n }\n\n clearAll() {\n for (const resource of this) {\n resource.clear();\n }\n }\n}\n\nexport const _allResources = new ResourceGroup();\nexport const allResources = {\n invalidateAll: _allResources.invalidateAll.bind(_allResources),\n clearAll: _allResources.clearAll.bind(_allResources),\n};\n","import { Cache } from '@lib/cache';\nimport { calcDuration } from '@lib/calcDuration';\nimport { CalculationHelper } from '@lib/calculationHelper';\nimport { defaultEquals, simpleShallowEquals } from '@lib/equals';\nimport { makeSelector } from '@lib/makeSelector';\nimport type { Path, Value } from '@lib/propAccess';\nimport type { Cancel, Duration, Listener, Selector, SubscribeOptions, Update, Use, UseFetch } from './commonTypes';\nimport type { ResourceGroup } from './resourceGroup';\nimport { _allResources } from './resourceGroup';\nimport { Store } from './store';\n\ntype Common<T> = { isUpdating: false; update?: undefined; ref: unknown } | { isUpdating: true; update: Promise<T>; ref: unknown };\ntype WithValue<T> = { status: 'value'; value: T; error?: undefined; isStale: boolean } & Common<T>;\ntype WithError<T> = { status: 'error'; value?: undefined; error: unknown; isStale: boolean } & Common<T>;\ntype Pending<T> = { status: 'pending'; value?: undefined; error?: undefined; isStale: true } & Common<T>;\nexport type FetchStoreState<T> = WithValue<T> | WithError<T> | Pending<T>;\n\nexport interface FetchOptions {\n cache?: 'updateWhenStale' | 'backgroundUpdate' | 'forceUpdate';\n}\n\nexport interface FetchFn<T, Args extends any[] = []> {\n (this: { use: Use; useFetch: UseFetch }, ...args: Args): Promise<T>;\n}\n\nexport interface FetchStoreOptions<T> {\n invalidateAfter?: Duration | ((state: FetchStoreState<T>) => Duration);\n clearAfter?: Duration | ((state: FetchStoreState<T>) => Duration);\n resourceGroup?: ResourceGroup | ResourceGroup[];\n retain?: number;\n clearUnusedAfter?: Duration;\n // parentStore?: { store: Store<any>; selectors: (Selector<any, any> | string)[] };\n}\n\nconst fetchStoreStateEquals =\n (equals = defaultEquals) =>\n (a: FetchStoreState<any>, b: FetchStoreState<any>) => {\n const { value: av, ...ar } = a;\n const { value: bv, ...br } = b;\n return simpleShallowEquals(ar, br) && (ar.status !== 'value' || equals(av, bv));\n };\n\nconst createRef = () => Math.random().toString(36).slice(2);\n\nexport class FetchStore<T> extends Store<FetchStoreState<T>> {\n calculationHelper = new CalculationHelper({\n calculate: ({ use, useFetch }) => {\n const promise = this.fetchFn.apply({ use, useFetch });\n this.setPromise(promise);\n },\n\n addEffect: this.addEffect,\n getValue: () => this.value.value,\n setValue: this.setValue,\n setError: this.setError,\n onInvalidate: this.invalidate,\n });\n\n constructor(protected fetchFn: FetchFn<T>, protected options: FetchStoreOptions<T> = {}) {\n super({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n ref: createRef(),\n });\n }\n\n update(value: Update<FetchStoreState<T>>): void {\n this.calculationHelper.stop();\n super.update(value);\n }\n\n async fetch(options?: FetchOptions): Promise<T> {\n this.calculationHelper.check();\n\n const { cache = 'updateWhenStale' } = options ?? {};\n const { status, value, error, update, isStale } = this.value;\n\n if (((status === 'pending' || isStale) && !update) || cache === 'forceUpdate') {\n this.calculationHelper.execute();\n\n if (status === 'pending' || cache !== 'backgroundUpdate') {\n return this.value.update!;\n }\n }\n\n if (status === 'value') {\n return value;\n }\n\n if (status === 'error') {\n throw error;\n }\n\n return update;\n }\n\n setValue(value: T | Promise<T>): void {\n if (value instanceof Promise) {\n this.calculationHelper.stop();\n this.setPromise(value);\n } else {\n this.update({\n status: 'value',\n value,\n isStale: false,\n isUpdating: false,\n ref: createRef(),\n });\n }\n }\n\n protected setPromise(promise: Promise<T>) {\n const ref = createRef();\n\n super.update({\n ...this.value,\n isUpdating: true,\n update: promise,\n ref,\n });\n\n promise\n .then((value) => {\n if (promise === this.value.update) {\n super.update({\n status: 'value',\n value,\n isStale: false,\n isUpdating: false,\n ref,\n });\n }\n })\n .catch((error) => {\n if (promise === this.value.update) {\n super.update({\n status: 'error',\n error,\n isStale: false,\n isUpdating: false,\n ref,\n });\n }\n });\n }\n\n setError(error: unknown): void {\n this.update({\n status: 'error',\n error,\n isStale: false,\n isUpdating: false,\n ref: createRef(),\n });\n }\n\n invalidate(): void {\n this.update({\n ...this.value,\n isStale: true,\n isUpdating: false,\n update: undefined,\n });\n\n if (this.isActive) {\n this.calculationHelper.execute();\n }\n }\n\n clear(): void {\n this.update({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n ref: createRef(),\n });\n\n if (this.isActive) {\n this.calculationHelper.execute();\n }\n }\n\n sub(listener: Listener<FetchStoreState<T>>, options?: SubscribeOptions): Cancel {\n return super.sub(listener, {\n ...options,\n equals: fetchStoreStateEquals(options?.equals),\n });\n }\n\n mapValue<S>(selector: Selector<T, S>): FetchStore<S>;\n mapValue<P extends Path<T>>(selector: P): FetchStore<Value<T, P>>;\n mapValue<S>(_selector: Selector<T, S> | string): FetchStore<S> {\n const selector = makeSelector(_selector);\n const that = this;\n\n return new FetchStore(async function () {\n const value: T = await this.useFetch(that);\n return selector(value);\n });\n }\n}\n\nconst defaultOptions: FetchStoreOptions<unknown> = {};\n\nfunction create<T>(fetch: FetchFn<T>, options?: FetchStoreOptions<T>): FetchStore<T> {\n return withArgs(fetch, options)();\n}\n\nfunction withArgs<T, Args extends any[]>(\n fetch: FetchFn<T, Args>,\n options?: FetchStoreOptions<T>\n): {\n (...args: Args): FetchStore<T>;\n invalidate: () => void;\n clear: () => void;\n} {\n const { clearUnusedAfter = defaultOptions.clearUnusedAfter ?? 0, resourceGroup } = options ?? {};\n\n const cache = new Cache(\n (...args: Args) =>\n new FetchStore(function () {\n return fetch.apply(this, args);\n }, options),\n calcDuration(clearUnusedAfter)\n );\n\n const get = (...args: Args) => {\n return cache.get(...args);\n };\n\n const invalidate = () => {\n for (const instance of cache.values()) {\n instance.invalidate();\n }\n };\n\n const clear = () => {\n for (const instance of cache.values()) {\n instance.clear();\n }\n };\n\n const resource = { invalidate, clear };\n const groups = Array.isArray(resourceGroup) ? resourceGroup : resourceGroup ? [resourceGroup] : [];\n for (const group of groups.concat(_allResources)) {\n group.add(resource);\n }\n\n return Object.assign(get, resource);\n}\n\nexport const fetchStore = Object.assign(create, {\n withArgs,\n defaultOptions,\n});\n","import type { Cancel, Listener } from './commonTypes';\n\ninterface Subscribe<T> {\n (listener: Listener<T>, options?: { runNow?: boolean }): Cancel;\n}\n\nexport function once<T, S extends T>(subscribe: Subscribe<T>, condition: (value: T) => value is S): Promise<S>;\nexport function once<T>(subscribe: Subscribe<T>, condition?: (value: T) => boolean): Promise<T>;\nexport function once<T>(subscribe: Subscribe<T>, condition?: (value: T) => boolean) {\n return new Promise<T>((resolve) => {\n let stopped = false;\n const cancel = subscribe(\n (value) => {\n if (stopped || (condition && !condition(value))) {\n return;\n }\n\n resolve(value);\n stopped = true;\n setTimeout(() => cancel());\n },\n {\n runNow: !!condition,\n }\n );\n });\n}\n\nexport function onceValue<T>(subscribe: Subscribe<{ value?: T; error?: unknown }>): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n let stopped = false;\n const cancel = subscribe(({ value, error }) => {\n if (stopped || (value === undefined && error === undefined)) {\n return;\n }\n\n if (value !== undefined) {\n resolve(value);\n } else {\n reject(error);\n }\n\n stopped = true;\n setTimeout(() => cancel());\n });\n });\n}\n"],"names":["a","b"],"mappings":";;AAEO,MAAM,MAA4C;AAAA,EAIvD,YAAoB,SAAuC,WAAoB;AAA3D,SAAA,UAAA;AAAuC,SAAA,YAAA;AAHnD,SAAA,4BAAY;AACpB,SAAQ,WAAW,KAAK,YAAY,YAAY,MAAM,KAAK,QAAW,GAAA,KAAK,IAAI,KAAK,YAAY,IAAI,CAAC,CAAC,IAAI;AAAA,EAE1B;AAAA,EAEhF,UAAU;;AACR,UAAM,SAAS,KAAK,IAAI,KAAK,KAAK,aAAa;AAEpC,eAAA,CAAC,KAAK,KAAK,KAAK,CAAC,GAAG,KAAK,MAAM,QAAQ,CAAC,GAAG;AACpD,UAAI,MAAM,OAAO,MAAM,KAAK,QAAQ;AAClC,eAAO,MAAM;AAAA,MACf;AAEA,UAAI,CAAC,MAAM,OAAO,GAAC,WAAM,YAAN,mBAAe,UAAS;AACpC,aAAA,MAAM,OAAO,GAAG;AAAA,MACvB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,OAAO,MAAY;;AACX,UAAA,MAAM,KAAK,IAAI;AACrB,QAAI,QAAQ,KAAK,MAAM,IAAI,GAAG;AAC9B,QAAI,SAAQ,+BAAO,UAAO,oCAAO,YAAP,mBAAgB;AAEtC,QAAA,CAAC,SAAS,CAAC,OAAO;AACZ,cAAA,KAAK,QAAQ,GAAG,IAAI;AACpB,cAAA;AAAA,QACN,GAAG,KAAK,IAAI;AAAA,QACZ,KAAK;AAAA,QACL,SAAS,OAAO,YAAY,cAAc,IAAI,QAAQ,KAAK,IAAI;AAAA,MAAA;AAG5D,WAAA,MAAM,IAAI,KAAK,KAAK;AAAA,IAAA,OACpB;AACC,YAAA,IAAI,KAAK;AACf,Y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O,SAAA,OAAO,OAAO,KAAK,QAAQ;AACpC;AAEa,MAAA,aAAa,OAAO,OAAO,QAAQ;AAAA,EAC9C;AAAA,EACA;AACF,CAAC;ACvPe,SAAA,KAAQ,WAAyB,WAAmC;AAC3E,SAAA,IAAI,QAAW,CAAC,YAAY;AACjC,QAAI,UAAU;AACd,UAAM,SAAS;AAAA,MACb,CAAC,UAAU;AACT,YAAI,WAAY,aAAa,CAAC,UAAU,KAAK,GAAI;AAC/C;AAAA,QACF;AAEA,gBAAQ,KAAK;AACH,kBAAA;AACC,mBAAA,MAAM,QAAQ;AAAA,MAC3B;AAAA,MACA;AAAA,QACE,QAAQ,CAAC,CAAC;AAAA,MACZ;AAAA,IAAA;AAAA,EACF,CACD;AACH;"}
package/dist/es/react.mjs CHANGED
@@ -1,24 +1,6 @@
1
+ import { h as hash, t as trackingProxy, g as store } from "./hash.mjs";
2
+ import require$$0, { useRef, useCallback, useLayoutEffect, useDebugValue, useMemo, useContext, createContext } from "react";
1
3
  import { jsx } from "react/jsx-runtime";
2
- import { g as store, h as hash, t as trackingProxy } from "./hash.mjs";
3
- import require$$0, { useMemo, useContext, createContext, useRef, useCallback, useLayoutEffect, useDebugValue } from "react";
4
- const contextMap = /* @__PURE__ */ new WeakMap();
5
- function getStoreScopeContext(scope) {
6
- let context = contextMap.get(scope);
7
- if (!context) {
8
- context = createContext(store(scope.defaultValue));
9
- contextMap.set(scope, context);
10
- }
11
- return context;
12
- }
13
- function StoreScopeProvider({ scope, store: inputStore, children }) {
14
- const context = getStoreScopeContext(scope);
15
- const currentStore = useMemo(() => inputStore ?? store(scope.defaultValue), [scope, inputStore]);
16
- return /* @__PURE__ */ jsx(context.Provider, { value: currentStore, children });
17
- }
18
- function useStoreScope(scope) {
19
- const context = getStoreScopeContext(scope);
20
- return useContext(context);
21
- }
22
4
  var withSelectorExports = {};
23
5
  var withSelector = {
24
6
  get exports() {
@@ -207,12 +189,41 @@ function useStore(store2, options) {
207
189
  useDebugValue(value);
208
190
  return proxiedValue;
209
191
  }
192
+ function read(store2, options) {
193
+ const { status, value, error } = useStore(store2, options);
194
+ if (status === "value") {
195
+ return value;
196
+ }
197
+ if (status === "error") {
198
+ throw error;
199
+ }
200
+ throw store2.fetch();
201
+ }
202
+ const contextMap = /* @__PURE__ */ new WeakMap();
203
+ function getStoreScopeContext(scope) {
204
+ let context = contextMap.get(scope);
205
+ if (!context) {
206
+ context = createContext(store(scope.defaultValue));
207
+ contextMap.set(scope, context);
208
+ }
209
+ return context;
210
+ }
211
+ function StoreScopeProvider({ scope, store: inputStore, children }) {
212
+ const context = getStoreScopeContext(scope);
213
+ const currentStore = useMemo(() => inputStore ?? store(scope.defaultValue), [scope, inputStore]);
214
+ return /* @__PURE__ */ jsx(context.Provider, { value: currentStore, children });
215
+ }
216
+ function useStoreScope(scope) {
217
+ const context = getStoreScopeContext(scope);
218
+ return useContext(context);
219
+ }
210
220
  function useProp(store2, options) {
211
221
  const value = useStore(store2, options);
212
222
  return [value, store2.update];
213
223
  }
214
224
  export {
215
225
  StoreScopeProvider,
226
+ read,
216
227
  useProp,
217
228
  useStore,
218
229
  useStoreScope
@@ -1 +1 @@
1
- {"version":3,"file":"react.mjs","sources":["../../src/react/storeScope.tsx","../../node_modules/.pnpm/use-sync-external-store@1.2.0_react@18.2.0/node_modules/use-sync-external-store/cjs/use-sync-external-store-with-selector.production.min.js","../../node_modules/.pnpm/use-sync-external-store@1.2.0_react@18.2.0/node_modules/use-sync-external-store/cjs/use-sync-external-store-with-selector.development.js","../../node_modules/.pnpm/use-sync-external-store@1.2.0_react@18.2.0/node_modules/use-sync-external-store/with-selector.js","../../src/react/useStore.ts","../../src/react/useProp.ts"],"sourcesContent":["import type { Store } from '@core/store';\nimport { store } from '@core/store';\nimport type { StoreScope } from '@core/storeScope';\nimport type { Context, ReactNode } from 'react';\nimport { createContext, useContext, useMemo } from 'react';\n\nexport type StoreScopeProps<T> = { scope: StoreScope<T>; store?: Store<T>; children?: ReactNode };\n\nexport const contextMap = new WeakMap<StoreScope<any>, Context<Store<any>>>();\n\nexport function getStoreScopeContext<T>(scope: StoreScope<T>): Context<Store<T>> {\n let context = contextMap.get(scope);\n\n if (!context) {\n context = createContext<Store<T>>(store(scope.defaultValue));\n contextMap.set(scope, context);\n }\n\n return context;\n}\n\nexport function StoreScopeProvider<T>({ scope, store: inputStore, children }: StoreScopeProps<T>) {\n const context = getStoreScopeContext(scope);\n const currentStore = useMemo(() => inputStore ?? store(scope.defaultValue), [scope, inputStore]);\n\n return <context.Provider value={currentStore}>{children}</context.Provider>;\n}\n\nexport function useStoreScope<T>(scope: StoreScope<T>): Store<T> {\n const context = getStoreScopeContext(scope);\n return useContext(context);\n}\n","/**\n * @license React\n * use-sync-external-store-with-selector.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var g=require(\"react\");function n(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var p=\"function\"===typeof Object.is?Object.is:n,q=g.useSyncExternalStore,r=g.useRef,t=g.useEffect,u=g.useMemo,v=g.useDebugValue;\nexports.useSyncExternalStoreWithSelector=function(a,b,e,l,h){var c=r(null);if(null===c.current){var f={hasValue:!1,value:null};c.current=f}else f=c.current;c=u(function(){function a(a){if(!c){c=!0;d=a;a=l(a);if(void 0!==h&&f.hasValue){var b=f.value;if(h(b,a))return k=b}return k=a}b=k;if(p(d,a))return b;var e=l(a);if(void 0!==h&&h(b,e))return b;d=a;return k=e}var c=!1,d,k,m=void 0===e?null:e;return[function(){return a(b())},null===m?void 0:function(){return a(m())}]},[b,e,l,h]);var d=q(a,c[0],c[1]);\nt(function(){f.hasValue=!0;f.value=d},[d]);v(d);return d};\n","/**\n * @license React\n * use-sync-external-store-with-selector.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nif (process.env.NODE_ENV !== \"production\") {\n (function() {\n\n 'use strict';\n\n/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());\n}\n var React = require('react');\n\n/**\n * inlined Object.is polyfill to avoid requiring consumers ship their own\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n */\nfunction is(x, y) {\n return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare\n ;\n}\n\nvar objectIs = typeof Object.is === 'function' ? Object.is : is;\n\nvar useSyncExternalStore = React.useSyncExternalStore;\n\n// for CommonJS interop.\n\nvar useRef = React.useRef,\n useEffect = React.useEffect,\n useMemo = React.useMemo,\n useDebugValue = React.useDebugValue; // Same as useSyncExternalStore, but supports selector and isEqual arguments.\n\nfunction useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {\n // Use this to track the rendered snapshot.\n var instRef = useRef(null);\n var inst;\n\n if (instRef.current === null) {\n inst = {\n hasValue: false,\n value: null\n };\n instRef.current = inst;\n } else {\n inst = instRef.current;\n }\n\n var _useMemo = useMemo(function () {\n // Track the memoized state using closure variables that are local to this\n // memoized instance of a getSnapshot function. Intentionally not using a\n // useRef hook, because that state would be shared across all concurrent\n // copies of the hook/component.\n var hasMemo = false;\n var memoizedSnapshot;\n var memoizedSelection;\n\n var memoizedSelector = function (nextSnapshot) {\n if (!hasMemo) {\n // The first time the hook is called, there is no memoized result.\n hasMemo = true;\n memoizedSnapshot = nextSnapshot;\n\n var _nextSelection = selector(nextSnapshot);\n\n if (isEqual !== undefined) {\n // Even if the selector has changed, the currently rendered selection\n // may be equal to the new selection. We should attempt to reuse the\n // current value if possible, to preserve downstream memoizations.\n if (inst.hasValue) {\n var currentSelection = inst.value;\n\n if (isEqual(currentSelection, _nextSelection)) {\n memoizedSelection = currentSelection;\n return currentSelection;\n }\n }\n }\n\n memoizedSelection = _nextSelection;\n return _nextSelection;\n } // We may be able to reuse the previous invocation's result.\n\n\n // We may be able to reuse the previous invocation's result.\n var prevSnapshot = memoizedSnapshot;\n var prevSelection = memoizedSelection;\n\n if (objectIs(prevSnapshot, nextSnapshot)) {\n // The snapshot is the same as last time. Reuse the previous selection.\n return prevSelection;\n } // The snapshot has changed, so we need to compute a new selection.\n\n\n // The snapshot has changed, so we need to compute a new selection.\n var nextSelection = selector(nextSnapshot); // If a custom isEqual function is provided, use that to check if the data\n // has changed. If it hasn't, return the previous selection. That signals\n // to React that the selections are conceptually equal, and we can bail\n // out of rendering.\n\n // If a custom isEqual function is provided, use that to check if the data\n // has changed. If it hasn't, return the previous selection. That signals\n // to React that the selections are conceptually equal, and we can bail\n // out of rendering.\n if (isEqual !== undefined && isEqual(prevSelection, nextSelection)) {\n return prevSelection;\n }\n\n memoizedSnapshot = nextSnapshot;\n memoizedSelection = nextSelection;\n return nextSelection;\n }; // Assigning this to a constant so that Flow knows it can't change.\n\n\n // Assigning this to a constant so that Flow knows it can't change.\n var maybeGetServerSnapshot = getServerSnapshot === undefined ? null : getServerSnapshot;\n\n var getSnapshotWithSelector = function () {\n return memoizedSelector(getSnapshot());\n };\n\n var getServerSnapshotWithSelector = maybeGetServerSnapshot === null ? undefined : function () {\n return memoizedSelector(maybeGetServerSnapshot());\n };\n return [getSnapshotWithSelector, getServerSnapshotWithSelector];\n }, [getSnapshot, getServerSnapshot, selector, isEqual]),\n getSelection = _useMemo[0],\n getServerSelection = _useMemo[1];\n\n var value = useSyncExternalStore(subscribe, getSelection, getServerSelection);\n useEffect(function () {\n inst.hasValue = true;\n inst.value = value;\n }, [value]);\n useDebugValue(value);\n return value;\n}\n\nexports.useSyncExternalStoreWithSelector = useSyncExternalStoreWithSelector;\n /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());\n}\n \n })();\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/use-sync-external-store-with-selector.production.min.js');\n} else {\n module.exports = require('./cjs/use-sync-external-store-with-selector.development.js');\n}\n","import type { SubscribeOptions } from '@core/commonTypes';\nimport type { Store } from '@core/store';\nimport { hash } from '@lib/hash';\nimport { trackingProxy } from '@lib/trackingProxy';\nimport { useCallback, useDebugValue, useLayoutEffect, useRef } from 'react';\nimport { useSyncExternalStoreWithSelector } from 'use-sync-external-store/with-selector';\n\nexport type UseStoreOptions = Omit<SubscribeOptions, 'runNow'>;\n\nexport function useStore<T>(store: Store<T>, options?: UseStoreOptions): T {\n const lastEqualsRef = useRef<(newValue: T) => boolean>();\n\n const subOptions = { ...options, runNow: false, equals: undefined };\n\n const subscribe = useCallback(\n (listener: () => void) => {\n return store.sub(listener, subOptions);\n },\n [store, hash(subOptions)]\n );\n\n const value = useSyncExternalStoreWithSelector(\n //\n subscribe,\n store.get,\n undefined,\n (x) => x,\n options?.equals ?? ((_v, newValue) => lastEqualsRef.current?.(newValue) ?? false)\n );\n const [proxiedValue, equals] = trackingProxy(value);\n\n useLayoutEffect(() => {\n lastEqualsRef.current = equals;\n });\n\n useDebugValue(value);\n return proxiedValue;\n}\n","import type { Store } from '@core/store';\nimport type { UpdateFn } from '@core/commonTypes';\nimport type { UseStoreOptions } from './useStore';\nimport { useStore } from './useStore';\n\nexport function useProp<T>(store: Store<T>, options?: UseStoreOptions): [value: T, setValue: UpdateFn<T>] {\n const value = useStore(store, options);\n\n return [value, store.update];\n}\n"],"names":["a","c","d","b","e","useRef","useMemo","useDebugValue","require$$0","require$$1","store","useSy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9B,SAAA,CAAC,OAAOA,OAAM,MAAM;AAC7B;"}
1
+ {"version":3,"file":"react.mjs","sources":["../../node_modules/.pnpm/use-sync-external-store@1.2.0_react@18.2.0/node_modules/use-sync-external-store/cjs/use-sync-external-store-with-selector.production.min.js","../../node_modules/.pnpm/use-sync-external-store@1.2.0_react@18.2.0/node_modules/use-sync-external-store/cjs/use-sync-external-store-with-selector.development.js","../../node_modules/.pnpm/use-sync-external-store@1.2.0_react@18.2.0/node_modules/use-sync-external-store/with-selector.js","../../src/react/useStore.ts","../../src/react/read.ts","../../src/react/storeScope.tsx","../../src/react/useProp.ts"],"sourcesContent":["/**\n * @license React\n * use-sync-external-store-with-selector.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var g=require(\"react\");function n(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var p=\"function\"===typeof Object.is?Object.is:n,q=g.useSyncExternalStore,r=g.useRef,t=g.useEffect,u=g.useMemo,v=g.useDebugValue;\nexports.useSyncExternalStoreWithSelector=function(a,b,e,l,h){var c=r(null);if(null===c.current){var f={hasValue:!1,value:null};c.current=f}else f=c.current;c=u(function(){function a(a){if(!c){c=!0;d=a;a=l(a);if(void 0!==h&&f.hasValue){var b=f.value;if(h(b,a))return k=b}return k=a}b=k;if(p(d,a))return b;var e=l(a);if(void 0!==h&&h(b,e))return b;d=a;return k=e}var c=!1,d,k,m=void 0===e?null:e;return[function(){return a(b())},null===m?void 0:function(){return a(m())}]},[b,e,l,h]);var d=q(a,c[0],c[1]);\nt(function(){f.hasValue=!0;f.value=d},[d]);v(d);return d};\n","/**\n * @license React\n * use-sync-external-store-with-selector.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nif (process.env.NODE_ENV !== \"production\") {\n (function() {\n\n 'use strict';\n\n/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());\n}\n var React = require('react');\n\n/**\n * inlined Object.is polyfill to avoid requiring consumers ship their own\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n */\nfunction is(x, y) {\n return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare\n ;\n}\n\nvar objectIs = typeof Object.is === 'function' ? Object.is : is;\n\nvar useSyncExternalStore = React.useSyncExternalStore;\n\n// for CommonJS interop.\n\nvar useRef = React.useRef,\n useEffect = React.useEffect,\n useMemo = React.useMemo,\n useDebugValue = React.useDebugValue; // Same as useSyncExternalStore, but supports selector and isEqual arguments.\n\nfunction useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {\n // Use this to track the rendered snapshot.\n var instRef = useRef(null);\n var inst;\n\n if (instRef.current === null) {\n inst = {\n hasValue: false,\n value: null\n };\n instRef.current = inst;\n } else {\n inst = instRef.current;\n }\n\n var _useMemo = useMemo(function () {\n // Track the memoized state using closure variables that are local to this\n // memoized instance of a getSnapshot function. Intentionally not using a\n // useRef hook, because that state would be shared across all concurrent\n // copies of the hook/component.\n var hasMemo = false;\n var memoizedSnapshot;\n var memoizedSelection;\n\n var memoizedSelector = function (nextSnapshot) {\n if (!hasMemo) {\n // The first time the hook is called, there is no memoized result.\n hasMemo = true;\n memoizedSnapshot = nextSnapshot;\n\n var _nextSelection = selector(nextSnapshot);\n\n if (isEqual !== undefined) {\n // Even if the selector has changed, the currently rendered selection\n // may be equal to the new selection. We should attempt to reuse the\n // current value if possible, to preserve downstream memoizations.\n if (inst.hasValue) {\n var currentSelection = inst.value;\n\n if (isEqual(currentSelection, _nextSelection)) {\n memoizedSelection = currentSelection;\n return currentSelection;\n }\n }\n }\n\n memoizedSelection = _nextSelection;\n return _nextSelection;\n } // We may be able to reuse the previous invocation's result.\n\n\n // We may be able to reuse the previous invocation's result.\n var prevSnapshot = memoizedSnapshot;\n var prevSelection = memoizedSelection;\n\n if (objectIs(prevSnapshot, nextSnapshot)) {\n // The snapshot is the same as last time. Reuse the previous selection.\n return prevSelection;\n } // The snapshot has changed, so we need to compute a new selection.\n\n\n // The snapshot has changed, so we need to compute a new selection.\n var nextSelection = selector(nextSnapshot); // If a custom isEqual function is provided, use that to check if the data\n // has changed. If it hasn't, return the previous selection. That signals\n // to React that the selections are conceptually equal, and we can bail\n // out of rendering.\n\n // If a custom isEqual function is provided, use that to check if the data\n // has changed. If it hasn't, return the previous selection. That signals\n // to React that the selections are conceptually equal, and we can bail\n // out of rendering.\n if (isEqual !== undefined && isEqual(prevSelection, nextSelection)) {\n return prevSelection;\n }\n\n memoizedSnapshot = nextSnapshot;\n memoizedSelection = nextSelection;\n return nextSelection;\n }; // Assigning this to a constant so that Flow knows it can't change.\n\n\n // Assigning this to a constant so that Flow knows it can't change.\n var maybeGetServerSnapshot = getServerSnapshot === undefined ? null : getServerSnapshot;\n\n var getSnapshotWithSelector = function () {\n return memoizedSelector(getSnapshot());\n };\n\n var getServerSnapshotWithSelector = maybeGetServerSnapshot === null ? undefined : function () {\n return memoizedSelector(maybeGetServerSnapshot());\n };\n return [getSnapshotWithSelector, getServerSnapshotWithSelector];\n }, [getSnapshot, getServerSnapshot, selector, isEqual]),\n getSelection = _useMemo[0],\n getServerSelection = _useMemo[1];\n\n var value = useSyncExternalStore(subscribe, getSelection, getServerSelection);\n useEffect(function () {\n inst.hasValue = true;\n inst.value = value;\n }, [value]);\n useDebugValue(value);\n return value;\n}\n\nexports.useSyncExternalStoreWithSelector = useSyncExternalStoreWithSelector;\n /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());\n}\n \n })();\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/use-sync-external-store-with-selector.production.min.js');\n} else {\n module.exports = require('./cjs/use-sync-external-store-with-selector.development.js');\n}\n","import type { SubscribeOptions } from '@core/commonTypes';\nimport type { Store } from '@core/store';\nimport { hash } from '@lib/hash';\nimport { trackingProxy } from '@lib/trackingProxy';\nimport { useCallback, useDebugValue, useLayoutEffect, useRef } from 'react';\nimport { useSyncExternalStoreWithSelector } from 'use-sync-external-store/with-selector';\n\nexport type UseStoreOptions = Omit<SubscribeOptions, 'runNow'>;\n\nexport function useStore<T>(store: Store<T>, options?: UseStoreOptions): T {\n const lastEqualsRef = useRef<(newValue: T) => boolean>();\n\n const subOptions = { ...options, runNow: false, equals: undefined };\n\n const subscribe = useCallback(\n (listener: () => void) => {\n return store.sub(listener, subOptions);\n },\n [store, hash(subOptions)]\n );\n\n const value = useSyncExternalStoreWithSelector(\n //\n subscribe,\n store.get,\n undefined,\n (x) => x,\n options?.equals ?? ((_v, newValue) => lastEqualsRef.current?.(newValue) ?? false)\n );\n const [proxiedValue, equals] = trackingProxy(value);\n\n useLayoutEffect(() => {\n lastEqualsRef.current = equals;\n });\n\n useDebugValue(value);\n return proxiedValue;\n}\n","import type { FetchStore } from '@core/fetchStore';\nimport type { SubscribeOptions } from '@core/commonTypes';\nimport { useStore } from './useStore';\n\nexport type UseStoreOptions = Omit<SubscribeOptions, 'runNow'>;\n\nexport function read<T>(store: FetchStore<T>, options?: UseStoreOptions): T {\n const { status, value, error } = useStore(store, options);\n\n if (status === 'value') {\n return value;\n }\n\n if (status === 'error') {\n throw error;\n }\n\n throw store.fetch();\n}\n","import type { Store } from '@core/store';\nimport { store } from '@core/store';\nimport type { StoreScope } from '@core/storeScope';\nimport type { Context, ReactNode } from 'react';\nimport { createContext, useContext, useMemo } from 'react';\n\nexport type StoreScopeProps<T> = { scope: StoreScope<T>; store?: Store<T>; children?: ReactNode };\n\nexport const contextMap = new WeakMap<StoreScope<any>, Context<Store<any>>>();\n\nexport function getStoreScopeContext<T>(scope: StoreScope<T>): Context<Store<T>> {\n let context = contextMap.get(scope);\n\n if (!context) {\n context = createContext<Store<T>>(store(scope.defaultValue));\n contextMap.set(scope, context);\n }\n\n return context;\n}\n\nexport function StoreScopeProvider<T>({ scope, store: inputStore, children }: StoreScopeProps<T>) {\n const context = getStoreScopeContext(scope);\n const currentStore = useMemo(() => inputStore ?? store(scope.defaultValue), [scope, inputStore]);\n\n return <context.Provider value={currentStore}>{children}</context.Provider>;\n}\n\nexport function useStoreScope<T>(scope: StoreScope<T>): Store<T> {\n const context = getStoreScopeContext(scope);\n return useContext(context);\n}\n","import type { Store } from '@core/store';\nimport type { UpdateFn } from '@core/commonTypes';\nimport type { UseStoreOptions } from './useStore';\nimport { useStore } from './useStore';\n\nexport function useProp<T>(store: Store<T>, options?: UseStoreOptions): [value: T, setValue: UpdateFn<T>] {\n const value = useStore(store, options);\n\n return [value, store.update];\n}\n"],"names":["a","c","d","b","e","useRef","useMemo","useDebugValue","require$$0","require$$1","store","useSyncExternalStoreWithSelector"],"mappings":";;;;;;;;;;;;;;;;;;AASa,MAAI,IAAE;AAAiB,WAAS,EAAE,GAAE,GAAE;AAAC,WAAO,MAAI,MAAI,MAAI,KAAG,IAAE,MAAI,IAAE,MAAI,MAAI,KAAG,MAAI;AAAA,EAAC;AAAC,MAAI,IAAE,eAAa,OAAO,OAAO,KAAG,OAAO,KAAG,GAAE,IAAE,EAAE,sBAAqB,IAAE,EAAE,QAAO,IAAE,EAAE,WAAU,IAAE,EAAE,SAAQ,IAAE,EAAE;AACrN,kDAAA,mCAAyC,SAAS,GAAE,GAAE,GAAE,GAAE,GAAE;AAAC,QAAI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AC,IAAI,aAAa;;AAAA,kCAAc,YAAd,uCAAwB,cAAa;AAAA;AAAA,EAAA;AAE7E,QAAM,CAAC,cAAc,MAAM,IAAI,cAAc,KAAK;AAElD,kBAAgB,MAAM;AACpB,kBAAc,UAAU;AAAA,EAAA,CACzB;AAED,gBAAc,KAAK;AACZ,SAAA;AACT;AC/BgB,SAAA,KAAQA,QAAsB,SAA8B;AAC1E,QAAM,EAAE,QAAQ,OAAO,MAAU,IAAA,SAASA,QAAO,OAAO;AAExD,MAAI,WAAW,SAAS;AACf,WAAA;AAAA,EACT;AAEA,MAAI,WAAW,SAAS;AAChB,UAAA;AAAA,EACR;AAEA,QAAMA,OAAM;AACd;ACVa,MAAA,iCAAiB;AAEvB,SAAS,qBAAwB,OAAyC;AAC3E,MAAA,UAAU,WAAW,IAAI,KAAK;AAElC,MAAI,CAAC,SAAS;AACZ,cAAU,cAAwB,MAAM,MAAM,YAAY,CAAC;AAChD,eAAA,IAAI,OAAO,OAAO;AAAA,EAC/B;AAEO,SAAA;AACT;AAEO,SAAS,mBAAsB,EAAE,OAAO,OAAO,YAAY,YAAgC;AAC1F,QAAA,UAAU,qBAAqB,KAAK;AACpC,QAAA,eAAe,QAAQ,MAAM,cAAc,MAAM,MAAM,YAAY,GAAG,CAAC,OAAO,UAAU,CAAC;AAE/F,6BAAQ,QAAQ,UAAR,EAAiB,OAAO,cAAe,SAAS,CAAA;AAC1D;AAEO,SAAS,cAAiB,OAAgC;AACzD,QAAA,UAAU,qBAAqB,KAAK;AAC1C,SAAO,WAAW,OAAO;AAC3B;AC1BgB,SAAA,QAAWA,QAAiB,SAA8D;AAClG,QAAA,QAAQ,SAASA,QAAO,OAAO;AAE9B,SAAA,CAAC,OAAOA,OAAM,MAAM;AAC7B;"}
@@ -1,6 +1,6 @@
1
1
  import { CalculationHelper } from '../lib/calculationHelper';
2
- import type { Path, Value } from '../lib/propAccess';
3
2
  import type { Cancel, Selector, Update, Use } from './commonTypes';
3
+ import type { StoreOptions } from './store';
4
4
  import { Store } from './store';
5
5
  export declare class DerivedStore<T> extends Store<T> {
6
6
  protected calculate: (this: {
@@ -8,6 +8,7 @@ export declare class DerivedStore<T> extends Store<T> {
8
8
  }, fns: {
9
9
  use: Use;
10
10
  }) => T;
11
+ protected readonly options: StoreOptions;
11
12
  protected derivedFrom?: {
12
13
  store: Store<any>;
13
14
  selectors: (Selector<any, any> | string)[];
@@ -20,20 +21,18 @@ export declare class DerivedStore<T> extends Store<T> {
20
21
  use: Use;
21
22
  }, fns: {
22
23
  use: Use;
23
- }) => T, derivedFrom?: {
24
+ }) => T, options?: StoreOptions, derivedFrom?: {
24
25
  store: Store<any>;
25
26
  selectors: (Selector<any, any> | string)[];
26
27
  } | undefined);
27
28
  get(): T;
28
29
  update(update: Update<T>): void;
29
- map<S>(selector: Selector<T, S>): DerivedStore<S>;
30
- map<P extends Path<T>>(selector: P): DerivedStore<Value<T, P>>;
31
30
  protected invalidate(): void;
32
31
  }
33
32
  declare function _derivedStore<T>(calculate: (this: {
34
33
  use: Use;
35
34
  }, fns: {
36
35
  use: Use;
37
- }) => T): DerivedStore<T>;
36
+ }) => T, options?: StoreOptions): DerivedStore<T>;
38
37
  export declare const derivedStore: typeof _derivedStore;
39
38
  export {};
@@ -3,7 +3,11 @@ export interface Resource {
3
3
  clear(): void;
4
4
  }
5
5
  export declare class ResourceGroup extends Set<Resource> {
6
- invalidate(): void;
7
- clear(): void;
6
+ invalidateAll(): void;
7
+ clearAll(): void;
8
8
  }
9
- export declare const allResources: ResourceGroup;
9
+ export declare const _allResources: ResourceGroup;
10
+ export declare const allResources: {
11
+ invalidateAll: () => void;
12
+ clearAll: () => void;
13
+ };