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