@legendapp/state 0.21.10 → 0.21.11

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.
@@ -0,0 +1,1630 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var state = require('@legendapp/state');
6
+ var react = require('@legendapp/state/react');
7
+ var React = require('react');
8
+
9
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
10
+
11
+ function _interopNamespace(e) {
12
+ if (e && e.__esModule) return e;
13
+ var n = Object.create(null);
14
+ if (e) {
15
+ Object.keys(e).forEach(function (k) {
16
+ if (k !== 'default') {
17
+ var d = Object.getOwnPropertyDescriptor(e, k);
18
+ Object.defineProperty(n, k, d.get ? d : {
19
+ enumerable: true,
20
+ get: function () { return e[k]; }
21
+ });
22
+ }
23
+ });
24
+ }
25
+ n["default"] = e;
26
+ return Object.freeze(n);
27
+ }
28
+
29
+ var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
30
+ var React__namespace = /*#__PURE__*/_interopNamespace(React);
31
+
32
+ class Subscribable {
33
+ constructor() {
34
+ this.listeners = [];
35
+ this.subscribe = this.subscribe.bind(this);
36
+ }
37
+
38
+ subscribe(listener) {
39
+ this.listeners.push(listener);
40
+ this.onSubscribe();
41
+ return () => {
42
+ this.listeners = this.listeners.filter(x => x !== listener);
43
+ this.onUnsubscribe();
44
+ };
45
+ }
46
+
47
+ hasListeners() {
48
+ return this.listeners.length > 0;
49
+ }
50
+
51
+ onSubscribe() {// Do nothing
52
+ }
53
+
54
+ onUnsubscribe() {// Do nothing
55
+ }
56
+
57
+ }
58
+
59
+ // TYPES
60
+ // UTILS
61
+ const isServer = typeof window === 'undefined';
62
+ function noop$1() {
63
+ return undefined;
64
+ }
65
+ function isValidTimeout(value) {
66
+ return typeof value === 'number' && value >= 0 && value !== Infinity;
67
+ }
68
+ function timeUntilStale(updatedAt, staleTime) {
69
+ return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0);
70
+ }
71
+ function parseMutationArgs(arg1, arg2, arg3) {
72
+ if (isQueryKey(arg1)) {
73
+ if (typeof arg2 === 'function') {
74
+ return { ...arg3,
75
+ mutationKey: arg1,
76
+ mutationFn: arg2
77
+ };
78
+ }
79
+
80
+ return { ...arg2,
81
+ mutationKey: arg1
82
+ };
83
+ }
84
+
85
+ if (typeof arg1 === 'function') {
86
+ return { ...arg2,
87
+ mutationFn: arg1
88
+ };
89
+ }
90
+
91
+ return { ...arg1
92
+ };
93
+ }
94
+ /**
95
+ * This function returns `a` if `b` is deeply equal.
96
+ * If not, it will replace any deeply equal children of `b` with those of `a`.
97
+ * This can be used for structural sharing between JSON values for example.
98
+ */
99
+
100
+ function replaceEqualDeep(a, b) {
101
+ if (a === b) {
102
+ return a;
103
+ }
104
+
105
+ const array = isPlainArray(a) && isPlainArray(b);
106
+
107
+ if (array || isPlainObject(a) && isPlainObject(b)) {
108
+ const aSize = array ? a.length : Object.keys(a).length;
109
+ const bItems = array ? b : Object.keys(b);
110
+ const bSize = bItems.length;
111
+ const copy = array ? [] : {};
112
+ let equalItems = 0;
113
+
114
+ for (let i = 0; i < bSize; i++) {
115
+ const key = array ? i : bItems[i];
116
+ copy[key] = replaceEqualDeep(a[key], b[key]);
117
+
118
+ if (copy[key] === a[key]) {
119
+ equalItems++;
120
+ }
121
+ }
122
+
123
+ return aSize === bSize && equalItems === aSize ? a : copy;
124
+ }
125
+
126
+ return b;
127
+ }
128
+ /**
129
+ * Shallow compare objects. Only works with objects that always have the same properties.
130
+ */
131
+
132
+ function shallowEqualObjects(a, b) {
133
+ if (a && !b || b && !a) {
134
+ return false;
135
+ }
136
+
137
+ for (const key in a) {
138
+ if (a[key] !== b[key]) {
139
+ return false;
140
+ }
141
+ }
142
+
143
+ return true;
144
+ }
145
+ function isPlainArray(value) {
146
+ return Array.isArray(value) && value.length === Object.keys(value).length;
147
+ } // Copied from: https://github.com/jonschlinkert/is-plain-object
148
+
149
+ function isPlainObject(o) {
150
+ if (!hasObjectPrototype(o)) {
151
+ return false;
152
+ } // If has modified constructor
153
+
154
+
155
+ const ctor = o.constructor;
156
+
157
+ if (typeof ctor === 'undefined') {
158
+ return true;
159
+ } // If has modified prototype
160
+
161
+
162
+ const prot = ctor.prototype;
163
+
164
+ if (!hasObjectPrototype(prot)) {
165
+ return false;
166
+ } // If constructor does not have an Object-specific method
167
+
168
+
169
+ if (!prot.hasOwnProperty('isPrototypeOf')) {
170
+ return false;
171
+ } // Most likely a plain Object
172
+
173
+
174
+ return true;
175
+ }
176
+
177
+ function hasObjectPrototype(o) {
178
+ return Object.prototype.toString.call(o) === '[object Object]';
179
+ }
180
+
181
+ function isQueryKey(value) {
182
+ return Array.isArray(value);
183
+ }
184
+ function sleep(timeout) {
185
+ return new Promise(resolve => {
186
+ setTimeout(resolve, timeout);
187
+ });
188
+ }
189
+ /**
190
+ * Schedules a microtask.
191
+ * This can be useful to schedule state updates after rendering.
192
+ */
193
+
194
+ function scheduleMicrotask(callback) {
195
+ sleep(0).then(callback);
196
+ }
197
+ function replaceData(prevData, data, options) {
198
+ // Use prev data if an isDataEqual function is defined and returns `true`
199
+ if (options.isDataEqual != null && options.isDataEqual(prevData, data)) {
200
+ return prevData;
201
+ } else if (typeof options.structuralSharing === 'function') {
202
+ return options.structuralSharing(prevData, data);
203
+ } else if (options.structuralSharing !== false) {
204
+ // Structurally share data between prev and new data if needed
205
+ return replaceEqualDeep(prevData, data);
206
+ }
207
+
208
+ return data;
209
+ }
210
+
211
+ class FocusManager extends Subscribable {
212
+ constructor() {
213
+ super();
214
+
215
+ this.setup = onFocus => {
216
+ // addEventListener does not exist in React Native, but window does
217
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
218
+ if (!isServer && window.addEventListener) {
219
+ const listener = () => onFocus(); // Listen to visibillitychange and focus
220
+
221
+
222
+ window.addEventListener('visibilitychange', listener, false);
223
+ window.addEventListener('focus', listener, false);
224
+ return () => {
225
+ // Be sure to unsubscribe if a new handler is set
226
+ window.removeEventListener('visibilitychange', listener);
227
+ window.removeEventListener('focus', listener);
228
+ };
229
+ }
230
+ };
231
+ }
232
+
233
+ onSubscribe() {
234
+ if (!this.cleanup) {
235
+ this.setEventListener(this.setup);
236
+ }
237
+ }
238
+
239
+ onUnsubscribe() {
240
+ if (!this.hasListeners()) {
241
+ var _this$cleanup;
242
+
243
+ (_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
244
+ this.cleanup = undefined;
245
+ }
246
+ }
247
+
248
+ setEventListener(setup) {
249
+ var _this$cleanup2;
250
+
251
+ this.setup = setup;
252
+ (_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
253
+ this.cleanup = setup(focused => {
254
+ if (typeof focused === 'boolean') {
255
+ this.setFocused(focused);
256
+ } else {
257
+ this.onFocus();
258
+ }
259
+ });
260
+ }
261
+
262
+ setFocused(focused) {
263
+ this.focused = focused;
264
+
265
+ if (focused) {
266
+ this.onFocus();
267
+ }
268
+ }
269
+
270
+ onFocus() {
271
+ this.listeners.forEach(listener => {
272
+ listener();
273
+ });
274
+ }
275
+
276
+ isFocused() {
277
+ if (typeof this.focused === 'boolean') {
278
+ return this.focused;
279
+ } // document global can be unavailable in react native
280
+
281
+
282
+ if (typeof document === 'undefined') {
283
+ return true;
284
+ }
285
+
286
+ return [undefined, 'visible', 'prerender'].includes(document.visibilityState);
287
+ }
288
+
289
+ }
290
+ const focusManager = new FocusManager();
291
+
292
+ class OnlineManager extends Subscribable {
293
+ constructor() {
294
+ super();
295
+
296
+ this.setup = onOnline => {
297
+ // addEventListener does not exist in React Native, but window does
298
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
299
+ if (!isServer && window.addEventListener) {
300
+ const listener = () => onOnline(); // Listen to online
301
+
302
+
303
+ window.addEventListener('online', listener, false);
304
+ window.addEventListener('offline', listener, false);
305
+ return () => {
306
+ // Be sure to unsubscribe if a new handler is set
307
+ window.removeEventListener('online', listener);
308
+ window.removeEventListener('offline', listener);
309
+ };
310
+ }
311
+ };
312
+ }
313
+
314
+ onSubscribe() {
315
+ if (!this.cleanup) {
316
+ this.setEventListener(this.setup);
317
+ }
318
+ }
319
+
320
+ onUnsubscribe() {
321
+ if (!this.hasListeners()) {
322
+ var _this$cleanup;
323
+
324
+ (_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
325
+ this.cleanup = undefined;
326
+ }
327
+ }
328
+
329
+ setEventListener(setup) {
330
+ var _this$cleanup2;
331
+
332
+ this.setup = setup;
333
+ (_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
334
+ this.cleanup = setup(online => {
335
+ if (typeof online === 'boolean') {
336
+ this.setOnline(online);
337
+ } else {
338
+ this.onOnline();
339
+ }
340
+ });
341
+ }
342
+
343
+ setOnline(online) {
344
+ this.online = online;
345
+
346
+ if (online) {
347
+ this.onOnline();
348
+ }
349
+ }
350
+
351
+ onOnline() {
352
+ this.listeners.forEach(listener => {
353
+ listener();
354
+ });
355
+ }
356
+
357
+ isOnline() {
358
+ if (typeof this.online === 'boolean') {
359
+ return this.online;
360
+ }
361
+
362
+ if (typeof navigator === 'undefined' || typeof navigator.onLine === 'undefined') {
363
+ return true;
364
+ }
365
+
366
+ return navigator.onLine;
367
+ }
368
+
369
+ }
370
+ const onlineManager = new OnlineManager();
371
+
372
+ function canFetch(networkMode) {
373
+ return (networkMode != null ? networkMode : 'online') === 'online' ? onlineManager.isOnline() : true;
374
+ }
375
+ class CancelledError {
376
+ constructor(options) {
377
+ this.revert = options == null ? void 0 : options.revert;
378
+ this.silent = options == null ? void 0 : options.silent;
379
+ }
380
+
381
+ }
382
+ function isCancelledError(value) {
383
+ return value instanceof CancelledError;
384
+ }
385
+
386
+ function createNotifyManager() {
387
+ let queue = [];
388
+ let transactions = 0;
389
+
390
+ let notifyFn = callback => {
391
+ callback();
392
+ };
393
+
394
+ let batchNotifyFn = callback => {
395
+ callback();
396
+ };
397
+
398
+ const batch = callback => {
399
+ let result;
400
+ transactions++;
401
+
402
+ try {
403
+ result = callback();
404
+ } finally {
405
+ transactions--;
406
+
407
+ if (!transactions) {
408
+ flush();
409
+ }
410
+ }
411
+
412
+ return result;
413
+ };
414
+
415
+ const schedule = callback => {
416
+ if (transactions) {
417
+ queue.push(callback);
418
+ } else {
419
+ scheduleMicrotask(() => {
420
+ notifyFn(callback);
421
+ });
422
+ }
423
+ };
424
+ /**
425
+ * All calls to the wrapped function will be batched.
426
+ */
427
+
428
+
429
+ const batchCalls = callback => {
430
+ return (...args) => {
431
+ schedule(() => {
432
+ callback(...args);
433
+ });
434
+ };
435
+ };
436
+
437
+ const flush = () => {
438
+ const originalQueue = queue;
439
+ queue = [];
440
+
441
+ if (originalQueue.length) {
442
+ scheduleMicrotask(() => {
443
+ batchNotifyFn(() => {
444
+ originalQueue.forEach(callback => {
445
+ notifyFn(callback);
446
+ });
447
+ });
448
+ });
449
+ }
450
+ };
451
+ /**
452
+ * Use this method to set a custom notify function.
453
+ * This can be used to for example wrap notifications with `React.act` while running tests.
454
+ */
455
+
456
+
457
+ const setNotifyFunction = fn => {
458
+ notifyFn = fn;
459
+ };
460
+ /**
461
+ * Use this method to set a custom function to batch notifications together into a single tick.
462
+ * By default React Query will use the batch function provided by ReactDOM or React Native.
463
+ */
464
+
465
+
466
+ const setBatchNotifyFunction = fn => {
467
+ batchNotifyFn = fn;
468
+ };
469
+
470
+ return {
471
+ batch,
472
+ batchCalls,
473
+ schedule,
474
+ setNotifyFunction,
475
+ setBatchNotifyFunction
476
+ };
477
+ } // SINGLETON
478
+
479
+ const notifyManager = createNotifyManager();
480
+
481
+ function getDefaultState() {
482
+ return {
483
+ context: undefined,
484
+ data: undefined,
485
+ error: null,
486
+ failureCount: 0,
487
+ failureReason: null,
488
+ isPaused: false,
489
+ status: 'idle',
490
+ variables: undefined
491
+ };
492
+ }
493
+
494
+ class QueryObserver extends Subscribable {
495
+ constructor(client, options) {
496
+ super();
497
+ this.client = client;
498
+ this.options = options;
499
+ this.trackedProps = new Set();
500
+ this.selectError = null;
501
+ this.bindMethods();
502
+ this.setOptions(options);
503
+ }
504
+
505
+ bindMethods() {
506
+ this.remove = this.remove.bind(this);
507
+ this.refetch = this.refetch.bind(this);
508
+ }
509
+
510
+ onSubscribe() {
511
+ if (this.listeners.length === 1) {
512
+ this.currentQuery.addObserver(this);
513
+
514
+ if (shouldFetchOnMount(this.currentQuery, this.options)) {
515
+ this.executeFetch();
516
+ }
517
+
518
+ this.updateTimers();
519
+ }
520
+ }
521
+
522
+ onUnsubscribe() {
523
+ if (!this.listeners.length) {
524
+ this.destroy();
525
+ }
526
+ }
527
+
528
+ shouldFetchOnReconnect() {
529
+ return shouldFetchOn(this.currentQuery, this.options, this.options.refetchOnReconnect);
530
+ }
531
+
532
+ shouldFetchOnWindowFocus() {
533
+ return shouldFetchOn(this.currentQuery, this.options, this.options.refetchOnWindowFocus);
534
+ }
535
+
536
+ destroy() {
537
+ this.listeners = [];
538
+ this.clearStaleTimeout();
539
+ this.clearRefetchInterval();
540
+ this.currentQuery.removeObserver(this);
541
+ }
542
+
543
+ setOptions(options, notifyOptions) {
544
+ const prevOptions = this.options;
545
+ const prevQuery = this.currentQuery;
546
+ this.options = this.client.defaultQueryOptions(options);
547
+
548
+ if (process.env.NODE_ENV !== 'production' && typeof (options == null ? void 0 : options.isDataEqual) !== 'undefined') {
549
+ this.client.getLogger().error("The isDataEqual option has been deprecated and will be removed in the next major version. You can achieve the same functionality by passing a function as the structuralSharing option");
550
+ }
551
+
552
+ if (!shallowEqualObjects(prevOptions, this.options)) {
553
+ this.client.getQueryCache().notify({
554
+ type: 'observerOptionsUpdated',
555
+ query: this.currentQuery,
556
+ observer: this
557
+ });
558
+ }
559
+
560
+ if (typeof this.options.enabled !== 'undefined' && typeof this.options.enabled !== 'boolean') {
561
+ throw new Error('Expected enabled to be a boolean');
562
+ } // Keep previous query key if the user does not supply one
563
+
564
+
565
+ if (!this.options.queryKey) {
566
+ this.options.queryKey = prevOptions.queryKey;
567
+ }
568
+
569
+ this.updateQuery();
570
+ const mounted = this.hasListeners(); // Fetch if there are subscribers
571
+
572
+ if (mounted && shouldFetchOptionally(this.currentQuery, prevQuery, this.options, prevOptions)) {
573
+ this.executeFetch();
574
+ } // Update result
575
+
576
+
577
+ this.updateResult(notifyOptions); // Update stale interval if needed
578
+
579
+ if (mounted && (this.currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || this.options.staleTime !== prevOptions.staleTime)) {
580
+ this.updateStaleTimeout();
581
+ }
582
+
583
+ const nextRefetchInterval = this.computeRefetchInterval(); // Update refetch interval if needed
584
+
585
+ if (mounted && (this.currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || nextRefetchInterval !== this.currentRefetchInterval)) {
586
+ this.updateRefetchInterval(nextRefetchInterval);
587
+ }
588
+ }
589
+
590
+ getOptimisticResult(options) {
591
+ const query = this.client.getQueryCache().build(this.client, options);
592
+ return this.createResult(query, options);
593
+ }
594
+
595
+ getCurrentResult() {
596
+ return this.currentResult;
597
+ }
598
+
599
+ trackResult(result) {
600
+ const trackedResult = {};
601
+ Object.keys(result).forEach(key => {
602
+ Object.defineProperty(trackedResult, key, {
603
+ configurable: false,
604
+ enumerable: true,
605
+ get: () => {
606
+ this.trackedProps.add(key);
607
+ return result[key];
608
+ }
609
+ });
610
+ });
611
+ return trackedResult;
612
+ }
613
+
614
+ getCurrentQuery() {
615
+ return this.currentQuery;
616
+ }
617
+
618
+ remove() {
619
+ this.client.getQueryCache().remove(this.currentQuery);
620
+ }
621
+
622
+ refetch({
623
+ refetchPage,
624
+ ...options
625
+ } = {}) {
626
+ return this.fetch({ ...options,
627
+ meta: {
628
+ refetchPage
629
+ }
630
+ });
631
+ }
632
+
633
+ fetchOptimistic(options) {
634
+ const defaultedOptions = this.client.defaultQueryOptions(options);
635
+ const query = this.client.getQueryCache().build(this.client, defaultedOptions);
636
+ query.isFetchingOptimistic = true;
637
+ return query.fetch().then(() => this.createResult(query, defaultedOptions));
638
+ }
639
+
640
+ fetch(fetchOptions) {
641
+ var _fetchOptions$cancelR;
642
+
643
+ return this.executeFetch({ ...fetchOptions,
644
+ cancelRefetch: (_fetchOptions$cancelR = fetchOptions.cancelRefetch) != null ? _fetchOptions$cancelR : true
645
+ }).then(() => {
646
+ this.updateResult();
647
+ return this.currentResult;
648
+ });
649
+ }
650
+
651
+ executeFetch(fetchOptions) {
652
+ // Make sure we reference the latest query as the current one might have been removed
653
+ this.updateQuery(); // Fetch
654
+
655
+ let promise = this.currentQuery.fetch(this.options, fetchOptions);
656
+
657
+ if (!(fetchOptions != null && fetchOptions.throwOnError)) {
658
+ promise = promise.catch(noop$1);
659
+ }
660
+
661
+ return promise;
662
+ }
663
+
664
+ updateStaleTimeout() {
665
+ this.clearStaleTimeout();
666
+
667
+ if (isServer || this.currentResult.isStale || !isValidTimeout(this.options.staleTime)) {
668
+ return;
669
+ }
670
+
671
+ const time = timeUntilStale(this.currentResult.dataUpdatedAt, this.options.staleTime); // The timeout is sometimes triggered 1 ms before the stale time expiration.
672
+ // To mitigate this issue we always add 1 ms to the timeout.
673
+
674
+ const timeout = time + 1;
675
+ this.staleTimeoutId = setTimeout(() => {
676
+ if (!this.currentResult.isStale) {
677
+ this.updateResult();
678
+ }
679
+ }, timeout);
680
+ }
681
+
682
+ computeRefetchInterval() {
683
+ var _this$options$refetch;
684
+
685
+ 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;
686
+ }
687
+
688
+ updateRefetchInterval(nextInterval) {
689
+ this.clearRefetchInterval();
690
+ this.currentRefetchInterval = nextInterval;
691
+
692
+ if (isServer || this.options.enabled === false || !isValidTimeout(this.currentRefetchInterval) || this.currentRefetchInterval === 0) {
693
+ return;
694
+ }
695
+
696
+ this.refetchIntervalId = setInterval(() => {
697
+ if (this.options.refetchIntervalInBackground || focusManager.isFocused()) {
698
+ this.executeFetch();
699
+ }
700
+ }, this.currentRefetchInterval);
701
+ }
702
+
703
+ updateTimers() {
704
+ this.updateStaleTimeout();
705
+ this.updateRefetchInterval(this.computeRefetchInterval());
706
+ }
707
+
708
+ clearStaleTimeout() {
709
+ if (this.staleTimeoutId) {
710
+ clearTimeout(this.staleTimeoutId);
711
+ this.staleTimeoutId = undefined;
712
+ }
713
+ }
714
+
715
+ clearRefetchInterval() {
716
+ if (this.refetchIntervalId) {
717
+ clearInterval(this.refetchIntervalId);
718
+ this.refetchIntervalId = undefined;
719
+ }
720
+ }
721
+
722
+ createResult(query, options) {
723
+ const prevQuery = this.currentQuery;
724
+ const prevOptions = this.options;
725
+ const prevResult = this.currentResult;
726
+ const prevResultState = this.currentResultState;
727
+ const prevResultOptions = this.currentResultOptions;
728
+ const queryChange = query !== prevQuery;
729
+ const queryInitialState = queryChange ? query.state : this.currentQueryInitialState;
730
+ const prevQueryResult = queryChange ? this.currentResult : this.previousQueryResult;
731
+ const {
732
+ state
733
+ } = query;
734
+ let {
735
+ dataUpdatedAt,
736
+ error,
737
+ errorUpdatedAt,
738
+ fetchStatus,
739
+ status
740
+ } = state;
741
+ let isPreviousData = false;
742
+ let isPlaceholderData = false;
743
+ let data; // Optimistically set result in fetching state if needed
744
+
745
+ if (options._optimisticResults) {
746
+ const mounted = this.hasListeners();
747
+ const fetchOnMount = !mounted && shouldFetchOnMount(query, options);
748
+ const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
749
+
750
+ if (fetchOnMount || fetchOptionally) {
751
+ fetchStatus = canFetch(query.options.networkMode) ? 'fetching' : 'paused';
752
+
753
+ if (!dataUpdatedAt) {
754
+ status = 'loading';
755
+ }
756
+ }
757
+
758
+ if (options._optimisticResults === 'isRestoring') {
759
+ fetchStatus = 'idle';
760
+ }
761
+ } // Keep previous data if needed
762
+
763
+
764
+ if (options.keepPreviousData && !state.dataUpdatedAt && prevQueryResult != null && prevQueryResult.isSuccess && status !== 'error') {
765
+ data = prevQueryResult.data;
766
+ dataUpdatedAt = prevQueryResult.dataUpdatedAt;
767
+ status = prevQueryResult.status;
768
+ isPreviousData = true;
769
+ } // Select data if needed
770
+ else if (options.select && typeof state.data !== 'undefined') {
771
+ // Memoize select result
772
+ if (prevResult && state.data === (prevResultState == null ? void 0 : prevResultState.data) && options.select === this.selectFn) {
773
+ data = this.selectResult;
774
+ } else {
775
+ try {
776
+ this.selectFn = options.select;
777
+ data = options.select(state.data);
778
+ data = replaceData(prevResult == null ? void 0 : prevResult.data, data, options);
779
+ this.selectResult = data;
780
+ this.selectError = null;
781
+ } catch (selectError) {
782
+ if (process.env.NODE_ENV !== 'production') {
783
+ this.client.getLogger().error(selectError);
784
+ }
785
+
786
+ this.selectError = selectError;
787
+ }
788
+ }
789
+ } // Use query data
790
+ else {
791
+ data = state.data;
792
+ } // Show placeholder data if needed
793
+
794
+
795
+ if (typeof options.placeholderData !== 'undefined' && typeof data === 'undefined' && status === 'loading') {
796
+ let placeholderData; // Memoize placeholder data
797
+
798
+ if (prevResult != null && prevResult.isPlaceholderData && options.placeholderData === (prevResultOptions == null ? void 0 : prevResultOptions.placeholderData)) {
799
+ placeholderData = prevResult.data;
800
+ } else {
801
+ placeholderData = typeof options.placeholderData === 'function' ? options.placeholderData() : options.placeholderData;
802
+
803
+ if (options.select && typeof placeholderData !== 'undefined') {
804
+ try {
805
+ placeholderData = options.select(placeholderData);
806
+ this.selectError = null;
807
+ } catch (selectError) {
808
+ if (process.env.NODE_ENV !== 'production') {
809
+ this.client.getLogger().error(selectError);
810
+ }
811
+
812
+ this.selectError = selectError;
813
+ }
814
+ }
815
+ }
816
+
817
+ if (typeof placeholderData !== 'undefined') {
818
+ status = 'success';
819
+ data = replaceData(prevResult == null ? void 0 : prevResult.data, placeholderData, options);
820
+ isPlaceholderData = true;
821
+ }
822
+ }
823
+
824
+ if (this.selectError) {
825
+ error = this.selectError;
826
+ data = this.selectResult;
827
+ errorUpdatedAt = Date.now();
828
+ status = 'error';
829
+ }
830
+
831
+ const isFetching = fetchStatus === 'fetching';
832
+ const isLoading = status === 'loading';
833
+ const isError = status === 'error';
834
+ const result = {
835
+ status,
836
+ fetchStatus,
837
+ isLoading,
838
+ isSuccess: status === 'success',
839
+ isError,
840
+ isInitialLoading: isLoading && isFetching,
841
+ data,
842
+ dataUpdatedAt,
843
+ error,
844
+ errorUpdatedAt,
845
+ failureCount: state.fetchFailureCount,
846
+ failureReason: state.fetchFailureReason,
847
+ errorUpdateCount: state.errorUpdateCount,
848
+ isFetched: state.dataUpdateCount > 0 || state.errorUpdateCount > 0,
849
+ isFetchedAfterMount: state.dataUpdateCount > queryInitialState.dataUpdateCount || state.errorUpdateCount > queryInitialState.errorUpdateCount,
850
+ isFetching,
851
+ isRefetching: isFetching && !isLoading,
852
+ isLoadingError: isError && state.dataUpdatedAt === 0,
853
+ isPaused: fetchStatus === 'paused',
854
+ isPlaceholderData,
855
+ isPreviousData,
856
+ isRefetchError: isError && state.dataUpdatedAt !== 0,
857
+ isStale: isStale(query, options),
858
+ refetch: this.refetch,
859
+ remove: this.remove
860
+ };
861
+ return result;
862
+ }
863
+
864
+ updateResult(notifyOptions) {
865
+ const prevResult = this.currentResult;
866
+ const nextResult = this.createResult(this.currentQuery, this.options);
867
+ this.currentResultState = this.currentQuery.state;
868
+ this.currentResultOptions = this.options; // Only notify and update result if something has changed
869
+
870
+ if (shallowEqualObjects(nextResult, prevResult)) {
871
+ return;
872
+ }
873
+
874
+ this.currentResult = nextResult; // Determine which callbacks to trigger
875
+
876
+ const defaultNotifyOptions = {
877
+ cache: true
878
+ };
879
+
880
+ const shouldNotifyListeners = () => {
881
+ if (!prevResult) {
882
+ return true;
883
+ }
884
+
885
+ const {
886
+ notifyOnChangeProps
887
+ } = this.options;
888
+
889
+ if (notifyOnChangeProps === 'all' || !notifyOnChangeProps && !this.trackedProps.size) {
890
+ return true;
891
+ }
892
+
893
+ const includedProps = new Set(notifyOnChangeProps != null ? notifyOnChangeProps : this.trackedProps);
894
+
895
+ if (this.options.useErrorBoundary) {
896
+ includedProps.add('error');
897
+ }
898
+
899
+ return Object.keys(this.currentResult).some(key => {
900
+ const typedKey = key;
901
+ const changed = this.currentResult[typedKey] !== prevResult[typedKey];
902
+ return changed && includedProps.has(typedKey);
903
+ });
904
+ };
905
+
906
+ if ((notifyOptions == null ? void 0 : notifyOptions.listeners) !== false && shouldNotifyListeners()) {
907
+ defaultNotifyOptions.listeners = true;
908
+ }
909
+
910
+ this.notify({ ...defaultNotifyOptions,
911
+ ...notifyOptions
912
+ });
913
+ }
914
+
915
+ updateQuery() {
916
+ const query = this.client.getQueryCache().build(this.client, this.options);
917
+
918
+ if (query === this.currentQuery) {
919
+ return;
920
+ }
921
+
922
+ const prevQuery = this.currentQuery;
923
+ this.currentQuery = query;
924
+ this.currentQueryInitialState = query.state;
925
+ this.previousQueryResult = this.currentResult;
926
+
927
+ if (this.hasListeners()) {
928
+ prevQuery == null ? void 0 : prevQuery.removeObserver(this);
929
+ query.addObserver(this);
930
+ }
931
+ }
932
+
933
+ onQueryUpdate(action) {
934
+ const notifyOptions = {};
935
+
936
+ if (action.type === 'success') {
937
+ notifyOptions.onSuccess = !action.manual;
938
+ } else if (action.type === 'error' && !isCancelledError(action.error)) {
939
+ notifyOptions.onError = true;
940
+ }
941
+
942
+ this.updateResult(notifyOptions);
943
+
944
+ if (this.hasListeners()) {
945
+ this.updateTimers();
946
+ }
947
+ }
948
+
949
+ notify(notifyOptions) {
950
+ notifyManager.batch(() => {
951
+ // First trigger the configuration callbacks
952
+ if (notifyOptions.onSuccess) {
953
+ var _this$options$onSucce, _this$options, _this$options$onSettl, _this$options2;
954
+
955
+ (_this$options$onSucce = (_this$options = this.options).onSuccess) == null ? void 0 : _this$options$onSucce.call(_this$options, this.currentResult.data);
956
+ (_this$options$onSettl = (_this$options2 = this.options).onSettled) == null ? void 0 : _this$options$onSettl.call(_this$options2, this.currentResult.data, null);
957
+ } else if (notifyOptions.onError) {
958
+ var _this$options$onError, _this$options3, _this$options$onSettl2, _this$options4;
959
+
960
+ (_this$options$onError = (_this$options3 = this.options).onError) == null ? void 0 : _this$options$onError.call(_this$options3, this.currentResult.error);
961
+ (_this$options$onSettl2 = (_this$options4 = this.options).onSettled) == null ? void 0 : _this$options$onSettl2.call(_this$options4, undefined, this.currentResult.error);
962
+ } // Then trigger the listeners
963
+
964
+
965
+ if (notifyOptions.listeners) {
966
+ this.listeners.forEach(listener => {
967
+ listener(this.currentResult);
968
+ });
969
+ } // Then the cache listeners
970
+
971
+
972
+ if (notifyOptions.cache) {
973
+ this.client.getQueryCache().notify({
974
+ query: this.currentQuery,
975
+ type: 'observerResultsUpdated'
976
+ });
977
+ }
978
+ });
979
+ }
980
+
981
+ }
982
+
983
+ function shouldLoadOnMount(query, options) {
984
+ return options.enabled !== false && !query.state.dataUpdatedAt && !(query.state.status === 'error' && options.retryOnMount === false);
985
+ }
986
+
987
+ function shouldFetchOnMount(query, options) {
988
+ return shouldLoadOnMount(query, options) || query.state.dataUpdatedAt > 0 && shouldFetchOn(query, options, options.refetchOnMount);
989
+ }
990
+
991
+ function shouldFetchOn(query, options, field) {
992
+ if (options.enabled !== false) {
993
+ const value = typeof field === 'function' ? field(query) : field;
994
+ return value === 'always' || value !== false && isStale(query, options);
995
+ }
996
+
997
+ return false;
998
+ }
999
+
1000
+ function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
1001
+ return options.enabled !== false && (query !== prevQuery || prevOptions.enabled === false) && (!options.suspense || query.state.status !== 'error') && isStale(query, options);
1002
+ }
1003
+
1004
+ function isStale(query, options) {
1005
+ return query.isStaleByTime(options.staleTime);
1006
+ }
1007
+
1008
+ // CLASS
1009
+ class MutationObserver extends Subscribable {
1010
+ constructor(client, options) {
1011
+ super();
1012
+ this.client = client;
1013
+ this.setOptions(options);
1014
+ this.bindMethods();
1015
+ this.updateResult();
1016
+ }
1017
+
1018
+ bindMethods() {
1019
+ this.mutate = this.mutate.bind(this);
1020
+ this.reset = this.reset.bind(this);
1021
+ }
1022
+
1023
+ setOptions(options) {
1024
+ const prevOptions = this.options;
1025
+ this.options = this.client.defaultMutationOptions(options);
1026
+
1027
+ if (!shallowEqualObjects(prevOptions, this.options)) {
1028
+ this.client.getMutationCache().notify({
1029
+ type: 'observerOptionsUpdated',
1030
+ mutation: this.currentMutation,
1031
+ observer: this
1032
+ });
1033
+ }
1034
+ }
1035
+
1036
+ onUnsubscribe() {
1037
+ if (!this.listeners.length) {
1038
+ var _this$currentMutation;
1039
+
1040
+ (_this$currentMutation = this.currentMutation) == null ? void 0 : _this$currentMutation.removeObserver(this);
1041
+ }
1042
+ }
1043
+
1044
+ onMutationUpdate(action) {
1045
+ this.updateResult(); // Determine which callbacks to trigger
1046
+
1047
+ const notifyOptions = {
1048
+ listeners: true
1049
+ };
1050
+
1051
+ if (action.type === 'success') {
1052
+ notifyOptions.onSuccess = true;
1053
+ } else if (action.type === 'error') {
1054
+ notifyOptions.onError = true;
1055
+ }
1056
+
1057
+ this.notify(notifyOptions);
1058
+ }
1059
+
1060
+ getCurrentResult() {
1061
+ return this.currentResult;
1062
+ }
1063
+
1064
+ reset() {
1065
+ this.currentMutation = undefined;
1066
+ this.updateResult();
1067
+ this.notify({
1068
+ listeners: true
1069
+ });
1070
+ }
1071
+
1072
+ mutate(variables, options) {
1073
+ this.mutateOptions = options;
1074
+
1075
+ if (this.currentMutation) {
1076
+ this.currentMutation.removeObserver(this);
1077
+ }
1078
+
1079
+ this.currentMutation = this.client.getMutationCache().build(this.client, { ...this.options,
1080
+ variables: typeof variables !== 'undefined' ? variables : this.options.variables
1081
+ });
1082
+ this.currentMutation.addObserver(this);
1083
+ return this.currentMutation.execute();
1084
+ }
1085
+
1086
+ updateResult() {
1087
+ const state = this.currentMutation ? this.currentMutation.state : getDefaultState();
1088
+ const result = { ...state,
1089
+ isLoading: state.status === 'loading',
1090
+ isSuccess: state.status === 'success',
1091
+ isError: state.status === 'error',
1092
+ isIdle: state.status === 'idle',
1093
+ mutate: this.mutate,
1094
+ reset: this.reset
1095
+ };
1096
+ this.currentResult = result;
1097
+ }
1098
+
1099
+ notify(options) {
1100
+ notifyManager.batch(() => {
1101
+ // First trigger the mutate callbacks
1102
+ if (this.mutateOptions) {
1103
+ if (options.onSuccess) {
1104
+ var _this$mutateOptions$o, _this$mutateOptions, _this$mutateOptions$o2, _this$mutateOptions2;
1105
+
1106
+ (_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);
1107
+ (_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);
1108
+ } else if (options.onError) {
1109
+ var _this$mutateOptions$o3, _this$mutateOptions3, _this$mutateOptions$o4, _this$mutateOptions4;
1110
+
1111
+ (_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);
1112
+ (_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);
1113
+ }
1114
+ } // Then trigger the listeners
1115
+
1116
+
1117
+ if (options.listeners) {
1118
+ this.listeners.forEach(listener => {
1119
+ listener(this.currentResult);
1120
+ });
1121
+ }
1122
+ });
1123
+ }
1124
+
1125
+ }
1126
+
1127
+ var shim = {exports: {}};
1128
+
1129
+ var useSyncExternalStoreShim_production_min = {};
1130
+
1131
+ /**
1132
+ * @license React
1133
+ * use-sync-external-store-shim.production.min.js
1134
+ *
1135
+ * Copyright (c) Facebook, Inc. and its affiliates.
1136
+ *
1137
+ * This source code is licensed under the MIT license found in the
1138
+ * LICENSE file in the root directory of this source tree.
1139
+ */
1140
+
1141
+ var hasRequiredUseSyncExternalStoreShim_production_min;
1142
+
1143
+ function requireUseSyncExternalStoreShim_production_min () {
1144
+ if (hasRequiredUseSyncExternalStoreShim_production_min) return useSyncExternalStoreShim_production_min;
1145
+ hasRequiredUseSyncExternalStoreShim_production_min = 1;
1146
+ var e=React__default["default"];function h(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var k="function"===typeof Object.is?Object.is:h,l=e.useState,m=e.useEffect,n=e.useLayoutEffect,p=e.useDebugValue;function q(a,b){var d=b(),f=l({inst:{value:d,getSnapshot:b}}),c=f[0].inst,g=f[1];n(function(){c.value=d;c.getSnapshot=b;r(c)&&g({inst:c});},[a,d,b]);m(function(){r(c)&&g({inst:c});return a(function(){r(c)&&g({inst:c});})},[a]);p(d);return d}
1147
+ function r(a){var b=a.getSnapshot;a=a.value;try{var d=b();return !k(a,d)}catch(f){return !0}}function t(a,b){return b()}var u="undefined"===typeof window||"undefined"===typeof window.document||"undefined"===typeof window.document.createElement?t:q;useSyncExternalStoreShim_production_min.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:u;
1148
+ return useSyncExternalStoreShim_production_min;
1149
+ }
1150
+
1151
+ var useSyncExternalStoreShim_development = {};
1152
+
1153
+ /**
1154
+ * @license React
1155
+ * use-sync-external-store-shim.development.js
1156
+ *
1157
+ * Copyright (c) Facebook, Inc. and its affiliates.
1158
+ *
1159
+ * This source code is licensed under the MIT license found in the
1160
+ * LICENSE file in the root directory of this source tree.
1161
+ */
1162
+
1163
+ var hasRequiredUseSyncExternalStoreShim_development;
1164
+
1165
+ function requireUseSyncExternalStoreShim_development () {
1166
+ if (hasRequiredUseSyncExternalStoreShim_development) return useSyncExternalStoreShim_development;
1167
+ hasRequiredUseSyncExternalStoreShim_development = 1;
1168
+
1169
+ if (process.env.NODE_ENV !== "production") {
1170
+ (function() {
1171
+
1172
+ /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
1173
+ if (
1174
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
1175
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===
1176
+ 'function'
1177
+ ) {
1178
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
1179
+ }
1180
+ var React = React__default["default"];
1181
+
1182
+ var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
1183
+
1184
+ function error(format) {
1185
+ {
1186
+ {
1187
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
1188
+ args[_key2 - 1] = arguments[_key2];
1189
+ }
1190
+
1191
+ printWarning('error', format, args);
1192
+ }
1193
+ }
1194
+ }
1195
+
1196
+ function printWarning(level, format, args) {
1197
+ // When changing this logic, you might want to also
1198
+ // update consoleWithStackDev.www.js as well.
1199
+ {
1200
+ var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
1201
+ var stack = ReactDebugCurrentFrame.getStackAddendum();
1202
+
1203
+ if (stack !== '') {
1204
+ format += '%s';
1205
+ args = args.concat([stack]);
1206
+ } // eslint-disable-next-line react-internal/safe-string-coercion
1207
+
1208
+
1209
+ var argsWithFormat = args.map(function (item) {
1210
+ return String(item);
1211
+ }); // Careful: RN currently depends on this prefix
1212
+
1213
+ argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
1214
+ // breaks IE9: https://github.com/facebook/react/issues/13610
1215
+ // eslint-disable-next-line react-internal/no-production-logging
1216
+
1217
+ Function.prototype.apply.call(console[level], console, argsWithFormat);
1218
+ }
1219
+ }
1220
+
1221
+ /**
1222
+ * inlined Object.is polyfill to avoid requiring consumers ship their own
1223
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
1224
+ */
1225
+ function is(x, y) {
1226
+ return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
1227
+ ;
1228
+ }
1229
+
1230
+ var objectIs = typeof Object.is === 'function' ? Object.is : is;
1231
+
1232
+ // dispatch for CommonJS interop named imports.
1233
+
1234
+ var useState = React.useState,
1235
+ useEffect = React.useEffect,
1236
+ useLayoutEffect = React.useLayoutEffect,
1237
+ useDebugValue = React.useDebugValue;
1238
+ var didWarnOld18Alpha = false;
1239
+ var didWarnUncachedGetSnapshot = false; // Disclaimer: This shim breaks many of the rules of React, and only works
1240
+ // because of a very particular set of implementation details and assumptions
1241
+ // -- change any one of them and it will break. The most important assumption
1242
+ // is that updates are always synchronous, because concurrent rendering is
1243
+ // only available in versions of React that also have a built-in
1244
+ // useSyncExternalStore API. And we only use this shim when the built-in API
1245
+ // does not exist.
1246
+ //
1247
+ // Do not assume that the clever hacks used by this hook also work in general.
1248
+ // The point of this shim is to replace the need for hacks by other libraries.
1249
+
1250
+ function useSyncExternalStore(subscribe, getSnapshot, // Note: The shim does not use getServerSnapshot, because pre-18 versions of
1251
+ // React do not expose a way to check if we're hydrating. So users of the shim
1252
+ // will need to track that themselves and return the correct value
1253
+ // from `getSnapshot`.
1254
+ getServerSnapshot) {
1255
+ {
1256
+ if (!didWarnOld18Alpha) {
1257
+ if (React.startTransition !== undefined) {
1258
+ didWarnOld18Alpha = true;
1259
+
1260
+ error('You are using an outdated, pre-release alpha of React 18 that ' + 'does not support useSyncExternalStore. The ' + 'use-sync-external-store shim will not work correctly. Upgrade ' + 'to a newer pre-release.');
1261
+ }
1262
+ }
1263
+ } // Read the current snapshot from the store on every render. Again, this
1264
+ // breaks the rules of React, and only works here because of specific
1265
+ // implementation details, most importantly that updates are
1266
+ // always synchronous.
1267
+
1268
+
1269
+ var value = getSnapshot();
1270
+
1271
+ {
1272
+ if (!didWarnUncachedGetSnapshot) {
1273
+ var cachedValue = getSnapshot();
1274
+
1275
+ if (!objectIs(value, cachedValue)) {
1276
+ error('The result of getSnapshot should be cached to avoid an infinite loop');
1277
+
1278
+ didWarnUncachedGetSnapshot = true;
1279
+ }
1280
+ }
1281
+ } // Because updates are synchronous, we don't queue them. Instead we force a
1282
+ // re-render whenever the subscribed state changes by updating an some
1283
+ // arbitrary useState hook. Then, during render, we call getSnapshot to read
1284
+ // the current value.
1285
+ //
1286
+ // Because we don't actually use the state returned by the useState hook, we
1287
+ // can save a bit of memory by storing other stuff in that slot.
1288
+ //
1289
+ // To implement the early bailout, we need to track some things on a mutable
1290
+ // object. Usually, we would put that in a useRef hook, but we can stash it in
1291
+ // our useState hook instead.
1292
+ //
1293
+ // To force a re-render, we call forceUpdate({inst}). That works because the
1294
+ // new object always fails an equality check.
1295
+
1296
+
1297
+ var _useState = useState({
1298
+ inst: {
1299
+ value: value,
1300
+ getSnapshot: getSnapshot
1301
+ }
1302
+ }),
1303
+ inst = _useState[0].inst,
1304
+ forceUpdate = _useState[1]; // Track the latest getSnapshot function with a ref. This needs to be updated
1305
+ // in the layout phase so we can access it during the tearing check that
1306
+ // happens on subscribe.
1307
+
1308
+
1309
+ useLayoutEffect(function () {
1310
+ inst.value = value;
1311
+ inst.getSnapshot = getSnapshot; // Whenever getSnapshot or subscribe changes, we need to check in the
1312
+ // commit phase if there was an interleaved mutation. In concurrent mode
1313
+ // this can happen all the time, but even in synchronous mode, an earlier
1314
+ // effect may have mutated the store.
1315
+
1316
+ if (checkIfSnapshotChanged(inst)) {
1317
+ // Force a re-render.
1318
+ forceUpdate({
1319
+ inst: inst
1320
+ });
1321
+ }
1322
+ }, [subscribe, value, getSnapshot]);
1323
+ useEffect(function () {
1324
+ // Check for changes right before subscribing. Subsequent changes will be
1325
+ // detected in the subscription handler.
1326
+ if (checkIfSnapshotChanged(inst)) {
1327
+ // Force a re-render.
1328
+ forceUpdate({
1329
+ inst: inst
1330
+ });
1331
+ }
1332
+
1333
+ var handleStoreChange = function () {
1334
+ // TODO: Because there is no cross-renderer API for batching updates, it's
1335
+ // up to the consumer of this library to wrap their subscription event
1336
+ // with unstable_batchedUpdates. Should we try to detect when this isn't
1337
+ // the case and print a warning in development?
1338
+ // The store changed. Check if the snapshot changed since the last time we
1339
+ // read from the store.
1340
+ if (checkIfSnapshotChanged(inst)) {
1341
+ // Force a re-render.
1342
+ forceUpdate({
1343
+ inst: inst
1344
+ });
1345
+ }
1346
+ }; // Subscribe to the store and return a clean-up function.
1347
+
1348
+
1349
+ return subscribe(handleStoreChange);
1350
+ }, [subscribe]);
1351
+ useDebugValue(value);
1352
+ return value;
1353
+ }
1354
+
1355
+ function checkIfSnapshotChanged(inst) {
1356
+ var latestGetSnapshot = inst.getSnapshot;
1357
+ var prevValue = inst.value;
1358
+
1359
+ try {
1360
+ var nextValue = latestGetSnapshot();
1361
+ return !objectIs(prevValue, nextValue);
1362
+ } catch (error) {
1363
+ return true;
1364
+ }
1365
+ }
1366
+
1367
+ function useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) {
1368
+ // Note: The shim does not use getServerSnapshot, because pre-18 versions of
1369
+ // React do not expose a way to check if we're hydrating. So users of the shim
1370
+ // will need to track that themselves and return the correct value
1371
+ // from `getSnapshot`.
1372
+ return getSnapshot();
1373
+ }
1374
+
1375
+ var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');
1376
+
1377
+ var isServerEnvironment = !canUseDOM;
1378
+
1379
+ var shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore;
1380
+ var useSyncExternalStore$2 = React.useSyncExternalStore !== undefined ? React.useSyncExternalStore : shim;
1381
+
1382
+ useSyncExternalStoreShim_development.useSyncExternalStore = useSyncExternalStore$2;
1383
+ /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
1384
+ if (
1385
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
1386
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===
1387
+ 'function'
1388
+ ) {
1389
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
1390
+ }
1391
+
1392
+ })();
1393
+ }
1394
+ return useSyncExternalStoreShim_development;
1395
+ }
1396
+
1397
+ (function (module) {
1398
+
1399
+ if (process.env.NODE_ENV === 'production') {
1400
+ module.exports = requireUseSyncExternalStoreShim_production_min();
1401
+ } else {
1402
+ module.exports = requireUseSyncExternalStoreShim_development();
1403
+ }
1404
+ } (shim));
1405
+
1406
+ // Temporary workaround due to an issue with react-native uSES - https://github.com/TanStack/query/pull/3601
1407
+ const useSyncExternalStore = shim.exports.useSyncExternalStore;
1408
+
1409
+ const defaultContext = /*#__PURE__*/React__namespace.createContext(undefined);
1410
+ const QueryClientSharingContext = /*#__PURE__*/React__namespace.createContext(false); // If we are given a context, we will use it.
1411
+ // Otherwise, if contextSharing is on, we share the first and at least one
1412
+ // instance of the context across the window
1413
+ // to ensure that if React Query is used across
1414
+ // different bundles or microfrontends they will
1415
+ // all use the same **instance** of context, regardless
1416
+ // of module scoping.
1417
+
1418
+ function getQueryClientContext(context, contextSharing) {
1419
+ if (context) {
1420
+ return context;
1421
+ }
1422
+
1423
+ if (contextSharing && typeof window !== 'undefined') {
1424
+ if (!window.ReactQueryClientContext) {
1425
+ window.ReactQueryClientContext = defaultContext;
1426
+ }
1427
+
1428
+ return window.ReactQueryClientContext;
1429
+ }
1430
+
1431
+ return defaultContext;
1432
+ }
1433
+
1434
+ const useQueryClient = ({
1435
+ context
1436
+ } = {}) => {
1437
+ const queryClient = React__namespace.useContext(getQueryClientContext(context, React__namespace.useContext(QueryClientSharingContext)));
1438
+
1439
+ if (!queryClient) {
1440
+ throw new Error('No QueryClient set, use QueryClientProvider to set one');
1441
+ }
1442
+
1443
+ return queryClient;
1444
+ };
1445
+
1446
+ const IsRestoringContext = /*#__PURE__*/React__namespace.createContext(false);
1447
+ const useIsRestoring = () => React__namespace.useContext(IsRestoringContext);
1448
+ IsRestoringContext.Provider;
1449
+
1450
+ function createValue() {
1451
+ let isReset = false;
1452
+ return {
1453
+ clearReset: () => {
1454
+ isReset = false;
1455
+ },
1456
+ reset: () => {
1457
+ isReset = true;
1458
+ },
1459
+ isReset: () => {
1460
+ return isReset;
1461
+ }
1462
+ };
1463
+ }
1464
+
1465
+ const QueryErrorResetBoundaryContext = /*#__PURE__*/React__namespace.createContext(createValue()); // HOOK
1466
+
1467
+ const useQueryErrorResetBoundary = () => React__namespace.useContext(QueryErrorResetBoundaryContext); // COMPONENT
1468
+
1469
+ function shouldThrowError$1(_useErrorBoundary, params) {
1470
+ // Allow useErrorBoundary function to override throwing behavior on a per-error basis
1471
+ if (typeof _useErrorBoundary === 'function') {
1472
+ return _useErrorBoundary(...params);
1473
+ }
1474
+
1475
+ return !!_useErrorBoundary;
1476
+ }
1477
+
1478
+ function useMutation(arg1, arg2, arg3) {
1479
+ const options = parseMutationArgs(arg1, arg2, arg3);
1480
+ const queryClient = useQueryClient({
1481
+ context: options.context
1482
+ });
1483
+ const [observer] = React__namespace.useState(() => new MutationObserver(queryClient, options));
1484
+ React__namespace.useEffect(() => {
1485
+ observer.setOptions(options);
1486
+ }, [observer, options]);
1487
+ const result = useSyncExternalStore(React__namespace.useCallback(onStoreChange => observer.subscribe(notifyManager.batchCalls(onStoreChange)), [observer]), () => observer.getCurrentResult(), () => observer.getCurrentResult());
1488
+ const mutate = React__namespace.useCallback((variables, mutateOptions) => {
1489
+ observer.mutate(variables, mutateOptions).catch(noop);
1490
+ }, [observer]);
1491
+
1492
+ if (result.error && shouldThrowError$1(observer.options.useErrorBoundary, [result.error])) {
1493
+ throw result.error;
1494
+ }
1495
+
1496
+ return { ...result,
1497
+ mutate,
1498
+ mutateAsync: result.mutate
1499
+ };
1500
+ } // eslint-disable-next-line @typescript-eslint/no-empty-function
1501
+
1502
+ function noop() {}
1503
+
1504
+ // This is basically just React Query's useBaseQuery with a few changes for Legend-State:
1505
+ const ensurePreventErrorBoundaryRetry = (options, errorResetBoundary) => {
1506
+ if (options.suspense || options.useErrorBoundary) {
1507
+ // Prevent retrying failed query if the error boundary has not been reset yet
1508
+ if (!errorResetBoundary.isReset()) {
1509
+ options.retryOnMount = false;
1510
+ }
1511
+ }
1512
+ };
1513
+ const useClearResetErrorBoundary = (errorResetBoundary) => {
1514
+ React__namespace.useEffect(() => {
1515
+ errorResetBoundary.clearReset();
1516
+ }, [errorResetBoundary]);
1517
+ };
1518
+ function shouldThrowError(_useErrorBoundary, params) {
1519
+ // Allow useErrorBoundary function to override throwing behavior on a per-error basis
1520
+ if (typeof _useErrorBoundary === 'function') {
1521
+ return _useErrorBoundary(...params);
1522
+ }
1523
+ return !!_useErrorBoundary;
1524
+ }
1525
+ const getHasError = ({ result, errorResetBoundary, useErrorBoundary, query, }) => {
1526
+ return (result.isError &&
1527
+ !errorResetBoundary.isReset() &&
1528
+ !result.isFetching &&
1529
+ shouldThrowError(useErrorBoundary, [result.error, query]));
1530
+ };
1531
+ function useObservableQuery(options, mutationOptions) {
1532
+ const Observer = QueryObserver;
1533
+ const queryClient = useQueryClient({ context: options.context });
1534
+ const isRestoring = useIsRestoring();
1535
+ const errorResetBoundary = useQueryErrorResetBoundary();
1536
+ const defaultedOptions = queryClient.defaultQueryOptions(options);
1537
+ // Make sure results are optimistically set in fetching state before subscribing or updating options
1538
+ defaultedOptions._optimisticResults = isRestoring ? 'isRestoring' : 'optimistic';
1539
+ // Include callbacks in batch renders
1540
+ if (defaultedOptions.onError) {
1541
+ defaultedOptions.onError = notifyManager.batchCalls(defaultedOptions.onError);
1542
+ }
1543
+ if (defaultedOptions.onSuccess) {
1544
+ defaultedOptions.onSuccess = notifyManager.batchCalls(defaultedOptions.onSuccess);
1545
+ }
1546
+ if (defaultedOptions.onSettled) {
1547
+ defaultedOptions.onSettled = notifyManager.batchCalls(defaultedOptions.onSettled);
1548
+ }
1549
+ if (defaultedOptions.suspense) {
1550
+ // Always set stale time when using suspense to prevent
1551
+ // fetching again when directly mounting after suspending
1552
+ if (typeof defaultedOptions.staleTime !== 'number') {
1553
+ defaultedOptions.staleTime = 1000;
1554
+ }
1555
+ }
1556
+ ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary);
1557
+ useClearResetErrorBoundary(errorResetBoundary);
1558
+ const [observer] = React__namespace.useState(() => new Observer(queryClient, defaultedOptions));
1559
+ const result = observer.getOptimisticResult(defaultedOptions);
1560
+ // useSyncExternalStore was here in useBaseQuery but is removed for Legend-State.
1561
+ React__namespace.useEffect(() => {
1562
+ // Do not notify on updates because of changes in the options because
1563
+ // these changes should already be reflected in the optimistic result.
1564
+ observer.setOptions(defaultedOptions, { listeners: false });
1565
+ }, [defaultedOptions, observer]);
1566
+ // Handle suspense
1567
+ if (defaultedOptions.suspense && result.isLoading && result.isFetching && !isRestoring) {
1568
+ throw observer
1569
+ .fetchOptimistic(defaultedOptions)
1570
+ .then(({ data }) => {
1571
+ var _a, _b;
1572
+ (_a = defaultedOptions.onSuccess) === null || _a === void 0 ? void 0 : _a.call(defaultedOptions, data);
1573
+ (_b = defaultedOptions.onSettled) === null || _b === void 0 ? void 0 : _b.call(defaultedOptions, data, null);
1574
+ })
1575
+ .catch((error) => {
1576
+ var _a, _b;
1577
+ errorResetBoundary.clearReset();
1578
+ (_a = defaultedOptions.onError) === null || _a === void 0 ? void 0 : _a.call(defaultedOptions, error);
1579
+ (_b = defaultedOptions.onSettled) === null || _b === void 0 ? void 0 : _b.call(defaultedOptions, undefined, error);
1580
+ });
1581
+ }
1582
+ // Handle error boundary
1583
+ if (getHasError({
1584
+ result,
1585
+ errorResetBoundary,
1586
+ useErrorBoundary: defaultedOptions.useErrorBoundary,
1587
+ query: observer.getCurrentQuery(),
1588
+ })) {
1589
+ throw result.error;
1590
+ }
1591
+ // Legend-State changes from here down
1592
+ let mutator;
1593
+ if (mutationOptions) {
1594
+ // eslint-disable-next-line react-hooks/rules-of-hooks
1595
+ mutator = useMutation(mutationOptions);
1596
+ }
1597
+ const { obs, unsubscribe } = React__namespace.useMemo(() => {
1598
+ const obs = state.observable(observer.getCurrentResult());
1599
+ let isSetting = false;
1600
+ // If there is a mutator watch for changes as long as they don't come from the the query observer
1601
+ if (mutator) {
1602
+ state.observe(() => {
1603
+ const data = obs.data.get();
1604
+ // Don't want to call mutate if there's no data or this coming from the query changing
1605
+ if (data && !isSetting) {
1606
+ mutator.mutate(data);
1607
+ }
1608
+ });
1609
+ }
1610
+ const unsubscribe = observer.subscribe((result) => {
1611
+ isSetting = true;
1612
+ try {
1613
+ // Update the observable with the latest value
1614
+ obs.set(result);
1615
+ }
1616
+ finally {
1617
+ // If set causes a crash for some reason we still need to reset isSetting
1618
+ isSetting = false;
1619
+ }
1620
+ });
1621
+ return { obs, unsubscribe };
1622
+ }, []);
1623
+ // Unsubscribe from the query observer on unmount
1624
+ react.useUnmount(unsubscribe);
1625
+ // Return the observable
1626
+ return obs;
1627
+ }
1628
+
1629
+ exports.useObservableQuery = useObservableQuery;
1630
+ //# sourceMappingURL=useObservableQuery.js.map