@tanstack/vue-query 5.0.0-alpha.5 → 5.0.0-alpha.51

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 (225) hide show
  1. package/README.md +18 -14
  2. package/build/lib/__mocks__/useBaseQuery.d.ts +2 -1
  3. package/build/lib/__mocks__/useBaseQuery.d.ts.map +1 -0
  4. package/build/lib/__mocks__/useQueryClient.d.ts +2 -1
  5. package/build/lib/__mocks__/useQueryClient.d.ts.map +1 -0
  6. package/build/lib/__tests__/mutationCache.test.d.ts +1 -0
  7. package/build/lib/__tests__/mutationCache.test.d.ts.map +1 -0
  8. package/build/lib/__tests__/queryCache.test.d.ts +1 -0
  9. package/build/lib/__tests__/queryCache.test.d.ts.map +1 -0
  10. package/build/lib/__tests__/queryClient.test.d.ts +1 -0
  11. package/build/lib/__tests__/queryClient.test.d.ts.map +1 -0
  12. package/build/lib/__tests__/test-utils.d.ts +3 -2
  13. package/build/lib/__tests__/test-utils.d.ts.map +1 -0
  14. package/build/lib/__tests__/useInfiniteQuery.test.d.ts +1 -0
  15. package/build/lib/__tests__/useInfiniteQuery.test.d.ts.map +1 -0
  16. package/build/lib/__tests__/useInfiniteQuery.types.test.d.ts +1 -0
  17. package/build/lib/__tests__/useInfiniteQuery.types.test.d.ts.map +1 -0
  18. package/build/lib/__tests__/useIsFetching.test.d.ts +1 -0
  19. package/build/lib/__tests__/useIsFetching.test.d.ts.map +1 -0
  20. package/build/lib/__tests__/useIsMutating.test.d.ts +1 -0
  21. package/build/lib/__tests__/useIsMutating.test.d.ts.map +1 -0
  22. package/build/lib/__tests__/useMutation.test.d.ts +1 -0
  23. package/build/lib/__tests__/useMutation.test.d.ts.map +1 -0
  24. package/build/lib/__tests__/useMutation.types.test.d.ts +1 -0
  25. package/build/lib/__tests__/useMutation.types.test.d.ts.map +1 -0
  26. package/build/lib/__tests__/useQueries.test.d.ts +1 -0
  27. package/build/lib/__tests__/useQueries.test.d.ts.map +1 -0
  28. package/build/lib/__tests__/useQuery.test.d.ts +1 -0
  29. package/build/lib/__tests__/useQuery.test.d.ts.map +1 -0
  30. package/build/lib/__tests__/useQuery.types.test.d.ts +1 -0
  31. package/build/lib/__tests__/useQuery.types.test.d.ts.map +1 -0
  32. package/build/lib/__tests__/useQueryClient.test.d.ts +1 -0
  33. package/build/lib/__tests__/useQueryClient.test.d.ts.map +1 -0
  34. package/build/lib/__tests__/utils.test.d.ts +1 -0
  35. package/build/lib/__tests__/utils.test.d.ts.map +1 -0
  36. package/build/lib/__tests__/vueQueryPlugin.test.d.ts +1 -0
  37. package/build/lib/__tests__/vueQueryPlugin.test.d.ts.map +1 -0
  38. package/build/lib/devtools/{devtools.esm.js → devtools.cjs} +62 -21
  39. package/build/lib/devtools/devtools.cjs.map +1 -0
  40. package/build/lib/devtools/devtools.d.ts +1 -0
  41. package/build/lib/devtools/devtools.d.ts.map +1 -0
  42. package/build/lib/devtools/devtools.js +59 -22
  43. package/build/lib/devtools/devtools.js.map +1 -1
  44. package/build/lib/devtools/{utils.esm.js → utils.cjs} +11 -6
  45. package/build/lib/devtools/utils.cjs.map +1 -0
  46. package/build/lib/devtools/utils.d.ts +2 -1
  47. package/build/lib/devtools/utils.d.ts.map +1 -0
  48. package/build/lib/devtools/utils.js +4 -11
  49. package/build/lib/devtools/utils.js.map +1 -1
  50. package/build/lib/index.cjs +38 -0
  51. package/build/lib/index.cjs.map +1 -0
  52. package/build/lib/index.d.ts +3 -2
  53. package/build/lib/index.d.ts.map +1 -0
  54. package/build/lib/index.js +13 -36
  55. package/build/lib/index.js.map +1 -1
  56. package/build/lib/mutationCache.cjs +16 -0
  57. package/build/lib/{mutationCache.mjs.map → mutationCache.cjs.map} +1 -1
  58. package/build/lib/mutationCache.d.ts +1 -0
  59. package/build/lib/mutationCache.d.ts.map +1 -0
  60. package/build/lib/mutationCache.js +6 -8
  61. package/build/lib/mutationCache.js.map +1 -1
  62. package/build/lib/queryCache.cjs +16 -0
  63. package/build/lib/{queryCache.mjs.map → queryCache.cjs.map} +1 -1
  64. package/build/lib/queryCache.d.ts +1 -0
  65. package/build/lib/queryCache.d.ts.map +1 -0
  66. package/build/lib/queryCache.js +6 -8
  67. package/build/lib/queryCache.js.map +1 -1
  68. package/build/lib/queryClient.cjs +86 -0
  69. package/build/lib/{queryClient.mjs.map → queryClient.cjs.map} +1 -1
  70. package/build/lib/queryClient.d.ts +1 -0
  71. package/build/lib/queryClient.d.ts.map +1 -0
  72. package/build/lib/queryClient.js +32 -34
  73. package/build/lib/queryClient.js.map +1 -1
  74. package/build/lib/types.d.ts +4 -3
  75. package/build/lib/types.d.ts.map +1 -0
  76. package/build/lib/{useBaseQuery.esm.js → useBaseQuery.cjs} +19 -17
  77. package/build/lib/{useBaseQuery.mjs.map → useBaseQuery.cjs.map} +1 -1
  78. package/build/lib/useBaseQuery.d.ts +3 -2
  79. package/build/lib/useBaseQuery.d.ts.map +1 -0
  80. package/build/lib/useBaseQuery.js +16 -18
  81. package/build/lib/useBaseQuery.js.map +1 -1
  82. package/build/lib/{useInfiniteQuery.esm.js → useInfiniteQuery.cjs} +8 -6
  83. package/build/lib/{useInfiniteQuery.mjs.map → useInfiniteQuery.cjs.map} +1 -1
  84. package/build/lib/useInfiniteQuery.d.ts +4 -3
  85. package/build/lib/useInfiniteQuery.d.ts.map +1 -0
  86. package/build/lib/useInfiniteQuery.js +5 -7
  87. package/build/lib/useInfiniteQuery.js.map +1 -1
  88. package/build/lib/useIsFetching.cjs +26 -0
  89. package/build/lib/{useIsFetching.mjs.map → useIsFetching.cjs.map} +1 -1
  90. package/build/lib/useIsFetching.d.ts +2 -1
  91. package/build/lib/useIsFetching.d.ts.map +1 -0
  92. package/build/lib/useIsFetching.js +9 -11
  93. package/build/lib/useIsFetching.js.map +1 -1
  94. package/build/lib/useMutation.cjs +41 -0
  95. package/build/lib/{useMutation.mjs.map → useMutation.cjs.map} +1 -1
  96. package/build/lib/useMutation.d.ts +5 -4
  97. package/build/lib/useMutation.d.ts.map +1 -0
  98. package/build/lib/useMutation.js +14 -16
  99. package/build/lib/useMutation.js.map +1 -1
  100. package/build/lib/useMutationState.cjs +36 -0
  101. package/build/lib/useMutationState.cjs.map +1 -0
  102. package/build/lib/useMutationState.d.ts +12 -0
  103. package/build/lib/useMutationState.d.ts.map +1 -0
  104. package/build/lib/useMutationState.js +33 -0
  105. package/build/lib/useMutationState.js.map +1 -0
  106. package/build/lib/useQueries.cjs +62 -0
  107. package/build/lib/useQueries.cjs.map +1 -0
  108. package/build/lib/useQueries.d.ts +12 -11
  109. package/build/lib/useQueries.d.ts.map +1 -0
  110. package/build/lib/useQueries.js +35 -23
  111. package/build/lib/useQueries.js.map +1 -1
  112. package/build/lib/useQuery.cjs +15 -0
  113. package/build/lib/{useQuery.mjs.map → useQuery.cjs.map} +1 -1
  114. package/build/lib/useQuery.d.ts +4 -3
  115. package/build/lib/useQuery.d.ts.map +1 -0
  116. package/build/lib/useQuery.js +4 -6
  117. package/build/lib/useQuery.js.map +1 -1
  118. package/build/lib/{useQueryClient.esm.js → useQueryClient.cjs} +9 -7
  119. package/build/lib/{useQueryClient.mjs.map → useQueryClient.cjs.map} +1 -1
  120. package/build/lib/useQueryClient.d.ts +1 -0
  121. package/build/lib/useQueryClient.d.ts.map +1 -0
  122. package/build/lib/useQueryClient.js +6 -8
  123. package/build/lib/useQueryClient.js.map +1 -1
  124. package/build/lib/{utils.mjs → utils.cjs} +12 -6
  125. package/build/lib/{utils.mjs.map → utils.cjs.map} +1 -1
  126. package/build/lib/utils.d.ts +1 -0
  127. package/build/lib/utils.d.ts.map +1 -0
  128. package/build/lib/utils.js +5 -11
  129. package/build/lib/utils.js.map +1 -1
  130. package/build/lib/{vueQueryPlugin.mjs → vueQueryPlugin.cjs} +15 -15
  131. package/build/lib/vueQueryPlugin.cjs.map +1 -0
  132. package/build/lib/vueQueryPlugin.d.ts +3 -2
  133. package/build/lib/vueQueryPlugin.d.ts.map +1 -0
  134. package/build/lib/vueQueryPlugin.js +12 -16
  135. package/build/lib/vueQueryPlugin.js.map +1 -1
  136. package/package.json +20 -16
  137. package/src/__mocks__/useBaseQuery.ts +8 -0
  138. package/src/__mocks__/useQueryClient.ts +10 -0
  139. package/src/__tests__/mutationCache.test.ts +40 -0
  140. package/src/__tests__/queryCache.test.ts +48 -0
  141. package/src/__tests__/queryClient.test.ts +365 -0
  142. package/src/__tests__/test-utils.ts +62 -0
  143. package/src/__tests__/useInfiniteQuery.test.ts +37 -0
  144. package/src/__tests__/useInfiniteQuery.types.test.tsx +102 -0
  145. package/src/__tests__/useIsFetching.test.ts +77 -0
  146. package/src/__tests__/useIsMutating.test.ts +123 -0
  147. package/src/__tests__/useMutation.test.ts +335 -0
  148. package/src/__tests__/useMutation.types.test.tsx +97 -0
  149. package/src/__tests__/useQueries.test.ts +256 -0
  150. package/src/__tests__/useQuery.test.ts +290 -0
  151. package/src/__tests__/useQuery.types.test.tsx +88 -0
  152. package/src/__tests__/useQueryClient.test.ts +51 -0
  153. package/src/__tests__/utils.test.ts +148 -0
  154. package/src/__tests__/vueQueryPlugin.test.ts +351 -0
  155. package/src/devtools/devtools.ts +249 -0
  156. package/src/devtools/utils.ts +96 -0
  157. package/src/index.ts +30 -0
  158. package/src/mutationCache.ts +25 -0
  159. package/src/queryCache.ts +21 -0
  160. package/src/queryClient.ts +278 -0
  161. package/src/types.ts +17 -0
  162. package/src/useBaseQuery.ts +152 -0
  163. package/src/useInfiniteQuery.ts +105 -0
  164. package/src/useIsFetching.ts +37 -0
  165. package/src/useMutation.ts +109 -0
  166. package/src/useMutationState.ts +73 -0
  167. package/src/useQueries.ts +227 -0
  168. package/src/useQuery.ts +125 -0
  169. package/src/useQueryClient.ts +23 -0
  170. package/src/utils.ts +67 -0
  171. package/src/vueQueryPlugin.ts +101 -0
  172. package/build/lib/devtools/devtools.esm.js.map +0 -1
  173. package/build/lib/devtools/devtools.mjs +0 -155
  174. package/build/lib/devtools/devtools.mjs.map +0 -1
  175. package/build/lib/devtools/utils.esm.js.map +0 -1
  176. package/build/lib/devtools/utils.mjs +0 -80
  177. package/build/lib/devtools/utils.mjs.map +0 -1
  178. package/build/lib/index.esm.js +0 -14
  179. package/build/lib/index.esm.js.map +0 -1
  180. package/build/lib/index.mjs +0 -14
  181. package/build/lib/index.mjs.map +0 -1
  182. package/build/lib/mutationCache.esm.js +0 -14
  183. package/build/lib/mutationCache.esm.js.map +0 -1
  184. package/build/lib/mutationCache.mjs +0 -14
  185. package/build/lib/queryCache.esm.js +0 -14
  186. package/build/lib/queryCache.esm.js.map +0 -1
  187. package/build/lib/queryCache.mjs +0 -14
  188. package/build/lib/queryClient.esm.js +0 -84
  189. package/build/lib/queryClient.esm.js.map +0 -1
  190. package/build/lib/queryClient.mjs +0 -84
  191. package/build/lib/useBaseQuery.esm.js.map +0 -1
  192. package/build/lib/useBaseQuery.mjs +0 -67
  193. package/build/lib/useInfiniteQuery.esm.js.map +0 -1
  194. package/build/lib/useInfiniteQuery.mjs +0 -18
  195. package/build/lib/useIsFetching.esm.js +0 -24
  196. package/build/lib/useIsFetching.esm.js.map +0 -1
  197. package/build/lib/useIsFetching.mjs +0 -24
  198. package/build/lib/useIsMutating.d.ts +0 -6
  199. package/build/lib/useIsMutating.esm.js +0 -24
  200. package/build/lib/useIsMutating.esm.js.map +0 -1
  201. package/build/lib/useIsMutating.js +0 -26
  202. package/build/lib/useIsMutating.js.map +0 -1
  203. package/build/lib/useIsMutating.mjs +0 -24
  204. package/build/lib/useIsMutating.mjs.map +0 -1
  205. package/build/lib/useMutation.esm.js +0 -39
  206. package/build/lib/useMutation.esm.js.map +0 -1
  207. package/build/lib/useMutation.mjs +0 -39
  208. package/build/lib/useQueries.esm.js +0 -46
  209. package/build/lib/useQueries.esm.js.map +0 -1
  210. package/build/lib/useQueries.mjs +0 -46
  211. package/build/lib/useQueries.mjs.map +0 -1
  212. package/build/lib/useQuery.esm.js +0 -13
  213. package/build/lib/useQuery.esm.js.map +0 -1
  214. package/build/lib/useQuery.mjs +0 -13
  215. package/build/lib/useQueryClient.esm.js.map +0 -1
  216. package/build/lib/useQueryClient.mjs +0 -18
  217. package/build/lib/utils.esm.js +0 -50
  218. package/build/lib/utils.esm.js.map +0 -1
  219. package/build/lib/vueQueryPlugin.esm.js +0 -75
  220. package/build/lib/vueQueryPlugin.esm.js.map +0 -1
  221. package/build/lib/vueQueryPlugin.mjs.map +0 -1
  222. package/build/umd/index.development.js +0 -4192
  223. package/build/umd/index.development.js.map +0 -1
  224. package/build/umd/index.production.js +0 -2
  225. package/build/umd/index.production.js.map +0 -1
