@tanstack/query-persist-client-core 5.104.4 → 5.105.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -21,7 +21,7 @@ const PERSISTER_KEY_PREFIX = "tanstack-query";
21
21
  * @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,
22
22
  * restore, remove, and garbage collect persisted queries manually.
23
23
  */
24
- function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e5, serialize = JSON.stringify, deserialize = JSON.parse, prefix = PERSISTER_KEY_PREFIX, refetchOnRestore = true, filters }) {
24
+ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e5, serialize = JSON.stringify, deserialize = JSON.parse, prefix = PERSISTER_KEY_PREFIX, refetchOnRestore = true, filters: persistFilters }) {
25
25
  /**
26
26
  * Checks whether a persisted query should be discarded.
27
27
  * @param persistedQuery - The persisted query to check.
@@ -111,7 +111,7 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
111
111
  * @returns A promise that resolves with the restored or fetched data.
112
112
  */
113
113
  async function persisterFn(queryFn, ctx, query) {
114
- const matchesFilter = filters ? (0, _tanstack_query_core.matchQuery)(filters, query) : true;
114
+ const matchesFilter = persistFilters ? (0, _tanstack_query_core.matchQuery)(persistFilters, query) : true;
115
115
  if (matchesFilter && query.state.data === void 0 && storage != null) {
116
116
  const restoredData = await retrieveQuery(query.queryHash, (persistedQuery) => {
117
117
  query.setState({
@@ -1 +1 @@
1
- {"version":3,"file":"createPersister.cjs","names":["matchQuery","hashKey","partialMatchKey"],"sources":["../../src/createPersister.ts"],"sourcesContent":["import {\n hashKey,\n matchQuery,\n notifyManager,\n partialMatchKey,\n} from '@tanstack/query-core'\nimport type {\n Query,\n QueryClient,\n QueryFilters,\n QueryFunctionContext,\n QueryKey,\n QueryState,\n} from '@tanstack/query-core'\n\n/**\n * A single query as stored by {@link experimental_createQueryPersister}.\n */\nexport interface PersistedQuery {\n /**\n * The `buster` the query was saved with. Entries with a different `buster` are discarded.\n */\n buster: string\n /**\n * The hash of the query.\n */\n queryHash: string\n /**\n * The key of the query.\n */\n queryKey: QueryKey\n /**\n * The state of the query, including its data and when it was last updated.\n */\n state: QueryState\n}\n\n/**\n * A value, or a promise that resolves to it.\n */\nexport type MaybePromise<T> = T | Promise<T>\n\n/**\n * A key-value storage, such as `localStorage` or `AsyncStorage`, whose methods may be synchronous\n * or return promises.\n */\nexport interface AsyncStorage<TStorageValue = string> {\n /**\n * Reads the value stored under `key`, or `null`/`undefined` if there is none.\n */\n getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>\n /**\n * Stores `value` under `key`.\n */\n setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>\n /**\n * Removes the value stored under `key`.\n */\n removeItem: (key: string) => MaybePromise<void>\n /**\n * Returns all stored key-value pairs. Required for removing expired entries in bulk.\n */\n entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>\n}\n\n/**\n * Options for {@link experimental_createQueryPersister}.\n */\nexport interface StoragePersisterOptions<TStorageValue = string> {\n /**\n * The storage client used for setting and retrieving items from cache.\n * For SSR pass in `undefined`.\n */\n storage: AsyncStorage<TStorageValue> | undefined | null\n /**\n * How to serialize the data to storage.\n * @default `JSON.stringify`\n */\n serialize?: (persistedQuery: PersistedQuery) => MaybePromise<TStorageValue>\n /**\n * How to deserialize the data from storage.\n * @default `JSON.parse`\n */\n deserialize?: (cachedString: TStorageValue) => MaybePromise<PersistedQuery>\n /**\n * A unique string that can be used to forcefully invalidate existing caches,\n * if they do not share the same buster string\n */\n buster?: string\n /**\n * The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded\n * @default 24 hours\n */\n maxAge?: number\n /**\n * Prefix to be used for storage key.\n * Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.\n * @default 'tanstack-query'\n */\n prefix?: string\n /**\n * If set to `true`, the query will refetch on successful query restoration if the data is stale.\n * If set to `false`, the query will not refetch on successful query restoration.\n * If set to `'always'`, the query will always refetch on successful query restoration.\n * @defaultValue true\n */\n refetchOnRestore?: boolean | 'always'\n /**\n * Filters to narrow down which Queries should be persisted.\n */\n filters?: QueryFilters\n}\n\nexport const PERSISTER_KEY_PREFIX = 'tanstack-query'\n\n/**\n * Warning: experimental feature.\n * This utility function enables fine-grained query persistence.\n * Simple add it as a `persister` parameter to `useQuery` or `defaultOptions` on `queryClient`.\n *\n * ```\n * useQuery({\n * queryKey: ['myKey'],\n * queryFn: fetcher,\n * persister: createPersister({\n * storage: localStorage,\n * }),\n * })\n * ```\n * @param options - The storage to persist to, and the options for serializing, expiring, and\n * filtering persisted queries.\n * @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,\n * restore, remove, and garbage collect persisted queries manually.\n */\nexport function experimental_createQueryPersister<TStorageValue = string>({\n storage,\n buster = '',\n maxAge = 1000 * 60 * 60 * 24,\n serialize = JSON.stringify as Required<\n StoragePersisterOptions<TStorageValue>\n >['serialize'],\n deserialize = JSON.parse as Required<\n StoragePersisterOptions<TStorageValue>\n >['deserialize'],\n prefix = PERSISTER_KEY_PREFIX,\n refetchOnRestore = true,\n filters,\n}: StoragePersisterOptions<TStorageValue>) {\n /**\n * Checks whether a persisted query should be discarded.\n * @param persistedQuery - The persisted query to check.\n * @returns `true` if it has no `dataUpdatedAt`, is older than `maxAge`, or has a different\n * `buster`.\n */\n function isExpiredOrBusted(persistedQuery: PersistedQuery) {\n if (persistedQuery.state.dataUpdatedAt) {\n const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt\n const expired = queryAge > maxAge\n const busted = persistedQuery.buster !== buster\n\n if (expired || busted) {\n return true\n }\n\n return false\n }\n\n return true\n }\n\n /**\n * Reads the persisted data of a query from storage. Expired, busted, or unreadable entries are\n * removed instead.\n * @param queryHash - The hash of the query to read.\n * @param afterRestoreMacroTask - Scheduled with the persisted query after it is restored.\n * @returns A promise that resolves with the persisted data, or `undefined` if nothing was\n * restored.\n */\n async function retrieveQuery<T>(\n queryHash: string,\n afterRestoreMacroTask?: (persistedQuery: PersistedQuery) => void,\n ) {\n if (storage != null) {\n const storageKey = `${prefix}-${queryHash}`\n try {\n const storedData = await storage.getItem(storageKey)\n if (storedData != null) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(storedData)\n } catch {\n await storage.removeItem(storageKey)\n return\n }\n\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(storageKey)\n } else {\n if (afterRestoreMacroTask) {\n // Just after restoring we want to get fresh data from the server if it's stale\n notifyManager.schedule(() =>\n afterRestoreMacroTask(persistedQuery),\n )\n }\n // We must resolve the promise here, as otherwise we will have `loading` state in the app until `queryFn` resolves\n return persistedQuery.state.data as T\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV === 'development') {\n console.error(err)\n console.warn(\n 'Encountered an error attempting to restore query cache from persisted location.',\n )\n }\n await storage.removeItem(storageKey)\n }\n }\n\n return\n }\n\n /**\n * Persists the query with the given key, if it exists in the client's cache.\n * @param queryKey - The key of the query to persist.\n * @param queryClient - The client whose cache holds the query.\n * @returns A promise that resolves once the query is persisted.\n */\n async function persistQueryByKey(\n queryKey: QueryKey,\n queryClient: QueryClient,\n ) {\n if (storage != null) {\n const query = queryClient.getQueryCache().find({ queryKey })\n if (query) {\n await persistQuery(query)\n } else {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n 'Could not find query to be persisted. QueryKey:',\n JSON.stringify(queryKey),\n )\n }\n }\n }\n }\n\n /**\n * Writes a query's state, key, hash, and `buster` to storage.\n * @param query - The query to persist.\n * @returns A promise that resolves once the entry is serialized and written.\n */\n async function persistQuery(query: Query) {\n if (storage != null) {\n const storageKey = `${prefix}-${query.queryHash}`\n await storage.setItem(\n storageKey,\n await serialize({\n state: query.state,\n queryKey: query.queryKey,\n queryHash: query.queryHash,\n buster: buster,\n }),\n )\n }\n }\n\n /**\n * The `persister` of a query: restores its data from storage if the query has none yet, otherwise\n * runs `queryFn` and persists the result.\n * @param queryFn - The query's own query function.\n * @param ctx - The context passed to `queryFn`.\n * @param query - The query being fetched.\n * @returns A promise that resolves with the restored or fetched data.\n */\n async function persisterFn<T, TQueryKey extends QueryKey>(\n queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>,\n ctx: QueryFunctionContext<TQueryKey>,\n query: Query,\n ) {\n const matchesFilter = filters ? matchQuery(filters, query) : true\n\n // Try to restore only if we do not have any data in the cache and we have persister defined\n if (matchesFilter && query.state.data === undefined && storage != null) {\n const restoredData = await retrieveQuery(\n query.queryHash,\n (persistedQuery: PersistedQuery) => {\n // Set proper updatedAt, since resolving in the first pass overrides those values\n query.setState({\n dataUpdatedAt: persistedQuery.state.dataUpdatedAt,\n errorUpdatedAt: persistedQuery.state.errorUpdatedAt,\n })\n\n if (\n refetchOnRestore === 'always' ||\n (refetchOnRestore === true && query.isStale())\n ) {\n query.fetch()\n }\n },\n )\n\n if (restoredData !== undefined) {\n return Promise.resolve(restoredData as T)\n }\n }\n\n // If we did not restore, or restoration failed - fetch\n const queryFnResult = await queryFn(ctx)\n\n if (matchesFilter && storage != null) {\n // Persist if we have storage defined, we use timeout to get proper state to be persisted\n notifyManager.schedule(() => {\n persistQuery(query)\n })\n }\n\n return Promise.resolve(queryFnResult)\n }\n\n /**\n * Removes expired, busted, or unreadable entries from storage. Requires the storage to implement\n * `entries`.\n * @returns A promise that resolves once every entry is checked.\n */\n async function persisterGc() {\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n }\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Garbage collection is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n /**\n * Restores every persisted query matching `filters` into the client's cache with\n * `queryClient.setQueryData`. Requires the storage to implement `entries`.\n * @param queryClient - The client to restore the queries into.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * restored.\n * @returns A promise that resolves once every entry is checked.\n */\n async function restoreQueries(\n queryClient: QueryClient,\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n continue\n }\n\n if (queryKey) {\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n }\n\n queryClient.setQueryData(\n persistedQuery.queryKey,\n persistedQuery.state.data,\n {\n updatedAt: persistedQuery.state.dataUpdatedAt,\n },\n )\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Restoration of all stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n /**\n * Removes every persisted query matching `filters` from storage. Requires the storage to implement\n * `entries`.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * removed.\n * @returns A promise that resolves once every entry is checked.\n */\n async function removeQueries(\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const entries = await storage.entries()\n const storageKeyPrefix = `${prefix}-`\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n if (!queryKey) {\n await storage.removeItem(key)\n continue\n }\n\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n\n await storage.removeItem(key)\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Removal of stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n return {\n persisterFn,\n persistQuery,\n persistQueryByKey,\n retrieveQuery,\n persisterGc,\n restoreQueries,\n removeQueries,\n }\n}\n"],"mappings":";;;AAmHA,MAAa,uBAAuB;;;;;;;;;;;;;;;;;;;;AAqBpC,SAAgB,kCAA0D,EACxE,SACA,SAAS,IACT,SAAS,OACT,YAAY,KAAK,WAGjB,cAAc,KAAK,OAGnB,SAAS,sBACT,mBAAmB,MACnB,WACyC;;;;;;;CAOzC,SAAS,kBAAkB,gBAAgC;EACzD,IAAI,eAAe,MAAM,eAAe;GAEtC,MAAM,UADW,KAAK,IAAI,IAAI,eAAe,MAAM,gBACxB;GAC3B,MAAM,SAAS,eAAe,WAAW;GAEzC,IAAI,WAAW,QACb,OAAO;GAGT,OAAO;EACT;EAEA,OAAO;CACT;;;;;;;;;CAUA,eAAe,cACb,WACA,uBACA;EACA,IAAI,WAAW,MAAM;GACnB,MAAM,aAAa,GAAG,OAAO,GAAG;GAChC,IAAI;IACF,MAAM,aAAa,MAAM,QAAQ,QAAQ,UAAU;IACnD,IAAI,cAAc,MAAM;KACtB,IAAI;KACJ,IAAI;MACF,iBAAiB,MAAM,YAAY,UAAU;KAC/C,QAAQ;MACN,MAAM,QAAQ,WAAW,UAAU;MACnC;KACF;KAEA,IAAI,kBAAkB,cAAc,GAClC,MAAM,QAAQ,WAAW,UAAU;UAC9B;MACL,IAAI,uBAEF,qBAAA,cAAc,eACZ,sBAAsB,cAAc,CACtC;MAGF,OAAO,eAAe,MAAM;KAC9B;IACF;GACF,SAAS,KAAK;IACZ,IAAI,QAAQ,IAAI,aAAa,eAAe;K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aAAa,eAClC,MAAM,IAAI,MACR,wJACF;CAEJ;;;;;;;;CASA,eAAe,cACb,UAAoD,CAAC,GACtC;EACf,MAAM,EAAE,OAAO,aAAa;EAE5B,IAAA,YAAA,QAAA,YAAA,KAAA,IAAA,KAAA,IAAI,QAAS,SAAS;GACpB,MAAM,UAAU,MAAM,QAAQ,QAAQ;GACtC,MAAM,mBAAmB,GAAG,OAAO;GACnC,KAAK,MAAM,CAAC,KAAK,UAAU,SACzB,IAAI,IAAI,WAAW,gBAAgB,GAAG;IACpC,IAAI,CAAC,UAAU;KACb,MAAM,QAAQ,WAAW,GAAG;KAC5B;IACF;IAEA,IAAI;IACJ,IAAI;KACF,iBAAiB,MAAM,YAAY,KAAK;IAC1C,QAAQ;KACN,MAAM,QAAQ,WAAW,GAAG;KAC5B;IACF;IAEA,IAAI,OACE;SAAA,eAAe,eAAA,GAAcD,qBAAAA,QAAAA,CAAQ,QAAQ,GAC/C;IAAA,OAEG,IAAI,EAAA,GAACC,qBAAAA,gBAAAA,CAAgB,eAAe,UAAU,QAAQ,GAC3D;IAGF,MAAM,QAAQ,WAAW,GAAG;GAC9B;EAEJ,OAAO,IAAI,QAAQ,IAAI,aAAa,eAClC,MAAM,IAAI,MACR,gJACF;CAEJ;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
1
+ {"version":3,"file":"createPersister.cjs","names":["matchQuery","hashKey","partialMatchKey"],"sources":["../../src/createPersister.ts"],"sourcesContent":["import {\n hashKey,\n matchQuery,\n notifyManager,\n partialMatchKey,\n} from '@tanstack/query-core'\nimport type {\n Query,\n QueryClient,\n QueryFilters,\n QueryFunctionContext,\n QueryKey,\n QueryState,\n} from '@tanstack/query-core'\n\n/**\n * A single query as stored by {@link experimental_createQueryPersister}.\n */\nexport interface PersistedQuery {\n /**\n * The `buster` the query was saved with. Entries with a different `buster` are discarded.\n */\n buster: string\n /**\n * The hash of the query.\n */\n queryHash: string\n /**\n * The key of the query.\n */\n queryKey: QueryKey\n /**\n * The state of the query, including its data and when it was last updated.\n */\n state: QueryState\n}\n\n/**\n * A value, or a promise that resolves to it.\n */\nexport type MaybePromise<T> = T | Promise<T>\n\n/**\n * A key-value storage, such as `localStorage` or `AsyncStorage`, whose methods may be synchronous\n * or return promises.\n */\nexport interface AsyncStorage<TStorageValue = string> {\n /**\n * Reads the value stored under `key`, or `null`/`undefined` if there is none.\n */\n getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>\n /**\n * Stores `value` under `key`.\n */\n setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>\n /**\n * Removes the value stored under `key`.\n */\n removeItem: (key: string) => MaybePromise<void>\n /**\n * Returns all stored key-value pairs. Required for removing expired entries in bulk.\n */\n entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>\n}\n\n/**\n * Options for {@link experimental_createQueryPersister}.\n */\nexport interface StoragePersisterOptions<TStorageValue = string> {\n /**\n * The storage client used for setting and retrieving items from cache.\n * For SSR pass in `undefined`.\n */\n storage: AsyncStorage<TStorageValue> | undefined | null\n /**\n * How to serialize the data to storage.\n * @default `JSON.stringify`\n */\n serialize?: (persistedQuery: PersistedQuery) => MaybePromise<TStorageValue>\n /**\n * How to deserialize the data from storage.\n * @default `JSON.parse`\n */\n deserialize?: (cachedString: TStorageValue) => MaybePromise<PersistedQuery>\n /**\n * A unique string that can be used to forcefully invalidate existing caches,\n * if they do not share the same buster string\n */\n buster?: string\n /**\n * The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded\n * @default 24 hours\n */\n maxAge?: number\n /**\n * Prefix to be used for storage key.\n * Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.\n * @default 'tanstack-query'\n */\n prefix?: string\n /**\n * If set to `true`, the query will refetch on successful query restoration if the data is stale.\n * If set to `false`, the query will not refetch on successful query restoration.\n * If set to `'always'`, the query will always refetch on successful query restoration.\n * @defaultValue true\n */\n refetchOnRestore?: boolean | 'always'\n /**\n * Filters to narrow down which Queries should be persisted.\n */\n filters?: QueryFilters\n}\n\nexport const PERSISTER_KEY_PREFIX = 'tanstack-query'\n\n/**\n * Warning: experimental feature.\n * This utility function enables fine-grained query persistence.\n * Simple add it as a `persister` parameter to `useQuery` or `defaultOptions` on `queryClient`.\n *\n * ```\n * useQuery({\n * queryKey: ['myKey'],\n * queryFn: fetcher,\n * persister: createPersister({\n * storage: localStorage,\n * }),\n * })\n * ```\n * @param options - The storage to persist to, and the options for serializing, expiring, and\n * filtering persisted queries.\n * @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,\n * restore, remove, and garbage collect persisted queries manually.\n */\nexport function experimental_createQueryPersister<TStorageValue = string>({\n storage,\n buster = '',\n maxAge = 24 * 60 * 60 * 1000,\n serialize = JSON.stringify as Required<\n StoragePersisterOptions<TStorageValue>\n >['serialize'],\n deserialize = JSON.parse as Required<\n StoragePersisterOptions<TStorageValue>\n >['deserialize'],\n prefix = PERSISTER_KEY_PREFIX,\n refetchOnRestore = true,\n filters: persistFilters,\n}: StoragePersisterOptions<TStorageValue>) {\n /**\n * Checks whether a persisted query should be discarded.\n * @param persistedQuery - The persisted query to check.\n * @returns `true` if it has no `dataUpdatedAt`, is older than `maxAge`, or has a different\n * `buster`.\n */\n function isExpiredOrBusted(persistedQuery: PersistedQuery) {\n if (persistedQuery.state.dataUpdatedAt) {\n const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt\n const expired = queryAge > maxAge\n const busted = persistedQuery.buster !== buster\n\n if (expired || busted) {\n return true\n }\n\n return false\n }\n\n return true\n }\n\n /**\n * Reads the persisted data of a query from storage. Expired, busted, or unreadable entries are\n * removed instead.\n * @param queryHash - The hash of the query to read.\n * @param afterRestoreMacroTask - Scheduled with the persisted query after it is restored.\n * @returns A promise that resolves with the persisted data, or `undefined` if nothing was\n * restored.\n */\n async function retrieveQuery<T>(\n queryHash: string,\n afterRestoreMacroTask?: (persistedQuery: PersistedQuery) => void,\n ) {\n if (storage != null) {\n const storageKey = `${prefix}-${queryHash}`\n try {\n const storedData = await storage.getItem(storageKey)\n if (storedData != null) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(storedData)\n } catch {\n await storage.removeItem(storageKey)\n return\n }\n\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(storageKey)\n } else {\n if (afterRestoreMacroTask) {\n // Just after restoring we want to get fresh data from the server if it's stale\n notifyManager.schedule(() =>\n afterRestoreMacroTask(persistedQuery),\n )\n }\n // We must resolve the promise here, as otherwise we will have `loading` state in the app until `queryFn` resolves\n return persistedQuery.state.data as T\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV === 'development') {\n console.error(err)\n console.warn(\n 'Encountered an error attempting to restore query cache from persisted location.',\n )\n }\n await storage.removeItem(storageKey)\n }\n }\n\n return\n }\n\n /**\n * Persists the query with the given key, if it exists in the client's cache.\n * @param queryKey - The key of the query to persist.\n * @param queryClient - The client whose cache holds the query.\n * @returns A promise that resolves once the query is persisted.\n */\n async function persistQueryByKey(\n queryKey: QueryKey,\n queryClient: QueryClient,\n ) {\n if (storage != null) {\n const query = queryClient.getQueryCache().find({ queryKey })\n if (query) {\n await persistQuery(query)\n } else {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n 'Could not find query to be persisted. QueryKey:',\n JSON.stringify(queryKey),\n )\n }\n }\n }\n }\n\n /**\n * Writes a query's state, key, hash, and `buster` to storage.\n * @param query - The query to persist.\n * @returns A promise that resolves once the entry is serialized and written.\n */\n async function persistQuery(query: Query) {\n if (storage != null) {\n const storageKey = `${prefix}-${query.queryHash}`\n await storage.setItem(\n storageKey,\n await serialize({\n state: query.state,\n queryKey: query.queryKey,\n queryHash: query.queryHash,\n buster: buster,\n }),\n )\n }\n }\n\n /**\n * The `persister` of a query: restores its data from storage if the query has none yet, otherwise\n * runs `queryFn` and persists the result.\n * @param queryFn - The query's own query function.\n * @param ctx - The context passed to `queryFn`.\n * @param query - The query being fetched.\n * @returns A promise that resolves with the restored or fetched data.\n */\n async function persisterFn<T, TQueryKey extends QueryKey>(\n queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>,\n ctx: QueryFunctionContext<TQueryKey>,\n query: Query,\n ) {\n const matchesFilter = persistFilters\n ? matchQuery(persistFilters, query)\n : true\n\n // Try to restore only if we do not have any data in the cache and we have persister defined\n if (matchesFilter && query.state.data === undefined && storage != null) {\n const restoredData = await retrieveQuery(\n query.queryHash,\n (persistedQuery: PersistedQuery) => {\n // Set proper updatedAt, since resolving in the first pass overrides those values\n query.setState({\n dataUpdatedAt: persistedQuery.state.dataUpdatedAt,\n errorUpdatedAt: persistedQuery.state.errorUpdatedAt,\n })\n\n if (\n refetchOnRestore === 'always' ||\n (refetchOnRestore === true && query.isStale())\n ) {\n query.fetch()\n }\n },\n )\n\n if (restoredData !== undefined) {\n return Promise.resolve(restoredData as T)\n }\n }\n\n // If we did not restore, or restoration failed - fetch\n const queryFnResult = await queryFn(ctx)\n\n if (matchesFilter && storage != null) {\n // Persist if we have storage defined, we use timeout to get proper state to be persisted\n notifyManager.schedule(() => {\n persistQuery(query)\n })\n }\n\n return Promise.resolve(queryFnResult)\n }\n\n /**\n * Removes expired, busted, or unreadable entries from storage. Requires the storage to implement\n * `entries`.\n * @returns A promise that resolves once every entry is checked.\n */\n async function persisterGc() {\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n }\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Garbage collection is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n /**\n * Restores every persisted query matching `filters` into the client's cache with\n * `queryClient.setQueryData`. Requires the storage to implement `entries`.\n * @param queryClient - The client to restore the queries into.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * restored.\n * @returns A promise that resolves once every entry is checked.\n */\n async function restoreQueries(\n queryClient: QueryClient,\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n continue\n }\n\n if (queryKey) {\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n }\n\n queryClient.setQueryData(\n persistedQuery.queryKey,\n persistedQuery.state.data,\n {\n updatedAt: persistedQuery.state.dataUpdatedAt,\n },\n )\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Restoration of all stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n /**\n * Removes every persisted query matching `filters` from storage. Requires the storage to implement\n * `entries`.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * removed.\n * @returns A promise that resolves once every entry is checked.\n */\n async function removeQueries(\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const entries = await storage.entries()\n const storageKeyPrefix = `${prefix}-`\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n if (!queryKey) {\n await storage.removeItem(key)\n continue\n }\n\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n\n await storage.removeItem(key)\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Removal of stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n return {\n persisterFn,\n persistQuery,\n persistQueryByKey,\n retrieveQuery,\n persisterGc,\n restoreQueries,\n removeQueries,\n }\n}\n"],"mappings":";;;AAmHA,MAAa,uBAAuB;;;;;;;;;;;;;;;;;;;;AAqBpC,SAAgB,kCAA0D,EACxE,SACA,SAAS,IACT,SAAS,OACT,YAAY,KAAK,WAGjB,cAAc,KAAK,OAGnB,SAAS,sBACT,mBAAmB,MACnB,SAAS,kBACgC;;;;;;;CAOzC,SAAS,kBAAkB,gBAAgC;EACzD,IAAI,eAAe,MAAM,eAAe;GAEtC,MAAM,UADW,KAAK,IAAI,IAAI,eAAe,MAAM,gBACxB;GAC3B,MAAM,SAAS,eAAe,WAAW;GAEzC,IAAI,WAAW,QACb,OAAO;GAGT,OAAO;EACT;EAEA,OAAO;CACT;;;;;;;;;CAUA,eAAe,cACb,WACA,uBACA;EACA,IAAI,WAAW,MAAM;GACnB,MAAM,aAAa,GAAG,OAAO,GAAG;GAChC,IAAI;IACF,MAAM,aAAa,MAAM,QAAQ,QAAQ,UAAU;IACnD,IAAI,cAAc,MAAM;KACtB,IAAI;KACJ,IAAI;MACF,iBAAiB,MAAM,YAAY,UAAU;KAC/C,QAAQ;MACN,MAAM,QAAQ,WAAW,UAAU;MACnC;KACF;KAEA,IAAI,kBAAkB,cAAc,GAClC,MAAM,QAAQ,WAAW,UAAU;UAC9B;MACL,IAAI,uBAEF,qBAAA,cAAc,eACZ,sBAAsB,cAAc,CACtC;MAGF,OAAO,eAAe,MAAM;KAC9B;IACF;GACF,SAAS,KAAK;IACZ,IAAI,QAAQ,IAAI,aAAa,eAAe;KAC1C,QAAQ,MAAM,GAAG;KACjB,QAAQ,KACN,iFACF;IACF;IACA,MA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Ae,cACb,UAAoD,CAAC,GACtC;EACf,MAAM,EAAE,OAAO,aAAa;EAE5B,IAAA,YAAA,QAAA,YAAA,KAAA,IAAA,KAAA,IAAI,QAAS,SAAS;GACpB,MAAM,UAAU,MAAM,QAAQ,QAAQ;GACtC,MAAM,mBAAmB,GAAG,OAAO;GACnC,KAAK,MAAM,CAAC,KAAK,UAAU,SACzB,IAAI,IAAI,WAAW,gBAAgB,GAAG;IACpC,IAAI,CAAC,UAAU;KACb,MAAM,QAAQ,WAAW,GAAG;KAC5B;IACF;IAEA,IAAI;IACJ,IAAI;KACF,iBAAiB,MAAM,YAAY,KAAK;IAC1C,QAAQ;KACN,MAAM,QAAQ,WAAW,GAAG;KAC5B;IACF;IAEA,IAAI,OACE;SAAA,eAAe,eAAA,GAAcD,qBAAAA,QAAAA,CAAQ,QAAQ,GAC/C;IAAA,OAEG,IAAI,EAAA,GAACC,qBAAAA,gBAAAA,CAAgB,eAAe,UAAU,QAAQ,GAC3D;IAGF,MAAM,QAAQ,WAAW,GAAG;GAC9B;EAEJ,OAAO,IAAI,QAAQ,IAAI,aAAa,eAClC,MAAM,IAAI,MACR,gJACF;CAEJ;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
@@ -116,7 +116,7 @@ export declare const PERSISTER_KEY_PREFIX = "tanstack-query";
116
116
  * @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,
117
117
  * restore, remove, and garbage collect persisted queries manually.
118
118
  */
119
- export declare function experimental_createQueryPersister<TStorageValue = string>({ storage, buster, maxAge, serialize, deserialize, prefix, refetchOnRestore, filters }: StoragePersisterOptions<TStorageValue>): {
119
+ export declare function experimental_createQueryPersister<TStorageValue = string>({ storage, buster, maxAge, serialize, deserialize, prefix, refetchOnRestore, filters: persistFilters }: StoragePersisterOptions<TStorageValue>): {
120
120
  persisterFn: <T, TQueryKey extends QueryKey>(queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>, ctx: QueryFunctionContext<TQueryKey>, query: Query) => Promise<T>;
121
121
  persistQuery: (query: Query) => Promise<void>;
122
122
  persistQueryByKey: (queryKey: QueryKey, queryClient: QueryClient) => Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"createPersister.d.cts","names":[],"sources":["../../src/createPersister.ts"],"mappings":";;;;;iBAkBiB;;;;EAIf;;;;EAIA;;;;EAIA,UAAU;;;;EAIV,OAAO;;;;;YAMG,aAAa,KAAK,IAAI,QAAQ;;;;;iBAMzB,aAAa;;;;EAI5B,UAAU,gBAAgB,aAAa;;;;EAIvC,UAAU,aAAa,OAAO,kBAAkB;;;;EAIhD,aAAa,gBAAgB;;;;EAI7B,gBAAgB,aAAa,OAAO,aAAa,OAAO;;;;;iBAMzC,wBAAwB;;;;;EAKvC,SAAS,aAAa;;;;;EAKtB,aAAa,gBAAgB,mBAAmB,aAAa;;;;;EAK7D,eAAe,cAAc,kBAAkB,aAAa;;;;;EAK5D;;;;;;;EAOA;;;;;;EAMA;;;;;;;EAOA;;;;EAIA,UAAU;;qBAGC;;;;;;;;;;;;;;;;;;;;wBAqBG,kCAAkC,0BAChD,SACA,QACA,QACA,WAGA,aAGA,QACA,kBACA,WACC,wBAAwB;EAgIE,cAAA,GAAG,kBAAkB,UAAQ,UAC5C,SAAS,qBAAqB,eAAe,IAAI,QAAQ,IAAE,KAChE,qBAAqB,YAAU,OAC7B,UAAK,QAAA;EA1BqB,eAAA,OAAA,UAAK;EAvB5B,oBAAA,UAAA,UAAQ,aACL,gBAAW;EApDG,gBAAA,GAAC,mBACX,yBACQ,gBAAgB,4BAAuB,QAAA;;EAmLnD,iBAAA,aAAA,aAAW,UACf,KAAK,wCACb;EAsDQ,gBAAA,UAAA,KAAK,wCACb"}
1
+ {"version":3,"file":"createPersister.d.cts","names":[],"sources":["../../src/createPersister.ts"],"mappings":";;;;;iBAkBiB;;;;EAIf;;;;EAIA;;;;EAIA,UAAU;;;;EAIV,OAAO;;;;;YAMG,aAAa,KAAK,IAAI,QAAQ;;;;;iBAMzB,aAAa;;;;EAI5B,UAAU,gBAAgB,aAAa;;;;EAIvC,UAAU,aAAa,OAAO,kBAAkB;;;;EAIhD,aAAa,gBAAgB;;;;EAI7B,gBAAgB,aAAa,OAAO,aAAa,OAAO;;;;;iBAMzC,wBAAwB;;;;;EAKvC,SAAS,aAAa;;;;;EAKtB,aAAa,gBAAgB,mBAAmB,aAAa;;;;;EAK7D,eAAe,cAAc,kBAAkB,aAAa;;;;;EAK5D;;;;;;;EAOA;;;;;;EAMA;;;;;;;EAOA;;;;EAIA,UAAU;;qBAGC;;;;;;;;;;;;;;;;;;;;wBAqBG,kCAAkC,0BAChD,SACA,QACA,QACA,WAGA,aAGA,QACA,kBACA,SAAS,kBACR,wBAAwB;EAgIE,cAAA,GAAG,kBAAkB,UAAQ,UAC5C,SAAS,qBAAqB,eAAe,IAAI,QAAQ,IAAE,KAChE,qBAAqB,YAAU,OAC7B,UAAK,QAAA;EA1BqB,eAAA,OAAA,UAAK;EAvB5B,oBAAA,UAAA,UAAQ,aACL,gBAAW;EApDG,gBAAA,GAAC,mBACX,yBACQ,gBAAgB,4BAAuB,QAAA;;EAqLnD,iBAAA,aAAA,aAAW,UACf,KAAK,wCACb;EAsDQ,gBAAA,UAAA,KAAK,wCACb"}
@@ -116,7 +116,7 @@ export declare const PERSISTER_KEY_PREFIX = "tanstack-query";
116
116
  * @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,
117
117
  * restore, remove, and garbage collect persisted queries manually.
118
118
  */
119
- export declare function experimental_createQueryPersister<TStorageValue = string>({ storage, buster, maxAge, serialize, deserialize, prefix, refetchOnRestore, filters }: StoragePersisterOptions<TStorageValue>): {
119
+ export declare function experimental_createQueryPersister<TStorageValue = string>({ storage, buster, maxAge, serialize, deserialize, prefix, refetchOnRestore, filters: persistFilters }: StoragePersisterOptions<TStorageValue>): {
120
120
  persisterFn: <T, TQueryKey extends QueryKey>(queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>, ctx: QueryFunctionContext<TQueryKey>, query: Query) => Promise<T>;
121
121
  persistQuery: (query: Query) => Promise<void>;
122
122
  persistQueryByKey: (queryKey: QueryKey, queryClient: QueryClient) => Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"createPersister.d.ts","names":[],"sources":["../../src/createPersister.ts"],"mappings":";;;;;iBAkBiB;;;;EAIf;;;;EAIA;;;;EAIA,UAAU;;;;EAIV,OAAO;;;;;YAMG,aAAa,KAAK,IAAI,QAAQ;;;;;iBAMzB,aAAa;;;;EAI5B,UAAU,gBAAgB,aAAa;;;;EAIvC,UAAU,aAAa,OAAO,kBAAkB;;;;EAIhD,aAAa,gBAAgB;;;;EAI7B,gBAAgB,aAAa,OAAO,aAAa,OAAO;;;;;iBAMzC,wBAAwB;;;;;EAKvC,SAAS,aAAa;;;;;EAKtB,aAAa,gBAAgB,mBAAmB,aAAa;;;;;EAK7D,eAAe,cAAc,kBAAkB,aAAa;;;;;EAK5D;;;;;;;EAOA;;;;;;EAMA;;;;;;;EAOA;;;;EAIA,UAAU;;qBAGC;;;;;;;;;;;;;;;;;;;;wBAqBG,kCAAkC,0BAChD,SACA,QACA,QACA,WAGA,aAGA,QACA,kBACA,WACC,wBAAwB;EAgIE,cAAA,GAAG,kBAAkB,UAAQ,UAC5C,SAAS,qBAAqB,eAAe,IAAI,QAAQ,IAAE,KAChE,qBAAqB,YAAU,OAC7B,UAAK,QAAA;EA1BqB,eAAA,OAAA,UAAK;EAvB5B,oBAAA,UAAA,UAAQ,aACL,gBAAW;EApDG,gBAAA,GAAC,mBACX,yBACQ,gBAAgB,4BAAuB,QAAA;;EAmLnD,iBAAA,aAAA,aAAW,UACf,KAAK,wCACb;EAsDQ,gBAAA,UAAA,KAAK,wCACb"}
1
+ {"version":3,"file":"createPersister.d.ts","names":[],"sources":["../../src/createPersister.ts"],"mappings":";;;;;iBAkBiB;;;;EAIf;;;;EAIA;;;;EAIA,UAAU;;;;EAIV,OAAO;;;;;YAMG,aAAa,KAAK,IAAI,QAAQ;;;;;iBAMzB,aAAa;;;;EAI5B,UAAU,gBAAgB,aAAa;;;;EAIvC,UAAU,aAAa,OAAO,kBAAkB;;;;EAIhD,aAAa,gBAAgB;;;;EAI7B,gBAAgB,aAAa,OAAO,aAAa,OAAO;;;;;iBAMzC,wBAAwB;;;;;EAKvC,SAAS,aAAa;;;;;EAKtB,aAAa,gBAAgB,mBAAmB,aAAa;;;;;EAK7D,eAAe,cAAc,kBAAkB,aAAa;;;;;EAK5D;;;;;;;EAOA;;;;;;EAMA;;;;;;;EAOA;;;;EAIA,UAAU;;qBAGC;;;;;;;;;;;;;;;;;;;;wBAqBG,kCAAkC,0BAChD,SACA,QACA,QACA,WAGA,aAGA,QACA,kBACA,SAAS,kBACR,wBAAwB;EAgIE,cAAA,GAAG,kBAAkB,UAAQ,UAC5C,SAAS,qBAAqB,eAAe,IAAI,QAAQ,IAAE,KAChE,qBAAqB,YAAU,OAC7B,UAAK,QAAA;EA1BqB,eAAA,OAAA,UAAK;EAvB5B,oBAAA,UAAA,UAAQ,aACL,gBAAW;EApDG,gBAAA,GAAC,mBACX,yBACQ,gBAAgB,4BAAuB,QAAA;;EAqLnD,iBAAA,aAAA,aAAW,UACf,KAAK,wCACb;EAsDQ,gBAAA,UAAA,KAAK,wCACb"}
@@ -20,7 +20,7 @@ const PERSISTER_KEY_PREFIX = "tanstack-query";
20
20
  * @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,
21
21
  * restore, remove, and garbage collect persisted queries manually.
22
22
  */
23
- function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e5, serialize = JSON.stringify, deserialize = JSON.parse, prefix = PERSISTER_KEY_PREFIX, refetchOnRestore = true, filters }) {
23
+ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e5, serialize = JSON.stringify, deserialize = JSON.parse, prefix = PERSISTER_KEY_PREFIX, refetchOnRestore = true, filters: persistFilters }) {
24
24
  /**
25
25
  * Checks whether a persisted query should be discarded.
26
26
  * @param persistedQuery - The persisted query to check.
@@ -110,7 +110,7 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
110
110
  * @returns A promise that resolves with the restored or fetched data.
111
111
  */
112
112
  async function persisterFn(queryFn, ctx, query) {
113
- const matchesFilter = filters ? matchQuery(filters, query) : true;
113
+ const matchesFilter = persistFilters ? matchQuery(persistFilters, query) : true;
114
114
  if (matchesFilter && query.state.data === void 0 && storage != null) {
115
115
  const restoredData = await retrieveQuery(query.queryHash, (persistedQuery) => {
116
116
  query.setState({
@@ -1 +1 @@
1
- {"version":3,"file":"createPersister.js","names":[],"sources":["../../src/createPersister.ts"],"sourcesContent":["import {\n hashKey,\n matchQuery,\n notifyManager,\n partialMatchKey,\n} from '@tanstack/query-core'\nimport type {\n Query,\n QueryClient,\n QueryFilters,\n QueryFunctionContext,\n QueryKey,\n QueryState,\n} from '@tanstack/query-core'\n\n/**\n * A single query as stored by {@link experimental_createQueryPersister}.\n */\nexport interface PersistedQuery {\n /**\n * The `buster` the query was saved with. Entries with a different `buster` are discarded.\n */\n buster: string\n /**\n * The hash of the query.\n */\n queryHash: string\n /**\n * The key of the query.\n */\n queryKey: QueryKey\n /**\n * The state of the query, including its data and when it was last updated.\n */\n state: QueryState\n}\n\n/**\n * A value, or a promise that resolves to it.\n */\nexport type MaybePromise<T> = T | Promise<T>\n\n/**\n * A key-value storage, such as `localStorage` or `AsyncStorage`, whose methods may be synchronous\n * or return promises.\n */\nexport interface AsyncStorage<TStorageValue = string> {\n /**\n * Reads the value stored under `key`, or `null`/`undefined` if there is none.\n */\n getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>\n /**\n * Stores `value` under `key`.\n */\n setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>\n /**\n * Removes the value stored under `key`.\n */\n removeItem: (key: string) => MaybePromise<void>\n /**\n * Returns all stored key-value pairs. Required for removing expired entries in bulk.\n */\n entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>\n}\n\n/**\n * Options for {@link experimental_createQueryPersister}.\n */\nexport interface StoragePersisterOptions<TStorageValue = string> {\n /**\n * The storage client used for setting and retrieving items from cache.\n * For SSR pass in `undefined`.\n */\n storage: AsyncStorage<TStorageValue> | undefined | null\n /**\n * How to serialize the data to storage.\n * @default `JSON.stringify`\n */\n serialize?: (persistedQuery: PersistedQuery) => MaybePromise<TStorageValue>\n /**\n * How to deserialize the data from storage.\n * @default `JSON.parse`\n */\n deserialize?: (cachedString: TStorageValue) => MaybePromise<PersistedQuery>\n /**\n * A unique string that can be used to forcefully invalidate existing caches,\n * if they do not share the same buster string\n */\n buster?: string\n /**\n * The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded\n * @default 24 hours\n */\n maxAge?: number\n /**\n * Prefix to be used for storage key.\n * Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.\n * @default 'tanstack-query'\n */\n prefix?: string\n /**\n * If set to `true`, the query will refetch on successful query restoration if the data is stale.\n * If set to `false`, the query will not refetch on successful query restoration.\n * If set to `'always'`, the query will always refetch on successful query restoration.\n * @defaultValue true\n */\n refetchOnRestore?: boolean | 'always'\n /**\n * Filters to narrow down which Queries should be persisted.\n */\n filters?: QueryFilters\n}\n\nexport const PERSISTER_KEY_PREFIX = 'tanstack-query'\n\n/**\n * Warning: experimental feature.\n * This utility function enables fine-grained query persistence.\n * Simple add it as a `persister` parameter to `useQuery` or `defaultOptions` on `queryClient`.\n *\n * ```\n * useQuery({\n * queryKey: ['myKey'],\n * queryFn: fetcher,\n * persister: createPersister({\n * storage: localStorage,\n * }),\n * })\n * ```\n * @param options - The storage to persist to, and the options for serializing, expiring, and\n * filtering persisted queries.\n * @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,\n * restore, remove, and garbage collect persisted queries manually.\n */\nexport function experimental_createQueryPersister<TStorageValue = string>({\n storage,\n buster = '',\n maxAge = 1000 * 60 * 60 * 24,\n serialize = JSON.stringify as Required<\n StoragePersisterOptions<TStorageValue>\n >['serialize'],\n deserialize = JSON.parse as Required<\n StoragePersisterOptions<TStorageValue>\n >['deserialize'],\n prefix = PERSISTER_KEY_PREFIX,\n refetchOnRestore = true,\n filters,\n}: StoragePersisterOptions<TStorageValue>) {\n /**\n * Checks whether a persisted query should be discarded.\n * @param persistedQuery - The persisted query to check.\n * @returns `true` if it has no `dataUpdatedAt`, is older than `maxAge`, or has a different\n * `buster`.\n */\n function isExpiredOrBusted(persistedQuery: PersistedQuery) {\n if (persistedQuery.state.dataUpdatedAt) {\n const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt\n const expired = queryAge > maxAge\n const busted = persistedQuery.buster !== buster\n\n if (expired || busted) {\n return true\n }\n\n return false\n }\n\n return true\n }\n\n /**\n * Reads the persisted data of a query from storage. Expired, busted, or unreadable entries are\n * removed instead.\n * @param queryHash - The hash of the query to read.\n * @param afterRestoreMacroTask - Scheduled with the persisted query after it is restored.\n * @returns A promise that resolves with the persisted data, or `undefined` if nothing was\n * restored.\n */\n async function retrieveQuery<T>(\n queryHash: string,\n afterRestoreMacroTask?: (persistedQuery: PersistedQuery) => void,\n ) {\n if (storage != null) {\n const storageKey = `${prefix}-${queryHash}`\n try {\n const storedData = await storage.getItem(storageKey)\n if (storedData != null) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(storedData)\n } catch {\n await storage.removeItem(storageKey)\n return\n }\n\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(storageKey)\n } else {\n if (afterRestoreMacroTask) {\n // Just after restoring we want to get fresh data from the server if it's stale\n notifyManager.schedule(() =>\n afterRestoreMacroTask(persistedQuery),\n )\n }\n // We must resolve the promise here, as otherwise we will have `loading` state in the app until `queryFn` resolves\n return persistedQuery.state.data as T\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV === 'development') {\n console.error(err)\n console.warn(\n 'Encountered an error attempting to restore query cache from persisted location.',\n )\n }\n await storage.removeItem(storageKey)\n }\n }\n\n return\n }\n\n /**\n * Persists the query with the given key, if it exists in the client's cache.\n * @param queryKey - The key of the query to persist.\n * @param queryClient - The client whose cache holds the query.\n * @returns A promise that resolves once the query is persisted.\n */\n async function persistQueryByKey(\n queryKey: QueryKey,\n queryClient: QueryClient,\n ) {\n if (storage != null) {\n const query = queryClient.getQueryCache().find({ queryKey })\n if (query) {\n await persistQuery(query)\n } else {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n 'Could not find query to be persisted. QueryKey:',\n JSON.stringify(queryKey),\n )\n }\n }\n }\n }\n\n /**\n * Writes a query's state, key, hash, and `buster` to storage.\n * @param query - The query to persist.\n * @returns A promise that resolves once the entry is serialized and written.\n */\n async function persistQuery(query: Query) {\n if (storage != null) {\n const storageKey = `${prefix}-${query.queryHash}`\n await storage.setItem(\n storageKey,\n await serialize({\n state: query.state,\n queryKey: query.queryKey,\n queryHash: query.queryHash,\n buster: buster,\n }),\n )\n }\n }\n\n /**\n * The `persister` of a query: restores its data from storage if the query has none yet, otherwise\n * runs `queryFn` and persists the result.\n * @param queryFn - The query's own query function.\n * @param ctx - The context passed to `queryFn`.\n * @param query - The query being fetched.\n * @returns A promise that resolves with the restored or fetched data.\n */\n async function persisterFn<T, TQueryKey extends QueryKey>(\n queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>,\n ctx: QueryFunctionContext<TQueryKey>,\n query: Query,\n ) {\n const matchesFilter = filters ? matchQuery(filters, query) : true\n\n // Try to restore only if we do not have any data in the cache and we have persister defined\n if (matchesFilter && query.state.data === undefined && storage != null) {\n const restoredData = await retrieveQuery(\n query.queryHash,\n (persistedQuery: PersistedQuery) => {\n // Set proper updatedAt, since resolving in the first pass overrides those values\n query.setState({\n dataUpdatedAt: persistedQuery.state.dataUpdatedAt,\n errorUpdatedAt: persistedQuery.state.errorUpdatedAt,\n })\n\n if (\n refetchOnRestore === 'always' ||\n (refetchOnRestore === true && query.isStale())\n ) {\n query.fetch()\n }\n },\n )\n\n if (restoredData !== undefined) {\n return Promise.resolve(restoredData as T)\n }\n }\n\n // If we did not restore, or restoration failed - fetch\n const queryFnResult = await queryFn(ctx)\n\n if (matchesFilter && storage != null) {\n // Persist if we have storage defined, we use timeout to get proper state to be persisted\n notifyManager.schedule(() => {\n persistQuery(query)\n })\n }\n\n return Promise.resolve(queryFnResult)\n }\n\n /**\n * Removes expired, busted, or unreadable entries from storage. Requires the storage to implement\n * `entries`.\n * @returns A promise that resolves once every entry is checked.\n */\n async function persisterGc() {\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n }\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Garbage collection is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n /**\n * Restores every persisted query matching `filters` into the client's cache with\n * `queryClient.setQueryData`. Requires the storage to implement `entries`.\n * @param queryClient - The client to restore the queries into.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * restored.\n * @returns A promise that resolves once every entry is checked.\n */\n async function restoreQueries(\n queryClient: QueryClient,\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n continue\n }\n\n if (queryKey) {\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n }\n\n queryClient.setQueryData(\n persistedQuery.queryKey,\n persistedQuery.state.data,\n {\n updatedAt: persistedQuery.state.dataUpdatedAt,\n },\n )\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Restoration of all stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n /**\n * Removes every persisted query matching `filters` from storage. Requires the storage to implement\n * `entries`.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * removed.\n * @returns A promise that resolves once every entry is checked.\n */\n async function removeQueries(\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const entries = await storage.entries()\n const storageKeyPrefix = `${prefix}-`\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n if (!queryKey) {\n await storage.removeItem(key)\n continue\n }\n\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n\n await storage.removeItem(key)\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Removal of stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n return {\n persisterFn,\n persistQuery,\n persistQueryByKey,\n retrieveQuery,\n persisterGc,\n restoreQueries,\n removeQueries,\n }\n}\n"],"mappings":";;AAmHA,MAAa,uBAAuB;;;;;;;;;;;;;;;;;;;;AAqBpC,SAAgB,kCAA0D,EACxE,SACA,SAAS,IACT,SAAS,OACT,YAAY,KAAK,WAGjB,cAAc,KAAK,OAGnB,SAAS,sBACT,mBAAmB,MACnB,WACyC;;;;;;;CAOzC,SAAS,kBAAkB,gBAAgC;EACzD,IAAI,eAAe,MAAM,eAAe;GAEtC,MAAM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AI,QAAQ,IAAI,aAAa,eAClC,MAAM,IAAI,MACR,gJACF;CAEJ;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
1
+ {"version":3,"file":"createPersister.js","names":[],"sources":["../../src/createPersister.ts"],"sourcesContent":["import {\n hashKey,\n matchQuery,\n notifyManager,\n partialMatchKey,\n} from '@tanstack/query-core'\nimport type {\n Query,\n QueryClient,\n QueryFilters,\n QueryFunctionContext,\n QueryKey,\n QueryState,\n} from '@tanstack/query-core'\n\n/**\n * A single query as stored by {@link experimental_createQueryPersister}.\n */\nexport interface PersistedQuery {\n /**\n * The `buster` the query was saved with. Entries with a different `buster` are discarded.\n */\n buster: string\n /**\n * The hash of the query.\n */\n queryHash: string\n /**\n * The key of the query.\n */\n queryKey: QueryKey\n /**\n * The state of the query, including its data and when it was last updated.\n */\n state: QueryState\n}\n\n/**\n * A value, or a promise that resolves to it.\n */\nexport type MaybePromise<T> = T | Promise<T>\n\n/**\n * A key-value storage, such as `localStorage` or `AsyncStorage`, whose methods may be synchronous\n * or return promises.\n */\nexport interface AsyncStorage<TStorageValue = string> {\n /**\n * Reads the value stored under `key`, or `null`/`undefined` if there is none.\n */\n getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>\n /**\n * Stores `value` under `key`.\n */\n setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>\n /**\n * Removes the value stored under `key`.\n */\n removeItem: (key: string) => MaybePromise<void>\n /**\n * Returns all stored key-value pairs. Required for removing expired entries in bulk.\n */\n entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>\n}\n\n/**\n * Options for {@link experimental_createQueryPersister}.\n */\nexport interface StoragePersisterOptions<TStorageValue = string> {\n /**\n * The storage client used for setting and retrieving items from cache.\n * For SSR pass in `undefined`.\n */\n storage: AsyncStorage<TStorageValue> | undefined | null\n /**\n * How to serialize the data to storage.\n * @default `JSON.stringify`\n */\n serialize?: (persistedQuery: PersistedQuery) => MaybePromise<TStorageValue>\n /**\n * How to deserialize the data from storage.\n * @default `JSON.parse`\n */\n deserialize?: (cachedString: TStorageValue) => MaybePromise<PersistedQuery>\n /**\n * A unique string that can be used to forcefully invalidate existing caches,\n * if they do not share the same buster string\n */\n buster?: string\n /**\n * The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded\n * @default 24 hours\n */\n maxAge?: number\n /**\n * Prefix to be used for storage key.\n * Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.\n * @default 'tanstack-query'\n */\n prefix?: string\n /**\n * If set to `true`, the query will refetch on successful query restoration if the data is stale.\n * If set to `false`, the query will not refetch on successful query restoration.\n * If set to `'always'`, the query will always refetch on successful query restoration.\n * @defaultValue true\n */\n refetchOnRestore?: boolean | 'always'\n /**\n * Filters to narrow down which Queries should be persisted.\n */\n filters?: QueryFilters\n}\n\nexport const PERSISTER_KEY_PREFIX = 'tanstack-query'\n\n/**\n * Warning: experimental feature.\n * This utility function enables fine-grained query persistence.\n * Simple add it as a `persister` parameter to `useQuery` or `defaultOptions` on `queryClient`.\n *\n * ```\n * useQuery({\n * queryKey: ['myKey'],\n * queryFn: fetcher,\n * persister: createPersister({\n * storage: localStorage,\n * }),\n * })\n * ```\n * @param options - The storage to persist to, and the options for serializing, expiring, and\n * filtering persisted queries.\n * @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,\n * restore, remove, and garbage collect persisted queries manually.\n */\nexport function experimental_createQueryPersister<TStorageValue = string>({\n storage,\n buster = '',\n maxAge = 24 * 60 * 60 * 1000,\n serialize = JSON.stringify as Required<\n StoragePersisterOptions<TStorageValue>\n >['serialize'],\n deserialize = JSON.parse as Required<\n StoragePersisterOptions<TStorageValue>\n >['deserialize'],\n prefix = PERSISTER_KEY_PREFIX,\n refetchOnRestore = true,\n filters: persistFilters,\n}: StoragePersisterOptions<TStorageValue>) {\n /**\n * Checks whether a persisted query should be discarded.\n * @param persistedQuery - The persisted query to check.\n * @returns `true` if it has no `dataUpdatedAt`, is older than `maxAge`, or has a different\n * `buster`.\n */\n function isExpiredOrBusted(persistedQuery: PersistedQuery) {\n if (persistedQuery.state.dataUpdatedAt) {\n const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt\n const expired = queryAge > maxAge\n const busted = persistedQuery.buster !== buster\n\n if (expired || busted) {\n return true\n }\n\n return false\n }\n\n return true\n }\n\n /**\n * Reads the persisted data of a query from storage. Expired, busted, or unreadable entries are\n * removed instead.\n * @param queryHash - The hash of the query to read.\n * @param afterRestoreMacroTask - Scheduled with the persisted query after it is restored.\n * @returns A promise that resolves with the persisted data, or `undefined` if nothing was\n * restored.\n */\n async function retrieveQuery<T>(\n queryHash: string,\n afterRestoreMacroTask?: (persistedQuery: PersistedQuery) => void,\n ) {\n if (storage != null) {\n const storageKey = `${prefix}-${queryHash}`\n try {\n const storedData = await storage.getItem(storageKey)\n if (storedData != null) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(storedData)\n } catch {\n await storage.removeItem(storageKey)\n return\n }\n\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(storageKey)\n } else {\n if (afterRestoreMacroTask) {\n // Just after restoring we want to get fresh data from the server if it's stale\n notifyManager.schedule(() =>\n afterRestoreMacroTask(persistedQuery),\n )\n }\n // We must resolve the promise here, as otherwise we will have `loading` state in the app until `queryFn` resolves\n return persistedQuery.state.data as T\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV === 'development') {\n console.error(err)\n console.warn(\n 'Encountered an error attempting to restore query cache from persisted location.',\n )\n }\n await storage.removeItem(storageKey)\n }\n }\n\n return\n }\n\n /**\n * Persists the query with the given key, if it exists in the client's cache.\n * @param queryKey - The key of the query to persist.\n * @param queryClient - The client whose cache holds the query.\n * @returns A promise that resolves once the query is persisted.\n */\n async function persistQueryByKey(\n queryKey: QueryKey,\n queryClient: QueryClient,\n ) {\n if (storage != null) {\n const query = queryClient.getQueryCache().find({ queryKey })\n if (query) {\n await persistQuery(query)\n } else {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n 'Could not find query to be persisted. QueryKey:',\n JSON.stringify(queryKey),\n )\n }\n }\n }\n }\n\n /**\n * Writes a query's state, key, hash, and `buster` to storage.\n * @param query - The query to persist.\n * @returns A promise that resolves once the entry is serialized and written.\n */\n async function persistQuery(query: Query) {\n if (storage != null) {\n const storageKey = `${prefix}-${query.queryHash}`\n await storage.setItem(\n storageKey,\n await serialize({\n state: query.state,\n queryKey: query.queryKey,\n queryHash: query.queryHash,\n buster: buster,\n }),\n )\n }\n }\n\n /**\n * The `persister` of a query: restores its data from storage if the query has none yet, otherwise\n * runs `queryFn` and persists the result.\n * @param queryFn - The query's own query function.\n * @param ctx - The context passed to `queryFn`.\n * @param query - The query being fetched.\n * @returns A promise that resolves with the restored or fetched data.\n */\n async function persisterFn<T, TQueryKey extends QueryKey>(\n queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>,\n ctx: QueryFunctionContext<TQueryKey>,\n query: Query,\n ) {\n const matchesFilter = persistFilters\n ? matchQuery(persistFilters, query)\n : true\n\n // Try to restore only if we do not have any data in the cache and we have persister defined\n if (matchesFilter && query.state.data === undefined && storage != null) {\n const restoredData = await retrieveQuery(\n query.queryHash,\n (persistedQuery: PersistedQuery) => {\n // Set proper updatedAt, since resolving in the first pass overrides those values\n query.setState({\n dataUpdatedAt: persistedQuery.state.dataUpdatedAt,\n errorUpdatedAt: persistedQuery.state.errorUpdatedAt,\n })\n\n if (\n refetchOnRestore === 'always' ||\n (refetchOnRestore === true && query.isStale())\n ) {\n query.fetch()\n }\n },\n )\n\n if (restoredData !== undefined) {\n return Promise.resolve(restoredData as T)\n }\n }\n\n // If we did not restore, or restoration failed - fetch\n const queryFnResult = await queryFn(ctx)\n\n if (matchesFilter && storage != null) {\n // Persist if we have storage defined, we use timeout to get proper state to be persisted\n notifyManager.schedule(() => {\n persistQuery(query)\n })\n }\n\n return Promise.resolve(queryFnResult)\n }\n\n /**\n * Removes expired, busted, or unreadable entries from storage. Requires the storage to implement\n * `entries`.\n * @returns A promise that resolves once every entry is checked.\n */\n async function persisterGc() {\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n }\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Garbage collection is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n /**\n * Restores every persisted query matching `filters` into the client's cache with\n * `queryClient.setQueryData`. Requires the storage to implement `entries`.\n * @param queryClient - The client to restore the queries into.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * restored.\n * @returns A promise that resolves once every entry is checked.\n */\n async function restoreQueries(\n queryClient: QueryClient,\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n continue\n }\n\n if (queryKey) {\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n }\n\n queryClient.setQueryData(\n persistedQuery.queryKey,\n persistedQuery.state.data,\n {\n updatedAt: persistedQuery.state.dataUpdatedAt,\n },\n )\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Restoration of all stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n /**\n * Removes every persisted query matching `filters` from storage. Requires the storage to implement\n * `entries`.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * removed.\n * @returns A promise that resolves once every entry is checked.\n */\n async function removeQueries(\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const entries = await storage.entries()\n const storageKeyPrefix = `${prefix}-`\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n if (!queryKey) {\n await storage.removeItem(key)\n continue\n }\n\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n\n await storage.removeItem(key)\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Removal of stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n return {\n persisterFn,\n persistQuery,\n persistQueryByKey,\n retrieveQuery,\n persisterGc,\n restoreQueries,\n removeQueries,\n }\n}\n"],"mappings":";;AAmHA,MAAa,uBAAuB;;;;;;;;;;;;;;;;;;;;AAqBpC,SAAgB,kCAA0D,EACxE,SACA,SAAS,IACT,SAAS,OACT,YAAY,KAAK,WAGjB,cAAc,KAAK,OAGnB,SAAS,sBACT,mBAAmB,MACnB,SAAS,kBACgC;;;;;;;CAOzC,SAAS,kBAAkB,gBAAgC;EACzD,IAAI,eAAe,MAAM,eAAe;GAEtC,MAAM,UADW,KAAK,IAAI,IAAI,eAAe,MAAM,gBACxB;GAC3B,MAAM,SAAS,eAAe,WAAW;GAEzC,IAAI,WAAW,QACb,OAAO;GAGT,OAAO;EACT;EAEA,OAAO;CACT;;;;;;;;;CAUA,eAAe,cACb,WACA,uBACA;EACA,IAAI,WAAW,MAAM;GACnB,MAAM,aAA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ate } from '@tanstack/query-core'\nimport type {\n DehydrateOptions,\n DehydratedState,\n HydrateOptions,\n NotifyEventType,\n QueryClient,\n} from '@tanstack/query-core'\n\n/**\n * A value, or a promise-like that resolves to it.\n */\nexport type Promisable<T> = T | PromiseLike<T>\n\n/**\n * Saves, restores, and removes a {@link PersistedClient} in a storage.\n */\nexport interface Persister {\n /**\n * Saves the persisted client to the storage.\n */\n persistClient: (persistClient: PersistedClient) => Promisable<void>\n /**\n * Reads the persisted client from the storage, or `undefined` if nothing was saved.\n */\n restoreClient: () => Promisable<PersistedClient | undefined>\n /**\n * Removes the persisted client from the storage.\n */\n removeClient: () => Promisable<void>\n}\n\n/**\n * The dehydrated state of a `QueryClient` as it is persisted, with the time it was saved and its\n * `buster`.\n */\nexport interface PersistedClient {\n /**\n * When the client was saved, in milliseconds since the epoch. Compared with `maxAge` on restore.\n */\n timestamp: number\n /**\n * The `buster` the client was saved with. A persisted client with a different `buster` is\n * discarded.\n */\n buster: string\n /**\n * The dehydrated cache of the `QueryClient`.\n */\n clientState: DehydratedState\n}\n\n/**\n * The options shared by restoring and saving a persisted `QueryClient`.\n */\nexport interface PersistQueryClientRootOptions {\n /** The QueryClient to persist */\n queryClient: QueryClient\n /**\n * The Persister interface for storing and restoring the cache\n * to/from a persisted location\n */\n persister: Persister\n /**\n * A unique string that can be used to forcefully\n * invalidate existing caches if they do not share the same buster string\n */\n buster?: string\n}\n\n/**\n * Options for restoring a persisted `QueryClient` with {@link persistQueryClientRestore}.\n */\nexport interface PersistedQueryClientRestoreOptions extends PersistQueryClientRootOptions {\n /**\n * The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded\n */\n maxAge?: number\n /** The options passed to the hydrate function */\n hydrateOptions?: HydrateOptions\n}\n\n/**\n * Options for saving a `QueryClient` with {@link persistQueryClientSave}.\n */\nexport interface PersistedQueryClientSaveOptions extends PersistQueryClientRootOptions {\n /** The options passed to the dehydrate function */\n dehydrateOptions?: DehydrateOptions\n}\n\n/**\n * Options for {@link persistQueryClient}, which both restores and saves a `QueryClient`.\n */\nexport interface PersistQueryClientOptions\n extends\n PersistedQueryClientRestoreOptions,\n PersistedQueryClientSaveOptions,\n PersistQueryClientRootOptions {}\n\nconst cacheEventTypes: Array<NotifyEventType> = ['added', 'removed', 'updated']\n\n/**\n * Checks if emitted event is about cache change and not about observers.\n * Useful for persist, where we only want to trigger save when cache is changed.\n * @param eventType - The type of the emitted event.\n * @returns `true` if the event is `'added'`, `'removed'`, or `'updated'`.\n */\nfunction isCacheEventType(eventType: NotifyEventType) {\n return cacheEventTypes.includes(eventType)\n}\n\n/**\n * Restores persisted data to the QueryCache.\n * - data obtained from persister.restoreClient.\n * - data is hydrated using hydrateOptions.\n * If data is expired, busted, empty, or throws, it runs persister.removeClient.\n * @param options - The `queryClient` to restore into, the `persister`, and the `maxAge`, `buster`,\n * and `hydrateOptions` that decide whether and how the persisted data is restored.\n * @returns A promise that resolves once the data is restored or removed. If restoring throws, it\n * attempts to remove the persisted data and then rejects with the restore error, or with the removal\n * error if the removal fails too.\n */\nexport async function persistQueryClientRestore({\n queryClient,\n persister,\n maxAge = 1000 * 60 * 60 * 24,\n buster = '',\n hydrateOptions,\n}: PersistedQueryClientRestoreOptions) {\n try {\n const persistedClient = await persister.restoreClient()\n\n if (persistedClient) {\n if (persistedClient.timestamp) {\n const expired = Date.now() - persistedClient.timestamp > maxAge\n const busted = persistedClient.buster !== buster\n if (expired || busted) {\n return persister.removeClient()\n } else {\n hydrate(queryClient, persistedClient.clientState, hydrateOptions)\n }\n } else {\n return persister.removeClient()\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(err)\n console.warn(\n 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',\n )\n }\n\n await persister.removeClient()\n\n throw err\n }\n}\n\n/**\n * Persists data from the QueryCache.\n * - data dehydrated using dehydrateOptions.\n * - data is persisted using persister.persistClient.\n * @param options - The `queryClient` to persist, the `persister`, the `buster`, and the\n * `dehydrateOptions`.\n */\nexport async function persistQueryClientSave({\n queryClient,\n persister,\n buster = '',\n dehydrateOptions,\n}: PersistedQueryClientSaveOptions) {\n const persistClient: PersistedClient = {\n buster,\n timestamp: Date.now(),\n clientState: dehydrate(queryClient, dehydrateOptions),\n }\n\n await persister.persistClient(persistClient)\n}\n\n/**\n * Subscribe to QueryCache and MutationCache updates (for persisting).\n * @param props - The `queryClient` to monitor, the `persister`, the `buster`, and the\n * `dehydrateOptions` used for each save.\n * @returns an unsubscribe function (to discontinue monitoring)\n */\nexport function persistQueryClientSubscribe(\n props: PersistedQueryClientSaveOptions,\n) {\n const unsubscribeQueryCache = props.queryClient\n .getQueryCache()\n .subscribe((event) => {\n if (isCacheEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n const unsubscribeMutationCache = props.queryClient\n .getMutationCache()\n .subscribe((event) => {\n if (isCacheEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n return () => {\n unsubscribeQueryCache()\n unsubscribeMutationCache()\n }\n}\n\n/**\n * Restores persisted data to QueryCache and persists further changes.\n * @param props - The options for both restoring and saving.\n * @returns A tuple of a function that stops persisting, and a promise that resolves once the\n * restore is done.\n */\nexport function persistQueryClient(\n props: PersistQueryClientOptions,\n): [() => void, Promise<void>] {\n let hasUnsubscribed = false\n let persistQueryClientUnsubscribe: (() => void) | undefined\n const unsubscribe = () => {\n hasUnsubscribed = true\n persistQueryClientUnsubscribe?.()\n }\n\n // Attempt restore\n const restorePromise = persistQueryClientRestore(props).then(() => {\n if (!hasUnsubscribed) {\n // Subscribe to changes in the query cache to trigger the save\n persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)\n }\n })\n\n return [unsubscribe, restorePromise]\n}\n"],"mappings":";;;AAqGA,MAAM,kBAA0C;CAAC;CAAS;CAAW;AAAS;;;;;;;AAQ9E,SAAS,iBAAiB,WAA4B;CACpD,OAAO,gBAAgB,SAAS,SAAS;AAC3C;;;;;;;;;;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A,KAAA,KAAA,8BAAgC;CAClC;CAUA,OAAO,CAAC,aAPe,0BAA0B,KAAK,CAAC,CAAC,WAAW;EACjE,IAAI,CAAC,iBAEH,gCAAgC,4BAA4B,KAAK;CAErE,CAEkC,CAAC;AACrC"}
1
+ {"version":3,"file":"persist.cjs","names":["dehydrate"],"sources":["../../src/persist.ts"],"sourcesContent":["import { dehydrate, hydrate } from '@tanstack/query-core'\nimport type {\n DehydrateOptions,\n DehydratedState,\n HydrateOptions,\n NotifyEventType,\n QueryClient,\n} from '@tanstack/query-core'\n\n/**\n * A value, or a promise-like that resolves to it.\n */\nexport type Promisable<T> = T | PromiseLike<T>\n\n/**\n * Saves, restores, and removes a {@link PersistedClient} in a storage.\n */\nexport interface Persister {\n /**\n * Saves the persisted client to the storage.\n */\n persistClient: (persistClient: PersistedClient) => Promisable<void>\n /**\n * Reads the persisted client from the storage, or `undefined` if nothing was saved.\n */\n restoreClient: () => Promisable<PersistedClient | undefined>\n /**\n * Removes the persisted client from the storage.\n */\n removeClient: () => Promisable<void>\n}\n\n/**\n * The dehydrated state of a `QueryClient` as it is persisted, with the time it was saved and its\n * `buster`.\n */\nexport interface PersistedClient {\n /**\n * When the client was saved, in milliseconds since the epoch. Compared with `maxAge` on restore.\n */\n timestamp: number\n /**\n * The `buster` the client was saved with. A persisted client with a different `buster` is\n * discarded.\n */\n buster: string\n /**\n * The dehydrated cache of the `QueryClient`.\n */\n clientState: DehydratedState\n}\n\n/**\n * The options shared by restoring and saving a persisted `QueryClient`.\n */\nexport interface PersistQueryClientRootOptions {\n /** The QueryClient to persist */\n queryClient: QueryClient\n /**\n * The Persister interface for storing and restoring the cache\n * to/from a persisted location\n */\n persister: Persister\n /**\n * A unique string that can be used to forcefully\n * invalidate existing caches if they do not share the same buster string\n */\n buster?: string\n}\n\n/**\n * Options for restoring a persisted `QueryClient` with {@link persistQueryClientRestore}.\n */\nexport interface PersistedQueryClientRestoreOptions extends PersistQueryClientRootOptions {\n /**\n * The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded\n */\n maxAge?: number\n /** The options passed to the hydrate function */\n hydrateOptions?: HydrateOptions\n}\n\n/**\n * Options for saving a `QueryClient` with {@link persistQueryClientSave}.\n */\nexport interface PersistedQueryClientSaveOptions extends PersistQueryClientRootOptions {\n /** The options passed to the dehydrate function */\n dehydrateOptions?: DehydrateOptions\n}\n\n/**\n * Options for {@link persistQueryClient}, which both restores and saves a `QueryClient`.\n */\nexport interface PersistQueryClientOptions\n extends\n PersistedQueryClientRestoreOptions,\n PersistedQueryClientSaveOptions,\n PersistQueryClientRootOptions {}\n\nconst cacheEventTypes: Array<NotifyEventType> = ['added', 'removed', 'updated']\n\n/**\n * Checks if emitted event is about cache change and not about observers.\n * Useful for persist, where we only want to trigger save when cache is changed.\n * @param eventType - The type of the emitted event.\n * @returns `true` if the event is `'added'`, `'removed'`, or `'updated'`.\n */\nfunction isCacheEventType(eventType: NotifyEventType) {\n return cacheEventTypes.includes(eventType)\n}\n\n/**\n * Restores persisted data to the QueryCache.\n * - data obtained from persister.restoreClient.\n * - data is hydrated using hydrateOptions.\n * If data is expired, busted, empty, or throws, it runs persister.removeClient.\n * @param options - The `queryClient` to restore into, the `persister`, and the `maxAge`, `buster`,\n * and `hydrateOptions` that decide whether and how the persisted data is restored.\n * @returns A promise that resolves once the data is restored or removed. If restoring throws, it\n * attempts to remove the persisted data and then rejects with the restore error, or with the removal\n * error if the removal fails too.\n */\nexport async function persistQueryClientRestore({\n queryClient,\n persister,\n maxAge = 24 * 60 * 60 * 1000,\n buster = '',\n hydrateOptions,\n}: PersistedQueryClientRestoreOptions) {\n try {\n const persistedClient = await persister.restoreClient()\n\n if (persistedClient) {\n if (persistedClient.timestamp) {\n const expired = Date.now() - persistedClient.timestamp > maxAge\n const busted = persistedClient.buster !== buster\n if (expired || busted) {\n return persister.removeClient()\n } else {\n hydrate(queryClient, persistedClient.clientState, hydrateOptions)\n }\n } else {\n return persister.removeClient()\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(err)\n console.warn(\n 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',\n )\n }\n\n await persister.removeClient()\n\n throw err\n }\n}\n\n/**\n * Persists data from the QueryCache.\n * - data dehydrated using dehydrateOptions.\n * - data is persisted using persister.persistClient.\n * @param options - The `queryClient` to persist, the `persister`, the `buster`, and the\n * `dehydrateOptions`.\n */\nexport async function persistQueryClientSave({\n queryClient,\n persister,\n buster = '',\n dehydrateOptions,\n}: PersistedQueryClientSaveOptions) {\n const persistClient: PersistedClient = {\n buster,\n timestamp: Date.now(),\n clientState: dehydrate(queryClient, dehydrateOptions),\n }\n\n await persister.persistClient(persistClient)\n}\n\n/**\n * Subscribe to QueryCache and MutationCache updates (for persisting).\n * @param props - The `queryClient` to monitor, the `persister`, the `buster`, and the\n * `dehydrateOptions` used for each save.\n * @returns an unsubscribe function (to discontinue monitoring)\n */\nexport function persistQueryClientSubscribe(\n props: PersistedQueryClientSaveOptions,\n) {\n const unsubscribeQueryCache = props.queryClient\n .getQueryCache()\n .subscribe((event) => {\n if (isCacheEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n const unsubscribeMutationCache = props.queryClient\n .getMutationCache()\n .subscribe((event) => {\n if (isCacheEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n return () => {\n unsubscribeQueryCache()\n unsubscribeMutationCache()\n }\n}\n\n/**\n * Restores persisted data to QueryCache and persists further changes.\n * @param props - The options for both restoring and saving.\n * @returns A tuple of a function that stops persisting, and a promise that resolves once the\n * restore is done.\n */\nexport function persistQueryClient(\n props: PersistQueryClientOptions,\n): [() => void, Promise<void>] {\n let hasUnsubscribed = false\n let persistQueryClientUnsubscribe: (() => void) | undefined\n const unsubscribe = () => {\n hasUnsubscribed = true\n persistQueryClientUnsubscribe?.()\n }\n\n // Attempt restore\n const restorePromise = persistQueryClientRestore(props).then(() => {\n if (!hasUnsubscribed) {\n // Subscribe to changes in the query cache to trigger the save\n persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)\n }\n })\n\n return [unsubscribe, restorePromise]\n}\n"],"mappings":";;;AAqGA,MAAM,kBAA0C;CAAC;CAAS;CAAW;AAAS;;;;;;;AAQ9E,SAAS,iBAAiB,WAA4B;CACpD,OAAO,gBAAgB,SAAS,SAAS;AAC3C;;;;;;;;;;;;AAaA,eAAsB,0BAA0B,EAC9C,aACA,WACA,SAAS,OACT,SAAS,IACT,kBACqC;CACrC,IAAI;EACF,MAAM,kBAAkB,MAAM,UAAU,cAAc;EAEtD,IAAI,iBAAiB;GACnB,IAAI,gBAAgB,WAAW;IAC7B,MAAM,UAAU,KAAK,IAAI,IAAI,gBAAgB,YAAY;IACzD,MAAM,SAAS,gBAAgB,WAAW;IAC1C,IAAI,WAAW,QACb,OAAO,UAAU,aAAa;SAE9B,CAAA,GAAA,qBAAA,QAAA,CAAQ,aAAa,gBAAgB,aAAa,cAAc;GAEpE,OACE,OAAO,UAAU,aAAa;EAElC;CACF,SAAS,KAAK;EACZ,IAAI,QAAQ,IAAI,aAAa,cAAc;GACzC,QAAQ,MAAM,GAAG;GACjB,QAAQ,KACN,0IACF;EACF;EAEA,MAAM,UAAU,aAAa;EAE7B,MAAM;CACR;AACF;;;;;;;;AASA,eAAsB,uBAAuB,EAC3C,aACA,WACA,SAAS,IACT,oBACkC;CAClC,MAAM,gBAAiC;EACrC;EACA,WAAW,KAAK,IAAI;EACpB,cAAA,GAAaA,qBAAAA,UAAAA,CAAU,aAAa,gBAAgB;CACtD;CAEA,MAAM,UAAU,cAAc,aAAa;AAC7C;;;;;;;AAQA,SAAgB,4BACd,OACA;CACA,MAAM,wBAAwB,MAAM,YACjC,cAAc,CAAC,CACf,WAAW,UAAU;EACpB,IAAI,iBAAiB,MAAM,IAAI,GAC7B,uBAAuB,KAAK;CAEhC,CAAC;CAEH,MAAM,2BAA2B,MAAM,YACpC,iBAAiB,CAAC,CAClB,WAAW,UAAU;EACpB,IAAI,iBAAiB,MAAM,IAAI,GAC7B,uBAAuB,KAAK;CAEhC,CAAC;CAEH,aAAa;EACX,sBAAsB;EACtB,yBAAyB;CAC3B;AACF;;;;;;;AAQA,SAAgB,mBACd,OAC6B;CAC7B,IAAI,kBAAkB;CACtB,IAAI;CACJ,MAAM,oBAAoB;EACxB,kBAAkB;EAClB,kCAAA,QAAA,kCAAA,KAAA,KAAA,8BAAgC;CAClC;CAUA,OAAO,CAAC,aAPe,0BAA0B,KAAK,CAAC,CAAC,WAAW;EACjE,IAAI,CAAC,iBAEH,gCAAgC,4BAA4B,KAAK;CAErE,CAEkC,CAAC;AACrC"}
@@ -1 +1 @@
1
- {"version":3,"file":"persist.js","names":[],"sources":["../../src/persist.ts"],"sourcesContent":["import { dehydrate, hydrate } from '@tanstack/query-core'\nimport type {\n DehydrateOptions,\n DehydratedState,\n HydrateOptions,\n NotifyEventType,\n QueryClient,\n} from '@tanstack/query-core'\n\n/**\n * A value, or a promise-like that resolves to it.\n */\nexport type Promisable<T> = T | PromiseLike<T>\n\n/**\n * Saves, restores, and removes a {@link PersistedClient} in a storage.\n */\nexport interface Persister {\n /**\n * Saves the persisted client to the storage.\n */\n persistClient: (persistClient: PersistedClient) => Promisable<void>\n /**\n * Reads the persisted client from the storage, or `undefined` if nothing was saved.\n */\n restoreClient: () => Promisable<PersistedClient | undefined>\n /**\n * Removes the persisted client from the storage.\n */\n removeClient: () => Promisable<void>\n}\n\n/**\n * The dehydrated state of a `QueryClient` as it is persisted, with the time it was saved and its\n * `buster`.\n */\nexport interface PersistedClient {\n /**\n * When the client was saved, in milliseconds since the epoch. Compared with `maxAge` on restore.\n */\n timestamp: number\n /**\n * The `buster` the client was saved with. A persisted client with a different `buster` is\n * discarded.\n */\n buster: string\n /**\n * The dehydrated cache of the `QueryClient`.\n */\n clientState: DehydratedState\n}\n\n/**\n * The options shared by restoring and saving a persisted `QueryClient`.\n */\nexport interface PersistQueryClientRootOptions {\n /** The QueryClient to persist */\n queryClient: QueryClient\n /**\n * The Persister interface for storing and restoring the cache\n * to/from a persisted location\n */\n persister: Persister\n /**\n * A unique string that can be used to forcefully\n * invalidate existing caches if they do not share the same buster string\n */\n buster?: string\n}\n\n/**\n * Options for restoring a persisted `QueryClient` with {@link persistQueryClientRestore}.\n */\nexport interface PersistedQueryClientRestoreOptions extends PersistQueryClientRootOptions {\n /**\n * The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded\n */\n maxAge?: number\n /** The options passed to the hydrate function */\n hydrateOptions?: HydrateOptions\n}\n\n/**\n * Options for saving a `QueryClient` with {@link persistQueryClientSave}.\n */\nexport interface PersistedQueryClientSaveOptions extends PersistQueryClientRootOptions {\n /** The options passed to the dehydrate function */\n dehydrateOptions?: DehydrateOptions\n}\n\n/**\n * Options for {@link persistQueryClient}, which both restores and saves a `QueryClient`.\n */\nexport interface PersistQueryClientOptions\n extends\n PersistedQueryClientRestoreOptions,\n PersistedQueryClientSaveOptions,\n PersistQueryClientRootOptions {}\n\nconst cacheEventTypes: Array<NotifyEventType> = ['added', 'removed', 'updated']\n\n/**\n * Checks if emitted event is about cache change and not about observers.\n * Useful for persist, where we only want to trigger save when cache is changed.\n * @param eventType - The type of the emitted event.\n * @returns `true` if the event is `'added'`, `'removed'`, or `'updated'`.\n */\nfunction isCacheEventType(eventType: NotifyEventType) {\n return cacheEventTypes.includes(eventType)\n}\n\n/**\n * Restores persisted data to the QueryCache.\n * - data obtained from persister.restoreClient.\n * - data is hydrated using hydrateOptions.\n * If data is expired, busted, empty, or throws, it runs persister.removeClient.\n * @param options - The `queryClient` to restore into, the `persister`, and the `maxAge`, `buster`,\n * and `hydrateOptions` that decide whether and how the persisted data is restored.\n * @returns A promise that resolves once the data is restored or removed. If restoring throws, it\n * attempts to remove the persisted data and then rejects with the restore error, or with the removal\n * error if the removal fails too.\n */\nexport async function persistQueryClientRestore({\n queryClient,\n persister,\n maxAge = 1000 * 60 * 60 * 24,\n buster = '',\n hydrateOptions,\n}: PersistedQueryClientRestoreOptions) {\n try {\n const persistedClient = await persister.restoreClient()\n\n if (persistedClient) {\n if (persistedClient.timestamp) {\n const expired = Date.now() - persistedClient.timestamp > maxAge\n const busted = persistedClient.buster !== buster\n if (expired || busted) {\n return persister.removeClient()\n } else {\n hydrate(queryClient, persistedClient.clientState, hydrateOptions)\n }\n } else {\n return persister.removeClient()\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(err)\n console.warn(\n 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',\n )\n }\n\n await persister.removeClient()\n\n throw err\n }\n}\n\n/**\n * Persists data from the QueryCache.\n * - data dehydrated using dehydrateOptions.\n * - data is persisted using persister.persistClient.\n * @param options - The `queryClient` to persist, the `persister`, the `buster`, and the\n * `dehydrateOptions`.\n */\nexport async function persistQueryClientSave({\n queryClient,\n persister,\n buster = '',\n dehydrateOptions,\n}: PersistedQueryClientSaveOptions) {\n const persistClient: PersistedClient = {\n buster,\n timestamp: Date.now(),\n clientState: dehydrate(queryClient, dehydrateOptions),\n }\n\n await persister.persistClient(persistClient)\n}\n\n/**\n * Subscribe to QueryCache and MutationCache updates (for persisting).\n * @param props - The `queryClient` to monitor, the `persister`, the `buster`, and the\n * `dehydrateOptions` used for each save.\n * @returns an unsubscribe function (to discontinue monitoring)\n */\nexport function persistQueryClientSubscribe(\n props: PersistedQueryClientSaveOptions,\n) {\n const unsubscribeQueryCache = props.queryClient\n .getQueryCache()\n .subscribe((event) => {\n if (isCacheEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n const unsubscribeMutationCache = props.queryClient\n .getMutationCache()\n .subscribe((event) => {\n if (isCacheEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n return () => {\n unsubscribeQueryCache()\n unsubscribeMutationCache()\n }\n}\n\n/**\n * Restores persisted data to QueryCache and persists further changes.\n * @param props - The options for both restoring and saving.\n * @returns A tuple of a function that stops persisting, and a promise that resolves once the\n * restore is done.\n */\nexport function persistQueryClient(\n props: PersistQueryClientOptions,\n): [() => void, Promise<void>] {\n let hasUnsubscribed = false\n let persistQueryClientUnsubscribe: (() => void) | undefined\n const unsubscribe = () => {\n hasUnsubscribed = true\n persistQueryClientUnsubscribe?.()\n }\n\n // Attempt restore\n const restorePromise = persistQueryClientRestore(props).then(() => {\n if (!hasUnsubscribed) {\n // Subscribe to changes in the query cache to trigger the save\n persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)\n }\n })\n\n return [unsubscribe, restorePromise]\n}\n"],"mappings":";;AAqGA,MAAM,kBAA0C;CAAC;CAAS;CAAW;AAAS;;;;;;;AAQ9E,SAAS,iBAAiB,WAA4B;CACpD,OAAO,gBAAgB,SAAS,SAAS;AAC3C;;;;;;;;;;;;AAaA,eAAsB,0BAA0B,EAC9C,aACA,WACA,SAAS,OACT,SAAS,IACT,kBACqC;CACrC,IAAI;EACF,MAAM,kBAAkB,MAAM,UAAU,cAAc;EAEtD,IAAI,iBAAiB;GACnB,IAAI,gBAAgB,WAAW;IAC7B,MAAM,UAAU,KAAK,IAAI,IAAI,gBAAgB,YAAY;IACzD,MAAM,SAAS,gBAAgB,WAAW;IAC1C,IAAI,WAAW,QACb,OAAO,UAAU,aAAa;SAE9B,QAAQ,aAAa,gBAAgB,aAAa,cAAc;GAEpE,OACE,OAAO,UAAU,aAAa;EAElC;CACF,SAAS,KAAK;EACZ,IAAI,QAAQ,IAAI,aAAa,cAAc;GACzC,QAAQ,MAAM,GAAG;GACjB,QAAQ,KACN,0IACF;EACF;EAEA,MAAM,UAAU,aAAa;EAE7B,MAAM;CACR;AACF;;;;;;;;AASA,eAAsB,uBAAuB,EAC3C,aACA,WACA,SAAS,IACT,oBACkC;CAClC,MAAM,gBAAiC;EACrC;EACA,WAAW,KAAK,IAAI;EACpB,aAAa,UAAU,aAAa,gBAAgB;CACtD;CAEA,MAAM,UAAU,cAAc,aAAa;AAC7C;;;;;;;AAQA,SAAgB,4BACd,OACA;CACA,MAAM,wBAAwB,MAAM,YACjC,cAAc,CAAC,CACf,WAAW,UAAU;EACpB,IAAI,iBAAiB,MAAM,IAAI,GAC7B,uBAAuB,KAAK;CAEhC,CAAC;CAEH,MAAM,2BAA2B,MAAM,YACpC,iBAAiB,CAAC,CAClB,WAAW,UAAU;EACpB,IAAI,iBAAiB,MAAM,IAAI,GAC7B,uBAAuB,KAAK;CAEhC,CAAC;CAEH,aAAa;EACX,sBAAsB;EACtB,yBAAyB;CAC3B;AACF;;;;;;;AAQA,SAAgB,mBACd,OAC6B;CAC7B,IAAI,kBAAkB;CACtB,IAAI;CACJ,MAAM,oBAAoB;EACxB,kBAAkB;EAClB,kCAAA,QAAA,kCAAA,KAAA,KAAA,8BAAgC;CAClC;CAUA,OAAO,CAAC,aAPe,0BAA0B,KAAK,CAAC,CAAC,WAAW;EACjE,IAAI,CAAC,iBAEH,gCAAgC,4BAA4B,KAAK;CAErE,CAEkC,CAAC;AACrC"}
1
+ {"version":3,"file":"persist.js","names":[],"sources":["../../src/persist.ts"],"sourcesContent":["import { dehydrate, hydrate } from '@tanstack/query-core'\nimport type {\n DehydrateOptions,\n DehydratedState,\n HydrateOptions,\n NotifyEventType,\n QueryClient,\n} from '@tanstack/query-core'\n\n/**\n * A value, or a promise-like that resolves to it.\n */\nexport type Promisable<T> = T | PromiseLike<T>\n\n/**\n * Saves, restores, and removes a {@link PersistedClient} in a storage.\n */\nexport interface Persister {\n /**\n * Saves the persisted client to the storage.\n */\n persistClient: (persistClient: PersistedClient) => Promisable<void>\n /**\n * Reads the persisted client from the storage, or `undefined` if nothing was saved.\n */\n restoreClient: () => Promisable<PersistedClient | undefined>\n /**\n * Removes the persisted client from the storage.\n */\n removeClient: () => Promisable<void>\n}\n\n/**\n * The dehydrated state of a `QueryClient` as it is persisted, with the time it was saved and its\n * `buster`.\n */\nexport interface PersistedClient {\n /**\n * When the client was saved, in milliseconds since the epoch. Compared with `maxAge` on restore.\n */\n timestamp: number\n /**\n * The `buster` the client was saved with. A persisted client with a different `buster` is\n * discarded.\n */\n buster: string\n /**\n * The dehydrated cache of the `QueryClient`.\n */\n clientState: DehydratedState\n}\n\n/**\n * The options shared by restoring and saving a persisted `QueryClient`.\n */\nexport interface PersistQueryClientRootOptions {\n /** The QueryClient to persist */\n queryClient: QueryClient\n /**\n * The Persister interface for storing and restoring the cache\n * to/from a persisted location\n */\n persister: Persister\n /**\n * A unique string that can be used to forcefully\n * invalidate existing caches if they do not share the same buster string\n */\n buster?: string\n}\n\n/**\n * Options for restoring a persisted `QueryClient` with {@link persistQueryClientRestore}.\n */\nexport interface PersistedQueryClientRestoreOptions extends PersistQueryClientRootOptions {\n /**\n * The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded\n */\n maxAge?: number\n /** The options passed to the hydrate function */\n hydrateOptions?: HydrateOptions\n}\n\n/**\n * Options for saving a `QueryClient` with {@link persistQueryClientSave}.\n */\nexport interface PersistedQueryClientSaveOptions extends PersistQueryClientRootOptions {\n /** The options passed to the dehydrate function */\n dehydrateOptions?: DehydrateOptions\n}\n\n/**\n * Options for {@link persistQueryClient}, which both restores and saves a `QueryClient`.\n */\nexport interface PersistQueryClientOptions\n extends\n PersistedQueryClientRestoreOptions,\n PersistedQueryClientSaveOptions,\n PersistQueryClientRootOptions {}\n\nconst cacheEventTypes: Array<NotifyEventType> = ['added', 'removed', 'updated']\n\n/**\n * Checks if emitted event is about cache change and not about observers.\n * Useful for persist, where we only want to trigger save when cache is changed.\n * @param eventType - The type of the emitted event.\n * @returns `true` if the event is `'added'`, `'removed'`, or `'updated'`.\n */\nfunction isCacheEventType(eventType: NotifyEventType) {\n return cacheEventTypes.includes(eventType)\n}\n\n/**\n * Restores persisted data to the QueryCache.\n * - data obtained from persister.restoreClient.\n * - data is hydrated using hydrateOptions.\n * If data is expired, busted, empty, or throws, it runs persister.removeClient.\n * @param options - The `queryClient` to restore into, the `persister`, and the `maxAge`, `buster`,\n * and `hydrateOptions` that decide whether and how the persisted data is restored.\n * @returns A promise that resolves once the data is restored or removed. If restoring throws, it\n * attempts to remove the persisted data and then rejects with the restore error, or with the removal\n * error if the removal fails too.\n */\nexport async function persistQueryClientRestore({\n queryClient,\n persister,\n maxAge = 24 * 60 * 60 * 1000,\n buster = '',\n hydrateOptions,\n}: PersistedQueryClientRestoreOptions) {\n try {\n const persistedClient = await persister.restoreClient()\n\n if (persistedClient) {\n if (persistedClient.timestamp) {\n const expired = Date.now() - persistedClient.timestamp > maxAge\n const busted = persistedClient.buster !== buster\n if (expired || busted) {\n return persister.removeClient()\n } else {\n hydrate(queryClient, persistedClient.clientState, hydrateOptions)\n }\n } else {\n return persister.removeClient()\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(err)\n console.warn(\n 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',\n )\n }\n\n await persister.removeClient()\n\n throw err\n }\n}\n\n/**\n * Persists data from the QueryCache.\n * - data dehydrated using dehydrateOptions.\n * - data is persisted using persister.persistClient.\n * @param options - The `queryClient` to persist, the `persister`, the `buster`, and the\n * `dehydrateOptions`.\n */\nexport async function persistQueryClientSave({\n queryClient,\n persister,\n buster = '',\n dehydrateOptions,\n}: PersistedQueryClientSaveOptions) {\n const persistClient: PersistedClient = {\n buster,\n timestamp: Date.now(),\n clientState: dehydrate(queryClient, dehydrateOptions),\n }\n\n await persister.persistClient(persistClient)\n}\n\n/**\n * Subscribe to QueryCache and MutationCache updates (for persisting).\n * @param props - The `queryClient` to monitor, the `persister`, the `buster`, and the\n * `dehydrateOptions` used for each save.\n * @returns an unsubscribe function (to discontinue monitoring)\n */\nexport function persistQueryClientSubscribe(\n props: PersistedQueryClientSaveOptions,\n) {\n const unsubscribeQueryCache = props.queryClient\n .getQueryCache()\n .subscribe((event) => {\n if (isCacheEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n const unsubscribeMutationCache = props.queryClient\n .getMutationCache()\n .subscribe((event) => {\n if (isCacheEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n return () => {\n unsubscribeQueryCache()\n unsubscribeMutationCache()\n }\n}\n\n/**\n * Restores persisted data to QueryCache and persists further changes.\n * @param props - The options for both restoring and saving.\n * @returns A tuple of a function that stops persisting, and a promise that resolves once the\n * restore is done.\n */\nexport function persistQueryClient(\n props: PersistQueryClientOptions,\n): [() => void, Promise<void>] {\n let hasUnsubscribed = false\n let persistQueryClientUnsubscribe: (() => void) | undefined\n const unsubscribe = () => {\n hasUnsubscribed = true\n persistQueryClientUnsubscribe?.()\n }\n\n // Attempt restore\n const restorePromise = persistQueryClientRestore(props).then(() => {\n if (!hasUnsubscribed) {\n // Subscribe to changes in the query cache to trigger the save\n persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)\n }\n })\n\n return [unsubscribe, restorePromise]\n}\n"],"mappings":";;AAqGA,MAAM,kBAA0C;CAAC;CAAS;CAAW;AAAS;;;;;;;AAQ9E,SAAS,iBAAiB,WAA4B;CACpD,OAAO,gBAAgB,SAAS,SAAS;AAC3C;;;;;;;;;;;;AAaA,eAAsB,0BAA0B,EAC9C,aACA,WACA,SAAS,OACT,SAAS,IACT,kBACqC;CACrC,IAAI;EACF,MAAM,kBAAkB,MAAM,UAAU,cAAc;EAEtD,IAAI,iBAAiB;GACnB,IAAI,gBAAgB,WAAW;IAC7B,MAAM,UAAU,KAAK,IAAI,IAAI,gBAAgB,YAAY;IACzD,MAAM,SAAS,gBAAgB,WAAW;IAC1C,IAAI,WAAW,QACb,OAAO,UAAU,aAAa;SAE9B,QAAQ,aAAa,gBAAgB,aAAa,cAAc;GAEpE,OACE,OAAO,UAAU,aAAa;EAElC;CACF,SAAS,KAAK;EACZ,IAAI,QAAQ,IAAI,aAAa,cAAc;GACzC,QAAQ,MAAM,GAAG;GACjB,QAAQ,KACN,0IACF;EACF;EAEA,MAAM,UAAU,aAAa;EAE7B,MAAM;CACR;AACF;;;;;;;;AASA,eAAsB,uBAAuB,EAC3C,aACA,WACA,SAAS,IACT,oBACkC;CAClC,MAAM,gBAAiC;EACrC;EACA,WAAW,KAAK,IAAI;EACpB,aAAa,UAAU,aAAa,gBAAgB;CACtD;CAEA,MAAM,UAAU,cAAc,aAAa;AAC7C;;;;;;;AAQA,SAAgB,4BACd,OACA;CACA,MAAM,wBAAwB,MAAM,YACjC,cAAc,CAAC,CACf,WAAW,UAAU;EACpB,IAAI,iBAAiB,MAAM,IAAI,GAC7B,uBAAuB,KAAK;CAEhC,CAAC;CAEH,MAAM,2BAA2B,MAAM,YACpC,iBAAiB,CAAC,CAClB,WAAW,UAAU;EACpB,IAAI,iBAAiB,MAAM,IAAI,GAC7B,uBAAuB,KAAK;CAEhC,CAAC;CAEH,aAAa;EACX,sBAAsB;EACtB,yBAAyB;CAC3B;AACF;;;;;;;AAQA,SAAgB,mBACd,OAC6B;CAC7B,IAAI,kBAAkB;CACtB,IAAI;CACJ,MAAM,oBAAoB;EACxB,kBAAkB;EAClB,kCAAA,QAAA,kCAAA,KAAA,KAAA,8BAAgC;CAClC;CAUA,OAAO,CAAC,aAPe,0BAA0B,KAAK,CAAC,CAAC,WAAW;EACjE,IAAI,CAAC,iBAEH,gCAAgC,4BAA4B,KAAK;CAErE,CAEkC,CAAC;AACrC"}
@@ -21,7 +21,7 @@ const PERSISTER_KEY_PREFIX = "tanstack-query";
21
21
  * @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,
22
22
  * restore, remove, and garbage collect persisted queries manually.
23
23
  */
24
- function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e5, serialize = JSON.stringify, deserialize = JSON.parse, prefix = PERSISTER_KEY_PREFIX, refetchOnRestore = true, filters }) {
24
+ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e5, serialize = JSON.stringify, deserialize = JSON.parse, prefix = PERSISTER_KEY_PREFIX, refetchOnRestore = true, filters: persistFilters }) {
25
25
  /**
26
26
  * Checks whether a persisted query should be discarded.
27
27
  * @param persistedQuery - The persisted query to check.
@@ -111,7 +111,7 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
111
111
  * @returns A promise that resolves with the restored or fetched data.
112
112
  */
113
113
  async function persisterFn(queryFn, ctx, query) {
114
- const matchesFilter = filters ? (0, _tanstack_query_core.matchQuery)(filters, query) : true;
114
+ const matchesFilter = persistFilters ? (0, _tanstack_query_core.matchQuery)(persistFilters, query) : true;
115
115
  if (matchesFilter && query.state.data === void 0 && storage != null) {
116
116
  const restoredData = await retrieveQuery(query.queryHash, (persistedQuery) => {
117
117
  query.setState({
@@ -1 +1 @@
1
- {"version":3,"file":"createPersister.cjs","names":["matchQuery","hashKey","partialMatchKey"],"sources":["../../src/createPersister.ts"],"sourcesContent":["import {\n hashKey,\n matchQuery,\n notifyManager,\n partialMatchKey,\n} from '@tanstack/query-core'\nimport type {\n Query,\n QueryClient,\n QueryFilters,\n QueryFunctionContext,\n QueryKey,\n QueryState,\n} from '@tanstack/query-core'\n\n/**\n * A single query as stored by {@link experimental_createQueryPersister}.\n */\nexport interface PersistedQuery {\n /**\n * The `buster` the query was saved with. Entries with a different `buster` are discarded.\n */\n buster: string\n /**\n * The hash of the query.\n */\n queryHash: string\n /**\n * The key of the query.\n */\n queryKey: QueryKey\n /**\n * The state of the query, including its data and when it was last updated.\n */\n state: QueryState\n}\n\n/**\n * A value, or a promise that resolves to it.\n */\nexport type MaybePromise<T> = T | Promise<T>\n\n/**\n * A key-value storage, such as `localStorage` or `AsyncStorage`, whose methods may be synchronous\n * or return promises.\n */\nexport interface AsyncStorage<TStorageValue = string> {\n /**\n * Reads the value stored under `key`, or `null`/`undefined` if there is none.\n */\n getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>\n /**\n * Stores `value` under `key`.\n */\n setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>\n /**\n * Removes the value stored under `key`.\n */\n removeItem: (key: string) => MaybePromise<void>\n /**\n * Returns all stored key-value pairs. Required for removing expired entries in bulk.\n */\n entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>\n}\n\n/**\n * Options for {@link experimental_createQueryPersister}.\n */\nexport interface StoragePersisterOptions<TStorageValue = string> {\n /**\n * The storage client used for setting and retrieving items from cache.\n * For SSR pass in `undefined`.\n */\n storage: AsyncStorage<TStorageValue> | undefined | null\n /**\n * How to serialize the data to storage.\n * @default `JSON.stringify`\n */\n serialize?: (persistedQuery: PersistedQuery) => MaybePromise<TStorageValue>\n /**\n * How to deserialize the data from storage.\n * @default `JSON.parse`\n */\n deserialize?: (cachedString: TStorageValue) => MaybePromise<PersistedQuery>\n /**\n * A unique string that can be used to forcefully invalidate existing caches,\n * if they do not share the same buster string\n */\n buster?: string\n /**\n * The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded\n * @default 24 hours\n */\n maxAge?: number\n /**\n * Prefix to be used for storage key.\n * Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.\n * @default 'tanstack-query'\n */\n prefix?: string\n /**\n * If set to `true`, the query will refetch on successful query restoration if the data is stale.\n * If set to `false`, the query will not refetch on successful query restoration.\n * If set to `'always'`, the query will always refetch on successful query restoration.\n * @defaultValue true\n */\n refetchOnRestore?: boolean | 'always'\n /**\n * Filters to narrow down which Queries should be persisted.\n */\n filters?: QueryFilters\n}\n\nexport const PERSISTER_KEY_PREFIX = 'tanstack-query'\n\n/**\n * Warning: experimental feature.\n * This utility function enables fine-grained query persistence.\n * Simple add it as a `persister` parameter to `useQuery` or `defaultOptions` on `queryClient`.\n *\n * ```\n * useQuery({\n * queryKey: ['myKey'],\n * queryFn: fetcher,\n * persister: createPersister({\n * storage: localStorage,\n * }),\n * })\n * ```\n * @param options - The storage to persist to, and the options for serializing, expiring, and\n * filtering persisted queries.\n * @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,\n * restore, remove, and garbage collect persisted queries manually.\n */\nexport function experimental_createQueryPersister<TStorageValue = string>({\n storage,\n buster = '',\n maxAge = 1000 * 60 * 60 * 24,\n serialize = JSON.stringify as Required<\n StoragePersisterOptions<TStorageValue>\n >['serialize'],\n deserialize = JSON.parse as Required<\n StoragePersisterOptions<TStorageValue>\n >['deserialize'],\n prefix = PERSISTER_KEY_PREFIX,\n refetchOnRestore = true,\n filters,\n}: StoragePersisterOptions<TStorageValue>) {\n /**\n * Checks whether a persisted query should be discarded.\n * @param persistedQuery - The persisted query to check.\n * @returns `true` if it has no `dataUpdatedAt`, is older than `maxAge`, or has a different\n * `buster`.\n */\n function isExpiredOrBusted(persistedQuery: PersistedQuery) {\n if (persistedQuery.state.dataUpdatedAt) {\n const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt\n const expired = queryAge > maxAge\n const busted = persistedQuery.buster !== buster\n\n if (expired || busted) {\n return true\n }\n\n return false\n }\n\n return true\n }\n\n /**\n * Reads the persisted data of a query from storage. Expired, busted, or unreadable entries are\n * removed instead.\n * @param queryHash - The hash of the query to read.\n * @param afterRestoreMacroTask - Scheduled with the persisted query after it is restored.\n * @returns A promise that resolves with the persisted data, or `undefined` if nothing was\n * restored.\n */\n async function retrieveQuery<T>(\n queryHash: string,\n afterRestoreMacroTask?: (persistedQuery: PersistedQuery) => void,\n ) {\n if (storage != null) {\n const storageKey = `${prefix}-${queryHash}`\n try {\n const storedData = await storage.getItem(storageKey)\n if (storedData != null) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(storedData)\n } catch {\n await storage.removeItem(storageKey)\n return\n }\n\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(storageKey)\n } else {\n if (afterRestoreMacroTask) {\n // Just after restoring we want to get fresh data from the server if it's stale\n notifyManager.schedule(() =>\n afterRestoreMacroTask(persistedQuery),\n )\n }\n // We must resolve the promise here, as otherwise we will have `loading` state in the app until `queryFn` resolves\n return persistedQuery.state.data as T\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV === 'development') {\n console.error(err)\n console.warn(\n 'Encountered an error attempting to restore query cache from persisted location.',\n )\n }\n await storage.removeItem(storageKey)\n }\n }\n\n return\n }\n\n /**\n * Persists the query with the given key, if it exists in the client's cache.\n * @param queryKey - The key of the query to persist.\n * @param queryClient - The client whose cache holds the query.\n * @returns A promise that resolves once the query is persisted.\n */\n async function persistQueryByKey(\n queryKey: QueryKey,\n queryClient: QueryClient,\n ) {\n if (storage != null) {\n const query = queryClient.getQueryCache().find({ queryKey })\n if (query) {\n await persistQuery(query)\n } else {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n 'Could not find query to be persisted. QueryKey:',\n JSON.stringify(queryKey),\n )\n }\n }\n }\n }\n\n /**\n * Writes a query's state, key, hash, and `buster` to storage.\n * @param query - The query to persist.\n * @returns A promise that resolves once the entry is serialized and written.\n */\n async function persistQuery(query: Query) {\n if (storage != null) {\n const storageKey = `${prefix}-${query.queryHash}`\n await storage.setItem(\n storageKey,\n await serialize({\n state: query.state,\n queryKey: query.queryKey,\n queryHash: query.queryHash,\n buster: buster,\n }),\n )\n }\n }\n\n /**\n * The `persister` of a query: restores its data from storage if the query has none yet, otherwise\n * runs `queryFn` and persists the result.\n * @param queryFn - The query's own query function.\n * @param ctx - The context passed to `queryFn`.\n * @param query - The query being fetched.\n * @returns A promise that resolves with the restored or fetched data.\n */\n async function persisterFn<T, TQueryKey extends QueryKey>(\n queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>,\n ctx: QueryFunctionContext<TQueryKey>,\n query: Query,\n ) {\n const matchesFilter = filters ? matchQuery(filters, query) : true\n\n // Try to restore only if we do not have any data in the cache and we have persister defined\n if (matchesFilter && query.state.data === undefined && storage != null) {\n const restoredData = await retrieveQuery(\n query.queryHash,\n (persistedQuery: PersistedQuery) => {\n // Set proper updatedAt, since resolving in the first pass overrides those values\n query.setState({\n dataUpdatedAt: persistedQuery.state.dataUpdatedAt,\n errorUpdatedAt: persistedQuery.state.errorUpdatedAt,\n })\n\n if (\n refetchOnRestore === 'always' ||\n (refetchOnRestore === true && query.isStale())\n ) {\n query.fetch()\n }\n },\n )\n\n if (restoredData !== undefined) {\n return Promise.resolve(restoredData as T)\n }\n }\n\n // If we did not restore, or restoration failed - fetch\n const queryFnResult = await queryFn(ctx)\n\n if (matchesFilter && storage != null) {\n // Persist if we have storage defined, we use timeout to get proper state to be persisted\n notifyManager.schedule(() => {\n persistQuery(query)\n })\n }\n\n return Promise.resolve(queryFnResult)\n }\n\n /**\n * Removes expired, busted, or unreadable entries from storage. Requires the storage to implement\n * `entries`.\n * @returns A promise that resolves once every entry is checked.\n */\n async function persisterGc() {\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n }\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Garbage collection is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n /**\n * Restores every persisted query matching `filters` into the client's cache with\n * `queryClient.setQueryData`. Requires the storage to implement `entries`.\n * @param queryClient - The client to restore the queries into.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * restored.\n * @returns A promise that resolves once every entry is checked.\n */\n async function restoreQueries(\n queryClient: QueryClient,\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n continue\n }\n\n if (queryKey) {\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n }\n\n queryClient.setQueryData(\n persistedQuery.queryKey,\n persistedQuery.state.data,\n {\n updatedAt: persistedQuery.state.dataUpdatedAt,\n },\n )\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Restoration of all stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n /**\n * Removes every persisted query matching `filters` from storage. Requires the storage to implement\n * `entries`.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * removed.\n * @returns A promise that resolves once every entry is checked.\n */\n async function removeQueries(\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const entries = await storage.entries()\n const storageKeyPrefix = `${prefix}-`\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n if (!queryKey) {\n await storage.removeItem(key)\n continue\n }\n\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n\n await storage.removeItem(key)\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Removal of stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n return {\n persisterFn,\n persistQuery,\n persistQueryByKey,\n retrieveQuery,\n persisterGc,\n restoreQueries,\n removeQueries,\n }\n}\n"],"mappings":";;;AAmHA,MAAa,uBAAuB;;;;;;;;;;;;;;;;;;;;AAqBpC,SAAgB,kCAA0D,EACxE,SACA,SAAS,IACT,SAAS,OACT,YAAY,KAAK,WAGjB,cAAc,KAAK,OAGnB,SAAS,sBACT,mBAAmB,MACnB,WACyC;;;;;;;CAOzC,SAAS,kBAAkB,gBAAgC;EACzD,IAAI,eAAe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G;GAC9B;EAEJ,OAAO,IAAI,QAAQ,IAAI,aAAa,eAClC,MAAM,IAAI,MACR,gJACF;CAEJ;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
1
+ {"version":3,"file":"createPersister.cjs","names":["matchQuery","hashKey","partialMatchKey"],"sources":["../../src/createPersister.ts"],"sourcesContent":["import {\n hashKey,\n matchQuery,\n notifyManager,\n partialMatchKey,\n} from '@tanstack/query-core'\nimport type {\n Query,\n QueryClient,\n QueryFilters,\n QueryFunctionContext,\n QueryKey,\n QueryState,\n} from '@tanstack/query-core'\n\n/**\n * A single query as stored by {@link experimental_createQueryPersister}.\n */\nexport interface PersistedQuery {\n /**\n * The `buster` the query was saved with. Entries with a different `buster` are discarded.\n */\n buster: string\n /**\n * The hash of the query.\n */\n queryHash: string\n /**\n * The key of the query.\n */\n queryKey: QueryKey\n /**\n * The state of the query, including its data and when it was last updated.\n */\n state: QueryState\n}\n\n/**\n * A value, or a promise that resolves to it.\n */\nexport type MaybePromise<T> = T | Promise<T>\n\n/**\n * A key-value storage, such as `localStorage` or `AsyncStorage`, whose methods may be synchronous\n * or return promises.\n */\nexport interface AsyncStorage<TStorageValue = string> {\n /**\n * Reads the value stored under `key`, or `null`/`undefined` if there is none.\n */\n getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>\n /**\n * Stores `value` under `key`.\n */\n setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>\n /**\n * Removes the value stored under `key`.\n */\n removeItem: (key: string) => MaybePromise<void>\n /**\n * Returns all stored key-value pairs. Required for removing expired entries in bulk.\n */\n entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>\n}\n\n/**\n * Options for {@link experimental_createQueryPersister}.\n */\nexport interface StoragePersisterOptions<TStorageValue = string> {\n /**\n * The storage client used for setting and retrieving items from cache.\n * For SSR pass in `undefined`.\n */\n storage: AsyncStorage<TStorageValue> | undefined | null\n /**\n * How to serialize the data to storage.\n * @default `JSON.stringify`\n */\n serialize?: (persistedQuery: PersistedQuery) => MaybePromise<TStorageValue>\n /**\n * How to deserialize the data from storage.\n * @default `JSON.parse`\n */\n deserialize?: (cachedString: TStorageValue) => MaybePromise<PersistedQuery>\n /**\n * A unique string that can be used to forcefully invalidate existing caches,\n * if they do not share the same buster string\n */\n buster?: string\n /**\n * The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded\n * @default 24 hours\n */\n maxAge?: number\n /**\n * Prefix to be used for storage key.\n * Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.\n * @default 'tanstack-query'\n */\n prefix?: string\n /**\n * If set to `true`, the query will refetch on successful query restoration if the data is stale.\n * If set to `false`, the query will not refetch on successful query restoration.\n * If set to `'always'`, the query will always refetch on successful query restoration.\n * @defaultValue true\n */\n refetchOnRestore?: boolean | 'always'\n /**\n * Filters to narrow down which Queries should be persisted.\n */\n filters?: QueryFilters\n}\n\nexport const PERSISTER_KEY_PREFIX = 'tanstack-query'\n\n/**\n * Warning: experimental feature.\n * This utility function enables fine-grained query persistence.\n * Simple add it as a `persister` parameter to `useQuery` or `defaultOptions` on `queryClient`.\n *\n * ```\n * useQuery({\n * queryKey: ['myKey'],\n * queryFn: fetcher,\n * persister: createPersister({\n * storage: localStorage,\n * }),\n * })\n * ```\n * @param options - The storage to persist to, and the options for serializing, expiring, and\n * filtering persisted queries.\n * @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,\n * restore, remove, and garbage collect persisted queries manually.\n */\nexport function experimental_createQueryPersister<TStorageValue = string>({\n storage,\n buster = '',\n maxAge = 24 * 60 * 60 * 1000,\n serialize = JSON.stringify as Required<\n StoragePersisterOptions<TStorageValue>\n >['serialize'],\n deserialize = JSON.parse as Required<\n StoragePersisterOptions<TStorageValue>\n >['deserialize'],\n prefix = PERSISTER_KEY_PREFIX,\n refetchOnRestore = true,\n filters: persistFilters,\n}: StoragePersisterOptions<TStorageValue>) {\n /**\n * Checks whether a persisted query should be discarded.\n * @param persistedQuery - The persisted query to check.\n * @returns `true` if it has no `dataUpdatedAt`, is older than `maxAge`, or has a different\n * `buster`.\n */\n function isExpiredOrBusted(persistedQuery: PersistedQuery) {\n if (persistedQuery.state.dataUpdatedAt) {\n const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt\n const expired = queryAge > maxAge\n const busted = persistedQuery.buster !== buster\n\n if (expired || busted) {\n return true\n }\n\n return false\n }\n\n return true\n }\n\n /**\n * Reads the persisted data of a query from storage. Expired, busted, or unreadable entries are\n * removed instead.\n * @param queryHash - The hash of the query to read.\n * @param afterRestoreMacroTask - Scheduled with the persisted query after it is restored.\n * @returns A promise that resolves with the persisted data, or `undefined` if nothing was\n * restored.\n */\n async function retrieveQuery<T>(\n queryHash: string,\n afterRestoreMacroTask?: (persistedQuery: PersistedQuery) => void,\n ) {\n if (storage != null) {\n const storageKey = `${prefix}-${queryHash}`\n try {\n const storedData = await storage.getItem(storageKey)\n if (storedData != null) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(storedData)\n } catch {\n await storage.removeItem(storageKey)\n return\n }\n\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(storageKey)\n } else {\n if (afterRestoreMacroTask) {\n // Just after restoring we want to get fresh data from the server if it's stale\n notifyManager.schedule(() =>\n afterRestoreMacroTask(persistedQuery),\n )\n }\n // We must resolve the promise here, as otherwise we will have `loading` state in the app until `queryFn` resolves\n return persistedQuery.state.data as T\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV === 'development') {\n console.error(err)\n console.warn(\n 'Encountered an error attempting to restore query cache from persisted location.',\n )\n }\n await storage.removeItem(storageKey)\n }\n }\n\n return\n }\n\n /**\n * Persists the query with the given key, if it exists in the client's cache.\n * @param queryKey - The key of the query to persist.\n * @param queryClient - The client whose cache holds the query.\n * @returns A promise that resolves once the query is persisted.\n */\n async function persistQueryByKey(\n queryKey: QueryKey,\n queryClient: QueryClient,\n ) {\n if (storage != null) {\n const query = queryClient.getQueryCache().find({ queryKey })\n if (query) {\n await persistQuery(query)\n } else {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n 'Could not find query to be persisted. QueryKey:',\n JSON.stringify(queryKey),\n )\n }\n }\n }\n }\n\n /**\n * Writes a query's state, key, hash, and `buster` to storage.\n * @param query - The query to persist.\n * @returns A promise that resolves once the entry is serialized and written.\n */\n async function persistQuery(query: Query) {\n if (storage != null) {\n const storageKey = `${prefix}-${query.queryHash}`\n await storage.setItem(\n storageKey,\n await serialize({\n state: query.state,\n queryKey: query.queryKey,\n queryHash: query.queryHash,\n buster: buster,\n }),\n )\n }\n }\n\n /**\n * The `persister` of a query: restores its data from storage if the query has none yet, otherwise\n * runs `queryFn` and persists the result.\n * @param queryFn - The query's own query function.\n * @param ctx - The context passed to `queryFn`.\n * @param query - The query being fetched.\n * @returns A promise that resolves with the restored or fetched data.\n */\n async function persisterFn<T, TQueryKey extends QueryKey>(\n queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>,\n ctx: QueryFunctionContext<TQueryKey>,\n query: Query,\n ) {\n const matchesFilter = persistFilters\n ? matchQuery(persistFilters, query)\n : true\n\n // Try to restore only if we do not have any data in the cache and we have persister defined\n if (matchesFilter && query.state.data === undefined && storage != null) {\n const restoredData = await retrieveQuery(\n query.queryHash,\n (persistedQuery: PersistedQuery) => {\n // Set proper updatedAt, since resolving in the first pass overrides those values\n query.setState({\n dataUpdatedAt: persistedQuery.state.dataUpdatedAt,\n errorUpdatedAt: persistedQuery.state.errorUpdatedAt,\n })\n\n if (\n refetchOnRestore === 'always' ||\n (refetchOnRestore === true && query.isStale())\n ) {\n query.fetch()\n }\n },\n )\n\n if (restoredData !== undefined) {\n return Promise.resolve(restoredData as T)\n }\n }\n\n // If we did not restore, or restoration failed - fetch\n const queryFnResult = await queryFn(ctx)\n\n if (matchesFilter && storage != null) {\n // Persist if we have storage defined, we use timeout to get proper state to be persisted\n notifyManager.schedule(() => {\n persistQuery(query)\n })\n }\n\n return Promise.resolve(queryFnResult)\n }\n\n /**\n * Removes expired, busted, or unreadable entries from storage. Requires the storage to implement\n * `entries`.\n * @returns A promise that resolves once every entry is checked.\n */\n async function persisterGc() {\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n }\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Garbage collection is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n /**\n * Restores every persisted query matching `filters` into the client's cache with\n * `queryClient.setQueryData`. Requires the storage to implement `entries`.\n * @param queryClient - The client to restore the queries into.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * restored.\n * @returns A promise that resolves once every entry is checked.\n */\n async function restoreQueries(\n queryClient: QueryClient,\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n continue\n }\n\n if (queryKey) {\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n }\n\n queryClient.setQueryData(\n persistedQuery.queryKey,\n persistedQuery.state.data,\n {\n updatedAt: persistedQuery.state.dataUpdatedAt,\n },\n )\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Restoration of all stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n /**\n * Removes every persisted query matching `filters` from storage. Requires the storage to implement\n * `entries`.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * removed.\n * @returns A promise that resolves once every entry is checked.\n */\n async function removeQueries(\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const entries = await storage.entries()\n const storageKeyPrefix = `${prefix}-`\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n if (!queryKey) {\n await storage.removeItem(key)\n continue\n }\n\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n\n await storage.removeItem(key)\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Removal of stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n return {\n persisterFn,\n persistQuery,\n persistQueryByKey,\n retrieveQuery,\n persisterGc,\n restoreQueries,\n removeQueries,\n }\n}\n"],"mappings":";;;AAmHA,MAAa,uBAAuB;;;;;;;;;;;;;;;;;;;;AAqBpC,SAAgB,kCAA0D,EACxE,SACA,SAAS,IACT,SAAS,OACT,YAAY,KAAK,WAGjB,cAAc,KAAK,OAGnB,SAAS,sBACT,mBAAmB,MACnB,SAAS,kBACgC;;;;;;;CAOzC,SAAS,kBAAkB,gBAAgC;EACzD,IAAI,eAAe,MAAM,eAAe;GAEtC,MAAM,UADW,KAAK,IAAI,IAAI,eAAe,MAAM,gBACxB;GAC3B,MAAM,SAAS,eAAe,WAAW;GAEzC,IAAI,WAAW,QACb,OAAO;GAGT,OAAO;EACT;EAEA,OAAO;CACT;;;;;;;;;CAUA,eAAe,cAC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X = "tanstack-query";
116
116
  * @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,
117
117
  * restore, remove, and garbage collect persisted queries manually.
118
118
  */
119
- export declare function experimental_createQueryPersister<TStorageValue = string>({ storage, buster, maxAge, serialize, deserialize, prefix, refetchOnRestore, filters }: StoragePersisterOptions<TStorageValue>): {
119
+ export declare function experimental_createQueryPersister<TStorageValue = string>({ storage, buster, maxAge, serialize, deserialize, prefix, refetchOnRestore, filters: persistFilters }: StoragePersisterOptions<TStorageValue>): {
120
120
  persisterFn: <T, TQueryKey extends QueryKey>(queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>, ctx: QueryFunctionContext<TQueryKey>, query: Query) => Promise<T>;
121
121
  persistQuery: (query: Query) => Promise<void>;
122
122
  persistQueryByKey: (queryKey: QueryKey, queryClient: QueryClient) => Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"createPersister.d.cts","names":[],"sources":["../../src/createPersister.ts"],"mappings":";;;;;iBAkBiB;;;;EAIf;;;;EAIA;;;;EAIA,UAAU;;;;EAIV,OAAO;;;;;YAMG,aAAa,KAAK,IAAI,QAAQ;;;;;iBAMzB,aAAa;;;;EAI5B,UAAU,gBAAgB,aAAa;;;;EAIvC,UAAU,aAAa,OAAO,kBAAkB;;;;EAIhD,aAAa,gBAAgB;;;;EAI7B,gBAAgB,aAAa,OAAO,aAAa,OAAO;;;;;iBAMzC,wBAAwB;;;;;EAKvC,SAAS,aAAa;;;;;EAKtB,aAAa,gBAAgB,mBAAmB,aAAa;;;;;EAK7D,eAAe,cAAc,kBAAkB,aAAa;;;;;EAK5D;;;;;;;EAOA;;;;;;EAMA;;;;;;;EAOA;;;;EAIA,UAAU;;qBAGC;;;;;;;;;;;;;;;;;;;;wBAqBG,kCAAkC,0BAChD,SACA,QACA,QACA,WAGA,aAGA,QACA,kBACA,WACC,wBAAwB;EAgIE,cAAA,GAAG,kBAAkB,UAAQ,UAC5C,SAAS,qBAAqB,eAAe,IAAI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const PERSISTER_KEY_PREFIX = "tanstack-query";
116
116
  * @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,
117
117
  * restore, remove, and garbage collect persisted queries manually.
118
118
  */
119
- export declare function experimental_createQueryPersister<TStorageValue = string>({ storage, buster, maxAge, serialize, deserialize, prefix, refetchOnRestore, filters }: StoragePersisterOptions<TStorageValue>): {
119
+ export declare function experimental_createQueryPersister<TStorageValue = string>({ storage, buster, maxAge, serialize, deserialize, prefix, refetchOnRestore, filters: persistFilters }: StoragePersisterOptions<TStorageValue>): {
120
120
  persisterFn: <T, TQueryKey extends QueryKey>(queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>, ctx: QueryFunctionContext<TQueryKey>, query: Query) => Promise<T>;
121
121
  persistQuery: (query: Query) => Promise<void>;
122
122
  persistQueryByKey: (queryKey: QueryKey, queryClient: QueryClient) => Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"createPersister.d.ts","names":[],"sources":["../../src/createPersister.ts"],"mappings":";;;;;iBAkBiB;;;;EAIf;;;;EAIA;;;;EAIA,UAAU;;;;EAIV,OAAO;;;;;YAMG,aAAa,KAAK,IAAI,QAAQ;;;;;iBAMzB,aAAa;;;;EAI5B,UAAU,gBAAgB,aAAa;;;;EAIvC,UAAU,aAAa,OAAO,kBAAkB;;;;EAIhD,aAAa,gBAAgB;;;;EAI7B,gBAAgB,aAAa,OAAO,aAAa,OAAO;;;;;iBAMzC,wBAAwB;;;;;EAKvC,SAAS,aAAa;;;;;EAKtB,aAAa,gBAAgB,mBAAmB,aAAa;;;;;EAK7D,eAAe,cAAc,kBAAkB,aAAa;;;;;EAK5D;;;;;;;EAOA;;;;;;EAMA;;;;;;;EAOA;;;;EAIA,UAAU;;qBAGC;;;;;;;;;;;;;;;;;;;;wBAqBG,kCAAkC,0BAChD,SACA,QACA,QACA,WAGA,aAGA,QACA,kBACA,WACC,wBAAwB;EAgIE,cAAA,GAAG,kBAAkB,UAAQ,UAC5C,SAAS,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-20,7 +20,7 @@ const PERSISTER_KEY_PREFIX = "tanstack-query";
20
20
  * @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,
21
21
  * restore, remove, and garbage collect persisted queries manually.
22
22
  */
23
- function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e5, serialize = JSON.stringify, deserialize = JSON.parse, prefix = PERSISTER_KEY_PREFIX, refetchOnRestore = true, filters }) {
23
+ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e5, serialize = JSON.stringify, deserialize = JSON.parse, prefix = PERSISTER_KEY_PREFIX, refetchOnRestore = true, filters: persistFilters }) {
24
24
  /**
25
25
  * Checks whether a persisted query should be discarded.
26
26
  * @param persistedQuery - The persisted query to check.
@@ -110,7 +110,7 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
110
110
  * @returns A promise that resolves with the restored or fetched data.
111
111
  */
112
112
  async function persisterFn(queryFn, ctx, query) {
113
- const matchesFilter = filters ? matchQuery(filters, query) : true;
113
+ const matchesFilter = persistFilters ? matchQuery(persistFilters, query) : true;
114
114
  if (matchesFilter && query.state.data === void 0 && storage != null) {
115
115
  const restoredData = await retrieveQuery(query.queryHash, (persistedQuery) => {
116
116
  query.setState({
@@ -1 +1 @@
1
- {"version":3,"file":"createPersister.js","names":[],"sources":["../../src/createPersister.ts"],"sourcesContent":["import {\n hashKey,\n matchQuery,\n notifyManager,\n partialMatchKey,\n} from '@tanstack/query-core'\nimport type {\n Query,\n QueryClient,\n QueryFilters,\n QueryFunctionContext,\n QueryKey,\n QueryState,\n} from '@tanstack/query-core'\n\n/**\n * A single query as stored by {@link experimental_createQueryPersister}.\n */\nexport interface PersistedQuery {\n /**\n * The `buster` the query was saved with. Entries with a different `buster` are discarded.\n */\n buster: string\n /**\n * The hash of the query.\n */\n queryHash: string\n /**\n * The key of the query.\n */\n queryKey: QueryKey\n /**\n * The state of the query, including its data and when it was last updated.\n */\n state: QueryState\n}\n\n/**\n * A value, or a promise that resolves to it.\n */\nexport type MaybePromise<T> = T | Promise<T>\n\n/**\n * A key-value storage, such as `localStorage` or `AsyncStorage`, whose methods may be synchronous\n * or return promises.\n */\nexport interface AsyncStorage<TStorageValue = string> {\n /**\n * Reads the value stored under `key`, or `null`/`undefined` if there is none.\n */\n getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>\n /**\n * Stores `value` under `key`.\n */\n setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>\n /**\n * Removes the value stored under `key`.\n */\n removeItem: (key: string) => MaybePromise<void>\n /**\n * Returns all stored key-value pairs. Required for removing expired entries in bulk.\n */\n entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>\n}\n\n/**\n * Options for {@link experimental_createQueryPersister}.\n */\nexport interface StoragePersisterOptions<TStorageValue = string> {\n /**\n * The storage client used for setting and retrieving items from cache.\n * For SSR pass in `undefined`.\n */\n storage: AsyncStorage<TStorageValue> | undefined | null\n /**\n * How to serialize the data to storage.\n * @default `JSON.stringify`\n */\n serialize?: (persistedQuery: PersistedQuery) => MaybePromise<TStorageValue>\n /**\n * How to deserialize the data from storage.\n * @default `JSON.parse`\n */\n deserialize?: (cachedString: TStorageValue) => MaybePromise<PersistedQuery>\n /**\n * A unique string that can be used to forcefully invalidate existing caches,\n * if they do not share the same buster string\n */\n buster?: string\n /**\n * The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded\n * @default 24 hours\n */\n maxAge?: number\n /**\n * Prefix to be used for storage key.\n * Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.\n * @default 'tanstack-query'\n */\n prefix?: string\n /**\n * If set to `true`, the query will refetch on successful query restoration if the data is stale.\n * If set to `false`, the query will not refetch on successful query restoration.\n * If set to `'always'`, the query will always refetch on successful query restoration.\n * @defaultValue true\n */\n refetchOnRestore?: boolean | 'always'\n /**\n * Filters to narrow down which Queries should be persisted.\n */\n filters?: QueryFilters\n}\n\nexport const PERSISTER_KEY_PREFIX = 'tanstack-query'\n\n/**\n * Warning: experimental feature.\n * This utility function enables fine-grained query persistence.\n * Simple add it as a `persister` parameter to `useQuery` or `defaultOptions` on `queryClient`.\n *\n * ```\n * useQuery({\n * queryKey: ['myKey'],\n * queryFn: fetcher,\n * persister: createPersister({\n * storage: localStorage,\n * }),\n * })\n * ```\n * @param options - The storage to persist to, and the options for serializing, expiring, and\n * filtering persisted queries.\n * @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,\n * restore, remove, and garbage collect persisted queries manually.\n */\nexport function experimental_createQueryPersister<TStorageValue = string>({\n storage,\n buster = '',\n maxAge = 1000 * 60 * 60 * 24,\n serialize = JSON.stringify as Required<\n StoragePersisterOptions<TStorageValue>\n >['serialize'],\n deserialize = JSON.parse as Required<\n StoragePersisterOptions<TStorageValue>\n >['deserialize'],\n prefix = PERSISTER_KEY_PREFIX,\n refetchOnRestore = true,\n filters,\n}: StoragePersisterOptions<TStorageValue>) {\n /**\n * Checks whether a persisted query should be discarded.\n * @param persistedQuery - The persisted query to check.\n * @returns `true` if it has no `dataUpdatedAt`, is older than `maxAge`, or has a different\n * `buster`.\n */\n function isExpiredOrBusted(persistedQuery: PersistedQuery) {\n if (persistedQuery.state.dataUpdatedAt) {\n const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt\n const expired = queryAge > maxAge\n const busted = persistedQuery.buster !== buster\n\n if (expired || busted) {\n return true\n }\n\n return false\n }\n\n return true\n }\n\n /**\n * Reads the persisted data of a query from storage. Expired, busted, or unreadable entries are\n * removed instead.\n * @param queryHash - The hash of the query to read.\n * @param afterRestoreMacroTask - Scheduled with the persisted query after it is restored.\n * @returns A promise that resolves with the persisted data, or `undefined` if nothing was\n * restored.\n */\n async function retrieveQuery<T>(\n queryHash: string,\n afterRestoreMacroTask?: (persistedQuery: PersistedQuery) => void,\n ) {\n if (storage != null) {\n const storageKey = `${prefix}-${queryHash}`\n try {\n const storedData = await storage.getItem(storageKey)\n if (storedData != null) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(storedData)\n } catch {\n await storage.removeItem(storageKey)\n return\n }\n\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(storageKey)\n } else {\n if (afterRestoreMacroTask) {\n // Just after restoring we want to get fresh data from the server if it's stale\n notifyManager.schedule(() =>\n afterRestoreMacroTask(persistedQuery),\n )\n }\n // We must resolve the promise here, as otherwise we will have `loading` state in the app until `queryFn` resolves\n return persistedQuery.state.data as T\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV === 'development') {\n console.error(err)\n console.warn(\n 'Encountered an error attempting to restore query cache from persisted location.',\n )\n }\n await storage.removeItem(storageKey)\n }\n }\n\n return\n }\n\n /**\n * Persists the query with the given key, if it exists in the client's cache.\n * @param queryKey - The key of the query to persist.\n * @param queryClient - The client whose cache holds the query.\n * @returns A promise that resolves once the query is persisted.\n */\n async function persistQueryByKey(\n queryKey: QueryKey,\n queryClient: QueryClient,\n ) {\n if (storage != null) {\n const query = queryClient.getQueryCache().find({ queryKey })\n if (query) {\n await persistQuery(query)\n } else {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n 'Could not find query to be persisted. QueryKey:',\n JSON.stringify(queryKey),\n )\n }\n }\n }\n }\n\n /**\n * Writes a query's state, key, hash, and `buster` to storage.\n * @param query - The query to persist.\n * @returns A promise that resolves once the entry is serialized and written.\n */\n async function persistQuery(query: Query) {\n if (storage != null) {\n const storageKey = `${prefix}-${query.queryHash}`\n await storage.setItem(\n storageKey,\n await serialize({\n state: query.state,\n queryKey: query.queryKey,\n queryHash: query.queryHash,\n buster: buster,\n }),\n )\n }\n }\n\n /**\n * The `persister` of a query: restores its data from storage if the query has none yet, otherwise\n * runs `queryFn` and persists the result.\n * @param queryFn - The query's own query function.\n * @param ctx - The context passed to `queryFn`.\n * @param query - The query being fetched.\n * @returns A promise that resolves with the restored or fetched data.\n */\n async function persisterFn<T, TQueryKey extends QueryKey>(\n queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>,\n ctx: QueryFunctionContext<TQueryKey>,\n query: Query,\n ) {\n const matchesFilter = filters ? matchQuery(filters, query) : true\n\n // Try to restore only if we do not have any data in the cache and we have persister defined\n if (matchesFilter && query.state.data === undefined && storage != null) {\n const restoredData = await retrieveQuery(\n query.queryHash,\n (persistedQuery: PersistedQuery) => {\n // Set proper updatedAt, since resolving in the first pass overrides those values\n query.setState({\n dataUpdatedAt: persistedQuery.state.dataUpdatedAt,\n errorUpdatedAt: persistedQuery.state.errorUpdatedAt,\n })\n\n if (\n refetchOnRestore === 'always' ||\n (refetchOnRestore === true && query.isStale())\n ) {\n query.fetch()\n }\n },\n )\n\n if (restoredData !== undefined) {\n return Promise.resolve(restoredData as T)\n }\n }\n\n // If we did not restore, or restoration failed - fetch\n const queryFnResult = await queryFn(ctx)\n\n if (matchesFilter && storage != null) {\n // Persist if we have storage defined, we use timeout to get proper state to be persisted\n notifyManager.schedule(() => {\n persistQuery(query)\n })\n }\n\n return Promise.resolve(queryFnResult)\n }\n\n /**\n * Removes expired, busted, or unreadable entries from storage. Requires the storage to implement\n * `entries`.\n * @returns A promise that resolves once every entry is checked.\n */\n async function persisterGc() {\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n }\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Garbage collection is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n /**\n * Restores every persisted query matching `filters` into the client's cache with\n * `queryClient.setQueryData`. Requires the storage to implement `entries`.\n * @param queryClient - The client to restore the queries into.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * restored.\n * @returns A promise that resolves once every entry is checked.\n */\n async function restoreQueries(\n queryClient: QueryClient,\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n continue\n }\n\n if (queryKey) {\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n }\n\n queryClient.setQueryData(\n persistedQuery.queryKey,\n persistedQuery.state.data,\n {\n updatedAt: persistedQuery.state.dataUpdatedAt,\n },\n )\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Restoration of all stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n /**\n * Removes every persisted query matching `filters` from storage. Requires the storage to implement\n * `entries`.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * removed.\n * @returns A promise that resolves once every entry is checked.\n */\n async function removeQueries(\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const entries = await storage.entries()\n const storageKeyPrefix = `${prefix}-`\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n if (!queryKey) {\n await storage.removeItem(key)\n continue\n }\n\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n\n await storage.removeItem(key)\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Removal of stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n return {\n persisterFn,\n persistQuery,\n persistQueryByKey,\n retrieveQuery,\n persisterGc,\n restoreQueries,\n removeQueries,\n }\n}\n"],"mappings":";;AAmHA,MAAa,uBAAuB;;;;;;;;;;;;;;;;;;;;AAqBpC,SAAgB,kCAA0D,EACxE,SACA,SAAS,IACT,SAAS,OACT,YAAY,KAAK,WAGjB,cAAc,KAAK,OAGnB,SAAS,sBACT,mBAAmB,MACnB,WACyC;;;;;;;CAOzC,SAAS,kBAAkB,gBAAgC;EACzD,IAAI,eAAe,MAAM,eAAe;GAEtC,MAAM,UADW,KAAK,IAAI,IAAI,eAAe,MAAM,gBACxB;GAC3B,MAAM,SAAS,eAAe,WAAW;GAEzC,IAAI,WAAW,QACb,OAAO;GAGT,OAAO;EACT;EAEA,OAAO;CACT;;;;;;;;;CAUA,eAAe,cACb,WACA,uBACA;EACA,IAAI,WAAW,MAAM;GACnB,MAAM,aAAa,GAAG,OAAO,GAAG;GAChC,IAAI;IACF,MAAM,aAAa,MAAM,QAAQ,QAAQ,UAAU;IACnD,IAAI,cAAc,MAAM;KACtB,IAAI;KACJ,IAAI;MACF,iBAAiB,MAAM,YAAY,UAAU;KAC/C,QAAQ;MACN,MAAM,QAAQ,WAAW,UAAU;MACnC;KACF;KAEA,IAAI,kBAAkB,cAAc,GAClC,MAAM,QAAQ,WAAW,UAAU;UAC9B;MACL,IAAI,uBAEF,cAAc,eACZ,sBAAsB,cAAc,CACtC;MAGF,OAAO,eAAe,MAAM;KAC9B;IACF;GACF,SAAS,KAAK;IACZ,IAAI,QAAQ,IAAI,aAAa,eAAe;KAC1C,QAAQ,MAAM,GAAG;KACjB,QAAQ,KACN,iFACF;IACF;IACA,MAAM,QAAQ,WAAW,UAAU;GACrC;EACF;CAGF;;;;;;;CAQA,eAAe,kBACb,UACA,aACA;EACA,IAAI,WAAW,MAAM;GACnB,MAAM,QAAQ,YAAY,cAAc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ACF;IAEA,IAAI;IACJ,IAAI;KACF,iBAAiB,MAAM,YAAY,KAAK;IAC1C,QAAQ;KACN,MAAM,QAAQ,WAAW,GAAG;KAC5B;IACF;IAEA,IAAI,OACE;SAAA,eAAe,cAAc,QAAQ,QAAQ,GAC/C;IAAA,OAEG,IAAI,CAAC,gBAAgB,eAAe,UAAU,QAAQ,GAC3D;IAGF,MAAM,QAAQ,WAAW,GAAG;GAC9B;EAEJ,OAAO,IAAI,QAAQ,IAAI,aAAa,eAClC,MAAM,IAAI,MACR,gJACF;CAEJ;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
1
+ {"version":3,"file":"createPersister.js","names":[],"sources":["../../src/createPersister.ts"],"sourcesContent":["import {\n hashKey,\n matchQuery,\n notifyManager,\n partialMatchKey,\n} from '@tanstack/query-core'\nimport type {\n Query,\n QueryClient,\n QueryFilters,\n QueryFunctionContext,\n QueryKey,\n QueryState,\n} from '@tanstack/query-core'\n\n/**\n * A single query as stored by {@link experimental_createQueryPersister}.\n */\nexport interface PersistedQuery {\n /**\n * The `buster` the query was saved with. Entries with a different `buster` are discarded.\n */\n buster: string\n /**\n * The hash of the query.\n */\n queryHash: string\n /**\n * The key of the query.\n */\n queryKey: QueryKey\n /**\n * The state of the query, including its data and when it was last updated.\n */\n state: QueryState\n}\n\n/**\n * A value, or a promise that resolves to it.\n */\nexport type MaybePromise<T> = T | Promise<T>\n\n/**\n * A key-value storage, such as `localStorage` or `AsyncStorage`, whose methods may be synchronous\n * or return promises.\n */\nexport interface AsyncStorage<TStorageValue = string> {\n /**\n * Reads the value stored under `key`, or `null`/`undefined` if there is none.\n */\n getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>\n /**\n * Stores `value` under `key`.\n */\n setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>\n /**\n * Removes the value stored under `key`.\n */\n removeItem: (key: string) => MaybePromise<void>\n /**\n * Returns all stored key-value pairs. Required for removing expired entries in bulk.\n */\n entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>\n}\n\n/**\n * Options for {@link experimental_createQueryPersister}.\n */\nexport interface StoragePersisterOptions<TStorageValue = string> {\n /**\n * The storage client used for setting and retrieving items from cache.\n * For SSR pass in `undefined`.\n */\n storage: AsyncStorage<TStorageValue> | undefined | null\n /**\n * How to serialize the data to storage.\n * @default `JSON.stringify`\n */\n serialize?: (persistedQuery: PersistedQuery) => MaybePromise<TStorageValue>\n /**\n * How to deserialize the data from storage.\n * @default `JSON.parse`\n */\n deserialize?: (cachedString: TStorageValue) => MaybePromise<PersistedQuery>\n /**\n * A unique string that can be used to forcefully invalidate existing caches,\n * if they do not share the same buster string\n */\n buster?: string\n /**\n * The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded\n * @default 24 hours\n */\n maxAge?: number\n /**\n * Prefix to be used for storage key.\n * Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.\n * @default 'tanstack-query'\n */\n prefix?: string\n /**\n * If set to `true`, the query will refetch on successful query restoration if the data is stale.\n * If set to `false`, the query will not refetch on successful query restoration.\n * If set to `'always'`, the query will always refetch on successful query restoration.\n * @defaultValue true\n */\n refetchOnRestore?: boolean | 'always'\n /**\n * Filters to narrow down which Queries should be persisted.\n */\n filters?: QueryFilters\n}\n\nexport const PERSISTER_KEY_PREFIX = 'tanstack-query'\n\n/**\n * Warning: experimental feature.\n * This utility function enables fine-grained query persistence.\n * Simple add it as a `persister` parameter to `useQuery` or `defaultOptions` on `queryClient`.\n *\n * ```\n * useQuery({\n * queryKey: ['myKey'],\n * queryFn: fetcher,\n * persister: createPersister({\n * storage: localStorage,\n * }),\n * })\n * ```\n * @param options - The storage to persist to, and the options for serializing, expiring, and\n * filtering persisted queries.\n * @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,\n * restore, remove, and garbage collect persisted queries manually.\n */\nexport function experimental_createQueryPersister<TStorageValue = string>({\n storage,\n buster = '',\n maxAge = 24 * 60 * 60 * 1000,\n serialize = JSON.stringify as Required<\n StoragePersisterOptions<TStorageValue>\n >['serialize'],\n deserialize = JSON.parse as Required<\n StoragePersisterOptions<TStorageValue>\n >['deserialize'],\n prefix = PERSISTER_KEY_PREFIX,\n refetchOnRestore = true,\n filters: persistFilters,\n}: StoragePersisterOptions<TStorageValue>) {\n /**\n * Checks whether a persisted query should be discarded.\n * @param persistedQuery - The persisted query to check.\n * @returns `true` if it has no `dataUpdatedAt`, is older than `maxAge`, or has a different\n * `buster`.\n */\n function isExpiredOrBusted(persistedQuery: PersistedQuery) {\n if (persistedQuery.state.dataUpdatedAt) {\n const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt\n const expired = queryAge > maxAge\n const busted = persistedQuery.buster !== buster\n\n if (expired || busted) {\n return true\n }\n\n return false\n }\n\n return true\n }\n\n /**\n * Reads the persisted data of a query from storage. Expired, busted, or unreadable entries are\n * removed instead.\n * @param queryHash - The hash of the query to read.\n * @param afterRestoreMacroTask - Scheduled with the persisted query after it is restored.\n * @returns A promise that resolves with the persisted data, or `undefined` if nothing was\n * restored.\n */\n async function retrieveQuery<T>(\n queryHash: string,\n afterRestoreMacroTask?: (persistedQuery: PersistedQuery) => void,\n ) {\n if (storage != null) {\n const storageKey = `${prefix}-${queryHash}`\n try {\n const storedData = await storage.getItem(storageKey)\n if (storedData != null) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(storedData)\n } catch {\n await storage.removeItem(storageKey)\n return\n }\n\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(storageKey)\n } else {\n if (afterRestoreMacroTask) {\n // Just after restoring we want to get fresh data from the server if it's stale\n notifyManager.schedule(() =>\n afterRestoreMacroTask(persistedQuery),\n )\n }\n // We must resolve the promise here, as otherwise we will have `loading` state in the app until `queryFn` resolves\n return persistedQuery.state.data as T\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV === 'development') {\n console.error(err)\n console.warn(\n 'Encountered an error attempting to restore query cache from persisted location.',\n )\n }\n await storage.removeItem(storageKey)\n }\n }\n\n return\n }\n\n /**\n * Persists the query with the given key, if it exists in the client's cache.\n * @param queryKey - The key of the query to persist.\n * @param queryClient - The client whose cache holds the query.\n * @returns A promise that resolves once the query is persisted.\n */\n async function persistQueryByKey(\n queryKey: QueryKey,\n queryClient: QueryClient,\n ) {\n if (storage != null) {\n const query = queryClient.getQueryCache().find({ queryKey })\n if (query) {\n await persistQuery(query)\n } else {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n 'Could not find query to be persisted. QueryKey:',\n JSON.stringify(queryKey),\n )\n }\n }\n }\n }\n\n /**\n * Writes a query's state, key, hash, and `buster` to storage.\n * @param query - The query to persist.\n * @returns A promise that resolves once the entry is serialized and written.\n */\n async function persistQuery(query: Query) {\n if (storage != null) {\n const storageKey = `${prefix}-${query.queryHash}`\n await storage.setItem(\n storageKey,\n await serialize({\n state: query.state,\n queryKey: query.queryKey,\n queryHash: query.queryHash,\n buster: buster,\n }),\n )\n }\n }\n\n /**\n * The `persister` of a query: restores its data from storage if the query has none yet, otherwise\n * runs `queryFn` and persists the result.\n * @param queryFn - The query's own query function.\n * @param ctx - The context passed to `queryFn`.\n * @param query - The query being fetched.\n * @returns A promise that resolves with the restored or fetched data.\n */\n async function persisterFn<T, TQueryKey extends QueryKey>(\n queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>,\n ctx: QueryFunctionContext<TQueryKey>,\n query: Query,\n ) {\n const matchesFilter = persistFilters\n ? matchQuery(persistFilters, query)\n : true\n\n // Try to restore only if we do not have any data in the cache and we have persister defined\n if (matchesFilter && query.state.data === undefined && storage != null) {\n const restoredData = await retrieveQuery(\n query.queryHash,\n (persistedQuery: PersistedQuery) => {\n // Set proper updatedAt, since resolving in the first pass overrides those values\n query.setState({\n dataUpdatedAt: persistedQuery.state.dataUpdatedAt,\n errorUpdatedAt: persistedQuery.state.errorUpdatedAt,\n })\n\n if (\n refetchOnRestore === 'always' ||\n (refetchOnRestore === true && query.isStale())\n ) {\n query.fetch()\n }\n },\n )\n\n if (restoredData !== undefined) {\n return Promise.resolve(restoredData as T)\n }\n }\n\n // If we did not restore, or restoration failed - fetch\n const queryFnResult = await queryFn(ctx)\n\n if (matchesFilter && storage != null) {\n // Persist if we have storage defined, we use timeout to get proper state to be persisted\n notifyManager.schedule(() => {\n persistQuery(query)\n })\n }\n\n return Promise.resolve(queryFnResult)\n }\n\n /**\n * Removes expired, busted, or unreadable entries from storage. Requires the storage to implement\n * `entries`.\n * @returns A promise that resolves once every entry is checked.\n */\n async function persisterGc() {\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n }\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Garbage collection is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n /**\n * Restores every persisted query matching `filters` into the client's cache with\n * `queryClient.setQueryData`. Requires the storage to implement `entries`.\n * @param queryClient - The client to restore the queries into.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * restored.\n * @returns A promise that resolves once every entry is checked.\n */\n async function restoreQueries(\n queryClient: QueryClient,\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n continue\n }\n\n if (queryKey) {\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n }\n\n queryClient.setQueryData(\n persistedQuery.queryKey,\n persistedQuery.state.data,\n {\n updatedAt: persistedQuery.state.dataUpdatedAt,\n },\n )\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Restoration of all stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n /**\n * Removes every persisted query matching `filters` from storage. Requires the storage to implement\n * `entries`.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * removed.\n * @returns A promise that resolves once every entry is checked.\n */\n async function removeQueries(\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const entries = await storage.entries()\n const storageKeyPrefix = `${prefix}-`\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n if (!queryKey) {\n await storage.removeItem(key)\n continue\n }\n\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n\n await storage.removeItem(key)\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Removal of stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n return {\n persisterFn,\n persistQuery,\n persistQueryByKey,\n retrieveQuery,\n persisterGc,\n restoreQueries,\n removeQueries,\n }\n}\n"],"mappings":";;AAmHA,MAAa,uBAAuB;;;;;;;;;;;;;;;;;;;;AAqBpC,SAAgB,kCAA0D,EACxE,SACA,SAAS,IACT,SAAS,OACT,YAAY,KAAK,WAGjB,cAAc,KAAK,OAGnB,SAAS,sBACT,mBAAmB,MACnB,SAAS,kBACgC;;;;;;;C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CAEJ;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"persist.cjs","names":["dehydrate"],"sources":["../../src/persist.ts"],"sourcesContent":["import { dehydrate, hydrate } from '@tanstack/query-core'\nimport type {\n DehydrateOptions,\n DehydratedState,\n HydrateOptions,\n NotifyEventType,\n QueryClient,\n} from '@tanstack/query-core'\n\n/**\n * A value, or a promise-like that resolves to it.\n */\nexport type Promisable<T> = T | PromiseLike<T>\n\n/**\n * Saves, restores, and removes a {@link PersistedClient} in a storage.\n */\nexport interface Persister {\n /**\n * Saves the persisted client to the storage.\n */\n persistClient: (persistClient: PersistedClient) => Promisable<void>\n /**\n * Reads the persisted client from the storage, or `undefined` if nothing was saved.\n */\n restoreClient: () => Promisable<PersistedClient | undefined>\n /**\n * Removes the persisted client from the storage.\n */\n removeClient: () => Promisable<void>\n}\n\n/**\n * The dehydrated state of a `QueryClient` as it is persisted, with the time it was saved and its\n * `buster`.\n */\nexport interface PersistedClient {\n /**\n * When the client was saved, in milliseconds since the epoch. Compared with `maxAge` on restore.\n */\n timestamp: number\n /**\n * The `buster` the client was saved with. A persisted client with a different `buster` is\n * discarded.\n */\n buster: string\n /**\n * The dehydrated cache of the `QueryClient`.\n */\n clientState: DehydratedState\n}\n\n/**\n * The options shared by restoring and saving a persisted `QueryClient`.\n */\nexport interface PersistQueryClientRootOptions {\n /** The QueryClient to persist */\n queryClient: QueryClient\n /**\n * The Persister interface for storing and restoring the cache\n * to/from a persisted location\n */\n persister: Persister\n /**\n * A unique string that can be used to forcefully\n * invalidate existing caches if they do not share the same buster string\n */\n buster?: string\n}\n\n/**\n * Options for restoring a persisted `QueryClient` with {@link persistQueryClientRestore}.\n */\nexport interface PersistedQueryClientRestoreOptions extends PersistQueryClientRootOptions {\n /**\n * The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded\n */\n maxAge?: number\n /** The options passed to the hydrate function */\n hydrateOptions?: HydrateOptions\n}\n\n/**\n * Options for saving a `QueryClient` with {@link persistQueryClientSave}.\n */\nexport interface PersistedQueryClientSaveOptions extends PersistQueryClientRootOptions {\n /** The options passed to the dehydrate function */\n dehydrateOptions?: DehydrateOptions\n}\n\n/**\n * Options for {@link persistQueryClient}, which both restores and saves a `QueryClient`.\n */\nexport interface PersistQueryClientOptions\n extends\n PersistedQueryClientRestoreOptions,\n PersistedQueryClientSaveOptions,\n PersistQueryClientRootOptions {}\n\nconst cacheEventTypes: Array<NotifyEventType> = ['added', 'removed', 'updated']\n\n/**\n * Checks if emitted event is about cache change and not about observers.\n * Useful for persist, where we only want to trigger save when cache is changed.\n * @param eventType - The type of the emitted event.\n * @returns `true` if the event is `'added'`, `'removed'`, or `'updated'`.\n */\nfunction isCacheEventType(eventType: NotifyEventType) {\n return cacheEventTypes.includes(eventType)\n}\n\n/**\n * Restores persisted data to the QueryCache.\n * - data obtained from persister.restoreClient.\n * - data is hydrated using hydrateOptions.\n * If data is expired, busted, empty, or throws, it runs persister.removeClient.\n * @param options - The `queryClient` to restore into, the `persister`, and the `maxAge`, `buster`,\n * and `hydrateOptions` that decide whether and how the persisted data is restored.\n * @returns A promise that resolves once the data is restored or removed. If restoring throws, it\n * attempts to remove the persisted data and then rejects with the restore error, or with the removal\n * error if the removal fails too.\n */\nexport async function persistQueryClientRestore({\n queryClient,\n persister,\n maxAge = 1000 * 60 * 60 * 24,\n buster = '',\n hydrateOptions,\n}: PersistedQueryClientRestoreOptions) {\n try {\n const persistedClient = await persister.restoreClient()\n\n if (persistedClient) {\n if (persistedClient.timestamp) {\n const expired = Date.now() - persistedClient.timestamp > maxAge\n const busted = persistedClient.buster !== buster\n if (expired || busted) {\n return persister.removeClient()\n } else {\n hydrate(queryClient, persistedClient.clientState, hydrateOptions)\n }\n } else {\n return persister.removeClient()\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(err)\n console.warn(\n 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',\n )\n }\n\n await persister.removeClient()\n\n throw err\n }\n}\n\n/**\n * Persists data from the QueryCache.\n * - data dehydrated using dehydrateOptions.\n * - data is persisted using persister.persistClient.\n * @param options - The `queryClient` to persist, the `persister`, the `buster`, and the\n * `dehydrateOptions`.\n */\nexport async function persistQueryClientSave({\n queryClient,\n persister,\n buster = '',\n dehydrateOptions,\n}: PersistedQueryClientSaveOptions) {\n const persistClient: PersistedClient = {\n buster,\n timestamp: Date.now(),\n clientState: dehydrate(queryClient, dehydrateOptions),\n }\n\n await persister.persistClient(persistClient)\n}\n\n/**\n * Subscribe to QueryCache and MutationCache updates (for persisting).\n * @param props - The `queryClient` to monitor, the `persister`, the `buster`, and the\n * `dehydrateOptions` used for each save.\n * @returns an unsubscribe function (to discontinue monitoring)\n */\nexport function persistQueryClientSubscribe(\n props: PersistedQueryClientSaveOptions,\n) {\n const unsubscribeQueryCache = props.queryClient\n .getQueryCache()\n .subscribe((event) => {\n if (isCacheEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n const unsubscribeMutationCache = props.queryClient\n .getMutationCache()\n .subscribe((event) => {\n if (isCacheEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n return () => {\n unsubscribeQueryCache()\n unsubscribeMutationCache()\n }\n}\n\n/**\n * Restores persisted data to QueryCache and persists further changes.\n * @param props - The options for both restoring and saving.\n * @returns A tuple of a function that stops persisting, and a promise that resolves once the\n * restore is done.\n */\nexport function persistQueryClient(\n props: PersistQueryClientOptions,\n): [() => void, Promise<void>] {\n let hasUnsubscribed = false\n let persistQueryClientUnsubscribe: (() => void) | undefined\n const unsubscribe = () => {\n hasUnsubscribed = true\n persistQueryClientUnsubscribe?.()\n }\n\n // Attempt restore\n const restorePromise = persistQueryClientRestore(props).then(() => {\n if (!hasUnsubscribed) {\n // Subscribe to changes in the query cache to trigger the save\n persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)\n }\n })\n\n return [unsubscribe,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AAsB;EACtB,yBAAyB;CAC3B;AACF;;;;;;;AAQA,SAAgB,mBACd,OAC6B;CAC7B,IAAI,kBAAkB;CACtB,IAAI;CACJ,MAAM,oBAAoB;EACxB,kBAAkB;EAClB,gCAAgC;CAClC;CAUA,OAAO,CAAC,aAPe,0BAA0B,KAAK,CAAC,CAAC,WAAW;EACjE,IAAI,CAAC,iBAEH,gCAAgC,4BAA4B,KAAK;CAErE,CAEkC,CAAC;AACrC"}
1
+ {"version":3,"file":"persist.cjs","names":["dehydrate"],"sources":["../../src/persist.ts"],"sourcesContent":["import { dehydrate, hydrate } from '@tanstack/query-core'\nimport type {\n DehydrateOptions,\n DehydratedState,\n HydrateOptions,\n NotifyEventType,\n QueryClient,\n} from '@tanstack/query-core'\n\n/**\n * A value, or a promise-like that resolves to it.\n */\nexport type Promisable<T> = T | PromiseLike<T>\n\n/**\n * Saves, restores, and removes a {@link PersistedClient} in a storage.\n */\nexport interface Persister {\n /**\n * Saves the persisted client to the storage.\n */\n persistClient: (persistClient: PersistedClient) => Promisable<void>\n /**\n * Reads the persisted client from the storage, or `undefined` if nothing was saved.\n */\n restoreClient: () => Promisable<PersistedClient | undefined>\n /**\n * Removes the persisted client from the storage.\n */\n removeClient: () => Promisable<void>\n}\n\n/**\n * The dehydrated state of a `QueryClient` as it is persisted, with the time it was saved and its\n * `buster`.\n */\nexport interface PersistedClient {\n /**\n * When the client was saved, in milliseconds since the epoch. Compared with `maxAge` on restore.\n */\n timestamp: number\n /**\n * The `buster` the client was saved with. A persisted client with a different `buster` is\n * discarded.\n */\n buster: string\n /**\n * The dehydrated cache of the `QueryClient`.\n */\n clientState: DehydratedState\n}\n\n/**\n * The options shared by restoring and saving a persisted `QueryClient`.\n */\nexport interface PersistQueryClientRootOptions {\n /** The QueryClient to persist */\n queryClient: QueryClient\n /**\n * The Persister interface for storing and restoring the cache\n * to/from a persisted location\n */\n persister: Persister\n /**\n * A unique string that can be used to forcefully\n * invalidate existing caches if they do not share the same buster string\n */\n buster?: string\n}\n\n/**\n * Options for restoring a persisted `QueryClient` with {@link persistQueryClientRestore}.\n */\nexport interface PersistedQueryClientRestoreOptions extends PersistQueryClientRootOptions {\n /**\n * The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded\n */\n maxAge?: number\n /** The options passed to the hydrate function */\n hydrateOptions?: HydrateOptions\n}\n\n/**\n * Options for saving a `QueryClient` with {@link persistQueryClientSave}.\n */\nexport interface PersistedQueryClientSaveOptions extends PersistQueryClientRootOptions {\n /** The options passed to the dehydrate function */\n dehydrateOptions?: DehydrateOptions\n}\n\n/**\n * Options for {@link persistQueryClient}, which both restores and saves a `QueryClient`.\n */\nexport interface PersistQueryClientOptions\n extends\n PersistedQueryClientRestoreOptions,\n PersistedQueryClientSaveOptions,\n PersistQueryClientRootOptions {}\n\nconst cacheEventTypes: Array<NotifyEventType> = ['added', 'removed', 'updated']\n\n/**\n * Checks if emitted event is about cache change and not about observers.\n * Useful for persist, where we only want to trigger save when cache is changed.\n * @param eventType - The type of the emitted event.\n * @returns `true` if the event is `'added'`, `'removed'`, or `'updated'`.\n */\nfunction isCacheEventType(eventType: NotifyEventType) {\n return cacheEventTypes.includes(eventType)\n}\n\n/**\n * Restores persisted data to the QueryCache.\n * - data obtained from persister.restoreClient.\n * - data is hydrated using hydrateOptions.\n * If data is expired, busted, empty, or throws, it runs persister.removeClient.\n * @param options - The `queryClient` to restore into, the `persister`, and the `maxAge`, `buster`,\n * and `hydrateOptions` that decide whether and how the persisted data is restored.\n * @returns A promise that resolves once the data is restored or removed. If restoring throws, it\n * attempts to remove the persisted data and then rejects with the restore error, or with the removal\n * error if the removal fails too.\n */\nexport async function persistQueryClientRestore({\n queryClient,\n persister,\n maxAge = 24 * 60 * 60 * 1000,\n buster = '',\n hydrateOptions,\n}: PersistedQueryClientRestoreOptions) {\n try {\n const persistedClient = await persister.restoreClient()\n\n if (persistedClient) {\n if (persistedClient.timestamp) {\n const expired = Date.now() - persistedClient.timestamp > maxAge\n const busted = persistedClient.buster !== buster\n if (expired || busted) {\n return persister.removeClient()\n } else {\n hydrate(queryClient, persistedClient.clientState, hydrateOptions)\n }\n } else {\n return persister.removeClient()\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(err)\n console.warn(\n 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',\n )\n }\n\n await persister.removeClient()\n\n throw err\n }\n}\n\n/**\n * Persists data from the QueryCache.\n * - data dehydrated using dehydrateOptions.\n * - data is persisted using persister.persistClient.\n * @param options - The `queryClient` to persist, the `persister`, the `buster`, and the\n * `dehydrateOptions`.\n */\nexport async function persistQueryClientSave({\n queryClient,\n persister,\n buster = '',\n dehydrateOptions,\n}: PersistedQueryClientSaveOptions) {\n const persistClient: PersistedClient = {\n buster,\n timestamp: Date.now(),\n clientState: dehydrate(queryClient, dehydrateOptions),\n }\n\n await persister.persistClient(persistClient)\n}\n\n/**\n * Subscribe to QueryCache and MutationCache updates (for persisting).\n * @param props - The `queryClient` to monitor, the `persister`, the `buster`, and the\n * `dehydrateOptions` used for each save.\n * @returns an unsubscribe function (to discontinue monitoring)\n */\nexport function persistQueryClientSubscribe(\n props: PersistedQueryClientSaveOptions,\n) {\n const unsubscribeQueryCache = props.queryClient\n .getQueryCache()\n .subscribe((event) => {\n if (isCacheEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n const unsubscribeMutationCache = props.queryClient\n .getMutationCache()\n .subscribe((event) => {\n if (isCacheEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n return () => {\n unsubscribeQueryCache()\n unsubscribeMutationCache()\n }\n}\n\n/**\n * Restores persisted data to QueryCache and persists further changes.\n * @param props - The options for both restoring and saving.\n * @returns A tuple of a function that stops persisting, and a promise that resolves once the\n * restore is done.\n */\nexport function persistQueryClient(\n props: PersistQueryClientOptions,\n): [() => void, Promise<void>] {\n let hasUnsubscribed = false\n let persistQueryClientUnsubscribe: (() => void) | undefined\n const unsubscribe = () => {\n hasUnsubscribed = true\n persistQueryClientUnsubscribe?.()\n }\n\n // Attempt restore\n const restorePromise = persistQueryClientRestore(props).then(() => {\n if (!hasUnsubscribed) {\n // Subscribe to changes in the query cache to trigger the save\n persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)\n }\n })\n\n return [unsubscribe, restorePromise]\n}\n"],"mappings":";;;AAqGA,MAAM,kBAA0C;CAAC;CAAS;CAAW;AAAS;;;;;;;AAQ9E,SAAS,iBAAiB,WAA4B;CACpD,OAAO,gBAAgB,SAAS,SAAS;AAC3C;;;;;;;;;;;;AAaA,eAAsB,0BAA0B,EAC9C,aACA,WACA,SAAS,OACT,SAAS,IACT,kBACqC;CACrC,IAAI;EACF,MAAM,kBAAkB,MAAM,UAAU,cAAc;EAEtD,IAAI,iBAAiB;GACnB,IAAI,gBAAgB,WAAW;IAC7B,MAAM,UAAU,KAAK,IAAI,IAAI,gBAAgB,YAAY;IACzD,MAAM,SAAS,gBAAgB,WAAW;IAC1C,IAAI,WAAW,QACb,OAAO,UAAU,aAAa;SAE9B,CAAA,GAAA,qBAAA,QAAA,CAAQ,aAAa,gBAAgB,aAAa,cAAc;GAEpE,OACE,OAAO,UAAU,aAAa;EAElC;CACF,SAAS,KAAK;EACZ,IAAI,QAAQ,IAAI,aAAa,cAAc;GACzC,QAAQ,MAAM,GAAG;GACjB,QAAQ,KACN,0IACF;EACF;EAEA,MAAM,UAAU,aAAa;EAE7B,MAAM;CACR;AACF;;;;;;;;AASA,eAAsB,uBAAuB,EAC3C,aACA,WACA,SAAS,IACT,oBACkC;CAClC,MAAM,gBAAiC;EACrC;EACA,WAAW,KAAK,IAAI;EACpB,cAAA,GAAaA,qBAAAA,UAAAA,CAAU,aAAa,gBAAgB;CACtD;CAEA,MAAM,UAAU,cAAc,aAAa;AAC7C;;;;;;;AAQA,SAAgB,4BACd,OACA;CACA,MAAM,wBAAwB,MAAM,YACjC,cAAc,CAAC,CACf,WAAW,UAAU;EACpB,IAAI,iBAAiB,MAAM,IAAI,GAC7B,uBAAuB,KAAK;CAEhC,CAAC;CAEH,MAAM,2BAA2B,MAAM,YACpC,iBAAiB,CAAC,CAClB,WAAW,UAAU;EACpB,IAAI,iBAAiB,MAAM,IAAI,GAC7B,uBAAuB,KAAK;CAEhC,CAAC;CAEH,aAAa;EACX,sBAAsB;EACtB,yBAAyB;CAC3B;AACF;;;;;;;AAQA,SAAgB,mBACd,OAC6B;CAC7B,IAAI,kBAAkB;CACtB,IAAI;CACJ,MAAM,oBAAoB;EACxB,kBAAkB;EAClB,gCAAgC;CAClC;CAUA,OAAO,CAAC,aAPe,0BAA0B,KAAK,CAAC,CAAC,WAAW;EACjE,IAAI,CAAC,iBAEH,gCAAgC,4BAA4B,KAAK;CAErE,CAEkC,CAAC;AACrC"}
@@ -1 +1 @@
1
- {"version":3,"file":"persist.js","names":[],"sources":["../../src/persist.ts"],"sourcesContent":["import { dehydrate, hydrate } from '@tanstack/query-core'\nimport type {\n DehydrateOptions,\n DehydratedState,\n HydrateOptions,\n NotifyEventType,\n QueryClient,\n} from '@tanstack/query-core'\n\n/**\n * A value, or a promise-like that resolves to it.\n */\nexport type Promisable<T> = T | PromiseLike<T>\n\n/**\n * Saves, restores, and removes a {@link PersistedClient} in a storage.\n */\nexport interface Persister {\n /**\n * Saves the persisted client to the storage.\n */\n persistClient: (persistClient: PersistedClient) => Promisable<void>\n /**\n * Reads the persisted client from the storage, or `undefined` if nothing was saved.\n */\n restoreClient: () => Promisable<PersistedClient | undefined>\n /**\n * Removes the persisted client from the storage.\n */\n removeClient: () => Promisable<void>\n}\n\n/**\n * The dehydrated state of a `QueryClient` as it is persisted, with the time it was saved and its\n * `buster`.\n */\nexport interface PersistedClient {\n /**\n * When the client was saved, in milliseconds since the epoch. Compared with `maxAge` on restore.\n */\n timestamp: number\n /**\n * The `buster` the client was saved with. A persisted client with a different `buster` is\n * discarded.\n */\n buster: string\n /**\n * The dehydrated cache of the `QueryClient`.\n */\n clientState: DehydratedState\n}\n\n/**\n * The options shared by restoring and saving a persisted `QueryClient`.\n */\nexport interface PersistQueryClientRootOptions {\n /** The QueryClient to persist */\n queryClient: QueryClient\n /**\n * The Persister interface for storing and restoring the cache\n * to/from a persisted location\n */\n persister: Persister\n /**\n * A unique string that can be used to forcefully\n * invalidate existing caches if they do not share the same buster string\n */\n buster?: string\n}\n\n/**\n * Options for restoring a persisted `QueryClient` with {@link persistQueryClientRestore}.\n */\nexport interface PersistedQueryClientRestoreOptions extends PersistQueryClientRootOptions {\n /**\n * The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded\n */\n maxAge?: number\n /** The options passed to the hydrate function */\n hydrateOptions?: HydrateOptions\n}\n\n/**\n * Options for saving a `QueryClient` with {@link persistQueryClientSave}.\n */\nexport interface PersistedQueryClientSaveOptions extends PersistQueryClientRootOptions {\n /** The options passed to the dehydrate function */\n dehydrateOptions?: DehydrateOptions\n}\n\n/**\n * Options for {@link persistQueryClient}, which both restores and saves a `QueryClient`.\n */\nexport interface PersistQueryClientOptions\n extends\n PersistedQueryClientRestoreOptions,\n PersistedQueryClientSaveOptions,\n PersistQueryClientRootOptions {}\n\nconst cacheEventTypes: Array<NotifyEventType> = ['added', 'removed', 'updated']\n\n/**\n * Checks if emitted event is about cache change and not about observers.\n * Useful for persist, where we only want to trigger save when cache is changed.\n * @param eventType - The type of the emitted event.\n * @returns `true` if the event is `'added'`, `'removed'`, or `'updated'`.\n */\nfunction isCacheEventType(eventType: NotifyEventType) {\n return cacheEventTypes.includes(eventType)\n}\n\n/**\n * Restores persisted data to the QueryCache.\n * - data obtained from persister.restoreClient.\n * - data is hydrated using hydrateOptions.\n * If data is expired, busted, empty, or throws, it runs persister.removeClient.\n * @param options - The `queryClient` to restore into, the `persister`, and the `maxAge`, `buster`,\n * and `hydrateOptions` that decide whether and how the persisted data is restored.\n * @returns A promise that resolves once the data is restored or removed. If restoring throws, it\n * attempts to remove the persisted data and then rejects with the restore error, or with the removal\n * error if the removal fails too.\n */\nexport async function persistQueryClientRestore({\n queryClient,\n persister,\n maxAge = 1000 * 60 * 60 * 24,\n buster = '',\n hydrateOptions,\n}: PersistedQueryClientRestoreOptions) {\n try {\n const persistedClient = await persister.restoreClient()\n\n if (persistedClient) {\n if (persistedClient.timestamp) {\n const expired = Date.now() - persistedClient.timestamp > maxAge\n const busted = persistedClient.buster !== buster\n if (expired || busted) {\n return persister.removeClient()\n } else {\n hydrate(queryClient, persistedClient.clientState, hydrateOptions)\n }\n } else {\n return persister.removeClient()\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(err)\n console.warn(\n 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',\n )\n }\n\n await persister.removeClient()\n\n throw err\n }\n}\n\n/**\n * Persists data from the QueryCache.\n * - data dehydrated using dehydrateOptions.\n * - data is persisted using persister.persistClient.\n * @param options - The `queryClient` to persist, the `persister`, the `buster`, and the\n * `dehydrateOptions`.\n */\nexport async function persistQueryClientSave({\n queryClient,\n persister,\n buster = '',\n dehydrateOptions,\n}: PersistedQueryClientSaveOptions) {\n const persistClient: PersistedClient = {\n buster,\n timestamp: Date.now(),\n clientState: dehydrate(queryClient, dehydrateOptions),\n }\n\n await persister.persistClient(persistClient)\n}\n\n/**\n * Subscribe to QueryCache and MutationCache updates (for persisting).\n * @param props - The `queryClient` to monitor, the `persister`, the `buster`, and the\n * `dehydrateOptions` used for each save.\n * @returns an unsubscribe function (to discontinue monitoring)\n */\nexport function persistQueryClientSubscribe(\n props: PersistedQueryClientSaveOptions,\n) {\n const unsubscribeQueryCache = props.queryClient\n .getQueryCache()\n .subscribe((event) => {\n if (isCacheEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n const unsubscribeMutationCache = props.queryClient\n .getMutationCache()\n .subscribe((event) => {\n if (isCacheEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n return () => {\n unsubscribeQueryCache()\n unsubscribeMutationCache()\n }\n}\n\n/**\n * Restores persisted data to QueryCache and persists further changes.\n * @param props - The options for both restoring and saving.\n * @returns A tuple of a function that stops persisting, and a promise that resolves once the\n * restore is done.\n */\nexport function persistQueryClient(\n props: PersistQueryClientOptions,\n): [() => void, Promise<void>] {\n let hasUnsubscribed = false\n let persistQueryClientUnsubscribe: (() => void) | undefined\n const unsubscribe = () => {\n hasUnsubscribed = true\n persistQueryClientUnsubscribe?.()\n }\n\n // Attempt restore\n const restorePromise = persistQueryClientRestore(props).then(() => {\n if (!hasUnsubscribed) {\n // Subscribe to changes in the query cache to trigger the save\n persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)\n }\n })\n\n return [unsubscribe, restorePromise]\n}\n"],"mappings":";;AAqGA,MAAM,kBAA0C;CAAC;CAAS;CAAW;AAAS;;;;;;;AAQ9E,SAAS,iBAAiB,WAA4B;CACpD,OAAO,gBAAgB,SAAS,SAAS;AAC3C;;;;;;;;;;;;AAaA,eAAsB,0BAA0B,EAC9C,aACA,WACA,SAAS,OACT,SAAS,IACT,kBACqC;CACrC,IAAI;EACF,MAAM,kBAAkB,MAAM,UAAU,cAAc;EAEtD,IAAI,iBAAiB;GACnB,IAAI,gBAAgB,WAAW;IAC7B,MAAM,UAAU,KAAK,IAAI,IAAI,gBAAgB,YAAY;IACzD,MAAM,SAAS,gBAAgB,WAAW;IAC1C,IAAI,WAAW,QACb,OAAO,UAAU,aAAa;SAE9B,QAAQ,aAAa,gBAAgB,aAAa,cAAc;GAEpE,OACE,OAAO,UAAU,aAAa;EAElC;CACF,SAAS,KAAK;EACZ,IAAI,QAAQ,IAAI,aAAa,cAAc;GACzC,QAAQ,MAAM,GAAG;GACjB,QAAQ,KACN,0IACF;EACF;EAEA,MAAM,UAAU,aAAa;EAE7B,MAAM;CACR;AACF;;;;;;;;AASA,eAAsB,uBAAuB,EAC3C,aACA,WACA,SAAS,IACT,oBACkC;CAClC,MAAM,gBAAiC;EACrC;EACA,WAAW,KAAK,IAAI;EACpB,aAAa,UAAU,aAAa,gBAAgB;CACtD;CAEA,MAAM,UAAU,cAAc,aAAa;AAC7C;;;;;;;AAQA,SAAgB,4BACd,OACA;CACA,MAAM,wBAAwB,MAAM,YACjC,cAAc,CAAC,CACf,WAAW,UAAU;EACpB,IAAI,iBAAiB,MAAM,IAAI,GAC7B,uBAAuB,KAAK;CAEhC,CAAC;CAEH,MAAM,2BAA2B,MAAM,YACpC,iBAAiB,CAAC,CAClB,WAAW,UAAU;EACpB,IAAI,iBAAiB,MAAM,IAAI,GAC7B,uBAAuB,KAAK;CAEhC,CAAC;CAEH,aAAa;EACX,sBAAsB;EACtB,yBAAyB;CAC3B;AACF;;;;;;;AAQA,SAAgB,mBACd,OAC6B;CAC7B,IAAI,kBAAkB;CACtB,IAAI;CACJ,MAAM,oBAAoB;EACxB,kBAAkB;EAClB,gCAAgC;CAClC;CAUA,OAAO,CAAC,aAPe,0BAA0B,KAAK,CAAC,CAAC,WAAW;EACjE,IAAI,CAAC,iBAEH,gCAAgC,4BAA4B,KAAK;CAErE,CAEkC,CAAC;AACrC"}
1
+ {"version":3,"file":"persist.js","names":[],"sources":["../../src/persist.ts"],"sourcesContent":["import { dehydrate, hydrate } from '@tanstack/query-core'\nimport type {\n DehydrateOptions,\n DehydratedState,\n HydrateOptions,\n NotifyEventType,\n QueryClient,\n} from '@tanstack/query-core'\n\n/**\n * A value, or a promise-like that resolves to it.\n */\nexport type Promisable<T> = T | PromiseLike<T>\n\n/**\n * Saves, restores, and removes a {@link PersistedClient} in a storage.\n */\nexport interface Persister {\n /**\n * Saves the persisted client to the storage.\n */\n persistClient: (persistClient: PersistedClient) => Promisable<void>\n /**\n * Reads the persisted client from the storage, or `undefined` if nothing was saved.\n */\n restoreClient: () => Promisable<PersistedClient | undefined>\n /**\n * Removes the persisted client from the storage.\n */\n removeClient: () => Promisable<void>\n}\n\n/**\n * The dehydrated state of a `QueryClient` as it is persisted, with the time it was saved and its\n * `buster`.\n */\nexport interface PersistedClient {\n /**\n * When the client was saved, in milliseconds since the epoch. Compared with `maxAge` on restore.\n */\n timestamp: number\n /**\n * The `buster` the client was saved with. A persisted client with a different `buster` is\n * discarded.\n */\n buster: string\n /**\n * The dehydrated cache of the `QueryClient`.\n */\n clientState: DehydratedState\n}\n\n/**\n * The options shared by restoring and saving a persisted `QueryClient`.\n */\nexport interface PersistQueryClientRootOptions {\n /** The QueryClient to persist */\n queryClient: QueryClient\n /**\n * The Persister interface for storing and restoring the cache\n * to/from a persisted location\n */\n persister: Persister\n /**\n * A unique string that can be used to forcefully\n * invalidate existing caches if they do not share the same buster string\n */\n buster?: string\n}\n\n/**\n * Options for restoring a persisted `QueryClient` with {@link persistQueryClientRestore}.\n */\nexport interface PersistedQueryClientRestoreOptions extends PersistQueryClientRootOptions {\n /**\n * The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded\n */\n maxAge?: number\n /** The options passed to the hydrate function */\n hydrateOptions?: HydrateOptions\n}\n\n/**\n * Options for saving a `QueryClient` with {@link persistQueryClientSave}.\n */\nexport interface PersistedQueryClientSaveOptions extends PersistQueryClientRootOptions {\n /** The options passed to the dehydrate function */\n dehydrateOptions?: DehydrateOptions\n}\n\n/**\n * Options for {@link persistQueryClient}, which both restores and saves a `QueryClient`.\n */\nexport interface PersistQueryClientOptions\n extends\n PersistedQueryClientRestoreOptions,\n PersistedQueryClientSaveOptions,\n PersistQueryClientRootOptions {}\n\nconst cacheEventTypes: Array<NotifyEventType> = ['added', 'removed', 'updated']\n\n/**\n * Checks if emitted event is about cache change and not about observers.\n * Useful for persist, where we only want to trigger save when cache is changed.\n * @param eventType - The type of the emitted event.\n * @returns `true` if the event is `'added'`, `'removed'`, or `'updated'`.\n */\nfunction isCacheEventType(eventType: NotifyEventType) {\n return cacheEventTypes.includes(eventType)\n}\n\n/**\n * Restores persisted data to the QueryCache.\n * - data obtained from persister.restoreClient.\n * - data is hydrated using hydrateOptions.\n * If data is expired, busted, empty, or throws, it runs persister.removeClient.\n * @param options - The `queryClient` to restore into, the `persister`, and the `maxAge`, `buster`,\n * and `hydrateOptions` that decide whether and how the persisted data is restored.\n * @returns A promise that resolves once the data is restored or removed. If restoring throws, it\n * attempts to remove the persisted data and then rejects with the restore error, or with the removal\n * error if the removal fails too.\n */\nexport async function persistQueryClientRestore({\n queryClient,\n persister,\n maxAge = 24 * 60 * 60 * 1000,\n buster = '',\n hydrateOptions,\n}: PersistedQueryClientRestoreOptions) {\n try {\n const persistedClient = await persister.restoreClient()\n\n if (persistedClient) {\n if (persistedClient.timestamp) {\n const expired = Date.now() - persistedClient.timestamp > maxAge\n const busted = persistedClient.buster !== buster\n if (expired || busted) {\n return persister.removeClient()\n } else {\n hydrate(queryClient, persistedClient.clientState, hydrateOptions)\n }\n } else {\n return persister.removeClient()\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(err)\n console.warn(\n 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',\n )\n }\n\n await persister.removeClient()\n\n throw err\n }\n}\n\n/**\n * Persists data from the QueryCache.\n * - data dehydrated using dehydrateOptions.\n * - data is persisted using persister.persistClient.\n * @param options - The `queryClient` to persist, the `persister`, the `buster`, and the\n * `dehydrateOptions`.\n */\nexport async function persistQueryClientSave({\n queryClient,\n persister,\n buster = '',\n dehydrateOptions,\n}: PersistedQueryClientSaveOptions) {\n const persistClient: PersistedClient = {\n buster,\n timestamp: Date.now(),\n clientState: dehydrate(queryClient, dehydrateOptions),\n }\n\n await persister.persistClient(persistClient)\n}\n\n/**\n * Subscribe to QueryCache and MutationCache updates (for persisting).\n * @param props - The `queryClient` to monitor, the `persister`, the `buster`, and the\n * `dehydrateOptions` used for each save.\n * @returns an unsubscribe function (to discontinue monitoring)\n */\nexport function persistQueryClientSubscribe(\n props: PersistedQueryClientSaveOptions,\n) {\n const unsubscribeQueryCache = props.queryClient\n .getQueryCache()\n .subscribe((event) => {\n if (isCacheEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n const unsubscribeMutationCache = props.queryClient\n .getMutationCache()\n .subscribe((event) => {\n if (isCacheEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n return () => {\n unsubscribeQueryCache()\n unsubscribeMutationCache()\n }\n}\n\n/**\n * Restores persisted data to QueryCache and persists further changes.\n * @param props - The options for both restoring and saving.\n * @returns A tuple of a function that stops persisting, and a promise that resolves once the\n * restore is done.\n */\nexport function persistQueryClient(\n props: PersistQueryClientOptions,\n): [() => void, Promise<void>] {\n let hasUnsubscribed = false\n let persistQueryClientUnsubscribe: (() => void) | undefined\n const unsubscribe = () => {\n hasUnsubscribed = true\n persistQueryClientUnsubscribe?.()\n }\n\n // Attempt restore\n const restorePromise = persistQueryClientRestore(props).then(() => {\n if (!hasUnsubscribed) {\n // Subscribe to changes in the query cache to trigger the save\n persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)\n }\n })\n\n return [unsubscribe, restorePromise]\n}\n"],"mappings":";;AAqGA,MAAM,kBAA0C;CAAC;CAAS;CAAW;AAAS;;;;;;;AAQ9E,SAAS,iBAAiB,WAA4B;CACpD,OAAO,gBAAgB,SAAS,SAAS;AAC3C;;;;;;;;;;;;AAaA,eAAsB,0BAA0B,EAC9C,aACA,WACA,SAAS,OACT,SAAS,IACT,kBACqC;CACrC,IAAI;EACF,MAAM,kBAAkB,MAAM,UAAU,cAAc;EAEtD,IAAI,iBAAiB;GACnB,IAAI,gBAAgB,WAAW;IAC7B,MAAM,UAAU,KAAK,IAAI,IAAI,gBAAgB,YAAY;IACzD,MAAM,SAAS,gBAAgB,WAAW;IAC1C,IAAI,WAAW,QACb,OAAO,UAAU,aAAa;SAE9B,QAAQ,aAAa,gBAAgB,aAAa,cAAc;GAEpE,OACE,OAAO,UAAU,aAAa;EAElC;CACF,SAAS,KAAK;EACZ,IAAI,QAAQ,IAAI,aAAa,cAAc;GACzC,QAAQ,MAAM,GAAG;GACjB,QAAQ,KACN,0IACF;EACF;EAEA,MAAM,UAAU,aAAa;EAE7B,MAAM;CACR;AACF;;;;;;;;AASA,eAAsB,uBAAuB,EAC3C,aACA,WACA,SAAS,IACT,oBACkC;CAClC,MAAM,gBAAiC;EACrC;EACA,WAAW,KAAK,IAAI;EACpB,aAAa,UAAU,aAAa,gBAAgB;CACtD;CAEA,MAAM,UAAU,cAAc,aAAa;AAC7C;;;;;;;AAQA,SAAgB,4BACd,OACA;CACA,MAAM,wBAAwB,MAAM,YACjC,cAAc,CAAC,CACf,WAAW,UAAU;EACpB,IAAI,iBAAiB,MAAM,IAAI,GAC7B,uBAAuB,KAAK;CAEhC,CAAC;CAEH,MAAM,2BAA2B,MAAM,YACpC,iBAAiB,CAAC,CAClB,WAAW,UAAU;EACpB,IAAI,iBAAiB,MAAM,IAAI,GAC7B,uBAAuB,KAAK;CAEhC,CAAC;CAEH,aAAa;EACX,sBAAsB;EACtB,yBAAyB;CAC3B;AACF;;;;;;;AAQA,SAAgB,mBACd,OAC6B;CAC7B,IAAI,kBAAkB;CACtB,IAAI;CACJ,MAAM,oBAAoB;EACxB,kBAAkB;EAClB,gCAAgC;CAClC;CAUA,OAAO,CAAC,aAPe,0BAA0B,KAAK,CAAC,CAAC,WAAW;EACjE,IAAI,CAAC,iBAEH,gCAAgC,4BAA4B,KAAK;CAErE,CAEkC,CAAC;AACrC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/query-persist-client-core",
3
- "version": "5.104.4",
3
+ "version": "5.105.0",
4
4
  "description": "Set of utilities for interacting with persisters, which can save your queryClient for later use",
5
5
  "author": "tannerlinsley",
6
6
  "license": "MIT",
@@ -40,7 +40,7 @@
40
40
  "!src/__tests__"
41
41
  ],
42
42
  "dependencies": {
43
- "@tanstack/query-core": "5.104.4"
43
+ "@tanstack/query-core": "5.105.0"
44
44
  },
45
45
  "devDependencies": {
46
46
  "@tanstack/query-test-utils": "0.0.0",
@@ -137,7 +137,7 @@ export const PERSISTER_KEY_PREFIX = 'tanstack-query'
137
137
  export function experimental_createQueryPersister<TStorageValue = string>({
138
138
  storage,
139
139
  buster = '',
140
- maxAge = 1000 * 60 * 60 * 24,
140
+ maxAge = 24 * 60 * 60 * 1000,
141
141
  serialize = JSON.stringify as Required<
142
142
  StoragePersisterOptions<TStorageValue>
143
143
  >['serialize'],
@@ -146,7 +146,7 @@ export function experimental_createQueryPersister<TStorageValue = string>({
146
146
  >['deserialize'],
147
147
  prefix = PERSISTER_KEY_PREFIX,
148
148
  refetchOnRestore = true,
149
- filters,
149
+ filters: persistFilters,
150
150
  }: StoragePersisterOptions<TStorageValue>) {
151
151
  /**
152
152
  * Checks whether a persisted query should be discarded.
@@ -280,7 +280,9 @@ export function experimental_createQueryPersister<TStorageValue = string>({
280
280
  ctx: QueryFunctionContext<TQueryKey>,
281
281
  query: Query,
282
282
  ) {
283
- const matchesFilter = filters ? matchQuery(filters, query) : true
283
+ const matchesFilter = persistFilters
284
+ ? matchQuery(persistFilters, query)
285
+ : true
284
286
 
285
287
  // Try to restore only if we do not have any data in the cache and we have persister defined
286
288
  if (matchesFilter && query.state.data === undefined && storage != null) {
package/src/persist.ts CHANGED
@@ -125,7 +125,7 @@ function isCacheEventType(eventType: NotifyEventType) {
125
125
  export async function persistQueryClientRestore({
126
126
  queryClient,
127
127
  persister,
128
- maxAge = 1000 * 60 * 60 * 24,
128
+ maxAge = 24 * 60 * 60 * 1000,
129
129
  buster = '',
130
130
  hydrateOptions,
131
131
  }: PersistedQueryClientRestoreOptions) {