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