@tanstack/query-core 5.0.0-alpha.7 → 5.0.0-alpha.70

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 (292) hide show
  1. package/build/lib/_virtual/{_rollupPluginBabelHelpers.js → _rollupPluginBabelHelpers.legacy.cjs} +1 -1
  2. package/build/lib/_virtual/_rollupPluginBabelHelpers.legacy.cjs.map +1 -0
  3. package/build/lib/_virtual/{_rollupPluginBabelHelpers.esm.js → _rollupPluginBabelHelpers.legacy.js} +1 -1
  4. package/build/lib/_virtual/_rollupPluginBabelHelpers.legacy.js.map +1 -0
  5. package/build/lib/{focusManager.mjs → focusManager.cjs} +9 -6
  6. package/build/lib/{focusManager.mjs.map → focusManager.cjs.map} +1 -1
  7. package/build/lib/focusManager.d.ts +2 -1
  8. package/build/lib/focusManager.d.ts.map +1 -0
  9. package/build/lib/focusManager.js +20 -39
  10. package/build/lib/focusManager.js.map +1 -1
  11. package/build/lib/focusManager.legacy.cjs +90 -0
  12. package/build/lib/focusManager.legacy.cjs.map +1 -0
  13. package/build/lib/{focusManager.esm.js → focusManager.legacy.js} +4 -4
  14. package/build/lib/focusManager.legacy.js.map +1 -0
  15. package/build/lib/{hydration.mjs → hydration.cjs} +11 -20
  16. package/build/lib/hydration.cjs.map +1 -0
  17. package/build/lib/hydration.d.ts +3 -6
  18. package/build/lib/hydration.d.ts.map +1 -0
  19. package/build/lib/hydration.js +7 -28
  20. package/build/lib/hydration.js.map +1 -1
  21. package/build/lib/hydration.legacy.cjs +92 -0
  22. package/build/lib/hydration.legacy.cjs.map +1 -0
  23. package/build/lib/{hydration.esm.js → hydration.legacy.js} +6 -19
  24. package/build/lib/hydration.legacy.js.map +1 -0
  25. package/build/lib/index.cjs +40 -0
  26. package/build/lib/index.cjs.map +1 -0
  27. package/build/lib/index.d.ts +5 -2
  28. package/build/lib/index.d.ts.map +1 -0
  29. package/build/lib/index.js +13 -39
  30. package/build/lib/index.js.map +1 -1
  31. package/build/lib/index.legacy.cjs +40 -0
  32. package/build/lib/index.legacy.cjs.map +1 -0
  33. package/build/lib/index.legacy.js +14 -0
  34. package/build/lib/index.legacy.js.map +1 -0
  35. package/build/lib/{infiniteQueryBehavior.mjs → infiniteQueryBehavior.cjs} +15 -18
  36. package/build/lib/infiniteQueryBehavior.cjs.map +1 -0
  37. package/build/lib/infiniteQueryBehavior.d.ts +2 -1
  38. package/build/lib/infiniteQueryBehavior.d.ts.map +1 -0
  39. package/build/lib/infiniteQueryBehavior.js +14 -26
  40. package/build/lib/infiniteQueryBehavior.js.map +1 -1
  41. package/build/lib/infiniteQueryBehavior.legacy.cjs +125 -0
  42. package/build/lib/infiniteQueryBehavior.legacy.cjs.map +1 -0
  43. package/build/lib/{infiniteQueryBehavior.esm.js → infiniteQueryBehavior.legacy.js} +10 -16
  44. package/build/lib/infiniteQueryBehavior.legacy.js.map +1 -0
  45. package/build/lib/{infiniteQueryObserver.mjs → infiniteQueryObserver.cjs} +11 -9
  46. package/build/lib/{infiniteQueryObserver.mjs.map → infiniteQueryObserver.cjs.map} +1 -1
  47. package/build/lib/infiniteQueryObserver.d.ts +2 -1
  48. package/build/lib/infiniteQueryObserver.d.ts.map +1 -0
  49. package/build/lib/infiniteQueryObserver.js +10 -13
  50. package/build/lib/infiniteQueryObserver.js.map +1 -1
  51. package/build/lib/infiniteQueryObserver.legacy.cjs +78 -0
  52. package/build/lib/infiniteQueryObserver.legacy.cjs.map +1 -0
  53. package/build/lib/{infiniteQueryObserver.esm.js → infiniteQueryObserver.legacy.js} +3 -3
  54. package/build/lib/infiniteQueryObserver.legacy.js.map +1 -0
  55. package/build/lib/{mutation.mjs → mutation.cjs} +13 -10
  56. package/build/lib/mutation.cjs.map +1 -0
  57. package/build/lib/mutation.d.ts +2 -1
  58. package/build/lib/mutation.d.ts.map +1 -0
  59. package/build/lib/mutation.js +107 -135
  60. package/build/lib/mutation.js.map +1 -1
  61. package/build/lib/mutation.legacy.cjs +262 -0
  62. package/build/lib/mutation.legacy.cjs.map +1 -0
  63. package/build/lib/{mutation.esm.js → mutation.legacy.js} +6 -6
  64. package/build/lib/mutation.legacy.js.map +1 -0
  65. package/build/lib/{mutationCache.mjs → mutationCache.cjs} +21 -18
  66. package/build/lib/mutationCache.cjs.map +1 -0
  67. package/build/lib/mutationCache.d.ts +3 -2
  68. package/build/lib/mutationCache.d.ts.map +1 -0
  69. package/build/lib/mutationCache.js +33 -47
  70. package/build/lib/mutationCache.js.map +1 -1
  71. package/build/lib/mutationCache.legacy.cjs +98 -0
  72. package/build/lib/mutationCache.legacy.cjs.map +1 -0
  73. package/build/lib/{mutationCache.esm.js → mutationCache.legacy.js} +11 -10
  74. package/build/lib/mutationCache.legacy.js.map +1 -0
  75. package/build/lib/{mutationObserver.mjs → mutationObserver.cjs} +13 -11
  76. package/build/lib/mutationObserver.cjs.map +1 -0
  77. package/build/lib/mutationObserver.d.ts +2 -1
  78. package/build/lib/mutationObserver.d.ts.map +1 -0
  79. package/build/lib/mutationObserver.js +59 -91
  80. package/build/lib/mutationObserver.js.map +1 -1
  81. package/build/lib/mutationObserver.legacy.cjs +128 -0
  82. package/build/lib/mutationObserver.legacy.cjs.map +1 -0
  83. package/build/lib/{mutationObserver.esm.js → mutationObserver.legacy.js} +7 -7
  84. package/build/lib/mutationObserver.legacy.js.map +1 -0
  85. package/build/lib/{notifyManager.mjs → notifyManager.cjs} +8 -5
  86. package/build/lib/notifyManager.cjs.map +1 -0
  87. package/build/lib/notifyManager.d.ts +7 -5
  88. package/build/lib/notifyManager.d.ts.map +1 -0
  89. package/build/lib/notifyManager.js +4 -7
  90. package/build/lib/notifyManager.js.map +1 -1
  91. package/build/lib/notifyManager.legacy.cjs +92 -0
  92. package/build/lib/notifyManager.legacy.cjs.map +1 -0
  93. package/build/lib/{notifyManager.esm.js → notifyManager.legacy.js} +2 -2
  94. package/build/lib/notifyManager.legacy.js.map +1 -0
  95. package/build/lib/{onlineManager.mjs → onlineManager.cjs} +16 -10
  96. package/build/lib/onlineManager.cjs.map +1 -0
  97. package/build/lib/onlineManager.d.ts +2 -1
  98. package/build/lib/onlineManager.d.ts.map +1 -0
  99. package/build/lib/onlineManager.js +26 -41
  100. package/build/lib/onlineManager.js.map +1 -1
  101. package/build/lib/onlineManager.legacy.cjs +94 -0
  102. package/build/lib/onlineManager.legacy.cjs.map +1 -0
  103. package/build/lib/{onlineManager.esm.js → onlineManager.legacy.js} +11 -8
  104. package/build/lib/onlineManager.legacy.js.map +1 -0
  105. package/build/lib/{queriesObserver.mjs → queriesObserver.cjs} +51 -26
  106. package/build/lib/queriesObserver.cjs.map +1 -0
  107. package/build/lib/queriesObserver.d.ts +14 -6
  108. package/build/lib/queriesObserver.d.ts.map +1 -0
  109. package/build/lib/queriesObserver.js +99 -107
  110. package/build/lib/queriesObserver.js.map +1 -1
  111. package/build/lib/queriesObserver.legacy.cjs +207 -0
  112. package/build/lib/queriesObserver.legacy.cjs.map +1 -0
  113. package/build/lib/{queriesObserver.esm.js → queriesObserver.legacy.js} +62 -22
  114. package/build/lib/queriesObserver.legacy.js.map +1 -0
  115. package/build/lib/{query.mjs → query.cjs} +23 -21
  116. package/build/lib/query.cjs.map +1 -0
  117. package/build/lib/query.d.ts +3 -2
  118. package/build/lib/query.d.ts.map +1 -0
  119. package/build/lib/query.js +174 -225
  120. package/build/lib/query.js.map +1 -1
  121. package/build/lib/query.legacy.cjs +471 -0
  122. package/build/lib/query.legacy.cjs.map +1 -0
  123. package/build/lib/{query.esm.js → query.legacy.js} +11 -11
  124. package/build/lib/query.legacy.js.map +1 -0
  125. package/build/lib/{queryCache.mjs → queryCache.cjs} +28 -23
  126. package/build/lib/queryCache.cjs.map +1 -0
  127. package/build/lib/queryCache.d.ts +3 -3
  128. package/build/lib/queryCache.d.ts.map +1 -0
  129. package/build/lib/queryCache.js +31 -37
  130. package/build/lib/queryCache.js.map +1 -1
  131. package/build/lib/queryCache.legacy.cjs +111 -0
  132. package/build/lib/queryCache.legacy.cjs.map +1 -0
  133. package/build/lib/{queryCache.esm.js → queryCache.legacy.js} +13 -12
  134. package/build/lib/queryCache.legacy.js.map +1 -0
  135. package/build/lib/{queryClient.mjs → queryClient.cjs} +50 -42
  136. package/build/lib/queryClient.cjs.map +1 -0
  137. package/build/lib/queryClient.d.ts +2 -2
  138. package/build/lib/queryClient.d.ts.map +1 -0
  139. package/build/lib/queryClient.js +98 -134
  140. package/build/lib/queryClient.js.map +1 -1
  141. package/build/lib/queryClient.legacy.cjs +322 -0
  142. package/build/lib/queryClient.legacy.cjs.map +1 -0
  143. package/build/lib/{queryClient.esm.js → queryClient.legacy.js} +29 -26
  144. package/build/lib/queryClient.legacy.js.map +1 -0
  145. package/build/lib/{queryObserver.mjs → queryObserver.cjs} +40 -50
  146. package/build/lib/queryObserver.cjs.map +1 -0
  147. package/build/lib/queryObserver.d.ts +6 -7
  148. package/build/lib/queryObserver.d.ts.map +1 -0
  149. package/build/lib/queryObserver.js +208 -323
  150. package/build/lib/queryObserver.js.map +1 -1
  151. package/build/lib/queryObserver.legacy.cjs +526 -0
  152. package/build/lib/queryObserver.legacy.cjs.map +1 -0
  153. package/build/lib/{queryObserver.esm.js → queryObserver.legacy.js} +71 -88
  154. package/build/lib/queryObserver.legacy.js.map +1 -0
  155. package/build/lib/{removable.mjs → removable.cjs} +7 -5
  156. package/build/lib/{removable.mjs.map → removable.cjs.map} +1 -1
  157. package/build/lib/removable.d.ts +1 -0
  158. package/build/lib/removable.d.ts.map +1 -0
  159. package/build/lib/removable.js +9 -18
  160. package/build/lib/removable.js.map +1 -1
  161. package/build/lib/removable.legacy.cjs +38 -0
  162. package/build/lib/removable.legacy.cjs.map +1 -0
  163. package/build/lib/{removable.esm.js → removable.legacy.js} +3 -3
  164. package/build/lib/removable.legacy.js.map +1 -0
  165. package/build/lib/{retryer.mjs → retryer.cjs} +15 -8
  166. package/build/lib/{retryer.mjs.map → retryer.cjs.map} +1 -1
  167. package/build/lib/retryer.d.ts +5 -4
  168. package/build/lib/retryer.d.ts.map +1 -0
  169. package/build/lib/retryer.js +21 -25
  170. package/build/lib/retryer.js.map +1 -1
  171. package/build/lib/retryer.legacy.cjs +158 -0
  172. package/build/lib/retryer.legacy.cjs.map +1 -0
  173. package/build/lib/{retryer.esm.js → retryer.legacy.js} +6 -4
  174. package/build/lib/retryer.legacy.js.map +1 -0
  175. package/build/lib/{subscribable.esm.js → subscribable.cjs} +8 -6
  176. package/build/lib/subscribable.cjs.map +1 -0
  177. package/build/lib/subscribable.d.ts +3 -2
  178. package/build/lib/subscribable.d.ts.map +1 -0
  179. package/build/lib/subscribable.js +5 -7
  180. package/build/lib/subscribable.js.map +1 -1
  181. package/build/lib/subscribable.legacy.cjs +28 -0
  182. package/build/lib/subscribable.legacy.cjs.map +1 -0
  183. package/build/lib/{subscribable.mjs → subscribable.legacy.js} +5 -5
  184. package/build/lib/subscribable.legacy.js.map +1 -0
  185. package/build/lib/tests/focusManager.test.d.ts +1 -0
  186. package/build/lib/tests/focusManager.test.d.ts.map +1 -0
  187. package/build/lib/tests/hydration.test.d.ts +1 -0
  188. package/build/lib/tests/hydration.test.d.ts.map +1 -0
  189. package/build/lib/tests/infiniteQueryBehavior.test.d.ts +1 -0
  190. package/build/lib/tests/infiniteQueryBehavior.test.d.ts.map +1 -0
  191. package/build/lib/tests/infiniteQueryObserver.test.d.ts +1 -0
  192. package/build/lib/tests/infiniteQueryObserver.test.d.ts.map +1 -0
  193. package/build/lib/tests/mutationCache.test.d.ts +1 -0
  194. package/build/lib/tests/mutationCache.test.d.ts.map +1 -0
  195. package/build/lib/tests/mutationObserver.test.d.ts +1 -0
  196. package/build/lib/tests/mutationObserver.test.d.ts.map +1 -0
  197. package/build/lib/tests/mutations.test.d.ts +1 -0
  198. package/build/lib/tests/mutations.test.d.ts.map +1 -0
  199. package/build/lib/tests/notifyManager.test.d.ts +1 -0
  200. package/build/lib/tests/notifyManager.test.d.ts.map +1 -0
  201. package/build/lib/tests/onlineManager.test.d.ts +1 -0
  202. package/build/lib/tests/onlineManager.test.d.ts.map +1 -0
  203. package/build/lib/tests/queriesObserver.test.d.ts +1 -0
  204. package/build/lib/tests/queriesObserver.test.d.ts.map +1 -0
  205. package/build/lib/tests/query.test.d.ts +1 -0
  206. package/build/lib/tests/query.test.d.ts.map +1 -0
  207. package/build/lib/tests/queryCache.test.d.ts +1 -0
  208. package/build/lib/tests/queryCache.test.d.ts.map +1 -0
  209. package/build/lib/tests/queryClient.test.d.ts +1 -0
  210. package/build/lib/tests/queryClient.test.d.ts.map +1 -0
  211. package/build/lib/tests/queryObserver.test.d.ts +1 -0
  212. package/build/lib/tests/queryObserver.test.d.ts.map +1 -0
  213. package/build/lib/tests/utils.d.ts +1 -0
  214. package/build/lib/tests/utils.d.ts.map +1 -0
  215. package/build/lib/tests/utils.test.d.ts +1 -0
  216. package/build/lib/tests/utils.test.d.ts.map +1 -0
  217. package/build/lib/types.d.ts +42 -48
  218. package/build/lib/types.d.ts.map +1 -0
  219. package/build/lib/{utils.mjs → utils.cjs} +23 -2
  220. package/build/lib/{utils.mjs.map → utils.cjs.map} +1 -1
  221. package/build/lib/utils.d.ts +4 -3
  222. package/build/lib/utils.d.ts.map +1 -0
  223. package/build/lib/utils.js +2 -23
  224. package/build/lib/utils.js.map +1 -1
  225. package/build/lib/utils.legacy.cjs +248 -0
  226. package/build/lib/utils.legacy.cjs.map +1 -0
  227. package/build/lib/{utils.esm.js → utils.legacy.js} +1 -1
  228. package/build/lib/utils.legacy.js.map +1 -0
  229. package/package.json +13 -9
  230. package/src/hydration.ts +18 -37
  231. package/src/index.ts +3 -3
  232. package/src/infiniteQueryBehavior.ts +16 -18
  233. package/src/mutation.ts +1 -1
  234. package/src/mutationCache.ts +4 -4
  235. package/src/mutationObserver.ts +1 -1
  236. package/src/notifyManager.ts +7 -3
  237. package/src/onlineManager.ts +8 -4
  238. package/src/queriesObserver.ts +75 -25
  239. package/src/query.ts +7 -5
  240. package/src/queryCache.ts +6 -9
  241. package/src/queryClient.ts +23 -21
  242. package/src/queryObserver.ts +47 -55
  243. package/src/subscribable.ts +5 -5
  244. package/src/tests/hydration.test.tsx +7 -3
  245. package/src/tests/infiniteQueryBehavior.test.tsx +5 -2
  246. package/src/tests/notifyManager.test.tsx +15 -0
  247. package/src/tests/query.test.tsx +4 -2
  248. package/src/tests/queryCache.test.tsx +1 -19
  249. package/src/tests/queryClient.test.tsx +79 -3
  250. package/src/tests/queryObserver.test.tsx +121 -0
  251. package/src/types.ts +31 -30
  252. package/build/lib/_virtual/_rollupPluginBabelHelpers.esm.js.map +0 -1
  253. package/build/lib/_virtual/_rollupPluginBabelHelpers.js.map +0 -1
  254. package/build/lib/focusManager.esm.js.map +0 -1
  255. package/build/lib/hydration.esm.js.map +0 -1
  256. package/build/lib/hydration.mjs.map +0 -1
  257. package/build/lib/index.esm.js +0 -14
  258. package/build/lib/index.esm.js.map +0 -1
  259. package/build/lib/index.mjs +0 -14
  260. package/build/lib/index.mjs.map +0 -1
  261. package/build/lib/infiniteQueryBehavior.esm.js.map +0 -1
  262. package/build/lib/infiniteQueryBehavior.mjs.map +0 -1
  263. package/build/lib/infiniteQueryObserver.esm.js.map +0 -1
  264. package/build/lib/mutation.esm.js.map +0 -1
  265. package/build/lib/mutation.mjs.map +0 -1
  266. package/build/lib/mutationCache.esm.js.map +0 -1
  267. package/build/lib/mutationCache.mjs.map +0 -1
  268. package/build/lib/mutationObserver.esm.js.map +0 -1
  269. package/build/lib/mutationObserver.mjs.map +0 -1
  270. package/build/lib/notifyManager.esm.js.map +0 -1
  271. package/build/lib/notifyManager.mjs.map +0 -1
  272. package/build/lib/onlineManager.esm.js.map +0 -1
  273. package/build/lib/onlineManager.mjs.map +0 -1
  274. package/build/lib/queriesObserver.esm.js.map +0 -1
  275. package/build/lib/queriesObserver.mjs.map +0 -1
  276. package/build/lib/query.esm.js.map +0 -1
  277. package/build/lib/query.mjs.map +0 -1
  278. package/build/lib/queryCache.esm.js.map +0 -1
  279. package/build/lib/queryCache.mjs.map +0 -1
  280. package/build/lib/queryClient.esm.js.map +0 -1
  281. package/build/lib/queryClient.mjs.map +0 -1
  282. package/build/lib/queryObserver.esm.js.map +0 -1
  283. package/build/lib/queryObserver.mjs.map +0 -1
  284. package/build/lib/removable.esm.js.map +0 -1
  285. package/build/lib/retryer.esm.js.map +0 -1
  286. package/build/lib/subscribable.esm.js.map +0 -1
  287. package/build/lib/subscribable.mjs.map +0 -1
  288. package/build/lib/utils.esm.js.map +0 -1
  289. package/build/umd/index.development.js +0 -2683
  290. package/build/umd/index.development.js.map +0 -1
  291. package/build/umd/index.production.js +0 -2
  292. package/build/umd/index.production.js.map +0 -1
