@tanstack/query-core 5.103.2 → 5.103.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (227) hide show
  1. package/build/legacy/{classPrivateFieldSet2-CV7wyte-.js → classPrivateFieldSet2-CukOTU3U.js} +5 -5
  2. package/build/legacy/{classPrivateFieldSet2-Bo0ZyOIv.cjs → classPrivateFieldSet2-CvCEk6bM.cjs} +5 -5
  3. package/build/legacy/{classPrivateMethodInitSpec-CBwa_Y7C.js → classPrivateMethodInitSpec-CgB-WYk3.js} +2 -2
  4. package/build/legacy/{classPrivateMethodInitSpec-DVhcLejn.cjs → classPrivateMethodInitSpec-Nr6mgZRs.cjs} +2 -2
  5. package/build/legacy/focusManager.cjs +1 -1
  6. package/build/legacy/focusManager.d.cts +1 -1
  7. package/build/legacy/focusManager.d.ts +1 -1
  8. package/build/legacy/focusManager.js +1 -1
  9. package/build/legacy/{hydration-Bp57N3SP.d.ts → hydration-B9t5w6NC.d.ts} +11 -4
  10. package/build/legacy/hydration-B9t5w6NC.d.ts.map +1 -0
  11. package/build/{modern/hydration-DRcloXEn.d.cts → legacy/hydration-Br9VIGXa.d.cts} +11 -4
  12. package/build/legacy/hydration-Br9VIGXa.d.cts.map +1 -0
  13. package/build/legacy/hydration.d.cts +1 -1
  14. package/build/legacy/hydration.d.ts +1 -1
  15. package/build/legacy/index.d.cts +1 -1
  16. package/build/legacy/index.d.ts +1 -1
  17. package/build/legacy/infiniteQueryBehavior.d.cts +1 -1
  18. package/build/legacy/infiniteQueryBehavior.d.ts +1 -1
  19. package/build/legacy/infiniteQueryObserver.d.cts +2 -2
  20. package/build/legacy/infiniteQueryObserver.d.ts +2 -2
  21. package/build/legacy/mutation.cjs +2 -2
  22. package/build/legacy/mutation.d.cts +1 -1
  23. package/build/legacy/mutation.d.ts +1 -1
  24. package/build/legacy/mutation.js +2 -2
  25. package/build/legacy/mutationCache.cjs +1 -1
  26. package/build/legacy/mutationCache.d.cts +1 -1
  27. package/build/legacy/mutationCache.d.ts +1 -1
  28. package/build/legacy/mutationCache.js +1 -1
  29. package/build/legacy/mutationObserver.cjs +2 -2
  30. package/build/legacy/mutationObserver.d.cts +1 -1
  31. package/build/legacy/mutationObserver.d.ts +1 -1
  32. package/build/legacy/mutationObserver.js +2 -2
  33. package/build/legacy/onlineManager.cjs +1 -1
  34. package/build/legacy/onlineManager.d.cts +1 -1
  35. package/build/legacy/onlineManager.d.ts +1 -1
  36. package/build/legacy/onlineManager.js +1 -1
  37. package/build/legacy/queriesObserver.cjs +2 -2
  38. package/build/legacy/queriesObserver.d.cts +2 -2
  39. package/build/legacy/queriesObserver.d.cts.map +1 -1
  40. package/build/legacy/queriesObserver.d.ts +2 -2
  41. package/build/legacy/queriesObserver.d.ts.map +1 -1
  42. package/build/legacy/queriesObserver.js +2 -2
  43. package/build/legacy/query.cjs +2 -2
  44. package/build/legacy/query.cjs.map +1 -1
  45. package/build/legacy/query.d.cts +1 -1
  46. package/build/legacy/query.d.ts +1 -1
  47. package/build/legacy/query.js +2 -2
  48. package/build/legacy/query.js.map +1 -1
  49. package/build/legacy/queryCache.cjs +1 -1
  50. package/build/legacy/queryCache.cjs.map +1 -1
  51. package/build/legacy/queryCache.d.cts +1 -1
  52. package/build/legacy/queryCache.d.ts +1 -1
  53. package/build/legacy/queryCache.js +1 -1
  54. package/build/legacy/queryCache.js.map +1 -1
  55. package/build/legacy/queryClient.cjs +8 -1
  56. package/build/legacy/queryClient.cjs.map +1 -1
  57. package/build/legacy/queryClient.d.cts +1 -1
  58. package/build/legacy/queryClient.d.ts +1 -1
  59. package/build/legacy/queryClient.js +8 -1
  60. package/build/legacy/queryClient.js.map +1 -1
  61. package/build/legacy/queryObserver.cjs +2 -2
  62. package/build/legacy/queryObserver.cjs.map +1 -1
  63. package/build/legacy/queryObserver.d.cts +1 -1
  64. package/build/legacy/queryObserver.d.ts +1 -1
  65. package/build/legacy/queryObserver.js +2 -2
  66. package/build/legacy/queryObserver.js.map +1 -1
  67. package/build/legacy/removable-0GzhW1PK.d.cts +22 -0
  68. package/build/legacy/removable-0GzhW1PK.d.cts.map +1 -0
  69. package/build/legacy/removable-0GzhW1PK.d.ts +22 -0
  70. package/build/legacy/removable-0GzhW1PK.d.ts.map +1 -0
  71. package/build/legacy/removable.cjs +10 -1
  72. package/build/legacy/removable.cjs.map +1 -1
  73. package/build/legacy/removable.d.cts +1 -1
  74. package/build/legacy/removable.d.ts +1 -1
  75. package/build/legacy/removable.js +10 -1
  76. package/build/legacy/removable.js.map +1 -1
  77. package/build/legacy/retryer.d.cts +1 -1
  78. package/build/legacy/retryer.d.ts +1 -1
  79. package/build/legacy/streamedQuery.cjs +0 -7
  80. package/build/legacy/streamedQuery.cjs.map +1 -1
  81. package/build/legacy/streamedQuery.d.cts +1 -8
  82. package/build/legacy/streamedQuery.d.cts.map +1 -1
  83. package/build/legacy/streamedQuery.d.ts +1 -8
  84. package/build/legacy/streamedQuery.d.ts.map +1 -1
  85. package/build/legacy/streamedQuery.js +0 -7
  86. package/build/legacy/streamedQuery.js.map +1 -1
  87. package/build/legacy/subscribable-CysQ0tne.d.cts +34 -0
  88. package/build/legacy/subscribable-CysQ0tne.d.cts.map +1 -0
  89. package/build/legacy/subscribable-CysQ0tne.d.ts +34 -0
  90. package/build/legacy/subscribable-CysQ0tne.d.ts.map +1 -0
  91. package/build/legacy/subscribable.cjs +22 -0
  92. package/build/legacy/subscribable.cjs.map +1 -1
  93. package/build/legacy/subscribable.d.cts +1 -1
  94. package/build/legacy/subscribable.d.ts +1 -1
  95. package/build/legacy/subscribable.js +22 -0
  96. package/build/legacy/subscribable.js.map +1 -1
  97. package/build/legacy/timeoutManager.cjs +1 -1
  98. package/build/legacy/timeoutManager.js +1 -1
  99. package/build/legacy/types.cjs.map +1 -1
  100. package/build/legacy/types.d.cts +1 -1
  101. package/build/legacy/types.d.ts +1 -1
  102. package/build/legacy/types.js.map +1 -1
  103. package/build/legacy/utils.d.cts +1 -1
  104. package/build/legacy/utils.d.ts +1 -1
  105. package/build/modern/focusManager.cjs.map +1 -1
  106. package/build/modern/focusManager.d.cts +1 -1
  107. package/build/modern/focusManager.d.ts +1 -1
  108. package/build/modern/focusManager.js.map +1 -1
  109. package/build/{legacy/hydration-DRcloXEn.d.cts → modern/hydration-B9t5w6NC.d.ts} +11 -4
  110. package/build/modern/hydration-B9t5w6NC.d.ts.map +1 -0
  111. package/build/modern/{hydration-Bp57N3SP.d.ts → hydration-Br9VIGXa.d.cts} +11 -4
  112. package/build/modern/hydration-Br9VIGXa.d.cts.map +1 -0
  113. package/build/modern/hydration.d.cts +1 -1
  114. package/build/modern/hydration.d.ts +1 -1
  115. package/build/modern/index.d.cts +1 -1
  116. package/build/modern/index.d.ts +1 -1
  117. package/build/modern/infiniteQueryBehavior.d.cts +1 -1
  118. package/build/modern/infiniteQueryBehavior.d.ts +1 -1
  119. package/build/modern/infiniteQueryObserver.d.cts +2 -2
  120. package/build/modern/infiniteQueryObserver.d.ts +2 -2
  121. package/build/modern/mutation.cjs.map +1 -1
  122. package/build/modern/mutation.d.cts +1 -1
  123. package/build/modern/mutation.d.ts +1 -1
  124. package/build/modern/mutation.js.map +1 -1
  125. package/build/modern/mutationCache.cjs.map +1 -1
  126. package/build/modern/mutationCache.d.cts +1 -1
  127. package/build/modern/mutationCache.d.ts +1 -1
  128. package/build/modern/mutationCache.js.map +1 -1
  129. package/build/modern/mutationObserver.cjs.map +1 -1
  130. package/build/modern/mutationObserver.d.cts +1 -1
  131. package/build/modern/mutationObserver.d.ts +1 -1
  132. package/build/modern/mutationObserver.js.map +1 -1
  133. package/build/modern/onlineManager.cjs.map +1 -1
  134. package/build/modern/onlineManager.d.cts +1 -1
  135. package/build/modern/onlineManager.d.ts +1 -1
  136. package/build/modern/onlineManager.js.map +1 -1
  137. package/build/modern/queriesObserver.cjs.map +1 -1
  138. package/build/modern/queriesObserver.d.cts +2 -2
  139. package/build/modern/queriesObserver.d.cts.map +1 -1
  140. package/build/modern/queriesObserver.d.ts +2 -2
  141. package/build/modern/queriesObserver.d.ts.map +1 -1
  142. package/build/modern/queriesObserver.js.map +1 -1
  143. package/build/modern/query.cjs.map +1 -1
  144. package/build/modern/query.d.cts +1 -1
  145. package/build/modern/query.d.ts +1 -1
  146. package/build/modern/query.js.map +1 -1
  147. package/build/modern/queryCache.cjs.map +1 -1
  148. package/build/modern/queryCache.d.cts +1 -1
  149. package/build/modern/queryCache.d.ts +1 -1
  150. package/build/modern/queryCache.js.map +1 -1
  151. package/build/modern/queryClient.cjs +7 -0
  152. package/build/modern/queryClient.cjs.map +1 -1
  153. package/build/modern/queryClient.d.cts +1 -1
  154. package/build/modern/queryClient.d.ts +1 -1
  155. package/build/modern/queryClient.js +7 -0
  156. package/build/modern/queryClient.js.map +1 -1
  157. package/build/modern/queryObserver.cjs.map +1 -1
  158. package/build/modern/queryObserver.d.cts +1 -1
  159. package/build/modern/queryObserver.d.ts +1 -1
  160. package/build/modern/queryObserver.js.map +1 -1
  161. package/build/modern/removable-0GzhW1PK.d.cts +22 -0
  162. package/build/modern/removable-0GzhW1PK.d.cts.map +1 -0
  163. package/build/modern/removable-0GzhW1PK.d.ts +22 -0
  164. package/build/modern/removable-0GzhW1PK.d.ts.map +1 -0
  165. package/build/modern/removable.cjs +9 -0
  166. package/build/modern/removable.cjs.map +1 -1
  167. package/build/modern/removable.d.cts +1 -1
  168. package/build/modern/removable.d.ts +1 -1
  169. package/build/modern/removable.js +9 -0
  170. package/build/modern/removable.js.map +1 -1
  171. package/build/modern/retryer.d.cts +1 -1
  172. package/build/modern/retryer.d.ts +1 -1
  173. package/build/modern/streamedQuery.cjs +0 -7
  174. package/build/modern/streamedQuery.cjs.map +1 -1
  175. package/build/modern/streamedQuery.d.cts +1 -8
  176. package/build/modern/streamedQuery.d.cts.map +1 -1
  177. package/build/modern/streamedQuery.d.ts +1 -8
  178. package/build/modern/streamedQuery.d.ts.map +1 -1
  179. package/build/modern/streamedQuery.js +0 -7
  180. package/build/modern/streamedQuery.js.map +1 -1
  181. package/build/modern/subscribable-CysQ0tne.d.cts +34 -0
  182. package/build/modern/subscribable-CysQ0tne.d.cts.map +1 -0
  183. package/build/modern/subscribable-CysQ0tne.d.ts +34 -0
  184. package/build/modern/subscribable-CysQ0tne.d.ts.map +1 -0
  185. package/build/modern/subscribable.cjs +22 -0
  186. package/build/modern/subscribable.cjs.map +1 -1
  187. package/build/modern/subscribable.d.cts +1 -1
  188. package/build/modern/subscribable.d.ts +1 -1
  189. package/build/modern/subscribable.js +22 -0
  190. package/build/modern/subscribable.js.map +1 -1
  191. package/build/modern/timeoutManager.cjs.map +1 -1
  192. package/build/modern/timeoutManager.js.map +1 -1
  193. package/build/modern/types.cjs.map +1 -1
  194. package/build/modern/types.d.cts +1 -1
  195. package/build/modern/types.d.ts +1 -1
  196. package/build/modern/types.js.map +1 -1
  197. package/build/modern/utils.d.cts +1 -1
  198. package/build/modern/utils.d.ts +1 -1
  199. package/package.json +3 -3
  200. package/src/query.ts +1 -2
  201. package/src/queryCache.ts +1 -2
  202. package/src/queryClient.ts +7 -0
  203. package/src/queryObserver.ts +4 -8
  204. package/src/removable.ts +9 -0
  205. package/src/streamedQuery.ts +0 -7
  206. package/src/subscribable.ts +22 -0
  207. package/src/types.ts +9 -15
  208. package/build/legacy/hydration-Bp57N3SP.d.ts.map +0 -1
  209. package/build/legacy/hydration-DRcloXEn.d.cts.map +0 -1
  210. package/build/legacy/removable-DeMjhW5M.d.cts +0 -13
  211. package/build/legacy/removable-DeMjhW5M.d.cts.map +0 -1
  212. package/build/legacy/removable-DeMjhW5M.d.ts +0 -13
  213. package/build/legacy/removable-DeMjhW5M.d.ts.map +0 -1
  214. package/build/legacy/subscribable-CbifVTKz.d.cts +0 -12
  215. package/build/legacy/subscribable-CbifVTKz.d.cts.map +0 -1
  216. package/build/legacy/subscribable-CbifVTKz.d.ts +0 -12
  217. package/build/legacy/subscribable-CbifVTKz.d.ts.map +0 -1
  218. package/build/modern/hydration-Bp57N3SP.d.ts.map +0 -1
  219. package/build/modern/hydration-DRcloXEn.d.cts.map +0 -1
  220. package/build/modern/removable-DeMjhW5M.d.cts +0 -13
  221. package/build/modern/removable-DeMjhW5M.d.cts.map +0 -1
  222. package/build/modern/removable-DeMjhW5M.d.ts +0 -13
  223. package/build/modern/removable-DeMjhW5M.d.ts.map +0 -1
  224. package/build/modern/subscribable-CbifVTKz.d.cts +0 -12
  225. package/build/modern/subscribable-CbifVTKz.d.cts.map +0 -1
  226. package/build/modern/subscribable-CbifVTKz.d.ts +0 -12
  227. package/build/modern/subscribable-CbifVTKz.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"queryObserver.cjs","names":["Subscribable","#client","#selectError","#currentQuery","#executeFetch","#updateTimers","#clearStaleTimeout","#clearRefetchInterval","resolveQueryValue","#updateQuery","shallowEqualObjects","#updateStaleTimeout","#computeRefetchInterval","#currentRefetchInterval","#updateRefetchInterval","#currentResult","#currentResultOptions","#currentResultState","#trackedProps","noop","isServerEnvironment","isValidTimeout","#shouldScheduleTimer","timeUntilStale","#staleTimeoutId","timeoutManager","#refetchIntervalId","focusManager","#currentQueryInitialState","fetchState","#lastQueryWithDefinedData","replaceData","#selectFn","#selectResult"],"sources":["../../src/queryObserver.ts"],"sourcesContent":["import { focusManager } from './focusManager'\nimport { isServer as isServerEnvironment } from './environmentManager'\nimport { notifyManager } from './notifyManager'\nimport { fetchState } from './query'\nimport { Subscribable } from './subscribable'\nimport {\n isValidTimeout,\n noop,\n replaceData,\n resolveQueryValue,\n shallowEqualObjects,\n timeUntilStale,\n} from './utils'\nimport { timeoutManager } from './timeoutManager'\nimport type { ManagedTimerId } from './timeoutManager'\nimport type { FetchOptions, Query, QueryState } from './query'\nimport type { QueryClient } from './queryClient'\nimport type {\n DefaultError,\n DefaultedQueryObserverOptions,\n PlaceholderDataFunction,\n QueryKey,\n QueryObserverBaseResult,\n QueryObserverOptions,\n QueryObserverResult,\n RefetchOptions,\n} from './types'\n\ntype QueryObserverListener<TData, TError> = (\n result: QueryObserverResult<TData, TError>,\n) => void\n\ninterface ObserverFetchOptions extends FetchOptions {\n throwOnError?: boolean\n}\n\n/**\n * A `QueryObserver` watches a single query in the `QueryCache` and computes a\n * `QueryObserverResult` from its state, recomputing and notifying subscribers\n * whenever the underlying query (or the observer's options) changes. It is\n * the primitive that framework adapters (e.g. `useQuery`) build their hooks\n * on top of, but it can also be used directly to observe and switch between\n * queries outside of any framework.\n *\n * @example\n * ```ts\n * const observer = new QueryObserver(queryClient, {\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * })\n *\n * const unsubscribe = observer.subscribe((result) => {\n * console.log(result.data)\n * })\n * ```\n */\nexport class QueryObserver<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> extends Subscribable<QueryObserverListener<TData, TError>> {\n #client: QueryClient\n #currentQuery: Query<TQueryFnData, TError, TQueryData, TQueryKey> = undefined!\n #currentQueryInitialState: QueryState<TQueryData, TError> = undefined!\n #currentResult: QueryObserverResult<TData, TError> = undefined!\n #currentResultState?: QueryState<TQueryData, TError>\n #currentResultOptions?: QueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >\n #selectError: TError | null\n #selectFn?: (data: TQueryData) => TData\n #selectResult?: TData\n // This property keeps track of the last query with defined data.\n // It will be used to pass the previous data and query to the placeholder function between renders.\n #lastQueryWithDefinedData?: Query<TQueryFnData, TError, TQueryData, TQueryKey>\n #staleTimeoutId?: ManagedTimerId\n #refetchIntervalId?: ManagedTimerId\n #currentRefetchInterval?: number | false\n #trackedProps = new Set<keyof QueryObserverResult>()\n\n constructor(\n client: QueryClient,\n public options: QueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n ) {\n super()\n\n this.#client = client\n this.#selectError = null\n\n this.bindMethods()\n this.setOptions(options)\n }\n\n protected bindMethods(): void {\n this.refetch = this.refetch.bind(this)\n }\n\n protected onSubscribe(): void {\n if (this.listeners.size === 1) {\n this.#currentQuery.addObserver(this)\n\n if (shouldFetchOnMount(this.#currentQuery, this.options)) {\n this.#executeFetch()\n } else {\n this.updateResult()\n }\n\n this.#updateTimers()\n }\n }\n\n protected onUnsubscribe(): void {\n if (!this.hasListeners()) {\n this.destroy()\n }\n }\n\n /**\n * Returns whether the observed query is currently stale and configured\n * (via the `refetchOnReconnect` option) to refetch when the network\n * reconnects.\n */\n shouldFetchOnReconnect(): boolean {\n return shouldFetchOn(\n this.#currentQuery,\n this.options,\n this.options.refetchOnReconnect,\n )\n }\n\n /**\n * Returns whether the observed query is currently stale and configured\n * (via the `refetchOnWindowFocus` option) to refetch when the window\n * regains focus.\n */\n shouldFetchOnWindowFocus(): boolean {\n return shouldFetchOn(\n this.#currentQuery,\n this.options,\n this.options.refetchOnWindowFocus,\n )\n }\n\n /**\n * Stops observing the current query: clears all listeners, cancels the\n * stale and refetch-interval timers, and removes this observer from the\n * query it was observing.\n */\n destroy(): void {\n this.listeners = new Set()\n this.#clearStaleTimeout()\n this.#clearRefetchInterval()\n this.#currentQuery.removeObserver(this)\n }\n\n /**\n * Updates the observer's options. This will re-resolve the query being\n * observed (switching to a different query if the `queryKey` changed),\n * trigger a fetch if the new options require one and the observer has\n * subscribers, recompute the current result, and reschedule the stale and\n * refetch-interval timers as needed.\n *\n * @example\n * ```ts\n * observer.setOptions({ queryKey: ['posts', 1], queryFn: () => fetchPost(1) })\n * // later: switch to a different query, reusing the same observer\n * observer.setOptions({ queryKey: ['posts', 2], queryFn: () => fetchPost(2) })\n * ```\n */\n setOptions(\n options: QueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n ): void {\n const prevOptions = this.options\n const prevQuery = this.#currentQuery\n\n this.options = this.#client.defaultQueryOptions(options)\n\n if (\n this.options.enabled !== undefined &&\n typeof this.options.enabled !== 'boolean' &&\n typeof this.options.enabled !== 'function' &&\n typeof resolveQueryValue(this.options.enabled, this.#currentQuery) !==\n 'boolean'\n ) {\n throw new Error(\n 'Expected enabled to be a boolean or a callback that returns a boolean',\n )\n }\n\n this.#updateQuery()\n this.#currentQuery.setOptions(this.options)\n\n if (\n prevOptions._defaulted &&\n !shallowEqualObjects(this.options, prevOptions)\n ) {\n this.#client.getQueryCache().notify({\n type: 'observerOptionsUpdated',\n query: this.#currentQuery,\n observer: this,\n })\n }\n\n const mounted = this.hasListeners()\n\n // Fetch if there are subscribers\n if (\n mounted &&\n shouldFetchOptionally(\n this.#currentQuery,\n prevQuery,\n this.options,\n prevOptions,\n )\n ) {\n this.#executeFetch()\n }\n\n // Update result\n this.updateResult()\n\n // Update stale interval if needed\n if (\n mounted &&\n (this.#currentQuery !== prevQuery ||\n resolveQueryValue(this.options.enabled, this.#currentQuery) !==\n resolveQueryValue(prevOptions.enabled, this.#currentQuery) ||\n resolveQueryValue(this.options.staleTime, this.#currentQuery) !==\n resolveQueryValue(prevOptions.staleTime, this.#currentQuery))\n ) {\n this.#updateStaleTimeout()\n }\n\n const nextRefetchInterval = this.#computeRefetchInterval()\n\n // Update refetch interval if needed\n if (\n mounted &&\n (this.#currentQuery !== prevQuery ||\n resolveQueryValue(this.options.enabled, this.#currentQuery) !==\n resolveQueryValue(prevOptions.enabled, this.#currentQuery) ||\n nextRefetchInterval !== this.#currentRefetchInterval)\n ) {\n this.#updateRefetchInterval(nextRefetchInterval)\n }\n }\n\n /**\n * Computes the result the observer would produce for the given (already-defaulted) options\n * right now, building the underlying `Query` if it doesn't exist yet, without waiting for a\n * subscription callback. Called by framework adapters on every render (e.g. `useQuery`) so the\n * returned value is available synchronously, ahead of `setOptions` triggering an actual fetch.\n */\n getOptimisticResult(\n options: DefaultedQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n ): QueryObserverResult<TData, TError> {\n const query = this.#client.getQueryCache().build(this.#client, options)\n\n const result = this.createResult(query, options)\n\n if (!shallowEqualObjects(this.getCurrentResult(), result)) {\n // this assigns the optimistic result to the current Observer\n // because if the query function changes, useQuery will be performing\n // an effect where it would fetch again.\n // When the fetch finishes, we perform a deep data cloning in order\n // to reuse objects references. This deep data clone is performed against\n // the `observer.currentResult.data` property\n // When QueryKey changes, we refresh the query and get new `optimistic`\n // result, while we leave the `observer.currentResult`, so when new data\n // arrives, it finds the old `observer.currentResult` which is related\n // to the old QueryKey. Which means that currentResult and selectData are\n // out of sync already.\n // To solve this, we move the cursor of the currentResult every time\n // an observer reads an optimistic value.\n\n // When keeping the previous data, the result doesn't change until new\n // data arrives.\n this.#currentResult = result\n this.#currentResultOptions = this.options\n this.#currentResultState = this.#currentQuery.state\n }\n return result\n }\n\n /**\n * Returns the most recently computed `QueryObserverResult` for the\n * observed query. This is a point-in-time read; to be notified of updates\n * as they happen, subscribe to the observer instead (its inherited\n * `subscribe` method).\n *\n * @example\n * ```ts\n * const result = observer.getCurrentResult()\n * console.log(result.status, result.data)\n * ```\n */\n getCurrentResult(): QueryObserverResult<TData, TError> {\n return this.#currentResult\n }\n\n /**\n * Wraps a `QueryObserverResult` in a `Proxy` that records which properties are read, via\n * {@link QueryObserver#trackProp} (and an optional `onPropTracked` callback). Used by framework\n * adapters when `notifyOnChangeProps` is not set, to implement its default \"only re-render on\n * properties you actually read\" behavior.\n */\n trackResult(\n result: QueryObserverResult<TData, TError>,\n onPropTracked?: (key: keyof QueryObserverResult) => void,\n ): QueryObserverResult<TData, TError> {\n return new Proxy(result, {\n get: (target, key) => {\n this.trackProp(key as keyof QueryObserverResult)\n onPropTracked?.(key as keyof QueryObserverResult)\n return Reflect.get(target, key)\n },\n })\n }\n\n /**\n * Records that the given `QueryObserverResult` property was read, so a subsequent update only\n * notifies this observer if a tracked property actually changed. Normally called indirectly via\n * {@link QueryObserver#trackResult}'s proxy; exposed directly for adapters that track property\n * access themselves (e.g. through their own reactivity system) instead of via the proxy.\n */\n trackProp(key: keyof QueryObserverResult) {\n this.#trackedProps.add(key)\n }\n\n /**\n * Returns the `Query` instance this observer is currently observing.\n */\n getCurrentQuery(): Query<TQueryFnData, TError, TQueryData, TQueryKey> {\n return this.#currentQuery\n }\n\n /**\n * Refetches the observed query and returns a promise that resolves with\n * the resulting `QueryObserverResult`.\n *\n * @example\n * ```ts\n * const result = await observer.refetch({ cancelRefetch: false })\n * console.log(result.data)\n * ```\n */\n refetch({ ...options }: RefetchOptions = {}): Promise<\n QueryObserverResult<TData, TError>\n > {\n return this.fetch({\n ...options,\n })\n }\n\n /**\n * Fetches a query defined by the given options without affecting this\n * observer's own tracked query or result, and returns a promise that\n * resolves with the `QueryObserverResult` for that fetch. This is useful\n * for prefetching data that another observer (e.g. a query about to be\n * navigated to) will need, ahead of time.\n *\n * @example\n * ```ts\n * const result = await observer.fetchOptimistic({\n * queryKey: ['posts', 2],\n * queryFn: () => fetchPost(2),\n * })\n * console.log(result.data)\n * ```\n */\n fetchOptimistic(\n options: QueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n ): Promise<QueryObserverResult<TData, TError>> {\n const defaultedOptions = this.#client.defaultQueryOptions(options)\n\n const query = this.#client\n .getQueryCache()\n .build(this.#client, defaultedOptions)\n\n let unsubscribe = () => {}\n let resolveEarly:\n | ((result: QueryObserverResult<TData, TError>) => void)\n | undefined\n\n const cachePromise = new Promise<QueryObserverResult<TData, TError>>(\n (resolve) => {\n resolveEarly = resolve\n unsubscribe = this.#client.getQueryCache().subscribe((event) => {\n if (\n event.type === 'updated' &&\n event.query.queryHash === query.queryHash &&\n query.state.data !== undefined\n ) {\n unsubscribe()\n resolve(this.createResult(query, defaultedOptions))\n }\n })\n },\n )\n\n return Promise.race([\n query\n .fetch()\n .then(() => {\n const result = this.createResult(query, defaultedOptions)\n // Settle the subscriber promise so both branches always settle.\n // This value is ignored by Promise.race since the fetch branch already won.\n resolveEarly?.(result)\n return result\n })\n .finally(() => {\n unsubscribe()\n }),\n cachePromise,\n ])\n }\n\n protected fetch(\n fetchOptions: ObserverFetchOptions,\n ): Promise<QueryObserverResult<TData, TError>> {\n return this.#executeFetch({\n ...fetchOptions,\n cancelRefetch: fetchOptions.cancelRefetch ?? true,\n }).then(() => {\n this.updateResult()\n return this.#currentResult\n })\n }\n\n #executeFetch(\n fetchOptions?: Omit<ObserverFetchOptions, 'initialPromise'>,\n ): Promise<TQueryData | undefined> {\n // Make sure we reference the latest query as the current one might have been removed\n this.#updateQuery()\n\n // Fetch\n let promise: Promise<TQueryData | undefined> = this.#currentQuery.fetch(\n this.options,\n fetchOptions,\n )\n\n if (!fetchOptions?.throwOnError) {\n promise = promise.catch(noop)\n }\n\n return promise\n }\n\n #shouldScheduleTimer(timeout: unknown): timeout is number {\n return (\n !isServerEnvironment() &&\n resolveQueryValue(this.options.enabled, this.#currentQuery) !== false &&\n isValidTimeout(timeout)\n )\n }\n\n #updateStaleTimeout(): void {\n this.#clearStaleTimeout()\n const staleTime = resolveQueryValue(\n this.options.staleTime,\n this.#currentQuery,\n )\n\n if (this.#currentResult.isStale || !this.#shouldScheduleTimer(staleTime)) {\n return\n }\n\n const time = timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime)\n\n // The timeout is sometimes triggered 1 ms before the stale time expiration.\n // To mitigate this issue we always add 1 ms to the timeout.\n const timeout = time + 1\n\n this.#staleTimeoutId = timeoutManager.setTimeout(() => {\n if (!this.#currentResult.isStale) {\n this.updateResult()\n }\n }, timeout)\n }\n\n #computeRefetchInterval() {\n return (\n resolveQueryValue(this.options.refetchInterval, this.#currentQuery) ??\n false\n )\n }\n\n #updateRefetchInterval(nextInterval: number | false): void {\n this.#clearRefetchInterval()\n\n this.#currentRefetchInterval = nextInterval\n\n if (\n this.#currentRefetchInterval === 0 ||\n !this.#shouldScheduleTimer(this.#currentRefetchInterval)\n ) {\n return\n }\n\n this.#refetchIntervalId = timeoutManager.setInterval(() => {\n if (\n this.options.refetchIntervalInBackground ||\n focusManager.isFocused()\n ) {\n this.#executeFetch()\n }\n }, this.#currentRefetchInterval)\n }\n\n #updateTimers(): void {\n this.#updateStaleTimeout()\n this.#updateRefetchInterval(this.#computeRefetchInterval())\n }\n\n #clearStaleTimeout(): void {\n if (this.#staleTimeoutId !== undefined) {\n timeoutManager.clearTimeout(this.#staleTimeoutId)\n this.#staleTimeoutId = undefined\n }\n }\n\n #clearRefetchInterval(): void {\n if (this.#refetchIntervalId !== undefined) {\n timeoutManager.clearInterval(this.#refetchIntervalId)\n this.#refetchIntervalId = undefined\n }\n }\n\n protected createResult(\n query: Query<TQueryFnData, TError, TQueryData, TQueryKey>,\n options: QueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n ): QueryObserverResult<TData, TError> {\n const prevQuery = this.#currentQuery\n const prevOptions = this.options\n const prevResult = this.#currentResult as\n | QueryObserverResult<TData, TError>\n | undefined\n const prevResultState = this.#currentResultState\n const prevResultOptions = this.#currentResultOptions\n const queryChange = query !== prevQuery\n const queryInitialState = queryChange\n ? query.state\n : this.#currentQueryInitialState\n\n const { state } = query\n let newState = { ...state }\n let isPlaceholderData = false\n let data: TData | undefined\n\n // Optimistically set result in fetching state if needed\n if (options._optimisticResults) {\n const mounted = this.hasListeners()\n\n const fetchOnMount = !mounted && shouldFetchOnMount(query, options)\n\n const fetchOptionally =\n mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions)\n\n if (fetchOnMount || fetchOptionally) {\n newState = {\n ...newState,\n ...fetchState(state.data, query.options),\n }\n }\n if (options._optimisticResults === 'isRestoring') {\n newState.fetchStatus = 'idle'\n }\n }\n\n let { error, errorUpdatedAt, status } = newState\n\n // Per default, use query data\n data = newState.data as unknown as TData\n let skipSelect = false\n\n // use placeholderData if needed\n if (\n options.placeholderData !== undefined &&\n data === undefined &&\n status === 'pending'\n ) {\n let placeholderData\n\n // Memoize placeholder data\n if (\n prevResult?.isPlaceholderData &&\n options.placeholderData === prevResultOptions?.placeholderData\n ) {\n placeholderData = prevResult.data\n // we have to skip select when reading this memoization\n // because prevResult.data is already \"selected\"\n skipSelect = true\n } else {\n // compute placeholderData\n placeholderData =\n typeof options.placeholderData === 'function'\n ? (\n options.placeholderData as unknown as PlaceholderDataFunction<TQueryData>\n )(\n this.#lastQueryWithDefinedData?.state.data,\n this.#lastQueryWithDefinedData as any,\n )\n : options.placeholderData\n }\n\n if (placeholderData !== undefined) {\n status = 'success'\n data = replaceData(\n prevResult?.data,\n placeholderData as unknown,\n options,\n ) as TData\n isPlaceholderData = true\n }\n }\n\n // Select data if needed\n // this also runs placeholderData through the select function\n if (options.select && data !== undefined && !skipSelect) {\n // Memoize select result\n if (\n prevResult &&\n data === prevResultState?.data &&\n options.select === this.#selectFn\n ) {\n data = this.#selectResult\n } else {\n try {\n this.#selectFn = options.select\n data = options.select(data as any)\n data = replaceData(prevResult?.data, data, options)\n this.#selectResult = data\n this.#selectError = null\n } catch (selectError) {\n this.#selectError = selectError as TError\n }\n }\n } else if (data === undefined) {\n // a stored select error belongs to previously selected data; once that\n // data is gone (query switch or reset), it must not leak into this result\n this.#selectError = null\n }\n\n if (this.#selectError) {\n error = this.#selectError\n data = this.#selectResult\n errorUpdatedAt = Date.now()\n status = 'error'\n isPlaceholderData = false\n }\n\n const isFetching = newState.fetchStatus === 'fetching'\n const isPending = status === 'pending'\n const isError = status === 'error'\n\n const isLoading = isPending && isFetching\n const hasData = data !== undefined\n\n const result: QueryObserverBaseResult<TData, TError> = {\n status,\n fetchStatus: newState.fetchStatus,\n isPending,\n isSuccess: status === 'success',\n isError,\n isInitialLoading: isLoading,\n isLoading,\n data,\n dataUpdatedAt: newState.dataUpdatedAt,\n error,\n errorUpdatedAt,\n failureCount: newState.fetchFailureCount,\n failureReason: newState.fetchFailureReason,\n errorUpdateCount: newState.errorUpdateCount,\n isFetched: query.isFetched(),\n isFetchedAfterMount:\n newState.dataUpdateCount > queryInitialState.dataUpdateCount ||\n newState.errorUpdateCount > queryInitialState.errorUpdateCount,\n isFetching,\n isRefetching: isFetching && !isPending,\n isLoadingError: isError && !hasData,\n isPaused: newState.fetchStatus === 'paused',\n isPlaceholderData,\n isRefetchError: isError && hasData,\n isStale: isStale(query, options),\n refetch: this.refetch,\n isEnabled: resolveQueryValue(options.enabled, query) !== false,\n }\n\n const nextResult = result as QueryObserverResult<TData, TError>\n\n return nextResult\n }\n\n /**\n * Recomputes and stores the current result from the current query/options, notifying listeners\n * if it changed. Framework adapters call this right after subscribing to make sure no query\n * update was missed in the gap between creating the observer and subscribing to it.\n */\n updateResult(): void {\n const prevResult = this.#currentResult as\n | QueryObserverResult<TData, TError>\n | undefined\n\n const nextResult = this.createResult(this.#currentQuery, this.options)\n\n this.#currentResultState = this.#currentQuery.state\n this.#currentResultOptions = this.options\n\n if (this.#currentResultState.data !== undefined) {\n this.#lastQueryWithDefinedData = this.#currentQuery\n }\n\n // Only notify and update result if something has changed\n if (shallowEqualObjects(nextResult, prevResult)) {\n return\n }\n\n this.#currentResult = nextResult\n\n const shouldNotifyListeners = (): boolean => {\n if (!prevResult) {\n return true\n }\n\n const { notifyOnChangeProps } = this.options\n const notifyOnChangePropsValue =\n typeof notifyOnChangeProps === 'function'\n ? notifyOnChangeProps()\n : notifyOnChangeProps\n\n if (\n notifyOnChangePropsValue === 'all' ||\n (!notifyOnChangePropsValue && !this.#trackedProps.size)\n ) {\n return true\n }\n\n const includedProps = new Set(\n notifyOnChangePropsValue ?? this.#trackedProps,\n )\n\n if (this.options.throwOnError) {\n includedProps.add('error')\n }\n\n return Object.keys(this.#currentResult).some((key) => {\n const typedKey = key as keyof QueryObserverResult\n const changed = this.#currentResult[typedKey] !== prevResult[typedKey]\n\n return changed && includedProps.has(typedKey)\n })\n }\n\n const notifyListeners = shouldNotifyListeners()\n\n notifyManager.batch(() => {\n // First, trigger the listeners\n if (notifyListeners) {\n this.listeners.forEach((listener) => {\n listener(this.#currentResult)\n })\n }\n\n // Then the cache listeners\n this.#client.getQueryCache().notify({\n query: this.#currentQuery,\n type: 'observerResultsUpdated',\n })\n })\n }\n\n #updateQuery(): void {\n const query = this.#client.getQueryCache().build(this.#client, this.options)\n\n if (query === this.#currentQuery) {\n return\n }\n\n const prevQuery = this.#currentQuery as\n | Query<TQueryFnData, TError, TQueryData, TQueryKey>\n | undefined\n this.#currentQuery = query\n this.#currentQueryInitialState = query.state\n\n if (this.hasListeners()) {\n prevQuery?.removeObserver(this)\n query.addObserver(this)\n }\n }\n\n /** @internal */\n onQueryUpdate(): void {\n this.updateResult()\n\n if (this.hasListeners()) {\n this.#updateTimers()\n }\n }\n}\n\nfunction shouldLoadOnMount(\n query: Query<any, any, any, any>,\n options: QueryObserverOptions<any, any, any, any>,\n): boolean {\n return (\n resolveQueryValue(options.enabled, query) !== false &&\n query.state.data === undefined &&\n !(\n query.state.status === 'error' &&\n resolveQueryValue(options.retryOnMount, query) === false\n )\n )\n}\n\nfunction shouldFetchOnMount(\n query: Query<any, any, any, any>,\n options: QueryObserverOptions<any, any, any, any, any>,\n): boolean {\n return (\n shouldLoadOnMount(query, options) ||\n (query.state.data !== undefined &&\n shouldFetchOn(query, options, options.refetchOnMount))\n )\n}\n\nfunction shouldFetchOn(\n query: Query<any, any, any, any>,\n options: QueryObserverOptions<any, any, any, any, any>,\n field: (typeof options)['refetchOnMount'] &\n (typeof options)['refetchOnWindowFocus'] &\n (typeof options)['refetchOnReconnect'],\n) {\n if (\n resolveQueryValue(options.enabled, query) !== false &&\n resolveQueryValue(options.staleTime, query) !== 'static'\n ) {\n const value = resolveQueryValue(field, query)\n\n return value === 'always' || (value !== false && isStale(query, options))\n }\n return false\n}\n\nfunction shouldFetchOptionally(\n query: Query<any, any, any, any>,\n prevQuery: Query<any, any, any, any>,\n options: QueryObserverOptions<any, any, any, any, any>,\n prevOptions: QueryObserverOptions<any, any, any, any, any>,\n): boolean {\n return (\n (query !== prevQuery ||\n resolveQueryValue(prevOptions.enabled, query) === false) &&\n (!options.suspense || query.state.status !== 'error') &&\n isStale(query, options)\n )\n}\n\nfunction isStale(\n query: Query<any, any, any, any>,\n options: QueryObserverOptions<any, any, any, any, any>,\n): boolean {\n return (\n resolveQueryValue(options.enabled, query) !== false &&\n query.isStaleByTime(resolveQueryValue(options.staleTime, query))\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,IAAa,gBAAb,cAMUA,qBAAAA,aAAmD;CAC3D;CACA,gBAAoE,KAAA;CACpE,4BAA4D,KAAA;CAC5D,iBAAqD,KAAA;CACrD;CACA;CAOA;CACA;CACA;CAGA;CACA;CACA;CACA;CACA,gCAAgB,IAAI,IAA+B;CAEnD,YACE,QACA,SAOA;EACA,MAAM;EARC,KAAA,UAAA;EAUP,KAAKC,UAAU;EACf,KAAKC,eAAe;EAEpB,KAAK,YAAY;EACjB,KAAK,WAAW,OAAO;CACzB;CAEA,cAA8B;EAC5B,KAAK,UAAU,KAAK,QAAQ,KAAK,IAAI;CACvC;CAEA,cAA8B;EAC5B,IAAI,KAAK,UAAU,SAAS,GAAG;GAC7B,KAAKC,cAAc,YAAY,IAAI;GAEnC,IAAI,mBAAmB,KAAKA,eAAe,KAAK,OAAO,GACrD,KAAKC,cAAc;QAEnB,KAAK,aAAa;GAGpB,KAAKC,cAAc;EACrB;CACF;CAEA,gBAAgC;EAC9B,IAAI,CAAC,KAAK,aAAa,GACrB,KAAK,QAAQ;CAEjB;;;;;;CAOA,yBAAkC;EAChC,OAAO,cACL,KAAKF,eACL,KAAK,SACL,KAAK,QAAQ,kBACf;CACF;;;;;;CAOA,2BAAoC;EAClC,OAAO,cACL,KAAKA,eACL,KAAK,SACL,KAAK,QAAQ,oBACf;CACF;;;;;;CAOA,UAAgB;EACd,KAAK,4BAAY,IAAI,IAAI;EACzB,KAAKG,mBAAmB;EACxB,KAAKC,sBAAsB;EAC3B,KAAKJ,cAAc,eAAe,IAAI;CACxC;;;;;;;;;;;;;;;CAgBA,WACE,SAOM;EACN,MAAM,cAAc,KAAK;EACzB,MAAM,YAAY,KAAKA;EAEvB,KAAK,UAA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AS,KAAK,MAAM,SAC9C,MAAM,cAAcA,cAAAA,kBAAkB,QAAQ,WAAW,KAAK,CAAC;AAEnE"}
