@tanstack/query-core 4.1.3 → 4.3.0-beta.0

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