@@ -1,2683 +0,0 @@
1
- (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.QueryCore = {}));
5
- })(this, (function (exports) { 'use strict';
6
-
7
- class Subscribable {
8
- constructor() {
9
- this.listeners = [];
10
- this.subscribe = this.subscribe.bind(this);
11
- }
12
- subscribe(listener) {
13
- this.listeners.push(listener);
14
- this.onSubscribe();
15
- return () => {
16
- this.listeners = this.listeners.filter(x => x !== listener);
17
- this.onUnsubscribe();
18
- };
19
- }
20
- hasListeners() {
21
- return this.listeners.length > 0;
22
- }
23
- onSubscribe() {
24
- // Do nothing
25
- }
26
- onUnsubscribe() {
27
- // Do nothing
28
- }
29
- }
30
-
31
- // TYPES
32
-
33
- // UTILS
34
-
35
- const isServer = typeof window === 'undefined' || 'Deno' in window;
36
- function noop() {
37
- return undefined;
38
- }
39
- function functionalUpdate(updater, input) {
40
- return typeof updater === 'function' ? updater(input) : updater;
41
- }
42
- function isValidTimeout(value) {
43
- return typeof value === 'number' && value >= 0 && value !== Infinity;
44
- }
45
- function timeUntilStale(updatedAt, staleTime) {
46
- return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0);
47
- }
48
- function matchQuery(filters, query) {
49
- const {
50
- type = 'all',
51
- exact,
52
- fetchStatus,
53
- predicate,
54
- queryKey,
55
- stale
56
- } = filters;
57
- if (queryKey) {
58
- if (exact) {
59
- if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
60
- return false;
61
- }
62
- } else if (!partialMatchKey(query.queryKey, queryKey)) {
63
- return false;
64
- }
65
- }
66
- if (type !== 'all') {
67
- const isActive = query.isActive();
68
- if (type === 'active' && !isActive) {
69
- return false;
70
- }
71
- if (type === 'inactive' && isActive) {
72
- return false;
73
- }
74
- }
75
- if (typeof stale === 'boolean' && query.isStale() !== stale) {
76
- return false;
77
- }
78
- if (typeof fetchStatus !== 'undefined' && fetchStatus !== query.state.fetchStatus) {
79
- return false;
80
- }
81
- if (predicate && !predicate(query)) {
82
- return false;
83
- }
84
- return true;
85
- }
86
- function matchMutation(filters, mutation) {
87
- const {
88
- exact,
89
- status,
90
- predicate,
91
- mutationKey
92
- } = filters;
93
- if (mutationKey) {
94
- if (!mutation.options.mutationKey) {
95
- return false;
96
- }
97
- if (exact) {
98
- if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {
99
- return false;
100
- }
101
- } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {
102
- return false;
103
- }
104
- }
105
- if (status && mutation.state.status !== status) {
106
- return false;
107
- }
108
- if (predicate && !predicate(mutation)) {
109
- return false;
110
- }
111
- return true;
112
- }
113
- function hashQueryKeyByOptions(queryKey, options) {
114
- const hashFn = options?.queryKeyHashFn || hashKey;
115
- return hashFn(queryKey);
116
- }
117
-
118
- /**
119
- * Default query & mutation keys hash function.
120
- * Hashes the value into a stable hash.
121
- */
122
- function hashKey(queryKey) {
123
- return JSON.stringify(queryKey, (_, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key) => {
124
- result[key] = val[key];
125
- return result;
126
- }, {}) : val);
127
- }
128
-
129
- /**
130
- * Checks if key `b` partially matches with key `a`.
131
- */
132
-
133
- function partialMatchKey(a, b) {
134
- if (a === b) {
135
- return true;
136
- }
137
- if (typeof a !== typeof b) {
138
- return false;
139
- }
140
- if (a && b && typeof a === 'object' && typeof b === 'object') {
141
- return !Object.keys(b).some(key => !partialMatchKey(a[key], b[key]));
142
- }
143
- return false;
144
- }
145
-
146
- /**
147
- * This function returns `a` if `b` is deeply equal.
148
- * If not, it will replace any deeply equal children of `b` with those of `a`.
149
- * This can be used for structural sharing between JSON values for example.
150
- */
151
-
152
- function replaceEqualDeep(a, b) {
153
- if (a === b) {
154
- return a;
155
- }
156
- const array = isPlainArray(a) && isPlainArray(b);
157
- if (array || isPlainObject(a) && isPlainObject(b)) {
158
- const aSize = array ? a.length : Object.keys(a).length;
159
- const bItems = array ? b : Object.keys(b);
160
- const bSize = bItems.length;
161
- const copy = array ? [] : {};
162
- let equalItems = 0;
163
- for (let i = 0; i < bSize; i++) {
164
- const key = array ? i : bItems[i];
165
- copy[key] = replaceEqualDeep(a[key], b[key]);
166
- if (copy[key] === a[key]) {
167
- equalItems++;
168
- }
169
- }
170
- return aSize === bSize && equalItems === aSize ? a : copy;
171
- }
172
- return b;
173
- }
174
-
175
- /**
176
- * Shallow compare objects. Only works with objects that always have the same properties.
177
- */
178
- function shallowEqualObjects(a, b) {
179
- if (a && !b || b && !a) {
180
- return false;
181
- }
182
- for (const key in a) {
183
- if (a[key] !== b[key]) {
184
- return false;
185
- }
186
- }
187
- return true;
188
- }
189
- function isPlainArray(value) {
190
- return Array.isArray(value) && value.length === Object.keys(value).length;
191
- }
192
-
193
- // Copied from: https://github.com/jonschlinkert/is-plain-object
194
- function isPlainObject(o) {
195
- if (!hasObjectPrototype(o)) {
196
- return false;
197
- }
198
-
199
- // If has modified constructor
200
- const ctor = o.constructor;
201
- if (typeof ctor === 'undefined') {
202
- return true;
203
- }
204
-
205
- // If has modified prototype
206
- const prot = ctor.prototype;
207
- if (!hasObjectPrototype(prot)) {
208
- return false;
209
- }
210
-
211
- // If constructor does not have an Object-specific method
212
- if (!prot.hasOwnProperty('isPrototypeOf')) {
213
- return false;
214
- }
215
-
216
- // Most likely a plain Object
217
- return true;
218
- }
219
- function hasObjectPrototype(o) {
220
- return Object.prototype.toString.call(o) === '[object Object]';
221
- }
222
- function sleep(timeout) {
223
- return new Promise(resolve => {
224
- setTimeout(resolve, timeout);
225
- });
226
- }
227
-
228
- /**
229
- * Schedules a microtask.
230
- * This can be useful to schedule state updates after rendering.
231
- */
232
- function scheduleMicrotask(callback) {
233
- sleep(0).then(callback);
234
- }
235
- function replaceData(prevData, data, options) {
236
- if (typeof options.structuralSharing === 'function') {
237
- return options.structuralSharing(prevData, data);
238
- } else if (options.structuralSharing !== false) {
239
- // Structurally share data between prev and new data if needed
240
- return replaceEqualDeep(prevData, data);
241
- }
242
- return data;
243
- }
244
- function keepPreviousData(previousData) {
245
- return previousData;
246
- }
247
- function addToEnd(items, item, max = 0) {
248
- const newItems = [...items, item];
249
- return max && newItems.length > max ? newItems.slice(1) : newItems;
250
- }
251
- function addToStart(items, item, max = 0) {
252
- const newItems = [item, ...items];
253
- return max && newItems.length > max ? newItems.slice(0, -1) : newItems;
254
- }
255
-
256
- class FocusManager extends Subscribable {
257
- #focused;
258
- #cleanup;
259
- #setup;
260
- constructor() {
261
- super();
262
- this.#setup = onFocus => {
263
- // addEventListener does not exist in React Native, but window does
264
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
265
- if (!isServer && window.addEventListener) {
266
- const listener = () => onFocus();
267
- // Listen to visibilitychange
268
- window.addEventListener('visibilitychange', listener, false);
269
- return () => {
270
- // Be sure to unsubscribe if a new handler is set
271
- window.removeEventListener('visibilitychange', listener);
272
- };
273
- }
274
- return;
275
- };
276
- }
277
- onSubscribe() {
278
- if (!this.#cleanup) {
279
- this.setEventListener(this.#setup);
280
- }
281
- }
282
- onUnsubscribe() {
283
- if (!this.hasListeners()) {
284
- this.#cleanup?.();
285
- this.#cleanup = undefined;
286
- }
287
- }
288
- setEventListener(setup) {
289
- this.#setup = setup;
290
- this.#cleanup?.();
291
- this.#cleanup = setup(focused => {
292
- if (typeof focused === 'boolean') {
293
- this.setFocused(focused);
294
- } else {
295
- this.onFocus();
296
- }
297
- });
298
- }
299
- setFocused(focused) {
300
- this.#focused = focused;
301
- if (focused) {
302
- this.onFocus();
303
- }
304
- }
305
- onFocus() {
306
- this.listeners.forEach(listener => {
307
- listener();
308
- });
309
- }
310
- isFocused() {
311
- if (typeof this.#focused === 'boolean') {
312
- return this.#focused;
313
- }
314
-
315
- // document global can be unavailable in react native
316
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
317
- return globalThis.document?.visibilityState !== 'hidden';
318
- }
319
- }
320
- const focusManager = new FocusManager();
321
-
322
- class OnlineManager extends Subscribable {
323
- #online;
324
- #cleanup;
325
- #setup;
326
- constructor() {
327
- super();
328
- this.#setup = onOnline => {
329
- // addEventListener does not exist in React Native, but window does
330
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
331
- if (!isServer && window.addEventListener) {
332
- const listener = () => onOnline();
333
- // Listen to online
334
- window.addEventListener('online', listener, false);
335
- window.addEventListener('offline', listener, false);
336
- return () => {
337
- // Be sure to unsubscribe if a new handler is set
338
- window.removeEventListener('online', listener);
339
- window.removeEventListener('offline', listener);
340
- };
341
- }
342
- return;
343
- };
344
- }
345
- onSubscribe() {
346
- if (!this.#cleanup) {
347
- this.setEventListener(this.#setup);
348
- }
349
- }
350
- onUnsubscribe() {
351
- if (!this.hasListeners()) {
352
- this.#cleanup?.();
353
- this.#cleanup = undefined;
354
- }
355
- }
356
- setEventListener(setup) {
357
- this.#setup = setup;
358
- this.#cleanup?.();
359
- this.#cleanup = setup(online => {
360
- if (typeof online === 'boolean') {
361
- this.setOnline(online);
362
- } else {
363
- this.onOnline();
364
- }
365
- });
366
- }
367
- setOnline(online) {
368
- this.#online = online;
369
- if (online) {
370
- this.onOnline();
371
- }
372
- }
373
- onOnline() {
374
- this.listeners.forEach(listener => {
375
- listener();
376
- });
377
- }
378
- isOnline() {
379
- if (typeof this.#online === 'boolean') {
380
- return this.#online;
381
- }
382
- if (typeof navigator === 'undefined' || typeof navigator.onLine === 'undefined') {
383
- return true;
384
- }
385
- return navigator.onLine;
386
- }
387
- }
388
- const onlineManager = new OnlineManager();
389
-
390
- function defaultRetryDelay(failureCount) {
391
- return Math.min(1000 * 2 ** failureCount, 30000);
392
- }
393
- function canFetch(networkMode) {
394
- return (networkMode ?? 'online') === 'online' ? onlineManager.isOnline() : true;
395
- }
396
- class CancelledError {
397
- constructor(options) {
398
- this.revert = options?.revert;
399
- this.silent = options?.silent;
400
- }
401
- }
402
- function isCancelledError(value) {
403
- return value instanceof CancelledError;
404
- }
405
- function createRetryer(config) {
406
- let isRetryCancelled = false;
407
- let failureCount = 0;
408
- let isResolved = false;
409
- let continueFn;
410
- let promiseResolve;
411
- let promiseReject;
412
- const promise = new Promise((outerResolve, outerReject) => {
413
- promiseResolve = outerResolve;
414
- promiseReject = outerReject;
415
- });
416
- const cancel = cancelOptions => {
417
- if (!isResolved) {
418
- reject(new CancelledError(cancelOptions));
419
- config.abort?.();
420
- }
421
- };
422
- const cancelRetry = () => {
423
- isRetryCancelled = true;
424
- };
425
- const continueRetry = () => {
426
- isRetryCancelled = false;
427
- };
428
- const shouldPause = () => !focusManager.isFocused() || config.networkMode !== 'always' && !onlineManager.isOnline();
429
- const resolve = value => {
430
- if (!isResolved) {
431
- isResolved = true;
432
- config.onSuccess?.(value);
433
- continueFn?.();
434
- promiseResolve(value);
435
- }
436
- };
437
- const reject = value => {
438
- if (!isResolved) {
439
- isResolved = true;
440
- config.onError?.(value);
441
- continueFn?.();
442
- promiseReject(value);
443
- }
444
- };
445
- const pause = () => {
446
- return new Promise(continueResolve => {
447
- continueFn = value => {
448
- const canContinue = isResolved || !shouldPause();
449
- if (canContinue) {
450
- continueResolve(value);
451
- }
452
- return canContinue;
453
- };
454
- config.onPause?.();
455
- }).then(() => {
456
- continueFn = undefined;
457
- if (!isResolved) {
458
- config.onContinue?.();
459
- }
460
- });
461
- };
462
-
463
- // Create loop function
464
- const run = () => {
465
- // Do nothing if already resolved
466
- if (isResolved) {
467
- return;
468
- }
469
- let promiseOrValue;
470
-
471
- // Execute query
472
- try {
473
- promiseOrValue = config.fn();
474
- } catch (error) {
475
- promiseOrValue = Promise.reject(error);
476
- }
477
- Promise.resolve(promiseOrValue).then(resolve).catch(error => {
478
- // Stop if the fetch is already resolved
479
- if (isResolved) {
480
- return;
481
- }
482
-
483
- // Do we need to retry the request?
484
- const retry = config.retry ?? 3;
485
- const retryDelay = config.retryDelay ?? defaultRetryDelay;
486
- const delay = typeof retryDelay === 'function' ? retryDelay(failureCount, error) : retryDelay;
487
- const shouldRetry = retry === true || typeof retry === 'number' && failureCount < retry || typeof retry === 'function' && retry(failureCount, error);
488
- if (isRetryCancelled || !shouldRetry) {
489
- // We are done if the query does not need to be retried
490
- reject(error);
491
- return;
492
- }
493
- failureCount++;
494
-
495
- // Notify on fail
496
- config.onFail?.(failureCount, error);
497
-
498
- // Delay
499
- sleep(delay)
500
- // Pause if the document is not visible or when the device is offline
501
- .then(() => {
502
- if (shouldPause()) {
503
- return pause();
504
- }
505
- return;
506
- }).then(() => {
507
- if (isRetryCancelled) {
508
- reject(error);
509
- } else {
510
- run();
511
- }
512
- });
513
- });
514
- };
515
-
516
- // Start loop
517
- if (canFetch(config.networkMode)) {
518
- run();
519
- } else {
520
- pause().then(run);
521
- }
522
- return {
523
- promise,
524
- cancel,
525
- continue: () => {
526
- const didContinue = continueFn?.();
527
- return didContinue ? promise : Promise.resolve();
528
- },
529
- cancelRetry,
530
- continueRetry
531
- };
532
- }
533
-
534
- // TYPES
535
-
536
- function createNotifyManager() {
537
- let queue = [];
538
- let transactions = 0;
539
- let notifyFn = callback => {
540
- callback();
541
- };
542
- let batchNotifyFn = callback => {
543
- callback();
544
- };
545
- const batch = callback => {
546
- let result;
547
- transactions++;
548
- try {
549
- result = callback();
550
- } finally {
551
- transactions--;
552
- if (!transactions) {
553
- flush();
554
- }
555
- }
556
- return result;
557
- };
558
- const schedule = callback => {
559
- if (transactions) {
560
- queue.push(callback);
561
- } else {
562
- scheduleMicrotask(() => {
563
- notifyFn(callback);
564
- });
565
- }
566
- };
567
-
568
- /**
569
- * All calls to the wrapped function will be batched.
570
- */
571
- const batchCalls = callback => {
572
- return (...args) => {
573
- schedule(() => {
574
- callback(...args);
575
- });
576
- };
577
- };
578
- const flush = () => {
579
- const originalQueue = queue;
580
- queue = [];
581
- if (originalQueue.length) {
582
- scheduleMicrotask(() => {
583
- batchNotifyFn(() => {
584
- originalQueue.forEach(callback => {
585
- notifyFn(callback);
586
- });
587
- });
588
- });
589
- }
590
- };
591
-
592
- /**
593
- * Use this method to set a custom notify function.
594
- * This can be used to for example wrap notifications with `React.act` while running tests.
595
- */
596
- const setNotifyFunction = fn => {
597
- notifyFn = fn;
598
- };
599
-
600
- /**
601
- * Use this method to set a custom function to batch notifications together into a single tick.
602
- * By default React Query will use the batch function provided by ReactDOM or React Native.
603
- */
604
- const setBatchNotifyFunction = fn => {
605
- batchNotifyFn = fn;
606
- };
607
- return {
608
- batch,
609
- batchCalls,
610
- schedule,
611
- setNotifyFunction,
612
- setBatchNotifyFunction
613
- };
614
- }
615
-
616
- // SINGLETON
617
- const notifyManager = createNotifyManager();
618
-
619
- class Removable {
620
- #gcTimeout;
621
- destroy() {
622
- this.clearGcTimeout();
623
- }
624
- scheduleGc() {
625
- this.clearGcTimeout();
626
- if (isValidTimeout(this.gcTime)) {
627
- this.#gcTimeout = setTimeout(() => {
628
- this.optionalRemove();
629
- }, this.gcTime);
630
- }
631
- }
632
- updateGcTime(newGcTime) {
633
- // Default to 5 minutes (Infinity for server-side) if no gcTime is set
634
- this.gcTime = Math.max(this.gcTime || 0, newGcTime ?? (isServer ? Infinity : 5 * 60 * 1000));
635
- }
636
- clearGcTimeout() {
637
- if (this.#gcTimeout) {
638
- clearTimeout(this.#gcTimeout);
639
- this.#gcTimeout = undefined;
640
- }
641
- }
642
- }
643
-
644
- // TYPES
645
-
646
- // CLASS
647
-
648
- class Query extends Removable {
649
- #initialState;
650
- #revertState;
651
- #cache;
652
- #promise;
653
- #retryer;
654
- #observers;
655
- #defaultOptions;
656
- #abortSignalConsumed;
657
- constructor(config) {
658
- super();
659
- this.#abortSignalConsumed = false;
660
- this.#defaultOptions = config.defaultOptions;
661
- this.#setOptions(config.options);
662
- this.#observers = [];
663
- this.#cache = config.cache;
664
- this.queryKey = config.queryKey;
665
- this.queryHash = config.queryHash;
666
- this.#initialState = config.state || getDefaultState$1(this.options);
667
- this.state = this.#initialState;
668
- this.scheduleGc();
669
- }
670
- get meta() {
671
- return this.options.meta;
672
- }
673
- #setOptions(options) {
674
- this.options = {
675
- ...this.#defaultOptions,
676
- ...options
677
- };
678
- this.updateGcTime(this.options.gcTime);
679
- }
680
- optionalRemove() {
681
- if (!this.#observers.length && this.state.fetchStatus === 'idle') {
682
- this.#cache.remove(this);
683
- }
684
- }
685
- setData(newData, options) {
686
- const data = replaceData(this.state.data, newData, this.options);
687
-
688
- // Set data and mark it as cached
689
- this.#dispatch({
690
- data,
691
- type: 'success',
692
- dataUpdatedAt: options?.updatedAt,
693
- manual: options?.manual
694
- });
695
- return data;
696
- }
697
- setState(state, setStateOptions) {
698
- this.#dispatch({
699
- type: 'setState',
700
- state,
701
- setStateOptions
702
- });
703
- }
704
- cancel(options) {
705
- const promise = this.#promise;
706
- this.#retryer?.cancel(options);
707
- return promise ? promise.then(noop).catch(noop) : Promise.resolve();
708
- }
709
- destroy() {
710
- super.destroy();
711
- this.cancel({
712
- silent: true
713
- });
714
- }
715
- reset() {
716
- this.destroy();
717
- this.setState(this.#initialState);
718
- }
719
- isActive() {
720
- return this.#observers.some(observer => observer.options.enabled !== false);
721
- }
722
- isDisabled() {
723
- return this.getObserversCount() > 0 && !this.isActive();
724
- }
725
- isStale() {
726
- return this.state.isInvalidated || !this.state.dataUpdatedAt || this.#observers.some(observer => observer.getCurrentResult().isStale);
727
- }
728
- isStaleByTime(staleTime = 0) {
729
- return this.state.isInvalidated || !this.state.dataUpdatedAt || !timeUntilStale(this.state.dataUpdatedAt, staleTime);
730
- }
731
- onFocus() {
732
- const observer = this.#observers.find(x => x.shouldFetchOnWindowFocus());
733
- observer?.refetch({
734
- cancelRefetch: false
735
- });
736
-
737
- // Continue fetch if currently paused
738
- this.#retryer?.continue();
739
- }
740
- onOnline() {
741
- const observer = this.#observers.find(x => x.shouldFetchOnReconnect());
742
- observer?.refetch({
743
- cancelRefetch: false
744
- });
745
-
746
- // Continue fetch if currently paused
747
- this.#retryer?.continue();
748
- }
749
- addObserver(observer) {
750
- if (this.#observers.indexOf(observer) === -1) {
751
- this.#observers.push(observer);
752
-
753
- // Stop the query from being garbage collected
754
- this.clearGcTimeout();
755
- this.#cache.notify({
756
- type: 'observerAdded',
757
- query: this,
758
- observer
759
- });
760
- }
761
- }
762
- removeObserver(observer) {
763
- if (this.#observers.indexOf(observer) !== -1) {
764
- this.#observers = this.#observers.filter(x => x !== observer);
765
- if (!this.#observers.length) {
766
- // If the transport layer does not support cancellation
767
- // we'll let the query continue so the result can be cached
768
- if (this.#retryer) {
769
- if (this.#abortSignalConsumed) {
770
- this.#retryer.cancel({
771
- revert: true
772
- });
773
- } else {
774
- this.#retryer.cancelRetry();
775
- }
776
- }
777
- this.scheduleGc();
778
- }
779
- this.#cache.notify({
780
- type: 'observerRemoved',
781
- query: this,
782
- observer
783
- });
784
- }
785
- }
786
- getObserversCount() {
787
- return this.#observers.length;
788
- }
789
- invalidate() {
790
- if (!this.state.isInvalidated) {
791
- this.#dispatch({
792
- type: 'invalidate'
793
- });
794
- }
795
- }
796
- fetch(options, fetchOptions) {
797
- if (this.state.fetchStatus !== 'idle') {
798
- if (this.state.dataUpdatedAt && fetchOptions?.cancelRefetch) {
799
- // Silently cancel current fetch if the user wants to cancel refetches
800
- this.cancel({
801
- silent: true
802
- });
803
- } else if (this.#promise) {
804
- // make sure that retries that were potentially cancelled due to unmounts can continue
805
- this.#retryer?.continueRetry();
806
- // Return current promise if we are already fetching
807
- return this.#promise;
808
- }
809
- }
810
-
811
- // Update config if passed, otherwise the config from the last execution is used
812
- if (options) {
813
- this.#setOptions(options);
814
- }
815
-
816
- // Use the options from the first observer with a query function if no function is found.
817
- // This can happen when the query is hydrated or created with setQueryData.
818
- if (!this.options.queryFn) {
819
- const observer = this.#observers.find(x => x.options.queryFn);
820
- if (observer) {
821
- this.#setOptions(observer.options);
822
- }
823
- }
824
- {
825
- if (!Array.isArray(this.options.queryKey)) {
826
- console.error(`As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`);
827
- }
828
- }
829
- const abortController = new AbortController();
830
-
831
- // Create query function context
832
- const queryFnContext = {
833
- queryKey: this.queryKey,
834
- meta: this.meta
835
- };
836
-
837
- // Adds an enumerable signal property to the object that
838
- // which sets abortSignalConsumed to true when the signal
839
- // is read.
840
- const addSignalProperty = object => {
841
- Object.defineProperty(object, 'signal', {
842
- enumerable: true,
843
- get: () => {
844
- this.#abortSignalConsumed = true;
845
- return abortController.signal;
846
- }
847
- });
848
- };
849
- addSignalProperty(queryFnContext);
850
-
851
- // Create fetch function
852
- const fetchFn = () => {
853
- if (!this.options.queryFn) {
854
- return Promise.reject(new Error('Missing queryFn'));
855
- }
856
- this.#abortSignalConsumed = false;
857
- return this.options.queryFn(queryFnContext);
858
- };
859
-
860
- // Trigger behavior hook
861
- const context = {
862
- fetchOptions,
863
- options: this.options,
864
- queryKey: this.queryKey,
865
- state: this.state,
866
- fetchFn
867
- };
868
- addSignalProperty(context);
869
- this.options.behavior?.onFetch(context);
870
-
871
- // Store state in case the current fetch needs to be reverted
872
- this.#revertState = this.state;
873
-
874
- // Set to fetching state if not already in it
875
- if (this.state.fetchStatus === 'idle' || this.state.fetchMeta !== context.fetchOptions?.meta) {
876
- this.#dispatch({
877
- type: 'fetch',
878
- meta: context.fetchOptions?.meta
879
- });
880
- }
881
- const onError = error => {
882
- // Optimistically update state if needed
883
- if (!(isCancelledError(error) && error.silent)) {
884
- this.#dispatch({
885
- type: 'error',
886
- error: error
887
- });
888
- }
889
- if (!isCancelledError(error)) {
890
- // Notify cache callback
891
- this.#cache.config.onError?.(error, this);
892
- this.#cache.config.onSettled?.(this.state.data, error, this);
893
- }
894
- if (!this.isFetchingOptimistic) {
895
- // Schedule query gc after fetching
896
- this.scheduleGc();
897
- }
898
- this.isFetchingOptimistic = false;
899
- };
900
-
901
- // Try to fetch the data
902
- this.#retryer = createRetryer({
903
- fn: context.fetchFn,
904
- abort: abortController.abort.bind(abortController),
905
- onSuccess: data => {
906
- if (typeof data === 'undefined') {
907
- {
908
- console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`);
909
- }
910
- onError(new Error('undefined'));
911
- return;
912
- }
913
- this.setData(data);
914
-
915
- // Notify cache callback
916
- this.#cache.config.onSuccess?.(data, this);
917
- this.#cache.config.onSettled?.(data, this.state.error, this);
918
- if (!this.isFetchingOptimistic) {
919
- // Schedule query gc after fetching
920
- this.scheduleGc();
921
- }
922
- this.isFetchingOptimistic = false;
923
- },
924
- onError,
925
- onFail: (failureCount, error) => {
926
- this.#dispatch({
927
- type: 'failed',
928
- failureCount,
929
- error
930
- });
931
- },
932
- onPause: () => {
933
- this.#dispatch({
934
- type: 'pause'
935
- });
936
- },
937
- onContinue: () => {
938
- this.#dispatch({
939
- type: 'continue'
940
- });
941
- },
942
- retry: context.options.retry,
943
- retryDelay: context.options.retryDelay,
944
- networkMode: context.options.networkMode
945
- });
946
- this.#promise = this.#retryer.promise;
947
- return this.#promise;
948
- }
949
- #dispatch(action) {
950
- const reducer = state => {
951
- switch (action.type) {
952
- case 'failed':
953
- return {
954
- ...state,
955
- fetchFailureCount: action.failureCount,
956
- fetchFailureReason: action.error
957
- };
958
- case 'pause':
959
- return {
960
- ...state,
961
- fetchStatus: 'paused'
962
- };
963
- case 'continue':
964
- return {
965
- ...state,
966
- fetchStatus: 'fetching'
967
- };
968
- case 'fetch':
969
- return {
970
- ...state,
971
- fetchFailureCount: 0,
972
- fetchFailureReason: null,
973
- fetchMeta: action.meta ?? null,
974
- fetchStatus: canFetch(this.options.networkMode) ? 'fetching' : 'paused',
975
- ...(!state.dataUpdatedAt && {
976
- error: null,
977
- status: 'pending'
978
- })
979
- };
980
- case 'success':
981
- return {
982
- ...state,
983
- data: action.data,
984
- dataUpdateCount: state.dataUpdateCount + 1,
985
- dataUpdatedAt: action.dataUpdatedAt ?? Date.now(),
986
- error: null,
987
- isInvalidated: false,
988
- status: 'success',
989
- ...(!action.manual && {
990
- fetchStatus: 'idle',
991
- fetchFailureCount: 0,
992
- fetchFailureReason: null
993
- })
994
- };
995
- case 'error':
996
- const error = action.error;
997
- if (isCancelledError(error) && error.revert && this.#revertState) {
998
- return {
999
- ...this.#revertState
1000
- };
1001
- }
1002
- return {
1003
- ...state,
1004
- error: error,
1005
- errorUpdateCount: state.errorUpdateCount + 1,
1006
- errorUpdatedAt: Date.now(),
1007
- fetchFailureCount: state.fetchFailureCount + 1,
1008
- fetchFailureReason: error,
1009
- fetchStatus: 'idle',
1010
- status: 'error'
1011
- };
1012
- case 'invalidate':
1013
- return {
1014
- ...state,
1015
- isInvalidated: true
1016
- };
1017
- case 'setState':
1018
- return {
1019
- ...state,
1020
- ...action.state
1021
- };
1022
- }
1023
- };
1024
- this.state = reducer(this.state);
1025
- notifyManager.batch(() => {
1026
- this.#observers.forEach(observer => {
1027
- observer.onQueryUpdate(action);
1028
- });
1029
- this.#cache.notify({
1030
- query: this,
1031
- type: 'updated',
1032
- action
1033
- });
1034
- });
1035
- }
1036
- }
1037
- function getDefaultState$1(options) {
1038
- const data = typeof options.initialData === 'function' ? options.initialData() : options.initialData;
1039
- const hasData = typeof data !== 'undefined';
1040
- const initialDataUpdatedAt = hasData ? typeof options.initialDataUpdatedAt === 'function' ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;
1041
- return {
1042
- data,
1043
- dataUpdateCount: 0,
1044
- dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0,
1045
- error: null,
1046
- errorUpdateCount: 0,
1047
- errorUpdatedAt: 0,
1048
- fetchFailureCount: 0,
1049
- fetchFailureReason: null,
1050
- fetchMeta: null,
1051
- isInvalidated: false,
1052
- status: hasData ? 'success' : 'pending',
1053
- fetchStatus: 'idle'
1054
- };
1055
- }
1056
-
1057
- // CLASS
1058
-
1059
- class QueryCache extends Subscribable {
1060
- #queries;
1061
- constructor(config = {}) {
1062
- super();
1063
- this.config = config;
1064
- this.#queries = config.createStore?.() ?? new Map();
1065
- }
1066
- build(client, options, state) {
1067
- const queryKey = options.queryKey;
1068
- const queryHash = options.queryHash ?? hashQueryKeyByOptions(queryKey, options);
1069
- let query = this.get(queryHash);
1070
- if (!query) {
1071
- query = new Query({
1072
- cache: this,
1073
- queryKey,
1074
- queryHash,
1075
- options: client.defaultQueryOptions(options),
1076
- state,
1077
- defaultOptions: client.getQueryDefaults(queryKey)
1078
- });
1079
- this.add(query);
1080
- }
1081
- return query;
1082
- }
1083
- add(query) {
1084
- if (!this.#queries.has(query.queryHash)) {
1085
- this.#queries.set(query.queryHash, query);
1086
- this.notify({
1087
- type: 'added',
1088
- query
1089
- });
1090
- }
1091
- }
1092
- remove(query) {
1093
- const queryInMap = this.#queries.get(query.queryHash);
1094
- if (queryInMap) {
1095
- query.destroy();
1096
- if (queryInMap === query) {
1097
- this.#queries.delete(query.queryHash);
1098
- }
1099
- this.notify({
1100
- type: 'removed',
1101
- query
1102
- });
1103
- }
1104
- }
1105
- clear() {
1106
- notifyManager.batch(() => {
1107
- this.getAll().forEach(query => {
1108
- this.remove(query);
1109
- });
1110
- });
1111
- }
1112
- get(queryHash) {
1113
- return this.#queries.get(queryHash);
1114
- }
1115
- getAll() {
1116
- return [...this.#queries.values()];
1117
- }
1118
- find(filters) {
1119
- if (typeof filters.exact === 'undefined') {
1120
- filters.exact = true;
1121
- }
1122
- return this.getAll().find(query => matchQuery(filters, query));
1123
- }
1124
- findAll(filters = {}) {
1125
- const queries = this.getAll();
1126
- return Object.keys(filters).length > 0 ? queries.filter(query => matchQuery(filters, query)) : queries;
1127
- }
1128
- notify(event) {
1129
- notifyManager.batch(() => {
1130
- this.listeners.forEach(listener => {
1131
- listener(event);
1132
- });
1133
- });
1134
- }
1135
- onFocus() {
1136
- notifyManager.batch(() => {
1137
- this.getAll().forEach(query => {
1138
- query.onFocus();
1139
- });
1140
- });
1141
- }
1142
- onOnline() {
1143
- notifyManager.batch(() => {
1144
- this.getAll().forEach(query => {
1145
- query.onOnline();
1146
- });
1147
- });
1148
- }
1149
- }
1150
-
1151
- // TYPES
1152
-
1153
- // CLASS
1154
-
1155
- class Mutation extends Removable {
1156
- #observers;
1157
- #defaultOptions;
1158
- #mutationCache;
1159
- #retryer;
1160
- constructor(config) {
1161
- super();
1162
- this.mutationId = config.mutationId;
1163
- this.#defaultOptions = config.defaultOptions;
1164
- this.#mutationCache = config.mutationCache;
1165
- this.#observers = [];
1166
- this.state = config.state || getDefaultState();
1167
- this.setOptions(config.options);
1168
- this.scheduleGc();
1169
- }
1170
- setOptions(options) {
1171
- this.options = {
1172
- ...this.#defaultOptions,
1173
- ...options
1174
- };
1175
- this.updateGcTime(this.options.gcTime);
1176
- }
1177
- get meta() {
1178
- return this.options.meta;
1179
- }
1180
- addObserver(observer) {
1181
- if (this.#observers.indexOf(observer) === -1) {
1182
- this.#observers.push(observer);
1183
-
1184
- // Stop the mutation from being garbage collected
1185
- this.clearGcTimeout();
1186
- this.#mutationCache.notify({
1187
- type: 'observerAdded',
1188
- mutation: this,
1189
- observer
1190
- });
1191
- }
1192
- }
1193
- removeObserver(observer) {
1194
- this.#observers = this.#observers.filter(x => x !== observer);
1195
- this.scheduleGc();
1196
- this.#mutationCache.notify({
1197
- type: 'observerRemoved',
1198
- mutation: this,
1199
- observer
1200
- });
1201
- }
1202
- optionalRemove() {
1203
- if (!this.#observers.length) {
1204
- if (this.state.status === 'pending') {
1205
- this.scheduleGc();
1206
- } else {
1207
- this.#mutationCache.remove(this);
1208
- }
1209
- }
1210
- }
1211
- continue() {
1212
- return this.#retryer?.continue() ??
1213
- // continuing a mutation assumes that variables are set, mutation must have been dehydrated before
1214
- this.execute(this.state.variables);
1215
- }
1216
- async execute(variables) {
1217
- const executeMutation = () => {
1218
- this.#retryer = createRetryer({
1219
- fn: () => {
1220
- if (!this.options.mutationFn) {
1221
- return Promise.reject(new Error('No mutationFn found'));
1222
- }
1223
- return this.options.mutationFn(variables);
1224
- },
1225
- onFail: (failureCount, error) => {
1226
- this.#dispatch({
1227
- type: 'failed',
1228
- failureCount,
1229
- error
1230
- });
1231
- },
1232
- onPause: () => {
1233
- this.#dispatch({
1234
- type: 'pause'
1235
- });
1236
- },
1237
- onContinue: () => {
1238
- this.#dispatch({
1239
- type: 'continue'
1240
- });
1241
- },
1242
- retry: this.options.retry ?? 0,
1243
- retryDelay: this.options.retryDelay,
1244
- networkMode: this.options.networkMode
1245
- });
1246
- return this.#retryer.promise;
1247
- };
1248
- const restored = this.state.status === 'pending';
1249
- try {
1250
- if (!restored) {
1251
- this.#dispatch({
1252
- type: 'pending',
1253
- variables
1254
- });
1255
- // Notify cache callback
1256
- await this.#mutationCache.config.onMutate?.(variables, this);
1257
- const context = await this.options.onMutate?.(variables);
1258
- if (context !== this.state.context) {
1259
- this.#dispatch({
1260
- type: 'pending',
1261
- context,
1262
- variables
1263
- });
1264
- }
1265
- }
1266
- const data = await executeMutation();
1267
-
1268
- // Notify cache callback
1269
- await this.#mutationCache.config.onSuccess?.(data, variables, this.state.context, this);
1270
- await this.options.onSuccess?.(data, variables, this.state.context);
1271
-
1272
- // Notify cache callback
1273
- await this.#mutationCache.config.onSettled?.(data, null, this.state.variables, this.state.context, this);
1274
- await this.options.onSettled?.(data, null, variables, this.state.context);
1275
- this.#dispatch({
1276
- type: 'success',
1277
- data
1278
- });
1279
- return data;
1280
- } catch (error) {
1281
- try {
1282
- // Notify cache callback
1283
- await this.#mutationCache.config.onError?.(error, variables, this.state.context, this);
1284
- await this.options.onError?.(error, variables, this.state.context);
1285
-
1286
- // Notify cache callback
1287
- await this.#mutationCache.config.onSettled?.(undefined, error, this.state.variables, this.state.context, this);
1288
- await this.options.onSettled?.(undefined, error, variables, this.state.context);
1289
- throw error;
1290
- } finally {
1291
- this.#dispatch({
1292
- type: 'error',
1293
- error: error
1294
- });
1295
- }
1296
- }
1297
- }
1298
- #dispatch(action) {
1299
- const reducer = state => {
1300
- switch (action.type) {
1301
- case 'failed':
1302
- return {
1303
- ...state,
1304
- failureCount: action.failureCount,
1305
- failureReason: action.error
1306
- };
1307
- case 'pause':
1308
- return {
1309
- ...state,
1310
- isPaused: true
1311
- };
1312
- case 'continue':
1313
- return {
1314
- ...state,
1315
- isPaused: false
1316
- };
1317
- case 'pending':
1318
- return {
1319
- ...state,
1320
- context: action.context,
1321
- data: undefined,
1322
- failureCount: 0,
1323
- failureReason: null,
1324
- error: null,
1325
- isPaused: !canFetch(this.options.networkMode),
1326
- status: 'pending',
1327
- variables: action.variables,
1328
- submittedAt: Date.now()
1329
- };
1330
- case 'success':
1331
- return {
1332
- ...state,
1333
- data: action.data,
1334
- failureCount: 0,
1335
- failureReason: null,
1336
- error: null,
1337
- status: 'success',
1338
- isPaused: false
1339
- };
1340
- case 'error':
1341
- return {
1342
- ...state,
1343
- data: undefined,
1344
- error: action.error,
1345
- failureCount: state.failureCount + 1,
1346
- failureReason: action.error,
1347
- isPaused: false,
1348
- status: 'error'
1349
- };
1350
- }
1351
- };
1352
- this.state = reducer(this.state);
1353
- notifyManager.batch(() => {
1354
- this.#observers.forEach(observer => {
1355
- observer.onMutationUpdate(action);
1356
- });
1357
- this.#mutationCache.notify({
1358
- mutation: this,
1359
- type: 'updated',
1360
- action
1361
- });
1362
- });
1363
- }
1364
- }
1365
- function getDefaultState() {
1366
- return {
1367
- context: undefined,
1368
- data: undefined,
1369
- error: null,
1370
- failureCount: 0,
1371
- failureReason: null,
1372
- isPaused: false,
1373
- status: 'idle',
1374
- variables: undefined,
1375
- submittedAt: 0
1376
- };
1377
- }
1378
-
1379
- // TYPES
1380
-
1381
- // CLASS
1382
-
1383
- class MutationCache extends Subscribable {
1384
- #mutations;
1385
- #mutationId;
1386
- #resuming;
1387
- constructor(config = {}) {
1388
- super();
1389
- this.config = config;
1390
- this.#mutations = [];
1391
- this.#mutationId = 0;
1392
- }
1393
- build(client, options, state) {
1394
- const mutation = new Mutation({
1395
- mutationCache: this,
1396
- mutationId: ++this.#mutationId,
1397
- options: client.defaultMutationOptions(options),
1398
- state
1399
- });
1400
- this.add(mutation);
1401
- return mutation;
1402
- }
1403
- add(mutation) {
1404
- this.#mutations.push(mutation);
1405
- this.notify({
1406
- type: 'added',
1407
- mutation
1408
- });
1409
- }
1410
- remove(mutation) {
1411
- this.#mutations = this.#mutations.filter(x => x !== mutation);
1412
- this.notify({
1413
- type: 'removed',
1414
- mutation
1415
- });
1416
- }
1417
- clear() {
1418
- notifyManager.batch(() => {
1419
- this.#mutations.forEach(mutation => {
1420
- this.remove(mutation);
1421
- });
1422
- });
1423
- }
1424
- getAll() {
1425
- return this.#mutations;
1426
- }
1427
- find(filters) {
1428
- if (typeof filters.exact === 'undefined') {
1429
- filters.exact = true;
1430
- }
1431
- return this.#mutations.find(mutation => matchMutation(filters, mutation));
1432
- }
1433
- findAll(filters = {}) {
1434
- return this.#mutations.filter(mutation => matchMutation(filters, mutation));
1435
- }
1436
- notify(event) {
1437
- notifyManager.batch(() => {
1438
- this.listeners.forEach(listener => {
1439
- listener(event);
1440
- });
1441
- });
1442
- }
1443
- resumePausedMutations() {
1444
- this.#resuming = (this.#resuming ?? Promise.resolve()).then(() => {
1445
- const pausedMutations = this.#mutations.filter(x => x.state.isPaused);
1446
- return notifyManager.batch(() => pausedMutations.reduce((promise, mutation) => promise.then(() => mutation.continue().catch(noop)), Promise.resolve()));
1447
- }).then(() => {
1448
- this.#resuming = undefined;
1449
- });
1450
- return this.#resuming;
1451
- }
1452
- }
1453
-
1454
- function infiniteQueryBehavior() {
1455
- return {
1456
- onFetch: context => {
1457
- context.fetchFn = async () => {
1458
- const options = context.options;
1459
- const direction = context.fetchOptions?.meta?.fetchMore?.direction;
1460
- const oldPages = context.state.data?.pages || [];
1461
- const oldPageParams = context.state.data?.pageParams || [];
1462
- const empty = {
1463
- pages: [],
1464
- pageParams: []
1465
- };
1466
- let cancelled = false;
1467
- const addSignalProperty = object => {
1468
- Object.defineProperty(object, 'signal', {
1469
- enumerable: true,
1470
- get: () => {
1471
- if (context.signal.aborted) {
1472
- cancelled = true;
1473
- } else {
1474
- context.signal.addEventListener('abort', () => {
1475
- cancelled = true;
1476
- });
1477
- }
1478
- return context.signal;
1479
- }
1480
- });
1481
- };
1482
-
1483
- // Get query function
1484
- const queryFn = context.options.queryFn || (() => Promise.reject(new Error('Missing queryFn')));
1485
-
1486
- // Create function to fetch a page
1487
- const fetchPage = async (data, param, previous) => {
1488
- if (cancelled) {
1489
- return Promise.reject();
1490
- }
1491
- if (typeof param === 'undefined' && data.pages.length) {
1492
- return Promise.resolve(data);
1493
- }
1494
- const queryFnContext = {
1495
- queryKey: context.queryKey,
1496
- pageParam: param,
1497
- direction: previous ? 'backward' : 'forward',
1498
- meta: context.options.meta
1499
- };
1500
- addSignalProperty(queryFnContext);
1501
- const page = await queryFn(queryFnContext);
1502
- const {
1503
- maxPages
1504
- } = context.options;
1505
- const addTo = previous ? addToStart : addToEnd;
1506
- return {
1507
- pages: addTo(data.pages, page, maxPages),
1508
- pageParams: addTo(data.pageParams, param, maxPages)
1509
- };
1510
- };
1511
- let result;
1512
-
1513
- // Fetch first page?
1514
- if (!oldPages.length) {
1515
- result = await fetchPage(empty, options.defaultPageParam);
1516
- }
1517
-
1518
- // fetch next / previous page?
1519
- else if (direction) {
1520
- const previous = direction === 'backward';
1521
- const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;
1522
- const oldData = {
1523
- pages: oldPages,
1524
- pageParams: oldPageParams
1525
- };
1526
- const param = pageParamFn(options, oldData);
1527
- result = await fetchPage(oldData, param, previous);
1528
- }
1529
-
1530
- // Refetch pages
1531
- else {
1532
- // Fetch first page
1533
- result = await fetchPage(empty, oldPageParams[0]);
1534
-
1535
- // Fetch remaining pages
1536
- for (let i = 1; i < oldPages.length; i++) {
1537
- const param = getNextPageParam(options, result);
1538
- result = await fetchPage(result, param);
1539
- }
1540
- }
1541
- return result;
1542
- };
1543
- }
1544
- };
1545
- }
1546
- function getNextPageParam(options, {
1547
- pages,
1548
- pageParams
1549
- }) {
1550
- const lastIndex = pages.length - 1;
1551
- return options.getNextPageParam(pages[lastIndex], pages, pageParams[lastIndex], pageParams);
1552
- }
1553
- function getPreviousPageParam(options, {
1554
- pages,
1555
- pageParams
1556
- }) {
1557
- return options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams);
1558
- }
1559
-
1560
- /**
1561
- * Checks if there is a next page.
1562
- */
1563
- function hasNextPage(options, data) {
1564
- if (!data) return false;
1565
- return typeof getNextPageParam(options, data) !== 'undefined';
1566
- }
1567
-
1568
- /**
1569
- * Checks if there is a previous page.
1570
- */
1571
- function hasPreviousPage(options, data) {
1572
- if (!data || !options.getPreviousPageParam) return false;
1573
- return typeof getPreviousPageParam(options, data) !== 'undefined';
1574
- }
1575
-
1576
- // CLASS
1577
-
1578
- class QueryClient {
1579
- #queryCache;
1580
- #mutationCache;
1581
- #defaultOptions;
1582
- #queryDefaults;
1583
- #mutationDefaults;
1584
- #mountCount;
1585
- #unsubscribeFocus;
1586
- #unsubscribeOnline;
1587
- constructor(config = {}) {
1588
- this.#queryCache = config.queryCache || new QueryCache();
1589
- this.#mutationCache = config.mutationCache || new MutationCache();
1590
- this.#defaultOptions = config.defaultOptions || {};
1591
- this.#queryDefaults = new Map();
1592
- this.#mutationDefaults = new Map();
1593
- this.#mountCount = 0;
1594
- }
1595
- mount() {
1596
- this.#mountCount++;
1597
- if (this.#mountCount !== 1) return;
1598
- this.#unsubscribeFocus = focusManager.subscribe(() => {
1599
- if (focusManager.isFocused()) {
1600
- this.resumePausedMutations();
1601
- this.#queryCache.onFocus();
1602
- }
1603
- });
1604
- this.#unsubscribeOnline = onlineManager.subscribe(() => {
1605
- if (onlineManager.isOnline()) {
1606
- this.resumePausedMutations();
1607
- this.#queryCache.onOnline();
1608
- }
1609
- });
1610
- }
1611
- unmount() {
1612
- this.#mountCount--;
1613
- if (this.#mountCount !== 0) return;
1614
- this.#unsubscribeFocus?.();
1615
- this.#unsubscribeFocus = undefined;
1616
- this.#unsubscribeOnline?.();
1617
- this.#unsubscribeOnline = undefined;
1618
- }
1619
- isFetching(filters) {
1620
- return this.#queryCache.findAll({
1621
- ...filters,
1622
- fetchStatus: 'fetching'
1623
- }).length;
1624
- }
1625
- isMutating(filters) {
1626
- return this.#mutationCache.findAll({
1627
- ...filters,
1628
- status: 'pending'
1629
- }).length;
1630
- }
1631
- getQueryData(queryKey) {
1632
- return this.#queryCache.find({
1633
- queryKey
1634
- })?.state.data;
1635
- }
1636
- ensureQueryData(options) {
1637
- const cachedData = this.getQueryData(options.queryKey);
1638
- return cachedData ? Promise.resolve(cachedData) : this.fetchQuery(options);
1639
- }
1640
- getQueriesData(filters) {
1641
- return this.getQueryCache().findAll(filters).map(({
1642
- queryKey,
1643
- state
1644
- }) => {
1645
- const data = state.data;
1646
- return [queryKey, data];
1647
- });
1648
- }
1649
- setQueryData(queryKey, updater, options) {
1650
- const query = this.#queryCache.find({
1651
- queryKey
1652
- });
1653
- const prevData = query?.state.data;
1654
- const data = functionalUpdate(updater, prevData);
1655
- if (typeof data === 'undefined') {
1656
- return undefined;
1657
- }
1658
- const defaultedOptions = this.defaultQueryOptions({
1659
- queryKey
1660
- });
1661
- return this.#queryCache.build(this, defaultedOptions).setData(data, {
1662
- ...options,
1663
- manual: true
1664
- });
1665
- }
1666
- setQueriesData(filters, updater, options) {
1667
- return notifyManager.batch(() => this.getQueryCache().findAll(filters).map(({
1668
- queryKey
1669
- }) => [queryKey, this.setQueryData(queryKey, updater, options)]));
1670
- }
1671
- getQueryState(queryKey) {
1672
- return this.#queryCache.find({
1673
- queryKey
1674
- })?.state;
1675
- }
1676
- removeQueries(filters) {
1677
- const queryCache = this.#queryCache;
1678
- notifyManager.batch(() => {
1679
- queryCache.findAll(filters).forEach(query => {
1680
- queryCache.remove(query);
1681
- });
1682
- });
1683
- }
1684
- resetQueries(filters, options) {
1685
- const queryCache = this.#queryCache;
1686
- const refetchFilters = {
1687
- type: 'active',
1688
- ...filters
1689
- };
1690
- return notifyManager.batch(() => {
1691
- queryCache.findAll(filters).forEach(query => {
1692
- query.reset();
1693
- });
1694
- return this.refetchQueries(refetchFilters, options);
1695
- });
1696
- }
1697
- cancelQueries(filters = {}, cancelOptions = {}) {
1698
- if (typeof cancelOptions.revert === 'undefined') {
1699
- cancelOptions.revert = true;
1700
- }
1701
- const promises = notifyManager.batch(() => this.#queryCache.findAll(filters).map(query => query.cancel(cancelOptions)));
1702
- return Promise.all(promises).then(noop).catch(noop);
1703
- }
1704
- invalidateQueries(filters = {}, options = {}) {
1705
- return notifyManager.batch(() => {
1706
- this.#queryCache.findAll(filters).forEach(query => {
1707
- query.invalidate();
1708
- });
1709
- if (filters.refetchType === 'none') {
1710
- return Promise.resolve();
1711
- }
1712
- const refetchFilters = {
1713
- ...filters,
1714
- type: filters.refetchType ?? filters.type ?? 'active'
1715
- };
1716
- return this.refetchQueries(refetchFilters, options);
1717
- });
1718
- }
1719
- refetchQueries(filters = {}, options) {
1720
- const promises = notifyManager.batch(() => this.#queryCache.findAll(filters).filter(query => !query.isDisabled()).map(query => query.fetch(undefined, {
1721
- ...options,
1722
- cancelRefetch: options?.cancelRefetch ?? true
1723
- })));
1724
- let promise = Promise.all(promises).then(noop);
1725
- if (!options?.throwOnError) {
1726
- promise = promise.catch(noop);
1727
- }
1728
- return promise;
1729
- }
1730
- fetchQuery(options) {
1731
- const defaultedOptions = this.defaultQueryOptions(options);
1732
-
1733
- // https://github.com/tannerlinsley/react-query/issues/652
1734
- if (typeof defaultedOptions.retry === 'undefined') {
1735
- defaultedOptions.retry = false;
1736
- }
1737
- const query = this.#queryCache.build(this, defaultedOptions);
1738
- return query.isStaleByTime(defaultedOptions.staleTime) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);
1739
- }
1740
- prefetchQuery(options) {
1741
- return this.fetchQuery(options).then(noop).catch(noop);
1742
- }
1743
- fetchInfiniteQuery(options) {
1744
- options.behavior = infiniteQueryBehavior();
1745
- return this.fetchQuery(options);
1746
- }
1747
- prefetchInfiniteQuery(options) {
1748
- return this.fetchInfiniteQuery(options).then(noop).catch(noop);
1749
- }
1750
- resumePausedMutations() {
1751
- return this.#mutationCache.resumePausedMutations();
1752
- }
1753
- getQueryCache() {
1754
- return this.#queryCache;
1755
- }
1756
- getMutationCache() {
1757
- return this.#mutationCache;
1758
- }
1759
- getDefaultOptions() {
1760
- return this.#defaultOptions;
1761
- }
1762
- setDefaultOptions(options) {
1763
- this.#defaultOptions = options;
1764
- }
1765
- setQueryDefaults(queryKey, options) {
1766
- this.#queryDefaults.set(hashKey(queryKey), {
1767
- queryKey,
1768
- defaultOptions: options
1769
- });
1770
- }
1771
- getQueryDefaults(queryKey) {
1772
- const defaults = [...this.#queryDefaults.values()];
1773
- let result = {};
1774
- defaults.forEach(queryDefault => {
1775
- if (partialMatchKey(queryKey, queryDefault.queryKey)) {
1776
- result = {
1777
- ...result,
1778
- ...queryDefault.defaultOptions
1779
- };
1780
- }
1781
- });
1782
- return result;
1783
- }
1784
- setMutationDefaults(mutationKey, options) {
1785
- this.#mutationDefaults.set(hashKey(mutationKey), {
1786
- mutationKey,
1787
- defaultOptions: options
1788
- });
1789
- }
1790
- getMutationDefaults(mutationKey) {
1791
- const defaults = [...this.#mutationDefaults.values()];
1792
- let result = {};
1793
- defaults.forEach(queryDefault => {
1794
- if (partialMatchKey(mutationKey, queryDefault.mutationKey)) {
1795
- result = {
1796
- ...result,
1797
- ...queryDefault.defaultOptions
1798
- };
1799
- }
1800
- });
1801
- return result;
1802
- }
1803
- defaultQueryOptions(options) {
1804
- if (options?._defaulted) {
1805
- return options;
1806
- }
1807
- const defaultedOptions = {
1808
- ...this.#defaultOptions.queries,
1809
- ...(options?.queryKey && this.getQueryDefaults(options.queryKey)),
1810
- ...options,
1811
- _defaulted: true
1812
- };
1813
- if (!defaultedOptions.queryHash) {
1814
- defaultedOptions.queryHash = hashQueryKeyByOptions(defaultedOptions.queryKey, defaultedOptions);
1815
- }
1816
-
1817
- // dependent default values
1818
- if (typeof defaultedOptions.refetchOnReconnect === 'undefined') {
1819
- defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== 'always';
1820
- }
1821
- if (typeof defaultedOptions.throwErrors === 'undefined') {
1822
- defaultedOptions.throwErrors = !!defaultedOptions.suspense;
1823
- }
1824
- return defaultedOptions;
1825
- }
1826
- defaultMutationOptions(options) {
1827
- if (options?._defaulted) {
1828
- return options;
1829
- }
1830
- return {
1831
- ...this.#defaultOptions.mutations,
1832
- ...(options?.mutationKey && this.getMutationDefaults(options.mutationKey)),
1833
- ...options,
1834
- _defaulted: true
1835
- };
1836
- }
1837
- clear() {
1838
- this.#queryCache.clear();
1839
- this.#mutationCache.clear();
1840
- }
1841
- }
1842
-
1843
- class QueryObserver extends Subscribable {
1844
- #client;
1845
- #currentQuery = undefined;
1846
- #currentQueryInitialState = undefined;
1847
- #currentResult = undefined;
1848
- #currentResultState;
1849
- #currentResultOptions;
1850
- #previousQueryResult;
1851
- #selectError;
1852
- #selectFn;
1853
- #selectResult;
1854
- #staleTimeoutId;
1855
- #refetchIntervalId;
1856
- #currentRefetchInterval;
1857
- #trackedProps = new Set();
1858
- constructor(client, options) {
1859
- super();
1860
- this.#client = client;
1861
- this.options = options;
1862
- this.#selectError = null;
1863
- this.bindMethods();
1864
- this.setOptions(options);
1865
- }
1866
- bindMethods() {
1867
- this.refetch = this.refetch.bind(this);
1868
- }
1869
- onSubscribe() {
1870
- if (this.listeners.length === 1) {
1871
- this.#currentQuery.addObserver(this);
1872
- if (shouldFetchOnMount(this.#currentQuery, this.options)) {
1873
- this.#executeFetch();
1874
- }
1875
- this.#updateTimers();
1876
- }
1877
- }
1878
- onUnsubscribe() {
1879
- if (!this.listeners.length) {
1880
- this.destroy();
1881
- }
1882
- }
1883
- shouldFetchOnReconnect() {
1884
- return shouldFetchOn(this.#currentQuery, this.options, this.options.refetchOnReconnect);
1885
- }
1886
- shouldFetchOnWindowFocus() {
1887
- return shouldFetchOn(this.#currentQuery, this.options, this.options.refetchOnWindowFocus);
1888
- }
1889
- destroy() {
1890
- this.listeners = [];
1891
- this.#clearStaleTimeout();
1892
- this.#clearRefetchInterval();
1893
- this.#currentQuery.removeObserver(this);
1894
- }
1895
- setOptions(options, notifyOptions) {
1896
- const prevOptions = this.options;
1897
- const prevQuery = this.#currentQuery;
1898
- this.options = this.#client.defaultQueryOptions(options);
1899
- if (!shallowEqualObjects(prevOptions, this.options)) {
1900
- this.#client.getQueryCache().notify({
1901
- type: 'observerOptionsUpdated',
1902
- query: this.#currentQuery,
1903
- observer: this
1904
- });
1905
- }
1906
- if (typeof this.options.enabled !== 'undefined' && typeof this.options.enabled !== 'boolean') {
1907
- throw new Error('Expected enabled to be a boolean');
1908
- }
1909
-
1910
- // Keep previous query key if the user does not supply one
1911
- if (!this.options.queryKey) {
1912
- this.options.queryKey = prevOptions.queryKey;
1913
- }
1914
- this.#updateQuery();
1915
- const mounted = this.hasListeners();
1916
-
1917
- // Fetch if there are subscribers
1918
- if (mounted && shouldFetchOptionally(this.#currentQuery, prevQuery, this.options, prevOptions)) {
1919
- this.#executeFetch();
1920
- }
1921
-
1922
- // Update result
1923
- this.#updateResult(notifyOptions);
1924
-
1925
- // Update stale interval if needed
1926
- if (mounted && (this.#currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || this.options.staleTime !== prevOptions.staleTime)) {
1927
- this.#updateStaleTimeout();
1928
- }
1929
- const nextRefetchInterval = this.#computeRefetchInterval();
1930
-
1931
- // Update refetch interval if needed
1932
- if (mounted && (this.#currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || nextRefetchInterval !== this.#currentRefetchInterval)) {
1933
- this.#updateRefetchInterval(nextRefetchInterval);
1934
- }
1935
- }
1936
- getOptimisticResult(options) {
1937
- const query = this.#client.getQueryCache().build(this.#client, options);
1938
- return this.createResult(query, options);
1939
- }
1940
- getCurrentResult() {
1941
- return this.#currentResult;
1942
- }
1943
- trackResult(result) {
1944
- const trackedResult = {};
1945
- Object.keys(result).forEach(key => {
1946
- Object.defineProperty(trackedResult, key, {
1947
- configurable: false,
1948
- enumerable: true,
1949
- get: () => {
1950
- this.#trackedProps.add(key);
1951
- return result[key];
1952
- }
1953
- });
1954
- });
1955
- return trackedResult;
1956
- }
1957
- getCurrentQuery() {
1958
- return this.#currentQuery;
1959
- }
1960
- refetch({
1961
- ...options
1962
- } = {}) {
1963
- return this.fetch({
1964
- ...options
1965
- });
1966
- }
1967
- fetchOptimistic(options) {
1968
- const defaultedOptions = this.#client.defaultQueryOptions(options);
1969
- const query = this.#client.getQueryCache().build(this.#client, defaultedOptions);
1970
- query.isFetchingOptimistic = true;
1971
- return query.fetch().then(() => this.createResult(query, defaultedOptions));
1972
- }
1973
- fetch(fetchOptions) {
1974
- return this.#executeFetch({
1975
- ...fetchOptions,
1976
- cancelRefetch: fetchOptions.cancelRefetch ?? true
1977
- }).then(() => {
1978
- this.#updateResult();
1979
- return this.#currentResult;
1980
- });
1981
- }
1982
- #executeFetch(fetchOptions) {
1983
- // Make sure we reference the latest query as the current one might have been removed
1984
- this.#updateQuery();
1985
-
1986
- // Fetch
1987
- let promise = this.#currentQuery.fetch(this.options, fetchOptions);
1988
- if (!fetchOptions?.throwOnError) {
1989
- promise = promise.catch(noop);
1990
- }
1991
- return promise;
1992
- }
1993
- #updateStaleTimeout() {
1994
- this.#clearStaleTimeout();
1995
- if (isServer || this.#currentResult.isStale || !isValidTimeout(this.options.staleTime)) {
1996
- return;
1997
- }
1998
- const time = timeUntilStale(this.#currentResult.dataUpdatedAt, this.options.staleTime);
1999
-
2000
- // The timeout is sometimes triggered 1 ms before the stale time expiration.
2001
- // To mitigate this issue we always add 1 ms to the timeout.
2002
- const timeout = time + 1;
2003
- this.#staleTimeoutId = setTimeout(() => {
2004
- if (!this.#currentResult.isStale) {
2005
- this.#updateResult();
2006
- }
2007
- }, timeout);
2008
- }
2009
- #computeRefetchInterval() {
2010
- return typeof this.options.refetchInterval === 'function' ? this.options.refetchInterval(this.#currentResult.data, this.#currentQuery) : this.options.refetchInterval ?? false;
2011
- }
2012
- #updateRefetchInterval(nextInterval) {
2013
- this.#clearRefetchInterval();
2014
- this.#currentRefetchInterval = nextInterval;
2015
- if (isServer || this.options.enabled === false || !isValidTimeout(this.#currentRefetchInterval) || this.#currentRefetchInterval === 0) {
2016
- return;
2017
- }
2018
- this.#refetchIntervalId = setInterval(() => {
2019
- if (this.options.refetchIntervalInBackground || focusManager.isFocused()) {
2020
- this.#executeFetch();
2021
- }
2022
- }, this.#currentRefetchInterval);
2023
- }
2024
- #updateTimers() {
2025
- this.#updateStaleTimeout();
2026
- this.#updateRefetchInterval(this.#computeRefetchInterval());
2027
- }
2028
- #clearStaleTimeout() {
2029
- if (this.#staleTimeoutId) {
2030
- clearTimeout(this.#staleTimeoutId);
2031
- this.#staleTimeoutId = undefined;
2032
- }
2033
- }
2034
- #clearRefetchInterval() {
2035
- if (this.#refetchIntervalId) {
2036
- clearInterval(this.#refetchIntervalId);
2037
- this.#refetchIntervalId = undefined;
2038
- }
2039
- }
2040
- createResult(query, options) {
2041
- const prevQuery = this.#currentQuery;
2042
- const prevOptions = this.options;
2043
- const prevResult = this.#currentResult;
2044
- const prevResultState = this.#currentResultState;
2045
- const prevResultOptions = this.#currentResultOptions;
2046
- const queryChange = query !== prevQuery;
2047
- const queryInitialState = queryChange ? query.state : this.#currentQueryInitialState;
2048
- const prevQueryResult = queryChange ? this.#currentResult : this.#previousQueryResult;
2049
- const {
2050
- state
2051
- } = query;
2052
- let {
2053
- error,
2054
- errorUpdatedAt,
2055
- fetchStatus,
2056
- status
2057
- } = state;
2058
- let isPlaceholderData = false;
2059
- let data;
2060
-
2061
- // Optimistically set result in fetching state if needed
2062
- if (options._optimisticResults) {
2063
- const mounted = this.hasListeners();
2064
- const fetchOnMount = !mounted && shouldFetchOnMount(query, options);
2065
- const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
2066
- if (fetchOnMount || fetchOptionally) {
2067
- fetchStatus = canFetch(query.options.networkMode) ? 'fetching' : 'paused';
2068
- if (!state.dataUpdatedAt) {
2069
- status = 'pending';
2070
- }
2071
- }
2072
- if (options._optimisticResults === 'isRestoring') {
2073
- fetchStatus = 'idle';
2074
- }
2075
- }
2076
-
2077
- // Select data if needed
2078
- if (options.select && typeof state.data !== 'undefined') {
2079
- // Memoize select result
2080
- if (prevResult && state.data === prevResultState?.data && options.select === this.#selectFn) {
2081
- data = this.#selectResult;
2082
- } else {
2083
- try {
2084
- this.#selectFn = options.select;
2085
- data = options.select(state.data);
2086
- data = replaceData(prevResult?.data, data, options);
2087
- this.#selectResult = data;
2088
- this.#selectError = null;
2089
- } catch (selectError) {
2090
- this.#selectError = selectError;
2091
- }
2092
- }
2093
- }
2094
- // Use query data
2095
- else {
2096
- data = state.data;
2097
- }
2098
-
2099
- // Show placeholder data if needed
2100
- if (typeof options.placeholderData !== 'undefined' && typeof data === 'undefined' && status === 'pending') {
2101
- let placeholderData;
2102
-
2103
- // Memoize placeholder data
2104
- if (prevResult?.isPlaceholderData && options.placeholderData === prevResultOptions?.placeholderData) {
2105
- placeholderData = prevResult.data;
2106
- } else {
2107
- placeholderData = typeof options.placeholderData === 'function' ? options.placeholderData(prevQueryResult?.data) : options.placeholderData;
2108
- if (options.select && typeof placeholderData !== 'undefined') {
2109
- try {
2110
- placeholderData = options.select(placeholderData);
2111
- this.#selectError = null;
2112
- } catch (selectError) {
2113
- this.#selectError = selectError;
2114
- }
2115
- }
2116
- }
2117
- if (typeof placeholderData !== 'undefined') {
2118
- status = 'success';
2119
- data = replaceData(prevResult?.data, placeholderData, options);
2120
- isPlaceholderData = true;
2121
- }
2122
- }
2123
- if (this.#selectError) {
2124
- error = this.#selectError;
2125
- data = this.#selectResult;
2126
- errorUpdatedAt = Date.now();
2127
- status = 'error';
2128
- }
2129
- const isFetching = fetchStatus === 'fetching';
2130
- const isPending = status === 'pending';
2131
- const isError = status === 'error';
2132
- const isLoading = isPending && isFetching;
2133
- const result = {
2134
- status,
2135
- fetchStatus,
2136
- isPending,
2137
- isSuccess: status === 'success',
2138
- isError,
2139
- isInitialLoading: isLoading,
2140
- isLoading,
2141
- data,
2142
- dataUpdatedAt: state.dataUpdatedAt,
2143
- error,
2144
- errorUpdatedAt,
2145
- failureCount: state.fetchFailureCount,
2146
- failureReason: state.fetchFailureReason,
2147
- errorUpdateCount: state.errorUpdateCount,
2148
- isFetched: state.dataUpdateCount > 0 || state.errorUpdateCount > 0,
2149
- isFetchedAfterMount: state.dataUpdateCount > queryInitialState.dataUpdateCount || state.errorUpdateCount > queryInitialState.errorUpdateCount,
2150
- isFetching,
2151
- isRefetching: isFetching && !isPending,
2152
- isLoadingError: isError && state.dataUpdatedAt === 0,
2153
- isPaused: fetchStatus === 'paused',
2154
- isPlaceholderData,
2155
- isRefetchError: isError && state.dataUpdatedAt !== 0,
2156
- isStale: isStale(query, options),
2157
- refetch: this.refetch
2158
- };
2159
- return result;
2160
- }
2161
- #updateResult(notifyOptions) {
2162
- const prevResult = this.#currentResult;
2163
- const nextResult = this.createResult(this.#currentQuery, this.options);
2164
- this.#currentResultState = this.#currentQuery.state;
2165
- this.#currentResultOptions = this.options;
2166
-
2167
- // Only notify and update result if something has changed
2168
- if (shallowEqualObjects(nextResult, prevResult)) {
2169
- return;
2170
- }
2171
- this.#currentResult = nextResult;
2172
-
2173
- // Determine which callbacks to trigger
2174
- const defaultNotifyOptions = {};
2175
- const shouldNotifyListeners = () => {
2176
- if (!prevResult) {
2177
- return true;
2178
- }
2179
- const {
2180
- notifyOnChangeProps
2181
- } = this.options;
2182
- if (notifyOnChangeProps === 'all' || !notifyOnChangeProps && !this.#trackedProps.size) {
2183
- return true;
2184
- }
2185
- const includedProps = new Set(notifyOnChangeProps ?? this.#trackedProps);
2186
- if (this.options.throwErrors) {
2187
- includedProps.add('error');
2188
- }
2189
- return Object.keys(this.#currentResult).some(key => {
2190
- const typedKey = key;
2191
- const changed = this.#currentResult[typedKey] !== prevResult[typedKey];
2192
- return changed && includedProps.has(typedKey);
2193
- });
2194
- };
2195
- if (notifyOptions?.listeners !== false && shouldNotifyListeners()) {
2196
- defaultNotifyOptions.listeners = true;
2197
- }
2198
- this.#notify({
2199
- ...defaultNotifyOptions,
2200
- ...notifyOptions
2201
- });
2202
- }
2203
- #updateQuery() {
2204
- const query = this.#client.getQueryCache().build(this.#client, this.options);
2205
- if (query === this.#currentQuery) {
2206
- return;
2207
- }
2208
- const prevQuery = this.#currentQuery;
2209
- this.#currentQuery = query;
2210
- this.#currentQueryInitialState = query.state;
2211
- this.#previousQueryResult = this.#currentResult;
2212
- if (this.hasListeners()) {
2213
- prevQuery?.removeObserver(this);
2214
- query.addObserver(this);
2215
- }
2216
- }
2217
- onQueryUpdate(action) {
2218
- const notifyOptions = {};
2219
- if (action.type === 'success') {
2220
- notifyOptions.onSuccess = !action.manual;
2221
- } else if (action.type === 'error' && !isCancelledError(action.error)) {
2222
- notifyOptions.onError = true;
2223
- }
2224
- this.#updateResult(notifyOptions);
2225
- if (this.hasListeners()) {
2226
- this.#updateTimers();
2227
- }
2228
- }
2229
- #notify(notifyOptions) {
2230
- notifyManager.batch(() => {
2231
- // First trigger the configuration callbacks
2232
- if (notifyOptions.onSuccess) {
2233
- this.options.onSuccess?.(this.#currentResult.data);
2234
- this.options.onSettled?.(this.#currentResult.data, null);
2235
- } else if (notifyOptions.onError) {
2236
- this.options.onError?.(this.#currentResult.error);
2237
- this.options.onSettled?.(undefined, this.#currentResult.error);
2238
- }
2239
-
2240
- // Then trigger the listeners
2241
- if (notifyOptions.listeners) {
2242
- this.listeners.forEach(listener => {
2243
- listener(this.#currentResult);
2244
- });
2245
- }
2246
-
2247
- // Then the cache listeners
2248
- this.#client.getQueryCache().notify({
2249
- query: this.#currentQuery,
2250
- type: 'observerResultsUpdated'
2251
- });
2252
- });
2253
- }
2254
- }
2255
- function shouldLoadOnMount(query, options) {
2256
- return options.enabled !== false && !query.state.dataUpdatedAt && !(query.state.status === 'error' && options.retryOnMount === false);
2257
- }
2258
- function shouldFetchOnMount(query, options) {
2259
- return shouldLoadOnMount(query, options) || query.state.dataUpdatedAt > 0 && shouldFetchOn(query, options, options.refetchOnMount);
2260
- }
2261
- function shouldFetchOn(query, options, field) {
2262
- if (options.enabled !== false) {
2263
- const value = typeof field === 'function' ? field(query) : field;
2264
- return value === 'always' || value !== false && isStale(query, options);
2265
- }
2266
- return false;
2267
- }
2268
- function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
2269
- return options.enabled !== false && (query !== prevQuery || prevOptions.enabled === false) && (!options.suspense || query.state.status !== 'error') && isStale(query, options);
2270
- }
2271
- function isStale(query, options) {
2272
- return query.isStaleByTime(options.staleTime);
2273
- }
2274
-
2275
- function difference(array1, array2) {
2276
- return array1.filter(x => array2.indexOf(x) === -1);
2277
- }
2278
- function replaceAt(array, index, value) {
2279
- const copy = array.slice(0);
2280
- copy[index] = value;
2281
- return copy;
2282
- }
2283
- class QueriesObserver extends Subscribable {
2284
- #client;
2285
- #result;
2286
- #queries;
2287
- #observers;
2288
- constructor(client, queries) {
2289
- super();
2290
- this.#client = client;
2291
- this.#queries = [];
2292
- this.#result = [];
2293
- this.#observers = [];
2294
- if (queries) {
2295
- this.setQueries(queries);
2296
- }
2297
- }
2298
- onSubscribe() {
2299
- if (this.listeners.length === 1) {
2300
- this.#observers.forEach(observer => {
2301
- observer.subscribe(result => {
2302
- this.#onUpdate(observer, result);
2303
- });
2304
- });
2305
- }
2306
- }
2307
- onUnsubscribe() {
2308
- if (!this.listeners.length) {
2309
- this.destroy();
2310
- }
2311
- }
2312
- destroy() {
2313
- this.listeners = [];
2314
- this.#observers.forEach(observer => {
2315
- observer.destroy();
2316
- });
2317
- }
2318
- setQueries(queries, notifyOptions) {
2319
- this.#queries = queries;
2320
- notifyManager.batch(() => {
2321
- const prevObservers = this.#observers;
2322
- const newObserverMatches = this.#findMatchingObservers(this.#queries);
2323
-
2324
- // set options for the new observers to notify of changes
2325
- newObserverMatches.forEach(match => match.observer.setOptions(match.defaultedQueryOptions, notifyOptions));
2326
- const newObservers = newObserverMatches.map(match => match.observer);
2327
- const newResult = newObservers.map(observer => observer.getCurrentResult());
2328
- const hasIndexChange = newObservers.some((observer, index) => observer !== prevObservers[index]);
2329
- if (prevObservers.length === newObservers.length && !hasIndexChange) {
2330
- return;
2331
- }
2332
- this.#observers = newObservers;
2333
- this.#result = newResult;
2334
- if (!this.hasListeners()) {
2335
- return;
2336
- }
2337
- difference(prevObservers, newObservers).forEach(observer => {
2338
- observer.destroy();
2339
- });
2340
- difference(newObservers, prevObservers).forEach(observer => {
2341
- observer.subscribe(result => {
2342
- this.#onUpdate(observer, result);
2343
- });
2344
- });
2345
- this.#notify();
2346
- });
2347
- }
2348
- getCurrentResult() {
2349
- return this.#result;
2350
- }
2351
- getQueries() {
2352
- return this.#observers.map(observer => observer.getCurrentQuery());
2353
- }
2354
- getObservers() {
2355
- return this.#observers;
2356
- }
2357
- getOptimisticResult(queries) {
2358
- return this.#findMatchingObservers(queries).map(match => match.observer.getOptimisticResult(match.defaultedQueryOptions));
2359
- }
2360
- #findMatchingObservers(queries) {
2361
- const prevObservers = this.#observers;
2362
- const defaultedQueryOptions = queries.map(options => this.#client.defaultQueryOptions(options));
2363
- const matchingObservers = defaultedQueryOptions.flatMap(defaultedOptions => {
2364
- const match = prevObservers.find(observer => observer.options.queryHash === defaultedOptions.queryHash);
2365
- if (match != null) {
2366
- return [{
2367
- defaultedQueryOptions: defaultedOptions,
2368
- observer: match
2369
- }];
2370
- }
2371
- return [];
2372
- });
2373
- const matchedQueryHashes = matchingObservers.map(match => match.defaultedQueryOptions.queryHash);
2374
- const unmatchedQueries = defaultedQueryOptions.filter(defaultedOptions => !matchedQueryHashes.includes(defaultedOptions.queryHash));
2375
- const getObserver = options => {
2376
- const defaultedOptions = this.#client.defaultQueryOptions(options);
2377
- const currentObserver = this.#observers.find(o => o.options.queryHash === defaultedOptions.queryHash);
2378
- return currentObserver ?? new QueryObserver(this.#client, defaultedOptions);
2379
- };
2380
- const newOrReusedObservers = unmatchedQueries.map(options => {
2381
- return {
2382
- defaultedQueryOptions: options,
2383
- observer: getObserver(options)
2384
- };
2385
- });
2386
- const sortMatchesByOrderOfQueries = (a, b) => defaultedQueryOptions.indexOf(a.defaultedQueryOptions) - defaultedQueryOptions.indexOf(b.defaultedQueryOptions);
2387
- return matchingObservers.concat(newOrReusedObservers).sort(sortMatchesByOrderOfQueries);
2388
- }
2389
- #onUpdate(observer, result) {
2390
- const index = this.#observers.indexOf(observer);
2391
- if (index !== -1) {
2392
- this.#result = replaceAt(this.#result, index, result);
2393
- this.#notify();
2394
- }
2395
- }
2396
- #notify() {
2397
- notifyManager.batch(() => {
2398
- this.listeners.forEach(listener => {
2399
- listener(this.#result);
2400
- });
2401
- });
2402
- }
2403
- }
2404
-
2405
- class InfiniteQueryObserver extends QueryObserver {
2406
- // Type override
2407
-
2408
- // Type override
2409
-
2410
- // Type override
2411
-
2412
- // eslint-disable-next-line @typescript-eslint/no-useless-constructor
2413
- constructor(client, options) {
2414
- super(client, options);
2415
- }
2416
- bindMethods() {
2417
- super.bindMethods();
2418
- this.fetchNextPage = this.fetchNextPage.bind(this);
2419
- this.fetchPreviousPage = this.fetchPreviousPage.bind(this);
2420
- }
2421
- setOptions(options, notifyOptions) {
2422
- super.setOptions({
2423
- ...options,
2424
- behavior: infiniteQueryBehavior()
2425
- }, notifyOptions);
2426
- }
2427
- getOptimisticResult(options) {
2428
- options.behavior = infiniteQueryBehavior();
2429
- return super.getOptimisticResult(options);
2430
- }
2431
- fetchNextPage(options) {
2432
- return this.fetch({
2433
- ...options,
2434
- meta: {
2435
- fetchMore: {
2436
- direction: 'forward'
2437
- }
2438
- }
2439
- });
2440
- }
2441
- fetchPreviousPage(options) {
2442
- return this.fetch({
2443
- ...options,
2444
- meta: {
2445
- fetchMore: {
2446
- direction: 'backward'
2447
- }
2448
- }
2449
- });
2450
- }
2451
- createResult(query, options) {
2452
- const {
2453
- state
2454
- } = query;
2455
- const result = super.createResult(query, options);
2456
- const {
2457
- isFetching,
2458
- isRefetching
2459
- } = result;
2460
- const isFetchingNextPage = isFetching && state.fetchMeta?.fetchMore?.direction === 'forward';
2461
- const isFetchingPreviousPage = isFetching && state.fetchMeta?.fetchMore?.direction === 'backward';
2462
- return {
2463
- ...result,
2464
- fetchNextPage: this.fetchNextPage,
2465
- fetchPreviousPage: this.fetchPreviousPage,
2466
- hasNextPage: hasNextPage(options, state.data),
2467
- hasPreviousPage: hasPreviousPage(options, state.data),
2468
- isFetchingNextPage,
2469
- isFetchingPreviousPage,
2470
- isRefetching: isRefetching && !isFetchingNextPage && !isFetchingPreviousPage
2471
- };
2472
- }
2473
- }
2474
-
2475
- // TYPES
2476
-
2477
- // CLASS
2478
-
2479
- class MutationObserver extends Subscribable {
2480
- #client;
2481
- #currentResult = undefined;
2482
- #currentMutation;
2483
- #mutateOptions;
2484
- constructor(client, options) {
2485
- super();
2486
- this.#client = client;
2487
- this.setOptions(options);
2488
- this.bindMethods();
2489
- this.#updateResult();
2490
- }
2491
- bindMethods() {
2492
- this.mutate = this.mutate.bind(this);
2493
- this.reset = this.reset.bind(this);
2494
- }
2495
- setOptions(options) {
2496
- const prevOptions = this.options;
2497
- this.options = this.#client.defaultMutationOptions(options);
2498
- if (!shallowEqualObjects(prevOptions, this.options)) {
2499
- this.#client.getMutationCache().notify({
2500
- type: 'observerOptionsUpdated',
2501
- mutation: this.#currentMutation,
2502
- observer: this
2503
- });
2504
- }
2505
- this.#currentMutation?.setOptions(this.options);
2506
- }
2507
- onUnsubscribe() {
2508
- if (!this.listeners.length) {
2509
- this.#currentMutation?.removeObserver(this);
2510
- }
2511
- }
2512
- onMutationUpdate(action) {
2513
- this.#updateResult();
2514
- this.#notify(action);
2515
- }
2516
- getCurrentResult() {
2517
- return this.#currentResult;
2518
- }
2519
- reset() {
2520
- this.#currentMutation = undefined;
2521
- this.#updateResult();
2522
- this.#notify();
2523
- }
2524
- mutate(variables, options) {
2525
- this.#mutateOptions = options;
2526
- this.#currentMutation?.removeObserver(this);
2527
- this.#currentMutation = this.#client.getMutationCache().build(this.#client, this.options);
2528
- this.#currentMutation.addObserver(this);
2529
- return this.#currentMutation.execute(variables);
2530
- }
2531
- #updateResult() {
2532
- const state = this.#currentMutation?.state ?? getDefaultState();
2533
- this.#currentResult = {
2534
- ...state,
2535
- isPending: state.status === 'pending',
2536
- isSuccess: state.status === 'success',
2537
- isError: state.status === 'error',
2538
- isIdle: state.status === 'idle',
2539
- mutate: this.mutate,
2540
- reset: this.reset
2541
- };
2542
- }
2543
- #notify(action) {
2544
- notifyManager.batch(() => {
2545
- // First trigger the mutate callbacks
2546
- if (this.#mutateOptions && this.hasListeners()) {
2547
- if (action?.type === 'success') {
2548
- this.#mutateOptions.onSuccess?.(action.data, this.#currentResult.variables, this.#currentResult.context);
2549
- this.#mutateOptions.onSettled?.(action.data, null, this.#currentResult.variables, this.#currentResult.context);
2550
- } else if (action?.type === 'error') {
2551
- this.#mutateOptions.onError?.(action.error, this.#currentResult.variables, this.#currentResult.context);
2552
- this.#mutateOptions.onSettled?.(undefined, action.error, this.#currentResult.variables, this.#currentResult.context);
2553
- }
2554
- }
2555
-
2556
- // Then trigger the listeners
2557
- this.listeners.forEach(listener => {
2558
- listener(this.#currentResult);
2559
- });
2560
- });
2561
- }
2562
- }
2563
-
2564
- // TYPES
2565
-
2566
- // FUNCTIONS
2567
-
2568
- function dehydrateMutation(mutation) {
2569
- return {
2570
- mutationKey: mutation.options.mutationKey,
2571
- state: mutation.state
2572
- };
2573
- }
2574
-
2575
- // Most config is not dehydrated but instead meant to configure again when
2576
- // consuming the de/rehydrated data, typically with useQuery on the client.
2577
- // Sometimes it might make sense to prefetch data on the server and include
2578
- // in the html-payload, but not consume it on the initial render.
2579
- function dehydrateQuery(query) {
2580
- return {
2581
- state: query.state,
2582
- queryKey: query.queryKey,
2583
- queryHash: query.queryHash
2584
- };
2585
- }
2586
- function defaultShouldDehydrateMutation(mutation) {
2587
- return mutation.state.isPaused;
2588
- }
2589
- function defaultShouldDehydrateQuery(query) {
2590
- return query.state.status === 'success';
2591
- }
2592
- function dehydrate(client, options = {}) {
2593
- const mutations = [];
2594
- const queries = [];
2595
- if (options.dehydrateMutations !== false) {
2596
- const shouldDehydrateMutation = options.shouldDehydrateMutation || defaultShouldDehydrateMutation;
2597
- client.getMutationCache().getAll().forEach(mutation => {
2598
- if (shouldDehydrateMutation(mutation)) {
2599
- mutations.push(dehydrateMutation(mutation));
2600
- }
2601
- });
2602
- }
2603
- if (options.dehydrateQueries !== false) {
2604
- const shouldDehydrateQuery = options.shouldDehydrateQuery || defaultShouldDehydrateQuery;
2605
- client.getQueryCache().getAll().forEach(query => {
2606
- if (shouldDehydrateQuery(query)) {
2607
- queries.push(dehydrateQuery(query));
2608
- }
2609
- });
2610
- }
2611
- return {
2612
- mutations,
2613
- queries
2614
- };
2615
- }
2616
- function hydrate(client, dehydratedState, options) {
2617
- if (typeof dehydratedState !== 'object' || dehydratedState === null) {
2618
- return;
2619
- }
2620
- const mutationCache = client.getMutationCache();
2621
- const queryCache = client.getQueryCache();
2622
-
2623
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2624
- const mutations = dehydratedState.mutations || [];
2625
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2626
- const queries = dehydratedState.queries || [];
2627
- mutations.forEach(dehydratedMutation => {
2628
- mutationCache.build(client, {
2629
- ...options?.defaultOptions?.mutations,
2630
- mutationKey: dehydratedMutation.mutationKey
2631
- }, dehydratedMutation.state);
2632
- });
2633
- queries.forEach(dehydratedQuery => {
2634
- const query = queryCache.get(dehydratedQuery.queryHash);
2635
-
2636
- // Reset fetch status to idle in the dehydrated state to avoid
2637
- // query being stuck in fetching state upon hydration
2638
- const dehydratedQueryState = {
2639
- ...dehydratedQuery.state,
2640
- fetchStatus: 'idle'
2641
- };
2642
-
2643
- // Do not hydrate if an existing query exists with newer data
2644
- if (query) {
2645
- if (query.state.dataUpdatedAt < dehydratedQueryState.dataUpdatedAt) {
2646
- query.setState(dehydratedQueryState);
2647
- }
2648
- return;
2649
- }
2650
-
2651
- // Restore query
2652
- queryCache.build(client, {
2653
- ...options?.defaultOptions?.queries,
2654
- queryKey: dehydratedQuery.queryKey,
2655
- queryHash: dehydratedQuery.queryHash
2656
- }, dehydratedQueryState);
2657
- });
2658
- }
2659
-
2660
- exports.CancelledError = CancelledError;
2661
- exports.InfiniteQueryObserver = InfiniteQueryObserver;
2662
- exports.MutationCache = MutationCache;
2663
- exports.MutationObserver = MutationObserver;
2664
- exports.QueriesObserver = QueriesObserver;
2665
- exports.QueryCache = QueryCache;
2666
- exports.QueryClient = QueryClient;
2667
- exports.QueryObserver = QueryObserver;
2668
- exports.defaultShouldDehydrateMutation = defaultShouldDehydrateMutation;
2669
- exports.defaultShouldDehydrateQuery = defaultShouldDehydrateQuery;
2670
- exports.dehydrate = dehydrate;
2671
- exports.focusManager = focusManager;
2672
- exports.hashKey = hashKey;
2673
- exports.hydrate = hydrate;
2674
- exports.isCancelledError = isCancelledError;
2675
- exports.isServer = isServer;
2676
- exports.keepPreviousData = keepPreviousData;
2677
- exports.matchQuery = matchQuery;
2678
- exports.notifyManager = notifyManager;
2679
- exports.onlineManager = onlineManager;
2680
- exports.replaceEqualDeep = replaceEqualDeep;
2681
-
2682
- }));
2683
- //# sourceMappingURL=index.development.js.map