1
+ {"version":3,"file":"queryObserver.cjs","names":["Subscribable","resolveQueryValue","shallowEqualObjects","noop","isServerEnvironment","isValidTimeout","timeUntilStale","timeoutManager","focusManager","fetchState","replaceData"],"sources":["../../src/queryObserver.ts"],"sourcesContent":["import { focusManager } from './focusManager'\nimport { isServer as isServerEnvironment } from './environmentManager'\nimport { notifyManager } from './notifyManager'\nimport { fetchState } from './query'\nimport { Subscribable } from './subscribable'\nimport {\n isValidTimeout,\n noop,\n replaceData,\n resolveQueryValue,\n shallowEqualObjects,\n timeUntilStale,\n} from './utils'\nimport { timeoutManager } from './timeoutManager'\nimport type { ManagedTimerId } from './timeoutManager'\nimport type { FetchOptions, Query, QueryState } from './query'\nimport type { QueryClient } from './queryClient'\nimport type {\n DefaultError,\n DefaultedQueryObserverOptions,\n PlaceholderDataFunction,\n QueryKey,\n QueryObserverBaseResult,\n QueryObserverOptions,\n QueryObserverResult,\n RefetchOptions,\n} from './types'\n\ntype QueryObserverListener<TData, TError> = (\n result: QueryObserverResult<TData, TError>,\n) => void\n\ninterface ObserverFetchOptions extends FetchOptions {\n throwOnError?: boolean\n}\n\n/**\n * A `QueryObserver` watches a single query in the `QueryCache` and computes a\n * `QueryObserverResult` from its state, recomputing and notifying subscribers\n * whenever the underlying query (or the observer's options) changes. It is\n * the primitive that framework adapters (e.g. `useQuery`) build their hooks\n * on top of, but it can also be used directly to observe and switch between\n * queries outside of any framework.\n *\n * @example\n * ```ts\n * const observer = new QueryObserver(queryClient, {\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * })\n *\n * const unsubscribe = observer.subscribe((result) => {\n * console.log(result.data)\n * })\n * ```\n */\nexport class QueryObserver<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> extends Subscribable<QueryObserverListener<TData, TError>> {\n #client: QueryClient\n #currentQuery: Query<TQueryFnData, TError, TQueryData, TQueryKey> = undefined!\n #currentQueryInitialState: QueryState<TQueryData, TError> = undefined!\n #currentResult: QueryObserverResult<TData, TError> = undefined!\n #currentResultState?: QueryState<TQueryData, TError>\n #currentResultOptions?: QueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >\n #selectError: TError | null\n #selectFn?: (data: TQueryData) => TData\n #selectResult?: TData\n // This property keeps track of the last query with defined data.\n // It will be used to pass the previous data and query to the placeholder function between renders.\n #lastQueryWithDefinedData?: Query<TQueryFnData, TError, TQueryData, TQueryKey>\n #staleTimeoutId?: ManagedTimerId\n #refetchIntervalId?: ManagedTimerId\n #currentRefetchInterval?: number | false\n #trackedProps = new Set<keyof QueryObserverResult>()\n\n constructor(\n client: QueryClient,\n public options: QueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n ) {\n super()\n\n this.#client = client\n this.#selectError = null\n\n this.bindMethods()\n this.setOptions(options)\n }\n\n protected bindMethods(): void {\n this.refetch = this.refetch.bind(this)\n }\n\n protected onSubscribe(): void {\n if (this.listeners.size === 1) {\n this.#currentQuery.addObserver(this)\n\n if (shouldFetchOnMount(this.#currentQuery, this.options)) {\n this.#executeFetch()\n } else {\n this.updateResult()\n }\n\n this.#updateTimers()\n }\n }\n\n protected onUnsubscribe(): void {\n if (!this.hasListeners()) {\n this.destroy()\n }\n }\n\n /**\n * Returns whether the observed query is currently stale and configured\n * (via the `refetchOnReconnect` option) to refetch when the network\n * reconnects.\n */\n shouldFetchOnReconnect(): boolean {\n return shouldFetchOn(\n this.#currentQuery,\n this.options,\n this.options.refetchOnReconnect,\n )\n }\n\n /**\n * Returns whether the observed query is currently stale and configured\n * (via the `refetchOnWindowFocus` option) to refetch when the window\n * regains focus.\n */\n shouldFetchOnWindowFocus(): boolean {\n return shouldFetchOn(\n this.#currentQuery,\n this.options,\n this.options.refetchOnWindowFocus,\n )\n }\n\n /**\n * Stops observing the current query: clears all listeners, cancels the\n * stale and refetch-interval timers, and removes this observer from the\n * query it was observing.\n */\n destroy(): void {\n this.listeners = new Set()\n this.#clearStaleTimeout()\n this.#clearRefetchInterval()\n this.#currentQuery.removeObserver(this)\n }\n\n /**\n * Updates the observer's options. This will re-resolve the query being\n * observed (switching to a different query if the `queryKey` changed),\n * trigger a fetch if the new options require one and the observer has\n * subscribers, recompute the current result, and reschedule the stale and\n * refetch-interval timers as needed.\n *\n * @example\n * ```ts\n * observer.setOptions({ queryKey: ['posts', 1], queryFn: () => fetchPost(1) })\n * // later: switch to a different query, reusing the same observer\n * observer.setOptions({ queryKey: ['posts', 2], queryFn: () => fetchPost(2) })\n * ```\n */\n setOptions(\n options: QueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n ): void {\n const prevOptions = this.options\n const prevQuery = this.#currentQuery\n\n this.options = this.#client.defaultQueryOptions(options)\n\n if (\n this.options.enabled !== undefined &&\n typeof this.options.enabled !== 'boolean' &&\n typeof this.options.enabled !== 'function' &&\n typeof resolveQueryValue(this.options.enabled, this.#currentQuery) !==\n 'boolean'\n ) {\n throw new Error(\n 'Expected enabled to be a boolean or a callback that returns a boolean',\n )\n }\n\n this.#updateQuery()\n this.#currentQuery.setOptions(this.options)\n\n if (\n prevOptions._defaulted &&\n !shallowEqualObjects(this.options, prevOptions)\n ) {\n this.#client.getQueryCache().notify({\n type: 'observerOptionsUpdated',\n query: this.#currentQuery,\n observer: this,\n })\n }\n\n const mounted = this.hasListeners()\n\n // Fetch if there are subscribers\n if (\n mounted &&\n shouldFetchOptionally(\n this.#currentQuery,\n prevQuery,\n this.options,\n prevOptions,\n )\n ) {\n this.#executeFetch()\n }\n\n // Update result\n this.updateResult()\n\n // Update stale interval if needed\n if (\n mounted &&\n (this.#currentQuery !== prevQuery ||\n resolveQueryValue(this.options.enabled, this.#currentQuery) !==\n resolveQueryValue(prevOptions.enabled, this.#currentQuery) ||\n resolveQueryValue(this.options.staleTime, this.#currentQuery) !==\n resolveQueryValue(prevOptions.staleTime, this.#currentQuery))\n ) {\n this.#updateStaleTimeout()\n }\n\n const nextRefetchInterval = this.#computeRefetchInterval()\n\n // Update refetch interval if needed\n if (\n mounted &&\n (this.#currentQuery !== prevQuery ||\n resolveQueryValue(this.options.enabled, this.#currentQuery) !==\n resolveQueryValue(prevOptions.enabled, this.#currentQuery) ||\n nextRefetchInterval !== this.#currentRefetchInterval)\n ) {\n this.#updateRefetchInterval(nextRefetchInterval)\n }\n }\n\n /**\n * Computes the result the observer would produce for the given (already-defaulted) options\n * right now, building the underlying `Query` if it doesn't exist yet, without waiting for a\n * subscription callback. Called by framework adapters on every render (e.g. `useQuery`) so the\n * returned value is available synchronously, ahead of `setOptions` triggering an actual fetch.\n */\n getOptimisticResult(\n options: DefaultedQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n ): QueryObserverResult<TData, TError> {\n const query = this.#client.getQueryCache().build(this.#client, options)\n\n const result = this.createResult(query, options)\n\n if (!shallowEqualObjects(this.getCurrentResult(), result)) {\n // this assigns the optimistic result to the current Observer\n // because if the query function changes, useQuery will be performing\n // an effect where it would fetch again.\n // When the fetch finishes, we perform a deep data cloning in order\n // to reuse objects references. This deep data clone is performed against\n // the `observer.currentResult.data` property\n // When QueryKey changes, we refresh the query and get new `optimistic`\n // result, while we leave the `observer.currentResult`, so when new data\n // arrives, it finds the old `observer.currentResult` which is related\n // to the old QueryKey. Which means that currentResult and selectData are\n // out of sync already.\n // To solve this, we move the cursor of the currentResult every time\n // an observer reads an optimistic value.\n\n // When keeping the previous data, the result doesn't change until new\n // data arrives.\n this.#currentResult = result\n this.#currentResultOptions = this.options\n this.#currentResultState = this.#currentQuery.state\n }\n return result\n }\n\n /**\n * Returns the most recently computed `QueryObserverResult` for the\n * observed query. This is a point-in-time read; to be notified of updates\n * as they happen, subscribe to the observer instead (its inherited\n * `subscribe` method).\n *\n * @example\n * ```ts\n * const result = observer.getCurrentResult()\n * console.log(result.status, result.data)\n * ```\n */\n getCurrentResult(): QueryObserverResult<TData, TError> {\n return this.#currentResult\n }\n\n /**\n * Wraps a `QueryObserverResult` in a `Proxy` that records which properties are read, via\n * {@link QueryObserver#trackProp} (and an optional `onPropTracked` callback). Used by framework\n * adapters when `notifyOnChangeProps` is not set, to implement its default \"only re-render on\n * properties you actually read\" behavior.\n */\n trackResult(\n result: QueryObserverResult<TData, TError>,\n onPropTracked?: (key: keyof QueryObserverResult) => void,\n ): QueryObserverResult<TData, TError> {\n return new Proxy(result, {\n get: (target, key) => {\n this.trackProp(key as keyof QueryObserverResult)\n onPropTracked?.(key as keyof QueryObserverResult)\n return Reflect.get(target, key)\n },\n })\n }\n\n /**\n * Records that the given `QueryObserverResult` property was read, so a subsequent update only\n * notifies this observer if a tracked property actually changed. Normally called indirectly via\n * {@link QueryObserver#trackResult}'s proxy; exposed directly for adapters that track property\n * access themselves (e.g. through their own reactivity system) instead of via the proxy.\n */\n trackProp(key: keyof QueryObserverResult) {\n this.#trackedProps.add(key)\n }\n\n /**\n * Returns the `Query` instance this observer is currently observing.\n */\n getCurrentQuery(): Query<TQueryFnData, TError, TQueryData, TQueryKey> {\n return this.#currentQuery\n }\n\n /**\n * Refetches the observed query and returns a promise that resolves with\n * the resulting `QueryObserverResult`.\n *\n * @example\n * ```ts\n * const result = await observer.refetch({ cancelRefetch: false })\n * console.log(result.data)\n * ```\n */\n refetch({ ...options }: RefetchOptions = {}): Promise<\n QueryObserverResult<TData, TError>\n > {\n return this.fetch({\n ...options,\n })\n }\n\n /**\n * Fetches a query defined by the given options without affecting this\n * observer's own tracked query or result, and returns a promise that\n * resolves with the `QueryObserverResult` for that fetch. This is useful\n * for prefetching data that another observer (e.g. a query about to be\n * navigated to) will need, ahead of time.\n *\n * @example\n * ```ts\n * const result = await observer.fetchOptimistic({\n * queryKey: ['posts', 2],\n * queryFn: () => fetchPost(2),\n * })\n * console.log(result.data)\n * ```\n */\n fetchOptimistic(\n options: QueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n ): Promise<QueryObserverResult<TData, TError>> {\n const defaultedOptions = this.#client.defaultQueryOptions(options)\n\n const query = this.#client\n .getQueryCache()\n .build(this.#client, defaultedOptions)\n\n let unsubscribe = () => {}\n let resolveEarly:\n ((result: QueryObserverResult<TData, TError>) => void) | undefined\n\n const cachePromise = new Promise<QueryObserverResult<TData, TError>>(\n (resolve) => {\n resolveEarly = resolve\n unsubscribe = this.#client.getQueryCache().subscribe((event) => {\n if (\n event.type === 'updated' &&\n event.query.queryHash === query.queryHash &&\n query.state.data !== undefined\n ) {\n unsubscribe()\n resolve(this.createResult(query, defaultedOptions))\n }\n })\n },\n )\n\n return Promise.race([\n query\n .fetch()\n .then(() => {\n const result = this.createResult(query, defaultedOptions)\n // Settle the subscriber promise so both branches always settle.\n // This value is ignored by Promise.race since the fetch branch already won.\n resolveEarly?.(result)\n return result\n })\n .finally(() => {\n unsubscribe()\n }),\n cachePromise,\n ])\n }\n\n protected fetch(\n fetchOptions: ObserverFetchOptions,\n ): Promise<QueryObserverResult<TData, TError>> {\n return this.#executeFetch({\n ...fetchOptions,\n cancelRefetch: fetchOptions.cancelRefetch ?? true,\n }).then(() => {\n this.updateResult()\n return this.#currentResult\n })\n }\n\n #executeFetch(\n fetchOptions?: Omit<ObserverFetchOptions, 'initialPromise'>,\n ): Promise<TQueryData | undefined> {\n // Make sure we reference the latest query as the current one might have been removed\n this.#updateQuery()\n\n // Fetch\n let promise: Promise<TQueryData | undefined> = this.#currentQuery.fetch(\n this.options,\n fetchOptions,\n )\n\n if (!fetchOptions?.throwOnError) {\n promise = promise.catch(noop)\n }\n\n return promise\n }\n\n #shouldScheduleTimer(timeout: unknown): timeout is number {\n return (\n !isServerEnvironment() &&\n resolveQueryValue(this.options.enabled, this.#currentQuery) !== false &&\n isValidTimeout(timeout)\n )\n }\n\n #updateStaleTimeout(): void {\n this.#clearStaleTimeout()\n const staleTime = resolveQueryValue(\n this.options.staleTime,\n this.#currentQuery,\n )\n\n if (this.#currentResult.isStale || !this.#shouldScheduleTimer(staleTime)) {\n return\n }\n\n const time = timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime)\n\n // The timeout is sometimes triggered 1 ms before the stale time expiration.\n // To mitigate this issue we always add 1 ms to the timeout.\n const timeout = time + 1\n\n this.#staleTimeoutId = timeoutManager.setTimeout(() => {\n if (!this.#currentResult.isStale) {\n this.updateResult()\n }\n }, timeout)\n }\n\n #computeRefetchInterval() {\n return (\n resolveQueryValue(this.options.refetchInterval, this.#currentQuery) ??\n false\n )\n }\n\n #updateRefetchInterval(nextInterval: number | false): void {\n this.#clearRefetchInterval()\n\n this.#currentRefetchInterval = nextInterval\n\n if (\n this.#currentRefetchInterval === 0 ||\n !this.#shouldScheduleTimer(this.#currentRefetchInterval)\n ) {\n return\n }\n\n this.#refetchIntervalId = timeoutManager.setInterval(() => {\n if (\n this.options.refetchIntervalInBackground ||\n focusManager.isFocused()\n ) {\n this.#executeFetch()\n }\n }, this.#currentRefetchInterval)\n }\n\n #updateTimers(): void {\n this.#updateStaleTimeout()\n this.#updateRefetchInterval(this.#computeRefetchInterval())\n }\n\n #clearStaleTimeout(): void {\n if (this.#staleTimeoutId !== undefined) {\n timeoutManager.clearTimeout(this.#staleTimeoutId)\n this.#staleTimeoutId = undefined\n }\n }\n\n #clearRefetchInterval(): void {\n if (this.#refetchIntervalId !== undefined) {\n timeoutManager.clearInterval(this.#refetchIntervalId)\n this.#refetchIntervalId = undefined\n }\n }\n\n protected createResult(\n query: Query<TQueryFnData, TError, TQueryData, TQueryKey>,\n options: QueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n ): QueryObserverResult<TData, TError> {\n const prevQuery = this.#currentQuery\n const prevOptions = this.options\n const prevResult = this.#currentResult as\n QueryObserverResult<TData, TError> | undefined\n const prevResultState = this.#currentResultState\n const prevResultOptions = this.#currentResultOptions\n const queryChange = query !== prevQuery\n const queryInitialState = queryChange\n ? query.state\n : this.#currentQueryInitialState\n\n const { state } = query\n let newState = { ...state }\n let isPlaceholderData = false\n let data: TData | undefined\n\n // Optimistically set result in fetching state if needed\n if (options._optimisticResults) {\n const mounted = this.hasListeners()\n\n const fetchOnMount = !mounted && shouldFetchOnMount(query, options)\n\n const fetchOptionally =\n mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions)\n\n if (fetchOnMount || fetchOptionally) {\n newState = {\n ...newState,\n ...fetchState(state.data, query.options),\n }\n }\n if (options._optimisticResults === 'isRestoring') {\n newState.fetchStatus = 'idle'\n }\n }\n\n let { error, errorUpdatedAt, status } = newState\n\n // Per default, use query data\n data = newState.data as unknown as TData\n let skipSelect = false\n\n // use placeholderData if needed\n if (\n options.placeholderData !== undefined &&\n data === undefined &&\n status === 'pending'\n ) {\n let placeholderData\n\n // Memoize placeholder data\n if (\n prevResult?.isPlaceholderData &&\n options.placeholderData === prevResultOptions?.placeholderData\n ) {\n placeholderData = prevResult.data\n // we have to skip select when reading this memoization\n // because prevResult.data is already \"selected\"\n skipSelect = true\n } else {\n // compute placeholderData\n placeholderData =\n typeof options.placeholderData === 'function'\n ? (\n options.placeholderData as unknown as PlaceholderDataFunction<TQueryData>\n )(\n this.#lastQueryWithDefinedData?.state.data,\n this.#lastQueryWithDefinedData as any,\n )\n : options.placeholderData\n }\n\n if (placeholderData !== undefined) {\n status = 'success'\n data = replaceData(\n prevResult?.data,\n placeholderData as unknown,\n options,\n ) as TData\n isPlaceholderData = true\n }\n }\n\n // Select data if needed\n // this also runs placeholderData through the select function\n if (options.select && data !== undefined && !skipSelect) {\n // Memoize select result\n if (\n prevResult &&\n data === prevResultState?.data &&\n options.select === this.#selectFn\n ) {\n data = this.#selectResult\n } else {\n try {\n this.#selectFn = options.select\n data = options.select(data as any)\n data = replaceData(prevResult?.data, data, options)\n this.#selectResult = data\n this.#selectError = null\n } catch (selectError) {\n this.#selectError = selectError as TError\n }\n }\n } else if (data === undefined) {\n // a stored select error belongs to previously selected data; once that\n // data is gone (query switch or reset), it must not leak into this result\n this.#selectError = null\n }\n\n if (this.#selectError) {\n error = this.#selectError\n data = this.#selectResult\n errorUpdatedAt = Date.now()\n status = 'error'\n isPlaceholderData = false\n }\n\n const isFetching = newState.fetchStatus === 'fetching'\n const isPending = status === 'pending'\n const isError = status === 'error'\n\n const isLoading = isPending && isFetching\n const hasData = data !== undefined\n\n const result: QueryObserverBaseResult<TData, TError> = {\n status,\n fetchStatus: newState.fetchStatus,\n isPending,\n isSuccess: status === 'success',\n isError,\n isInitialLoading: isLoading,\n isLoading,\n data,\n dataUpdatedAt: newState.dataUpdatedAt,\n error,\n errorUpdatedAt,\n failureCount: newState.fetchFailureCount,\n failureReason: newState.fetchFailureReason,\n errorUpdateCount: newState.errorUpdateCount,\n isFetched: query.isFetched(),\n isFetchedAfterMount:\n newState.dataUpdateCount > queryInitialState.dataUpdateCount ||\n newState.errorUpdateCount > queryInitialState.errorUpdateCount,\n isFetching,\n isRefetching: isFetching && !isPending,\n isLoadingError: isError && !hasData,\n isPaused: newState.fetchStatus === 'paused',\n isPlaceholderData,\n isRefetchError: isError && hasData,\n isStale: isStale(query, options),\n refetch: this.refetch,\n isEnabled: resolveQueryValue(options.enabled, query) !== false,\n }\n\n const nextResult = result as QueryObserverResult<TData, TError>\n\n return nextResult\n }\n\n /**\n * Recomputes and stores the current result from the current query/options, notifying listeners\n * if it changed. Framework adapters call this right after subscribing to make sure no query\n * update was missed in the gap between creating the observer and subscribing to it.\n */\n updateResult(): void {\n const prevResult = this.#currentResult as\n QueryObserverResult<TData, TError> | undefined\n\n const nextResult = this.createResult(this.#currentQuery, this.options)\n\n this.#currentResultState = this.#currentQuery.state\n this.#currentResultOptions = this.options\n\n if (this.#currentResultState.data !== undefined) {\n this.#lastQueryWithDefinedData = this.#currentQuery\n }\n\n // Only notify and update result if something has changed\n if (shallowEqualObjects(nextResult, prevResult)) {\n return\n }\n\n this.#currentResult = nextResult\n\n const shouldNotifyListeners = (): boolean => {\n if (!prevResult) {\n return true\n }\n\n const { notifyOnChangeProps } = this.options\n const notifyOnChangePropsValue =\n typeof notifyOnChangeProps === 'function'\n ? notifyOnChangeProps()\n : notifyOnChangeProps\n\n if (\n notifyOnChangePropsValue === 'all' ||\n (!notifyOnChangePropsValue && !this.#trackedProps.size)\n ) {\n return true\n }\n\n const includedProps = new Set(\n notifyOnChangePropsValue ?? this.#trackedProps,\n )\n\n if (this.options.throwOnError) {\n includedProps.add('error')\n }\n\n return Object.keys(this.#currentResult).some((key) => {\n const typedKey = key as keyof QueryObserverResult\n const changed = this.#currentResult[typedKey] !== prevResult[typedKey]\n\n return changed && includedProps.has(typedKey)\n })\n }\n\n const notifyListeners = shouldNotifyListeners()\n\n notifyManager.batch(() => {\n // First, trigger the listeners\n if (notifyListeners) {\n this.listeners.forEach((listener) => {\n listener(this.#currentResult)\n })\n }\n\n // Then the cache listeners\n this.#client.getQueryCache().notify({\n query: this.#currentQuery,\n type: 'observerResultsUpdated',\n })\n })\n }\n\n #updateQuery(): void {\n const query = this.#client.getQueryCache().build(this.#client, this.options)\n\n if (query === this.#currentQuery) {\n return\n }\n\n const prevQuery = this.#currentQuery as\n Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined\n this.#currentQuery = query\n this.#currentQueryInitialState = query.state\n\n if (this.hasListeners()) {\n prevQuery?.removeObserver(this)\n query.addObserver(this)\n }\n }\n\n /** @internal */\n onQueryUpdate(): void {\n this.updateResult()\n\n if (this.hasListeners()) {\n this.#updateTimers()\n }\n }\n}\n\nfunction shouldLoadOnMount(\n query: Query<any, any, any, any>,\n options: QueryObserverOptions<any, any, any, any>,\n): boolean {\n return (\n resolveQueryValue(options.enabled, query) !== false &&\n query.state.data === undefined &&\n !(\n query.state.status === 'error' &&\n resolveQueryValue(options.retryOnMount, query) === false\n )\n )\n}\n\nfunction shouldFetchOnMount(\n query: Query<any, any, any, any>,\n options: QueryObserverOptions<any, any, any, any, any>,\n): boolean {\n return (\n shouldLoadOnMount(query, options) ||\n (query.state.data !== undefined &&\n shouldFetchOn(query, options, options.refetchOnMount))\n )\n}\n\nfunction shouldFetchOn(\n query: Query<any, any, any, any>,\n options: QueryObserverOptions<any, any, any, any, any>,\n field: (typeof options)['refetchOnMount'] &\n (typeof options)['refetchOnWindowFocus'] &\n (typeof options)['refetchOnReconnect'],\n) {\n if (\n resolveQueryValue(options.enabled, query) !== false &&\n resolveQueryValue(options.staleTime, query) !== 'static'\n ) {\n const value = resolveQueryValue(field, query)\n\n return value === 'always' || (value !== false && isStale(query, options))\n }\n return false\n}\n\nfunction shouldFetchOptionally(\n query: Query<any, any, any, any>,\n prevQuery: Query<any, any, any, any>,\n options: QueryObserverOptions<any, any, any, any, any>,\n prevOptions: QueryObserverOptions<any, any, any, any, any>,\n): boolean {\n return (\n (query !== prevQuery ||\n resolveQueryValue(prevOptions.enabled, query) === false) &&\n (!options.suspense || query.state.status !== 'error') &&\n isStale(query, options)\n )\n}\n\nfunction isStale(\n query: Query<any, any, any, any>,\n options: QueryObserverOptions<any, any, any, any, any>,\n): boolean {\n return (\n resolveQueryValue(options.enabled, query) !== false &&\n query.isStaleByTime(resolveQueryValue(options.staleTime, query))\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,IAAa,gBAAb,cAMUA,qBAAAA,aAAmD;CAC3D;CACA,gBAAoE,KAAA;CACpE,4BAA4D,KAAA;CAC5D,iBAAqD,KAAA;CACrD;CACA;CAOA;CACA;CACA;CAGA;CACA;CACA;CACA;CACA,gCAAgB,IAAI,IAA+B;CAEnD,YACE,QACA,SAOA;EACA,MAAM;EARC,KAAA,UAAA;EAUP,KAAK,UAAU;EACf,KAAK,eAAe;EAEpB,KAAK,YAAY;EACjB,KAAK,WAAW,OAAO;CACzB;CAEA,cAA8B;EAC5B,KAAK,UAAU,KAAK,QAAQ,KAAK,IAAI;CACvC;CAEA,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Ac;AAE1D;AAEA,SAAS,cACP,OACA,SACA,OAGA;CACA,IACEA,cAAAA,kBAAkB,QAAQ,SAAS,KAAK,MAAM,SAC9CA,cAAAA,kBAAkB,QAAQ,WAAW,KAAK,MAAM,UAChD;EACA,MAAM,QAAQA,cAAAA,kBAAkB,OAAO,KAAK;EAE5C,OAAO,UAAU,YAAa,UAAU,SAAS,QAAQ,OAAO,OAAO;CACzE;CACA,OAAO;AACT;AAEA,SAAS,sBACP,OACA,WACA,SACA,aACS;CACT,QACG,UAAU,aACTA,cAAAA,kBAAkB,YAAY,SAAS,KAAK,MAAM,WACnD,CAAC,QAAQ,YAAY,MAAM,MAAM,WAAW,YAC7C,QAAQ,OAAO,OAAO;AAE1B;AAEA,SAAS,QACP,OACA,SACS;CACT,OACEA,cAAAA,kBAAkB,QAAQ,SAAS,KAAK,MAAM,SAC9C,MAAM,cAAcA,cAAAA,kBAAkB,QAAQ,WAAW,KAAK,CAAC;AAEnE"}
@@ -1,2 +1,2 @@
1
- import { rr as QueryObserver } from "./hydration-DRcloXEn.cjs";
1
+ import { rr as QueryObserver } from "./hydration-Br9VIGXa.cjs";
2
2
  export { QueryObserver };
@@ -1,2 +1,2 @@
1
- import { rr as QueryObserver } from "./hydration-Bp57N3SP.js";
1
+ import { rr as QueryObserver } from "./hydration-B9t5w6NC.js";
2
2
  export { QueryObserver };
@@ -1 +1 @@
1
- {"version":3,"file":"queryObserver.js","names":["#client","#selectError","#currentQuery","#executeFetch","#updateTimers","#clearStaleTimeout","#clearRefetchInterval","#updateQuery","#updateStaleTimeout","#computeRefetchInterval","#currentRefetchInterval","#updateRefetchInterval","#currentResult","#currentResultOptions","#currentResultState","#trackedProps","isServerEnvironment","#shouldScheduleTimer","#staleTimeoutId","#refetchIntervalId","#currentQueryInitialState","#lastQueryWithDefinedData","#selectFn","#selectResult"],"sources":["../../src/queryObserver.ts"],"sourcesContent":["import { focusManager } from './focusManager'\nimport { isServer as isServerEnvironment } from './environmentManager'\nimport { notifyManager } from './notifyManager'\nimport { fetchState } from './query'\nimport { Subscribable } from './subscribable'\nimport {\n isValidTimeout,\n noop,\n replaceData,\n resolveQueryValue,\n shallowEqualObjects,\n timeUntilStale,\n} from './utils'\nimport { timeoutManager } from './timeoutManager'\nimport type { ManagedTimerId } from './timeoutManager'\nimport type { FetchOptions, Query, QueryState } from './query'\nimport type { QueryClient } from './queryClient'\nimport type {\n DefaultError,\n DefaultedQueryObserverOptions,\n PlaceholderDataFunction,\n QueryKey,\n QueryObserverBaseResult,\n QueryObserverOptions,\n QueryObserverResult,\n RefetchOptions,\n} from './types'\n\ntype QueryObserverListener<TData, TError> = (\n result: QueryObserverResult<TData, TError>,\n) => void\n\ninterface ObserverFetchOptions extends FetchOptions {\n throwOnError?: boolean\n}\n\n/**\n * A `QueryObserver` watches a single query in the `QueryCache` and computes a\n * `QueryObserverResult` from its state, recomputing and notifying subscribers\n * whenever the underlying query (or the observer's options) changes. It is\n * the primitive that framework adapters (e.g. `useQuery`) build their hooks\n * on top of, but it can also be used directly to observe and switch between\n * queries outside of any framework.\n *\n * @example\n * ```ts\n * const observer = new QueryObserver(queryClient, {\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * })\n *\n * const unsubscribe = observer.subscribe((result) => {\n * console.log(result.data)\n * })\n * ```\n */\nexport class QueryObserver<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> extends Subscribable<QueryObserverListener<TData, TError>> {\n #client: QueryClient\n #currentQuery: Query<TQueryFnData, TError, TQueryData, TQueryKey> = undefined!\n #currentQueryInitialState: QueryState<TQueryData, TError> = undefined!\n #currentResult: QueryObserverResult<TData, TError> = undefined!\n #currentResultState?: QueryState<TQueryData, TError>\n #currentResultOptions?: QueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >\n #selectError: TError | null\n #selectFn?: (data: TQueryData) => TData\n #selectResult?: TData\n // This property keeps track of the last query with defined data.\n // It will be used to pass the previous data and query to the placeholder function between renders.\n #lastQueryWithDefinedData?: Query<TQueryFnData, TError, TQueryData, TQueryKey>\n #staleTimeoutId?: ManagedTimerId\n #refetchIntervalId?: ManagedTimerId\n #currentRefetchInterval?: number | false\n #trackedProps = new Set<keyof QueryObserverResult>()\n\n constructor(\n client: QueryClient,\n public options: QueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n ) {\n super()\n\n this.#client = client\n this.#selectError = null\n\n this.bindMethods()\n this.setOptions(options)\n }\n\n protected bindMethods(): void {\n this.refetch = this.refetch.bind(this)\n }\n\n protected onSubscribe(): void {\n if (this.listeners.size === 1) {\n this.#currentQuery.addObserver(this)\n\n if (shouldFetchOnMount(this.#currentQuery, this.options)) {\n this.#executeFetch()\n } else {\n this.updateResult()\n }\n\n this.#updateTimers()\n }\n }\n\n protected onUnsubscribe(): void {\n if (!this.hasListeners()) {\n this.destroy()\n }\n }\n\n /**\n * Returns whether the observed query is currently stale and configured\n * (via the `refetchOnReconnect` option) to refetch when the network\n * reconnects.\n */\n shouldFetchOnReconnect(): boolean {\n return shouldFetchOn(\n this.#currentQuery,\n this.options,\n this.options.refetchOnReconnect,\n )\n }\n\n /**\n * Returns whether the observed query is currently stale and configured\n * (via the `refetchOnWindowFocus` option) to refetch when the window\n * regains focus.\n */\n shouldFetchOnWindowFocus(): boolean {\n return shouldFetchOn(\n this.#currentQuery,\n this.options,\n this.options.refetchOnWindowFocus,\n )\n }\n\n /**\n * Stops observing the current query: clears all listeners, cancels the\n * stale and refetch-interval timers, and removes this observer from the\n * query it was observing.\n */\n destroy(): void {\n this.listeners = new Set()\n this.#clearStaleTimeout()\n this.#clearRefetchInterval()\n this.#currentQuery.removeObserver(this)\n }\n\n /**\n * Updates the observer's options. This will re-resolve the query being\n * observed (switching to a different query if the `queryKey` changed),\n * trigger a fetch if the new options require one and the observer has\n * subscribers, recompute the current result, and reschedule the stale and\n * refetch-interval timers as needed.\n *\n * @example\n * ```ts\n * observer.setOptions({ queryKey: ['posts', 1], queryFn: () => fetchPost(1) })\n * // later: switch to a different query, reusing the same observer\n * observer.setOptions({ queryKey: ['posts', 2], queryFn: () => fetchPost(2) })\n * ```\n */\n setOptions(\n options: QueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n ): void {\n const prevOptions = this.options\n const prevQuery = this.#currentQuery\n\n this.options = this.#client.defaultQueryOptions(options)\n\n if (\n this.options.enabled !== undefined &&\n typeof this.options.enabled !== 'boolean' &&\n typeof this.options.enabled !== 'function' &&\n typeof resolveQueryValue(this.options.enabled, this.#currentQuery) !==\n 'boolean'\n ) {\n throw new Error(\n 'Expected enabled to be a boolean or a callback that returns a boolean',\n )\n }\n\n this.#updateQuery()\n this.#currentQuery.setOptions(this.options)\n\n if (\n prevOptions._defaulted &&\n !shallowEqualObjects(this.options, prevOptions)\n ) {\n this.#client.getQueryCache().notify({\n type: 'observerOptionsUpdated',\n query: this.#currentQuery,\n observer: this,\n })\n }\n\n const mounted = this.hasListeners()\n\n // Fetch if there are subscribers\n if (\n mounted &&\n shouldFetchOptionally(\n this.#currentQuery,\n prevQuery,\n this.options,\n prevOptions,\n )\n ) {\n this.#executeFetch()\n }\n\n // Update result\n this.updateResult()\n\n // Update stale interval if needed\n if (\n mounted &&\n (this.#currentQuery !== prevQuery ||\n resolveQueryValue(this.options.enabled, this.#currentQuery) !==\n resolveQueryValue(prevOptions.enabled, this.#currentQuery) ||\n resolveQueryValue(this.options.staleTime, this.#currentQuery) !==\n resolveQueryValue(prevOptions.staleTime, this.#currentQuery))\n ) {\n this.#updateStaleTimeout()\n }\n\n const nextRefetchInterval = this.#computeRefetchInterval()\n\n // Update refetch interval if needed\n if (\n mounted &&\n (this.#currentQuery !== prevQuery ||\n resolveQueryValue(this.options.enabled, this.#currentQuery) !==\n resolveQueryValue(prevOptions.enabled, this.#currentQuery) ||\n nextRefetchInterval !== this.#currentRefetchInterval)\n ) {\n this.#updateRefetchInterval(nextRefetchInterval)\n }\n }\n\n /**\n * Computes the result the observer would produce for the given (already-defaulted) options\n * right now, building the underlying `Query` if it doesn't exist yet, without waiting for a\n * subscription callback. Called by framework adapters on every render (e.g. `useQuery`) so the\n * returned value is available synchronously, ahead of `setOptions` triggering an actual fetch.\n */\n getOptimisticResult(\n options: DefaultedQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n ): QueryObserverResult<TData, TError> {\n const query = this.#client.getQueryCache().build(this.#client, options)\n\n const result = this.createResult(query, options)\n\n if (!shallowEqualObjects(this.getCurrentResult(), result)) {\n // this assigns the optimistic result to the current Observer\n // because if the query function changes, useQuery will be performing\n // an effect where it would fetch again.\n // When the fetch finishes, we perform a deep data cloning in order\n // to reuse objects references. This deep data clone is performed against\n // the `observer.currentResult.data` property\n // When QueryKey changes, we refresh the query and get new `optimistic`\n // result, while we leave the `observer.currentResult`, so when new data\n // arrives, it finds the old `observer.currentResult` which is related\n // to the old QueryKey. Which means that currentResult and selectData are\n // out of sync already.\n // To solve this, we move the cursor of the currentResult every time\n // an observer reads an optimistic value.\n\n // When keeping the previous data, the result doesn't change until new\n // data arrives.\n this.#currentResult = result\n this.#currentResultOptions = this.options\n this.#currentResultState = this.#currentQuery.state\n }\n return result\n }\n\n /**\n * Returns the most recently computed `QueryObserverResult` for the\n * observed query. This is a point-in-time read; to be notified of updates\n * as they happen, subscribe to the observer instead (its inherited\n * `subscribe` method).\n *\n * @example\n * ```ts\n * const result = observer.getCurrentResult()\n * console.log(result.status, result.data)\n * ```\n */\n getCurrentResult(): QueryObserverResult<TData, TError> {\n return this.#currentResult\n }\n\n /**\n * Wraps a `QueryObserverResult` in a `Proxy` that records which properties are read, via\n * {@link QueryObserver#trackProp} (and an optional `onPropTracked` callback). Used by framework\n * adapters when `notifyOnChangeProps` is not set, to implement its default \"only re-render on\n * properties you actually read\" behavior.\n */\n trackResult(\n result: QueryObserverResult<TData, TError>,\n onPropTracked?: (key: keyof QueryObserverResult) => void,\n ): QueryObserverResult<TData, TError> {\n return new Proxy(result, {\n get: (target, key) => {\n this.trackProp(key as keyof QueryObserverResult)\n onPropTracked?.(key as keyof QueryObserverResult)\n return Reflect.get(target, key)\n },\n })\n }\n\n /**\n * Records that the given `QueryObserverResult` property was read, so a subsequent update only\n * notifies this observer if a tracked property actually changed. Normally called indirectly via\n * {@link QueryObserver#trackResult}'s proxy; exposed directly for adapters that track property\n * access themselves (e.g. through their own reactivity system) instead of via the proxy.\n */\n trackProp(key: keyof QueryObserverResult) {\n this.#trackedProps.add(key)\n }\n\n /**\n * Returns the `Query` instance this observer is currently observing.\n */\n getCurrentQuery(): Query<TQueryFnData, TError, TQueryData, TQueryKey> {\n return this.#currentQuery\n }\n\n /**\n * Refetches the observed query and returns a promise that resolves with\n * the resulting `QueryObserverResult`.\n *\n * @example\n * ```ts\n * const result = await observer.refetch({ cancelRefetch: false })\n * console.log(result.data)\n * ```\n */\n refetch({ ...options }: RefetchOptions = {}): Promise<\n QueryObserverResult<TData, TError>\n > {\n return this.fetch({\n ...options,\n })\n }\n\n /**\n * Fetches a query defined by the given options without affecting this\n * observer's own tracked query or result, and returns a promise that\n * resolves with the `QueryObserverResult` for that fetch. This is useful\n * for prefetching data that another observer (e.g. a query about to be\n * navigated to) will need, ahead of time.\n *\n * @example\n * ```ts\n * const result = await observer.fetchOptimistic({\n * queryKey: ['posts', 2],\n * queryFn: () => fetchPost(2),\n * })\n * console.log(result.data)\n * ```\n */\n fetchOptimistic(\n options: QueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n ): Promise<QueryObserverResult<TData, TError>> {\n const defaultedOptions = this.#client.defaultQueryOptions(options)\n\n const query = this.#client\n .getQueryCache()\n .build(this.#client, defaultedOptions)\n\n let unsubscribe = () => {}\n let resolveEarly:\n | ((result: QueryObserverResult<TData, TError>) => void)\n | undefined\n\n const cachePromise = new Promise<QueryObserverResult<TData, TError>>(\n (resolve) => {\n resolveEarly = resolve\n unsubscribe = this.#client.getQueryCache().subscribe((event) => {\n if (\n event.type === 'updated' &&\n event.query.queryHash === query.queryHash &&\n query.state.data !== undefined\n ) {\n unsubscribe()\n resolve(this.createResult(query, defaultedOptions))\n }\n })\n },\n )\n\n return Promise.race([\n query\n .fetch()\n .then(() => {\n const result = this.createResult(query, defaultedOptions)\n // Settle the subscriber promise so both branches always settle.\n // This value is ignored by Promise.race since the fetch branch already won.\n resolveEarly?.(result)\n return result\n })\n .finally(() => {\n unsubscribe()\n }),\n cachePromise,\n ])\n }\n\n protected fetch(\n fetchOptions: ObserverFetchOptions,\n ): Promise<QueryObserverResult<TData, TError>> {\n return this.#executeFetch({\n ...fetchOptions,\n cancelRefetch: fetchOptions.cancelRefetch ?? true,\n }).then(() => {\n this.updateResult()\n return this.#currentResult\n })\n }\n\n #executeFetch(\n fetchOptions?: Omit<ObserverFetchOptions, 'initialPromise'>,\n ): Promise<TQueryData | undefined> {\n // Make sure we reference the latest query as the current one might have been removed\n this.#updateQuery()\n\n // Fetch\n let promise: Promise<TQueryData | undefined> = this.#currentQuery.fetch(\n this.options,\n fetchOptions,\n )\n\n if (!fetchOptions?.throwOnError) {\n promise = promise.catch(noop)\n }\n\n return promise\n }\n\n #shouldScheduleTimer(timeout: unknown): timeout is number {\n return (\n !isServerEnvironment() &&\n resolveQueryValue(this.options.enabled, this.#currentQuery) !== false &&\n isValidTimeout(timeout)\n )\n }\n\n #updateStaleTimeout(): void {\n this.#clearStaleTimeout()\n const staleTime = resolveQueryValue(\n this.options.staleTime,\n this.#currentQuery,\n )\n\n if (this.#currentResult.isStale || !this.#shouldScheduleTimer(staleTime)) {\n return\n }\n\n const time = timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime)\n\n // The timeout is sometimes triggered 1 ms before the stale time expiration.\n // To mitigate this issue we always add 1 ms to the timeout.\n const timeout = time + 1\n\n this.#staleTimeoutId = timeoutManager.setTimeout(() => {\n if (!this.#currentResult.isStale) {\n this.updateResult()\n }\n }, timeout)\n }\n\n #computeRefetchInterval() {\n return (\n resolveQueryValue(this.options.refetchInterval, this.#currentQuery) ??\n false\n )\n }\n\n #updateRefetchInterval(nextInterval: number | false): void {\n this.#clearRefetchInterval()\n\n this.#currentRefetchInterval = nextInterval\n\n if (\n this.#currentRefetchInterval === 0 ||\n !this.#shouldScheduleTimer(this.#currentRefetchInterval)\n ) {\n return\n }\n\n this.#refetchIntervalId = timeoutManager.setInterval(() => {\n if (\n this.options.refetchIntervalInBackground ||\n focusManager.isFocused()\n ) {\n this.#executeFetch()\n }\n }, this.#currentRefetchInterval)\n }\n\n #updateTimers(): void {\n this.#updateStaleTimeout()\n this.#updateRefetchInterval(this.#computeRefetchInterval())\n }\n\n #clearStaleTimeout(): void {\n if (this.#staleTimeoutId !== undefined) {\n timeoutManager.clearTimeout(this.#staleTimeoutId)\n this.#staleTimeoutId = undefined\n }\n }\n\n #clearRefetchInterval(): void {\n if (this.#refetchIntervalId !== undefined) {\n timeoutManager.clearInterval(this.#refetchIntervalId)\n this.#refetchIntervalId = undefined\n }\n }\n\n protected createResult(\n query: Query<TQueryFnData, TError, TQueryData, TQueryKey>,\n options: QueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n ): QueryObserverResult<TData, TError> {\n const prevQuery = this.#currentQuery\n const prevOptions = this.options\n const prevResult = this.#currentResult as\n | QueryObserverResult<TData, TError>\n | undefined\n const prevResultState = this.#currentResultState\n const prevResultOptions = this.#currentResultOptions\n const queryChange = query !== prevQuery\n const queryInitialState = queryChange\n ? query.state\n : this.#currentQueryInitialState\n\n const { state } = query\n let newState = { ...state }\n let isPlaceholderData = false\n let data: TData | undefined\n\n // Optimistically set result in fetching state if needed\n if (options._optimisticResults) {\n const mounted = this.hasListeners()\n\n const fetchOnMount = !mounted && shouldFetchOnMount(query, options)\n\n const fetchOptionally =\n mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions)\n\n if (fetchOnMount || fetchOptionally) {\n newState = {\n ...newState,\n ...fetchState(state.data, query.options),\n }\n }\n if (options._optimisticResults === 'isRestoring') {\n newState.fetchStatus = 'idle'\n }\n }\n\n let { error, errorUpdatedAt, status } = newState\n\n // Per default, use query data\n data = newState.data as unknown as TData\n let skipSelect = false\n\n // use placeholderData if needed\n if (\n options.placeholderData !== undefined &&\n data === undefined &&\n status === 'pending'\n ) {\n let placeholderData\n\n // Memoize placeholder data\n if (\n prevResult?.isPlaceholderData &&\n options.placeholderData === prevResultOptions?.placeholderData\n ) {\n placeholderData = prevResult.data\n // we have to skip select when reading this memoization\n // because prevResult.data is already \"selected\"\n skipSelect = true\n } else {\n // compute placeholderData\n placeholderData =\n typeof options.placeholderData === 'function'\n ? (\n options.placeholderData as unknown as PlaceholderDataFunction<TQueryData>\n )(\n this.#lastQueryWithDefinedData?.state.data,\n this.#lastQueryWithDefinedData as any,\n )\n : options.placeholderData\n }\n\n if (placeholderData !== undefined) {\n status = 'success'\n data = replaceData(\n prevResult?.data,\n placeholderData as unknown,\n options,\n ) as TData\n isPlaceholderData = true\n }\n }\n\n // Select data if needed\n // this also runs placeholderData through the select function\n if (options.select && data !== undefined && !skipSelect) {\n // Memoize select result\n if (\n prevResult &&\n data === prevResultState?.data &&\n options.select === this.#selectFn\n ) {\n data = this.#selectResult\n } else {\n try {\n this.#selectFn = options.select\n data = options.select(data as any)\n data = replaceData(prevResult?.data, data, options)\n this.#selectResult = data\n this.#selectError = null\n } catch (selectError) {\n this.#selectError = selectError as TError\n }\n }\n } else if (data === undefined) {\n // a stored select error belongs to previously selected data; once that\n // data is gone (query switch or reset), it must not leak into this result\n this.#selectError = null\n }\n\n if (this.#selectError) {\n error = this.#selectError\n data = this.#selectResult\n errorUpdatedAt = Date.now()\n status = 'error'\n isPlaceholderData = false\n }\n\n const isFetching = newState.fetchStatus === 'fetching'\n const isPending = status === 'pending'\n const isError = status === 'error'\n\n const isLoading = isPending && isFetching\n const hasData = data !== undefined\n\n const result: QueryObserverBaseResult<TData, TError> = {\n status,\n fetchStatus: newState.fetchStatus,\n isPending,\n isSuccess: status === 'success',\n isError,\n isInitialLoading: isLoading,\n isLoading,\n data,\n dataUpdatedAt: newState.dataUpdatedAt,\n error,\n errorUpdatedAt,\n failureCount: newState.fetchFailureCount,\n failureReason: newState.fetchFailureReason,\n errorUpdateCount: newState.errorUpdateCount,\n isFetched: query.isFetched(),\n isFetchedAfterMount:\n newState.dataUpdateCount > queryInitialState.dataUpdateCount ||\n newState.errorUpdateCount > queryInitialState.errorUpdateCount,\n isFetching,\n isRefetching: isFetching && !isPending,\n isLoadingError: isError && !hasData,\n isPaused: newState.fetchStatus === 'paused',\n isPlaceholderData,\n isRefetchError: isError && hasData,\n isStale: isStale(query, options),\n refetch: this.refetch,\n isEnabled: resolveQueryValue(options.enabled, query) !== false,\n }\n\n const nextResult = result as QueryObserverResult<TData, TError>\n\n return nextResult\n }\n\n /**\n * Recomputes and stores the current result from the current query/options, notifying listeners\n * if it changed. Framework adapters call this right after subscribing to make sure no query\n * update was missed in the gap between creating the observer and subscribing to it.\n */\n updateResult(): void {\n const prevResult = this.#currentResult as\n | QueryObserverResult<TData, TError>\n | undefined\n\n const nextResult = this.createResult(this.#currentQuery, this.options)\n\n this.#currentResultState = this.#currentQuery.state\n this.#currentResultOptions = this.options\n\n if (this.#currentResultState.data !== undefined) {\n this.#lastQueryWithDefinedData = this.#currentQuery\n }\n\n // Only notify and update result if something has changed\n if (shallowEqualObjects(nextResult, prevResult)) {\n return\n }\n\n this.#currentResult = nextResult\n\n const shouldNotifyListeners = (): boolean => {\n if (!prevResult) {\n return true\n }\n\n const { notifyOnChangeProps } = this.options\n const notifyOnChangePropsValue =\n typeof notifyOnChangeProps === 'function'\n ? notifyOnChangeProps()\n : notifyOnChangeProps\n\n if (\n notifyOnChangePropsValue === 'all' ||\n (!notifyOnChangePropsValue && !this.#trackedProps.size)\n ) {\n return true\n }\n\n const includedProps = new Set(\n notifyOnChangePropsValue ?? this.#trackedProps,\n )\n\n if (this.options.throwOnError) {\n includedProps.add('error')\n }\n\n return Object.keys(this.#currentResult).some((key) => {\n const typedKey = key as keyof QueryObserverResult\n const changed = this.#currentResult[typedKey] !== prevResult[typedKey]\n\n return changed && includedProps.has(typedKey)\n })\n }\n\n const notifyListeners = shouldNotifyListeners()\n\n notifyManager.batch(() => {\n // First, trigger the listeners\n if (notifyListeners) {\n this.listeners.forEach((listener) => {\n listener(this.#currentResult)\n })\n }\n\n // Then the cache listeners\n this.#client.getQueryCache().notify({\n query: this.#currentQuery,\n type: 'observerResultsUpdated',\n })\n })\n }\n\n #updateQuery(): void {\n const query = this.#client.getQueryCache().build(this.#client, this.options)\n\n if (query === this.#currentQuery) {\n return\n }\n\n const prevQuery = this.#currentQuery as\n | Query<TQueryFnData, TError, TQueryData, TQueryKey>\n | undefined\n this.#currentQuery = query\n this.#currentQueryInitialState = query.state\n\n if (this.hasListeners()) {\n prevQuery?.removeObserver(this)\n query.addObserver(this)\n }\n }\n\n /** @internal */\n onQueryUpdate(): void {\n this.updateResult()\n\n if (this.hasListeners()) {\n this.#updateTimers()\n }\n }\n}\n\nfunction shouldLoadOnMount(\n query: Query<any, any, any, any>,\n options: QueryObserverOptions<any, any, any, any>,\n): boolean {\n return (\n resolveQueryValue(options.enabled, query) !== false &&\n query.state.data === undefined &&\n !(\n query.state.status === 'error' &&\n resolveQueryValue(options.retryOnMount, query) === false\n )\n )\n}\n\nfunction shouldFetchOnMount(\n query: Query<any, any, any, any>,\n options: QueryObserverOptions<any, any, any, any, any>,\n): boolean {\n return (\n shouldLoadOnMount(query, options) ||\n (query.state.data !== undefined &&\n shouldFetchOn(query, options, options.refetchOnMount))\n )\n}\n\nfunction shouldFetchOn(\n query: Query<any, any, any, any>,\n options: QueryObserverOptions<any, any, any, any, any>,\n field: (typeof options)['refetchOnMount'] &\n (typeof options)['refetchOnWindowFocus'] &\n (typeof options)['refetchOnReconnect'],\n) {\n if (\n resolveQueryValue(options.enabled, query) !== false &&\n resolveQueryValue(options.staleTime, query) !== 'static'\n ) {\n const value = resolveQueryValue(field, query)\n\n return value === 'always' || (value !== false && isStale(query, options))\n }\n return false\n}\n\nfunction shouldFetchOptionally(\n query: Query<any, any, any, any>,\n prevQuery: Query<any, any, any, any>,\n options: QueryObserverOptions<any, any, any, any, any>,\n prevOptions: QueryObserverOptions<any, any, any, any, any>,\n): boolean {\n return (\n (query !== prevQuery ||\n resolveQueryValue(prevOptions.enabled, query) === false) &&\n (!options.suspense || query.state.status !== 'error') &&\n isStale(query, options)\n )\n}\n\nfunction isStale(\n query: Query<any, any, any, any>,\n options: QueryObserverOptions<any, any, any, any, any>,\n): boolean {\n return (\n resolveQueryValue(options.enabled, query) !== false &&\n query.isStaleByTime(resolveQueryValue(options.staleTime, query))\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,IAAa,gBAAb,cAMU,aAAmD;CAC3D;CACA,gBAAoE,KAAA;CACpE,4BAA4D,KAAA;CAC5D,iBAAqD,KAAA;CACrD;CACA;CAOA;CACA;CACA;CAGA;CACA;CACA;CACA;CACA,gCAAgB,IAAI,IAA+B;CAEnD,YACE,QACA,SAOA;EACA,MAAM;EARC,KAAA,UAAA;EAUP,KAAKA,UAAU;EACf,KAAKC,eAAe;EAEpB,KAAK,YAAY;EACjB,KAAK,WAAW,OAAO;CACzB;CAEA,cAA8B;EAC5B,KAAK,UAAU,KAAK,QAAQ,KAAK,IAAI;CACvC;CAEA,cAA8B;EAC5B,IAAI,KAAK,UAAU,SAAS,GAAG;GAC7B,KAAKC,cAAc,YAAY,IAAI;GAEnC,IAAI,mBAAmB,KAAKA,eAAe,KAAK,OAAO,GACrD,KAAKC,cAAc;QAEnB,KAAK,aAAa;GAGpB,KAAKC,cAAc;EACrB;CACF;CAEA,gBAAgC;EAC9B,IAAI,CAAC,KAAK,aAAa,GACrB,KAAK,QAAQ;CAEjB;;;;;;CAOA,yBAAkC;EAChC,OAAO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7C,QAAQ,OAAO,OAAO;AAE1B;AAEA,SAAS,QACP,OACA,SACS;CACT,OACE,kBAAkB,QAAQ,SAAS,KAAK,MAAM,SAC9C,MAAM,cAAc,kBAAkB,QAAQ,WAAW,KAAK,CAAC;AAEnE"}
1
+ {"version":3,"file":"queryObserver.js","names":["isServerEnvironment"],"sources":["../../src/queryObserver.ts"],"sourcesContent":["import { focusManager } from './focusManager'\nimport { isServer as isServerEnvironment } from './environmentManager'\nimport { notifyManager } from './notifyManager'\nimport { fetchState } from './query'\nimport { Subscribable } from './subscribable'\nimport {\n isValidTimeout,\n noop,\n replaceData,\n resolveQueryValue,\n shallowEqualObjects,\n timeUntilStale,\n} from './utils'\nimport { timeoutManager } from './timeoutManager'\nimport type { ManagedTimerId } from './timeoutManager'\nimport type { FetchOptions, Query, QueryState } from './query'\nimport type { QueryClient } from './queryClient'\nimport type {\n DefaultError,\n DefaultedQueryObserverOptions,\n PlaceholderDataFunction,\n QueryKey,\n QueryObserverBaseResult,\n QueryObserverOptions,\n QueryObserverResult,\n RefetchOptions,\n} from './types'\n\ntype QueryObserverListener<TData, TError> = (\n result: QueryObserverResult<TData, TError>,\n) => void\n\ninterface ObserverFetchOptions extends FetchOptions {\n throwOnError?: boolean\n}\n\n/**\n * A `QueryObserver` watches a single query in the `QueryCache` and computes a\n * `QueryObserverResult` from its state, recomputing and notifying subscribers\n * whenever the underlying query (or the observer's options) changes. It is\n * the primitive that framework adapters (e.g. `useQuery`) build their hooks\n * on top of, but it can also be used directly to observe and switch between\n * queries outside of any framework.\n *\n * @example\n * ```ts\n * const observer = new QueryObserver(queryClient, {\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * })\n *\n * const unsubscribe = observer.subscribe((result) => {\n * console.log(result.data)\n * })\n * ```\n */\nexport class QueryObserver<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> extends Subscribable<QueryObserverListener<TData, TError>> {\n #client: QueryClient\n #currentQuery: Query<TQueryFnData, TError, TQueryData, TQueryKey> = undefined!\n #currentQueryInitialState: QueryState<TQueryData, TError> = undefined!\n #currentResult: QueryObserverResult<TData, TError> = undefined!\n #currentResultState?: QueryState<TQueryData, TError>\n #currentResultOptions?: QueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >\n #selectError: TError | null\n #selectFn?: (data: TQueryData) => TData\n #selectResult?: TData\n // This property keeps track of the last query with defined data.\n // It will be used to pass the previous data and query to the placeholder function between renders.\n #lastQueryWithDefinedData?: Query<TQueryFnData, TError, TQueryData, TQueryKey>\n #staleTimeoutId?: ManagedTimerId\n #refetchIntervalId?: ManagedTimerId\n #currentRefetchInterval?: number | false\n #trackedProps = new Set<keyof QueryObserverResult>()\n\n constructor(\n client: QueryClient,\n public options: QueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n ) {\n super()\n\n this.#client = client\n this.#selectError = null\n\n this.bindMethods()\n this.setOptions(options)\n }\n\n protected bindMethods(): void {\n this.refetch = this.refetch.bind(this)\n }\n\n protected onSubscribe(): void {\n if (this.listeners.size === 1) {\n this.#currentQuery.addObserver(this)\n\n if (shouldFetchOnMount(this.#currentQuery, this.options)) {\n this.#executeFetch()\n } else {\n this.updateResult()\n }\n\n this.#updateTimers()\n }\n }\n\n protected onUnsubscribe(): void {\n if (!this.hasListeners()) {\n this.destroy()\n }\n }\n\n /**\n * Returns whether the observed query is currently stale and configured\n * (via the `refetchOnReconnect` option) to refetch when the network\n * reconnects.\n */\n shouldFetchOnReconnect(): boolean {\n return shouldFetchOn(\n this.#currentQuery,\n this.options,\n this.options.refetchOnReconnect,\n )\n }\n\n /**\n * Returns whether the observed query is currently stale and configured\n * (via the `refetchOnWindowFocus` option) to refetch when the window\n * regains focus.\n */\n shouldFetchOnWindowFocus(): boolean {\n return shouldFetchOn(\n this.#currentQuery,\n this.options,\n this.options.refetchOnWindowFocus,\n )\n }\n\n /**\n * Stops observing the current query: clears all listeners, cancels the\n * stale and refetch-interval timers, and removes this observer from the\n * query it was observing.\n */\n destroy(): void {\n this.listeners = new Set()\n this.#clearStaleTimeout()\n this.#clearRefetchInterval()\n this.#currentQuery.removeObserver(this)\n }\n\n /**\n * Updates the observer's options. This will re-resolve the query being\n * observed (switching to a different query if the `queryKey` changed),\n * trigger a fetch if the new options require one and the observer has\n * subscribers, recompute the current result, and reschedule the stale and\n * refetch-interval timers as needed.\n *\n * @example\n * ```ts\n * observer.setOptions({ queryKey: ['posts', 1], queryFn: () => fetchPost(1) })\n * // later: switch to a different query, reusing the same observer\n * observer.setOptions({ queryKey: ['posts', 2], queryFn: () => fetchPost(2) })\n * ```\n */\n setOptions(\n options: QueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n ): void {\n const prevOptions = this.options\n const prevQuery = this.#currentQuery\n\n this.options = this.#client.defaultQueryOptions(options)\n\n if (\n this.options.enabled !== undefined &&\n typeof this.options.enabled !== 'boolean' &&\n typeof this.options.enabled !== 'function' &&\n typeof resolveQueryValue(this.options.enabled, this.#currentQuery) !==\n 'boolean'\n ) {\n throw new Error(\n 'Expected enabled to be a boolean or a callback that returns a boolean',\n )\n }\n\n this.#updateQuery()\n this.#currentQuery.setOptions(this.options)\n\n if (\n prevOptions._defaulted &&\n !shallowEqualObjects(this.options, prevOptions)\n ) {\n this.#client.getQueryCache().notify({\n type: 'observerOptionsUpdated',\n query: this.#currentQuery,\n observer: this,\n })\n }\n\n const mounted = this.hasListeners()\n\n // Fetch if there are subscribers\n if (\n mounted &&\n shouldFetchOptionally(\n this.#currentQuery,\n prevQuery,\n this.options,\n prevOptions,\n )\n ) {\n this.#executeFetch()\n }\n\n // Update result\n this.updateResult()\n\n // Update stale interval if needed\n if (\n mounted &&\n (this.#currentQuery !== prevQuery ||\n resolveQueryValue(this.options.enabled, this.#currentQuery) !==\n resolveQueryValue(prevOptions.enabled, this.#currentQuery) ||\n resolveQueryValue(this.options.staleTime, this.#currentQuery) !==\n resolveQueryValue(prevOptions.staleTime, this.#currentQuery))\n ) {\n this.#updateStaleTimeout()\n }\n\n const nextRefetchInterval = this.#computeRefetchInterval()\n\n // Update refetch interval if needed\n if (\n mounted &&\n (this.#currentQuery !== prevQuery ||\n resolveQueryValue(this.options.enabled, this.#currentQuery) !==\n resolveQueryValue(prevOptions.enabled, this.#currentQuery) ||\n nextRefetchInterval !== this.#currentRefetchInterval)\n ) {\n this.#updateRefetchInterval(nextRefetchInterval)\n }\n }\n\n /**\n * Computes the result the observer would produce for the given (already-defaulted) options\n * right now, building the underlying `Query` if it doesn't exist yet, without waiting for a\n * subscription callback. Called by framework adapters on every render (e.g. `useQuery`) so the\n * returned value is available synchronously, ahead of `setOptions` triggering an actual fetch.\n */\n getOptimisticResult(\n options: DefaultedQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n ): QueryObserverResult<TData, TError> {\n const query = this.#client.getQueryCache().build(this.#client, options)\n\n const result = this.createResult(query, options)\n\n if (!shallowEqualObjects(this.getCurrentResult(), result)) {\n // this assigns the optimistic result to the current Observer\n // because if the query function changes, useQuery will be performing\n // an effect where it would fetch again.\n // When the fetch finishes, we perform a deep data cloning in order\n // to reuse objects references. This deep data clone is performed against\n // the `observer.currentResult.data` property\n // When QueryKey changes, we refresh the query and get new `optimistic`\n // result, while we leave the `observer.currentResult`, so when new data\n // arrives, it finds the old `observer.currentResult` which is related\n // to the old QueryKey. Which means that currentResult and selectData are\n // out of sync already.\n // To solve this, we move the cursor of the currentResult every time\n // an observer reads an optimistic value.\n\n // When keeping the previous data, the result doesn't change until new\n // data arrives.\n this.#currentResult = result\n this.#currentResultOptions = this.options\n this.#currentResultState = this.#currentQuery.state\n }\n return result\n }\n\n /**\n * Returns the most recently computed `QueryObserverResult` for the\n * observed query. This is a point-in-time read; to be notified of updates\n * as they happen, subscribe to the observer instead (its inherited\n * `subscribe` method).\n *\n * @example\n * ```ts\n * const result = observer.getCurrentResult()\n * console.log(result.status, result.data)\n * ```\n */\n getCurrentResult(): QueryObserverResult<TData, TError> {\n return this.#currentResult\n }\n\n /**\n * Wraps a `QueryObserverResult` in a `Proxy` that records which properties are read, via\n * {@link QueryObserver#trackProp} (and an optional `onPropTracked` callback). Used by framework\n * adapters when `notifyOnChangeProps` is not set, to implement its default \"only re-render on\n * properties you actually read\" behavior.\n */\n trackResult(\n result: QueryObserverResult<TData, TError>,\n onPropTracked?: (key: keyof QueryObserverResult) => void,\n ): QueryObserverResult<TData, TError> {\n return new Proxy(result, {\n get: (target, key) => {\n this.trackProp(key as keyof QueryObserverResult)\n onPropTracked?.(key as keyof QueryObserverResult)\n return Reflect.get(target, key)\n },\n })\n }\n\n /**\n * Records that the given `QueryObserverResult` property was read, so a subsequent update only\n * notifies this observer if a tracked property actually changed. Normally called indirectly via\n * {@link QueryObserver#trackResult}'s proxy; exposed directly for adapters that track property\n * access themselves (e.g. through their own reactivity system) instead of via the proxy.\n */\n trackProp(key: keyof QueryObserverResult) {\n this.#trackedProps.add(key)\n }\n\n /**\n * Returns the `Query` instance this observer is currently observing.\n */\n getCurrentQuery(): Query<TQueryFnData, TError, TQueryData, TQueryKey> {\n return this.#currentQuery\n }\n\n /**\n * Refetches the observed query and returns a promise that resolves with\n * the resulting `QueryObserverResult`.\n *\n * @example\n * ```ts\n * const result = await observer.refetch({ cancelRefetch: false })\n * console.log(result.data)\n * ```\n */\n refetch({ ...options }: RefetchOptions = {}): Promise<\n QueryObserverResult<TData, TError>\n > {\n return this.fetch({\n ...options,\n })\n }\n\n /**\n * Fetches a query defined by the given options without affecting this\n * observer's own tracked query or result, and returns a promise that\n * resolves with the `QueryObserverResult` for that fetch. This is useful\n * for prefetching data that another observer (e.g. a query about to be\n * navigated to) will need, ahead of time.\n *\n * @example\n * ```ts\n * const result = await observer.fetchOptimistic({\n * queryKey: ['posts', 2],\n * queryFn: () => fetchPost(2),\n * })\n * console.log(result.data)\n * ```\n */\n fetchOptimistic(\n options: QueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n ): Promise<QueryObserverResult<TData, TError>> {\n const defaultedOptions = this.#client.defaultQueryOptions(options)\n\n const query = this.#client\n .getQueryCache()\n .build(this.#client, defaultedOptions)\n\n let unsubscribe = () => {}\n let resolveEarly:\n ((result: QueryObserverResult<TData, TError>) => void) | undefined\n\n const cachePromise = new Promise<QueryObserverResult<TData, TError>>(\n (resolve) => {\n resolveEarly = resolve\n unsubscribe = this.#client.getQueryCache().subscribe((event) => {\n if (\n event.type === 'updated' &&\n event.query.queryHash === query.queryHash &&\n query.state.data !== undefined\n ) {\n unsubscribe()\n resolve(this.createResult(query, defaultedOptions))\n }\n })\n },\n )\n\n return Promise.race([\n query\n .fetch()\n .then(() => {\n const result = this.createResult(query, defaultedOptions)\n // Settle the subscriber promise so both branches always settle.\n // This value is ignored by Promise.race since the fetch branch already won.\n resolveEarly?.(result)\n return result\n })\n .finally(() => {\n unsubscribe()\n }),\n cachePromise,\n ])\n }\n\n protected fetch(\n fetchOptions: ObserverFetchOptions,\n ): Promise<QueryObserverResult<TData, TError>> {\n return this.#executeFetch({\n ...fetchOptions,\n cancelRefetch: fetchOptions.cancelRefetch ?? true,\n }).then(() => {\n this.updateResult()\n return this.#currentResult\n })\n }\n\n #executeFetch(\n fetchOptions?: Omit<ObserverFetchOptions, 'initialPromise'>,\n ): Promise<TQueryData | undefined> {\n // Make sure we reference the latest query as the current one might have been removed\n this.#updateQuery()\n\n // Fetch\n let promise: Promise<TQueryData | undefined> = this.#currentQuery.fetch(\n this.options,\n fetchOptions,\n )\n\n if (!fetchOptions?.throwOnError) {\n promise = promise.catch(noop)\n }\n\n return promise\n }\n\n #shouldScheduleTimer(timeout: unknown): timeout is number {\n return (\n !isServerEnvironment() &&\n resolveQueryValue(this.options.enabled, this.#currentQuery) !== false &&\n isValidTimeout(timeout)\n )\n }\n\n #updateStaleTimeout(): void {\n this.#clearStaleTimeout()\n const staleTime = resolveQueryValue(\n this.options.staleTime,\n this.#currentQuery,\n )\n\n if (this.#currentResult.isStale || !this.#shouldScheduleTimer(staleTime)) {\n return\n }\n\n const time = timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime)\n\n // The timeout is sometimes triggered 1 ms before the stale time expiration.\n // To mitigate this issue we always add 1 ms to the timeout.\n const timeout = time + 1\n\n this.#staleTimeoutId = timeoutManager.setTimeout(() => {\n if (!this.#currentResult.isStale) {\n this.updateResult()\n }\n }, timeout)\n }\n\n #computeRefetchInterval() {\n return (\n resolveQueryValue(this.options.refetchInterval, this.#currentQuery) ??\n false\n )\n }\n\n #updateRefetchInterval(nextInterval: number | false): void {\n this.#clearRefetchInterval()\n\n this.#currentRefetchInterval = nextInterval\n\n if (\n this.#currentRefetchInterval === 0 ||\n !this.#shouldScheduleTimer(this.#currentRefetchInterval)\n ) {\n return\n }\n\n this.#refetchIntervalId = timeoutManager.setInterval(() => {\n if (\n this.options.refetchIntervalInBackground ||\n focusManager.isFocused()\n ) {\n this.#executeFetch()\n }\n }, this.#currentRefetchInterval)\n }\n\n #updateTimers(): void {\n this.#updateStaleTimeout()\n this.#updateRefetchInterval(this.#computeRefetchInterval())\n }\n\n #clearStaleTimeout(): void {\n if (this.#staleTimeoutId !== undefined) {\n timeoutManager.clearTimeout(this.#staleTimeoutId)\n this.#staleTimeoutId = undefined\n }\n }\n\n #clearRefetchInterval(): void {\n if (this.#refetchIntervalId !== undefined) {\n timeoutManager.clearInterval(this.#refetchIntervalId)\n this.#refetchIntervalId = undefined\n }\n }\n\n protected createResult(\n query: Query<TQueryFnData, TError, TQueryData, TQueryKey>,\n options: QueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n ): QueryObserverResult<TData, TError> {\n const prevQuery = this.#currentQuery\n const prevOptions = this.options\n const prevResult = this.#currentResult as\n QueryObserverResult<TData, TError> | undefined\n const prevResultState = this.#currentResultState\n const prevResultOptions = this.#currentResultOptions\n const queryChange = query !== prevQuery\n const queryInitialState = queryChange\n ? query.state\n : this.#currentQueryInitialState\n\n const { state } = query\n let newState = { ...state }\n let isPlaceholderData = false\n let data: TData | undefined\n\n // Optimistically set result in fetching state if needed\n if (options._optimisticResults) {\n const mounted = this.hasListeners()\n\n const fetchOnMount = !mounted && shouldFetchOnMount(query, options)\n\n const fetchOptionally =\n mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions)\n\n if (fetchOnMount || fetchOptionally) {\n newState = {\n ...newState,\n ...fetchState(state.data, query.options),\n }\n }\n if (options._optimisticResults === 'isRestoring') {\n newState.fetchStatus = 'idle'\n }\n }\n\n let { error, errorUpdatedAt, status } = newState\n\n // Per default, use query data\n data = newState.data as unknown as TData\n let skipSelect = false\n\n // use placeholderData if needed\n if (\n options.placeholderData !== undefined &&\n data === undefined &&\n status === 'pending'\n ) {\n let placeholderData\n\n // Memoize placeholder data\n if (\n prevResult?.isPlaceholderData &&\n options.placeholderData === prevResultOptions?.placeholderData\n ) {\n placeholderData = prevResult.data\n // we have to skip select when reading this memoization\n // because prevResult.data is already \"selected\"\n skipSelect = true\n } else {\n // compute placeholderData\n placeholderData =\n typeof options.placeholderData === 'function'\n ? (\n options.placeholderData as unknown as PlaceholderDataFunction<TQueryData>\n )(\n this.#lastQueryWithDefinedData?.state.data,\n this.#lastQueryWithDefinedData as any,\n )\n : options.placeholderData\n }\n\n if (placeholderData !== undefined) {\n status = 'success'\n data = replaceData(\n prevResult?.data,\n placeholderData as unknown,\n options,\n ) as TData\n isPlaceholderData = true\n }\n }\n\n // Select data if needed\n // this also runs placeholderData through the select function\n if (options.select && data !== undefined && !skipSelect) {\n // Memoize select result\n if (\n prevResult &&\n data === prevResultState?.data &&\n options.select === this.#selectFn\n ) {\n data = this.#selectResult\n } else {\n try {\n this.#selectFn = options.select\n data = options.select(data as any)\n data = replaceData(prevResult?.data, data, options)\n this.#selectResult = data\n this.#selectError = null\n } catch (selectError) {\n this.#selectError = selectError as TError\n }\n }\n } else if (data === undefined) {\n // a stored select error belongs to previously selected data; once that\n // data is gone (query switch or reset), it must not leak into this result\n this.#selectError = null\n }\n\n if (this.#selectError) {\n error = this.#selectError\n data = this.#selectResult\n errorUpdatedAt = Date.now()\n status = 'error'\n isPlaceholderData = false\n }\n\n const isFetching = newState.fetchStatus === 'fetching'\n const isPending = status === 'pending'\n const isError = status === 'error'\n\n const isLoading = isPending && isFetching\n const hasData = data !== undefined\n\n const result: QueryObserverBaseResult<TData, TError> = {\n status,\n fetchStatus: newState.fetchStatus,\n isPending,\n isSuccess: status === 'success',\n isError,\n isInitialLoading: isLoading,\n isLoading,\n data,\n dataUpdatedAt: newState.dataUpdatedAt,\n error,\n errorUpdatedAt,\n failureCount: newState.fetchFailureCount,\n failureReason: newState.fetchFailureReason,\n errorUpdateCount: newState.errorUpdateCount,\n isFetched: query.isFetched(),\n isFetchedAfterMount:\n newState.dataUpdateCount > queryInitialState.dataUpdateCount ||\n newState.errorUpdateCount > queryInitialState.errorUpdateCount,\n isFetching,\n isRefetching: isFetching && !isPending,\n isLoadingError: isError && !hasData,\n isPaused: newState.fetchStatus === 'paused',\n isPlaceholderData,\n isRefetchError: isError && hasData,\n isStale: isStale(query, options),\n refetch: this.refetch,\n isEnabled: resolveQueryValue(options.enabled, query) !== false,\n }\n\n const nextResult = result as QueryObserverResult<TData, TError>\n\n return nextResult\n }\n\n /**\n * Recomputes and stores the current result from the current query/options, notifying listeners\n * if it changed. Framework adapters call this right after subscribing to make sure no query\n * update was missed in the gap between creating the observer and subscribing to it.\n */\n updateResult(): void {\n const prevResult = this.#currentResult as\n QueryObserverResult<TData, TError> | undefined\n\n const nextResult = this.createResult(this.#currentQuery, this.options)\n\n this.#currentResultState = this.#currentQuery.state\n this.#currentResultOptions = this.options\n\n if (this.#currentResultState.data !== undefined) {\n this.#lastQueryWithDefinedData = this.#currentQuery\n }\n\n // Only notify and update result if something has changed\n if (shallowEqualObjects(nextResult, prevResult)) {\n return\n }\n\n this.#currentResult = nextResult\n\n const shouldNotifyListeners = (): boolean => {\n if (!prevResult) {\n return true\n }\n\n const { notifyOnChangeProps } = this.options\n const notifyOnChangePropsValue =\n typeof notifyOnChangeProps === 'function'\n ? notifyOnChangeProps()\n : notifyOnChangeProps\n\n if (\n notifyOnChangePropsValue === 'all' ||\n (!notifyOnChangePropsValue && !this.#trackedProps.size)\n ) {\n return true\n }\n\n const includedProps = new Set(\n notifyOnChangePropsValue ?? this.#trackedProps,\n )\n\n if (this.options.throwOnError) {\n includedProps.add('error')\n }\n\n return Object.keys(this.#currentResult).some((key) => {\n const typedKey = key as keyof QueryObserverResult\n const changed = this.#currentResult[typedKey] !== prevResult[typedKey]\n\n return changed && includedProps.has(typedKey)\n })\n }\n\n const notifyListeners = shouldNotifyListeners()\n\n notifyManager.batch(() => {\n // First, trigger the listeners\n if (notifyListeners) {\n this.listeners.forEach((listener) => {\n listener(this.#currentResult)\n })\n }\n\n // Then the cache listeners\n this.#client.getQueryCache().notify({\n query: this.#currentQuery,\n type: 'observerResultsUpdated',\n })\n })\n }\n\n #updateQuery(): void {\n const query = this.#client.getQueryCache().build(this.#client, this.options)\n\n if (query === this.#currentQuery) {\n return\n }\n\n const prevQuery = this.#currentQuery as\n Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined\n this.#currentQuery = query\n this.#currentQueryInitialState = query.state\n\n if (this.hasListeners()) {\n prevQuery?.removeObserver(this)\n query.addObserver(this)\n }\n }\n\n /** @internal */\n onQueryUpdate(): void {\n this.updateResult()\n\n if (this.hasListeners()) {\n this.#updateTimers()\n }\n }\n}\n\nfunction shouldLoadOnMount(\n query: Query<any, any, any, any>,\n options: QueryObserverOptions<any, any, any, any>,\n): boolean {\n return (\n resolveQueryValue(options.enabled, query) !== false &&\n query.state.data === undefined &&\n !(\n query.state.status === 'error' &&\n resolveQueryValue(options.retryOnMount, query) === false\n )\n )\n}\n\nfunction shouldFetchOnMount(\n query: Query<any, any, any, any>,\n options: QueryObserverOptions<any, any, any, any, any>,\n): boolean {\n return (\n shouldLoadOnMount(query, options) ||\n (query.state.data !== undefined &&\n shouldFetchOn(query, options, options.refetchOnMount))\n )\n}\n\nfunction shouldFetchOn(\n query: Query<any, any, any, any>,\n options: QueryObserverOptions<any, any, any, any, any>,\n field: (typeof options)['refetchOnMount'] &\n (typeof options)['refetchOnWindowFocus'] &\n (typeof options)['refetchOnReconnect'],\n) {\n if (\n resolveQueryValue(options.enabled, query) !== false &&\n resolveQueryValue(options.staleTime, query) !== 'static'\n ) {\n const value = resolveQueryValue(field, query)\n\n return value === 'always' || (value !== false && isStale(query, options))\n }\n return false\n}\n\nfunction shouldFetchOptionally(\n query: Query<any, any, any, any>,\n prevQuery: Query<any, any, any, any>,\n options: QueryObserverOptions<any, any, any, any, any>,\n prevOptions: QueryObserverOptions<any, any, any, any, any>,\n): boolean {\n return (\n (query !== prevQuery ||\n resolveQueryValue(prevOptions.enabled, query) === false) &&\n (!options.suspense || query.state.status !== 'error') &&\n isStale(query, options)\n )\n}\n\nfunction isStale(\n query: Query<any, any, any, any>,\n options: QueryObserverOptions<any, any, any, any, any>,\n): boolean {\n return (\n resolveQueryValue(options.enabled, query) !== false &&\n query.isStaleByTime(resolveQueryValue(options.staleTime, query))\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,IAAa,gBAAb,cAMU,aAAmD;CAC3D;CACA,gBAAoE,KAAA;CACpE,4BAA4D,KAAA;CAC5D,iBAAqD,KAAA;CACrD;CACA;CAOA;CACA;CACA;CAGA;CACA;CACA;CACA;CACA,gCAAgB,IAAI,IAA+B;CAEnD,YACE,QACA,SAOA;EACA,MAAM;EARC,KAAA,UAAA;EAUP,KAAK,UAAU;EACf,KAAK,eAAe;EAEpB,KAAK,YAAY;EACjB,KAAK,WAAW,OAAO;CACzB;CAEA,cAA8B;EAC5B,KAAK,UAAU,KAAK,QAAQ,KAAK,IAAI;CACvC;CAEA,cAA8B;EAC5B,IA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AS,sBACP,OACA,WACA,SACA,aACS;CACT,QACG,UAAU,aACT,kBAAkB,YAAY,SAAS,KAAK,MAAM,WACnD,CAAC,QAAQ,YAAY,MAAM,MAAM,WAAW,YAC7C,QAAQ,OAAO,OAAO;AAE1B;AAEA,SAAS,QACP,OACA,SACS;CACT,OACE,kBAAkB,QAAQ,SAAS,KAAK,MAAM,SAC9C,MAAM,cAAc,kBAAkB,QAAQ,WAAW,KAAK,CAAC;AAEnE"}
@@ -0,0 +1,22 @@
1
+ //#region src/removable.d.ts
2
+ /**
3
+ * The base class for cache entries that are garbage collected once nothing is using them —
4
+ * `Query` and `Mutation` both extend it. `gcTime` controls how long an unused entry is kept.
5
+ */
6
+ declare abstract class Removable {
7
+ #private;
8
+ gcTime: number;
9
+ /**
10
+ * Clears the pending garbage collection timeout, so the entry is no longer scheduled for removal.
11
+ * A subclass may override this to release what it holds on to as well — `Query` also cancels any
12
+ * in-flight fetch.
13
+ */
14
+ destroy(): void;
15
+ protected scheduleGc(): void;
16
+ protected updateGcTime(newGcTime: number | undefined): void;
17
+ protected clearGcTimeout(): void;
18
+ protected abstract optionalRemove(): void;
19
+ }
20
+ //#endregion
21
+ export { Removable as t };
22
+ //# sourceMappingURL=removable-0GzhW1PK.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"removable-0GzhW1PK.d.cts","names":[],"sources":["../../src/removable.ts"],"mappings":";;;;;uBASsB;;EACpB;;;;;;EAQA;YAIU;YAUA,aAAa;YAQb;qBAOS"}
@@ -0,0 +1,22 @@
1
+ //#region src/removable.d.ts
2
+ /**
3
+ * The base class for cache entries that are garbage collected once nothing is using them —
4
+ * `Query` and `Mutation` both extend it. `gcTime` controls how long an unused entry is kept.
5
+ */
6
+ declare abstract class Removable {
7
+ #private;
8
+ gcTime: number;
9
+ /**
10
+ * Clears the pending garbage collection timeout, so the entry is no longer scheduled for removal.
11
+ * A subclass may override this to release what it holds on to as well — `Query` also cancels any
12
+ * in-flight fetch.
13
+ */
14
+ destroy(): void;
15
+ protected scheduleGc(): void;
16
+ protected updateGcTime(newGcTime: number | undefined): void;
17
+ protected clearGcTimeout(): void;
18
+ protected abstract optionalRemove(): void;
19
+ }
20
+ //#endregion
21
+ export { Removable as t };
22
+ //# sourceMappingURL=removable-0GzhW1PK.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"removable-0GzhW1PK.d.ts","names":[],"sources":["../../src/removable.ts"],"mappings":";;;;;uBASsB;;EACpB;;;;;;EAQA;YAIU;YAUA,aAAa;YAQb;qBAOS"}
@@ -3,8 +3,17 @@ const require_timeoutManager = require("./timeoutManager.cjs");
3
3
  const require_utils = require("./utils.cjs");
4
4
  const require_environmentManager = require("./environmentManager.cjs");
5
5
  //#region src/removable.ts
6
+ /**
7
+ * The base class for cache entries that are garbage collected once nothing is using them —
8
+ * `Query` and `Mutation` both extend it. `gcTime` controls how long an unused entry is kept.
9
+ */
6
10
  var Removable = class {
7
11
  #gcTimeout;
12
+ /**
13
+ * Clears the pending garbage collection timeout, so the entry is no longer scheduled for removal.
14
+ * A subclass may override this to release what it holds on to as well — `Query` also cancels any
15
+ * in-flight fetch.
16
+ */
8
17
  destroy() {
9
18
  this.clearGcTimeout();
10
19
  }
@@ -1 +1 @@
1
- {"version":3,"file":"removable.cjs","names":["isValidTimeout","#gcTimeout","timeoutManager","isServerEnvironment"],"sources":["../../src/removable.ts"],"sourcesContent":["import { timeoutManager } from './timeoutManager'\nimport { isServer as isServerEnvironment } from './environmentManager'\nimport { isValidTimeout } from './utils'\nimport type { ManagedTimerId } from './timeoutManager'\n\nexport abstract class Removable {\n gcTime!: number\n #gcTimeout?: ManagedTimerId\n\n destroy(): void {\n this.clearGcTimeout()\n }\n\n protected scheduleGc(): void {\n this.clearGcTimeout()\n\n if (isValidTimeout(this.gcTime)) {\n this.#gcTimeout = timeoutManager.setTimeout(() => {\n this.optionalRemove()\n }, this.gcTime)\n }\n }\n\n protected updateGcTime(newGcTime: number | undefined): void {\n // Default to 5 minutes (Infinity for server-side) if no gcTime is set\n this.gcTime = Math.max(\n this.gcTime || 0,\n newGcTime ?? (isServerEnvironment() ? Infinity : 5 * 60 * 1000),\n )\n }\n\n protected clearGcTimeout() {\n if (this.#gcTimeout !== undefined) {\n timeoutManager.clearTimeout(this.#gcTimeout)\n this.#gcTimeout = undefined\n }\n }\n\n protected abstract optionalRemove(): void\n}\n"],"mappings":";;;;;AAKA,IAAsB,YAAtB,MAAgC;CAE9B;CAEA,UAAgB;EACd,KAAK,eAAe;CACtB;CAEA,aAA6B;EAC3B,KAAK,eAAe;EAEpB,IAAIA,cAAAA,eAAe,KAAK,MAAM,GAC5B,KAAKC,aAAaC,uBAAAA,eAAe,iBAAiB;GAChD,KAAK,eAAe;EACtB,GAAG,KAAK,MAAM;CAElB;CAEA,aAAuB,WAAqC;EAE1D,KAAK,SAAS,KAAK,IACjB,KAAK,UAAU,GACf,cAAcC,2BAAAA,SAAoB,IAAI,WAAW,IACnD;CACF;CAEA,iBAA2B;EACzB,IAAI,KAAKF,eAAe,KAAA,GAAW;GACjC,uBAAA,eAAe,aAAa,KAAKA,UAAU;GAC3C,KAAKA,aAAa,KAAA;EACpB;CACF;AAGF"}
1
+ {"version":3,"file":"removable.cjs","names":["isValidTimeout","timeoutManager","isServerEnvironment"],"sources":["../../src/removable.ts"],"sourcesContent":["import { timeoutManager } from './timeoutManager'\nimport { isServer as isServerEnvironment } from './environmentManager'\nimport { isValidTimeout } from './utils'\nimport type { ManagedTimerId } from './timeoutManager'\n\n/**\n * The base class for cache entries that are garbage collected once nothing is using them —\n * `Query` and `Mutation` both extend it. `gcTime` controls how long an unused entry is kept.\n */\nexport abstract class Removable {\n gcTime!: number\n #gcTimeout?: ManagedTimerId\n\n /**\n * Clears the pending garbage collection timeout, so the entry is no longer scheduled for removal.\n * A subclass may override this to release what it holds on to as well — `Query` also cancels any\n * in-flight fetch.\n */\n destroy(): void {\n this.clearGcTimeout()\n }\n\n protected scheduleGc(): void {\n this.clearGcTimeout()\n\n if (isValidTimeout(this.gcTime)) {\n this.#gcTimeout = timeoutManager.setTimeout(() => {\n this.optionalRemove()\n }, this.gcTime)\n }\n }\n\n protected updateGcTime(newGcTime: number | undefined): void {\n // Default to 5 minutes (Infinity for server-side) if no gcTime is set\n this.gcTime = Math.max(\n this.gcTime || 0,\n newGcTime ?? (isServerEnvironment() ? Infinity : 5 * 60 * 1000),\n )\n }\n\n protected clearGcTimeout() {\n if (this.#gcTimeout !== undefined) {\n timeoutManager.clearTimeout(this.#gcTimeout)\n this.#gcTimeout = undefined\n }\n }\n\n protected abstract optionalRemove(): void\n}\n"],"mappings":";;;;;;;;;AASA,IAAsB,YAAtB,MAAgC;CAE9B;;;;;;CAOA,UAAgB;EACd,KAAK,eAAe;CACtB;CAEA,aAA6B;EAC3B,KAAK,eAAe;EAEpB,IAAIA,cAAAA,eAAe,KAAK,MAAM,GAC5B,KAAK,aAAaC,uBAAAA,eAAe,iBAAiB;GAChD,KAAK,eAAe;EACtB,GAAG,KAAK,MAAM;CAElB;CAEA,aAAuB,WAAqC;EAE1D,KAAK,SAAS,KAAK,IACjB,KAAK,UAAU,GACf,cAAcC,2BAAAA,SAAoB,IAAI,WAAW,IACnD;CACF;CAEA,iBAA2B;EACzB,IAAI,KAAK,eAAe,KAAA,GAAW;GACjC,uBAAA,eAAe,aAAa,KAAK,UAAU;GAC3C,KAAK,aAAa,KAAA;EACpB;CACF;AAGF"}
@@ -1,2 +1,2 @@
1
- import { t as Removable } from "./removable-DeMjhW5M.cjs";
1
+ import { t as Removable } from "./removable-0GzhW1PK.cjs";
2
2
  export { Removable };
@@ -1,2 +1,2 @@
1
- import { t as Removable } from "./removable-DeMjhW5M.js";
1
+ import { t as Removable } from "./removable-0GzhW1PK.js";
2
2
  export { Removable };
@@ -2,8 +2,17 @@ import { timeoutManager } from "./timeoutManager.js";
2
2
  import { isValidTimeout } from "./utils.js";
3
3
  import { isServer } from "./environmentManager.js";
4
4
  //#region src/removable.ts
5
+ /**
6
+ * The base class for cache entries that are garbage collected once nothing is using them —
7
+ * `Query` and `Mutation` both extend it. `gcTime` controls how long an unused entry is kept.
8
+ */
5
9
  var Removable = class {
6
10
  #gcTimeout;
11
+ /**
12
+ * Clears the pending garbage collection timeout, so the entry is no longer scheduled for removal.
13
+ * A subclass may override this to release what it holds on to as well — `Query` also cancels any
14
+ * in-flight fetch.
15
+ */
7
16
  destroy() {
8
17
  this.clearGcTimeout();
9
18
  }
@@ -1 +1 @@
1
- {"version":3,"file":"removable.js","names":["#gcTimeout","isServerEnvironment"],"sources":["../../src/removable.ts"],"sourcesContent":["import { timeoutManager } from './timeoutManager'\nimport { isServer as isServerEnvironment } from './environmentManager'\nimport { isValidTimeout } from './utils'\nimport type { ManagedTimerId } from './timeoutManager'\n\nexport abstract class Removable {\n gcTime!: number\n #gcTimeout?: ManagedTimerId\n\n destroy(): void {\n this.clearGcTimeout()\n }\n\n protected scheduleGc(): void {\n this.clearGcTimeout()\n\n if (isValidTimeout(this.gcTime)) {\n this.#gcTimeout = timeoutManager.setTimeout(() => {\n this.optionalRemove()\n }, this.gcTime)\n }\n }\n\n protected updateGcTime(newGcTime: number | undefined): void {\n // Default to 5 minutes (Infinity for server-side) if no gcTime is set\n this.gcTime = Math.max(\n this.gcTime || 0,\n newGcTime ?? (isServerEnvironment() ? Infinity : 5 * 60 * 1000),\n )\n }\n\n protected clearGcTimeout() {\n if (this.#gcTimeout !== undefined) {\n timeoutManager.clearTimeout(this.#gcTimeout)\n this.#gcTimeout = undefined\n }\n }\n\n protected abstract optionalRemove(): void\n}\n"],"mappings":";;;;AAKA,IAAsB,YAAtB,MAAgC;CAE9B;CAEA,UAAgB;EACd,KAAK,eAAe;CACtB;CAEA,aAA6B;EAC3B,KAAK,eAAe;EAEpB,IAAI,eAAe,KAAK,MAAM,GAC5B,KAAKA,aAAa,eAAe,iBAAiB;GAChD,KAAK,eAAe;EACtB,GAAG,KAAK,MAAM;CAElB;CAEA,aAAuB,WAAqC;EAE1D,KAAK,SAAS,KAAK,IACjB,KAAK,UAAU,GACf,cAAcC,SAAoB,IAAI,WAAW,IACnD;CACF;CAEA,iBAA2B;EACzB,IAAI,KAAKD,eAAe,KAAA,GAAW;GACjC,eAAe,aAAa,KAAKA,UAAU;GAC3C,KAAKA,aAAa,KAAA;EACpB;CACF;AAGF"}
1
+ {"version":3,"file":"removable.js","names":["isServerEnvironment"],"sources":["../../src/removable.ts"],"sourcesContent":["import { timeoutManager } from './timeoutManager'\nimport { isServer as isServerEnvironment } from './environmentManager'\nimport { isValidTimeout } from './utils'\nimport type { ManagedTimerId } from './timeoutManager'\n\n/**\n * The base class for cache entries that are garbage collected once nothing is using them —\n * `Query` and `Mutation` both extend it. `gcTime` controls how long an unused entry is kept.\n */\nexport abstract class Removable {\n gcTime!: number\n #gcTimeout?: ManagedTimerId\n\n /**\n * Clears the pending garbage collection timeout, so the entry is no longer scheduled for removal.\n * A subclass may override this to release what it holds on to as well — `Query` also cancels any\n * in-flight fetch.\n */\n destroy(): void {\n this.clearGcTimeout()\n }\n\n protected scheduleGc(): void {\n this.clearGcTimeout()\n\n if (isValidTimeout(this.gcTime)) {\n this.#gcTimeout = timeoutManager.setTimeout(() => {\n this.optionalRemove()\n }, this.gcTime)\n }\n }\n\n protected updateGcTime(newGcTime: number | undefined): void {\n // Default to 5 minutes (Infinity for server-side) if no gcTime is set\n this.gcTime = Math.max(\n this.gcTime || 0,\n newGcTime ?? (isServerEnvironment() ? Infinity : 5 * 60 * 1000),\n )\n }\n\n protected clearGcTimeout() {\n if (this.#gcTimeout !== undefined) {\n timeoutManager.clearTimeout(this.#gcTimeout)\n this.#gcTimeout = undefined\n }\n }\n\n protected abstract optionalRemove(): void\n}\n"],"mappings":";;;;;;;;AASA,IAAsB,YAAtB,MAAgC;CAE9B;;;;;;CAOA,UAAgB;EACd,KAAK,eAAe;CACtB;CAEA,aAA6B;EAC3B,KAAK,eAAe;EAEpB,IAAI,eAAe,KAAK,MAAM,GAC5B,KAAK,aAAa,eAAe,iBAAiB;GAChD,KAAK,eAAe;EACtB,GAAG,KAAK,MAAM;CAElB;CAEA,aAAuB,WAAqC;EAE1D,KAAK,SAAS,KAAK,IACjB,KAAK,UAAU,GACf,cAAcA,SAAoB,IAAI,WAAW,IACnD;CACF;CAEA,iBAA2B;EACzB,IAAI,KAAK,eAAe,KAAA,GAAW;GACjC,eAAe,aAAa,KAAK,UAAU;GAC3C,KAAK,aAAa,KAAA;EACpB;CACF;AAGF"}
@@ -1,2 +1,2 @@
1
- import { $t as CancelledError, an as isCancelledError, en as RetryDelayValue, in as createRetryer, nn as Retryer, rn as canFetch, tn as RetryValue } from "./hydration-DRcloXEn.cjs";
1
+ import { $t as CancelledError, an as isCancelledError, en as RetryDelayValue, in as createRetryer, nn as Retryer, rn as canFetch, tn as RetryValue } from "./hydration-Br9VIGXa.cjs";
2
2
  export { CancelledError, RetryDelayValue, RetryValue, Retryer, canFetch, createRetryer, isCancelledError };
@@ -1,2 +1,2 @@
1
- import { $t as CancelledError, an as isCancelledError, en as RetryDelayValue, in as createRetryer, nn as Retryer, rn as canFetch, tn as RetryValue } from "./hydration-Bp57N3SP.js";
1
+ import { $t as CancelledError, an as isCancelledError, en as RetryDelayValue, in as createRetryer, nn as Retryer, rn as canFetch, tn as RetryValue } from "./hydration-B9t5w6NC.js";
2
2
  export { CancelledError, RetryDelayValue, RetryValue, Retryer, canFetch, createRetryer, isCancelledError };
@@ -7,13 +7,6 @@ const require_utils = require("./utils.cjs");
7
7
  * The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.
8
8
  * The query will stay in fetchStatus 'fetching' until the stream ends.
9
9
  * @param streamFn - The function that returns an AsyncIterable to stream data from.
10
- * @param refetchMode - Defines how re-fetches are handled.
11
- * Defaults to `'reset'`, erases all data and puts the query back into `pending` state.
12
- * Set to `'append'` to append new data to the existing data.
13
- * Set to `'replace'` to write all data to the cache once the stream ends.
14
- * @param reducer - A function to reduce the streamed chunks into the final data.
15
- * Defaults to a function that appends chunks to the end of the array.
16
- * @param initialValue - Initial value to be used while the first chunk is being fetched, and returned if the stream yields no values.
17
10
  * @example
18
11
  * ```ts
19
12
  * await queryClient.query({
@@ -1 +1 @@
1
- {"version":3,"file":"streamedQuery.cjs","names":["addToEnd","addConsumeAwareSignal"],"sources":["../../src/streamedQuery.ts"],"sourcesContent":["import { addConsumeAwareSignal, addToEnd } from './utils'\nimport type {\n OmitKeyof,\n QueryFunction,\n QueryFunctionContext,\n QueryKey,\n} from './types'\n\ntype BaseStreamedQueryParams<TQueryFnData, TQueryKey extends QueryKey> = {\n /** The function that returns an `AsyncIterable` to stream data from. */\n streamFn: (\n context: QueryFunctionContext<TQueryKey>,\n ) => AsyncIterable<TQueryFnData> | Promise<AsyncIterable<TQueryFnData>>\n /**\n * Defines how refetches are handled.\n * - `'reset'` (default): erases all data and puts the query back into `pending` state.\n * - `'append'`: appends new data to the existing data.\n * - `'replace'`: writes all data to the cache once the stream ends.\n */\n refetchMode?: 'append' | 'reset' | 'replace'\n}\n\ntype SimpleStreamedQueryParams<\n TQueryFnData,\n TQueryKey extends QueryKey,\n> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {\n reducer?: never\n initialValue?: never\n}\n\ntype ReducibleStreamedQueryParams<\n TQueryFnData,\n TData,\n TQueryKey extends QueryKey,\n> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {\n /**\n * Reduces streamed chunks into the final data shape. Required whenever `TData` is not an\n * array, since there is no default way to accumulate non-array chunks.\n */\n reducer: (acc: TData, chunk: TQueryFnData) => TData\n /**\n * The value used while the first chunk is being fetched, and returned if the stream yields no\n * values. Required together with a custom `reducer`.\n */\n initialValue: TData\n}\n\ntype StreamedQueryParams<TQueryFnData, TData, TQueryKey extends QueryKey> =\n | SimpleStreamedQueryParams<TQueryFnData, TQueryKey>\n | ReducibleStreamedQueryParams<TQueryFnData, TData, TQueryKey>\n\n/**\n * This is a helper function to create a query function that streams data from an AsyncIterable.\n * Data will be an Array of all the chunks received.\n * The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.\n * The query will stay in fetchStatus 'fetching' until the stream ends.\n * @param streamFn - The function that returns an AsyncIterable to stream data from.\n * @param refetchMode - Defines how re-fetches are handled.\n * Defaults to `'reset'`, erases all data and puts the query back into `pending` state.\n * Set to `'append'` to append new data to the existing data.\n * Set to `'replace'` to write all data to the cache once the stream ends.\n * @param reducer - A function to reduce the streamed chunks into the final data.\n * Defaults to a function that appends chunks to the end of the array.\n * @param initialValue - Initial value to be used while the first chunk is being fetched, and returned if the stream yields no values.\n * @example\n * ```ts\n * await queryClient.query({\n * queryKey: ['data'],\n * queryFn: streamedQuery({\n * streamFn: fetchDataInChunks,\n * }),\n * })\n * ```\n */\nexport function streamedQuery<\n TQueryFnData = unknown,\n TData = Array<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n>({\n streamFn,\n refetchMode = 'reset',\n reducer = (items, chunk) =>\n addToEnd(items as Array<TQueryFnData>, chunk) as TData,\n initialValue = [] as TData,\n}: StreamedQueryParams<TQueryFnData, TData, TQueryKey>): QueryFunction<\n TData,\n TQueryKey\n> {\n return async (context) => {\n const query = context.client\n .getQueryCache()\n .find({ queryKey: context.queryKey, exact: true })\n const isRefetch = !!query && query.isFetched()\n if (isRefetch && refetchMode === 'reset') {\n query.setState({\n ...query.resetState,\n fetchStatus: 'fetching',\n })\n }\n\n let result = initialValue\n\n let cancelled: boolean = false as boolean\n const streamFnContext = addConsumeAwareSignal<\n OmitKeyof<typeof context, 'signal'>\n >(\n {\n client: context.client,\n meta: context.meta,\n queryKey: context.queryKey,\n pageParam: context.pageParam,\n direction: context.direction,\n },\n () => context.signal,\n () => (cancelled = true),\n )\n\n const stream = await streamFn(streamFnContext)\n\n const isReplaceRefetch = isRefetch && refetchMode === 'replace'\n\n for await (const chunk of stream) {\n if (cancelled) {\n break\n }\n\n if (isReplaceRefetch) {\n // don't append to the cache directly when replace-refetching\n result = reducer(result, chunk)\n } else {\n context.client.setQueryData<TData>(context.queryKey, (prev) =>\n reducer(prev === undefined ? initialValue : prev, chunk),\n )\n }\n }\n\n // finalize result: replace-refetching needs to write to the cache\n if (isReplaceRefetch && !cancelled) {\n context.client.setQueryData<TData>(context.queryKey, result)\n }\n\n const data = context.client.getQueryData<TData>(context.queryKey)\n return data === undefined ? initialValue : data\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,SAAgB,cAId,EACA,UACA,cAAc,SACd,WAAW,OAAO,UAChBA,cAAAA,SAAS,OAA8B,KAAK,GAC9C,eAAe,CAAC,KAIhB;CACA,OAAO,OAAO,YAAY;EACxB,MAAM,QAAQ,QAAQ,OACnB,cAAc,CAAC,CACf,KAAK;GAAE,UAAU,QAAQ;GAAU,OAAO;EAAK,CAAC;EACnD,MAAM,YAAY,CAAC,CAAC,SAAS,MAAM,UAAU;EAC7C,IAAI,aAAa,gBAAgB,SAC/B,MAAM,SAAS;GACb,GAAG,MAAM;GACT,aAAa;EACf,CAAC;EAGH,IAAI,SAAS;EAEb,IAAI,YAAqB;EAezB,MAAM,SAAS,MAAM,SAdGC,cAAAA,sBAGtB;GACE,QAAQ,QAAQ;GAChB,MAAM,QAAQ;GACd,UAAU,QAAQ;GAClB,WAAW,QAAQ;GACnB,WAAW,QAAQ;EACrB,SACM,QAAQ,cACP,YAAY,IAGuB,CAAC;EAE7C,MAAM,mBAAmB,aAAa,gBAAgB;EAEtD,WAAW,MAAM,SAAS,QAAQ;GAChC,IAAI,WACF;GAGF,IAAI,kBAEF,SAAS,QAAQ,QAAQ,KAAK;QAE9B,QAAQ,OAAO,aAAoB,QAAQ,WAAW,SACpD,QAAQ,SAAS,KAAA,IAAY,eAAe,MAAM,KAAK,CACzD;EAEJ;EAGA,IAAI,oBAAoB,CAAC,WACvB,QAAQ,OAAO,aAAoB,QAAQ,UAAU,MAAM;EAG7D,MAAM,OAAO,QAAQ,OAAO,aAAoB,QAAQ,QAAQ;EAChE,OAAO,SAAS,KAAA,IAAY,eAAe;CAC7C;AACF"}
1
+ {"version":3,"file":"streamedQuery.cjs","names":["addToEnd","addConsumeAwareSignal"],"sources":["../../src/streamedQuery.ts"],"sourcesContent":["import { addConsumeAwareSignal, addToEnd } from './utils'\nimport type {\n OmitKeyof,\n QueryFunction,\n QueryFunctionContext,\n QueryKey,\n} from './types'\n\ntype BaseStreamedQueryParams<TQueryFnData, TQueryKey extends QueryKey> = {\n /** The function that returns an `AsyncIterable` to stream data from. */\n streamFn: (\n context: QueryFunctionContext<TQueryKey>,\n ) => AsyncIterable<TQueryFnData> | Promise<AsyncIterable<TQueryFnData>>\n /**\n * Defines how refetches are handled.\n * - `'reset'` (default): erases all data and puts the query back into `pending` state.\n * - `'append'`: appends new data to the existing data.\n * - `'replace'`: writes all data to the cache once the stream ends.\n */\n refetchMode?: 'append' | 'reset' | 'replace'\n}\n\ntype SimpleStreamedQueryParams<\n TQueryFnData,\n TQueryKey extends QueryKey,\n> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {\n reducer?: never\n initialValue?: never\n}\n\ntype ReducibleStreamedQueryParams<\n TQueryFnData,\n TData,\n TQueryKey extends QueryKey,\n> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {\n /**\n * Reduces streamed chunks into the final data shape. Required whenever `TData` is not an\n * array, since there is no default way to accumulate non-array chunks.\n */\n reducer: (acc: TData, chunk: TQueryFnData) => TData\n /**\n * The value used while the first chunk is being fetched, and returned if the stream yields no\n * values. Required together with a custom `reducer`.\n */\n initialValue: TData\n}\n\ntype StreamedQueryParams<TQueryFnData, TData, TQueryKey extends QueryKey> =\n | SimpleStreamedQueryParams<TQueryFnData, TQueryKey>\n | ReducibleStreamedQueryParams<TQueryFnData, TData, TQueryKey>\n\n/**\n * This is a helper function to create a query function that streams data from an AsyncIterable.\n * Data will be an Array of all the chunks received.\n * The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.\n * The query will stay in fetchStatus 'fetching' until the stream ends.\n * @param streamFn - The function that returns an AsyncIterable to stream data from.\n * @example\n * ```ts\n * await queryClient.query({\n * queryKey: ['data'],\n * queryFn: streamedQuery({\n * streamFn: fetchDataInChunks,\n * }),\n * })\n * ```\n */\nexport function streamedQuery<\n TQueryFnData = unknown,\n TData = Array<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n>({\n streamFn,\n refetchMode = 'reset',\n reducer = (items, chunk) =>\n addToEnd(items as Array<TQueryFnData>, chunk) as TData,\n initialValue = [] as TData,\n}: StreamedQueryParams<TQueryFnData, TData, TQueryKey>): QueryFunction<\n TData,\n TQueryKey\n> {\n return async (context) => {\n const query = context.client\n .getQueryCache()\n .find({ queryKey: context.queryKey, exact: true })\n const isRefetch = !!query && query.isFetched()\n if (isRefetch && refetchMode === 'reset') {\n query.setState({\n ...query.resetState,\n fetchStatus: 'fetching',\n })\n }\n\n let result = initialValue\n\n let cancelled: boolean = false as boolean\n const streamFnContext = addConsumeAwareSignal<\n OmitKeyof<typeof context, 'signal'>\n >(\n {\n client: context.client,\n meta: context.meta,\n queryKey: context.queryKey,\n pageParam: context.pageParam,\n direction: context.direction,\n },\n () => context.signal,\n () => (cancelled = true),\n )\n\n const stream = await streamFn(streamFnContext)\n\n const isReplaceRefetch = isRefetch && refetchMode === 'replace'\n\n for await (const chunk of stream) {\n if (cancelled) {\n break\n }\n\n if (isReplaceRefetch) {\n // don't append to the cache directly when replace-refetching\n result = reducer(result, chunk)\n } else {\n context.client.setQueryData<TData>(context.queryKey, (prev) =>\n reducer(prev === undefined ? initialValue : prev, chunk),\n )\n }\n }\n\n // finalize result: replace-refetching needs to write to the cache\n if (isReplaceRefetch && !cancelled) {\n context.client.setQueryData<TData>(context.queryKey, result)\n }\n\n const data = context.client.getQueryData<TData>(context.queryKey)\n return data === undefined ? initialValue : data\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmEA,SAAgB,cAId,EACA,UACA,cAAc,SACd,WAAW,OAAO,UAChBA,cAAAA,SAAS,OAA8B,KAAK,GAC9C,eAAe,CAAC,KAIhB;CACA,OAAO,OAAO,YAAY;EACxB,MAAM,QAAQ,QAAQ,OACnB,cAAc,CAAC,CACf,KAAK;GAAE,UAAU,QAAQ;GAAU,OAAO;EAAK,CAAC;EACnD,MAAM,YAAY,CAAC,CAAC,SAAS,MAAM,UAAU;EAC7C,IAAI,aAAa,gBAAgB,SAC/B,MAAM,SAAS;GACb,GAAG,MAAM;GACT,aAAa;EACf,CAAC;EAGH,IAAI,SAAS;EAEb,IAAI,YAAqB;EAezB,MAAM,SAAS,MAAM,SAdGC,cAAAA,sBAGtB;GACE,QAAQ,QAAQ;GAChB,MAAM,QAAQ;GACd,UAAU,QAAQ;GAClB,WAAW,QAAQ;GACnB,WAAW,QAAQ;EACrB,SACM,QAAQ,cACP,YAAY,IAGuB,CAAC;EAE7C,MAAM,mBAAmB,aAAa,gBAAgB;EAEtD,WAAW,MAAM,SAAS,QAAQ;GAChC,IAAI,WACF;GAGF,IAAI,kBAEF,SAAS,QAAQ,QAAQ,KAAK;QAE9B,QAAQ,OAAO,aAAoB,QAAQ,WAAW,SACpD,QAAQ,SAAS,KAAA,IAAY,eAAe,MAAM,KAAK,CACzD;EAEJ;EAGA,IAAI,oBAAoB,CAAC,WACvB,QAAQ,OAAO,aAAoB,QAAQ,UAAU,MAAM;EAG7D,MAAM,OAAO,QAAQ,OAAO,aAAoB,QAAQ,QAAQ;EAChE,OAAO,SAAS,KAAA,IAAY,eAAe;CAC7C;AACF"}
@@ -1,4 +1,4 @@
1
- import { Ct as QueryKey, St as QueryFunctionContext, xt as QueryFunction } from "./hydration-DRcloXEn.cjs";
1
+ import { Ct as QueryKey, St as QueryFunctionContext, xt as QueryFunction } from "./hydration-Br9VIGXa.cjs";
2
2
  //#region src/streamedQuery.d.ts
3
3
  type BaseStreamedQueryParams<TQueryFnData, TQueryKey extends QueryKey> = {
4
4
  /** The function that returns an `AsyncIterable` to stream data from. */
@@ -34,13 +34,6 @@ type StreamedQueryParams<TQueryFnData, TData, TQueryKey extends QueryKey> = Simp
34
34
  * The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.
35
35
  * The query will stay in fetchStatus 'fetching' until the stream ends.
36
36
  * @param streamFn - The function that returns an AsyncIterable to stream data from.
37
- * @param refetchMode - Defines how re-fetches are handled.
38
- * Defaults to `'reset'`, erases all data and puts the query back into `pending` state.
39
- * Set to `'append'` to append new data to the existing data.
40
- * Set to `'replace'` to write all data to the cache once the stream ends.
41
- * @param reducer - A function to reduce the streamed chunks into the final data.
42
- * Defaults to a function that appends chunks to the end of the array.
43
- * @param initialValue - Initial value to be used while the first chunk is being fetched, and returned if the stream yields no values.
44
37
  * @example
45
38
  * ```ts
46
39
  * await queryClient.query({
@@ -1 +1 @@
1
- {"version":3,"file":"streamedQuery.d.cts","names":[],"sources":["../../src/streamedQuery.ts"],"mappings":";;KAQK,wBAAwB,cAAc,kBAAkB;;EAE3D,WACE,SAAS,qBAAqB,eAC3B,cAAc,gBAAgB,QAAQ,cAAc;;;;;;;EAOzD;;KAGG,0BACH,cACA,kBAAkB,YAChB,wBAAwB,cAAc;EACxC;EACA;;KAGG,6BACH,cACA,OACA,kBAAkB,YAChB,wBAAwB,cAAc;;;;;EAKxC,UAAU,KAAK,OAAO,OAAO,iBAAiB;;;;;EAK9C,cAAc;;KAGX,oBAAoB,cAAc,OAAO,kBAAkB,YAC5D,0BAA0B,cAAc,aACxC,6BAA6B,cAAc,OAAO;;;;;;;;;;;;;;;;;;;;;;;;iBAyBtC,cACd,wBACA,QAAQ,MAAM,eACd,kBAAkB,WAAW,YAE7B,UACA,aACA,SAEA,gBACC,oBAAoB,cAAc,OAAO,aAAa,cACvD,OACA"}
1
+ {"version":3,"file":"streamedQuery.d.cts","names":[],"sources":["../../src/streamedQuery.ts"],"mappings":";;KAQK,wBAAwB,cAAc,kBAAkB;;EAE3D,WACE,SAAS,qBAAqB,eAC3B,cAAc,gBAAgB,QAAQ,cAAc;;;;;;;EAOzD;;KAGG,0BACH,cACA,kBAAkB,YAChB,wBAAwB,cAAc;EACxC;EACA;;KAGG,6BACH,cACA,OACA,kBAAkB,YAChB,wBAAwB,cAAc;;;;;EAKxC,UAAU,KAAK,OAAO,OAAO,iBAAiB;;;;;EAK9C,cAAc;;KAGX,oBAAoB,cAAc,OAAO,kBAAkB,YAC5D,0BAA0B,cAAc,aACxC,6BAA6B,cAAc,OAAO;;;;;;;;;;;;;;;;;iBAkBtC,cACd,wBACA,QAAQ,MAAM,eACd,kBAAkB,WAAW,YAE7B,UACA,aACA,SAEA,gBACC,oBAAoB,cAAc,OAAO,aAAa,cACvD,OACA"}