cross-state 0.54.6 → 0.54.7
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/{hash-DwJ18aiM.js → hash-DNFM5y_h.js} +2 -2
- package/dist/{hash-DwJ18aiM.js.map → hash-DNFM5y_h.js.map} +1 -1
- package/dist/{hash-CLSnumfo.cjs → hash-Dv3XlmHn.cjs} +2 -2
- package/dist/{hash-CLSnumfo.cjs.map → hash-Dv3XlmHn.cjs.map} +1 -1
- package/dist/index.cjs +6 -6
- package/dist/index.js +6 -6
- package/dist/mutative/register.cjs +2 -2
- package/dist/mutative/register.js +2 -2
- package/dist/{patchMethods-CvzN7VKv.js → patchMethods-C_f3PORQ.js} +2 -2
- package/dist/{patchMethods-CvzN7VKv.js.map → patchMethods-C_f3PORQ.js.map} +1 -1
- package/dist/{patchMethods-BZiDZ2P3.cjs → patchMethods-hhlLwtqE.cjs} +2 -2
- package/dist/{patchMethods-BZiDZ2P3.cjs.map → patchMethods-hhlLwtqE.cjs.map} +1 -1
- package/dist/patches/index.cjs +2 -2
- package/dist/patches/index.js +2 -2
- package/dist/patches/register.cjs +3 -3
- package/dist/patches/register.js +3 -3
- package/dist/persist/register.cjs +4 -4
- package/dist/persist/register.js +4 -4
- package/dist/{persist-DMLaOyyf.js → persist-Btgg3qGU.js} +4 -4
- package/dist/{persist-DMLaOyyf.js.map → persist-Btgg3qGU.js.map} +1 -1
- package/dist/{persist-E99nqNZD.cjs → persist-CGLe7YUX.cjs} +4 -4
- package/dist/{persist-E99nqNZD.cjs.map → persist-CGLe7YUX.cjs.map} +1 -1
- package/dist/{propAccess-BF1Etw2-.js → propAccess-B260LXN1.js} +2 -2
- package/dist/propAccess-B260LXN1.js.map +1 -0
- package/dist/{propAccess-jVjduANf.cjs → propAccess-BdLsqViO.cjs} +2 -2
- package/dist/propAccess-BdLsqViO.cjs.map +1 -0
- package/dist/react/index.cjs +4 -4
- package/dist/react/index.js +4 -4
- package/dist/react/register.cjs +5 -5
- package/dist/react/register.js +5 -5
- package/dist/{scope-DV1yaa6v.js → scope-6P87zGw6.js} +4 -4
- package/dist/{scope-DV1yaa6v.js.map → scope-6P87zGw6.js.map} +1 -1
- package/dist/{scope-iQ_P6a3x.cjs → scope-BfYAP7hS.cjs} +4 -4
- package/dist/{scope-iQ_P6a3x.cjs.map → scope-BfYAP7hS.cjs.map} +1 -1
- package/dist/{store-CDJLP4mE.cjs → store-1TGlSyq4.cjs} +2 -2
- package/dist/{store-CDJLP4mE.cjs.map → store-1TGlSyq4.cjs.map} +1 -1
- package/dist/{store-CYQjkIDF.js → store-BpMJxIHt.js} +2 -2
- package/dist/{store-CYQjkIDF.js.map → store-BpMJxIHt.js.map} +1 -1
- package/dist/{storeMethods-BkLWi0lY.cjs → storeMethods-C_RzHBQL.cjs} +4 -4
- package/dist/{storeMethods-BkLWi0lY.cjs.map → storeMethods-C_RzHBQL.cjs.map} +1 -1
- package/dist/{storeMethods-Dq7bKZ6Z.js → storeMethods-CkvcMFoL.js} +4 -4
- package/dist/{storeMethods-Dq7bKZ6Z.js.map → storeMethods-CkvcMFoL.js.map} +1 -1
- package/package.json +1 -1
- package/dist/propAccess-BF1Etw2-.js.map +0 -1
- package/dist/propAccess-jVjduANf.cjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"persist-E99nqNZD.cjs","names":["isPromise","value","entries: Map<KeyType, unknown>","path","isPromise","store: Store<T>","options: PersistOptions<T>","queue","castArrayPath","calcDuration","subscribePatches","path","shallowEqual","isPromise","fromExtendedJsonString","remove","set","get","value","toExtendedJsonString"],"sources":["../src/lib/promiseChain.ts","../src/persist/persistPathHelpers.ts","../src/persist/persistStorage.ts","../src/persist/persist.ts"],"sourcesContent":["import isPromise from '@lib/isPromise';\n\nexport interface Chain<T> {\n value: T;\n next<S>(fn: (value: Awaited<T>) => S): T extends Promise<any> ? Chain<Promise<S>> : Chain<S>;\n}\n\nexport default function promiseChain<T>(value: T | (() => T)): Chain<T> {\n if (value instanceof Function) {\n value = value();\n }\n\n return {\n value,\n next(fn) {\n const next = isPromise(value)\n ? value.then((value) => fn(value as Awaited<T>))\n : fn(value as Awaited<T>);\n\n return promiseChain(next) as any;\n },\n };\n}\n","import type { KeyType } from '@lib/path';\n\nexport const isAncestor = (ancestor: KeyType[], path: KeyType[]): boolean => {\n return (\n ancestor.length <= path.length &&\n ancestor.every((v, i) => v === '*' || path[i] === '*' || v === path[i])\n );\n};\n\nexport const split = (value: any, path: KeyType[]): { path: KeyType[]; value: unknown }[] => {\n const [first, ...rest] = path;\n if (first === undefined) return [{ path: [], value }];\n\n let entries: Map<KeyType, unknown>;\n if (value instanceof Map) {\n entries = value;\n } else if (value instanceof Set) {\n entries = new Map([...value].map((v, i) => [i, v]));\n } else if (Array.isArray(value)) {\n entries = new Map(value.map((v, i) => [i, v]));\n } else if (typeof value === 'object' && value !== null) {\n entries = new Map(Object.entries(value));\n } else {\n return [{ path: [], value }];\n }\n\n if (first === '*') {\n return [...entries].flatMap(([k, v]) =>\n split(v, rest).map(({ path, value }) => ({ path: [k, ...path], value })),\n );\n }\n\n const subValue = entries.get(first);\n if (subValue === undefined) return [{ path: [], value }];\n\n return split(subValue, rest).map(({ path, value }) => ({ path: [first, ...path], value }));\n};\n","import isPromise from '@lib/isPromise';\nimport promiseChain from '@lib/promiseChain';\n\nexport interface PersistStorageBase {\n getItem: (key: string) => string | null | Promise<string | null>;\n setItem: (key: string, value: string) => void | Promise<unknown>;\n removeItem: (key: string) => void | Promise<unknown>;\n}\n\nexport interface PersistStorageWithKeys extends PersistStorageBase {\n keys: () => string[] | Promise<string[]>;\n}\n\nexport interface PersistStorageWithLength extends PersistStorageBase {\n length: number | (() => number | Promise<number>);\n key: (keyIndex: number) => string | null | Promise<string | null>;\n}\n\nexport interface PersistStorageWithListItems extends PersistStorageBase {\n listItems: () => Map<string, string> | Promise<Map<string, string>>;\n}\n\nexport type PersistStorage =\n | PersistStorageWithKeys\n | PersistStorageWithLength\n | PersistStorageWithListItems;\n\nexport function normalizeStorage(storage: PersistStorage): PersistStorageWithListItems {\n return {\n getItem: storage.getItem.bind(storage),\n setItem: storage.setItem.bind(storage),\n removeItem: storage.removeItem.bind(storage),\n\n listItems() {\n if ('listItems' in storage) {\n return storage.listItems();\n }\n\n return promiseChain(() => {\n if ('keys' in storage) {\n return storage.keys();\n } else {\n return promiseChain(\n storage.length instanceof Function ? storage.length() : storage.length,\n )\n .next((length) => {\n const keys = Array.from({ length }, (_, index) => storage.key(index));\n return keys.some(isPromise) ? Promise.all(keys) : (keys as (string | null)[]);\n })\n .next((keys) => {\n return keys.filter((key): key is string => typeof key === 'string');\n }).value;\n }\n })\n .next((keys) => {\n const results = keys.map(\n (key) =>\n promiseChain(storage.getItem(key)).next((value) => [key, value] as const).value,\n );\n\n return results.some(isPromise)\n ? Promise.all(results)\n : (results as [string, string | null][]);\n })\n .next((results) => {\n return new Map(results.filter(([, value]) => value !== null) as [string, string][]);\n }).value;\n },\n };\n}\n","import { type Cancel, type Duration, type Store } from '@core';\nimport { calcDuration } from '@lib/calcDuration';\nimport { shallowEqual } from '@lib/equals';\nimport { fromExtendedJsonString, toExtendedJsonString } from '@lib/extendedJson';\nimport isPromise from '@lib/isPromise';\nimport type { KeyType, WildcardPath } from '@lib/path';\nimport promiseChain from '@lib/promiseChain';\nimport { castArrayPath, get, remove, set } from '@lib/propAccess';\nimport { queue } from '@lib/queue';\nimport { subscribePatches } from '@patches/patchMethods';\nimport { isAncestor, split } from '@persist/persistPathHelpers';\nimport {\n normalizeStorage,\n type PersistStorage,\n type PersistStorageWithListItems,\n} from './persistStorage';\n\ntype PathOption<T> =\n | WildcardPath<T>\n | {\n path: WildcardPath<T>;\n // throttle?: Duration;\n };\n\ntype Key = { type: 'internal'; path: string } | { type: 'data'; path: KeyType[] };\n\nexport interface PersistOptions<T> {\n id: string;\n storage: PersistStorage;\n paths?: PathOption<T>[];\n throttle?: Duration;\n persistInitialState?: boolean;\n}\n\nexport class Persist<T> {\n readonly storage: PersistStorageWithListItems;\n readonly [Symbol.dispose]!: Cancel;\n\n readonly paths: {\n path: KeyType[];\n throttle?: number;\n }[];\n\n readonly initialized: Promise<void>;\n\n private resolveInitialized?: () => void;\n\n private channel: BroadcastChannel;\n\n private queue = queue();\n\n private handles = new Set<Cancel>();\n\n private stopped = false;\n\n private updateInProgress = new Map<string, unknown>();\n\n private prefix;\n\n constructor(\n public readonly store: Store<T>,\n public readonly options: PersistOptions<T>,\n ) {\n this.storage = normalizeStorage(options.storage);\n this.channel = new BroadcastChannel(`cross-state-persist_${options.id}`);\n this.prefix = `${options.id}:`;\n\n if (Symbol.dispose) {\n this[Symbol.dispose] = () => this.stop();\n }\n\n this.paths = (options.paths ?? [])\n .map<{\n path: KeyType[];\n throttle?: number;\n }>((p) => {\n if (isPlainPath(p)) {\n return {\n path: castArrayPath(p),\n throttle: options.throttle && calcDuration(options.throttle),\n };\n }\n\n const _p = p as { path: KeyType[]; throttle?: Duration };\n\n return {\n path: castArrayPath(_p.path),\n throttle:\n (_p.throttle && calcDuration(_p.throttle)) ??\n (options.throttle && calcDuration(options.throttle)),\n };\n })\n .sort((a, b) => b.path.length - a.path.length);\n\n if (this.paths.length === 0) {\n this.paths.push({\n path: ['*'],\n throttle: options.throttle && calcDuration(options.throttle),\n });\n }\n\n this.initialized = new Promise((resolve) => {\n this.resolveInitialized = resolve;\n });\n\n this.watchStore();\n this.watchStorage();\n }\n\n private watchStore() {\n const throttle = Math.min(...this.paths.map((p) => p.throttle ?? 0)) || undefined;\n\n const cancel = subscribePatches.apply(this.store as Store<unknown>, [\n (patches, reversePatches) => {\n let i = 0;\n for (const patch of patches) {\n const reversePatch = reversePatches[i++];\n\n const stringPath = JSON.stringify(patch.path);\n if (\n this.updateInProgress.has(stringPath) &&\n this.updateInProgress.get(stringPath) ===\n (patch.op === 'remove' ? undefined : patch.value)\n ) {\n continue;\n }\n\n const matchingPaths = this.paths.filter(\n (p) => isAncestor(p.path, patch.path) || isAncestor(patch.path, p.path),\n );\n\n for (const { path } of matchingPaths) {\n if (path.length <= patch.path.length) {\n const pathToSave = patch.path.slice(0, path.length);\n this.queue(() => this.save(pathToSave), pathToSave);\n } else if (patch.op === 'remove') {\n const subValues = split(\n reversePatch?.op === 'add' ? reversePatch.value : {},\n path.slice(patch.path.length),\n );\n\n for (const { path } of subValues) {\n this.queue(() => this.save([...patch.path, ...path]), [...patch.path, ...path]);\n }\n } else {\n const updatedValues = split(patch.value, path.slice(patch.path.length));\n const removedValues = split(\n reversePatch?.op !== 'remove' ? (reversePatch?.value ?? {}) : {},\n path.slice(patch.path.length),\n ).filter((v) => !updatedValues.some((u) => shallowEqual(u.path, v.path)));\n\n for (const { path } of updatedValues) {\n this.queue(() => this.save([...patch.path, ...path]), [...patch.path, ...path]);\n }\n for (const { path } of removedValues) {\n this.queue(() => this.save([...patch.path, ...path]), [...patch.path, ...path]);\n }\n }\n }\n }\n },\n { runNow: this.options.persistInitialState ?? false, passive: true, throttle },\n ]);\n\n this.handles.add(cancel);\n }\n\n private async watchStorage() {\n if (!this.options.persistInitialState) {\n let items = this.storage.listItems();\n if (isPromise(items)) {\n items = await items;\n }\n\n if (this.stopped) {\n return;\n }\n\n const toLoad = new Map(\n [...items.entries()]\n .sort((a, b) => b[1].length - a[1].length)\n .map(([key, value]) => [this.parseKey(key), value])\n .filter(([key]) => key) as [Key, string][],\n );\n\n this.queue(() => this.load(toLoad));\n }\n\n this.queue(() => this.resolveInitialized?.());\n\n const listener = (event: MessageEvent) => {\n this.queue(() => this.load([{ type: 'data', path: event.data }]));\n };\n\n this.channel.addEventListener('message', listener);\n this.handles.add(() => this.channel.removeEventListener('message', listener));\n }\n\n private buildKey({ type, path }: Key) {\n return `${this.prefix}${type === 'internal' ? path : JSON.stringify(path)}`;\n }\n\n private parseKey(key: string): Key | undefined {\n if (!key.startsWith(this.prefix)) {\n return;\n }\n\n key = key.slice(this.prefix.length);\n\n if (!key.startsWith('[')) {\n return { type: 'internal', path: key };\n }\n\n return { type: 'data', path: JSON.parse(key) as KeyType[] };\n }\n\n private load(items: Key[] | Map<Key, string>): void | Promise<void> {\n return promiseChain(() => {\n if (Array.isArray(items)) {\n return promiseChain(() => {\n const entries = items.map(\n (key) =>\n promiseChain(() => {\n return this.storage.getItem(this.buildKey(key));\n }).next((value) => [key, value] as const).value,\n );\n\n return entries.some(isPromise)\n ? Promise.all(entries)\n : (entries as [Key, string | null][]);\n }).next((entries) => {\n return entries.filter((entry) => entry !== null) as [Key, string][];\n }).value;\n } else {\n return [...items.entries()];\n }\n }).next((entries) => {\n if (this.stopped) {\n return;\n }\n\n const toWrite = entries\n .filter(([key, value]) => {\n if (key.type !== 'data' || !value) {\n return;\n }\n\n if (\n !this.paths.find(\n (p) =>\n (p.path.length === 1 && p.path[0] === '*' && key.path.length === 0) ||\n (p.path.length === key.path.length && isAncestor(p.path, key.path)),\n )\n ) {\n return null;\n }\n\n const inSaveQueue = this.queue\n .getRefs()\n .find((ref) => isAncestor(ref, key.path) || isAncestor(key.path, ref));\n return !inSaveQueue;\n })\n .map(([key, value]) => {\n try {\n return {\n path: key.path,\n value: !value || value === 'undefined' ? undefined : fromExtendedJsonString(value),\n };\n } catch {\n return undefined;\n }\n })\n .filter(Boolean) as { path: KeyType[]; value: unknown }[];\n\n if (toWrite.length > 0) {\n for (const { path, value } of toWrite) {\n this.updateInProgress.set(JSON.stringify(path), value);\n }\n\n this.store.set((state) => {\n for (const { path, value } of toWrite) {\n if (value === undefined) {\n state = remove(state, path as any);\n } else {\n state = set(state, path as any, value);\n }\n }\n\n return state;\n });\n\n this.updateInProgress.clear();\n }\n\n const versionEntry = entries.find(\n ([key]) => key.type === 'internal' && key.path === 'version',\n );\n if (versionEntry) {\n this.store.version = versionEntry[1];\n }\n }).value;\n }\n\n private save(path: KeyType[]): void | Promise<unknown> {\n const key = this.buildKey({ type: 'data', path });\n const value = get(this.store.get() as any, path);\n\n return promiseChain(value)\n .next((value) => {\n if (value === undefined) {\n return this.storage.removeItem(key);\n } else {\n return this.storage.setItem(key, toExtendedJsonString(value));\n }\n })\n .next(() => {\n this.channel.postMessage(path);\n\n if (this.store.version) {\n return this.storage.setItem(\n this.buildKey({ type: 'internal', path: 'version' }),\n this.store.version,\n );\n } else {\n return this.storage.removeItem(this.buildKey({ type: 'internal', path: 'version' }));\n }\n }).value;\n }\n\n async stop(): Promise<void> {\n this.stopped = true;\n\n for (const handle of this.handles) {\n handle();\n }\n\n await this.queue.whenDone();\n this.channel.close();\n }\n}\n\nexport function persist<T>(store: Store<T>, options: PersistOptions<T>): Persist<T> {\n return new Persist<T>(store, options);\n}\n\nfunction isPlainPath<T>(p: PathOption<T>): p is WildcardPath<T> & (KeyType[] | string) {\n return typeof p === 'string' || Array.isArray(p);\n}\n"],"mappings":";;;;;;AAOA,SAAwB,aAAgB,OAAgC;AACtE,KAAI,iBAAiB,SACnB,SAAQ;AAGV,QAAO;EACL;EACA,KAAK,IAAI;GACP,MAAM,OAAOA,wBAAU,SACnB,MAAM,MAAM,YAAU,GAAGC,YACzB,GAAG;AAEP,UAAO,aAAa;;;;;;;ACjB1B,MAAa,cAAc,UAAqB,SAA6B;AAC3E,QACE,SAAS,UAAU,KAAK,UACxB,SAAS,OAAO,GAAG,MAAM,MAAM,OAAO,KAAK,OAAO,OAAO,MAAM,KAAK;;AAIxE,MAAa,SAAS,OAAY,SAA2D;CAC3F,MAAM,CAAC,OAAO,GAAG,QAAQ;AACzB,KAAI,UAAU,OAAW,QAAO,CAAC;EAAE,MAAM;EAAI;;CAE7C,IAAIC;AACJ,KAAI,iBAAiB,IACnB,WAAU;UACD,iBAAiB,IAC1B,WAAU,IAAI,IAAI,CAAC,GAAG,OAAO,KAAK,GAAG,MAAM,CAAC,GAAG;UACtC,MAAM,QAAQ,OACvB,WAAU,IAAI,IAAI,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG;UACjC,OAAO,UAAU,YAAY,UAAU,KAChD,WAAU,IAAI,IAAI,OAAO,QAAQ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AAW,KAAK,SAAS;IAAE,MAAM;IAAY,MAAM;;KAExE;;CAGP,MAAM,OAAsB;AAC1B,OAAK,UAAU;AAEf,OAAK,MAAM,UAAU,KAAK,QACxB;AAGF,QAAM,KAAK,MAAM;AACjB,OAAK,QAAQ;;;AAIjB,SAAgB,QAAW,OAAiB,SAAwC;AAClF,QAAO,IAAI,QAAW,OAAO;;AAG/B,SAAS,YAAe,GAA+D;AACrF,QAAO,OAAO,MAAM,YAAY,MAAM,QAAQ"}
|
|
1
|
+
{"version":3,"file":"persist-CGLe7YUX.cjs","names":["isPromise","value","entries: Map<KeyType, unknown>","path","isPromise","store: Store<T>","options: PersistOptions<T>","queue","castArrayPath","calcDuration","subscribePatches","path","shallowEqual","isPromise","fromExtendedJsonString","remove","set","get","value","toExtendedJsonString"],"sources":["../src/lib/promiseChain.ts","../src/persist/persistPathHelpers.ts","../src/persist/persistStorage.ts","../src/persist/persist.ts"],"sourcesContent":["import isPromise from '@lib/isPromise';\n\nexport interface Chain<T> {\n value: T;\n next<S>(fn: (value: Awaited<T>) => S): T extends Promise<any> ? Chain<Promise<S>> : Chain<S>;\n}\n\nexport default function promiseChain<T>(value: T | (() => T)): Chain<T> {\n if (value instanceof Function) {\n value = value();\n }\n\n return {\n value,\n next(fn) {\n const next = isPromise(value)\n ? value.then((value) => fn(value as Awaited<T>))\n : fn(value as Awaited<T>);\n\n return promiseChain(next) as any;\n },\n };\n}\n","import type { KeyType } from '@lib/path';\n\nexport const isAncestor = (ancestor: KeyType[], path: KeyType[]): boolean => {\n return (\n ancestor.length <= path.length &&\n ancestor.every((v, i) => v === '*' || path[i] === '*' || v === path[i])\n );\n};\n\nexport const split = (value: any, path: KeyType[]): { path: KeyType[]; value: unknown }[] => {\n const [first, ...rest] = path;\n if (first === undefined) return [{ path: [], value }];\n\n let entries: Map<KeyType, unknown>;\n if (value instanceof Map) {\n entries = value;\n } else if (value instanceof Set) {\n entries = new Map([...value].map((v, i) => [i, v]));\n } else if (Array.isArray(value)) {\n entries = new Map(value.map((v, i) => [i, v]));\n } else if (typeof value === 'object' && value !== null) {\n entries = new Map(Object.entries(value));\n } else {\n return [{ path: [], value }];\n }\n\n if (first === '*') {\n return [...entries].flatMap(([k, v]) =>\n split(v, rest).map(({ path, value }) => ({ path: [k, ...path], value })),\n );\n }\n\n const subValue = entries.get(first);\n if (subValue === undefined) return [{ path: [], value }];\n\n return split(subValue, rest).map(({ path, value }) => ({ path: [first, ...path], value }));\n};\n","import isPromise from '@lib/isPromise';\nimport promiseChain from '@lib/promiseChain';\n\nexport interface PersistStorageBase {\n getItem: (key: string) => string | null | Promise<string | null>;\n setItem: (key: string, value: string) => void | Promise<unknown>;\n removeItem: (key: string) => void | Promise<unknown>;\n}\n\nexport interface PersistStorageWithKeys extends PersistStorageBase {\n keys: () => string[] | Promise<string[]>;\n}\n\nexport interface PersistStorageWithLength extends PersistStorageBase {\n length: number | (() => number | Promise<number>);\n key: (keyIndex: number) => string | null | Promise<string | null>;\n}\n\nexport interface PersistStorageWithListItems extends PersistStorageBase {\n listItems: () => Map<string, string> | Promise<Map<string, string>>;\n}\n\nexport type PersistStorage =\n | PersistStorageWithKeys\n | PersistStorageWithLength\n | PersistStorageWithListItems;\n\nexport function normalizeStorage(storage: PersistStorage): PersistStorageWithListItems {\n return {\n getItem: storage.getItem.bind(storage),\n setItem: storage.setItem.bind(storage),\n removeItem: storage.removeItem.bind(storage),\n\n listItems() {\n if ('listItems' in storage) {\n return storage.listItems();\n }\n\n return promiseChain(() => {\n if ('keys' in storage) {\n return storage.keys();\n } else {\n return promiseChain(\n storage.length instanceof Function ? storage.length() : storage.length,\n )\n .next((length) => {\n const keys = Array.from({ length }, (_, index) => storage.key(index));\n return keys.some(isPromise) ? Promise.all(keys) : (keys as (string | null)[]);\n })\n .next((keys) => {\n return keys.filter((key): key is string => typeof key === 'string');\n }).value;\n }\n })\n .next((keys) => {\n const results = keys.map(\n (key) =>\n promiseChain(storage.getItem(key)).next((value) => [key, value] as const).value,\n );\n\n return results.some(isPromise)\n ? Promise.all(results)\n : (results as [string, string | null][]);\n })\n .next((results) => {\n return new Map(results.filter(([, value]) => value !== null) as [string, string][]);\n }).value;\n },\n };\n}\n","import { type Cancel, type Duration, type Store } from '@core';\nimport { calcDuration } from '@lib/calcDuration';\nimport { shallowEqual } from '@lib/equals';\nimport { fromExtendedJsonString, toExtendedJsonString } from '@lib/extendedJson';\nimport isPromise from '@lib/isPromise';\nimport type { KeyType, WildcardPath } from '@lib/path';\nimport promiseChain from '@lib/promiseChain';\nimport { castArrayPath, get, remove, set } from '@lib/propAccess';\nimport { queue } from '@lib/queue';\nimport { subscribePatches } from '@patches/patchMethods';\nimport { isAncestor, split } from '@persist/persistPathHelpers';\nimport {\n normalizeStorage,\n type PersistStorage,\n type PersistStorageWithListItems,\n} from './persistStorage';\n\ntype PathOption<T> =\n | WildcardPath<T>\n | {\n path: WildcardPath<T>;\n // throttle?: Duration;\n };\n\ntype Key = { type: 'internal'; path: string } | { type: 'data'; path: KeyType[] };\n\nexport interface PersistOptions<T> {\n id: string;\n storage: PersistStorage;\n paths?: PathOption<T>[];\n throttle?: Duration;\n persistInitialState?: boolean;\n}\n\nexport class Persist<T> {\n readonly storage: PersistStorageWithListItems;\n readonly [Symbol.dispose]!: Cancel;\n\n readonly paths: {\n path: KeyType[];\n throttle?: number;\n }[];\n\n readonly initialized: Promise<void>;\n\n private resolveInitialized?: () => void;\n\n private channel: BroadcastChannel;\n\n private queue = queue();\n\n private handles = new Set<Cancel>();\n\n private stopped = false;\n\n private updateInProgress = new Map<string, unknown>();\n\n private prefix;\n\n constructor(\n public readonly store: Store<T>,\n public readonly options: PersistOptions<T>,\n ) {\n this.storage = normalizeStorage(options.storage);\n this.channel = new BroadcastChannel(`cross-state-persist_${options.id}`);\n this.prefix = `${options.id}:`;\n\n if (Symbol.dispose) {\n this[Symbol.dispose] = () => this.stop();\n }\n\n this.paths = (options.paths ?? [])\n .map<{\n path: KeyType[];\n throttle?: number;\n }>((p) => {\n if (isPlainPath(p)) {\n return {\n path: castArrayPath(p),\n throttle: options.throttle && calcDuration(options.throttle),\n };\n }\n\n const _p = p as { path: KeyType[]; throttle?: Duration };\n\n return {\n path: castArrayPath(_p.path),\n throttle:\n (_p.throttle && calcDuration(_p.throttle)) ??\n (options.throttle && calcDuration(options.throttle)),\n };\n })\n .sort((a, b) => b.path.length - a.path.length);\n\n if (this.paths.length === 0) {\n this.paths.push({\n path: ['*'],\n throttle: options.throttle && calcDuration(options.throttle),\n });\n }\n\n this.initialized = new Promise((resolve) => {\n this.resolveInitialized = resolve;\n });\n\n this.watchStore();\n this.watchStorage();\n }\n\n private watchStore() {\n const throttle = Math.min(...this.paths.map((p) => p.throttle ?? 0)) || undefined;\n\n const cancel = subscribePatches.apply(this.store as Store<unknown>, [\n (patches, reversePatches) => {\n let i = 0;\n for (const patch of patches) {\n const reversePatch = reversePatches[i++];\n\n const stringPath = JSON.stringify(patch.path);\n if (\n this.updateInProgress.has(stringPath) &&\n this.updateInProgress.get(stringPath) ===\n (patch.op === 'remove' ? undefined : patch.value)\n ) {\n continue;\n }\n\n const matchingPaths = this.paths.filter(\n (p) => isAncestor(p.path, patch.path) || isAncestor(patch.path, p.path),\n );\n\n for (const { path } of matchingPaths) {\n if (path.length <= patch.path.length) {\n const pathToSave = patch.path.slice(0, path.length);\n this.queue(() => this.save(pathToSave), pathToSave);\n } else if (patch.op === 'remove') {\n const subValues = split(\n reversePatch?.op === 'add' ? reversePatch.value : {},\n path.slice(patch.path.length),\n );\n\n for (const { path } of subValues) {\n this.queue(() => this.save([...patch.path, ...path]), [...patch.path, ...path]);\n }\n } else {\n const updatedValues = split(patch.value, path.slice(patch.path.length));\n const removedValues = split(\n reversePatch?.op !== 'remove' ? (reversePatch?.value ?? {}) : {},\n path.slice(patch.path.length),\n ).filter((v) => !updatedValues.some((u) => shallowEqual(u.path, v.path)));\n\n for (const { path } of updatedValues) {\n this.queue(() => this.save([...patch.path, ...path]), [...patch.path, ...path]);\n }\n for (const { path } of removedValues) {\n this.queue(() => this.save([...patch.path, ...path]), [...patch.path, ...path]);\n }\n }\n }\n }\n },\n { runNow: this.options.persistInitialState ?? false, passive: true, throttle },\n ]);\n\n this.handles.add(cancel);\n }\n\n private async watchStorage() {\n if (!this.options.persistInitialState) {\n let items = this.storage.listItems();\n if (isPromise(items)) {\n items = await items;\n }\n\n if (this.stopped) {\n return;\n }\n\n const toLoad = new Map(\n [...items.entries()]\n .sort((a, b) => b[1].length - a[1].length)\n .map(([key, value]) => [this.parseKey(key), value])\n .filter(([key]) => key) as [Key, string][],\n );\n\n this.queue(() => this.load(toLoad));\n }\n\n this.queue(() => this.resolveInitialized?.());\n\n const listener = (event: MessageEvent) => {\n this.queue(() => this.load([{ type: 'data', path: event.data }]));\n };\n\n this.channel.addEventListener('message', listener);\n this.handles.add(() => this.channel.removeEventListener('message', listener));\n }\n\n private buildKey({ type, path }: Key) {\n return `${this.prefix}${type === 'internal' ? path : JSON.stringify(path)}`;\n }\n\n private parseKey(key: string): Key | undefined {\n if (!key.startsWith(this.prefix)) {\n return;\n }\n\n key = key.slice(this.prefix.length);\n\n if (!key.startsWith('[')) {\n return { type: 'internal', path: key };\n }\n\n return { type: 'data', path: JSON.parse(key) as KeyType[] };\n }\n\n private load(items: Key[] | Map<Key, string>): void | Promise<void> {\n return promiseChain(() => {\n if (Array.isArray(items)) {\n return promiseChain(() => {\n const entries = items.map(\n (key) =>\n promiseChain(() => {\n return this.storage.getItem(this.buildKey(key));\n }).next((value) => [key, value] as const).value,\n );\n\n return entries.some(isPromise)\n ? Promise.all(entries)\n : (entries as [Key, string | null][]);\n }).next((entries) => {\n return entries.filter((entry) => entry !== null) as [Key, string][];\n }).value;\n } else {\n return [...items.entries()];\n }\n }).next((entries) => {\n if (this.stopped) {\n return;\n }\n\n const toWrite = entries\n .filter(([key, value]) => {\n if (key.type !== 'data' || !value) {\n return;\n }\n\n if (\n !this.paths.find(\n (p) =>\n (p.path.length === 1 && p.path[0] === '*' && key.path.length === 0) ||\n (p.path.length === key.path.length && isAncestor(p.path, key.path)),\n )\n ) {\n return null;\n }\n\n const inSaveQueue = this.queue\n .getRefs()\n .find((ref) => isAncestor(ref, key.path) || isAncestor(key.path, ref));\n return !inSaveQueue;\n })\n .map(([key, value]) => {\n try {\n return {\n path: key.path,\n value: !value || value === 'undefined' ? undefined : fromExtendedJsonString(value),\n };\n } catch {\n return undefined;\n }\n })\n .filter(Boolean) as { path: KeyType[]; value: unknown }[];\n\n if (toWrite.length > 0) {\n for (const { path, value } of toWrite) {\n this.updateInProgress.set(JSON.stringify(path), value);\n }\n\n this.store.set((state) => {\n for (const { path, value } of toWrite) {\n if (value === undefined) {\n state = remove(state, path as any);\n } else {\n state = set(state, path as any, value);\n }\n }\n\n return state;\n });\n\n this.updateInProgress.clear();\n }\n\n const versionEntry = entries.find(\n ([key]) => key.type === 'internal' && key.path === 'version',\n );\n if (versionEntry) {\n this.store.version = versionEntry[1];\n }\n }).value;\n }\n\n private save(path: KeyType[]): void | Promise<unknown> {\n const key = this.buildKey({ type: 'data', path });\n const value = get(this.store.get() as any, path);\n\n return promiseChain(value)\n .next((value) => {\n if (value === undefined) {\n return this.storage.removeItem(key);\n } else {\n return this.storage.setItem(key, toExtendedJsonString(value));\n }\n })\n .next(() => {\n this.channel.postMessage(path);\n\n if (this.store.version) {\n return this.storage.setItem(\n this.buildKey({ type: 'internal', path: 'version' }),\n this.store.version,\n );\n } else {\n return this.storage.removeItem(this.buildKey({ type: 'internal', path: 'version' }));\n }\n }).value;\n }\n\n async stop(): Promise<void> {\n this.stopped = true;\n\n for (const handle of this.handles) {\n handle();\n }\n\n await this.queue.whenDone();\n this.channel.close();\n }\n}\n\nexport function persist<T>(store: Store<T>, options: PersistOptions<T>): Persist<T> {\n return new Persist<T>(store, options);\n}\n\nfunction isPlainPath<T>(p: PathOption<T>): p is WildcardPath<T> & (KeyType[] | string) {\n return typeof p === 'string' || Array.isArray(p);\n}\n"],"mappings":";;;;;;AAOA,SA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,KAAK,UAAU;AACxB,UAAK,MAAM,EAAE,MAAM,WAAW,QAC5B,KAAI,UAAU,OACZ,SAAQC,0BAAO,OAAO;SAEtB,SAAQC,uBAAI,OAAO,MAAa;AAIpC,YAAO;;AAGT,SAAK,iBAAiB;;GAGxB,MAAM,eAAe,QAAQ,MAC1B,CAAC,SAAS,IAAI,SAAS,cAAc,IAAI,SAAS;AAErD,OAAI,aACF,MAAK,MAAM,UAAU,aAAa;KAEnC;;CAGL,AAAQ,KAAK,MAA0C;EACrD,MAAM,MAAM,KAAK,SAAS;GAAE,MAAM;GAAQ;;EAC1C,MAAM,QAAQC,uBAAI,KAAK,MAAM,OAAc;AAE3C,SAAO,aAAa,OACjB,MAAM,YAAU;AACf,OAAIC,YAAU,OACZ,QAAO,KAAK,QAAQ,WAAW;OAE/B,QAAO,KAAK,QAAQ,QAAQ,KAAKC,0CAAqBD;KAGzD,WAAW;AACV,QAAK,QAAQ,YAAY;AAEzB,OAAI,KAAK,MAAM,QACb,QAAO,KAAK,QAAQ,QAClB,KAAK,SAAS;IAAE,MAAM;IAAY,MAAM;OACxC,KAAK,MAAM;OAGb,QAAO,KAAK,QAAQ,WAAW,KAAK,SAAS;IAAE,MAAM;IAAY,MAAM;;KAExE;;CAGP,MAAM,OAAsB;AAC1B,OAAK,UAAU;AAEf,OAAK,MAAM,UAAU,KAAK,QACxB;AAGF,QAAM,KAAK,MAAM;AACjB,OAAK,QAAQ;;;AAIjB,SAAgB,QAAW,OAAiB,SAAwC;AAClF,QAAO,IAAI,QAAW,OAAO;;AAG/B,SAAS,YAAe,GAA+D;AACrF,QAAO,OAAO,MAAM,YAAY,MAAM,QAAQ"}
|
|
@@ -6,7 +6,7 @@ function shallowEqual(a, b, options) {
|
|
|
6
6
|
return internalEqual(a, b, strictEqual, options);
|
|
7
7
|
}
|
|
8
8
|
function deepEqual(a, b, options) {
|
|
9
|
-
return internalEqual(a, b, deepEqual, options);
|
|
9
|
+
return internalEqual(a, b, (a$1, b$1) => deepEqual(a$1, b$1, options), options);
|
|
10
10
|
}
|
|
11
11
|
const internalEqual = (a, b, comp, { undefinedEqualsAbsent = false } = {}) => {
|
|
12
12
|
if (a === b) return true;
|
|
@@ -122,4 +122,4 @@ function join(a, b) {
|
|
|
122
122
|
|
|
123
123
|
//#endregion
|
|
124
124
|
export { castArrayPath, deepEqual, get, isObject, isPlainObject, join, remove, set, shallowEqual, strictEqual };
|
|
125
|
-
//# sourceMappingURL=propAccess-
|
|
125
|
+
//# sourceMappingURL=propAccess-B260LXN1.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"propAccess-B260LXN1.js","names":["a","b"],"sources":["../src/lib/equals.ts","../src/lib/helpers.ts","../src/lib/clone.ts","../src/lib/propAccess.ts"],"sourcesContent":["export interface EqualityOptions {\n /** Treat undefined values as absent\n * @default false\n */\n undefinedEqualsAbsent?: boolean;\n}\n\nexport function strictEqual(a: any, b: any): boolean {\n return a === b;\n}\n\nexport function shallowEqual(a: any, b: any, options?: EqualityOptions): boolean {\n return internalEqual(a, b, strictEqual, options);\n}\n\nexport function deepEqual(a: any, b: any, options?: EqualityOptions): boolean {\n return internalEqual(a, b, (a, b) => deepEqual(a, b, options), options);\n}\n\nconst internalEqual = (\n a: any,\n b: any,\n comp: (a: any, b: any) => boolean,\n { undefinedEqualsAbsent = false }: EqualityOptions = {},\n) => {\n if (a === b) {\n return true;\n }\n\n if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') {\n // eslint-disable-next-line no-self-compare\n return a !== a && b !== b;\n }\n\n if (a.constructor !== b.constructor) {\n return false;\n }\n\n if (a.constructor === Object || Array.isArray(a)) {\n let entries1 = Object.entries(a);\n let entries2 = Object.entries(b);\n\n if (undefinedEqualsAbsent) {\n entries1 = entries1.filter(([_, value]) => value !== undefined);\n entries2 = entries2.filter(([_, value]) => value !== undefined);\n }\n\n return (\n entries1.length === entries2.length &&\n entries1.every(([key, value]) => key in b && comp(value, b[key]))\n );\n }\n\n if (a instanceof Date) {\n return a.getTime() === b.getTime();\n }\n\n if (a instanceof RegExp) {\n return a.source === b.source && a.flags === b.flags;\n }\n\n if (a instanceof Map) {\n let entries1 = [...a.entries()];\n let entries2 = [...b.entries()];\n\n if (undefinedEqualsAbsent) {\n entries1 = entries1.filter(([_, value]) => value !== undefined);\n entries2 = entries2.filter(([_, value]) => value !== undefined);\n }\n\n return (\n entries1.length === entries2.length &&\n entries1.every(([key, value]) => b.has(key) && comp(value, b.get(key)))\n );\n }\n\n if (a instanceof Set) {\n return a.size === b.size && [...a.values()].every((value) => b.has(value));\n }\n\n if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView(a)) {\n if (a.byteLength !== b.byteLength) {\n return false;\n }\n\n const a_ = new Int8Array(a.buffer);\n const b_ = new Int8Array(b.buffer);\n return a_.every((value, i) => value === b_[i]);\n }\n\n return false;\n};\n","export function isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n\n const prototype = Object.getPrototypeOf(value);\n return (\n (prototype === null ||\n prototype === Object.prototype ||\n Object.getPrototypeOf(prototype) === null) &&\n !(Symbol.toStringTag in value) &&\n !(Symbol.iterator in value)\n );\n}\n","import { isObject } from '@lib/helpers';\n\nexport function flatClone<T>(object: T): T {\n if (object instanceof Map) {\n return new Map(object) as any;\n }\n\n if (object instanceof Set) {\n return new Set(object) as any;\n }\n\n if (Array.isArray(object)) {\n return [...object] as any;\n }\n\n if (isObject(object)) {\n return { ...object };\n }\n\n return object;\n}\n","import type { Constrain } from '@lib/constrain';\nimport { isObject } from '@lib/helpers';\nimport { flatClone } from './clone';\nimport type { KeyType, Path, SettablePath, SettableValue, Value } from './path';\n\nexport function castArrayPath(path: string | KeyType[]): KeyType[] {\n if (Array.isArray(path)) {\n return path;\n }\n\n if (path === '') {\n return [];\n }\n\n return (path as string).split('.');\n}\n\nexport function get<T, const P>(object: T, path: Constrain<P, Path<T>>): Value<T, P> {\n const _path = castArrayPath(path as any);\n const [first, ...rest] = _path;\n\n if (first === undefined || !object) {\n return object as Value<T, P>;\n }\n\n if (object instanceof Map) {\n return get(object.get(first), rest);\n }\n\n if (object instanceof Set) {\n return get(Array.from(object)[Number(first)], rest);\n }\n\n if (isObject(object)) {\n return get(object[first as keyof T], rest as any) as Value<T, P>;\n }\n\n throw new Error(`Could not get ${path} of ${object}`);\n}\n\nexport function set<T, const P>(\n object: T,\n path: Constrain<P, SettablePath<T>>,\n value: SettableValue<T, P>,\n rootPath: string | readonly KeyType[] = path,\n): T {\n const _path = castArrayPath(path as any);\n const [first, ...rest] = _path;\n\n if (first === undefined) {\n return value as T;\n }\n\n if (object instanceof Map) {\n const copy = flatClone(object);\n const child = copy.get(first);\n copy.set(first, set(child, rest as any, value, rootPath));\n return copy;\n }\n\n if (object instanceof Set) {\n const copy = [...object];\n const child = copy[Number(first)];\n copy[Number(first)] = set(child, rest as any, value, rootPath);\n return new Set(copy) as any;\n }\n\n if (isObject(object) || object === undefined) {\n const copy = flatClone(object ?? ({} as T));\n copy[first as keyof T] = set(copy[first as keyof T], rest as any, value as any, rootPath);\n return copy;\n }\n\n throw new Error(`Could not set ${path} of ${object}`);\n}\n\nexport function remove<T, const P>(object: T, path: Constrain<P, Path<T, true>>): T {\n const _path = castArrayPath(path as any);\n\n if (_path.length === 0) {\n return undefined as any;\n }\n\n const parentPath = _path.slice(0, -1);\n const key = _path[_path.length - 1];\n\n const parent = flatClone(get(object, parentPath as any));\n\n if (parent instanceof Map) {\n parent.delete(key);\n } else if (parent instanceof Set) {\n const value = Array.from(parent)[Number(key)];\n parent.delete(value);\n } else if (Array.isArray(parent)) {\n parent.splice(Number(key), 1);\n } else {\n delete parent[key as keyof typeof parent];\n }\n\n return set(object, parentPath as any, parent);\n}\n\nexport function join(a: string, b: string): string {\n return [a, b].filter(Boolean).join('.');\n}\n"],"mappings":";AAOA,SAAgB,YAAY,GA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GAAG,OAAO,SAAS,KAAK"}
|
|
@@ -7,7 +7,7 @@ function shallowEqual(a, b, options) {
|
|
|
7
7
|
return internalEqual(a, b, strictEqual, options);
|
|
8
8
|
}
|
|
9
9
|
function deepEqual(a, b, options) {
|
|
10
|
-
return internalEqual(a, b, deepEqual, options);
|
|
10
|
+
return internalEqual(a, b, (a$1, b$1) => deepEqual(a$1, b$1, options), options);
|
|
11
11
|
}
|
|
12
12
|
const internalEqual = (a, b, comp, { undefinedEqualsAbsent = false } = {}) => {
|
|
13
13
|
if (a === b) return true;
|
|
@@ -182,4 +182,4 @@ Object.defineProperty(exports, 'strictEqual', {
|
|
|
182
182
|
return strictEqual;
|
|
183
183
|
}
|
|
184
184
|
});
|
|
185
|
-
//# sourceMappingURL=propAccess-
|
|
185
|
+
//# sourceMappingURL=propAccess-BdLsqViO.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"propAccess-BdLsqViO.cjs","names":["a","b"],"sources":["../src/lib/equals.ts","../src/lib/helpers.ts","../src/lib/clone.ts","../src/lib/propAccess.ts"],"sourcesContent":["export interface EqualityOptions {\n /** Treat undefined values as absent\n * @default false\n */\n undefinedEqualsAbsent?: boolean;\n}\n\nexport function strictEqual(a: any, b: any): boolean {\n return a === b;\n}\n\nexport function shallowEqual(a: any, b: any, options?: EqualityOptions): boolean {\n return internalEqual(a, b, strictEqual, options);\n}\n\nexport function deepEqual(a: any, b: any, options?: EqualityOptions): boolean {\n return internalEqual(a, b, (a, b) => deepEqual(a, b, options), options);\n}\n\nconst internalEqual = (\n a: any,\n b: any,\n comp: (a: any, b: any) => boolean,\n { undefinedEqualsAbsent = false }: EqualityOptions = {},\n) => {\n if (a === b) {\n return true;\n }\n\n if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') {\n // eslint-disable-next-line no-self-compare\n return a !== a && b !== b;\n }\n\n if (a.constructor !== b.constructor) {\n return false;\n }\n\n if (a.constructor === Object || Array.isArray(a)) {\n let entries1 = Object.entries(a);\n let entries2 = Object.entries(b);\n\n if (undefinedEqualsAbsent) {\n entries1 = entries1.filter(([_, value]) => value !== undefined);\n entries2 = entries2.filter(([_, value]) => value !== undefined);\n }\n\n return (\n entries1.length === entries2.length &&\n entries1.every(([key, value]) => key in b && comp(value, b[key]))\n );\n }\n\n if (a instanceof Date) {\n return a.getTime() === b.getTime();\n }\n\n if (a instanceof RegExp) {\n return a.source === b.source && a.flags === b.flags;\n }\n\n if (a instanceof Map) {\n let entries1 = [...a.entries()];\n let entries2 = [...b.entries()];\n\n if (undefinedEqualsAbsent) {\n entries1 = entries1.filter(([_, value]) => value !== undefined);\n entries2 = entries2.filter(([_, value]) => value !== undefined);\n }\n\n return (\n entries1.length === entries2.length &&\n entries1.every(([key, value]) => b.has(key) && comp(value, b.get(key)))\n );\n }\n\n if (a instanceof Set) {\n return a.size === b.size && [...a.values()].every((value) => b.has(value));\n }\n\n if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView(a)) {\n if (a.byteLength !== b.byteLength) {\n return false;\n }\n\n const a_ = new Int8Array(a.buffer);\n const b_ = new Int8Array(b.buffer);\n return a_.every((value, i) => value === b_[i]);\n }\n\n return false;\n};\n","export function isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n\n const prototype = Object.getPrototypeOf(value);\n return (\n (prototype === null ||\n prototype === Object.prototype ||\n Object.getPrototypeOf(prototype) === null) &&\n !(Symbol.toStringTag in value) &&\n !(Symbol.iterator in value)\n );\n}\n","import { isObject } from '@lib/helpers';\n\nexport function flatClone<T>(object: T): T {\n if (object instanceof Map) {\n return new Map(object) as any;\n }\n\n if (object instanceof Set) {\n return new Set(object) as any;\n }\n\n if (Array.isArray(object)) {\n return [...object] as any;\n }\n\n if (isObject(object)) {\n return { ...object };\n }\n\n return object;\n}\n","import type { Constrain } from '@lib/constrain';\nimport { isObject } from '@lib/helpers';\nimport { flatClone } from './clone';\nimport type { KeyType, Path, SettablePath, SettableValue, Value } from './path';\n\nexport function castArrayPath(path: string | KeyType[]): KeyType[] {\n if (Array.isArray(path)) {\n return path;\n }\n\n if (path === '') {\n return [];\n }\n\n return (path as string).split('.');\n}\n\nexport function get<T, const P>(object: T, path: Constrain<P, Path<T>>): Value<T, P> {\n const _path = castArrayPath(path as any);\n const [first, ...rest] = _path;\n\n if (first === undefined || !object) {\n return object as Value<T, P>;\n }\n\n if (object instanceof Map) {\n return get(object.get(first), rest);\n }\n\n if (object instanceof Set) {\n return get(Array.from(object)[Number(first)], rest);\n }\n\n if (isObject(object)) {\n return get(object[first as keyof T], rest as any) as Value<T, P>;\n }\n\n throw new Error(`Could not get ${path} of ${object}`);\n}\n\nexport function set<T, const P>(\n object: T,\n path: Constrain<P, SettablePath<T>>,\n value: SettableValue<T, P>,\n rootPath: string | readonly KeyType[] = path,\n): T {\n const _path = castArrayPath(path as any);\n const [first, ...rest] = _path;\n\n if (first === undefined) {\n return value as T;\n }\n\n if (object instanceof Map) {\n const copy = flatClone(object);\n const child = copy.get(first);\n copy.set(first, set(child, rest as any, value, rootPath));\n return copy;\n }\n\n if (object instanceof Set) {\n const copy = [...object];\n const child = copy[Number(first)];\n copy[Number(first)] = set(child, rest as any, value, rootPath);\n return new Set(copy) as any;\n }\n\n if (isObject(object) || object === undefined) {\n const copy = flatClone(object ?? ({} as T));\n copy[first as keyof T] = set(copy[first as keyof T], rest as any, value as any, rootPath);\n return copy;\n }\n\n throw new Error(`Could not set ${path} of ${object}`);\n}\n\nexport function remove<T, const P>(object: T, path: Constrain<P, Path<T, true>>): T {\n const _path = castArrayPath(path as any);\n\n if (_path.length === 0) {\n return undefined as any;\n }\n\n const parentPath = _path.slice(0, -1);\n const key = _path[_path.length - 1];\n\n const parent = flatClone(get(object, parentPath as any));\n\n if (parent instanceof Map) {\n parent.delete(key);\n } else if (parent instanceof Set) {\n const value = Array.from(parent)[Number(key)];\n parent.delete(value);\n } else if (Array.isArray(parent)) {\n parent.splice(Number(key), 1);\n } else {\n delete parent[key as keyof typeof parent];\n }\n\n return set(object, parentPath as any, parent);\n}\n\nexport function join(a: string, b: string): string {\n return [a, b].filter(Boolean).join('.');\n}\n"],"mappings":";;AAOA,SAAgB,YAAY,GAAQ,GAAiB;AACnD,QAAO,MAAM;;AAGf,SAAgB,aAAa,GAAQ,GAAQ,SAAoC;AAC/E,QAAO,cAAc,GAAG,GAAG,aAAa;;AAG1C,SAAgB,UAAU,GAAQ,GAAQ,SAAoC;AAC5E,QAAO,cAAc,GAAG,IAAI,KAAG,QAAM,UAAUA,KAAGC,KAAG,UAAU;;AAGjE,MAAM,iBACJ,GACA,GACA,MACA,EAAE,wBAAwB,UAA2B,OAClD;AACH,KAAI,MAAM,EACR,QAAO;AAGT,KAAI,MAAM,QAAQ,MAAM,QAAQ,OAAO,MAAM,YAAY,OAAO,MAAM,SAEpE,QAAO,MAAM,KAAK,MAAM;AAG1B,KAAI,EAAE,gBAAgB,EAAE,YACtB,QAAO;AAGT,KAAI,EAAE,gBAAgB,UAAU,MAAM,QAAQ,IAAI;EAChD,IAAI,WAAW,OAAO,QAAQ;EAC9B,IAAI,WAAW,OAAO,QAAQ;AAE9B,MAAI,uBAAuB;AACzB,cAAW,SAAS,QAAQ,CAAC,GAAG,WAAW,UAAU;AACrD,cAAW,SAAS,QAAQ,CAAC,GAAG,WAAW,UAAU;;AAGvD,SACE,SAAS,WAAW,SAAS,UAC7B,SAAS,OAAO,CAAC,KAAK,WAAW,OAAO,KAAK,KAAK,OAAO,EAAE;;AAI/D,KAAI,aAAa,KACf,QAAO,EAAE,cAAc,EAAE;AAG3B,KAAI,aAAa,OACf,QAAO,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE;AAGhD,KAAI,aAAa,KAAK;EACpB,IAAI,WAAW,CAAC,GAAG,EAAE;EACrB,IAAI,WAAW,CAAC,GAAG,EAAE;AAErB,MAAI,uBAAuB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M,KAAK,QAAQ,OAAO;AACxC,SAAO,OAAO;YACL,MAAM,QAAQ,QACvB,QAAO,OAAO,OAAO,MAAM;KAE3B,QAAO,OAAO;AAGhB,QAAO,IAAI,QAAQ,YAAmB;;AAGxC,SAAgB,KAAK,GAAW,GAAmB;AACjD,QAAO,CAAC,GAAG,GAAG,OAAO,SAAS,KAAK"}
|
package/dist/react/index.cjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
const require_chunk = require('../chunk-CUT6urMc.cjs');
|
|
2
|
-
const require_store = require('../store-
|
|
3
|
-
const require_propAccess = require('../propAccess-
|
|
4
|
-
const require_hash = require('../hash-
|
|
2
|
+
const require_store = require('../store-1TGlSyq4.cjs');
|
|
3
|
+
const require_propAccess = require('../propAccess-BdLsqViO.cjs');
|
|
4
|
+
const require_hash = require('../hash-Dv3XlmHn.cjs');
|
|
5
5
|
const require_extendedJson = require('../extendedJson-Dn2F7Edo.cjs');
|
|
6
|
-
const require_storeMethods = require('../storeMethods-
|
|
6
|
+
const require_storeMethods = require('../storeMethods-C_RzHBQL.cjs');
|
|
7
7
|
const react = require_chunk.__toESM(require("react"));
|
|
8
8
|
const react_jsx_runtime = require_chunk.__toESM(require("react/jsx-runtime"));
|
|
9
9
|
|
package/dist/react/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { autobind, calcDuration, createStore, debounce, queue, throttle } from "../store-
|
|
2
|
-
import { castArrayPath, deepEqual, get, isObject, join, set } from "../propAccess-
|
|
3
|
-
import { simpleHash } from "../hash-
|
|
1
|
+
import { autobind, calcDuration, createStore, debounce, queue, throttle } from "../store-BpMJxIHt.js";
|
|
2
|
+
import { castArrayPath, deepEqual, get, isObject, join, set } from "../propAccess-B260LXN1.js";
|
|
3
|
+
import { simpleHash } from "../hash-DNFM5y_h.js";
|
|
4
4
|
import { fromExtendedJsonString, toExtendedJsonString } from "../extendedJson-BZkQBXEv.js";
|
|
5
|
-
import { LoadingBoundary, ScopeProvider, cacheMethods, scopeMethods, storeMethods, useCache, useLoadingBoundary, useProp, useScope, useStore } from "../storeMethods-
|
|
5
|
+
import { LoadingBoundary, ScopeProvider, cacheMethods, scopeMethods, storeMethods, useCache, useLoadingBoundary, useProp, useScope, useStore } from "../storeMethods-CkvcMFoL.js";
|
|
6
6
|
import React, { Fragment, createContext, createElement, startTransition, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
|
|
7
7
|
import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
|
|
8
8
|
|
package/dist/react/register.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
const require_store = require('../store-
|
|
2
|
-
require('../propAccess-
|
|
3
|
-
require('../hash-
|
|
4
|
-
const require_scope = require('../scope-
|
|
5
|
-
const require_storeMethods = require('../storeMethods-
|
|
1
|
+
const require_store = require('../store-1TGlSyq4.cjs');
|
|
2
|
+
require('../propAccess-BdLsqViO.cjs');
|
|
3
|
+
require('../hash-Dv3XlmHn.cjs');
|
|
4
|
+
const require_scope = require('../scope-BfYAP7hS.cjs');
|
|
5
|
+
const require_storeMethods = require('../storeMethods-C_RzHBQL.cjs');
|
|
6
6
|
|
|
7
7
|
//#region src/react/register.ts
|
|
8
8
|
Object.assign(require_store.Store.prototype, require_storeMethods.storeMethods);
|
package/dist/react/register.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { Store, autobind } from "../store-
|
|
2
|
-
import "../propAccess-
|
|
3
|
-
import "../hash-
|
|
4
|
-
import { Cache, Scope } from "../scope-
|
|
5
|
-
import { cacheMethods, scopeMethods, storeMethods } from "../storeMethods-
|
|
1
|
+
import { Store, autobind } from "../store-BpMJxIHt.js";
|
|
2
|
+
import "../propAccess-B260LXN1.js";
|
|
3
|
+
import "../hash-DNFM5y_h.js";
|
|
4
|
+
import { Cache, Scope } from "../scope-6P87zGw6.js";
|
|
5
|
+
import { cacheMethods, scopeMethods, storeMethods } from "../storeMethods-CkvcMFoL.js";
|
|
6
6
|
|
|
7
7
|
//#region src/react/register.ts
|
|
8
8
|
Object.assign(Store.prototype, storeMethods);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { PromiseWithState, Store, autobind, calcDuration, calculatedValue, createStore, makeSelector } from "./store-
|
|
2
|
-
import { deepEqual } from "./propAccess-
|
|
3
|
-
import { simpleHash } from "./hash-
|
|
1
|
+
import { PromiseWithState, Store, autobind, calcDuration, calculatedValue, createStore, makeSelector } from "./store-BpMJxIHt.js";
|
|
2
|
+
import { deepEqual } from "./propAccess-B260LXN1.js";
|
|
3
|
+
import { simpleHash } from "./hash-DNFM5y_h.js";
|
|
4
4
|
|
|
5
5
|
//#region src/lib/instanceCache.ts
|
|
6
6
|
var InstanceCache = class {
|
|
@@ -319,4 +319,4 @@ function createScope(defaultValue) {
|
|
|
319
319
|
|
|
320
320
|
//#endregion
|
|
321
321
|
export { Cache, InstanceCache, ResourceGroup, Scope, allResources, createCache, createResourceGroup, createScope };
|
|
322
|
-
//# sourceMappingURL=scope-
|
|
322
|
+
//# sourceMappingURL=scope-6P87zGw6.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scope-DV1yaa6v.js","names":["factory: (...args: Args) => T","cacheTime?: number","name?: string","allResources: ResourceGroup","args: Args","options: CacheOptions<T, Args>","derivedFromCache?: {\n cache: Cache<any, any>;\n selectors: (Selector<any, any> | AnyPath)[];\n }","baseInstance: CacheBundle<T, Args> & Cache<T, Args>","createCache: typeof create & { defaultOptions: CacheOptions<any, any> }","defaultValue: T"],"sources":["../src/lib/instanceCache.ts","../src/core/resourceGroup.ts","../src/core/cache.ts","../src/core/scope.ts"],"sourcesContent":["import { simpleHash } from './hash';\n\nexport class InstanceCache<Args extends any[], T extends object> {\n private cache = new Map<string, { t: number; ref?: T; weakRef: WeakRef<T> }>();\n\n private interval = this.cacheTime\n ? setInterval(() => this.cleanup(), Math.max(this.cacheTime / 10, 1))\n : undefined;\n\n constructor(\n public readonly factory: (...args: Args) => T,\n public readonly cacheTime?: number,\n ) {}\n\n cleanup(): void {\n const cutoff = this.now() - (this.cacheTime ?? 0);\n\n for (const [key, entry] of this.cache.entries()) {\n if (entry.ref && entry.t <= cutoff) {\n delete entry.ref;\n }\n\n if (!entry.ref && !entry.weakRef?.deref()) {\n this.cache.delete(key);\n }\n }\n }\n\n get(...args: Args): T {\n return this.getWithKey(args, args);\n }\n\n getWithKey(args: Args, cacheKey: unknown): T {\n const key = simpleHash(cacheKey);\n let entry = this.cache.get(key);\n let value = entry?.ref ?? entry?.weakRef?.deref();\n\n if (!entry || !value) {\n value = this.factory(...args);\n entry = {\n t: this.now(),\n ref: value,\n weakRef: new WeakRef(value),\n };\n\n this.cache.set(key, entry);\n } else {\n entry.t = this.now();\n entry.ref ??= value;\n }\n\n return value;\n }\n\n values(): T[] {\n return [...this.cache.values()]\n .map((entry) => entry.ref ?? entry.weakRef?.deref())\n .filter((value): value is T => !!value);\n }\n\n stop(): void {\n if (this.interval) {\n clearInterval(this.interval);\n }\n }\n\n stats(): { count: number; withRef: number; withWeakRef: number } {\n return {\n count: this.cache.size,\n withRef: [...this.cache.values()].filter((x) => !!x.ref).length,\n withWeakRef: [...this.cache.values()].filter((x) => !!x.weakRef?.deref()).length,\n };\n }\n\n private now() {\n return performance.now();\n }\n}\n","import { autobind } from '@lib/autobind';\n\nexport interface Resource {\n invalidateAll(): void;\n clearAll(): void;\n}\n\nexport class ResourceGroup {\n private refMap = new WeakMap<Resource, WeakRef<Resource>>();\n\n private refSet = new Set<WeakRef<Resource>>();\n\n constructor(public readonly name?: string) {\n autobind(ResourceGroup);\n }\n\n add(resource: Resource): void {\n const ref = new WeakRef(resource);\n this.refMap.set(resource, ref);\n this.refSet.add(ref);\n }\n\n delete(resource: Resource): void {\n const ref = this.refMap.get(resource);\n if (ref) {\n this.refMap.delete(resource);\n this.refSet.delete(ref);\n }\n }\n\n invalidateAll(): void {\n for (const ref of this.refSet) {\n const resource = ref.deref();\n if (resource) {\n resource.invalidateAll();\n } else {\n this.refSet.delete(ref);\n }\n }\n }\n\n clearAll(): void {\n for (const ref of this.refSet) {\n const resource = ref.deref();\n if (resource) {\n resource.clearAll();\n } else {\n this.refSet.delete(ref);\n }\n }\n }\n}\n\nexport const allResources: ResourceGroup = /* @__PURE__ */ new ResourceGroup();\n\nexport function createResourceGroup(name?: string): ResourceGroup {\n return new ResourceGroup(name);\n}\n","import { autobind } from '@lib/autobind';\nimport type { CacheState, ErrorState, ValueState } from '@lib/cacheState';\nimport { calcDuration } from '@lib/calcDuration';\nimport { calculatedValue } from '@lib/calculatedValue';\nimport type { Constrain } from '@lib/constrain';\nimport { deepEqual } from '@lib/equals';\nimport { InstanceCache } from '@lib/instanceCache';\nimport { makeSelector } from '@lib/makeSelector';\nimport { type MaybePromise } from '@lib/maybePromise';\nimport type { AnyPath, Path, Value } from '@lib/path';\nimport { PromiseWithState } from '@lib/promiseWithState';\nimport type { Duration, Selector } from './commonTypes';\nimport { allResources, type ResourceGroup } from './resourceGroup';\nimport { Store, createStore, type Calculate, type StoreOptions } from './store';\n\nexport interface CacheGetOptions {\n /**\n * How to handle the cache when getting the value.\n * - `whenMissing`: Only fetch a new value if there is no cached value.\n * - `whenStale`: Fetch a new value if there is no cached value or if the cached value is stale.\n * - `force`: Always fetch a new value, regardless of the cache state.\n */\n update?: 'whenMissing' | 'whenStale' | 'force';\n\n /**\n * If set to `true`, the cache will be updated in the background.\n * This means that a stale value will be returned immediately, if available, while the new value is being fetched.\n */\n backgroundUpdate?: boolean;\n}\n\nexport interface CacheFunction<T, Args extends any[] = []> {\n (...args: Args): Promise<T> | Calculate<Promise<T>>;\n}\n\nexport interface CacheOptions<T, Args extends any[]> extends StoreOptions<Promise<T>> {\n /**\n * How long to keep the cache entry before it is considered stale.\n * If set to `undefined` or `null`, the cache entry will never be invalidated automatically.\n *\n * @example\n * ```typescript\n * createCache(fetchData, {\n * invalidateAfter: { seconds: 10 },\n * });\n * ```\n */\n invalidateAfter?: Duration | ((state: ValueState<T> | ErrorState) => Duration | null) | null;\n\n /**\n * If set, the cache will be invalidated when the window gets focused.\n * This is useful for caches that are used in a browser environment and might become stale when the user switches tabs.\n */\n invalidateOnWindowFocus?: boolean;\n\n /**\n * If set, the cached value will be cleared when the cache is invalidated.\n * Without this option, the cache will keep the last value as stale until a new value becomes available.\n */\n clearOnInvalidate?: boolean;\n\n /**\n * If set, cache entries will be cleared after approximately the specified duration.\n * This is useful for long lived pages or applications and helps to prevent memory leaks.\n * The exact time when the entry is cleared is not guaranteed, since it will be cleared during garbage collection.\n */\n clearUnusedAfter?: Duration | null;\n\n /**\n * Add the cache to the specified resource group(s).\n * This allows you to invalidate or clear multiple caches that belong to the same group.\n * All caches are always added to the `allResources` group.\n */\n resourceGroup?: ResourceGroup | ResourceGroup[];\n\n /**\n * Function to generate a custom cache key based on the provided arguments.\n * This allows you to control how cache entries are identified and reused.\n * By default, the arguments array is used as the cache key.\n *\n * @example\n * ```typescript\n * // Will use the same instance when provided with `undefined`, `{ num: 0 }`, `{ bool: false }`, etc.\n * createCache((filter?: { num?: number, bool?: boolean }) => fetchData(filter), {\n * getCacheKey: (filter?) => ({\n * num: filter?.num ?? 0,\n * bool: filter?.bool ?? false,\n * }),\n * });\n * ```\n */\n getCacheKey?: (...args: NoInfer<Args>) => unknown;\n}\n\nexport class Cache<T, Args extends any[] = []> extends Store<Promise<T>> {\n readonly state: Store<CacheState<T>> = createStore<CacheState<T>>({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n isConnected: false,\n });\n\n protected stalePromise?: Promise<T>;\n\n protected invalidationTimer?: ReturnType<typeof setTimeout>;\n\n constructor(\n getter: Calculate<Promise<T>>,\n public readonly args: Args,\n public readonly options: CacheOptions<T, Args> = {},\n public readonly derivedFromCache?: {\n cache: Cache<any, any>;\n selectors: (Selector<any, any> | AnyPath)[];\n },\n ) {\n super(getter, options, undefined);\n autobind(Cache);\n\n this.watchPromise();\n this.watchFocus();\n }\n\n get({ update = 'whenStale', backgroundUpdate = false }: CacheGetOptions = {}): Promise<T> {\n this.calculatedValue?.check();\n const promise = this.calculatedValue?.value;\n const stalePromise = this.stalePromise;\n\n if (\n (update === 'whenMissing' && !promise && !stalePromise) ||\n (update === 'whenStale' && !promise) ||\n update === 'force'\n ) {\n this.calculatedValue = calculatedValue(this, this.notify);\n this.notify();\n\n if ((!promise && !stalePromise) || !backgroundUpdate) {\n return this.calculatedValue.value;\n }\n }\n\n if (!promise || (stalePromise && backgroundUpdate)) {\n return stalePromise!;\n }\n\n return promise;\n }\n\n updateValue(value: MaybePromise<T> | ((value: T | undefined) => T)): void {\n if (value instanceof Function) {\n value = value(this.state.get().value);\n }\n this.set(PromiseWithState.resolve(value));\n }\n\n updateError(error: unknown): void {\n this.set(PromiseWithState.reject(error));\n }\n\n invalidate(recursive?: boolean): void {\n const { clearOnInvalidate } = this.options;\n\n if (clearOnInvalidate) {\n return this.clear(recursive);\n }\n\n const { status, isStale, isUpdating } = this.state.get();\n if (status !== 'pending' && !isStale && !isUpdating) {\n this.stalePromise = this.calculatedValue?.value;\n }\n\n this.state.set((state) => ({\n ...state,\n isStale: true,\n isUpdating: false,\n }));\n\n super.invalidate(recursive);\n }\n\n clear(recursive?: boolean): void {\n this.state.set({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n isConnected: false,\n });\n delete this.stalePromise;\n\n super.invalidate(recursive);\n }\n\n mapValue<S>(selector: Selector<T, S>): Cache<S, Args>;\n\n mapValue<const P extends AnyPath>(\n selector: P extends Path<T> ? P : Path<T>,\n ): Cache<Value<T, P>, Args>;\n\n mapValue(selector: Selector<any, any> | AnyPath) {\n return mapValue(this, selector);\n }\n\n protected watchPromise(): void {\n this.subscribe(\n async (promise) => {\n if (promise instanceof PromiseWithState && promise.state.status !== 'pending') {\n promise.catch(() => undefined);\n\n this.state.set((state) => ({\n ...promise.state,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n\n delete this.stalePromise;\n this.setTimers();\n return;\n }\n\n this.state.set((state) => ({\n ...state,\n isUpdating: true,\n }));\n\n this.setTimers();\n\n try {\n const value = await promise;\n\n if (promise !== this.calculatedValue?.value) {\n return;\n }\n\n this.state.set((state) => ({\n status: 'value',\n value,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n delete this.stalePromise;\n this.setTimers();\n } catch (error) {\n if (promise !== this.calculatedValue?.value) {\n return;\n }\n\n this.state.set((state) => ({\n status: 'error',\n error,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n delete this.stalePromise;\n this.setTimers();\n }\n },\n { passive: true },\n );\n }\n\n protected setTimers(): void {\n if (this.invalidationTimer) {\n clearTimeout(this.invalidationTimer);\n }\n this.invalidationTimer = undefined;\n\n const state = this.state.get();\n let { invalidateAfter } = this.options;\n const ref = new WeakRef(this);\n\n if (state.status === 'pending') {\n return;\n }\n\n if (invalidateAfter instanceof Function) {\n invalidateAfter = invalidateAfter(state);\n }\n\n if (invalidateAfter !== null && invalidateAfter !== undefined) {\n this.invalidationTimer = setTimeout(\n () => ref?.deref()?.invalidate(),\n calcDuration(invalidateAfter),\n );\n }\n }\n\n protected watchFocus(): void {\n const { invalidateOnWindowFocus } = this.options;\n\n if (\n !invalidateOnWindowFocus ||\n typeof document === 'undefined' ||\n typeof document.addEventListener === 'undefined'\n ) {\n return;\n }\n\n const ref = new WeakRef(this);\n\n const onFocus = () => {\n const that = ref?.deref();\n if (!that) {\n document.removeEventListener('visibilitychange', onFocus);\n return;\n }\n\n if (!document.hidden && !that.state.get().isConnected) {\n that.invalidate();\n }\n };\n\n document.addEventListener('visibilitychange', onFocus);\n }\n}\n\nfunction mapValue<T, S, Args extends any[]>(\n cache: Cache<T, Args>,\n _selector: Selector<T, S> | AnyPath,\n): Cache<S, Args> {\n const selector = makeSelector(_selector);\n const derivedFromCache = {\n cache: cache.derivedFromCache ? cache.derivedFromCache.cache : cache,\n selectors: cache.derivedFromCache\n ? [...cache.derivedFromCache.selectors, _selector]\n : [_selector],\n };\n\n return new Cache<S, Args>(\n async ({ use }) => {\n const value = await use(cache);\n return selector(value);\n },\n cache.args,\n {\n equals: cache.options.equals,\n },\n derivedFromCache,\n );\n}\n\nexport type CreateCacheResult<T, Args extends any[]> = [] extends Args\n ? CacheBundle<T, Args> & Cache<T, Args>\n : CacheBundle<T, Args>;\n\nexport interface InvalidationOptions<T, Args extends any[]> {\n filter?: (cache: Cache<T, Args>) => boolean;\n}\n\nexport type CacheBundle<T, Args extends any[]> = {\n (...args: Args): Cache<T, Args>;\n mapCache<S>(selector: Selector<T, S>): CreateCacheResult<S, Args>;\n mapValue<const P>(selector: Constrain<P, Path<T>>): CreateCacheResult<Value<T, P>, Args>;\n invalidateAll: (options?: InvalidationOptions<T, Args>) => void;\n clearAll: (options?: InvalidationOptions<T, Args>) => void;\n getInstances: () => Cache<T, Args>[];\n};\n\nfunction create<T, Args extends any[] = []>(\n cacheFunction: CacheFunction<T, Args>,\n options?: CacheOptions<T, Args>,\n): CreateCacheResult<T, Args> {\n return internalCreate<T, Args>(cacheFunction, options);\n}\n\nfunction internalCreate<T, Args extends any[] = []>(\n source:\n | CacheFunction<T, Args>\n | [cache: CacheBundle<any, Args>, selector: Selector<any, T> | AnyPath],\n options?: CacheOptions<T, Args>,\n): CreateCacheResult<T, Args> {\n options = { ...createCache.defaultOptions, ...options };\n const { clearUnusedAfter, resourceGroup } = options ?? {};\n\n let baseInstance: CacheBundle<T, Args> & Cache<T, Args>;\n\n const instanceCache = new InstanceCache<Args, Cache<T, Args>>(\n (...args: Args): Cache<T, Args> => {\n if (Array.isArray(source)) {\n const [cache, selector] = source;\n return mapValue(cache(...args), selector);\n }\n\n return new Cache(\n (helpers) => {\n const result = source.apply(helpers, args);\n\n if (result instanceof Function) {\n return result(helpers);\n }\n\n return result;\n },\n args,\n options,\n undefined,\n );\n },\n clearUnusedAfter ? calcDuration(clearUnusedAfter) : undefined,\n );\n\n function get(...args: Args) {\n const sliceAfter = args.lastIndexOf(undefined);\n if (sliceAfter !== -1) {\n args = args.slice(0, sliceAfter) as Args;\n }\n\n const cacheKey = options?.getCacheKey ? options.getCacheKey(...args) : args;\n return instanceCache.getWithKey(args, cacheKey);\n }\n\n const mapCache = (selector: any) => {\n return internalCreate([baseInstance, selector]);\n };\n\n const invalidateAll = ({ filter = () => true }: InvalidationOptions<T, Args> = {}) => {\n for (const instance of instanceCache.values()) {\n if (filter(instance)) {\n instance.invalidate();\n }\n }\n };\n\n const clearAll = ({ filter = () => true }: InvalidationOptions<T, Args> = {}) => {\n for (const instance of instanceCache.values()) {\n if (filter(instance)) {\n instance.clear();\n }\n }\n };\n\n const getInstances = () => {\n return instanceCache.values();\n };\n\n baseInstance = new Proxy(\n Object.assign(() => undefined, {\n mapCache,\n invalidateAll,\n clearAll,\n getInstances,\n }),\n {\n apply(_target, _thisArg, argArray) {\n return get(...(argArray as unknown as Args));\n },\n get(target, p, receiver) {\n if (Reflect.has(target, p)) {\n return Reflect.get(target, p, receiver);\n }\n\n const baseCache = get(...([] as unknown as Args));\n return Reflect.get(baseCache, p, baseCache);\n },\n },\n ) as unknown as CacheBundle<T, Args> & Cache<T, Args>;\n\n const groups = Array.isArray(resourceGroup)\n ? resourceGroup\n : resourceGroup\n ? [resourceGroup]\n : [];\n\n for (const group of groups.concat(allResources)) {\n group.add(baseInstance);\n }\n\n return baseInstance;\n}\n\nexport const createCache: typeof create & { defaultOptions: CacheOptions<any, any> } =\n /* @__PURE__ */ Object.assign(create, {\n defaultOptions: {\n invalidateOnWindowFocus: true,\n clearUnusedAfter: { days: 1 },\n retain: { milliseconds: 1 },\n equals: deepEqual,\n } as CacheOptions<any, any>,\n });\n","import { autobind } from '@lib/autobind';\n\nexport class Scope<T> {\n constructor(public readonly defaultValue: T) {\n autobind(Scope);\n }\n}\n\nexport function createScope<T>(defaultValue: T): Scope<T> {\n return new Scope(defaultValue);\n}\n"],"mappings":";;;;;AAEA,IAAa,gBAAb,MAAiE;CAO/D,YACE,AAAgBA,SAChB,AAAgBC,WACh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AAM,YAAY,IAAI,GAAI;AAC1B,UAAO,QAAQ,IAAI,WAAW,GAAG;;;CAKvC,MAAM,SAAS,MAAM,QAAQ,iBACzB,gBACA,gBACE,CAAC,iBACD;AAEN,MAAK,MAAM,SAAS,OAAO,OAAO,cAChC,OAAM,IAAI;AAGZ,QAAO;;AAGT,MAAaC,cACK,uBAAO,OAAO,QAAQ,EACpC,gBAAgB;CACd,yBAAyB;CACzB,kBAAkB,EAAE,MAAM;CAC1B,QAAQ,EAAE,cAAc;CACxB,QAAQ;;;;;AC3dd,IAAa,QAAb,MAAa,MAAS;CACpB,YAAY,AAAgBC,cAAiB;EAAjB;AAC1B,WAAS;;;AAIb,SAAgB,YAAe,cAA2B;AACxD,QAAO,IAAI,MAAM"}
|
|
1
|
+
{"version":3,"file":"scope-6P87zGw6.js","names":["factory: (...args: Args) => T","cacheTime?: number","name?: string","allResources: ResourceGroup","args: Args","options: CacheOptions<T, Args>","derivedFromCache?: {\n cache: Cache<any, any>;\n selectors: (Selector<any, any> | AnyPath)[];\n }","baseInstance: CacheBundle<T, Args> & Cache<T, Args>","createCache: typeof create & { defaultOptions: CacheOptions<any, any> }","defaultValue: T"],"sources":["../src/lib/instanceCache.ts","../src/core/resourceGroup.ts","../src/core/cache.ts","../src/core/scope.ts"],"sourcesContent":["import { simpleHash } from './hash';\n\nexport class InstanceCache<Args extends any[], T extends object> {\n private cache = new Map<string, { t: number; ref?: T; weakRef: WeakRef<T> }>();\n\n private interval = this.cacheTime\n ? setInterval(() => this.cleanup(), Math.max(this.cacheTime / 10, 1))\n : undefined;\n\n constructor(\n public readonly factory: (...args: Args) => T,\n public readonly cacheTime?: number,\n ) {}\n\n cleanup(): void {\n const cutoff = this.now() - (this.cacheTime ?? 0);\n\n for (const [key, entry] of this.cache.entries()) {\n if (entry.ref && entry.t <= cutoff) {\n delete entry.ref;\n }\n\n if (!entry.ref && !entry.weakRef?.deref()) {\n this.cache.delete(key);\n }\n }\n }\n\n get(...args: Args): T {\n return this.getWithKey(args, args);\n }\n\n getWithKey(args: Args, cacheKey: unknown): T {\n const key = simpleHash(cacheKey);\n let entry = this.cache.get(key);\n let value = entry?.ref ?? entry?.weakRef?.deref();\n\n if (!entry || !value) {\n value = this.factory(...args);\n entry = {\n t: this.now(),\n ref: value,\n weakRef: new WeakRef(value),\n };\n\n this.cache.set(key, entry);\n } else {\n entry.t = this.now();\n entry.ref ??= value;\n }\n\n return value;\n }\n\n values(): T[] {\n return [...this.cache.values()]\n .map((entry) => entry.ref ?? entry.weakRef?.deref())\n .filter((value): value is T => !!value);\n }\n\n stop(): void {\n if (this.interval) {\n clearInterval(this.interval);\n }\n }\n\n stats(): { count: number; withRef: number; withWeakRef: number } {\n return {\n count: this.cache.size,\n withRef: [...this.cache.values()].filter((x) => !!x.ref).length,\n withWeakRef: [...this.cache.values()].filter((x) => !!x.weakRef?.deref()).length,\n };\n }\n\n private now() {\n return performance.now();\n }\n}\n","import { autobind } from '@lib/autobind';\n\nexport interface Resource {\n invalidateAll(): void;\n clearAll(): void;\n}\n\nexport class ResourceGroup {\n private refMap = new WeakMap<Resource, WeakRef<Resource>>();\n\n private refSet = new Set<WeakRef<Resource>>();\n\n constructor(public readonly name?: string) {\n autobind(ResourceGroup);\n }\n\n add(resource: Resource): void {\n const ref = new WeakRef(resource);\n this.refMap.set(resource, ref);\n this.refSet.add(ref);\n }\n\n delete(resource: Resource): void {\n const ref = this.refMap.get(resource);\n if (ref) {\n this.refMap.delete(resource);\n this.refSet.delete(ref);\n }\n }\n\n invalidateAll(): void {\n for (const ref of this.refSet) {\n const resource = ref.deref();\n if (resource) {\n resource.invalidateAll();\n } else {\n this.refSet.delete(ref);\n }\n }\n }\n\n clearAll(): void {\n for (const ref of this.refSet) {\n const resource = ref.deref();\n if (resource) {\n resource.clearAll();\n } else {\n this.refSet.delete(ref);\n }\n }\n }\n}\n\nexport const allResources: ResourceGroup = /* @__PURE__ */ new ResourceGroup();\n\nexport function createResourceGroup(name?: string): ResourceGroup {\n return new ResourceGroup(name);\n}\n","import { autobind } from '@lib/autobind';\nimport type { CacheState, ErrorState, ValueState } from '@lib/cacheState';\nimport { calcDuration } from '@lib/calcDuration';\nimport { calculatedValue } from '@lib/calculatedValue';\nimport type { Constrain } from '@lib/constrain';\nimport { deepEqual } from '@lib/equals';\nimport { InstanceCache } from '@lib/instanceCache';\nimport { makeSelector } from '@lib/makeSelector';\nimport { type MaybePromise } from '@lib/maybePromise';\nimport type { AnyPath, Path, Value } from '@lib/path';\nimport { PromiseWithState } from '@lib/promiseWithState';\nimport type { Duration, Selector } from './commonTypes';\nimport { allResources, type ResourceGroup } from './resourceGroup';\nimport { Store, createStore, type Calculate, type StoreOptions } from './store';\n\nexport interface CacheGetOptions {\n /**\n * How to handle the cache when getting the value.\n * - `whenMissing`: Only fetch a new value if there is no cached value.\n * - `whenStale`: Fetch a new value if there is no cached value or if the cached value is stale.\n * - `force`: Always fetch a new value, regardless of the cache state.\n */\n update?: 'whenMissing' | 'whenStale' | 'force';\n\n /**\n * If set to `true`, the cache will be updated in the background.\n * This means that a stale value will be returned immediately, if available, while the new value is being fetched.\n */\n backgroundUpdate?: boolean;\n}\n\nexport interface CacheFunction<T, Args extends any[] = []> {\n (...args: Args): Promise<T> | Calculate<Promise<T>>;\n}\n\nexport interface CacheOptions<T, Args extends any[]> extends StoreOptions<Promise<T>> {\n /**\n * How long to keep the cache entry before it is considered stale.\n * If set to `undefined` or `null`, the cache entry will never be invalidated automatically.\n *\n * @example\n * ```typescript\n * createCache(fetchData, {\n * invalidateAfter: { seconds: 10 },\n * });\n * ```\n */\n invalidateAfter?: Duration | ((state: ValueState<T> | ErrorState) => Duration | null) | null;\n\n /**\n * If set, the cache will be invalidated when the window gets focused.\n * This is useful for caches that are used in a browser environment and might become stale when the user switches tabs.\n */\n invalidateOnWindowFocus?: boolean;\n\n /**\n * If set, the cached value will be cleared when the cache is invalidated.\n * Without this option, the cache will keep the last value as stale until a new value becomes available.\n */\n clearOnInvalidate?: boolean;\n\n /**\n * If set, cache entries will be cleared after approximately the specified duration.\n * This is useful for long lived pages or applications and helps to prevent memory leaks.\n * The exact time when the entry is cleared is not guaranteed, since it will be cleared during garbage collection.\n */\n clearUnusedAfter?: Duration | null;\n\n /**\n * Add the cache to the specified resource group(s).\n * This allows you to invalidate or clear multiple caches that belong to the same group.\n * All caches are always added to the `allResources` group.\n */\n resourceGroup?: ResourceGroup | ResourceGroup[];\n\n /**\n * Function to generate a custom cache key based on the provided arguments.\n * This allows you to control how cache entries are identified and reused.\n * By default, the arguments array is used as the cache key.\n *\n * @example\n * ```typescript\n * // Will use the same instance when provided with `undefined`, `{ num: 0 }`, `{ bool: false }`, etc.\n * createCache((filter?: { num?: number, bool?: boolean }) => fetchData(filter), {\n * getCacheKey: (filter?) => ({\n * num: filter?.num ?? 0,\n * bool: filter?.bool ?? false,\n * }),\n * });\n * ```\n */\n getCacheKey?: (...args: NoInfer<Args>) => unknown;\n}\n\nexport class Cache<T, Args extends any[] = []> extends Store<Promise<T>> {\n readonly state: Store<CacheState<T>> = createStore<CacheState<T>>({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n isConnected: false,\n });\n\n protected stalePromise?: Promise<T>;\n\n protected invalidationTimer?: ReturnType<typeof setTimeout>;\n\n constructor(\n getter: Calculate<Promise<T>>,\n public readonly args: Args,\n public readonly options: CacheOptions<T, Args> = {},\n public readonly derivedFromCache?: {\n cache: Cache<any, any>;\n selectors: (Selector<any, any> | AnyPath)[];\n },\n ) {\n super(getter, options, undefined);\n autobind(Cache);\n\n this.watchPromise();\n this.watchFocus();\n }\n\n get({ update = 'whenStale', backgroundUpdate = false }: CacheGetOptions = {}): Promise<T> {\n this.calculatedValue?.check();\n const promise = this.calculatedValue?.value;\n const stalePromise = this.stalePromise;\n\n if (\n (update === 'whenMissing' && !promise && !stalePromise) ||\n (update === 'whenStale' && !promise) ||\n update === 'force'\n ) {\n this.calculatedValue = calculatedValue(this, this.notify);\n this.notify();\n\n if ((!promise && !stalePromise) || !backgroundUpdate) {\n return this.calculatedValue.value;\n }\n }\n\n if (!promise || (stalePromise && backgroundUpdate)) {\n return stalePromise!;\n }\n\n return promise;\n }\n\n updateValue(value: MaybePromise<T> | ((value: T | undefined) => T)): void {\n if (value instanceof Function) {\n value = value(this.state.get().value);\n }\n this.set(PromiseWithState.resolve(value));\n }\n\n updateError(error: unknown): void {\n this.set(PromiseWithState.reject(error));\n }\n\n invalidate(recursive?: boolean): void {\n const { clearOnInvalidate } = this.options;\n\n if (clearOnInvalidate) {\n return this.clear(recursive);\n }\n\n const { status, isStale, isUpdating } = this.state.get();\n if (status !== 'pending' && !isStale && !isUpdating) {\n this.stalePromise = this.calculatedValue?.value;\n }\n\n this.state.set((state) => ({\n ...state,\n isStale: true,\n isUpdating: false,\n }));\n\n super.invalidate(recursive);\n }\n\n clear(recursive?: boolean): void {\n this.state.set({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n isConnected: false,\n });\n delete this.stalePromise;\n\n super.invalidate(recursive);\n }\n\n mapValue<S>(selector: Selector<T, S>): Cache<S, Args>;\n\n mapValue<const P extends AnyPath>(\n selector: P extends Path<T> ? P : Path<T>,\n ): Cache<Value<T, P>, Args>;\n\n mapValue(selector: Selector<any, any> | AnyPath) {\n return mapValue(this, selector);\n }\n\n protected watchPromise(): void {\n this.subscribe(\n async (promise) => {\n if (promise instanceof PromiseWithState && promise.state.status !== 'pending') {\n promise.catch(() => undefined);\n\n this.state.set((state) => ({\n ...promise.state,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n\n delete this.stalePromise;\n this.setTimers();\n return;\n }\n\n this.state.set((state) => ({\n ...state,\n isUpdating: true,\n }));\n\n this.setTimers();\n\n try {\n const value = await promise;\n\n if (promise !== this.calculatedValue?.value) {\n return;\n }\n\n this.state.set((state) => ({\n status: 'value',\n value,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n delete this.stalePromise;\n this.setTimers();\n } catch (error) {\n if (promise !== this.calculatedValue?.value) {\n return;\n }\n\n this.state.set((state) => ({\n status: 'error',\n error,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n delete this.stalePromise;\n this.setTimers();\n }\n },\n { passive: true },\n );\n }\n\n protected setTimers(): void {\n if (this.invalidationTimer) {\n clearTimeout(this.invalidationTimer);\n }\n this.invalidationTimer = undefined;\n\n const state = this.state.get();\n let { invalidateAfter } = this.options;\n const ref = new WeakRef(this);\n\n if (state.status === 'pending') {\n return;\n }\n\n if (invalidateAfter instanceof Function) {\n invalidateAfter = invalidateAfter(state);\n }\n\n if (invalidateAfter !== null && invalidateAfter !== undefined) {\n this.invalidationTimer = setTimeout(\n () => ref?.deref()?.invalidate(),\n calcDuration(invalidateAfter),\n );\n }\n }\n\n protected watchFocus(): void {\n const { invalidateOnWindowFocus } = this.options;\n\n if (\n !invalidateOnWindowFocus ||\n typeof document === 'undefined' ||\n typeof document.addEventListener === 'undefined'\n ) {\n return;\n }\n\n const ref = new WeakRef(this);\n\n const onFocus = () => {\n const that = ref?.deref();\n if (!that) {\n document.removeEventListener('visibilitychange', onFocus);\n return;\n }\n\n if (!document.hidden && !that.state.get().isConnected) {\n that.invalidate();\n }\n };\n\n document.addEventListener('visibilitychange', onFocus);\n }\n}\n\nfunction mapValue<T, S, Args extends any[]>(\n cache: Cache<T, Args>,\n _selector: Selector<T, S> | AnyPath,\n): Cache<S, Args> {\n const selector = makeSelector(_selector);\n const derivedFromCache = {\n cache: cache.derivedFromCache ? cache.derivedFromCache.cache : cache,\n selectors: cache.derivedFromCache\n ? [...cache.derivedFromCache.selectors, _selector]\n : [_selector],\n };\n\n return new Cache<S, Args>(\n async ({ use }) => {\n const value = await use(cache);\n return selector(value);\n },\n cache.args,\n {\n equals: cache.options.equals,\n },\n derivedFromCache,\n );\n}\n\nexport type CreateCacheResult<T, Args extends any[]> = [] extends Args\n ? CacheBundle<T, Args> & Cache<T, Args>\n : CacheBundle<T, Args>;\n\nexport interface InvalidationOptions<T, Args extends any[]> {\n filter?: (cache: Cache<T, Args>) => boolean;\n}\n\nexport type CacheBundle<T, Args extends any[]> = {\n (...args: Args): Cache<T, Args>;\n mapCache<S>(selector: Selector<T, S>): CreateCacheResult<S, Args>;\n mapValue<const P>(selector: Constrain<P, Path<T>>): CreateCacheResult<Value<T, P>, Args>;\n invalidateAll: (options?: InvalidationOptions<T, Args>) => void;\n clearAll: (options?: InvalidationOptions<T, Args>) => void;\n getInstances: () => Cache<T, Args>[];\n};\n\nfunction create<T, Args extends any[] = []>(\n cacheFunction: CacheFunction<T, Args>,\n options?: CacheOptions<T, Args>,\n): CreateCacheResult<T, Args> {\n return internalCreate<T, Args>(cacheFunction, options);\n}\n\nfunction internalCreate<T, Args extends any[] = []>(\n source:\n | CacheFunction<T, Args>\n | [cache: CacheBundle<any, Args>, selector: Selector<any, T> | AnyPath],\n options?: CacheOptions<T, Args>,\n): CreateCacheResult<T, Args> {\n options = { ...createCache.defaultOptions, ...options };\n const { clearUnusedAfter, resourceGroup } = options ?? {};\n\n let baseInstance: CacheBundle<T, Args> & Cache<T, Args>;\n\n const instanceCache = new InstanceCache<Args, Cache<T, Args>>(\n (...args: Args): Cache<T, Args> => {\n if (Array.isArray(source)) {\n const [cache, selector] = source;\n return mapValue(cache(...args), selector);\n }\n\n return new Cache(\n (helpers) => {\n const result = source.apply(helpers, args);\n\n if (result instanceof Function) {\n return result(helpers);\n }\n\n return result;\n },\n args,\n options,\n undefined,\n );\n },\n clearUnusedAfter ? calcDuration(clearUnusedAfter) : undefined,\n );\n\n function get(...args: Args) {\n const sliceAfter = args.lastIndexOf(undefined);\n if (sliceAfter !== -1) {\n args = args.slice(0, sliceAfter) as Args;\n }\n\n const cacheKey = options?.getCacheKey ? options.getCacheKey(...args) : args;\n return instanceCache.getWithKey(args, cacheKey);\n }\n\n const mapCache = (selector: any) => {\n return internalCreate([baseInstance, selector]);\n };\n\n const invalidateAll = ({ filter = () => true }: InvalidationOptions<T, Args> = {}) => {\n for (const instance of instanceCache.values()) {\n if (filter(instance)) {\n instance.invalidate();\n }\n }\n };\n\n const clearAll = ({ filter = () => true }: InvalidationOptions<T, Args> = {}) => {\n for (const instance of instanceCache.values()) {\n if (filter(instance)) {\n instance.clear();\n }\n }\n };\n\n const getInstances = () => {\n return instanceCache.values();\n };\n\n baseInstance = new Proxy(\n Object.assign(() => undefined, {\n mapCache,\n invalidateAll,\n clearAll,\n getInstances,\n }),\n {\n apply(_target, _thisArg, argArray) {\n return get(...(argArray as unknown as Args));\n },\n get(target, p, receiver) {\n if (Reflect.has(target, p)) {\n return Reflect.get(target, p, receiver);\n }\n\n const baseCache = get(...([] as unknown as Args));\n return Reflect.get(baseCache, p, baseCache);\n },\n },\n ) as unknown as CacheBundle<T, Args> & Cache<T, Args>;\n\n const groups = Array.isArray(resourceGroup)\n ? resourceGroup\n : resourceGroup\n ? [resourceGroup]\n : [];\n\n for (const group of groups.concat(allResources)) {\n group.add(baseInstance);\n }\n\n return baseInstance;\n}\n\nexport const createCache: typeof create & { defaultOptions: CacheOptions<any, any> } =\n /* @__PURE__ */ Object.assign(create, {\n defaultOptions: {\n invalidateOnWindowFocus: true,\n clearUnusedAfter: { days: 1 },\n retain: { milliseconds: 1 },\n equals: deepEqual,\n } as CacheOptions<any, any>,\n });\n","import { autobind } from '@lib/autobind';\n\nexport class Scope<T> {\n constructor(public readonly defaultValue: T) {\n autobind(Scope);\n }\n}\n\nexport function createScope<T>(defaultValue: T): Scope<T> {\n return new Scope(defaultValue);\n}\n"],"mappings":";;;;;AAEA,IAAa,gBAAb,MAAiE;CAO/D,YACE,AAAgBA,SAChB,AAAgBC,WAChB;EAFgB;EACA;+BARF,IAAI;kBAED,KAAK,YACpB,kBAAkB,KAAK,WAAW,KAAK,IAAI,KAAK,YAAY,IAAI,MAChE;;CAOJ,UAAgB;EACd,MAAM,SAAS,KAAK,SAAS,KAAK,aAAa;AAE/C,OAAK,MAAM,CAAC,KAAK,UAAU,KAAK,MAAM,WAAW;AAC/C,OAAI,MAAM,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,EACpC,gBAAgB;CACd,yBAAyB;CACzB,kBAAkB,EAAE,MAAM;CAC1B,QAAQ,EAAE,cAAc;CACxB,QAAQ;;;;;AC3dd,IAAa,QAAb,MAAa,MAAS;CACpB,YAAY,AAAgBC,cAAiB;EAAjB;AAC1B,WAAS;;;AAIb,SAAgB,YAAe,cAA2B;AACxD,QAAO,IAAI,MAAM"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
const require_store = require('./store-
|
|
2
|
-
const require_propAccess = require('./propAccess-
|
|
3
|
-
const require_hash = require('./hash-
|
|
1
|
+
const require_store = require('./store-1TGlSyq4.cjs');
|
|
2
|
+
const require_propAccess = require('./propAccess-BdLsqViO.cjs');
|
|
3
|
+
const require_hash = require('./hash-Dv3XlmHn.cjs');
|
|
4
4
|
|
|
5
5
|
//#region src/lib/instanceCache.ts
|
|
6
6
|
var InstanceCache = class {
|
|
@@ -366,4 +366,4 @@ Object.defineProperty(exports, 'createScope', {
|
|
|
366
366
|
return createScope;
|
|
367
367
|
}
|
|
368
368
|
});
|
|
369
|
-
//# sourceMappingURL=scope-
|
|
369
|
+
//# sourceMappingURL=scope-BfYAP7hS.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scope-iQ_P6a3x.cjs","names":["factory: (...args: Args) => T","cacheTime?: number","simpleHash","name?: string","allResources: ResourceGroup","Store","args: Args","options: CacheOptions<T, Args>","derivedFromCache?: {\n cache: Cache<any, any>;\n selectors: (Selector<any, any> | AnyPath)[];\n }","createStore","calculatedValue","PromiseWithState","calcDuration","makeSelector","baseInstance: CacheBundle<T, Args> & Cache<T, Args>","createCache: typeof create & { defaultOptions: CacheOptions<any, any> }","deepEqual","defaultValue: T"],"sources":["../src/lib/instanceCache.ts","../src/core/resourceGroup.ts","../src/core/cache.ts","../src/core/scope.ts"],"sourcesContent":["import { simpleHash } from './hash';\n\nexport class InstanceCache<Args extends any[], T extends object> {\n private cache = new Map<string, { t: number; ref?: T; weakRef: WeakRef<T> }>();\n\n private interval = this.cacheTime\n ? setInterval(() => this.cleanup(), Math.max(this.cacheTime / 10, 1))\n : undefined;\n\n constructor(\n public readonly factory: (...args: Args) => T,\n public readonly cacheTime?: number,\n ) {}\n\n cleanup(): void {\n const cutoff = this.now() - (this.cacheTime ?? 0);\n\n for (const [key, entry] of this.cache.entries()) {\n if (entry.ref && entry.t <= cutoff) {\n delete entry.ref;\n }\n\n if (!entry.ref && !entry.weakRef?.deref()) {\n this.cache.delete(key);\n }\n }\n }\n\n get(...args: Args): T {\n return this.getWithKey(args, args);\n }\n\n getWithKey(args: Args, cacheKey: unknown): T {\n const key = simpleHash(cacheKey);\n let entry = this.cache.get(key);\n let value = entry?.ref ?? entry?.weakRef?.deref();\n\n if (!entry || !value) {\n value = this.factory(...args);\n entry = {\n t: this.now(),\n ref: value,\n weakRef: new WeakRef(value),\n };\n\n this.cache.set(key, entry);\n } else {\n entry.t = this.now();\n entry.ref ??= value;\n }\n\n return value;\n }\n\n values(): T[] {\n return [...this.cache.values()]\n .map((entry) => entry.ref ?? entry.weakRef?.deref())\n .filter((value): value is T => !!value);\n }\n\n stop(): void {\n if (this.interval) {\n clearInterval(this.interval);\n }\n }\n\n stats(): { count: number; withRef: number; withWeakRef: number } {\n return {\n count: this.cache.size,\n withRef: [...this.cache.values()].filter((x) => !!x.ref).length,\n withWeakRef: [...this.cache.values()].filter((x) => !!x.weakRef?.deref()).length,\n };\n }\n\n private now() {\n return performance.now();\n }\n}\n","import { autobind } from '@lib/autobind';\n\nexport interface Resource {\n invalidateAll(): void;\n clearAll(): void;\n}\n\nexport class ResourceGroup {\n private refMap = new WeakMap<Resource, WeakRef<Resource>>();\n\n private refSet = new Set<WeakRef<Resource>>();\n\n constructor(public readonly name?: string) {\n autobind(ResourceGroup);\n }\n\n add(resource: Resource): void {\n const ref = new WeakRef(resource);\n this.refMap.set(resource, ref);\n this.refSet.add(ref);\n }\n\n delete(resource: Resource): void {\n const ref = this.refMap.get(resource);\n if (ref) {\n this.refMap.delete(resource);\n this.refSet.delete(ref);\n }\n }\n\n invalidateAll(): void {\n for (const ref of this.refSet) {\n const resource = ref.deref();\n if (resource) {\n resource.invalidateAll();\n } else {\n this.refSet.delete(ref);\n }\n }\n }\n\n clearAll(): void {\n for (const ref of this.refSet) {\n const resource = ref.deref();\n if (resource) {\n resource.clearAll();\n } else {\n this.refSet.delete(ref);\n }\n }\n }\n}\n\nexport const allResources: ResourceGroup = /* @__PURE__ */ new ResourceGroup();\n\nexport function createResourceGroup(name?: string): ResourceGroup {\n return new ResourceGroup(name);\n}\n","import { autobind } from '@lib/autobind';\nimport type { CacheState, ErrorState, ValueState } from '@lib/cacheState';\nimport { calcDuration } from '@lib/calcDuration';\nimport { calculatedValue } from '@lib/calculatedValue';\nimport type { Constrain } from '@lib/constrain';\nimport { deepEqual } from '@lib/equals';\nimport { InstanceCache } from '@lib/instanceCache';\nimport { makeSelector } from '@lib/makeSelector';\nimport { type MaybePromise } from '@lib/maybePromise';\nimport type { AnyPath, Path, Value } from '@lib/path';\nimport { PromiseWithState } from '@lib/promiseWithState';\nimport type { Duration, Selector } from './commonTypes';\nimport { allResources, type ResourceGroup } from './resourceGroup';\nimport { Store, createStore, type Calculate, type StoreOptions } from './store';\n\nexport interface CacheGetOptions {\n /**\n * How to handle the cache when getting the value.\n * - `whenMissing`: Only fetch a new value if there is no cached value.\n * - `whenStale`: Fetch a new value if there is no cached value or if the cached value is stale.\n * - `force`: Always fetch a new value, regardless of the cache state.\n */\n update?: 'whenMissing' | 'whenStale' | 'force';\n\n /**\n * If set to `true`, the cache will be updated in the background.\n * This means that a stale value will be returned immediately, if available, while the new value is being fetched.\n */\n backgroundUpdate?: boolean;\n}\n\nexport interface CacheFunction<T, Args extends any[] = []> {\n (...args: Args): Promise<T> | Calculate<Promise<T>>;\n}\n\nexport interface CacheOptions<T, Args extends any[]> extends StoreOptions<Promise<T>> {\n /**\n * How long to keep the cache entry before it is considered stale.\n * If set to `undefined` or `null`, the cache entry will never be invalidated automatically.\n *\n * @example\n * ```typescript\n * createCache(fetchData, {\n * invalidateAfter: { seconds: 10 },\n * });\n * ```\n */\n invalidateAfter?: Duration | ((state: ValueState<T> | ErrorState) => Duration | null) | null;\n\n /**\n * If set, the cache will be invalidated when the window gets focused.\n * This is useful for caches that are used in a browser environment and might become stale when the user switches tabs.\n */\n invalidateOnWindowFocus?: boolean;\n\n /**\n * If set, the cached value will be cleared when the cache is invalidated.\n * Without this option, the cache will keep the last value as stale until a new value becomes available.\n */\n clearOnInvalidate?: boolean;\n\n /**\n * If set, cache entries will be cleared after approximately the specified duration.\n * This is useful for long lived pages or applications and helps to prevent memory leaks.\n * The exact time when the entry is cleared is not guaranteed, since it will be cleared during garbage collection.\n */\n clearUnusedAfter?: Duration | null;\n\n /**\n * Add the cache to the specified resource group(s).\n * This allows you to invalidate or clear multiple caches that belong to the same group.\n * All caches are always added to the `allResources` group.\n */\n resourceGroup?: ResourceGroup | ResourceGroup[];\n\n /**\n * Function to generate a custom cache key based on the provided arguments.\n * This allows you to control how cache entries are identified and reused.\n * By default, the arguments array is used as the cache key.\n *\n * @example\n * ```typescript\n * // Will use the same instance when provided with `undefined`, `{ num: 0 }`, `{ bool: false }`, etc.\n * createCache((filter?: { num?: number, bool?: boolean }) => fetchData(filter), {\n * getCacheKey: (filter?) => ({\n * num: filter?.num ?? 0,\n * bool: filter?.bool ?? false,\n * }),\n * });\n * ```\n */\n getCacheKey?: (...args: NoInfer<Args>) => unknown;\n}\n\nexport class Cache<T, Args extends any[] = []> extends Store<Promise<T>> {\n readonly state: Store<CacheState<T>> = createStore<CacheState<T>>({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n isConnected: false,\n });\n\n protected stalePromise?: Promise<T>;\n\n protected invalidationTimer?: ReturnType<typeof setTimeout>;\n\n constructor(\n getter: Calculate<Promise<T>>,\n public readonly args: Args,\n public readonly options: CacheOptions<T, Args> = {},\n public readonly derivedFromCache?: {\n cache: Cache<any, any>;\n selectors: (Selector<any, any> | AnyPath)[];\n },\n ) {\n super(getter, options, undefined);\n autobind(Cache);\n\n this.watchPromise();\n this.watchFocus();\n }\n\n get({ update = 'whenStale', backgroundUpdate = false }: CacheGetOptions = {}): Promise<T> {\n this.calculatedValue?.check();\n const promise = this.calculatedValue?.value;\n const stalePromise = this.stalePromise;\n\n if (\n (update === 'whenMissing' && !promise && !stalePromise) ||\n (update === 'whenStale' && !promise) ||\n update === 'force'\n ) {\n this.calculatedValue = calculatedValue(this, this.notify);\n this.notify();\n\n if ((!promise && !stalePromise) || !backgroundUpdate) {\n return this.calculatedValue.value;\n }\n }\n\n if (!promise || (stalePromise && backgroundUpdate)) {\n return stalePromise!;\n }\n\n return promise;\n }\n\n updateValue(value: MaybePromise<T> | ((value: T | undefined) => T)): void {\n if (value instanceof Function) {\n value = value(this.state.get().value);\n }\n this.set(PromiseWithState.resolve(value));\n }\n\n updateError(error: unknown): void {\n this.set(PromiseWithState.reject(error));\n }\n\n invalidate(recursive?: boolean): void {\n const { clearOnInvalidate } = this.options;\n\n if (clearOnInvalidate) {\n return this.clear(recursive);\n }\n\n const { status, isStale, isUpdating } = this.state.get();\n if (status !== 'pending' && !isStale && !isUpdating) {\n this.stalePromise = this.calculatedValue?.value;\n }\n\n this.state.set((state) => ({\n ...state,\n isStale: true,\n isUpdating: false,\n }));\n\n super.invalidate(recursive);\n }\n\n clear(recursive?: boolean): void {\n this.state.set({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n isConnected: false,\n });\n delete this.stalePromise;\n\n super.invalidate(recursive);\n }\n\n mapValue<S>(selector: Selector<T, S>): Cache<S, Args>;\n\n mapValue<const P extends AnyPath>(\n selector: P extends Path<T> ? P : Path<T>,\n ): Cache<Value<T, P>, Args>;\n\n mapValue(selector: Selector<any, any> | AnyPath) {\n return mapValue(this, selector);\n }\n\n protected watchPromise(): void {\n this.subscribe(\n async (promise) => {\n if (promise instanceof PromiseWithState && promise.state.status !== 'pending') {\n promise.catch(() => undefined);\n\n this.state.set((state) => ({\n ...promise.state,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n\n delete this.stalePromise;\n this.setTimers();\n return;\n }\n\n this.state.set((state) => ({\n ...state,\n isUpdating: true,\n }));\n\n this.setTimers();\n\n try {\n const value = await promise;\n\n if (promise !== this.calculatedValue?.value) {\n return;\n }\n\n this.state.set((state) => ({\n status: 'value',\n value,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n delete this.stalePromise;\n this.setTimers();\n } catch (error) {\n if (promise !== this.calculatedValue?.value) {\n return;\n }\n\n this.state.set((state) => ({\n status: 'error',\n error,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n delete this.stalePromise;\n this.setTimers();\n }\n },\n { passive: true },\n );\n }\n\n protected setTimers(): void {\n if (this.invalidationTimer) {\n clearTimeout(this.invalidationTimer);\n }\n this.invalidationTimer = undefined;\n\n const state = this.state.get();\n let { invalidateAfter } = this.options;\n const ref = new WeakRef(this);\n\n if (state.status === 'pending') {\n return;\n }\n\n if (invalidateAfter instanceof Function) {\n invalidateAfter = invalidateAfter(state);\n }\n\n if (invalidateAfter !== null && invalidateAfter !== undefined) {\n this.invalidationTimer = setTimeout(\n () => ref?.deref()?.invalidate(),\n calcDuration(invalidateAfter),\n );\n }\n }\n\n protected watchFocus(): void {\n const { invalidateOnWindowFocus } = this.options;\n\n if (\n !invalidateOnWindowFocus ||\n typeof document === 'undefined' ||\n typeof document.addEventListener === 'undefined'\n ) {\n return;\n }\n\n const ref = new WeakRef(this);\n\n const onFocus = () => {\n const that = ref?.deref();\n if (!that) {\n document.removeEventListener('visibilitychange', onFocus);\n return;\n }\n\n if (!document.hidden && !that.state.get().isConnected) {\n that.invalidate();\n }\n };\n\n document.addEventListener('visibilitychange', onFocus);\n }\n}\n\nfunction mapValue<T, S, Args extends any[]>(\n cache: Cache<T, Args>,\n _selector: Selector<T, S> | AnyPath,\n): Cache<S, Args> {\n const selector = makeSelector(_selector);\n const derivedFromCache = {\n cache: cache.derivedFromCache ? cache.derivedFromCache.cache : cache,\n selectors: cache.derivedFromCache\n ? [...cache.derivedFromCache.selectors, _selector]\n : [_selector],\n };\n\n return new Cache<S, Args>(\n async ({ use }) => {\n const value = await use(cache);\n return selector(value);\n },\n cache.args,\n {\n equals: cache.options.equals,\n },\n derivedFromCache,\n );\n}\n\nexport type CreateCacheResult<T, Args extends any[]> = [] extends Args\n ? CacheBundle<T, Args> & Cache<T, Args>\n : CacheBundle<T, Args>;\n\nexport interface InvalidationOptions<T, Args extends any[]> {\n filter?: (cache: Cache<T, Args>) => boolean;\n}\n\nexport type CacheBundle<T, Args extends any[]> = {\n (...args: Args): Cache<T, Args>;\n mapCache<S>(selector: Selector<T, S>): CreateCacheResult<S, Args>;\n mapValue<const P>(selector: Constrain<P, Path<T>>): CreateCacheResult<Value<T, P>, Args>;\n invalidateAll: (options?: InvalidationOptions<T, Args>) => void;\n clearAll: (options?: InvalidationOptions<T, Args>) => void;\n getInstances: () => Cache<T, Args>[];\n};\n\nfunction create<T, Args extends any[] = []>(\n cacheFunction: CacheFunction<T, Args>,\n options?: CacheOptions<T, Args>,\n): CreateCacheResult<T, Args> {\n return internalCreate<T, Args>(cacheFunction, options);\n}\n\nfunction internalCreate<T, Args extends any[] = []>(\n source:\n | CacheFunction<T, Args>\n | [cache: CacheBundle<any, Args>, selector: Selector<any, T> | AnyPath],\n options?: CacheOptions<T, Args>,\n): CreateCacheResult<T, Args> {\n options = { ...createCache.defaultOptions, ...options };\n const { clearUnusedAfter, resourceGroup } = options ?? {};\n\n let baseInstance: CacheBundle<T, Args> & Cache<T, Args>;\n\n const instanceCache = new InstanceCache<Args, Cache<T, Args>>(\n (...args: Args): Cache<T, Args> => {\n if (Array.isArray(source)) {\n const [cache, selector] = source;\n return mapValue(cache(...args), selector);\n }\n\n return new Cache(\n (helpers) => {\n const result = source.apply(helpers, args);\n\n if (result instanceof Function) {\n return result(helpers);\n }\n\n return result;\n },\n args,\n options,\n undefined,\n );\n },\n clearUnusedAfter ? calcDuration(clearUnusedAfter) : undefined,\n );\n\n function get(...args: Args) {\n const sliceAfter = args.lastIndexOf(undefined);\n if (sliceAfter !== -1) {\n args = args.slice(0, sliceAfter) as Args;\n }\n\n const cacheKey = options?.getCacheKey ? options.getCacheKey(...args) : args;\n return instanceCache.getWithKey(args, cacheKey);\n }\n\n const mapCache = (selector: any) => {\n return internalCreate([baseInstance, selector]);\n };\n\n const invalidateAll = ({ filter = () => true }: InvalidationOptions<T, Args> = {}) => {\n for (const instance of instanceCache.values()) {\n if (filter(instance)) {\n instance.invalidate();\n }\n }\n };\n\n const clearAll = ({ filter = () => true }: InvalidationOptions<T, Args> = {}) => {\n for (const instance of instanceCache.values()) {\n if (filter(instance)) {\n instance.clear();\n }\n }\n };\n\n const getInstances = () => {\n return instanceCache.values();\n };\n\n baseInstance = new Proxy(\n Object.assign(() => undefined, {\n mapCache,\n invalidateAll,\n clearAll,\n getInstances,\n }),\n {\n apply(_target, _thisArg, argArray) {\n return get(...(argArray as unknown as Args));\n },\n get(target, p, receiver) {\n if (Reflect.has(target, p)) {\n return Reflect.get(target, p, receiver);\n }\n\n const baseCache = get(...([] as unknown as Args));\n return Reflect.get(baseCache, p, baseCache);\n },\n },\n ) as unknown as CacheBundle<T, Args> & Cache<T, Args>;\n\n const groups = Array.isArray(resourceGroup)\n ? resourceGroup\n : resourceGroup\n ? [resourceGroup]\n : [];\n\n for (const group of groups.concat(allResources)) {\n group.add(baseInstance);\n }\n\n return baseInstance;\n}\n\nexport const createCache: typeof create & { defaultOptions: CacheOptions<any, any> } =\n /* @__PURE__ */ Object.assign(create, {\n defaultOptions: {\n invalidateOnWindowFocus: true,\n clearUnusedAfter: { days: 1 },\n retain: { milliseconds: 1 },\n equals: deepEqual,\n } as CacheOptions<any, any>,\n });\n","import { autobind } from '@lib/autobind';\n\nexport class Scope<T> {\n constructor(public readonly defaultValue: T) {\n autobind(Scope);\n }\n}\n\nexport function createScope<T>(defaultValue: T): Scope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AO,IAAI,GAAI;;EAEjB,IAAI,QAAQ,GAAG,UAAU;AACvB,OAAI,QAAQ,IAAI,QAAQ,GACtB,QAAO,QAAQ,IAAI,QAAQ,GAAG;GAGhC,MAAM,YAAY,IAAI,GAAI;AAC1B,UAAO,QAAQ,IAAI,WAAW,GAAG;;;CAKvC,MAAM,SAAS,MAAM,QAAQ,iBACzB,gBACA,gBACE,CAAC,iBACD;AAEN,MAAK,MAAM,SAAS,OAAO,OAAO,cAChC,OAAM,IAAI;AAGZ,QAAO;;AAGT,MAAaG,cACK,uBAAO,OAAO,QAAQ,EACpC,gBAAgB;CACd,yBAAyB;CACzB,kBAAkB,EAAE,MAAM;CAC1B,QAAQ,EAAE,cAAc;CACxB,QAAQC;;;;;AC3dd,IAAa,QAAb,MAAa,MAAS;CACpB,YAAY,AAAgBC,cAAiB;EAAjB;AAC1B,yBAAS;;;AAIb,SAAgB,YAAe,cAA2B;AACxD,QAAO,IAAI,MAAM"}
|
|
1
|
+
{"version":3,"file":"scope-BfYAP7hS.cjs","names":["factory: (...args: Args) => T","cacheTime?: number","simpleHash","name?: string","allResources: ResourceGroup","Store","args: Args","options: CacheOptions<T, Args>","derivedFromCache?: {\n cache: Cache<any, any>;\n selectors: (Selector<any, any> | AnyPath)[];\n }","createStore","calculatedValue","PromiseWithState","calcDuration","makeSelector","baseInstance: CacheBundle<T, Args> & Cache<T, Args>","createCache: typeof create & { defaultOptions: CacheOptions<any, any> }","deepEqual","defaultValue: T"],"sources":["../src/lib/instanceCache.ts","../src/core/resourceGroup.ts","../src/core/cache.ts","../src/core/scope.ts"],"sourcesContent":["import { simpleHash } from './hash';\n\nexport class InstanceCache<Args extends any[], T extends object> {\n private cache = new Map<string, { t: number; ref?: T; weakRef: WeakRef<T> }>();\n\n private interval = this.cacheTime\n ? setInterval(() => this.cleanup(), Math.max(this.cacheTime / 10, 1))\n : undefined;\n\n constructor(\n public readonly factory: (...args: Args) => T,\n public readonly cacheTime?: number,\n ) {}\n\n cleanup(): void {\n const cutoff = this.now() - (this.cacheTime ?? 0);\n\n for (const [key, entry] of this.cache.entries()) {\n if (entry.ref && entry.t <= cutoff) {\n delete entry.ref;\n }\n\n if (!entry.ref && !entry.weakRef?.deref()) {\n this.cache.delete(key);\n }\n }\n }\n\n get(...args: Args): T {\n return this.getWithKey(args, args);\n }\n\n getWithKey(args: Args, cacheKey: unknown): T {\n const key = simpleHash(cacheKey);\n let entry = this.cache.get(key);\n let value = entry?.ref ?? entry?.weakRef?.deref();\n\n if (!entry || !value) {\n value = this.factory(...args);\n entry = {\n t: this.now(),\n ref: value,\n weakRef: new WeakRef(value),\n };\n\n this.cache.set(key, entry);\n } else {\n entry.t = this.now();\n entry.ref ??= value;\n }\n\n return value;\n }\n\n values(): T[] {\n return [...this.cache.values()]\n .map((entry) => entry.ref ?? entry.weakRef?.deref())\n .filter((value): value is T => !!value);\n }\n\n stop(): void {\n if (this.interval) {\n clearInterval(this.interval);\n }\n }\n\n stats(): { count: number; withRef: number; withWeakRef: number } {\n return {\n count: this.cache.size,\n withRef: [...this.cache.values()].filter((x) => !!x.ref).length,\n withWeakRef: [...this.cache.values()].filter((x) => !!x.weakRef?.deref()).length,\n };\n }\n\n private now() {\n return performance.now();\n }\n}\n","import { autobind } from '@lib/autobind';\n\nexport interface Resource {\n invalidateAll(): void;\n clearAll(): void;\n}\n\nexport class ResourceGroup {\n private refMap = new WeakMap<Resource, WeakRef<Resource>>();\n\n private refSet = new Set<WeakRef<Resource>>();\n\n constructor(public readonly name?: string) {\n autobind(ResourceGroup);\n }\n\n add(resource: Resource): void {\n const ref = new WeakRef(resource);\n this.refMap.set(resource, ref);\n this.refSet.add(ref);\n }\n\n delete(resource: Resource): void {\n const ref = this.refMap.get(resource);\n if (ref) {\n this.refMap.delete(resource);\n this.refSet.delete(ref);\n }\n }\n\n invalidateAll(): void {\n for (const ref of this.refSet) {\n const resource = ref.deref();\n if (resource) {\n resource.invalidateAll();\n } else {\n this.refSet.delete(ref);\n }\n }\n }\n\n clearAll(): void {\n for (const ref of this.refSet) {\n const resource = ref.deref();\n if (resource) {\n resource.clearAll();\n } else {\n this.refSet.delete(ref);\n }\n }\n }\n}\n\nexport const allResources: ResourceGroup = /* @__PURE__ */ new ResourceGroup();\n\nexport function createResourceGroup(name?: string): ResourceGroup {\n return new ResourceGroup(name);\n}\n","import { autobind } from '@lib/autobind';\nimport type { CacheState, ErrorState, ValueState } from '@lib/cacheState';\nimport { calcDuration } from '@lib/calcDuration';\nimport { calculatedValue } from '@lib/calculatedValue';\nimport type { Constrain } from '@lib/constrain';\nimport { deepEqual } from '@lib/equals';\nimport { InstanceCache } from '@lib/instanceCache';\nimport { makeSelector } from '@lib/makeSelector';\nimport { type MaybePromise } from '@lib/maybePromise';\nimport type { AnyPath, Path, Value } from '@lib/path';\nimport { PromiseWithState } from '@lib/promiseWithState';\nimport type { Duration, Selector } from './commonTypes';\nimport { allResources, type ResourceGroup } from './resourceGroup';\nimport { Store, createStore, type Calculate, type StoreOptions } from './store';\n\nexport interface CacheGetOptions {\n /**\n * How to handle the cache when getting the value.\n * - `whenMissing`: Only fetch a new value if there is no cached value.\n * - `whenStale`: Fetch a new value if there is no cached value or if the cached value is stale.\n * - `force`: Always fetch a new value, regardless of the cache state.\n */\n update?: 'whenMissing' | 'whenStale' | 'force';\n\n /**\n * If set to `true`, the cache will be updated in the background.\n * This means that a stale value will be returned immediately, if available, while the new value is being fetched.\n */\n backgroundUpdate?: boolean;\n}\n\nexport interface CacheFunction<T, Args extends any[] = []> {\n (...args: Args): Promise<T> | Calculate<Promise<T>>;\n}\n\nexport interface CacheOptions<T, Args extends any[]> extends StoreOptions<Promise<T>> {\n /**\n * How long to keep the cache entry before it is considered stale.\n * If set to `undefined` or `null`, the cache entry will never be invalidated automatically.\n *\n * @example\n * ```typescript\n * createCache(fetchData, {\n * invalidateAfter: { seconds: 10 },\n * });\n * ```\n */\n invalidateAfter?: Duration | ((state: ValueState<T> | ErrorState) => Duration | null) | null;\n\n /**\n * If set, the cache will be invalidated when the window gets focused.\n * This is useful for caches that are used in a browser environment and might become stale when the user switches tabs.\n */\n invalidateOnWindowFocus?: boolean;\n\n /**\n * If set, the cached value will be cleared when the cache is invalidated.\n * Without this option, the cache will keep the last value as stale until a new value becomes available.\n */\n clearOnInvalidate?: boolean;\n\n /**\n * If set, cache entries will be cleared after approximately the specified duration.\n * This is useful for long lived pages or applications and helps to prevent memory leaks.\n * The exact time when the entry is cleared is not guaranteed, since it will be cleared during garbage collection.\n */\n clearUnusedAfter?: Duration | null;\n\n /**\n * Add the cache to the specified resource group(s).\n * This allows you to invalidate or clear multiple caches that belong to the same group.\n * All caches are always added to the `allResources` group.\n */\n resourceGroup?: ResourceGroup | ResourceGroup[];\n\n /**\n * Function to generate a custom cache key based on the provided arguments.\n * This allows you to control how cache entries are identified and reused.\n * By default, the arguments array is used as the cache key.\n *\n * @example\n * ```typescript\n * // Will use the same instance when provided with `undefined`, `{ num: 0 }`, `{ bool: false }`, etc.\n * createCache((filter?: { num?: number, bool?: boolean }) => fetchData(filter), {\n * getCacheKey: (filter?) => ({\n * num: filter?.num ?? 0,\n * bool: filter?.bool ?? false,\n * }),\n * });\n * ```\n */\n getCacheKey?: (...args: NoInfer<Args>) => unknown;\n}\n\nexport class Cache<T, Args extends any[] = []> extends Store<Promise<T>> {\n readonly state: Store<CacheState<T>> = createStore<CacheState<T>>({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n isConnected: false,\n });\n\n protected stalePromise?: Promise<T>;\n\n protected invalidationTimer?: ReturnType<typeof setTimeout>;\n\n constructor(\n getter: Calculate<Promise<T>>,\n public readonly args: Args,\n public readonly options: CacheOptions<T, Args> = {},\n public readonly derivedFromCache?: {\n cache: Cache<any, any>;\n selectors: (Selector<any, any> | AnyPath)[];\n },\n ) {\n super(getter, options, undefined);\n autobind(Cache);\n\n this.watchPromise();\n this.watchFocus();\n }\n\n get({ update = 'whenStale', backgroundUpdate = false }: CacheGetOptions = {}): Promise<T> {\n this.calculatedValue?.check();\n const promise = this.calculatedValue?.value;\n const stalePromise = this.stalePromise;\n\n if (\n (update === 'whenMissing' && !promise && !stalePromise) ||\n (update === 'whenStale' && !promise) ||\n update === 'force'\n ) {\n this.calculatedValue = calculatedValue(this, this.notify);\n this.notify();\n\n if ((!promise && !stalePromise) || !backgroundUpdate) {\n return this.calculatedValue.value;\n }\n }\n\n if (!promise || (stalePromise && backgroundUpdate)) {\n return stalePromise!;\n }\n\n return promise;\n }\n\n updateValue(value: MaybePromise<T> | ((value: T | undefined) => T)): void {\n if (value instanceof Function) {\n value = value(this.state.get().value);\n }\n this.set(PromiseWithState.resolve(value));\n }\n\n updateError(error: unknown): void {\n this.set(PromiseWithState.reject(error));\n }\n\n invalidate(recursive?: boolean): void {\n const { clearOnInvalidate } = this.options;\n\n if (clearOnInvalidate) {\n return this.clear(recursive);\n }\n\n const { status, isStale, isUpdating } = this.state.get();\n if (status !== 'pending' && !isStale && !isUpdating) {\n this.stalePromise = this.calculatedValue?.value;\n }\n\n this.state.set((state) => ({\n ...state,\n isStale: true,\n isUpdating: false,\n }));\n\n super.invalidate(recursive);\n }\n\n clear(recursive?: boolean): void {\n this.state.set({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n isConnected: false,\n });\n delete this.stalePromise;\n\n super.invalidate(recursive);\n }\n\n mapValue<S>(selector: Selector<T, S>): Cache<S, Args>;\n\n mapValue<const P extends AnyPath>(\n selector: P extends Path<T> ? P : Path<T>,\n ): Cache<Value<T, P>, Args>;\n\n mapValue(selector: Selector<any, any> | AnyPath) {\n return mapValue(this, selector);\n }\n\n protected watchPromise(): void {\n this.subscribe(\n async (promise) => {\n if (promise instanceof PromiseWithState && promise.state.status !== 'pending') {\n promise.catch(() => undefined);\n\n this.state.set((state) => ({\n ...promise.state,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n\n delete this.stalePromise;\n this.setTimers();\n return;\n }\n\n this.state.set((state) => ({\n ...state,\n isUpdating: true,\n }));\n\n this.setTimers();\n\n try {\n const value = await promise;\n\n if (promise !== this.calculatedValue?.value) {\n return;\n }\n\n this.state.set((state) => ({\n status: 'value',\n value,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n delete this.stalePromise;\n this.setTimers();\n } catch (error) {\n if (promise !== this.calculatedValue?.value) {\n return;\n }\n\n this.state.set((state) => ({\n status: 'error',\n error,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n delete this.stalePromise;\n this.setTimers();\n }\n },\n { passive: true },\n );\n }\n\n protected setTimers(): void {\n if (this.invalidationTimer) {\n clearTimeout(this.invalidationTimer);\n }\n this.invalidationTimer = undefined;\n\n const state = this.state.get();\n let { invalidateAfter } = this.options;\n const ref = new WeakRef(this);\n\n if (state.status === 'pending') {\n return;\n }\n\n if (invalidateAfter instanceof Function) {\n invalidateAfter = invalidateAfter(state);\n }\n\n if (invalidateAfter !== null && invalidateAfter !== undefined) {\n this.invalidationTimer = setTimeout(\n () => ref?.deref()?.invalidate(),\n calcDuration(invalidateAfter),\n );\n }\n }\n\n protected watchFocus(): void {\n const { invalidateOnWindowFocus } = this.options;\n\n if (\n !invalidateOnWindowFocus ||\n typeof document === 'undefined' ||\n typeof document.addEventListener === 'undefined'\n ) {\n return;\n }\n\n const ref = new WeakRef(this);\n\n const onFocus = () => {\n const that = ref?.deref();\n if (!that) {\n document.removeEventListener('visibilitychange', onFocus);\n return;\n }\n\n if (!document.hidden && !that.state.get().isConnected) {\n that.invalidate();\n }\n };\n\n document.addEventListener('visibilitychange', onFocus);\n }\n}\n\nfunction mapValue<T, S, Args extends any[]>(\n cache: Cache<T, Args>,\n _selector: Selector<T, S> | AnyPath,\n): Cache<S, Args> {\n const selector = makeSelector(_selector);\n const derivedFromCache = {\n cache: cache.derivedFromCache ? cache.derivedFromCache.cache : cache,\n selectors: cache.derivedFromCache\n ? [...cache.derivedFromCache.selectors, _selector]\n : [_selector],\n };\n\n return new Cache<S, Args>(\n async ({ use }) => {\n const value = await use(cache);\n return selector(value);\n },\n cache.args,\n {\n equals: cache.options.equals,\n },\n derivedFromCache,\n );\n}\n\nexport type CreateCacheResult<T, Args extends any[]> = [] extends Args\n ? CacheBundle<T, Args> & Cache<T, Args>\n : CacheBundle<T, Args>;\n\nexport interface InvalidationOptions<T, Args extends any[]> {\n filter?: (cache: Cache<T, Args>) => boolean;\n}\n\nexport type CacheBundle<T, Args extends any[]> = {\n (...args: Args): Cache<T, Args>;\n mapCache<S>(selector: Selector<T, S>): CreateCacheResult<S, Args>;\n mapValue<const P>(selector: Constrain<P, Path<T>>): CreateCacheResult<Value<T, P>, Args>;\n invalidateAll: (options?: InvalidationOptions<T, Args>) => void;\n clearAll: (options?: InvalidationOptions<T, Args>) => void;\n getInstances: () => Cache<T, Args>[];\n};\n\nfunction create<T, Args extends any[] = []>(\n cacheFunction: CacheFunction<T, Args>,\n options?: CacheOptions<T, Args>,\n): CreateCacheResult<T, Args> {\n return internalCreate<T, Args>(cacheFunction, options);\n}\n\nfunction internalCreate<T, Args extends any[] = []>(\n source:\n | CacheFunction<T, Args>\n | [cache: CacheBundle<any, Args>, selector: Selector<any, T> | AnyPath],\n options?: CacheOptions<T, Args>,\n): CreateCacheResult<T, Args> {\n options = { ...createCache.defaultOptions, ...options };\n const { clearUnusedAfter, resourceGroup } = options ?? {};\n\n let baseInstance: CacheBundle<T, Args> & Cache<T, Args>;\n\n const instanceCache = new InstanceCache<Args, Cache<T, Args>>(\n (...args: Args): Cache<T, Args> => {\n if (Array.isArray(source)) {\n const [cache, selector] = source;\n return mapValue(cache(...args), selector);\n }\n\n return new Cache(\n (helpers) => {\n const result = source.apply(helpers, args);\n\n if (result instanceof Function) {\n return result(helpers);\n }\n\n return result;\n },\n args,\n options,\n undefined,\n );\n },\n clearUnusedAfter ? calcDuration(clearUnusedAfter) : undefined,\n );\n\n function get(...args: Args) {\n const sliceAfter = args.lastIndexOf(undefined);\n if (sliceAfter !== -1) {\n args = args.slice(0, sliceAfter) as Args;\n }\n\n const cacheKey = options?.getCacheKey ? options.getCacheKey(...args) : args;\n return instanceCache.getWithKey(args, cacheKey);\n }\n\n const mapCache = (selector: any) => {\n return internalCreate([baseInstance, selector]);\n };\n\n const invalidateAll = ({ filter = () => true }: InvalidationOptions<T, Args> = {}) => {\n for (const instance of instanceCache.values()) {\n if (filter(instance)) {\n instance.invalidate();\n }\n }\n };\n\n const clearAll = ({ filter = () => true }: InvalidationOptions<T, Args> = {}) => {\n for (const instance of instanceCache.values()) {\n if (filter(instance)) {\n instance.clear();\n }\n }\n };\n\n const getInstances = () => {\n return instanceCache.values();\n };\n\n baseInstance = new Proxy(\n Object.assign(() => undefined, {\n mapCache,\n invalidateAll,\n clearAll,\n getInstances,\n }),\n {\n apply(_target, _thisArg, argArray) {\n return get(...(argArray as unknown as Args));\n },\n get(target, p, receiver) {\n if (Reflect.has(target, p)) {\n return Reflect.get(target, p, receiver);\n }\n\n const baseCache = get(...([] as unknown as Args));\n return Reflect.get(baseCache, p, baseCache);\n },\n },\n ) as unknown as CacheBundle<T, Args> & Cache<T, Args>;\n\n const groups = Array.isArray(resourceGroup)\n ? resourceGroup\n : resourceGroup\n ? [resourceGroup]\n : [];\n\n for (const group of groups.concat(allResources)) {\n group.add(baseInstance);\n }\n\n return baseInstance;\n}\n\nexport const createCache: typeof create & { defaultOptions: CacheOptions<any, any> } =\n /* @__PURE__ */ Object.assign(create, {\n defaultOptions: {\n invalidateOnWindowFocus: true,\n clearUnusedAfter: { days: 1 },\n retain: { milliseconds: 1 },\n equals: deepEqual,\n } as CacheOptions<any, any>,\n });\n","import { autobind } from '@lib/autobind';\n\nexport class Scope<T> {\n constructor(public readonly defaultValue: T) {\n autobind(Scope);\n }\n}\n\nexport function createScope<T>(defaultValue: T): Scope<T> {\n return new Scope(defaultValue);\n}\n"],"mappings":";;;;;AAEA,IAAa,gBAAb,MAAiE;CAO/D,YACE,AAAgBA,SAChB,AAAgBC,WAChB;EAFgB;EACA;+BARF,IAAI;kBAED,KAAK,YACpB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;AAC1B,UAAO,QAAQ,IAAI,WAAW,GAAG;;;CAKvC,MAAM,SAAS,MAAM,QAAQ,iBACzB,gBACA,gBACE,CAAC,iBACD;AAEN,MAAK,MAAM,SAAS,OAAO,OAAO,cAChC,OAAM,IAAI;AAGZ,QAAO;;AAGT,MAAaG,cACK,uBAAO,OAAO,QAAQ,EACpC,gBAAgB;CACd,yBAAyB;CACzB,kBAAkB,EAAE,MAAM;CAC1B,QAAQ,EAAE,cAAc;CACxB,QAAQC;;;;;AC3dd,IAAa,QAAb,MAAa,MAAS;CACpB,YAAY,AAAgBC,cAAiB;EAAjB;AAC1B,yBAAS;;;AAIb,SAAgB,YAAe,cAA2B;AACxD,QAAO,IAAI,MAAM"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const require_propAccess = require('./propAccess-
|
|
1
|
+
const require_propAccess = require('./propAccess-BdLsqViO.cjs');
|
|
2
2
|
|
|
3
3
|
//#region src/lib/autobind.ts
|
|
4
4
|
const marker = Symbol("autobind");
|
|
@@ -816,4 +816,4 @@ Object.defineProperty(exports, 'throttle', {
|
|
|
816
816
|
return throttle;
|
|
817
817
|
}
|
|
818
818
|
});
|
|
819
|
-
//# sourceMappingURL=store-
|
|
819
|
+
//# sourceMappingURL=store-1TGlSyq4.cjs.map
|