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