@@ -1,4192 +0,0 @@
1
- (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('vue-demi')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'vue-demi'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.VueQuery = {}, global.Vue));
5
- })(this, (function (exports, vueDemi) { '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$1(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$1(a) && isPlainObject$1(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$1(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
- let QueryCache$1 = 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
- let MutationCache$1 = 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
- meta: context.options.meta
1498
- };
1499
- addSignalProperty(queryFnContext);
1500
- const page = await queryFn(queryFnContext);
1501
- const {
1502
- maxPages
1503
- } = context.options;
1504
- const addTo = previous ? addToStart : addToEnd;
1505
- return {
1506
- pages: addTo(data.pages, page, maxPages),
1507
- pageParams: addTo(data.pageParams, param, maxPages)
1508
- };
1509
- };
1510
- let result;
1511
-
1512
- // Fetch first page?
1513
- if (!oldPages.length) {
1514
- result = await fetchPage(empty, options.defaultPageParam);
1515
- }
1516
-
1517
- // fetch next / previous page?
1518
- else if (direction) {
1519
- const previous = direction === 'backward';
1520
- const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;
1521
- const oldData = {
1522
- pages: oldPages,
1523
- pageParams: oldPageParams
1524
- };
1525
- const param = pageParamFn(options, oldData);
1526
- result = await fetchPage(oldData, param, previous);
1527
- }
1528
-
1529
- // Refetch pages
1530
- else {
1531
- // Fetch first page
1532
- result = await fetchPage(empty, oldPageParams[0]);
1533
-
1534
- // Fetch remaining pages
1535
- for (let i = 1; i < oldPages.length; i++) {
1536
- const param = getNextPageParam(options, result);
1537
- result = await fetchPage(result, param);
1538
- }
1539
- }
1540
- return result;
1541
- };
1542
- }
1543
- };
1544
- }
1545
- function getNextPageParam(options, {
1546
- pages,
1547
- pageParams
1548
- }) {
1549
- const lastIndex = pages.length - 1;
1550
- return options.getNextPageParam(pages[lastIndex], pages, pageParams[lastIndex], pageParams);
1551
- }
1552
- function getPreviousPageParam(options, {
1553
- pages,
1554
- pageParams
1555
- }) {
1556
- return options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams);
1557
- }
1558
-
1559
- /**
1560
- * Checks if there is a next page.
1561
- */
1562
- function hasNextPage(options, data) {
1563
- if (!data) return false;
1564
- return typeof getNextPageParam(options, data) !== 'undefined';
1565
- }
1566
-
1567
- /**
1568
- * Checks if there is a previous page.
1569
- */
1570
- function hasPreviousPage(options, data) {
1571
- if (!data || !options.getPreviousPageParam) return false;
1572
- return typeof getPreviousPageParam(options, data) !== 'undefined';
1573
- }
1574
-
1575
- // CLASS
1576
-
1577
- let QueryClient$1 = class QueryClient {
1578
- #queryCache;
1579
- #mutationCache;
1580
- #defaultOptions;
1581
- #queryDefaults;
1582
- #mutationDefaults;
1583
- #mountCount;
1584
- #unsubscribeFocus;
1585
- #unsubscribeOnline;
1586
- constructor(config = {}) {
1587
- this.#queryCache = config.queryCache || new QueryCache$1();
1588
- this.#mutationCache = config.mutationCache || new MutationCache$1();
1589
- this.#defaultOptions = config.defaultOptions || {};
1590
- this.#queryDefaults = new Map();
1591
- this.#mutationDefaults = new Map();
1592
- this.#mountCount = 0;
1593
- }
1594
- mount() {
1595
- this.#mountCount++;
1596
- if (this.#mountCount !== 1) return;
1597
- this.#unsubscribeFocus = focusManager.subscribe(() => {
1598
- if (focusManager.isFocused()) {
1599
- this.resumePausedMutations();
1600
- this.#queryCache.onFocus();
1601
- }
1602
- });
1603
- this.#unsubscribeOnline = onlineManager.subscribe(() => {
1604
- if (onlineManager.isOnline()) {
1605
- this.resumePausedMutations();
1606
- this.#queryCache.onOnline();
1607
- }
1608
- });
1609
- }
1610
- unmount() {
1611
- this.#mountCount--;
1612
- if (this.#mountCount !== 0) return;
1613
- this.#unsubscribeFocus?.();
1614
- this.#unsubscribeFocus = undefined;
1615
- this.#unsubscribeOnline?.();
1616
- this.#unsubscribeOnline = undefined;
1617
- }
1618
- isFetching(filters) {
1619
- return this.#queryCache.findAll({
1620
- ...filters,
1621
- fetchStatus: 'fetching'
1622
- }).length;
1623
- }
1624
- isMutating(filters) {
1625
- return this.#mutationCache.findAll({
1626
- ...filters,
1627
- status: 'pending'
1628
- }).length;
1629
- }
1630
- getQueryData(queryKey) {
1631
- return this.#queryCache.find({
1632
- queryKey
1633
- })?.state.data;
1634
- }
1635
- ensureQueryData(options) {
1636
- const cachedData = this.getQueryData(options.queryKey);
1637
- return cachedData ? Promise.resolve(cachedData) : this.fetchQuery(options);
1638
- }
1639
- getQueriesData(filters) {
1640
- return this.getQueryCache().findAll(filters).map(({
1641
- queryKey,
1642
- state
1643
- }) => {
1644
- const data = state.data;
1645
- return [queryKey, data];
1646
- });
1647
- }
1648
- setQueryData(queryKey, updater, options) {
1649
- const query = this.#queryCache.find({
1650
- queryKey
1651
- });
1652
- const prevData = query?.state.data;
1653
- const data = functionalUpdate(updater, prevData);
1654
- if (typeof data === 'undefined') {
1655
- return undefined;
1656
- }
1657
- const defaultedOptions = this.defaultQueryOptions({
1658
- queryKey
1659
- });
1660
- return this.#queryCache.build(this, defaultedOptions).setData(data, {
1661
- ...options,
1662
- manual: true
1663
- });
1664
- }
1665
- setQueriesData(filters, updater, options) {
1666
- return notifyManager.batch(() => this.getQueryCache().findAll(filters).map(({
1667
- queryKey
1668
- }) => [queryKey, this.setQueryData(queryKey, updater, options)]));
1669
- }
1670
- getQueryState(queryKey) {
1671
- return this.#queryCache.find({
1672
- queryKey
1673
- })?.state;
1674
- }
1675
- removeQueries(filters) {
1676
- const queryCache = this.#queryCache;
1677
- notifyManager.batch(() => {
1678
- queryCache.findAll(filters).forEach(query => {
1679
- queryCache.remove(query);
1680
- });
1681
- });
1682
- }
1683
- resetQueries(filters, options) {
1684
- const queryCache = this.#queryCache;
1685
- const refetchFilters = {
1686
- type: 'active',
1687
- ...filters
1688
- };
1689
- return notifyManager.batch(() => {
1690
- queryCache.findAll(filters).forEach(query => {
1691
- query.reset();
1692
- });
1693
- return this.refetchQueries(refetchFilters, options);
1694
- });
1695
- }
1696
- cancelQueries(filters = {}, cancelOptions = {}) {
1697
- if (typeof cancelOptions.revert === 'undefined') {
1698
- cancelOptions.revert = true;
1699
- }
1700
- const promises = notifyManager.batch(() => this.#queryCache.findAll(filters).map(query => query.cancel(cancelOptions)));
1701
- return Promise.all(promises).then(noop).catch(noop);
1702
- }
1703
- invalidateQueries(filters = {}, options = {}) {
1704
- return notifyManager.batch(() => {
1705
- this.#queryCache.findAll(filters).forEach(query => {
1706
- query.invalidate();
1707
- });
1708
- if (filters.refetchType === 'none') {
1709
- return Promise.resolve();
1710
- }
1711
- const refetchFilters = {
1712
- ...filters,
1713
- type: filters.refetchType ?? filters.type ?? 'active'
1714
- };
1715
- return this.refetchQueries(refetchFilters, options);
1716
- });
1717
- }
1718
- refetchQueries(filters = {}, options) {
1719
- const promises = notifyManager.batch(() => this.#queryCache.findAll(filters).filter(query => !query.isDisabled()).map(query => query.fetch(undefined, {
1720
- ...options,
1721
- cancelRefetch: options?.cancelRefetch ?? true
1722
- })));
1723
- let promise = Promise.all(promises).then(noop);
1724
- if (!options?.throwOnError) {
1725
- promise = promise.catch(noop);
1726
- }
1727
- return promise;
1728
- }
1729
- fetchQuery(options) {
1730
- const defaultedOptions = this.defaultQueryOptions(options);
1731
-
1732
- // https://github.com/tannerlinsley/react-query/issues/652
1733
- if (typeof defaultedOptions.retry === 'undefined') {
1734
- defaultedOptions.retry = false;
1735
- }
1736
- const query = this.#queryCache.build(this, defaultedOptions);
1737
- return query.isStaleByTime(defaultedOptions.staleTime) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);
1738
- }
1739
- prefetchQuery(options) {
1740
- return this.fetchQuery(options).then(noop).catch(noop);
1741
- }
1742
- fetchInfiniteQuery(options) {
1743
- options.behavior = infiniteQueryBehavior();
1744
- return this.fetchQuery(options);
1745
- }
1746
- prefetchInfiniteQuery(options) {
1747
- return this.fetchInfiniteQuery(options).then(noop).catch(noop);
1748
- }
1749
- resumePausedMutations() {
1750
- return this.#mutationCache.resumePausedMutations();
1751
- }
1752
- getQueryCache() {
1753
- return this.#queryCache;
1754
- }
1755
- getMutationCache() {
1756
- return this.#mutationCache;
1757
- }
1758
- getDefaultOptions() {
1759
- return this.#defaultOptions;
1760
- }
1761
- setDefaultOptions(options) {
1762
- this.#defaultOptions = options;
1763
- }
1764
- setQueryDefaults(queryKey, options) {
1765
- this.#queryDefaults.set(hashKey(queryKey), {
1766
- queryKey,
1767
- defaultOptions: options
1768
- });
1769
- }
1770
- getQueryDefaults(queryKey) {
1771
- const defaults = [...this.#queryDefaults.values()];
1772
- let result = {};
1773
- defaults.forEach(queryDefault => {
1774
- if (partialMatchKey(queryKey, queryDefault.queryKey)) {
1775
- result = {
1776
- ...result,
1777
- ...queryDefault.defaultOptions
1778
- };
1779
- }
1780
- });
1781
- return result;
1782
- }
1783
- setMutationDefaults(mutationKey, options) {
1784
- this.#mutationDefaults.set(hashKey(mutationKey), {
1785
- mutationKey,
1786
- defaultOptions: options
1787
- });
1788
- }
1789
- getMutationDefaults(mutationKey) {
1790
- const defaults = [...this.#mutationDefaults.values()];
1791
- let result = {};
1792
- defaults.forEach(queryDefault => {
1793
- if (partialMatchKey(mutationKey, queryDefault.mutationKey)) {
1794
- result = {
1795
- ...result,
1796
- ...queryDefault.defaultOptions
1797
- };
1798
- }
1799
- });
1800
- return result;
1801
- }
1802
- defaultQueryOptions(options) {
1803
- if (options?._defaulted) {
1804
- return options;
1805
- }
1806
- const defaultedOptions = {
1807
- ...this.#defaultOptions.queries,
1808
- ...(options?.queryKey && this.getQueryDefaults(options.queryKey)),
1809
- ...options,
1810
- _defaulted: true
1811
- };
1812
- if (!defaultedOptions.queryHash) {
1813
- defaultedOptions.queryHash = hashQueryKeyByOptions(defaultedOptions.queryKey, defaultedOptions);
1814
- }
1815
-
1816
- // dependent default values
1817
- if (typeof defaultedOptions.refetchOnReconnect === 'undefined') {
1818
- defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== 'always';
1819
- }
1820
- if (typeof defaultedOptions.throwErrors === 'undefined') {
1821
- defaultedOptions.throwErrors = !!defaultedOptions.suspense;
1822
- }
1823
- return defaultedOptions;
1824
- }
1825
- defaultMutationOptions(options) {
1826
- if (options?._defaulted) {
1827
- return options;
1828
- }
1829
- return {
1830
- ...this.#defaultOptions.mutations,
1831
- ...(options?.mutationKey && this.getMutationDefaults(options.mutationKey)),
1832
- ...options,
1833
- _defaulted: true
1834
- };
1835
- }
1836
- clear() {
1837
- this.#queryCache.clear();
1838
- this.#mutationCache.clear();
1839
- }
1840
- };
1841
-
1842
- class QueryObserver extends Subscribable {
1843
- #client;
1844
- #currentQuery = undefined;
1845
- #currentQueryInitialState = undefined;
1846
- #currentResult = undefined;
1847
- #currentResultState;
1848
- #currentResultOptions;
1849
- #previousQueryResult;
1850
- #selectError;
1851
- #selectFn;
1852
- #selectResult;
1853
- #staleTimeoutId;
1854
- #refetchIntervalId;
1855
- #currentRefetchInterval;
1856
- #trackedProps = new Set();
1857
- constructor(client, options) {
1858
- super();
1859
- this.#client = client;
1860
- this.options = options;
1861
- this.#selectError = null;
1862
- this.bindMethods();
1863
- this.setOptions(options);
1864
- }
1865
- bindMethods() {
1866
- this.refetch = this.refetch.bind(this);
1867
- }
1868
- onSubscribe() {
1869
- if (this.listeners.length === 1) {
1870
- this.#currentQuery.addObserver(this);
1871
- if (shouldFetchOnMount(this.#currentQuery, this.options)) {
1872
- this.#executeFetch();
1873
- }
1874
- this.#updateTimers();
1875
- }
1876
- }
1877
- onUnsubscribe() {
1878
- if (!this.listeners.length) {
1879
- this.destroy();
1880
- }
1881
- }
1882
- shouldFetchOnReconnect() {
1883
- return shouldFetchOn(this.#currentQuery, this.options, this.options.refetchOnReconnect);
1884
- }
1885
- shouldFetchOnWindowFocus() {
1886
- return shouldFetchOn(this.#currentQuery, this.options, this.options.refetchOnWindowFocus);
1887
- }
1888
- destroy() {
1889
- this.listeners = [];
1890
- this.#clearStaleTimeout();
1891
- this.#clearRefetchInterval();
1892
- this.#currentQuery.removeObserver(this);
1893
- }
1894
- setOptions(options, notifyOptions) {
1895
- const prevOptions = this.options;
1896
- const prevQuery = this.#currentQuery;
1897
- this.options = this.#client.defaultQueryOptions(options);
1898
- if (!shallowEqualObjects(prevOptions, this.options)) {
1899
- this.#client.getQueryCache().notify({
1900
- type: 'observerOptionsUpdated',
1901
- query: this.#currentQuery,
1902
- observer: this
1903
- });
1904
- }
1905
- if (typeof this.options.enabled !== 'undefined' && typeof this.options.enabled !== 'boolean') {
1906
- throw new Error('Expected enabled to be a boolean');
1907
- }
1908
-
1909
- // Keep previous query key if the user does not supply one
1910
- if (!this.options.queryKey) {
1911
- this.options.queryKey = prevOptions.queryKey;
1912
- }
1913
- this.#updateQuery();
1914
- const mounted = this.hasListeners();
1915
-
1916
- // Fetch if there are subscribers
1917
- if (mounted && shouldFetchOptionally(this.#currentQuery, prevQuery, this.options, prevOptions)) {
1918
- this.#executeFetch();
1919
- }
1920
-
1921
- // Update result
1922
- this.#updateResult(notifyOptions);
1923
-
1924
- // Update stale interval if needed
1925
- if (mounted && (this.#currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || this.options.staleTime !== prevOptions.staleTime)) {
1926
- this.#updateStaleTimeout();
1927
- }
1928
- const nextRefetchInterval = this.#computeRefetchInterval();
1929
-
1930
- // Update refetch interval if needed
1931
- if (mounted && (this.#currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || nextRefetchInterval !== this.#currentRefetchInterval)) {
1932
- this.#updateRefetchInterval(nextRefetchInterval);
1933
- }
1934
- }
1935
- getOptimisticResult(options) {
1936
- const query = this.#client.getQueryCache().build(this.#client, options);
1937
- return this.createResult(query, options);
1938
- }
1939
- getCurrentResult() {
1940
- return this.#currentResult;
1941
- }
1942
- trackResult(result) {
1943
- const trackedResult = {};
1944
- Object.keys(result).forEach(key => {
1945
- Object.defineProperty(trackedResult, key, {
1946
- configurable: false,
1947
- enumerable: true,
1948
- get: () => {
1949
- this.#trackedProps.add(key);
1950
- return result[key];
1951
- }
1952
- });
1953
- });
1954
- return trackedResult;
1955
- }
1956
- getCurrentQuery() {
1957
- return this.#currentQuery;
1958
- }
1959
- refetch({
1960
- ...options
1961
- } = {}) {
1962
- return this.fetch({
1963
- ...options
1964
- });
1965
- }
1966
- fetchOptimistic(options) {
1967
- const defaultedOptions = this.#client.defaultQueryOptions(options);
1968
- const query = this.#client.getQueryCache().build(this.#client, defaultedOptions);
1969
- query.isFetchingOptimistic = true;
1970
- return query.fetch().then(() => this.createResult(query, defaultedOptions));
1971
- }
1972
- fetch(fetchOptions) {
1973
- return this.#executeFetch({
1974
- ...fetchOptions,
1975
- cancelRefetch: fetchOptions.cancelRefetch ?? true
1976
- }).then(() => {
1977
- this.#updateResult();
1978
- return this.#currentResult;
1979
- });
1980
- }
1981
- #executeFetch(fetchOptions) {
1982
- // Make sure we reference the latest query as the current one might have been removed
1983
- this.#updateQuery();
1984
-
1985
- // Fetch
1986
- let promise = this.#currentQuery.fetch(this.options, fetchOptions);
1987
- if (!fetchOptions?.throwOnError) {
1988
- promise = promise.catch(noop);
1989
- }
1990
- return promise;
1991
- }
1992
- #updateStaleTimeout() {
1993
- this.#clearStaleTimeout();
1994
- if (isServer || this.#currentResult.isStale || !isValidTimeout(this.options.staleTime)) {
1995
- return;
1996
- }
1997
- const time = timeUntilStale(this.#currentResult.dataUpdatedAt, this.options.staleTime);
1998
-
1999
- // The timeout is sometimes triggered 1 ms before the stale time expiration.
2000
- // To mitigate this issue we always add 1 ms to the timeout.
2001
- const timeout = time + 1;
2002
- this.#staleTimeoutId = setTimeout(() => {
2003
- if (!this.#currentResult.isStale) {
2004
- this.#updateResult();
2005
- }
2006
- }, timeout);
2007
- }
2008
- #computeRefetchInterval() {
2009
- return typeof this.options.refetchInterval === 'function' ? this.options.refetchInterval(this.#currentResult.data, this.#currentQuery) : this.options.refetchInterval ?? false;
2010
- }
2011
- #updateRefetchInterval(nextInterval) {
2012
- this.#clearRefetchInterval();
2013
- this.#currentRefetchInterval = nextInterval;
2014
- if (isServer || this.options.enabled === false || !isValidTimeout(this.#currentRefetchInterval) || this.#currentRefetchInterval === 0) {
2015
- return;
2016
- }
2017
- this.#refetchIntervalId = setInterval(() => {
2018
- if (this.options.refetchIntervalInBackground || focusManager.isFocused()) {
2019
- this.#executeFetch();
2020
- }
2021
- }, this.#currentRefetchInterval);
2022
- }
2023
- #updateTimers() {
2024
- this.#updateStaleTimeout();
2025
- this.#updateRefetchInterval(this.#computeRefetchInterval());
2026
- }
2027
- #clearStaleTimeout() {
2028
- if (this.#staleTimeoutId) {
2029
- clearTimeout(this.#staleTimeoutId);
2030
- this.#staleTimeoutId = undefined;
2031
- }
2032
- }
2033
- #clearRefetchInterval() {
2034
- if (this.#refetchIntervalId) {
2035
- clearInterval(this.#refetchIntervalId);
2036
- this.#refetchIntervalId = undefined;
2037
- }
2038
- }
2039
- createResult(query, options) {
2040
- const prevQuery = this.#currentQuery;
2041
- const prevOptions = this.options;
2042
- const prevResult = this.#currentResult;
2043
- const prevResultState = this.#currentResultState;
2044
- const prevResultOptions = this.#currentResultOptions;
2045
- const queryChange = query !== prevQuery;
2046
- const queryInitialState = queryChange ? query.state : this.#currentQueryInitialState;
2047
- const prevQueryResult = queryChange ? this.#currentResult : this.#previousQueryResult;
2048
- const {
2049
- state
2050
- } = query;
2051
- let {
2052
- error,
2053
- errorUpdatedAt,
2054
- fetchStatus,
2055
- status
2056
- } = state;
2057
- let isPlaceholderData = false;
2058
- let data;
2059
-
2060
- // Optimistically set result in fetching state if needed
2061
- if (options._optimisticResults) {
2062
- const mounted = this.hasListeners();
2063
- const fetchOnMount = !mounted && shouldFetchOnMount(query, options);
2064
- const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
2065
- if (fetchOnMount || fetchOptionally) {
2066
- fetchStatus = canFetch(query.options.networkMode) ? 'fetching' : 'paused';
2067
- if (!state.dataUpdatedAt) {
2068
- status = 'pending';
2069
- }
2070
- }
2071
- if (options._optimisticResults === 'isRestoring') {
2072
- fetchStatus = 'idle';
2073
- }
2074
- }
2075
-
2076
- // Select data if needed
2077
- if (options.select && typeof state.data !== 'undefined') {
2078
- // Memoize select result
2079
- if (prevResult && state.data === prevResultState?.data && options.select === this.#selectFn) {
2080
- data = this.#selectResult;
2081
- } else {
2082
- try {
2083
- this.#selectFn = options.select;
2084
- data = options.select(state.data);
2085
- data = replaceData(prevResult?.data, data, options);
2086
- this.#selectResult = data;
2087
- this.#selectError = null;
2088
- } catch (selectError) {
2089
- this.#selectError = selectError;
2090
- }
2091
- }
2092
- }
2093
- // Use query data
2094
- else {
2095
- data = state.data;
2096
- }
2097
-
2098
- // Show placeholder data if needed
2099
- if (typeof options.placeholderData !== 'undefined' && typeof data === 'undefined' && status === 'pending') {
2100
- let placeholderData;
2101
-
2102
- // Memoize placeholder data
2103
- if (prevResult?.isPlaceholderData && options.placeholderData === prevResultOptions?.placeholderData) {
2104
- placeholderData = prevResult.data;
2105
- } else {
2106
- placeholderData = typeof options.placeholderData === 'function' ? options.placeholderData(prevQueryResult?.data) : options.placeholderData;
2107
- if (options.select && typeof placeholderData !== 'undefined') {
2108
- try {
2109
- placeholderData = options.select(placeholderData);
2110
- this.#selectError = null;
2111
- } catch (selectError) {
2112
- this.#selectError = selectError;
2113
- }
2114
- }
2115
- }
2116
- if (typeof placeholderData !== 'undefined') {
2117
- status = 'success';
2118
- data = replaceData(prevResult?.data, placeholderData, options);
2119
- isPlaceholderData = true;
2120
- }
2121
- }
2122
- if (this.#selectError) {
2123
- error = this.#selectError;
2124
- data = this.#selectResult;
2125
- errorUpdatedAt = Date.now();
2126
- status = 'error';
2127
- }
2128
- const isFetching = fetchStatus === 'fetching';
2129
- const isPending = status === 'pending';
2130
- const isError = status === 'error';
2131
- const isLoading = isPending && isFetching;
2132
- const result = {
2133
- status,
2134
- fetchStatus,
2135
- isPending,
2136
- isSuccess: status === 'success',
2137
- isError,
2138
- isInitialLoading: isLoading,
2139
- isLoading,
2140
- data,
2141
- dataUpdatedAt: state.dataUpdatedAt,
2142
- error,
2143
- errorUpdatedAt,
2144
- failureCount: state.fetchFailureCount,
2145
- failureReason: state.fetchFailureReason,
2146
- errorUpdateCount: state.errorUpdateCount,
2147
- isFetched: state.dataUpdateCount > 0 || state.errorUpdateCount > 0,
2148
- isFetchedAfterMount: state.dataUpdateCount > queryInitialState.dataUpdateCount || state.errorUpdateCount > queryInitialState.errorUpdateCount,
2149
- isFetching,
2150
- isRefetching: isFetching && !isPending,
2151
- isLoadingError: isError && state.dataUpdatedAt === 0,
2152
- isPaused: fetchStatus === 'paused',
2153
- isPlaceholderData,
2154
- isRefetchError: isError && state.dataUpdatedAt !== 0,
2155
- isStale: isStale(query, options),
2156
- refetch: this.refetch
2157
- };
2158
- return result;
2159
- }
2160
- #updateResult(notifyOptions) {
2161
- const prevResult = this.#currentResult;
2162
- const nextResult = this.createResult(this.#currentQuery, this.options);
2163
- this.#currentResultState = this.#currentQuery.state;
2164
- this.#currentResultOptions = this.options;
2165
-
2166
- // Only notify and update result if something has changed
2167
- if (shallowEqualObjects(nextResult, prevResult)) {
2168
- return;
2169
- }
2170
- this.#currentResult = nextResult;
2171
-
2172
- // Determine which callbacks to trigger
2173
- const defaultNotifyOptions = {};
2174
- const shouldNotifyListeners = () => {
2175
- if (!prevResult) {
2176
- return true;
2177
- }
2178
- const {
2179
- notifyOnChangeProps
2180
- } = this.options;
2181
- if (notifyOnChangeProps === 'all' || !notifyOnChangeProps && !this.#trackedProps.size) {
2182
- return true;
2183
- }
2184
- const includedProps = new Set(notifyOnChangeProps ?? this.#trackedProps);
2185
- if (this.options.throwErrors) {
2186
- includedProps.add('error');
2187
- }
2188
- return Object.keys(this.#currentResult).some(key => {
2189
- const typedKey = key;
2190
- const changed = this.#currentResult[typedKey] !== prevResult[typedKey];
2191
- return changed && includedProps.has(typedKey);
2192
- });
2193
- };
2194
- if (notifyOptions?.listeners !== false && shouldNotifyListeners()) {
2195
- defaultNotifyOptions.listeners = true;
2196
- }
2197
- this.#notify({
2198
- ...defaultNotifyOptions,
2199
- ...notifyOptions
2200
- });
2201
- }
2202
- #updateQuery() {
2203
- const query = this.#client.getQueryCache().build(this.#client, this.options);
2204
- if (query === this.#currentQuery) {
2205
- return;
2206
- }
2207
- const prevQuery = this.#currentQuery;
2208
- this.#currentQuery = query;
2209
- this.#currentQueryInitialState = query.state;
2210
- this.#previousQueryResult = this.#currentResult;
2211
- if (this.hasListeners()) {
2212
- prevQuery?.removeObserver(this);
2213
- query.addObserver(this);
2214
- }
2215
- }
2216
- onQueryUpdate(action) {
2217
- const notifyOptions = {};
2218
- if (action.type === 'success') {
2219
- notifyOptions.onSuccess = !action.manual;
2220
- } else if (action.type === 'error' && !isCancelledError(action.error)) {
2221
- notifyOptions.onError = true;
2222
- }
2223
- this.#updateResult(notifyOptions);
2224
- if (this.hasListeners()) {
2225
- this.#updateTimers();
2226
- }
2227
- }
2228
- #notify(notifyOptions) {
2229
- notifyManager.batch(() => {
2230
- // First trigger the configuration callbacks
2231
- if (notifyOptions.onSuccess) {
2232
- this.options.onSuccess?.(this.#currentResult.data);
2233
- this.options.onSettled?.(this.#currentResult.data, null);
2234
- } else if (notifyOptions.onError) {
2235
- this.options.onError?.(this.#currentResult.error);
2236
- this.options.onSettled?.(undefined, this.#currentResult.error);
2237
- }
2238
-
2239
- // Then trigger the listeners
2240
- if (notifyOptions.listeners) {
2241
- this.listeners.forEach(listener => {
2242
- listener(this.#currentResult);
2243
- });
2244
- }
2245
-
2246
- // Then the cache listeners
2247
- this.#client.getQueryCache().notify({
2248
- query: this.#currentQuery,
2249
- type: 'observerResultsUpdated'
2250
- });
2251
- });
2252
- }
2253
- }
2254
- function shouldLoadOnMount(query, options) {
2255
- return options.enabled !== false && !query.state.dataUpdatedAt && !(query.state.status === 'error' && options.retryOnMount === false);
2256
- }
2257
- function shouldFetchOnMount(query, options) {
2258
- return shouldLoadOnMount(query, options) || query.state.dataUpdatedAt > 0 && shouldFetchOn(query, options, options.refetchOnMount);
2259
- }
2260
- function shouldFetchOn(query, options, field) {
2261
- if (options.enabled !== false) {
2262
- const value = typeof field === 'function' ? field(query) : field;
2263
- return value === 'always' || value !== false && isStale(query, options);
2264
- }
2265
- return false;
2266
- }
2267
- function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
2268
- return options.enabled !== false && (query !== prevQuery || prevOptions.enabled === false) && (!options.suspense || query.state.status !== 'error') && isStale(query, options);
2269
- }
2270
- function isStale(query, options) {
2271
- return query.isStaleByTime(options.staleTime);
2272
- }
2273
-
2274
- function difference(array1, array2) {
2275
- return array1.filter(x => array2.indexOf(x) === -1);
2276
- }
2277
- function replaceAt(array, index, value) {
2278
- const copy = array.slice(0);
2279
- copy[index] = value;
2280
- return copy;
2281
- }
2282
- class QueriesObserver extends Subscribable {
2283
- #client;
2284
- #result;
2285
- #queries;
2286
- #observers;
2287
- constructor(client, queries) {
2288
- super();
2289
- this.#client = client;
2290
- this.#queries = [];
2291
- this.#result = [];
2292
- this.#observers = [];
2293
- if (queries) {
2294
- this.setQueries(queries);
2295
- }
2296
- }
2297
- onSubscribe() {
2298
- if (this.listeners.length === 1) {
2299
- this.#observers.forEach(observer => {
2300
- observer.subscribe(result => {
2301
- this.#onUpdate(observer, result);
2302
- });
2303
- });
2304
- }
2305
- }
2306
- onUnsubscribe() {
2307
- if (!this.listeners.length) {
2308
- this.destroy();
2309
- }
2310
- }
2311
- destroy() {
2312
- this.listeners = [];
2313
- this.#observers.forEach(observer => {
2314
- observer.destroy();
2315
- });
2316
- }
2317
- setQueries(queries, notifyOptions) {
2318
- this.#queries = queries;
2319
- notifyManager.batch(() => {
2320
- const prevObservers = this.#observers;
2321
- const newObserverMatches = this.#findMatchingObservers(this.#queries);
2322
-
2323
- // set options for the new observers to notify of changes
2324
- newObserverMatches.forEach(match => match.observer.setOptions(match.defaultedQueryOptions, notifyOptions));
2325
- const newObservers = newObserverMatches.map(match => match.observer);
2326
- const newResult = newObservers.map(observer => observer.getCurrentResult());
2327
- const hasIndexChange = newObservers.some((observer, index) => observer !== prevObservers[index]);
2328
- if (prevObservers.length === newObservers.length && !hasIndexChange) {
2329
- return;
2330
- }
2331
- this.#observers = newObservers;
2332
- this.#result = newResult;
2333
- if (!this.hasListeners()) {
2334
- return;
2335
- }
2336
- difference(prevObservers, newObservers).forEach(observer => {
2337
- observer.destroy();
2338
- });
2339
- difference(newObservers, prevObservers).forEach(observer => {
2340
- observer.subscribe(result => {
2341
- this.#onUpdate(observer, result);
2342
- });
2343
- });
2344
- this.#notify();
2345
- });
2346
- }
2347
- getCurrentResult() {
2348
- return this.#result;
2349
- }
2350
- getQueries() {
2351
- return this.#observers.map(observer => observer.getCurrentQuery());
2352
- }
2353
- getObservers() {
2354
- return this.#observers;
2355
- }
2356
- getOptimisticResult(queries) {
2357
- return this.#findMatchingObservers(queries).map(match => match.observer.getOptimisticResult(match.defaultedQueryOptions));
2358
- }
2359
- #findMatchingObservers(queries) {
2360
- const prevObservers = this.#observers;
2361
- const defaultedQueryOptions = queries.map(options => this.#client.defaultQueryOptions(options));
2362
- const matchingObservers = defaultedQueryOptions.flatMap(defaultedOptions => {
2363
- const match = prevObservers.find(observer => observer.options.queryHash === defaultedOptions.queryHash);
2364
- if (match != null) {
2365
- return [{
2366
- defaultedQueryOptions: defaultedOptions,
2367
- observer: match
2368
- }];
2369
- }
2370
- return [];
2371
- });
2372
- const matchedQueryHashes = matchingObservers.map(match => match.defaultedQueryOptions.queryHash);
2373
- const unmatchedQueries = defaultedQueryOptions.filter(defaultedOptions => !matchedQueryHashes.includes(defaultedOptions.queryHash));
2374
- const getObserver = options => {
2375
- const defaultedOptions = this.#client.defaultQueryOptions(options);
2376
- const currentObserver = this.#observers.find(o => o.options.queryHash === defaultedOptions.queryHash);
2377
- return currentObserver ?? new QueryObserver(this.#client, defaultedOptions);
2378
- };
2379
- const newOrReusedObservers = unmatchedQueries.map(options => {
2380
- return {
2381
- defaultedQueryOptions: options,
2382
- observer: getObserver(options)
2383
- };
2384
- });
2385
- const sortMatchesByOrderOfQueries = (a, b) => defaultedQueryOptions.indexOf(a.defaultedQueryOptions) - defaultedQueryOptions.indexOf(b.defaultedQueryOptions);
2386
- return matchingObservers.concat(newOrReusedObservers).sort(sortMatchesByOrderOfQueries);
2387
- }
2388
- #onUpdate(observer, result) {
2389
- const index = this.#observers.indexOf(observer);
2390
- if (index !== -1) {
2391
- this.#result = replaceAt(this.#result, index, result);
2392
- this.#notify();
2393
- }
2394
- }
2395
- #notify() {
2396
- notifyManager.batch(() => {
2397
- this.listeners.forEach(listener => {
2398
- listener(this.#result);
2399
- });
2400
- });
2401
- }
2402
- }
2403
-
2404
- class InfiniteQueryObserver extends QueryObserver {
2405
- // Type override
2406
-
2407
- // Type override
2408
-
2409
- // Type override
2410
-
2411
- // eslint-disable-next-line @typescript-eslint/no-useless-constructor
2412
- constructor(client, options) {
2413
- super(client, options);
2414
- }
2415
- bindMethods() {
2416
- super.bindMethods();
2417
- this.fetchNextPage = this.fetchNextPage.bind(this);
2418
- this.fetchPreviousPage = this.fetchPreviousPage.bind(this);
2419
- }
2420
- setOptions(options, notifyOptions) {
2421
- super.setOptions({
2422
- ...options,
2423
- behavior: infiniteQueryBehavior()
2424
- }, notifyOptions);
2425
- }
2426
- getOptimisticResult(options) {
2427
- options.behavior = infiniteQueryBehavior();
2428
- return super.getOptimisticResult(options);
2429
- }
2430
- fetchNextPage(options) {
2431
- return this.fetch({
2432
- ...options,
2433
- meta: {
2434
- fetchMore: {
2435
- direction: 'forward'
2436
- }
2437
- }
2438
- });
2439
- }
2440
- fetchPreviousPage(options) {
2441
- return this.fetch({
2442
- ...options,
2443
- meta: {
2444
- fetchMore: {
2445
- direction: 'backward'
2446
- }
2447
- }
2448
- });
2449
- }
2450
- createResult(query, options) {
2451
- const {
2452
- state
2453
- } = query;
2454
- const result = super.createResult(query, options);
2455
- const {
2456
- isFetching,
2457
- isRefetching
2458
- } = result;
2459
- const isFetchingNextPage = isFetching && state.fetchMeta?.fetchMore?.direction === 'forward';
2460
- const isFetchingPreviousPage = isFetching && state.fetchMeta?.fetchMore?.direction === 'backward';
2461
- return {
2462
- ...result,
2463
- fetchNextPage: this.fetchNextPage,
2464
- fetchPreviousPage: this.fetchPreviousPage,
2465
- hasNextPage: hasNextPage(options, state.data),
2466
- hasPreviousPage: hasPreviousPage(options, state.data),
2467
- isFetchingNextPage,
2468
- isFetchingPreviousPage,
2469
- isRefetching: isRefetching && !isFetchingNextPage && !isFetchingPreviousPage
2470
- };
2471
- }
2472
- }
2473
-
2474
- // TYPES
2475
-
2476
- // CLASS
2477
-
2478
- class MutationObserver extends Subscribable {
2479
- #client;
2480
- #currentResult = undefined;
2481
- #currentMutation;
2482
- #mutateOptions;
2483
- constructor(client, options) {
2484
- super();
2485
- this.#client = client;
2486
- this.setOptions(options);
2487
- this.bindMethods();
2488
- this.#updateResult();
2489
- }
2490
- bindMethods() {
2491
- this.mutate = this.mutate.bind(this);
2492
- this.reset = this.reset.bind(this);
2493
- }
2494
- setOptions(options) {
2495
- const prevOptions = this.options;
2496
- this.options = this.#client.defaultMutationOptions(options);
2497
- if (!shallowEqualObjects(prevOptions, this.options)) {
2498
- this.#client.getMutationCache().notify({
2499
- type: 'observerOptionsUpdated',
2500
- mutation: this.#currentMutation,
2501
- observer: this
2502
- });
2503
- }
2504
- this.#currentMutation?.setOptions(this.options);
2505
- }
2506
- onUnsubscribe() {
2507
- if (!this.listeners.length) {
2508
- this.#currentMutation?.removeObserver(this);
2509
- }
2510
- }
2511
- onMutationUpdate(action) {
2512
- this.#updateResult();
2513
- this.#notify(action);
2514
- }
2515
- getCurrentResult() {
2516
- return this.#currentResult;
2517
- }
2518
- reset() {
2519
- this.#currentMutation = undefined;
2520
- this.#updateResult();
2521
- this.#notify();
2522
- }
2523
- mutate(variables, options) {
2524
- this.#mutateOptions = options;
2525
- this.#currentMutation?.removeObserver(this);
2526
- this.#currentMutation = this.#client.getMutationCache().build(this.#client, this.options);
2527
- this.#currentMutation.addObserver(this);
2528
- return this.#currentMutation.execute(variables);
2529
- }
2530
- #updateResult() {
2531
- const state = this.#currentMutation?.state ?? getDefaultState();
2532
- this.#currentResult = {
2533
- ...state,
2534
- isPending: state.status === 'pending',
2535
- isSuccess: state.status === 'success',
2536
- isError: state.status === 'error',
2537
- isIdle: state.status === 'idle',
2538
- mutate: this.mutate,
2539
- reset: this.reset
2540
- };
2541
- }
2542
- #notify(action) {
2543
- notifyManager.batch(() => {
2544
- // First trigger the mutate callbacks
2545
- if (this.#mutateOptions && this.hasListeners()) {
2546
- if (action?.type === 'success') {
2547
- this.#mutateOptions.onSuccess?.(action.data, this.#currentResult.variables, this.#currentResult.context);
2548
- this.#mutateOptions.onSettled?.(action.data, null, this.#currentResult.variables, this.#currentResult.context);
2549
- } else if (action?.type === 'error') {
2550
- this.#mutateOptions.onError?.(action.error, this.#currentResult.variables, this.#currentResult.context);
2551
- this.#mutateOptions.onSettled?.(undefined, action.error, this.#currentResult.variables, this.#currentResult.context);
2552
- }
2553
- }
2554
-
2555
- // Then trigger the listeners
2556
- this.listeners.forEach(listener => {
2557
- listener(this.#currentResult);
2558
- });
2559
- });
2560
- }
2561
- }
2562
-
2563
- // TYPES
2564
-
2565
- // FUNCTIONS
2566
-
2567
- function dehydrateMutation(mutation) {
2568
- return {
2569
- mutationKey: mutation.options.mutationKey,
2570
- state: mutation.state
2571
- };
2572
- }
2573
-
2574
- // Most config is not dehydrated but instead meant to configure again when
2575
- // consuming the de/rehydrated data, typically with useQuery on the client.
2576
- // Sometimes it might make sense to prefetch data on the server and include
2577
- // in the html-payload, but not consume it on the initial render.
2578
- function dehydrateQuery(query) {
2579
- return {
2580
- state: query.state,
2581
- queryKey: query.queryKey,
2582
- queryHash: query.queryHash
2583
- };
2584
- }
2585
- function defaultShouldDehydrateMutation(mutation) {
2586
- return mutation.state.isPaused;
2587
- }
2588
- function defaultShouldDehydrateQuery(query) {
2589
- return query.state.status === 'success';
2590
- }
2591
- function dehydrate(client, options = {}) {
2592
- const mutations = [];
2593
- const queries = [];
2594
- if (options.dehydrateMutations !== false) {
2595
- const shouldDehydrateMutation = options.shouldDehydrateMutation || defaultShouldDehydrateMutation;
2596
- client.getMutationCache().getAll().forEach(mutation => {
2597
- if (shouldDehydrateMutation(mutation)) {
2598
- mutations.push(dehydrateMutation(mutation));
2599
- }
2600
- });
2601
- }
2602
- if (options.dehydrateQueries !== false) {
2603
- const shouldDehydrateQuery = options.shouldDehydrateQuery || defaultShouldDehydrateQuery;
2604
- client.getQueryCache().getAll().forEach(query => {
2605
- if (shouldDehydrateQuery(query)) {
2606
- queries.push(dehydrateQuery(query));
2607
- }
2608
- });
2609
- }
2610
- return {
2611
- mutations,
2612
- queries
2613
- };
2614
- }
2615
- function hydrate(client, dehydratedState, options) {
2616
- if (typeof dehydratedState !== 'object' || dehydratedState === null) {
2617
- return;
2618
- }
2619
- const mutationCache = client.getMutationCache();
2620
- const queryCache = client.getQueryCache();
2621
-
2622
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2623
- const mutations = dehydratedState.mutations || [];
2624
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2625
- const queries = dehydratedState.queries || [];
2626
- mutations.forEach(dehydratedMutation => {
2627
- mutationCache.build(client, {
2628
- ...options?.defaultOptions?.mutations,
2629
- mutationKey: dehydratedMutation.mutationKey
2630
- }, dehydratedMutation.state);
2631
- });
2632
- queries.forEach(dehydratedQuery => {
2633
- const query = queryCache.get(dehydratedQuery.queryHash);
2634
-
2635
- // Reset fetch status to idle in the dehydrated state to avoid
2636
- // query being stuck in fetching state upon hydration
2637
- const dehydratedQueryState = {
2638
- ...dehydratedQuery.state,
2639
- fetchStatus: 'idle'
2640
- };
2641
-
2642
- // Do not hydrate if an existing query exists with newer data
2643
- if (query) {
2644
- if (query.state.dataUpdatedAt < dehydratedQueryState.dataUpdatedAt) {
2645
- query.setState(dehydratedQueryState);
2646
- }
2647
- return;
2648
- }
2649
-
2650
- // Restore query
2651
- queryCache.build(client, {
2652
- ...options?.defaultOptions?.queries,
2653
- queryKey: dehydratedQuery.queryKey,
2654
- queryHash: dehydratedQuery.queryHash
2655
- }, dehydratedQueryState);
2656
- });
2657
- }
2658
-
2659
- const VUE_QUERY_CLIENT = 'VUE_QUERY_CLIENT';
2660
- function getClientKey(key) {
2661
- const suffix = key ? `:${key}` : '';
2662
- return `${VUE_QUERY_CLIENT}${suffix}`;
2663
- }
2664
- function updateState(state, update) {
2665
- Object.keys(state).forEach(key => {
2666
- state[key] = update[key];
2667
- });
2668
- }
2669
- function cloneDeep(value, customizer) {
2670
- if (customizer) {
2671
- const result = customizer(value);
2672
- // If it's a ref of undefined, return undefined
2673
- if (result === undefined && vueDemi.isRef(value)) {
2674
- return result;
2675
- }
2676
- if (result !== undefined) {
2677
- return result;
2678
- }
2679
- }
2680
- if (Array.isArray(value)) {
2681
- return value.map(val => cloneDeep(val, customizer));
2682
- }
2683
- if (typeof value === 'object' && isPlainObject(value)) {
2684
- const entries = Object.entries(value).map(([key, val]) => [key, cloneDeep(val, customizer)]);
2685
- return Object.fromEntries(entries);
2686
- }
2687
- return value;
2688
- }
2689
- function cloneDeepUnref(obj) {
2690
- return cloneDeep(obj, val => {
2691
- if (vueDemi.isRef(val)) {
2692
- return cloneDeepUnref(vueDemi.unref(val));
2693
- }
2694
- return undefined;
2695
- });
2696
- }
2697
- function isPlainObject(value) {
2698
- if (Object.prototype.toString.call(value) !== '[object Object]') {
2699
- return false;
2700
- }
2701
- const prototype = Object.getPrototypeOf(value);
2702
- return prototype === null || prototype === Object.prototype;
2703
- }
2704
-
2705
- function useQueryClient(id = '') {
2706
- const vm = vueDemi.getCurrentInstance()?.proxy;
2707
- if (!vm) {
2708
- throw new Error('vue-query hooks can only be used inside setup() function.');
2709
- }
2710
- const key = getClientKey(id);
2711
- const queryClient = vueDemi.inject(key);
2712
- if (!queryClient) {
2713
- throw new Error("No 'queryClient' found in Vue context, use 'VueQueryPlugin' to properly initialize the library.");
2714
- }
2715
- return queryClient;
2716
- }
2717
-
2718
- class QueryCache extends QueryCache$1 {
2719
- find(filters) {
2720
- return super.find(cloneDeepUnref(filters));
2721
- }
2722
- findAll(filters = {}) {
2723
- return super.findAll(cloneDeepUnref(filters));
2724
- }
2725
- }
2726
-
2727
- class MutationCache extends MutationCache$1 {
2728
- find(filters) {
2729
- return super.find(cloneDeepUnref(filters));
2730
- }
2731
- findAll(filters = {}) {
2732
- return super.findAll(cloneDeepUnref(filters));
2733
- }
2734
- }
2735
-
2736
- class QueryClient extends QueryClient$1 {
2737
- constructor(config = {}) {
2738
- const unreffedConfig = cloneDeepUnref(config);
2739
- const vueQueryConfig = {
2740
- defaultOptions: unreffedConfig.defaultOptions,
2741
- queryCache: unreffedConfig.queryCache || new QueryCache(),
2742
- mutationCache: unreffedConfig.mutationCache || new MutationCache()
2743
- };
2744
- super(vueQueryConfig);
2745
- }
2746
- isRestoring = vueDemi.ref(false);
2747
- isFetching(filters = {}) {
2748
- return super.isFetching(cloneDeepUnref(filters));
2749
- }
2750
- isMutating(filters = {}) {
2751
- return super.isMutating(cloneDeepUnref(filters));
2752
- }
2753
- getQueryData(queryKey) {
2754
- return super.getQueryData(cloneDeepUnref(queryKey));
2755
- }
2756
- getQueriesData(filters) {
2757
- return super.getQueriesData(cloneDeepUnref(filters));
2758
- }
2759
- setQueryData(queryKey, updater, options = {}) {
2760
- return super.setQueryData(cloneDeepUnref(queryKey), updater, cloneDeepUnref(options));
2761
- }
2762
- setQueriesData(filters, updater, options = {}) {
2763
- return super.setQueriesData(cloneDeepUnref(filters), updater, cloneDeepUnref(options));
2764
- }
2765
- getQueryState(queryKey) {
2766
- return super.getQueryState(cloneDeepUnref(queryKey));
2767
- }
2768
- removeQueries(filters = {}) {
2769
- return super.removeQueries(cloneDeepUnref(filters));
2770
- }
2771
- resetQueries(filters = {}, options = {}) {
2772
- return super.resetQueries(cloneDeepUnref(filters), cloneDeepUnref(options));
2773
- }
2774
- cancelQueries(filters = {}, options = {}) {
2775
- return super.cancelQueries(cloneDeepUnref(filters), cloneDeepUnref(options));
2776
- }
2777
- invalidateQueries(filters = {}, options = {}) {
2778
- return super.invalidateQueries(cloneDeepUnref(filters), cloneDeepUnref(options));
2779
- }
2780
- refetchQueries(filters = {}, options = {}) {
2781
- return super.refetchQueries(cloneDeepUnref(filters), cloneDeepUnref(options));
2782
- }
2783
- fetchQuery(options) {
2784
- return super.fetchQuery(cloneDeepUnref(options));
2785
- }
2786
- prefetchQuery(options) {
2787
- return super.prefetchQuery(cloneDeepUnref(options));
2788
- }
2789
- fetchInfiniteQuery(options) {
2790
- return super.fetchInfiniteQuery(cloneDeepUnref(options));
2791
- }
2792
- prefetchInfiniteQuery(options) {
2793
- return super.prefetchInfiniteQuery(cloneDeepUnref(options));
2794
- }
2795
- setDefaultOptions(options) {
2796
- super.setDefaultOptions(cloneDeepUnref(options));
2797
- }
2798
- setQueryDefaults(queryKey, options) {
2799
- super.setQueryDefaults(cloneDeepUnref(queryKey), cloneDeepUnref(options));
2800
- }
2801
- getQueryDefaults(queryKey) {
2802
- return super.getQueryDefaults(cloneDeepUnref(queryKey));
2803
- }
2804
- setMutationDefaults(mutationKey, options) {
2805
- super.setMutationDefaults(cloneDeepUnref(mutationKey), cloneDeepUnref(options));
2806
- }
2807
- getMutationDefaults(mutationKey) {
2808
- return super.getMutationDefaults(cloneDeepUnref(mutationKey));
2809
- }
2810
- }
2811
-
2812
- function getDevtoolsGlobalHook() {
2813
- return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__;
2814
- }
2815
- function getTarget() {
2816
- // @ts-ignore
2817
- return (typeof navigator !== 'undefined' && typeof window !== 'undefined')
2818
- ? window
2819
- : typeof global !== 'undefined'
2820
- ? global
2821
- : {};
2822
- }
2823
- const isProxyAvailable = typeof Proxy === 'function';
2824
-
2825
- const HOOK_SETUP = 'devtools-plugin:setup';
2826
- const HOOK_PLUGIN_SETTINGS_SET = 'plugin:settings:set';
2827
-
2828
- let supported;
2829
- let perf;
2830
- function isPerformanceSupported() {
2831
- var _a;
2832
- if (supported !== undefined) {
2833
- return supported;
2834
- }
2835
- if (typeof window !== 'undefined' && window.performance) {
2836
- supported = true;
2837
- perf = window.performance;
2838
- }
2839
- else if (typeof global !== 'undefined' && ((_a = global.perf_hooks) === null || _a === void 0 ? void 0 : _a.performance)) {
2840
- supported = true;
2841
- perf = global.perf_hooks.performance;
2842
- }
2843
- else {
2844
- supported = false;
2845
- }
2846
- return supported;
2847
- }
2848
- function now() {
2849
- return isPerformanceSupported() ? perf.now() : Date.now();
2850
- }
2851
-
2852
- class ApiProxy {
2853
- constructor(plugin, hook) {
2854
- this.target = null;
2855
- this.targetQueue = [];
2856
- this.onQueue = [];
2857
- this.plugin = plugin;
2858
- this.hook = hook;
2859
- const defaultSettings = {};
2860
- if (plugin.settings) {
2861
- for (const id in plugin.settings) {
2862
- const item = plugin.settings[id];
2863
- defaultSettings[id] = item.defaultValue;
2864
- }
2865
- }
2866
- const localSettingsSaveId = `__vue-devtools-plugin-settings__${plugin.id}`;
2867
- let currentSettings = Object.assign({}, defaultSettings);
2868
- try {
2869
- const raw = localStorage.getItem(localSettingsSaveId);
2870
- const data = JSON.parse(raw);
2871
- Object.assign(currentSettings, data);
2872
- }
2873
- catch (e) {
2874
- // noop
2875
- }
2876
- this.fallbacks = {
2877
- getSettings() {
2878
- return currentSettings;
2879
- },
2880
- setSettings(value) {
2881
- try {
2882
- localStorage.setItem(localSettingsSaveId, JSON.stringify(value));
2883
- }
2884
- catch (e) {
2885
- // noop
2886
- }
2887
- currentSettings = value;
2888
- },
2889
- now() {
2890
- return now();
2891
- },
2892
- };
2893
- if (hook) {
2894
- hook.on(HOOK_PLUGIN_SETTINGS_SET, (pluginId, value) => {
2895
- if (pluginId === this.plugin.id) {
2896
- this.fallbacks.setSettings(value);
2897
- }
2898
- });
2899
- }
2900
- this.proxiedOn = new Proxy({}, {
2901
- get: (_target, prop) => {
2902
- if (this.target) {
2903
- return this.target.on[prop];
2904
- }
2905
- else {
2906
- return (...args) => {
2907
- this.onQueue.push({
2908
- method: prop,
2909
- args,
2910
- });
2911
- };
2912
- }
2913
- },
2914
- });
2915
- this.proxiedTarget = new Proxy({}, {
2916
- get: (_target, prop) => {
2917
- if (this.target) {
2918
- return this.target[prop];
2919
- }
2920
- else if (prop === 'on') {
2921
- return this.proxiedOn;
2922
- }
2923
- else if (Object.keys(this.fallbacks).includes(prop)) {
2924
- return (...args) => {
2925
- this.targetQueue.push({
2926
- method: prop,
2927
- args,
2928
- resolve: () => { },
2929
- });
2930
- return this.fallbacks[prop](...args);
2931
- };
2932
- }
2933
- else {
2934
- return (...args) => {
2935
- return new Promise(resolve => {
2936
- this.targetQueue.push({
2937
- method: prop,
2938
- args,
2939
- resolve,
2940
- });
2941
- });
2942
- };
2943
- }
2944
- },
2945
- });
2946
- }
2947
- async setRealTarget(target) {
2948
- this.target = target;
2949
- for (const item of this.onQueue) {
2950
- this.target.on[item.method](...item.args);
2951
- }
2952
- for (const item of this.targetQueue) {
2953
- item.resolve(await this.target[item.method](...item.args));
2954
- }
2955
- }
2956
- }
2957
-
2958
- function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
2959
- const descriptor = pluginDescriptor;
2960
- const target = getTarget();
2961
- const hook = getDevtoolsGlobalHook();
2962
- const enableProxy = isProxyAvailable && descriptor.enableEarlyProxy;
2963
- if (hook && (target.__VUE_DEVTOOLS_PLUGIN_API_AVAILABLE__ || !enableProxy)) {
2964
- hook.emit(HOOK_SETUP, pluginDescriptor, setupFn);
2965
- }
2966
- else {
2967
- const proxy = enableProxy ? new ApiProxy(descriptor, hook) : null;
2968
- const list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || [];
2969
- list.push({
2970
- pluginDescriptor: descriptor,
2971
- setupFn,
2972
- proxy,
2973
- });
2974
- if (proxy)
2975
- setupFn(proxy.proxiedTarget);
2976
- }
2977
- }
2978
-
2979
- /**
2980
- * match-sorter-utils
2981
- *
2982
- * Copyright (c) TanStack
2983
- *
2984
- * This source code is licensed under the MIT license found in the
2985
- * LICENSE.md file in the root directory of this source tree.
2986
- *
2987
- * @license MIT
2988
- */
2989
- const characterMap = {
2990
- À: 'A',
2991
- Á: 'A',
2992
- Â: 'A',
2993
- Ã: 'A',
2994
- Ä: 'A',
2995
- Å: 'A',
2996
- Ấ: 'A',
2997
- Ắ: 'A',
2998
- Ẳ: 'A',
2999
- Ẵ: 'A',
3000
- Ặ: 'A',
3001
- Æ: 'AE',
3002
- Ầ: 'A',
3003
- Ằ: 'A',
3004
- Ȃ: 'A',
3005
- Ç: 'C',
3006
- Ḉ: 'C',
3007
- È: 'E',
3008
- É: 'E',
3009
- Ê: 'E',
3010
- Ë: 'E',
3011
- Ế: 'E',
3012
- Ḗ: 'E',
3013
- Ề: 'E',
3014
- Ḕ: 'E',
3015
- Ḝ: 'E',
3016
- Ȇ: 'E',
3017
- Ì: 'I',
3018
- Í: 'I',
3019
- Î: 'I',
3020
- Ï: 'I',
3021
- Ḯ: 'I',
3022
- Ȋ: 'I',
3023
- Ð: 'D',
3024
- Ñ: 'N',
3025
- Ò: 'O',
3026
- Ó: 'O',
3027
- Ô: 'O',
3028
- Õ: 'O',
3029
- Ö: 'O',
3030
- Ø: 'O',
3031
- Ố: 'O',
3032
- Ṍ: 'O',
3033
- Ṓ: 'O',
3034
- Ȏ: 'O',
3035
- Ù: 'U',
3036
- Ú: 'U',
3037
- Û: 'U',
3038
- Ü: 'U',
3039
- Ý: 'Y',
3040
- à: 'a',
3041
- á: 'a',
3042
- â: 'a',
3043
- ã: 'a',
3044
- ä: 'a',
3045
- å: 'a',
3046
- ấ: 'a',
3047
- ắ: 'a',
3048
- ẳ: 'a',
3049
- ẵ: 'a',
3050
- ặ: 'a',
3051
- æ: 'ae',
3052
- ầ: 'a',
3053
- ằ: 'a',
3054
- ȃ: 'a',
3055
- ç: 'c',
3056
- ḉ: 'c',
3057
- è: 'e',
3058
- é: 'e',
3059
- ê: 'e',
3060
- ë: 'e',
3061
- ế: 'e',
3062
- ḗ: 'e',
3063
- ề: 'e',
3064
- ḕ: 'e',
3065
- ḝ: 'e',
3066
- ȇ: 'e',
3067
- ì: 'i',
3068
- í: 'i',
3069
- î: 'i',
3070
- ï: 'i',
3071
- ḯ: 'i',
3072
- ȋ: 'i',
3073
- ð: 'd',
3074
- ñ: 'n',
3075
- ò: 'o',
3076
- ó: 'o',
3077
- ô: 'o',
3078
- õ: 'o',
3079
- ö: 'o',
3080
- ø: 'o',
3081
- ố: 'o',
3082
- ṍ: 'o',
3083
- ṓ: 'o',
3084
- ȏ: 'o',
3085
- ù: 'u',
3086
- ú: 'u',
3087
- û: 'u',
3088
- ü: 'u',
3089
- ý: 'y',
3090
- ÿ: 'y',
3091
- Ā: 'A',
3092
- ā: 'a',
3093
- Ă: 'A',
3094
- ă: 'a',
3095
- Ą: 'A',
3096
- ą: 'a',
3097
- Ć: 'C',
3098
- ć: 'c',
3099
- Ĉ: 'C',
3100
- ĉ: 'c',
3101
- Ċ: 'C',
3102
- ċ: 'c',
3103
- Č: 'C',
3104
- č: 'c',
3105
- C̆: 'C',
3106
- c̆: 'c',
3107
- Ď: 'D',
3108
- ď: 'd',
3109
- Đ: 'D',
3110
- đ: 'd',
3111
- Ē: 'E',
3112
- ē: 'e',
3113
- Ĕ: 'E',
3114
- ĕ: 'e',
3115
- Ė: 'E',
3116
- ė: 'e',
3117
- Ę: 'E',
3118
- ę: 'e',
3119
- Ě: 'E',
3120
- ě: 'e',
3121
- Ĝ: 'G',
3122
- Ǵ: 'G',
3123
- ĝ: 'g',
3124
- ǵ: 'g',
3125
- Ğ: 'G',
3126
- ğ: 'g',
3127
- Ġ: 'G',
3128
- ġ: 'g',
3129
- Ģ: 'G',
3130
- ģ: 'g',
3131
- Ĥ: 'H',
3132
- ĥ: 'h',
3133
- Ħ: 'H',
3134
- ħ: 'h',
3135
- Ḫ: 'H',
3136
- ḫ: 'h',
3137
- Ĩ: 'I',
3138
- ĩ: 'i',
3139
- Ī: 'I',
3140
- ī: 'i',
3141
- Ĭ: 'I',
3142
- ĭ: 'i',
3143
- Į: 'I',
3144
- į: 'i',
3145
- İ: 'I',
3146
- ı: 'i',
3147
- IJ: 'IJ',
3148
- ij: 'ij',
3149
- Ĵ: 'J',
3150
- ĵ: 'j',
3151
- Ķ: 'K',
3152
- ķ: 'k',
3153
- Ḱ: 'K',
3154
- ḱ: 'k',
3155
- K̆: 'K',
3156
- k̆: 'k',
3157
- Ĺ: 'L',
3158
- ĺ: 'l',
3159
- Ļ: 'L',
3160
- ļ: 'l',
3161
- Ľ: 'L',
3162
- ľ: 'l',
3163
- Ŀ: 'L',
3164
- ŀ: 'l',
3165
- Ł: 'l',
3166
- ł: 'l',
3167
- Ḿ: 'M',
3168
- ḿ: 'm',
3169
- M̆: 'M',
3170
- m̆: 'm',
3171
- Ń: 'N',
3172
- ń: 'n',
3173
- Ņ: 'N',
3174
- ņ: 'n',
3175
- Ň: 'N',
3176
- ň: 'n',
3177
- ʼn: 'n',
3178
- N̆: 'N',
3179
- n̆: 'n',
3180
- Ō: 'O',
3181
- ō: 'o',
3182
- Ŏ: 'O',
3183
- ŏ: 'o',
3184
- Ő: 'O',
3185
- ő: 'o',
3186
- Œ: 'OE',
3187
- œ: 'oe',
3188
- P̆: 'P',
3189
- p̆: 'p',
3190
- Ŕ: 'R',
3191
- ŕ: 'r',
3192
- Ŗ: 'R',
3193
- ŗ: 'r',
3194
- Ř: 'R',
3195
- ř: 'r',
3196
- R̆: 'R',
3197
- r̆: 'r',
3198
- Ȓ: 'R',
3199
- ȓ: 'r',
3200
- Ś: 'S',
3201
- ś: 's',
3202
- Ŝ: 'S',
3203
- ŝ: 's',
3204
- Ş: 'S',
3205
- Ș: 'S',
3206
- ș: 's',
3207
- ş: 's',
3208
- Š: 'S',
3209
- š: 's',
3210
- Ţ: 'T',
3211
- ţ: 't',
3212
- ț: 't',
3213
- Ț: 'T',
3214
- Ť: 'T',
3215
- ť: 't',
3216
- Ŧ: 'T',
3217
- ŧ: 't',
3218
- T̆: 'T',
3219
- t̆: 't',
3220
- Ũ: 'U',
3221
- ũ: 'u',
3222
- Ū: 'U',
3223
- ū: 'u',
3224
- Ŭ: 'U',
3225
- ŭ: 'u',
3226
- Ů: 'U',
3227
- ů: 'u',
3228
- Ű: 'U',
3229
- ű: 'u',
3230
- Ų: 'U',
3231
- ų: 'u',
3232
- Ȗ: 'U',
3233
- ȗ: 'u',
3234
- V̆: 'V',
3235
- v̆: 'v',
3236
- Ŵ: 'W',
3237
- ŵ: 'w',
3238
- Ẃ: 'W',
3239
- ẃ: 'w',
3240
- X̆: 'X',
3241
- x̆: 'x',
3242
- Ŷ: 'Y',
3243
- ŷ: 'y',
3244
- Ÿ: 'Y',
3245
- Y̆: 'Y',
3246
- y̆: 'y',
3247
- Ź: 'Z',
3248
- ź: 'z',
3249
- Ż: 'Z',
3250
- ż: 'z',
3251
- Ž: 'Z',
3252
- ž: 'z',
3253
- ſ: 's',
3254
- ƒ: 'f',
3255
- Ơ: 'O',
3256
- ơ: 'o',
3257
- Ư: 'U',
3258
- ư: 'u',
3259
- Ǎ: 'A',
3260
- ǎ: 'a',
3261
- Ǐ: 'I',
3262
- ǐ: 'i',
3263
- Ǒ: 'O',
3264
- ǒ: 'o',
3265
- Ǔ: 'U',
3266
- ǔ: 'u',
3267
- Ǖ: 'U',
3268
- ǖ: 'u',
3269
- Ǘ: 'U',
3270
- ǘ: 'u',
3271
- Ǚ: 'U',
3272
- ǚ: 'u',
3273
- Ǜ: 'U',
3274
- ǜ: 'u',
3275
- Ứ: 'U',
3276
- ứ: 'u',
3277
- Ṹ: 'U',
3278
- ṹ: 'u',
3279
- Ǻ: 'A',
3280
- ǻ: 'a',
3281
- Ǽ: 'AE',
3282
- ǽ: 'ae',
3283
- Ǿ: 'O',
3284
- ǿ: 'o',
3285
- Þ: 'TH',
3286
- þ: 'th',
3287
- Ṕ: 'P',
3288
- ṕ: 'p',
3289
- Ṥ: 'S',
3290
- ṥ: 's',
3291
- X́: 'X',
3292
- x́: 'x',
3293
- Ѓ: 'Г',
3294
- ѓ: 'г',
3295
- Ќ: 'К',
3296
- ќ: 'к',
3297
- A̋: 'A',
3298
- a̋: 'a',
3299
- E̋: 'E',
3300
- e̋: 'e',
3301
- I̋: 'I',
3302
- i̋: 'i',
3303
- Ǹ: 'N',
3304
- ǹ: 'n',
3305
- Ồ: 'O',
3306
- ồ: 'o',
3307
- Ṑ: 'O',
3308
- ṑ: 'o',
3309
- Ừ: 'U',
3310
- ừ: 'u',
3311
- Ẁ: 'W',
3312
- ẁ: 'w',
3313
- Ỳ: 'Y',
3314
- ỳ: 'y',
3315
- Ȁ: 'A',
3316
- ȁ: 'a',
3317
- Ȅ: 'E',
3318
- ȅ: 'e',
3319
- Ȉ: 'I',
3320
- ȉ: 'i',
3321
- Ȍ: 'O',
3322
- ȍ: 'o',
3323
- Ȑ: 'R',
3324
- ȑ: 'r',
3325
- Ȕ: 'U',
3326
- ȕ: 'u',
3327
- B̌: 'B',
3328
- b̌: 'b',
3329
- Č̣: 'C',
3330
- č̣: 'c',
3331
- Ê̌: 'E',
3332
- ê̌: 'e',
3333
- F̌: 'F',
3334
- f̌: 'f',
3335
- Ǧ: 'G',
3336
- ǧ: 'g',
3337
- Ȟ: 'H',
3338
- ȟ: 'h',
3339
- J̌: 'J',
3340
- ǰ: 'j',
3341
- Ǩ: 'K',
3342
- ǩ: 'k',
3343
- M̌: 'M',
3344
- m̌: 'm',
3345
- P̌: 'P',
3346
- p̌: 'p',
3347
- Q̌: 'Q',
3348
- q̌: 'q',
3349
- Ř̩: 'R',
3350
- ř̩: 'r',
3351
- Ṧ: 'S',
3352
- ṧ: 's',
3353
- V̌: 'V',
3354
- v̌: 'v',
3355
- W̌: 'W',
3356
- w̌: 'w',
3357
- X̌: 'X',
3358
- x̌: 'x',
3359
- Y̌: 'Y',
3360
- y̌: 'y',
3361
- A̧: 'A',
3362
- a̧: 'a',
3363
- B̧: 'B',
3364
- b̧: 'b',
3365
- Ḑ: 'D',
3366
- ḑ: 'd',
3367
- Ȩ: 'E',
3368
- ȩ: 'e',
3369
- Ɛ̧: 'E',
3370
- ɛ̧: 'e',
3371
- Ḩ: 'H',
3372
- ḩ: 'h',
3373
- I̧: 'I',
3374
- i̧: 'i',
3375
- Ɨ̧: 'I',
3376
- ɨ̧: 'i',
3377
- M̧: 'M',
3378
- m̧: 'm',
3379
- O̧: 'O',
3380
- o̧: 'o',
3381
- Q̧: 'Q',
3382
- q̧: 'q',
3383
- U̧: 'U',
3384
- u̧: 'u',
3385
- X̧: 'X',
3386
- x̧: 'x',
3387
- Z̧: 'Z',
3388
- z̧: 'z'
3389
- };
3390
- const chars = Object.keys(characterMap).join('|');
3391
- const allAccents = new RegExp(chars, 'g');
3392
- function removeAccents(str) {
3393
- return str.replace(allAccents, match => {
3394
- return characterMap[match];
3395
- });
3396
- }
3397
-
3398
- /**
3399
- * @name match-sorter
3400
- * @license MIT license.
3401
- * @copyright (c) 2099 Kent C. Dodds
3402
- * @author Kent C. Dodds <me@kentcdodds.com> (https://kentcdodds.com)
3403
- */
3404
- const rankings = {
3405
- CASE_SENSITIVE_EQUAL: 7,
3406
- EQUAL: 6,
3407
- STARTS_WITH: 5,
3408
- WORD_STARTS_WITH: 4,
3409
- CONTAINS: 3,
3410
- ACRONYM: 2,
3411
- MATCHES: 1,
3412
- NO_MATCH: 0
3413
- };
3414
- /**
3415
- * Gets the highest ranking for value for the given item based on its values for the given keys
3416
- * @param {*} item - the item to rank
3417
- * @param {Array} keys - the keys to get values from the item for the ranking
3418
- * @param {String} value - the value to rank against
3419
- * @param {Object} options - options to control the ranking
3420
- * @return {{rank: Number, accessorIndex: Number, accessorThreshold: Number}} - the highest ranking
3421
- */
3422
- function rankItem(item, value, options) {
3423
- var _options$threshold;
3424
- options = options || {};
3425
- options.threshold = (_options$threshold = options.threshold) != null ? _options$threshold : rankings.MATCHES;
3426
- if (!options.accessors) {
3427
- // if keys is not specified, then we assume the item given is ready to be matched
3428
- const rank = getMatchRanking(item, value, options);
3429
- return {
3430
- // ends up being duplicate of 'item' in matches but consistent
3431
- rankedValue: item,
3432
- rank,
3433
- accessorIndex: -1,
3434
- accessorThreshold: options.threshold,
3435
- passed: rank >= options.threshold
3436
- };
3437
- }
3438
- const valuesToRank = getAllValuesToRank(item, options.accessors);
3439
- const rankingInfo = {
3440
- rankedValue: item,
3441
- rank: rankings.NO_MATCH,
3442
- accessorIndex: -1,
3443
- accessorThreshold: options.threshold,
3444
- passed: false
3445
- };
3446
- for (let i = 0; i < valuesToRank.length; i++) {
3447
- const rankValue = valuesToRank[i];
3448
- let newRank = getMatchRanking(rankValue.itemValue, value, options);
3449
- const {
3450
- minRanking,
3451
- maxRanking,
3452
- threshold = options.threshold
3453
- } = rankValue.attributes;
3454
- if (newRank < minRanking && newRank >= rankings.MATCHES) {
3455
- newRank = minRanking;
3456
- } else if (newRank > maxRanking) {
3457
- newRank = maxRanking;
3458
- }
3459
- newRank = Math.min(newRank, maxRanking);
3460
- if (newRank >= threshold && newRank > rankingInfo.rank) {
3461
- rankingInfo.rank = newRank;
3462
- rankingInfo.passed = true;
3463
- rankingInfo.accessorIndex = i;
3464
- rankingInfo.accessorThreshold = threshold;
3465
- rankingInfo.rankedValue = rankValue.itemValue;
3466
- }
3467
- }
3468
- return rankingInfo;
3469
- }
3470
-
3471
- /**
3472
- * Gives a rankings score based on how well the two strings match.
3473
- * @param {String} testString - the string to test against
3474
- * @param {String} stringToRank - the string to rank
3475
- * @param {Object} options - options for the match (like keepDiacritics for comparison)
3476
- * @returns {Number} the ranking for how well stringToRank matches testString
3477
- */
3478
- function getMatchRanking(testString, stringToRank, options) {
3479
- testString = prepareValueForComparison(testString, options);
3480
- stringToRank = prepareValueForComparison(stringToRank, options);
3481
-
3482
- // too long
3483
- if (stringToRank.length > testString.length) {
3484
- return rankings.NO_MATCH;
3485
- }
3486
-
3487
- // case sensitive equals
3488
- if (testString === stringToRank) {
3489
- return rankings.CASE_SENSITIVE_EQUAL;
3490
- }
3491
-
3492
- // Lower casing before further comparison
3493
- testString = testString.toLowerCase();
3494
- stringToRank = stringToRank.toLowerCase();
3495
-
3496
- // case insensitive equals
3497
- if (testString === stringToRank) {
3498
- return rankings.EQUAL;
3499
- }
3500
-
3501
- // starts with
3502
- if (testString.startsWith(stringToRank)) {
3503
- return rankings.STARTS_WITH;
3504
- }
3505
-
3506
- // word starts with
3507
- if (testString.includes(` ${stringToRank}`)) {
3508
- return rankings.WORD_STARTS_WITH;
3509
- }
3510
-
3511
- // contains
3512
- if (testString.includes(stringToRank)) {
3513
- return rankings.CONTAINS;
3514
- } else if (stringToRank.length === 1) {
3515
- // If the only character in the given stringToRank
3516
- // isn't even contained in the testString, then
3517
- // it's definitely not a match.
3518
- return rankings.NO_MATCH;
3519
- }
3520
-
3521
- // acronym
3522
- if (getAcronym(testString).includes(stringToRank)) {
3523
- return rankings.ACRONYM;
3524
- }
3525
-
3526
- // will return a number between rankings.MATCHES and
3527
- // rankings.MATCHES + 1 depending on how close of a match it is.
3528
- return getClosenessRanking(testString, stringToRank);
3529
- }
3530
-
3531
- /**
3532
- * Generates an acronym for a string.
3533
- *
3534
- * @param {String} string the string for which to produce the acronym
3535
- * @returns {String} the acronym
3536
- */
3537
- function getAcronym(string) {
3538
- let acronym = '';
3539
- const wordsInString = string.split(' ');
3540
- wordsInString.forEach(wordInString => {
3541
- const splitByHyphenWords = wordInString.split('-');
3542
- splitByHyphenWords.forEach(splitByHyphenWord => {
3543
- acronym += splitByHyphenWord.substr(0, 1);
3544
- });
3545
- });
3546
- return acronym;
3547
- }
3548
-
3549
- /**
3550
- * Returns a score based on how spread apart the
3551
- * characters from the stringToRank are within the testString.
3552
- * A number close to rankings.MATCHES represents a loose match. A number close
3553
- * to rankings.MATCHES + 1 represents a tighter match.
3554
- * @param {String} testString - the string to test against
3555
- * @param {String} stringToRank - the string to rank
3556
- * @returns {Number} the number between rankings.MATCHES and
3557
- * rankings.MATCHES + 1 for how well stringToRank matches testString
3558
- */
3559
- function getClosenessRanking(testString, stringToRank) {
3560
- let matchingInOrderCharCount = 0;
3561
- let charNumber = 0;
3562
- function findMatchingCharacter(matchChar, string, index) {
3563
- for (let j = index, J = string.length; j < J; j++) {
3564
- const stringChar = string[j];
3565
- if (stringChar === matchChar) {
3566
- matchingInOrderCharCount += 1;
3567
- return j + 1;
3568
- }
3569
- }
3570
- return -1;
3571
- }
3572
- function getRanking(spread) {
3573
- const spreadPercentage = 1 / spread;
3574
- const inOrderPercentage = matchingInOrderCharCount / stringToRank.length;
3575
- const ranking = rankings.MATCHES + inOrderPercentage * spreadPercentage;
3576
- return ranking;
3577
- }
3578
- const firstIndex = findMatchingCharacter(stringToRank[0], testString, 0);
3579
- if (firstIndex < 0) {
3580
- return rankings.NO_MATCH;
3581
- }
3582
- charNumber = firstIndex;
3583
- for (let i = 1, I = stringToRank.length; i < I; i++) {
3584
- const matchChar = stringToRank[i];
3585
- charNumber = findMatchingCharacter(matchChar, testString, charNumber);
3586
- const found = charNumber > -1;
3587
- if (!found) {
3588
- return rankings.NO_MATCH;
3589
- }
3590
- }
3591
- const spread = charNumber - firstIndex;
3592
- return getRanking(spread);
3593
- }
3594
-
3595
- /**
3596
- * Prepares value for comparison by stringifying it, removing diacritics (if specified)
3597
- * @param {String} value - the value to clean
3598
- * @param {Object} options - {keepDiacritics: whether to remove diacritics}
3599
- * @return {String} the prepared value
3600
- */
3601
- function prepareValueForComparison(value, _ref) {
3602
- let {
3603
- keepDiacritics
3604
- } = _ref;
3605
- // value might not actually be a string at this point (we don't get to choose)
3606
- // so part of preparing the value for comparison is ensure that it is a string
3607
- value = `${value}`; // toString
3608
- if (!keepDiacritics) {
3609
- value = removeAccents(value);
3610
- }
3611
- return value;
3612
- }
3613
-
3614
- /**
3615
- * Gets value for key in item at arbitrarily nested keypath
3616
- * @param {Object} item - the item
3617
- * @param {Object|Function} key - the potentially nested keypath or property callback
3618
- * @return {Array} - an array containing the value(s) at the nested keypath
3619
- */
3620
- function getItemValues(item, accessor) {
3621
- let accessorFn = accessor;
3622
- if (typeof accessor === 'object') {
3623
- accessorFn = accessor.accessor;
3624
- }
3625
- const value = accessorFn(item);
3626
-
3627
- // because `value` can also be undefined
3628
- if (value == null) {
3629
- return [];
3630
- }
3631
- if (Array.isArray(value)) {
3632
- return value;
3633
- }
3634
- return [String(value)];
3635
- }
3636
-
3637
- /**
3638
- * Gets all the values for the given keys in the given item and returns an array of those values
3639
- * @param item - the item from which the values will be retrieved
3640
- * @param keys - the keys to use to retrieve the values
3641
- * @return objects with {itemValue, attributes}
3642
- */
3643
- function getAllValuesToRank(item, accessors) {
3644
- const allValues = [];
3645
- for (let j = 0, J = accessors.length; j < J; j++) {
3646
- const accessor = accessors[j];
3647
- const attributes = getAccessorAttributes(accessor);
3648
- const itemValues = getItemValues(item, accessor);
3649
- for (let i = 0, I = itemValues.length; i < I; i++) {
3650
- allValues.push({
3651
- itemValue: itemValues[i],
3652
- attributes
3653
- });
3654
- }
3655
- }
3656
- return allValues;
3657
- }
3658
- const defaultKeyAttributes = {
3659
- maxRanking: Infinity,
3660
- minRanking: -Infinity
3661
- };
3662
- /**
3663
- * Gets all the attributes for the given accessor
3664
- * @param accessor - the accessor from which the attributes will be retrieved
3665
- * @return object containing the accessor's attributes
3666
- */
3667
- function getAccessorAttributes(accessor) {
3668
- if (typeof accessor === 'function') {
3669
- return defaultKeyAttributes;
3670
- }
3671
- return {
3672
- ...defaultKeyAttributes,
3673
- ...accessor
3674
- };
3675
- }
3676
-
3677
- /* istanbul ignore file */
3678
- // eslint-disable-next-line no-shadow
3679
- var QueryState;
3680
- (function (QueryState) {
3681
- QueryState[QueryState["Fetching"] = 0] = "Fetching";
3682
- QueryState[QueryState["Fresh"] = 1] = "Fresh";
3683
- QueryState[QueryState["Stale"] = 2] = "Stale";
3684
- QueryState[QueryState["Inactive"] = 3] = "Inactive";
3685
- QueryState[QueryState["Paused"] = 4] = "Paused";
3686
- })(QueryState || (QueryState = {}));
3687
- function getQueryState(query) {
3688
- if (query.state.fetchStatus === 'fetching') {
3689
- return QueryState.Fetching;
3690
- }
3691
- if (query.state.fetchStatus === 'paused') {
3692
- return QueryState.Paused;
3693
- }
3694
- if (!query.getObserversCount()) {
3695
- return QueryState.Inactive;
3696
- }
3697
- if (query.isStale()) {
3698
- return QueryState.Stale;
3699
- }
3700
- return QueryState.Fresh;
3701
- }
3702
- function getQueryStateLabel(query) {
3703
- const queryState = getQueryState(query);
3704
- if (queryState === QueryState.Fetching) {
3705
- return 'fetching';
3706
- }
3707
- if (queryState === QueryState.Paused) {
3708
- return 'paused';
3709
- }
3710
- if (queryState === QueryState.Stale) {
3711
- return 'stale';
3712
- }
3713
- if (queryState === QueryState.Inactive) {
3714
- return 'inactive';
3715
- }
3716
- return 'fresh';
3717
- }
3718
- function getQueryStatusFg(query) {
3719
- const queryState = getQueryState(query);
3720
- if (queryState === QueryState.Stale) {
3721
- return 0x000000;
3722
- }
3723
- return 0xffffff;
3724
- }
3725
- function getQueryStatusBg(query) {
3726
- const queryState = getQueryState(query);
3727
- if (queryState === QueryState.Fetching) {
3728
- return 0x006bff;
3729
- }
3730
- if (queryState === QueryState.Paused) {
3731
- return 0x8c49eb;
3732
- }
3733
- if (queryState === QueryState.Stale) {
3734
- return 0xffb200;
3735
- }
3736
- if (queryState === QueryState.Inactive) {
3737
- return 0x3f4e60;
3738
- }
3739
- return 0x008327;
3740
- }
3741
- const queryHashSort = (a, b) => a.queryHash.localeCompare(b.queryHash);
3742
- const dateSort = (a, b) => a.state.dataUpdatedAt < b.state.dataUpdatedAt ? 1 : -1;
3743
- const statusAndDateSort = (a, b) => {
3744
- if (getQueryState(a) === getQueryState(b)) {
3745
- return dateSort(a, b);
3746
- }
3747
- return getQueryState(a) > getQueryState(b) ? 1 : -1;
3748
- };
3749
- const sortFns = {
3750
- 'Status > Last Updated': statusAndDateSort,
3751
- 'Query Hash': queryHashSort,
3752
- 'Last Updated': dateSort
3753
- };
3754
-
3755
- /* istanbul ignore file */
3756
- const pluginId = 'vue-query';
3757
- const pluginName = 'Vue Query';
3758
- function setupDevtools(app, queryClient) {
3759
- setupDevtoolsPlugin({
3760
- id: pluginId,
3761
- label: pluginName,
3762
- packageName: 'vue-query',
3763
- homepage: 'https://tanstack.com/query/v4',
3764
- logo: 'https://vue-query.vercel.app/vue-query.svg',
3765
- app,
3766
- settings: {
3767
- baseSort: {
3768
- type: 'choice',
3769
- component: 'button-group',
3770
- label: 'Sort Cache Entries',
3771
- options: [{
3772
- label: 'ASC',
3773
- value: 1
3774
- }, {
3775
- label: 'DESC',
3776
- value: -1
3777
- }],
3778
- defaultValue: 1
3779
- },
3780
- sortFn: {
3781
- type: 'choice',
3782
- label: 'Sort Function',
3783
- options: Object.keys(sortFns).map(key => ({
3784
- label: key,
3785
- value: key
3786
- })),
3787
- defaultValue: Object.keys(sortFns)[0]
3788
- }
3789
- }
3790
- }, api => {
3791
- const queryCache = queryClient.getQueryCache();
3792
- api.addInspector({
3793
- id: pluginId,
3794
- label: pluginName,
3795
- icon: 'api',
3796
- nodeActions: [{
3797
- icon: 'cloud_download',
3798
- tooltip: 'Refetch',
3799
- action: queryHash => {
3800
- queryCache.get(queryHash)?.fetch();
3801
- }
3802
- }, {
3803
- icon: 'alarm',
3804
- tooltip: 'Invalidate',
3805
- action: queryHash => {
3806
- const query = queryCache.get(queryHash);
3807
- queryClient.invalidateQueries(query);
3808
- }
3809
- }, {
3810
- icon: 'settings_backup_restore',
3811
- tooltip: 'Reset',
3812
- action: queryHash => {
3813
- queryCache.get(queryHash)?.reset();
3814
- }
3815
- }, {
3816
- icon: 'delete',
3817
- tooltip: 'Remove',
3818
- action: queryHash => {
3819
- const query = queryCache.get(queryHash);
3820
- queryCache.remove(query);
3821
- }
3822
- }]
3823
- });
3824
- api.addTimelineLayer({
3825
- id: pluginId,
3826
- label: pluginName,
3827
- color: 0xffd94c
3828
- });
3829
- queryCache.subscribe(event => {
3830
- api.sendInspectorTree(pluginId);
3831
- api.sendInspectorState(pluginId);
3832
- if (
3833
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
3834
- event && ['queryAdded', 'queryRemoved', 'queryUpdated'].includes(event.type)) {
3835
- api.addTimelineEvent({
3836
- layerId: pluginId,
3837
- event: {
3838
- title: event.type,
3839
- subtitle: event.query.queryHash,
3840
- time: api.now(),
3841
- data: {
3842
- queryHash: event.query.queryHash,
3843
- ...event
3844
- }
3845
- }
3846
- });
3847
- }
3848
- });
3849
- api.on.getInspectorTree(payload => {
3850
- if (payload.inspectorId === pluginId) {
3851
- const queries = queryCache.getAll();
3852
- const settings = api.getSettings();
3853
- const filtered = payload.filter ? queries.filter(item => rankItem(item.queryHash, payload.filter).passed) : [...queries];
3854
- const sorted = filtered.sort((a, b) => sortFns[settings.sortFn](a, b) * settings.baseSort);
3855
- const nodes = sorted.map(query => {
3856
- const stateLabel = getQueryStateLabel(query);
3857
- return {
3858
- id: query.queryHash,
3859
- label: query.queryHash,
3860
- tags: [{
3861
- label: `${stateLabel} [${query.getObserversCount()}]`,
3862
- textColor: getQueryStatusFg(query),
3863
- backgroundColor: getQueryStatusBg(query)
3864
- }]
3865
- };
3866
- });
3867
- payload.rootNodes = nodes;
3868
- }
3869
- });
3870
- api.on.getInspectorState(payload => {
3871
- if (payload.inspectorId === pluginId) {
3872
- const query = queryCache.get(payload.nodeId);
3873
- if (!query) {
3874
- return;
3875
- }
3876
- payload.state = {
3877
- ' Query Details': [{
3878
- key: 'Query key',
3879
- value: query.queryHash
3880
- }, {
3881
- key: 'Query status',
3882
- value: getQueryStateLabel(query)
3883
- }, {
3884
- key: 'Observers',
3885
- value: query.getObserversCount()
3886
- }, {
3887
- key: 'Last Updated',
3888
- value: new Date(query.state.dataUpdatedAt).toLocaleTimeString()
3889
- }],
3890
- 'Data Explorer': [{
3891
- key: 'Data',
3892
- value: query.state.data
3893
- }],
3894
- 'Query Explorer': [{
3895
- key: 'Query',
3896
- value: query
3897
- }]
3898
- };
3899
- }
3900
- });
3901
- });
3902
- }
3903
-
3904
- const VueQueryPlugin = {
3905
- install: (app, options = {}) => {
3906
- const clientKey = getClientKey(options.queryClientKey);
3907
- let client;
3908
- if ('queryClient' in options && options.queryClient) {
3909
- client = options.queryClient;
3910
- } else {
3911
- const clientConfig = 'queryClientConfig' in options ? options.queryClientConfig : undefined;
3912
- client = new QueryClient(clientConfig);
3913
- }
3914
- if (!isServer) {
3915
- client.mount();
3916
- }
3917
- let persisterUnmount = () => {
3918
- // noop
3919
- };
3920
- if (options.clientPersister) {
3921
- client.isRestoring.value = true;
3922
- const [unmount, promise] = options.clientPersister(client);
3923
- persisterUnmount = unmount;
3924
- promise.then(() => {
3925
- client.isRestoring.value = false;
3926
- });
3927
- }
3928
- const cleanup = () => {
3929
- client.unmount();
3930
- persisterUnmount();
3931
- };
3932
- if (app.onUnmount) {
3933
- app.onUnmount(cleanup);
3934
- } else {
3935
- const originalUnmount = app.unmount;
3936
- app.unmount = function vueQueryUnmount() {
3937
- cleanup();
3938
- originalUnmount();
3939
- };
3940
- }
3941
-
3942
- /* istanbul ignore next */
3943
- if (vueDemi.isVue2) {
3944
- app.mixin({
3945
- beforeCreate() {
3946
- // HACK: taken from provide(): https://github.com/vuejs/composition-api/blob/master/src/apis/inject.ts#L30
3947
- if (!this._provided) {
3948
- const provideCache = {};
3949
- Object.defineProperty(this, '_provided', {
3950
- get: () => provideCache,
3951
- set: v => Object.assign(provideCache, v)
3952
- });
3953
- }
3954
- this._provided[clientKey] = client;
3955
- {
3956
- if (this === this.$root) {
3957
- setupDevtools(this, client);
3958
- }
3959
- }
3960
- }
3961
- });
3962
- } else {
3963
- app.provide(clientKey, client);
3964
- {
3965
- setupDevtools(app, client);
3966
- }
3967
- }
3968
- }
3969
- };
3970
-
3971
- function useBaseQuery(Observer, options, queryClient) {
3972
- const client = queryClient || useQueryClient();
3973
- const defaultedOptions = vueDemi.computed(() => {
3974
- const defaulted = client.defaultQueryOptions(cloneDeepUnref(options));
3975
- defaulted._optimisticResults = client.isRestoring.value ? 'isRestoring' : 'optimistic';
3976
- return defaulted;
3977
- });
3978
- const observer = new Observer(client, defaultedOptions.value);
3979
- const state = vueDemi.reactive(observer.getCurrentResult());
3980
- const unsubscribe = vueDemi.ref(() => {
3981
- // noop
3982
- });
3983
- vueDemi.watch(client.isRestoring, isRestoring => {
3984
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
3985
- if (!isRestoring) {
3986
- unsubscribe.value();
3987
- unsubscribe.value = observer.subscribe(result => {
3988
- updateState(state, result);
3989
- });
3990
- }
3991
- }, {
3992
- immediate: true
3993
- });
3994
- vueDemi.watch(defaultedOptions, () => {
3995
- observer.setOptions(defaultedOptions.value);
3996
- updateState(state, observer.getCurrentResult());
3997
- }, {
3998
- deep: true
3999
- });
4000
- vueDemi.onScopeDispose(() => {
4001
- unsubscribe.value();
4002
- });
4003
- const suspense = () => {
4004
- return new Promise(resolve => {
4005
- let stopWatch = () => {
4006
- //noop
4007
- };
4008
- const run = () => {
4009
- if (defaultedOptions.value.enabled !== false) {
4010
- const optimisticResult = observer.getOptimisticResult(defaultedOptions.value);
4011
- if (optimisticResult.isStale) {
4012
- stopWatch();
4013
- resolve(observer.fetchOptimistic(defaultedOptions.value));
4014
- } else {
4015
- stopWatch();
4016
- resolve(optimisticResult);
4017
- }
4018
- }
4019
- };
4020
- run();
4021
- stopWatch = vueDemi.watch(defaultedOptions, run, {
4022
- deep: true
4023
- });
4024
- });
4025
- };
4026
- return {
4027
- ...vueDemi.toRefs(vueDemi.readonly(state)),
4028
- suspense
4029
- };
4030
- }
4031
-
4032
- function useQuery(options, queryClient) {
4033
- const result = useBaseQuery(QueryObserver, options, queryClient);
4034
- return {
4035
- ...result,
4036
- refetch: result.refetch.value
4037
- };
4038
- }
4039
-
4040
- /* eslint-disable @typescript-eslint/no-explicit-any */
4041
- function useQueries({
4042
- queries
4043
- }, queryClient) {
4044
- const client = queryClient || useQueryClient();
4045
- const defaultedQueries = vueDemi.computed(() => cloneDeepUnref(queries).map(options => {
4046
- const defaulted = client.defaultQueryOptions(options);
4047
- defaulted._optimisticResults = client.isRestoring.value ? 'isRestoring' : 'optimistic';
4048
- return defaulted;
4049
- }));
4050
- const observer = new QueriesObserver(client, defaultedQueries.value);
4051
- const state = vueDemi.ref(observer.getCurrentResult());
4052
- const unsubscribe = vueDemi.ref(() => {
4053
- // noop
4054
- });
4055
- vueDemi.watch(client.isRestoring, isRestoring => {
4056
- if (!isRestoring) {
4057
- unsubscribe.value();
4058
- unsubscribe.value = observer.subscribe(result => {
4059
- state.value.splice(0, result.length, ...result);
4060
- });
4061
- // Subscription would not fire for persisted results
4062
- state.value.splice(0, state.value.length, ...observer.getOptimisticResult(defaultedQueries.value));
4063
- }
4064
- }, {
4065
- immediate: true
4066
- });
4067
- vueDemi.watch(defaultedQueries, () => {
4068
- observer.setQueries(defaultedQueries.value);
4069
- state.value.splice(0, state.value.length, ...observer.getCurrentResult());
4070
- }, {
4071
- deep: true
4072
- });
4073
- vueDemi.onScopeDispose(() => {
4074
- unsubscribe.value();
4075
- });
4076
- return vueDemi.readonly(state);
4077
- }
4078
-
4079
- function useInfiniteQuery(options, queryClient) {
4080
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
4081
- const result = useBaseQuery(
4082
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
4083
- InfiniteQueryObserver, options, queryClient);
4084
- return {
4085
- ...result,
4086
- fetchNextPage: result.fetchNextPage.value,
4087
- fetchPreviousPage: result.fetchPreviousPage.value,
4088
- refetch: result.refetch.value
4089
- };
4090
- }
4091
-
4092
- function useMutation(mutationOptions, queryClient) {
4093
- const client = queryClient || useQueryClient();
4094
- const options = vueDemi.computed(() => {
4095
- return client.defaultMutationOptions(cloneDeepUnref(mutationOptions));
4096
- });
4097
- const observer = new MutationObserver(client, options.value);
4098
- const state = vueDemi.reactive(observer.getCurrentResult());
4099
- const unsubscribe = observer.subscribe(result => {
4100
- updateState(state, result);
4101
- });
4102
- const mutate = (variables, mutateOptions) => {
4103
- observer.mutate(variables, mutateOptions).catch(() => {
4104
- // This is intentional
4105
- });
4106
- };
4107
- vueDemi.watch(options, () => {
4108
- observer.setOptions(options.value);
4109
- }, {
4110
- deep: true
4111
- });
4112
- vueDemi.onScopeDispose(() => {
4113
- unsubscribe();
4114
- });
4115
- const resultRefs = vueDemi.toRefs(vueDemi.readonly(state));
4116
- return {
4117
- ...resultRefs,
4118
- mutate,
4119
- mutateAsync: state.mutate,
4120
- reset: state.reset
4121
- };
4122
- }
4123
-
4124
- function useIsFetching(fetchingFilters = {}, queryClient) {
4125
- const filters = vueDemi.computed(() => cloneDeepUnref(fetchingFilters));
4126
- const client = queryClient || useQueryClient();
4127
- const isFetching = vueDemi.ref(client.isFetching(filters));
4128
- const unsubscribe = client.getQueryCache().subscribe(() => {
4129
- isFetching.value = client.isFetching(filters);
4130
- });
4131
- vueDemi.watch(filters, () => {
4132
- isFetching.value = client.isFetching(filters);
4133
- }, {
4134
- deep: true
4135
- });
4136
- vueDemi.onScopeDispose(() => {
4137
- unsubscribe();
4138
- });
4139
- return isFetching;
4140
- }
4141
-
4142
- function useIsMutating(mutationFilters = {}, queryClient) {
4143
- const filters = vueDemi.computed(() => cloneDeepUnref(mutationFilters));
4144
- const client = queryClient || useQueryClient();
4145
- const isMutating = vueDemi.ref(client.isMutating(filters));
4146
- const unsubscribe = client.getMutationCache().subscribe(() => {
4147
- isMutating.value = client.isMutating(filters);
4148
- });
4149
- vueDemi.watch(filters, () => {
4150
- isMutating.value = client.isMutating(filters);
4151
- }, {
4152
- deep: true
4153
- });
4154
- vueDemi.onScopeDispose(() => {
4155
- unsubscribe();
4156
- });
4157
- return isMutating;
4158
- }
4159
-
4160
- exports.CancelledError = CancelledError;
4161
- exports.InfiniteQueryObserver = InfiniteQueryObserver;
4162
- exports.MutationCache = MutationCache;
4163
- exports.MutationObserver = MutationObserver;
4164
- exports.QueriesObserver = QueriesObserver;
4165
- exports.QueryCache = QueryCache;
4166
- exports.QueryClient = QueryClient;
4167
- exports.QueryObserver = QueryObserver;
4168
- exports.VUE_QUERY_CLIENT = VUE_QUERY_CLIENT;
4169
- exports.VueQueryPlugin = VueQueryPlugin;
4170
- exports.defaultShouldDehydrateMutation = defaultShouldDehydrateMutation;
4171
- exports.defaultShouldDehydrateQuery = defaultShouldDehydrateQuery;
4172
- exports.dehydrate = dehydrate;
4173
- exports.focusManager = focusManager;
4174
- exports.hashKey = hashKey;
4175
- exports.hydrate = hydrate;
4176
- exports.isCancelledError = isCancelledError;
4177
- exports.isServer = isServer;
4178
- exports.keepPreviousData = keepPreviousData;
4179
- exports.matchQuery = matchQuery;
4180
- exports.notifyManager = notifyManager;
4181
- exports.onlineManager = onlineManager;
4182
- exports.replaceEqualDeep = replaceEqualDeep;
4183
- exports.useInfiniteQuery = useInfiniteQuery;
4184
- exports.useIsFetching = useIsFetching;
4185
- exports.useIsMutating = useIsMutating;
4186
- exports.useMutation = useMutation;
4187
- exports.useQueries = useQueries;
4188
- exports.useQuery = useQuery;
4189
- exports.useQueryClient = useQueryClient;
4190
-
4191
- }));
4192
- //# sourceMappingURL=index.development.js.map