@0xsquid/react-hooks 8.3.1-beta-stellar-issued-assets.1 → 8.3.1-embed-tanstack-build.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 (38) hide show
  1. package/dist/core/queries/queries-keys.d.ts +1 -5
  2. package/dist/core/types/index.d.ts +1 -1
  3. package/dist/core/types/stellar.d.ts +0 -52
  4. package/dist/core/types/tokens.d.ts +0 -4
  5. package/dist/hooks/index.d.ts +0 -1
  6. package/dist/{index-DPakWLan.js → index-D3LtAuC9.js} +3694 -361
  7. package/dist/index-D3LtAuC9.js.map +1 -0
  8. package/dist/{index-CJQHDfLM.js → index-DOoP75Yp.js} +3740 -418
  9. package/dist/index-DOoP75Yp.js.map +1 -0
  10. package/dist/{index.es-CMuCSzqv.js → index.es-C4uVlA0B.js} +2 -3
  11. package/dist/index.es-C4uVlA0B.js.map +1 -0
  12. package/dist/{index.es-CT2n71aB.js → index.es-C5DLFXAX.js} +2 -3
  13. package/dist/index.es-C5DLFXAX.js.map +1 -0
  14. package/dist/index.esm.js +1 -2
  15. package/dist/index.esm.js.map +1 -1
  16. package/dist/index.js +1 -13
  17. package/dist/index.js.map +1 -1
  18. package/dist/{secretService-D8hWz2Gz.js → secretService-BwFxfXV7.js} +2 -3
  19. package/dist/{secretService-D8hWz2Gz.js.map → secretService-BwFxfXV7.js.map} +1 -1
  20. package/dist/{secretService-CdbkGf17.js → secretService-CY6elBY4.js} +2 -3
  21. package/dist/{secretService-CdbkGf17.js.map → secretService-CY6elBY4.js.map} +1 -1
  22. package/dist/services/external/rpcService.d.ts +1 -1
  23. package/dist/services/external/stellarApiClient.d.ts +0 -4
  24. package/dist/services/external/stellarRpcClient.d.ts +2 -2
  25. package/dist/services/external/xrplRpcClient.d.ts +1 -2
  26. package/dist/services/index.d.ts +0 -1
  27. package/dist/services/internal/stellarService.d.ts +0 -9
  28. package/dist/services/internal/xrplService.d.ts +0 -2
  29. package/dist/{stellarService.client-ESo7_qhK.js → stellarService.client-2CVAOoJl.js} +2 -3
  30. package/dist/{stellarService.client-Dve9IZZm.js.map → stellarService.client-2CVAOoJl.js.map} +1 -1
  31. package/dist/{stellarService.client-Dve9IZZm.js → stellarService.client-OMPy5fjH.js} +2 -3
  32. package/dist/{stellarService.client-ESo7_qhK.js.map → stellarService.client-OMPy5fjH.js.map} +1 -1
  33. package/package.json +1 -1
  34. package/dist/hooks/stellar/useStellarTrustLine.d.ts +0 -13
  35. package/dist/index-CJQHDfLM.js.map +0 -1
  36. package/dist/index-DPakWLan.js.map +0 -1
  37. package/dist/index.es-CMuCSzqv.js.map +0 -1
  38. package/dist/index.es-CT2n71aB.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  import { ChainType, ActionType, SquidDataType, BridgeType, BridgeProvider, FeeType } from '@0xsquid/squid-types';
2
2
  import { zeroAddress as zeroAddress$1, parseUnits, formatUnits, isAddress, SwitchChainError, UserRejectedRequestError, getAddress, defineChain, encodeFunctionData, erc20Abi } from 'viem';
3
- import React, { useMemo, useCallback, useState, useEffect, createContext, useContext, useRef } from 'react';
4
- import { useQuery, useMutation, useQueries, useQueryClient, QueryClient, QueryClientProvider } from '@tanstack/react-query';
3
+ import * as React from 'react';
4
+ import React__default, { useMemo, useCallback, useState, useEffect, createContext, useContext, useRef } from 'react';
5
5
  import { fromBech32 } from '@cosmjs/encoding';
6
6
  import * as bitcoin from 'bitcoinjs-lib';
7
7
  import { address } from 'bitcoinjs-lib';
@@ -13,7 +13,7 @@ import { isValidXAddress, isValidClassicAddress } from 'ripple-address-codec';
13
13
  import { getAssociatedTokenAddress, createAssociatedTokenAccountInstruction, createTransferInstruction } from '@solana/spl-token';
14
14
  import { StandardWalletAdapter } from '@solana/wallet-standard-wallet-adapter-base';
15
15
  import { PublicKey, VersionedTransaction, Transaction, SystemProgram, Connection } from '@solana/web3.js';
16
- import { StrKey, Networks, nativeToScVal, Address, rpc, TransactionBuilder, BASE_FEE, Contract, TimeoutInfinite, scValToNative, Asset, Operation, Transaction as Transaction$1, xdr } from '@stellar/stellar-sdk';
16
+ import { StrKey, Networks, nativeToScVal, Address, rpc, TransactionBuilder, BASE_FEE, Contract, TimeoutInfinite, scValToNative, Operation, Transaction as Transaction$1, xdr } from '@stellar/stellar-sdk';
17
17
  import { SUI_TESTNET_CHAIN, SUI_MAINNET_CHAIN } from '@mysten/wallet-standard';
18
18
  import { CloudflareProvider, BrowserProvider, JsonRpcSigner, JsonRpcProvider, ethers, Interface, Contract as Contract$1, isError } from 'ethers';
19
19
  import BigNumber$1, { BigNumber } from 'bignumber.js';
@@ -200,22 +200,3053 @@ const transactionEndStatuses = [
200
200
  ...transactionErrorStatuses,
201
201
  ];
202
202
 
203
- var TransactionErrorType;
204
- (function (TransactionErrorType) {
205
- TransactionErrorType[TransactionErrorType["REJECTED_BY_USER"] = 0] = "REJECTED_BY_USER";
206
- TransactionErrorType[TransactionErrorType["CALL_EXCEPTION"] = 1] = "CALL_EXCEPTION";
207
- TransactionErrorType[TransactionErrorType["UNKNOWN"] = 2] = "UNKNOWN";
208
- TransactionErrorType[TransactionErrorType["WARNING"] = 3] = "WARNING";
209
- })(TransactionErrorType || (TransactionErrorType = {}));
210
- var SquidStatusErrorType;
211
- (function (SquidStatusErrorType) {
212
- SquidStatusErrorType["NotFoundError"] = "NotFoundError";
213
- })(SquidStatusErrorType || (SquidStatusErrorType = {}));
214
- class QrCodeGenerationError extends Error {
215
- constructor(message) {
216
- super(message);
217
- this.name = "QrCodeGenerationError";
203
+ class Subscribable {
204
+ constructor() {
205
+ this.listeners = new Set();
206
+ this.subscribe = this.subscribe.bind(this);
207
+ }
208
+
209
+ subscribe(listener) {
210
+ const identity = {
211
+ listener
212
+ };
213
+ this.listeners.add(identity);
214
+ this.onSubscribe();
215
+ return () => {
216
+ this.listeners.delete(identity);
217
+ this.onUnsubscribe();
218
+ };
219
+ }
220
+
221
+ hasListeners() {
222
+ return this.listeners.size > 0;
223
+ }
224
+
225
+ onSubscribe() {// Do nothing
226
+ }
227
+
228
+ onUnsubscribe() {// Do nothing
229
+ }
230
+
231
+ }
232
+
233
+ // TYPES
234
+ // UTILS
235
+ const isServer = typeof window === 'undefined' || 'Deno' in window;
236
+ function noop$1() {
237
+ return undefined;
238
+ }
239
+ function functionalUpdate(updater, input) {
240
+ return typeof updater === 'function' ? updater(input) : updater;
241
+ }
242
+ function isValidTimeout(value) {
243
+ return typeof value === 'number' && value >= 0 && value !== Infinity;
244
+ }
245
+ function difference(array1, array2) {
246
+ return array1.filter(x => !array2.includes(x));
247
+ }
248
+ function replaceAt(array, index, value) {
249
+ const copy = array.slice(0);
250
+ copy[index] = value;
251
+ return copy;
252
+ }
253
+ function timeUntilStale(updatedAt, staleTime) {
254
+ return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0);
255
+ }
256
+ function parseQueryArgs(arg1, arg2, arg3) {
257
+ if (!isQueryKey(arg1)) {
258
+ return arg1;
259
+ }
260
+
261
+ if (typeof arg2 === 'function') {
262
+ return { ...arg3,
263
+ queryKey: arg1,
264
+ queryFn: arg2
265
+ };
266
+ }
267
+
268
+ return { ...arg2,
269
+ queryKey: arg1
270
+ };
271
+ }
272
+ function parseMutationArgs(arg1, arg2, arg3) {
273
+ if (isQueryKey(arg1)) {
274
+ if (typeof arg2 === 'function') {
275
+ return { ...arg3,
276
+ mutationKey: arg1,
277
+ mutationFn: arg2
278
+ };
279
+ }
280
+
281
+ return { ...arg2,
282
+ mutationKey: arg1
283
+ };
284
+ }
285
+
286
+ if (typeof arg1 === 'function') {
287
+ return { ...arg2,
288
+ mutationFn: arg1
289
+ };
290
+ }
291
+
292
+ return { ...arg1
293
+ };
294
+ }
295
+ function parseFilterArgs(arg1, arg2, arg3) {
296
+ return isQueryKey(arg1) ? [{ ...arg2,
297
+ queryKey: arg1
298
+ }, arg3] : [arg1 || {}, arg2];
299
+ }
300
+ function matchQuery(filters, query) {
301
+ const {
302
+ type = 'all',
303
+ exact,
304
+ fetchStatus,
305
+ predicate,
306
+ queryKey,
307
+ stale
308
+ } = filters;
309
+
310
+ if (isQueryKey(queryKey)) {
311
+ if (exact) {
312
+ if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
313
+ return false;
314
+ }
315
+ } else if (!partialMatchKey(query.queryKey, queryKey)) {
316
+ return false;
317
+ }
318
+ }
319
+
320
+ if (type !== 'all') {
321
+ const isActive = query.isActive();
322
+
323
+ if (type === 'active' && !isActive) {
324
+ return false;
325
+ }
326
+
327
+ if (type === 'inactive' && isActive) {
328
+ return false;
329
+ }
330
+ }
331
+
332
+ if (typeof stale === 'boolean' && query.isStale() !== stale) {
333
+ return false;
334
+ }
335
+
336
+ if (typeof fetchStatus !== 'undefined' && fetchStatus !== query.state.fetchStatus) {
337
+ return false;
338
+ }
339
+
340
+ if (predicate && !predicate(query)) {
341
+ return false;
342
+ }
343
+
344
+ return true;
345
+ }
346
+ function matchMutation(filters, mutation) {
347
+ const {
348
+ exact,
349
+ fetching,
350
+ predicate,
351
+ mutationKey
352
+ } = filters;
353
+
354
+ if (isQueryKey(mutationKey)) {
355
+ if (!mutation.options.mutationKey) {
356
+ return false;
357
+ }
358
+
359
+ if (exact) {
360
+ if (hashQueryKey(mutation.options.mutationKey) !== hashQueryKey(mutationKey)) {
361
+ return false;
362
+ }
363
+ } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {
364
+ return false;
365
+ }
366
+ }
367
+
368
+ if (typeof fetching === 'boolean' && mutation.state.status === 'loading' !== fetching) {
369
+ return false;
370
+ }
371
+
372
+ if (predicate && !predicate(mutation)) {
373
+ return false;
374
+ }
375
+
376
+ return true;
377
+ }
378
+ function hashQueryKeyByOptions(queryKey, options) {
379
+ const hashFn = (options == null ? void 0 : options.queryKeyHashFn) || hashQueryKey;
380
+ return hashFn(queryKey);
381
+ }
382
+ /**
383
+ * Default query keys hash function.
384
+ * Hashes the value into a stable hash.
385
+ */
386
+
387
+ function hashQueryKey(queryKey) {
388
+ return JSON.stringify(queryKey, (_, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key) => {
389
+ result[key] = val[key];
390
+ return result;
391
+ }, {}) : val);
392
+ }
393
+ /**
394
+ * Checks if key `b` partially matches with key `a`.
395
+ */
396
+
397
+ function partialMatchKey(a, b) {
398
+ return partialDeepEqual(a, b);
399
+ }
400
+ /**
401
+ * Checks if `b` partially matches with `a`.
402
+ */
403
+
404
+ function partialDeepEqual(a, b) {
405
+ if (a === b) {
406
+ return true;
407
+ }
408
+
409
+ if (typeof a !== typeof b) {
410
+ return false;
411
+ }
412
+
413
+ if (a && b && typeof a === 'object' && typeof b === 'object') {
414
+ return !Object.keys(b).some(key => !partialDeepEqual(a[key], b[key]));
415
+ }
416
+
417
+ return false;
418
+ }
419
+ /**
420
+ * This function returns `a` if `b` is deeply equal.
421
+ * If not, it will replace any deeply equal children of `b` with those of `a`.
422
+ * This can be used for structural sharing between JSON values for example.
423
+ */
424
+
425
+ function replaceEqualDeep(a, b) {
426
+ if (a === b) {
427
+ return a;
428
+ }
429
+
430
+ const array = isPlainArray(a) && isPlainArray(b);
431
+
432
+ if (array || isPlainObject(a) && isPlainObject(b)) {
433
+ const aSize = array ? a.length : Object.keys(a).length;
434
+ const bItems = array ? b : Object.keys(b);
435
+ const bSize = bItems.length;
436
+ const copy = array ? [] : {};
437
+ let equalItems = 0;
438
+
439
+ for (let i = 0; i < bSize; i++) {
440
+ const key = array ? i : bItems[i];
441
+ copy[key] = replaceEqualDeep(a[key], b[key]);
442
+
443
+ if (copy[key] === a[key]) {
444
+ equalItems++;
445
+ }
446
+ }
447
+
448
+ return aSize === bSize && equalItems === aSize ? a : copy;
449
+ }
450
+
451
+ return b;
452
+ }
453
+ /**
454
+ * Shallow compare objects. Only works with objects that always have the same properties.
455
+ */
456
+
457
+ function shallowEqualObjects(a, b) {
458
+ if (a && !b || b && !a) {
459
+ return false;
460
+ }
461
+
462
+ for (const key in a) {
463
+ if (a[key] !== b[key]) {
464
+ return false;
465
+ }
466
+ }
467
+
468
+ return true;
469
+ }
470
+ function isPlainArray(value) {
471
+ return Array.isArray(value) && value.length === Object.keys(value).length;
472
+ } // Copied from: https://github.com/jonschlinkert/is-plain-object
473
+
474
+ function isPlainObject(o) {
475
+ if (!hasObjectPrototype(o)) {
476
+ return false;
477
+ } // If has modified constructor
478
+
479
+
480
+ const ctor = o.constructor;
481
+
482
+ if (typeof ctor === 'undefined') {
483
+ return true;
484
+ } // If has modified prototype
485
+
486
+
487
+ const prot = ctor.prototype;
488
+
489
+ if (!hasObjectPrototype(prot)) {
490
+ return false;
491
+ } // If constructor does not have an Object-specific method
492
+
493
+
494
+ if (!prot.hasOwnProperty('isPrototypeOf')) {
495
+ return false;
496
+ } // Most likely a plain Object
497
+
498
+
499
+ return true;
500
+ }
501
+
502
+ function hasObjectPrototype(o) {
503
+ return Object.prototype.toString.call(o) === '[object Object]';
504
+ }
505
+
506
+ function isQueryKey(value) {
507
+ return Array.isArray(value);
508
+ }
509
+ function sleep$1(timeout) {
510
+ return new Promise(resolve => {
511
+ setTimeout(resolve, timeout);
512
+ });
513
+ }
514
+ /**
515
+ * Schedules a microtask.
516
+ * This can be useful to schedule state updates after rendering.
517
+ */
518
+
519
+ function scheduleMicrotask(callback) {
520
+ sleep$1(0).then(callback);
521
+ }
522
+ function getAbortController() {
523
+ if (typeof AbortController === 'function') {
524
+ return new AbortController();
525
+ }
526
+
527
+ return;
528
+ }
529
+ function replaceData(prevData, data, options) {
530
+ // Use prev data if an isDataEqual function is defined and returns `true`
531
+ if (options.isDataEqual != null && options.isDataEqual(prevData, data)) {
532
+ return prevData;
533
+ } else if (typeof options.structuralSharing === 'function') {
534
+ return options.structuralSharing(prevData, data);
535
+ } else if (options.structuralSharing !== false) {
536
+ // Structurally share data between prev and new data if needed
537
+ return replaceEqualDeep(prevData, data);
538
+ }
539
+
540
+ return data;
541
+ }
542
+
543
+ class FocusManager extends Subscribable {
544
+ constructor() {
545
+ super();
546
+
547
+ this.setup = onFocus => {
548
+ // addEventListener does not exist in React Native, but window does
549
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
550
+ if (!isServer && window.addEventListener) {
551
+ const listener = () => onFocus(); // Listen to visibillitychange and focus
552
+
553
+
554
+ window.addEventListener('visibilitychange', listener, false);
555
+ window.addEventListener('focus', listener, false);
556
+ return () => {
557
+ // Be sure to unsubscribe if a new handler is set
558
+ window.removeEventListener('visibilitychange', listener);
559
+ window.removeEventListener('focus', listener);
560
+ };
561
+ }
562
+
563
+ return;
564
+ };
565
+ }
566
+
567
+ onSubscribe() {
568
+ if (!this.cleanup) {
569
+ this.setEventListener(this.setup);
570
+ }
571
+ }
572
+
573
+ onUnsubscribe() {
574
+ if (!this.hasListeners()) {
575
+ var _this$cleanup;
576
+
577
+ (_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
578
+ this.cleanup = undefined;
579
+ }
580
+ }
581
+
582
+ setEventListener(setup) {
583
+ var _this$cleanup2;
584
+
585
+ this.setup = setup;
586
+ (_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
587
+ this.cleanup = setup(focused => {
588
+ if (typeof focused === 'boolean') {
589
+ this.setFocused(focused);
590
+ } else {
591
+ this.onFocus();
592
+ }
593
+ });
594
+ }
595
+
596
+ setFocused(focused) {
597
+ const changed = this.focused !== focused;
598
+
599
+ if (changed) {
600
+ this.focused = focused;
601
+ this.onFocus();
602
+ }
603
+ }
604
+
605
+ onFocus() {
606
+ this.listeners.forEach(({
607
+ listener
608
+ }) => {
609
+ listener();
610
+ });
611
+ }
612
+
613
+ isFocused() {
614
+ if (typeof this.focused === 'boolean') {
615
+ return this.focused;
616
+ } // document global can be unavailable in react native
617
+
618
+
619
+ if (typeof document === 'undefined') {
620
+ return true;
621
+ }
622
+
623
+ return [undefined, 'visible', 'prerender'].includes(document.visibilityState);
624
+ }
625
+
626
+ }
627
+ const focusManager = new FocusManager();
628
+
629
+ const onlineEvents = ['online', 'offline'];
630
+ class OnlineManager extends Subscribable {
631
+ constructor() {
632
+ super();
633
+
634
+ this.setup = onOnline => {
635
+ // addEventListener does not exist in React Native, but window does
636
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
637
+ if (!isServer && window.addEventListener) {
638
+ const listener = () => onOnline(); // Listen to online
639
+
640
+
641
+ onlineEvents.forEach(event => {
642
+ window.addEventListener(event, listener, false);
643
+ });
644
+ return () => {
645
+ // Be sure to unsubscribe if a new handler is set
646
+ onlineEvents.forEach(event => {
647
+ window.removeEventListener(event, listener);
648
+ });
649
+ };
650
+ }
651
+
652
+ return;
653
+ };
654
+ }
655
+
656
+ onSubscribe() {
657
+ if (!this.cleanup) {
658
+ this.setEventListener(this.setup);
659
+ }
660
+ }
661
+
662
+ onUnsubscribe() {
663
+ if (!this.hasListeners()) {
664
+ var _this$cleanup;
665
+
666
+ (_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
667
+ this.cleanup = undefined;
668
+ }
669
+ }
670
+
671
+ setEventListener(setup) {
672
+ var _this$cleanup2;
673
+
674
+ this.setup = setup;
675
+ (_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
676
+ this.cleanup = setup(online => {
677
+ if (typeof online === 'boolean') {
678
+ this.setOnline(online);
679
+ } else {
680
+ this.onOnline();
681
+ }
682
+ });
683
+ }
684
+
685
+ setOnline(online) {
686
+ const changed = this.online !== online;
687
+
688
+ if (changed) {
689
+ this.online = online;
690
+ this.onOnline();
691
+ }
692
+ }
693
+
694
+ onOnline() {
695
+ this.listeners.forEach(({
696
+ listener
697
+ }) => {
698
+ listener();
699
+ });
700
+ }
701
+
702
+ isOnline() {
703
+ if (typeof this.online === 'boolean') {
704
+ return this.online;
705
+ }
706
+
707
+ if (typeof navigator === 'undefined' || typeof navigator.onLine === 'undefined') {
708
+ return true;
709
+ }
710
+
711
+ return navigator.onLine;
712
+ }
713
+
714
+ }
715
+ const onlineManager = new OnlineManager();
716
+
717
+ function defaultRetryDelay(failureCount) {
718
+ return Math.min(1000 * 2 ** failureCount, 30000);
719
+ }
720
+
721
+ function canFetch(networkMode) {
722
+ return (networkMode != null ? networkMode : 'online') === 'online' ? onlineManager.isOnline() : true;
723
+ }
724
+ class CancelledError {
725
+ constructor(options) {
726
+ this.revert = options == null ? void 0 : options.revert;
727
+ this.silent = options == null ? void 0 : options.silent;
728
+ }
729
+
730
+ }
731
+ function isCancelledError(value) {
732
+ return value instanceof CancelledError;
733
+ }
734
+ function createRetryer(config) {
735
+ let isRetryCancelled = false;
736
+ let failureCount = 0;
737
+ let isResolved = false;
738
+ let continueFn;
739
+ let promiseResolve;
740
+ let promiseReject;
741
+ const promise = new Promise((outerResolve, outerReject) => {
742
+ promiseResolve = outerResolve;
743
+ promiseReject = outerReject;
744
+ });
745
+
746
+ const cancel = cancelOptions => {
747
+ if (!isResolved) {
748
+ reject(new CancelledError(cancelOptions));
749
+ config.abort == null ? void 0 : config.abort();
750
+ }
751
+ };
752
+
753
+ const cancelRetry = () => {
754
+ isRetryCancelled = true;
755
+ };
756
+
757
+ const continueRetry = () => {
758
+ isRetryCancelled = false;
759
+ };
760
+
761
+ const shouldPause = () => !focusManager.isFocused() || config.networkMode !== 'always' && !onlineManager.isOnline();
762
+
763
+ const resolve = value => {
764
+ if (!isResolved) {
765
+ isResolved = true;
766
+ config.onSuccess == null ? void 0 : config.onSuccess(value);
767
+ continueFn == null ? void 0 : continueFn();
768
+ promiseResolve(value);
769
+ }
770
+ };
771
+
772
+ const reject = value => {
773
+ if (!isResolved) {
774
+ isResolved = true;
775
+ config.onError == null ? void 0 : config.onError(value);
776
+ continueFn == null ? void 0 : continueFn();
777
+ promiseReject(value);
778
+ }
779
+ };
780
+
781
+ const pause = () => {
782
+ return new Promise(continueResolve => {
783
+ continueFn = value => {
784
+ const canContinue = isResolved || !shouldPause();
785
+
786
+ if (canContinue) {
787
+ continueResolve(value);
788
+ }
789
+
790
+ return canContinue;
791
+ };
792
+
793
+ config.onPause == null ? void 0 : config.onPause();
794
+ }).then(() => {
795
+ continueFn = undefined;
796
+
797
+ if (!isResolved) {
798
+ config.onContinue == null ? void 0 : config.onContinue();
799
+ }
800
+ });
801
+ }; // Create loop function
802
+
803
+
804
+ const run = () => {
805
+ // Do nothing if already resolved
806
+ if (isResolved) {
807
+ return;
808
+ }
809
+
810
+ let promiseOrValue; // Execute query
811
+
812
+ try {
813
+ promiseOrValue = config.fn();
814
+ } catch (error) {
815
+ promiseOrValue = Promise.reject(error);
816
+ }
817
+
818
+ Promise.resolve(promiseOrValue).then(resolve).catch(error => {
819
+ var _config$retry, _config$retryDelay;
820
+
821
+ // Stop if the fetch is already resolved
822
+ if (isResolved) {
823
+ return;
824
+ } // Do we need to retry the request?
825
+
826
+
827
+ const retry = (_config$retry = config.retry) != null ? _config$retry : 3;
828
+ const retryDelay = (_config$retryDelay = config.retryDelay) != null ? _config$retryDelay : defaultRetryDelay;
829
+ const delay = typeof retryDelay === 'function' ? retryDelay(failureCount, error) : retryDelay;
830
+ const shouldRetry = retry === true || typeof retry === 'number' && failureCount < retry || typeof retry === 'function' && retry(failureCount, error);
831
+
832
+ if (isRetryCancelled || !shouldRetry) {
833
+ // We are done if the query does not need to be retried
834
+ reject(error);
835
+ return;
836
+ }
837
+
838
+ failureCount++; // Notify on fail
839
+
840
+ config.onFail == null ? void 0 : config.onFail(failureCount, error); // Delay
841
+
842
+ sleep$1(delay) // Pause if the document is not visible or when the device is offline
843
+ .then(() => {
844
+ if (shouldPause()) {
845
+ return pause();
846
+ }
847
+
848
+ return;
849
+ }).then(() => {
850
+ if (isRetryCancelled) {
851
+ reject(error);
852
+ } else {
853
+ run();
854
+ }
855
+ });
856
+ });
857
+ }; // Start loop
858
+
859
+
860
+ if (canFetch(config.networkMode)) {
861
+ run();
862
+ } else {
863
+ pause().then(run);
864
+ }
865
+
866
+ return {
867
+ promise,
868
+ cancel,
869
+ continue: () => {
870
+ const didContinue = continueFn == null ? void 0 : continueFn();
871
+ return didContinue ? promise : Promise.resolve();
872
+ },
873
+ cancelRetry,
874
+ continueRetry
875
+ };
876
+ }
877
+
878
+ const defaultLogger = console;
879
+
880
+ function createNotifyManager() {
881
+ let queue = [];
882
+ let transactions = 0;
883
+
884
+ let notifyFn = callback => {
885
+ callback();
886
+ };
887
+
888
+ let batchNotifyFn = callback => {
889
+ callback();
890
+ };
891
+
892
+ const batch = callback => {
893
+ let result;
894
+ transactions++;
895
+
896
+ try {
897
+ result = callback();
898
+ } finally {
899
+ transactions--;
900
+
901
+ if (!transactions) {
902
+ flush();
903
+ }
904
+ }
905
+
906
+ return result;
907
+ };
908
+
909
+ const schedule = callback => {
910
+ if (transactions) {
911
+ queue.push(callback);
912
+ } else {
913
+ scheduleMicrotask(() => {
914
+ notifyFn(callback);
915
+ });
916
+ }
917
+ };
918
+ /**
919
+ * All calls to the wrapped function will be batched.
920
+ */
921
+
922
+
923
+ const batchCalls = callback => {
924
+ return (...args) => {
925
+ schedule(() => {
926
+ callback(...args);
927
+ });
928
+ };
929
+ };
930
+
931
+ const flush = () => {
932
+ const originalQueue = queue;
933
+ queue = [];
934
+
935
+ if (originalQueue.length) {
936
+ scheduleMicrotask(() => {
937
+ batchNotifyFn(() => {
938
+ originalQueue.forEach(callback => {
939
+ notifyFn(callback);
940
+ });
941
+ });
942
+ });
943
+ }
944
+ };
945
+ /**
946
+ * Use this method to set a custom notify function.
947
+ * This can be used to for example wrap notifications with `React.act` while running tests.
948
+ */
949
+
950
+
951
+ const setNotifyFunction = fn => {
952
+ notifyFn = fn;
953
+ };
954
+ /**
955
+ * Use this method to set a custom function to batch notifications together into a single tick.
956
+ * By default React Query will use the batch function provided by ReactDOM or React Native.
957
+ */
958
+
959
+
960
+ const setBatchNotifyFunction = fn => {
961
+ batchNotifyFn = fn;
962
+ };
963
+
964
+ return {
965
+ batch,
966
+ batchCalls,
967
+ schedule,
968
+ setNotifyFunction,
969
+ setBatchNotifyFunction
970
+ };
971
+ } // SINGLETON
972
+
973
+ const notifyManager = createNotifyManager();
974
+
975
+ class Removable {
976
+ destroy() {
977
+ this.clearGcTimeout();
978
+ }
979
+
980
+ scheduleGc() {
981
+ this.clearGcTimeout();
982
+
983
+ if (isValidTimeout(this.cacheTime)) {
984
+ this.gcTimeout = setTimeout(() => {
985
+ this.optionalRemove();
986
+ }, this.cacheTime);
987
+ }
988
+ }
989
+
990
+ updateCacheTime(newCacheTime) {
991
+ // Default to 5 minutes (Infinity for server-side) if no cache time is set
992
+ this.cacheTime = Math.max(this.cacheTime || 0, newCacheTime != null ? newCacheTime : isServer ? Infinity : 5 * 60 * 1000);
993
+ }
994
+
995
+ clearGcTimeout() {
996
+ if (this.gcTimeout) {
997
+ clearTimeout(this.gcTimeout);
998
+ this.gcTimeout = undefined;
999
+ }
1000
+ }
1001
+
1002
+ }
1003
+
1004
+ // CLASS
1005
+ class Query extends Removable {
1006
+ constructor(config) {
1007
+ super();
1008
+ this.abortSignalConsumed = false;
1009
+ this.defaultOptions = config.defaultOptions;
1010
+ this.setOptions(config.options);
1011
+ this.observers = [];
1012
+ this.cache = config.cache;
1013
+ this.logger = config.logger || defaultLogger;
1014
+ this.queryKey = config.queryKey;
1015
+ this.queryHash = config.queryHash;
1016
+ this.initialState = config.state || getDefaultState$1(this.options);
1017
+ this.state = this.initialState;
1018
+ this.scheduleGc();
1019
+ }
1020
+
1021
+ get meta() {
1022
+ return this.options.meta;
1023
+ }
1024
+
1025
+ setOptions(options) {
1026
+ this.options = { ...this.defaultOptions,
1027
+ ...options
1028
+ };
1029
+ this.updateCacheTime(this.options.cacheTime);
1030
+ }
1031
+
1032
+ optionalRemove() {
1033
+ if (!this.observers.length && this.state.fetchStatus === 'idle') {
1034
+ this.cache.remove(this);
1035
+ }
1036
+ }
1037
+
1038
+ setData(newData, options) {
1039
+ const data = replaceData(this.state.data, newData, this.options); // Set data and mark it as cached
1040
+
1041
+ this.dispatch({
1042
+ data,
1043
+ type: 'success',
1044
+ dataUpdatedAt: options == null ? void 0 : options.updatedAt,
1045
+ manual: options == null ? void 0 : options.manual
1046
+ });
1047
+ return data;
1048
+ }
1049
+
1050
+ setState(state, setStateOptions) {
1051
+ this.dispatch({
1052
+ type: 'setState',
1053
+ state,
1054
+ setStateOptions
1055
+ });
1056
+ }
1057
+
1058
+ cancel(options) {
1059
+ var _this$retryer;
1060
+
1061
+ const promise = this.promise;
1062
+ (_this$retryer = this.retryer) == null ? void 0 : _this$retryer.cancel(options);
1063
+ return promise ? promise.then(noop$1).catch(noop$1) : Promise.resolve();
1064
+ }
1065
+
1066
+ destroy() {
1067
+ super.destroy();
1068
+ this.cancel({
1069
+ silent: true
1070
+ });
1071
+ }
1072
+
1073
+ reset() {
1074
+ this.destroy();
1075
+ this.setState(this.initialState);
1076
+ }
1077
+
1078
+ isActive() {
1079
+ return this.observers.some(observer => observer.options.enabled !== false);
1080
+ }
1081
+
1082
+ isDisabled() {
1083
+ return this.getObserversCount() > 0 && !this.isActive();
1084
+ }
1085
+
1086
+ isStale() {
1087
+ return this.state.isInvalidated || !this.state.dataUpdatedAt || this.observers.some(observer => observer.getCurrentResult().isStale);
1088
+ }
1089
+
1090
+ isStaleByTime(staleTime = 0) {
1091
+ return this.state.isInvalidated || !this.state.dataUpdatedAt || !timeUntilStale(this.state.dataUpdatedAt, staleTime);
1092
+ }
1093
+
1094
+ onFocus() {
1095
+ var _this$retryer2;
1096
+
1097
+ const observer = this.observers.find(x => x.shouldFetchOnWindowFocus());
1098
+
1099
+ if (observer) {
1100
+ observer.refetch({
1101
+ cancelRefetch: false
1102
+ });
1103
+ } // Continue fetch if currently paused
1104
+
1105
+
1106
+ (_this$retryer2 = this.retryer) == null ? void 0 : _this$retryer2.continue();
1107
+ }
1108
+
1109
+ onOnline() {
1110
+ var _this$retryer3;
1111
+
1112
+ const observer = this.observers.find(x => x.shouldFetchOnReconnect());
1113
+
1114
+ if (observer) {
1115
+ observer.refetch({
1116
+ cancelRefetch: false
1117
+ });
1118
+ } // Continue fetch if currently paused
1119
+
1120
+
1121
+ (_this$retryer3 = this.retryer) == null ? void 0 : _this$retryer3.continue();
1122
+ }
1123
+
1124
+ addObserver(observer) {
1125
+ if (!this.observers.includes(observer)) {
1126
+ this.observers.push(observer); // Stop the query from being garbage collected
1127
+
1128
+ this.clearGcTimeout();
1129
+ this.cache.notify({
1130
+ type: 'observerAdded',
1131
+ query: this,
1132
+ observer
1133
+ });
1134
+ }
1135
+ }
1136
+
1137
+ removeObserver(observer) {
1138
+ if (this.observers.includes(observer)) {
1139
+ this.observers = this.observers.filter(x => x !== observer);
1140
+
1141
+ if (!this.observers.length) {
1142
+ // If the transport layer does not support cancellation
1143
+ // we'll let the query continue so the result can be cached
1144
+ if (this.retryer) {
1145
+ if (this.abortSignalConsumed) {
1146
+ this.retryer.cancel({
1147
+ revert: true
1148
+ });
1149
+ } else {
1150
+ this.retryer.cancelRetry();
1151
+ }
1152
+ }
1153
+
1154
+ this.scheduleGc();
1155
+ }
1156
+
1157
+ this.cache.notify({
1158
+ type: 'observerRemoved',
1159
+ query: this,
1160
+ observer
1161
+ });
1162
+ }
1163
+ }
1164
+
1165
+ getObserversCount() {
1166
+ return this.observers.length;
1167
+ }
1168
+
1169
+ invalidate() {
1170
+ if (!this.state.isInvalidated) {
1171
+ this.dispatch({
1172
+ type: 'invalidate'
1173
+ });
1174
+ }
1175
+ }
1176
+
1177
+ fetch(options, fetchOptions) {
1178
+ var _this$options$behavio, _context$fetchOptions;
1179
+
1180
+ if (this.state.fetchStatus !== 'idle') {
1181
+ if (this.state.dataUpdatedAt && fetchOptions != null && fetchOptions.cancelRefetch) {
1182
+ // Silently cancel current fetch if the user wants to cancel refetches
1183
+ this.cancel({
1184
+ silent: true
1185
+ });
1186
+ } else if (this.promise) {
1187
+ var _this$retryer4;
1188
+
1189
+ // make sure that retries that were potentially cancelled due to unmounts can continue
1190
+ (_this$retryer4 = this.retryer) == null ? void 0 : _this$retryer4.continueRetry(); // Return current promise if we are already fetching
1191
+
1192
+ return this.promise;
1193
+ }
1194
+ } // Update config if passed, otherwise the config from the last execution is used
1195
+
1196
+
1197
+ if (options) {
1198
+ this.setOptions(options);
1199
+ } // Use the options from the first observer with a query function if no function is found.
1200
+ // This can happen when the query is hydrated or created with setQueryData.
1201
+
1202
+
1203
+ if (!this.options.queryFn) {
1204
+ const observer = this.observers.find(x => x.options.queryFn);
1205
+
1206
+ if (observer) {
1207
+ this.setOptions(observer.options);
1208
+ }
1209
+ }
1210
+
1211
+ if (process.env.NODE_ENV !== 'production') {
1212
+ if (!Array.isArray(this.options.queryKey)) {
1213
+ 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']");
1214
+ }
1215
+ }
1216
+
1217
+ const abortController = getAbortController(); // Create query function context
1218
+
1219
+ const queryFnContext = {
1220
+ queryKey: this.queryKey,
1221
+ pageParam: undefined,
1222
+ meta: this.meta
1223
+ }; // Adds an enumerable signal property to the object that
1224
+ // which sets abortSignalConsumed to true when the signal
1225
+ // is read.
1226
+
1227
+ const addSignalProperty = object => {
1228
+ Object.defineProperty(object, 'signal', {
1229
+ enumerable: true,
1230
+ get: () => {
1231
+ if (abortController) {
1232
+ this.abortSignalConsumed = true;
1233
+ return abortController.signal;
1234
+ }
1235
+
1236
+ return undefined;
1237
+ }
1238
+ });
1239
+ };
1240
+
1241
+ addSignalProperty(queryFnContext); // Create fetch function
1242
+
1243
+ const fetchFn = () => {
1244
+ if (!this.options.queryFn) {
1245
+ return Promise.reject("Missing queryFn for queryKey '" + this.options.queryHash + "'");
1246
+ }
1247
+
1248
+ this.abortSignalConsumed = false;
1249
+ return this.options.queryFn(queryFnContext);
1250
+ }; // Trigger behavior hook
1251
+
1252
+
1253
+ const context = {
1254
+ fetchOptions,
1255
+ options: this.options,
1256
+ queryKey: this.queryKey,
1257
+ state: this.state,
1258
+ fetchFn
1259
+ };
1260
+ addSignalProperty(context);
1261
+ (_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
1262
+
1263
+ this.revertState = this.state; // Set to fetching state if not already in it
1264
+
1265
+ if (this.state.fetchStatus === 'idle' || this.state.fetchMeta !== ((_context$fetchOptions = context.fetchOptions) == null ? void 0 : _context$fetchOptions.meta)) {
1266
+ var _context$fetchOptions2;
1267
+
1268
+ this.dispatch({
1269
+ type: 'fetch',
1270
+ meta: (_context$fetchOptions2 = context.fetchOptions) == null ? void 0 : _context$fetchOptions2.meta
1271
+ });
1272
+ }
1273
+
1274
+ const onError = error => {
1275
+ // Optimistically update state if needed
1276
+ if (!(isCancelledError(error) && error.silent)) {
1277
+ this.dispatch({
1278
+ type: 'error',
1279
+ error: error
1280
+ });
1281
+ }
1282
+
1283
+ if (!isCancelledError(error)) {
1284
+ var _this$cache$config$on, _this$cache$config, _this$cache$config$on2, _this$cache$config2;
1285
+
1286
+ // Notify cache callback
1287
+ (_this$cache$config$on = (_this$cache$config = this.cache.config).onError) == null ? void 0 : _this$cache$config$on.call(_this$cache$config, error, this);
1288
+ (_this$cache$config$on2 = (_this$cache$config2 = this.cache.config).onSettled) == null ? void 0 : _this$cache$config$on2.call(_this$cache$config2, this.state.data, error, this);
1289
+
1290
+ if (process.env.NODE_ENV !== 'production') {
1291
+ this.logger.error(error);
1292
+ }
1293
+ }
1294
+
1295
+ if (!this.isFetchingOptimistic) {
1296
+ // Schedule query gc after fetching
1297
+ this.scheduleGc();
1298
+ }
1299
+
1300
+ this.isFetchingOptimistic = false;
1301
+ }; // Try to fetch the data
1302
+
1303
+
1304
+ this.retryer = createRetryer({
1305
+ fn: context.fetchFn,
1306
+ abort: abortController == null ? void 0 : abortController.abort.bind(abortController),
1307
+ onSuccess: data => {
1308
+ var _this$cache$config$on3, _this$cache$config3, _this$cache$config$on4, _this$cache$config4;
1309
+
1310
+ if (typeof data === 'undefined') {
1311
+ if (process.env.NODE_ENV !== 'production') {
1312
+ this.logger.error("Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: " + this.queryHash);
1313
+ }
1314
+
1315
+ onError(new Error(this.queryHash + " data is undefined"));
1316
+ return;
1317
+ }
1318
+
1319
+ this.setData(data); // Notify cache callback
1320
+
1321
+ (_this$cache$config$on3 = (_this$cache$config3 = this.cache.config).onSuccess) == null ? void 0 : _this$cache$config$on3.call(_this$cache$config3, data, this);
1322
+ (_this$cache$config$on4 = (_this$cache$config4 = this.cache.config).onSettled) == null ? void 0 : _this$cache$config$on4.call(_this$cache$config4, data, this.state.error, this);
1323
+
1324
+ if (!this.isFetchingOptimistic) {
1325
+ // Schedule query gc after fetching
1326
+ this.scheduleGc();
1327
+ }
1328
+
1329
+ this.isFetchingOptimistic = false;
1330
+ },
1331
+ onError,
1332
+ onFail: (failureCount, error) => {
1333
+ this.dispatch({
1334
+ type: 'failed',
1335
+ failureCount,
1336
+ error
1337
+ });
1338
+ },
1339
+ onPause: () => {
1340
+ this.dispatch({
1341
+ type: 'pause'
1342
+ });
1343
+ },
1344
+ onContinue: () => {
1345
+ this.dispatch({
1346
+ type: 'continue'
1347
+ });
1348
+ },
1349
+ retry: context.options.retry,
1350
+ retryDelay: context.options.retryDelay,
1351
+ networkMode: context.options.networkMode
1352
+ });
1353
+ this.promise = this.retryer.promise;
1354
+ return this.promise;
1355
+ }
1356
+
1357
+ dispatch(action) {
1358
+ const reducer = state => {
1359
+ var _action$meta, _action$dataUpdatedAt;
1360
+
1361
+ switch (action.type) {
1362
+ case 'failed':
1363
+ return { ...state,
1364
+ fetchFailureCount: action.failureCount,
1365
+ fetchFailureReason: action.error
1366
+ };
1367
+
1368
+ case 'pause':
1369
+ return { ...state,
1370
+ fetchStatus: 'paused'
1371
+ };
1372
+
1373
+ case 'continue':
1374
+ return { ...state,
1375
+ fetchStatus: 'fetching'
1376
+ };
1377
+
1378
+ case 'fetch':
1379
+ return { ...state,
1380
+ fetchFailureCount: 0,
1381
+ fetchFailureReason: null,
1382
+ fetchMeta: (_action$meta = action.meta) != null ? _action$meta : null,
1383
+ fetchStatus: canFetch(this.options.networkMode) ? 'fetching' : 'paused',
1384
+ ...(!state.dataUpdatedAt && {
1385
+ error: null,
1386
+ status: 'loading'
1387
+ })
1388
+ };
1389
+
1390
+ case 'success':
1391
+ return { ...state,
1392
+ data: action.data,
1393
+ dataUpdateCount: state.dataUpdateCount + 1,
1394
+ dataUpdatedAt: (_action$dataUpdatedAt = action.dataUpdatedAt) != null ? _action$dataUpdatedAt : Date.now(),
1395
+ error: null,
1396
+ isInvalidated: false,
1397
+ status: 'success',
1398
+ ...(!action.manual && {
1399
+ fetchStatus: 'idle',
1400
+ fetchFailureCount: 0,
1401
+ fetchFailureReason: null
1402
+ })
1403
+ };
1404
+
1405
+ case 'error':
1406
+ const error = action.error;
1407
+
1408
+ if (isCancelledError(error) && error.revert && this.revertState) {
1409
+ return { ...this.revertState,
1410
+ fetchStatus: 'idle'
1411
+ };
1412
+ }
1413
+
1414
+ return { ...state,
1415
+ error: error,
1416
+ errorUpdateCount: state.errorUpdateCount + 1,
1417
+ errorUpdatedAt: Date.now(),
1418
+ fetchFailureCount: state.fetchFailureCount + 1,
1419
+ fetchFailureReason: error,
1420
+ fetchStatus: 'idle',
1421
+ status: 'error'
1422
+ };
1423
+
1424
+ case 'invalidate':
1425
+ return { ...state,
1426
+ isInvalidated: true
1427
+ };
1428
+
1429
+ case 'setState':
1430
+ return { ...state,
1431
+ ...action.state
1432
+ };
1433
+ }
1434
+ };
1435
+
1436
+ this.state = reducer(this.state);
1437
+ notifyManager.batch(() => {
1438
+ this.observers.forEach(observer => {
1439
+ observer.onQueryUpdate(action);
1440
+ });
1441
+ this.cache.notify({
1442
+ query: this,
1443
+ type: 'updated',
1444
+ action
1445
+ });
1446
+ });
1447
+ }
1448
+
1449
+ }
1450
+
1451
+ function getDefaultState$1(options) {
1452
+ const data = typeof options.initialData === 'function' ? options.initialData() : options.initialData;
1453
+ const hasData = typeof data !== 'undefined';
1454
+ const initialDataUpdatedAt = hasData ? typeof options.initialDataUpdatedAt === 'function' ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;
1455
+ return {
1456
+ data,
1457
+ dataUpdateCount: 0,
1458
+ dataUpdatedAt: hasData ? initialDataUpdatedAt != null ? initialDataUpdatedAt : Date.now() : 0,
1459
+ error: null,
1460
+ errorUpdateCount: 0,
1461
+ errorUpdatedAt: 0,
1462
+ fetchFailureCount: 0,
1463
+ fetchFailureReason: null,
1464
+ fetchMeta: null,
1465
+ isInvalidated: false,
1466
+ status: hasData ? 'success' : 'loading',
1467
+ fetchStatus: 'idle'
1468
+ };
1469
+ }
1470
+
1471
+ // CLASS
1472
+ class QueryCache extends Subscribable {
1473
+ constructor(config) {
1474
+ super();
1475
+ this.config = config || {};
1476
+ this.queries = [];
1477
+ this.queriesMap = {};
1478
+ }
1479
+
1480
+ build(client, options, state) {
1481
+ var _options$queryHash;
1482
+
1483
+ const queryKey = options.queryKey;
1484
+ const queryHash = (_options$queryHash = options.queryHash) != null ? _options$queryHash : hashQueryKeyByOptions(queryKey, options);
1485
+ let query = this.get(queryHash);
1486
+
1487
+ if (!query) {
1488
+ query = new Query({
1489
+ cache: this,
1490
+ logger: client.getLogger(),
1491
+ queryKey,
1492
+ queryHash,
1493
+ options: client.defaultQueryOptions(options),
1494
+ state,
1495
+ defaultOptions: client.getQueryDefaults(queryKey)
1496
+ });
1497
+ this.add(query);
1498
+ }
1499
+
1500
+ return query;
1501
+ }
1502
+
1503
+ add(query) {
1504
+ if (!this.queriesMap[query.queryHash]) {
1505
+ this.queriesMap[query.queryHash] = query;
1506
+ this.queries.push(query);
1507
+ this.notify({
1508
+ type: 'added',
1509
+ query
1510
+ });
1511
+ }
1512
+ }
1513
+
1514
+ remove(query) {
1515
+ const queryInMap = this.queriesMap[query.queryHash];
1516
+
1517
+ if (queryInMap) {
1518
+ query.destroy();
1519
+ this.queries = this.queries.filter(x => x !== query);
1520
+
1521
+ if (queryInMap === query) {
1522
+ delete this.queriesMap[query.queryHash];
1523
+ }
1524
+
1525
+ this.notify({
1526
+ type: 'removed',
1527
+ query
1528
+ });
1529
+ }
1530
+ }
1531
+
1532
+ clear() {
1533
+ notifyManager.batch(() => {
1534
+ this.queries.forEach(query => {
1535
+ this.remove(query);
1536
+ });
1537
+ });
1538
+ }
1539
+
1540
+ get(queryHash) {
1541
+ return this.queriesMap[queryHash];
1542
+ }
1543
+
1544
+ getAll() {
1545
+ return this.queries;
1546
+ }
1547
+
1548
+ find(arg1, arg2) {
1549
+ const [filters] = parseFilterArgs(arg1, arg2);
1550
+
1551
+ if (typeof filters.exact === 'undefined') {
1552
+ filters.exact = true;
1553
+ }
1554
+
1555
+ return this.queries.find(query => matchQuery(filters, query));
1556
+ }
1557
+
1558
+ findAll(arg1, arg2) {
1559
+ const [filters] = parseFilterArgs(arg1, arg2);
1560
+ return Object.keys(filters).length > 0 ? this.queries.filter(query => matchQuery(filters, query)) : this.queries;
1561
+ }
1562
+
1563
+ notify(event) {
1564
+ notifyManager.batch(() => {
1565
+ this.listeners.forEach(({
1566
+ listener
1567
+ }) => {
1568
+ listener(event);
1569
+ });
1570
+ });
1571
+ }
1572
+
1573
+ onFocus() {
1574
+ notifyManager.batch(() => {
1575
+ this.queries.forEach(query => {
1576
+ query.onFocus();
1577
+ });
1578
+ });
1579
+ }
1580
+
1581
+ onOnline() {
1582
+ notifyManager.batch(() => {
1583
+ this.queries.forEach(query => {
1584
+ query.onOnline();
1585
+ });
1586
+ });
1587
+ }
1588
+
1589
+ }
1590
+
1591
+ // CLASS
1592
+ class Mutation extends Removable {
1593
+ constructor(config) {
1594
+ super();
1595
+ this.defaultOptions = config.defaultOptions;
1596
+ this.mutationId = config.mutationId;
1597
+ this.mutationCache = config.mutationCache;
1598
+ this.logger = config.logger || defaultLogger;
1599
+ this.observers = [];
1600
+ this.state = config.state || getDefaultState();
1601
+ this.setOptions(config.options);
1602
+ this.scheduleGc();
1603
+ }
1604
+
1605
+ setOptions(options) {
1606
+ this.options = { ...this.defaultOptions,
1607
+ ...options
1608
+ };
1609
+ this.updateCacheTime(this.options.cacheTime);
1610
+ }
1611
+
1612
+ get meta() {
1613
+ return this.options.meta;
1614
+ }
1615
+
1616
+ setState(state) {
1617
+ this.dispatch({
1618
+ type: 'setState',
1619
+ state
1620
+ });
1621
+ }
1622
+
1623
+ addObserver(observer) {
1624
+ if (!this.observers.includes(observer)) {
1625
+ this.observers.push(observer); // Stop the mutation from being garbage collected
1626
+
1627
+ this.clearGcTimeout();
1628
+ this.mutationCache.notify({
1629
+ type: 'observerAdded',
1630
+ mutation: this,
1631
+ observer
1632
+ });
1633
+ }
1634
+ }
1635
+
1636
+ removeObserver(observer) {
1637
+ this.observers = this.observers.filter(x => x !== observer);
1638
+ this.scheduleGc();
1639
+ this.mutationCache.notify({
1640
+ type: 'observerRemoved',
1641
+ mutation: this,
1642
+ observer
1643
+ });
1644
+ }
1645
+
1646
+ optionalRemove() {
1647
+ if (!this.observers.length) {
1648
+ if (this.state.status === 'loading') {
1649
+ this.scheduleGc();
1650
+ } else {
1651
+ this.mutationCache.remove(this);
1652
+ }
1653
+ }
1654
+ }
1655
+
1656
+ continue() {
1657
+ var _this$retryer$continu, _this$retryer;
1658
+
1659
+ return (_this$retryer$continu = (_this$retryer = this.retryer) == null ? void 0 : _this$retryer.continue()) != null ? _this$retryer$continu : this.execute();
1660
+ }
1661
+
1662
+ async execute() {
1663
+ const executeMutation = () => {
1664
+ var _this$options$retry;
1665
+
1666
+ this.retryer = createRetryer({
1667
+ fn: () => {
1668
+ if (!this.options.mutationFn) {
1669
+ return Promise.reject('No mutationFn found');
1670
+ }
1671
+
1672
+ return this.options.mutationFn(this.state.variables);
1673
+ },
1674
+ onFail: (failureCount, error) => {
1675
+ this.dispatch({
1676
+ type: 'failed',
1677
+ failureCount,
1678
+ error
1679
+ });
1680
+ },
1681
+ onPause: () => {
1682
+ this.dispatch({
1683
+ type: 'pause'
1684
+ });
1685
+ },
1686
+ onContinue: () => {
1687
+ this.dispatch({
1688
+ type: 'continue'
1689
+ });
1690
+ },
1691
+ retry: (_this$options$retry = this.options.retry) != null ? _this$options$retry : 0,
1692
+ retryDelay: this.options.retryDelay,
1693
+ networkMode: this.options.networkMode
1694
+ });
1695
+ return this.retryer.promise;
1696
+ };
1697
+
1698
+ const restored = this.state.status === 'loading';
1699
+
1700
+ try {
1701
+ var _this$mutationCache$c3, _this$mutationCache$c4, _this$options$onSucce, _this$options2, _this$mutationCache$c5, _this$mutationCache$c6, _this$options$onSettl, _this$options3;
1702
+
1703
+ if (!restored) {
1704
+ var _this$mutationCache$c, _this$mutationCache$c2, _this$options$onMutat, _this$options;
1705
+
1706
+ this.dispatch({
1707
+ type: 'loading',
1708
+ variables: this.options.variables
1709
+ }); // Notify cache callback
1710
+
1711
+ await ((_this$mutationCache$c = (_this$mutationCache$c2 = this.mutationCache.config).onMutate) == null ? void 0 : _this$mutationCache$c.call(_this$mutationCache$c2, this.state.variables, this));
1712
+ const context = await ((_this$options$onMutat = (_this$options = this.options).onMutate) == null ? void 0 : _this$options$onMutat.call(_this$options, this.state.variables));
1713
+
1714
+ if (context !== this.state.context) {
1715
+ this.dispatch({
1716
+ type: 'loading',
1717
+ context,
1718
+ variables: this.state.variables
1719
+ });
1720
+ }
1721
+ }
1722
+
1723
+ const data = await executeMutation(); // Notify cache callback
1724
+
1725
+ await ((_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));
1726
+ 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)); // Notify cache callback
1727
+
1728
+ await ((_this$mutationCache$c5 = (_this$mutationCache$c6 = this.mutationCache.config).onSettled) == null ? void 0 : _this$mutationCache$c5.call(_this$mutationCache$c6, data, null, this.state.variables, this.state.context, this));
1729
+ 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));
1730
+ this.dispatch({
1731
+ type: 'success',
1732
+ data
1733
+ });
1734
+ return data;
1735
+ } catch (error) {
1736
+ try {
1737
+ var _this$mutationCache$c7, _this$mutationCache$c8, _this$options$onError, _this$options4, _this$mutationCache$c9, _this$mutationCache$c10, _this$options$onSettl2, _this$options5;
1738
+
1739
+ // Notify cache callback
1740
+ await ((_this$mutationCache$c7 = (_this$mutationCache$c8 = this.mutationCache.config).onError) == null ? void 0 : _this$mutationCache$c7.call(_this$mutationCache$c8, error, this.state.variables, this.state.context, this));
1741
+
1742
+ if (process.env.NODE_ENV !== 'production') {
1743
+ this.logger.error(error);
1744
+ }
1745
+
1746
+ 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)); // Notify cache callback
1747
+
1748
+ await ((_this$mutationCache$c9 = (_this$mutationCache$c10 = this.mutationCache.config).onSettled) == null ? void 0 : _this$mutationCache$c9.call(_this$mutationCache$c10, undefined, error, this.state.variables, this.state.context, this));
1749
+ 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));
1750
+ throw error;
1751
+ } finally {
1752
+ this.dispatch({
1753
+ type: 'error',
1754
+ error: error
1755
+ });
1756
+ }
1757
+ }
1758
+ }
1759
+
1760
+ dispatch(action) {
1761
+ const reducer = state => {
1762
+ switch (action.type) {
1763
+ case 'failed':
1764
+ return { ...state,
1765
+ failureCount: action.failureCount,
1766
+ failureReason: action.error
1767
+ };
1768
+
1769
+ case 'pause':
1770
+ return { ...state,
1771
+ isPaused: true
1772
+ };
1773
+
1774
+ case 'continue':
1775
+ return { ...state,
1776
+ isPaused: false
1777
+ };
1778
+
1779
+ case 'loading':
1780
+ return { ...state,
1781
+ context: action.context,
1782
+ data: undefined,
1783
+ failureCount: 0,
1784
+ failureReason: null,
1785
+ error: null,
1786
+ isPaused: !canFetch(this.options.networkMode),
1787
+ status: 'loading',
1788
+ variables: action.variables
1789
+ };
1790
+
1791
+ case 'success':
1792
+ return { ...state,
1793
+ data: action.data,
1794
+ failureCount: 0,
1795
+ failureReason: null,
1796
+ error: null,
1797
+ status: 'success',
1798
+ isPaused: false
1799
+ };
1800
+
1801
+ case 'error':
1802
+ return { ...state,
1803
+ data: undefined,
1804
+ error: action.error,
1805
+ failureCount: state.failureCount + 1,
1806
+ failureReason: action.error,
1807
+ isPaused: false,
1808
+ status: 'error'
1809
+ };
1810
+
1811
+ case 'setState':
1812
+ return { ...state,
1813
+ ...action.state
1814
+ };
1815
+ }
1816
+ };
1817
+
1818
+ this.state = reducer(this.state);
1819
+ notifyManager.batch(() => {
1820
+ this.observers.forEach(observer => {
1821
+ observer.onMutationUpdate(action);
1822
+ });
1823
+ this.mutationCache.notify({
1824
+ mutation: this,
1825
+ type: 'updated',
1826
+ action
1827
+ });
1828
+ });
1829
+ }
1830
+
1831
+ }
1832
+ function getDefaultState() {
1833
+ return {
1834
+ context: undefined,
1835
+ data: undefined,
1836
+ error: null,
1837
+ failureCount: 0,
1838
+ failureReason: null,
1839
+ isPaused: false,
1840
+ status: 'idle',
1841
+ variables: undefined
1842
+ };
1843
+ }
1844
+
1845
+ // CLASS
1846
+ class MutationCache extends Subscribable {
1847
+ constructor(config) {
1848
+ super();
1849
+ this.config = config || {};
1850
+ this.mutations = [];
1851
+ this.mutationId = 0;
1852
+ }
1853
+
1854
+ build(client, options, state) {
1855
+ const mutation = new Mutation({
1856
+ mutationCache: this,
1857
+ logger: client.getLogger(),
1858
+ mutationId: ++this.mutationId,
1859
+ options: client.defaultMutationOptions(options),
1860
+ state,
1861
+ defaultOptions: options.mutationKey ? client.getMutationDefaults(options.mutationKey) : undefined
1862
+ });
1863
+ this.add(mutation);
1864
+ return mutation;
1865
+ }
1866
+
1867
+ add(mutation) {
1868
+ this.mutations.push(mutation);
1869
+ this.notify({
1870
+ type: 'added',
1871
+ mutation
1872
+ });
1873
+ }
1874
+
1875
+ remove(mutation) {
1876
+ this.mutations = this.mutations.filter(x => x !== mutation);
1877
+ this.notify({
1878
+ type: 'removed',
1879
+ mutation
1880
+ });
1881
+ }
1882
+
1883
+ clear() {
1884
+ notifyManager.batch(() => {
1885
+ this.mutations.forEach(mutation => {
1886
+ this.remove(mutation);
1887
+ });
1888
+ });
1889
+ }
1890
+
1891
+ getAll() {
1892
+ return this.mutations;
1893
+ }
1894
+
1895
+ find(filters) {
1896
+ if (typeof filters.exact === 'undefined') {
1897
+ filters.exact = true;
1898
+ }
1899
+
1900
+ return this.mutations.find(mutation => matchMutation(filters, mutation));
1901
+ }
1902
+
1903
+ findAll(filters) {
1904
+ return this.mutations.filter(mutation => matchMutation(filters, mutation));
1905
+ }
1906
+
1907
+ notify(event) {
1908
+ notifyManager.batch(() => {
1909
+ this.listeners.forEach(({
1910
+ listener
1911
+ }) => {
1912
+ listener(event);
1913
+ });
1914
+ });
1915
+ }
1916
+
1917
+ resumePausedMutations() {
1918
+ var _this$resuming;
1919
+
1920
+ this.resuming = ((_this$resuming = this.resuming) != null ? _this$resuming : Promise.resolve()).then(() => {
1921
+ const pausedMutations = this.mutations.filter(x => x.state.isPaused);
1922
+ return notifyManager.batch(() => pausedMutations.reduce((promise, mutation) => promise.then(() => mutation.continue().catch(noop$1)), Promise.resolve()));
1923
+ }).then(() => {
1924
+ this.resuming = undefined;
1925
+ });
1926
+ return this.resuming;
1927
+ }
1928
+
1929
+ }
1930
+
1931
+ function infiniteQueryBehavior() {
1932
+ return {
1933
+ onFetch: context => {
1934
+ context.fetchFn = () => {
1935
+ var _context$fetchOptions, _context$fetchOptions2, _context$fetchOptions3, _context$fetchOptions4, _context$state$data, _context$state$data2;
1936
+
1937
+ const refetchPage = (_context$fetchOptions = context.fetchOptions) == null ? void 0 : (_context$fetchOptions2 = _context$fetchOptions.meta) == null ? void 0 : _context$fetchOptions2.refetchPage;
1938
+ const fetchMore = (_context$fetchOptions3 = context.fetchOptions) == null ? void 0 : (_context$fetchOptions4 = _context$fetchOptions3.meta) == null ? void 0 : _context$fetchOptions4.fetchMore;
1939
+ const pageParam = fetchMore == null ? void 0 : fetchMore.pageParam;
1940
+ const isFetchingNextPage = (fetchMore == null ? void 0 : fetchMore.direction) === 'forward';
1941
+ const isFetchingPreviousPage = (fetchMore == null ? void 0 : fetchMore.direction) === 'backward';
1942
+ const oldPages = ((_context$state$data = context.state.data) == null ? void 0 : _context$state$data.pages) || [];
1943
+ const oldPageParams = ((_context$state$data2 = context.state.data) == null ? void 0 : _context$state$data2.pageParams) || [];
1944
+ let newPageParams = oldPageParams;
1945
+ let cancelled = false;
1946
+
1947
+ const addSignalProperty = object => {
1948
+ Object.defineProperty(object, 'signal', {
1949
+ enumerable: true,
1950
+ get: () => {
1951
+ var _context$signal;
1952
+
1953
+ if ((_context$signal = context.signal) != null && _context$signal.aborted) {
1954
+ cancelled = true;
1955
+ } else {
1956
+ var _context$signal2;
1957
+
1958
+ (_context$signal2 = context.signal) == null ? void 0 : _context$signal2.addEventListener('abort', () => {
1959
+ cancelled = true;
1960
+ });
1961
+ }
1962
+
1963
+ return context.signal;
1964
+ }
1965
+ });
1966
+ }; // Get query function
1967
+
1968
+
1969
+ const queryFn = context.options.queryFn || (() => Promise.reject("Missing queryFn for queryKey '" + context.options.queryHash + "'"));
1970
+
1971
+ const buildNewPages = (pages, param, page, previous) => {
1972
+ newPageParams = previous ? [param, ...newPageParams] : [...newPageParams, param];
1973
+ return previous ? [page, ...pages] : [...pages, page];
1974
+ }; // Create function to fetch a page
1975
+
1976
+
1977
+ const fetchPage = (pages, manual, param, previous) => {
1978
+ if (cancelled) {
1979
+ return Promise.reject('Cancelled');
1980
+ }
1981
+
1982
+ if (typeof param === 'undefined' && !manual && pages.length) {
1983
+ return Promise.resolve(pages);
1984
+ }
1985
+
1986
+ const queryFnContext = {
1987
+ queryKey: context.queryKey,
1988
+ pageParam: param,
1989
+ meta: context.options.meta
1990
+ };
1991
+ addSignalProperty(queryFnContext);
1992
+ const queryFnResult = queryFn(queryFnContext);
1993
+ const promise = Promise.resolve(queryFnResult).then(page => buildNewPages(pages, param, page, previous));
1994
+ return promise;
1995
+ };
1996
+
1997
+ let promise; // Fetch first page?
1998
+
1999
+ if (!oldPages.length) {
2000
+ promise = fetchPage([]);
2001
+ } // Fetch next page?
2002
+ else if (isFetchingNextPage) {
2003
+ const manual = typeof pageParam !== 'undefined';
2004
+ const param = manual ? pageParam : getNextPageParam(context.options, oldPages);
2005
+ promise = fetchPage(oldPages, manual, param);
2006
+ } // Fetch previous page?
2007
+ else if (isFetchingPreviousPage) {
2008
+ const manual = typeof pageParam !== 'undefined';
2009
+ const param = manual ? pageParam : getPreviousPageParam(context.options, oldPages);
2010
+ promise = fetchPage(oldPages, manual, param, true);
2011
+ } // Refetch pages
2012
+ else {
2013
+ newPageParams = [];
2014
+ const manual = typeof context.options.getNextPageParam === 'undefined';
2015
+ const shouldFetchFirstPage = refetchPage && oldPages[0] ? refetchPage(oldPages[0], 0, oldPages) : true; // Fetch first page
2016
+
2017
+ promise = shouldFetchFirstPage ? fetchPage([], manual, oldPageParams[0]) : Promise.resolve(buildNewPages([], oldPageParams[0], oldPages[0])); // Fetch remaining pages
2018
+
2019
+ for (let i = 1; i < oldPages.length; i++) {
2020
+ promise = promise.then(pages => {
2021
+ const shouldFetchNextPage = refetchPage && oldPages[i] ? refetchPage(oldPages[i], i, oldPages) : true;
2022
+
2023
+ if (shouldFetchNextPage) {
2024
+ const param = manual ? oldPageParams[i] : getNextPageParam(context.options, pages);
2025
+ return fetchPage(pages, manual, param);
2026
+ }
2027
+
2028
+ return Promise.resolve(buildNewPages(pages, oldPageParams[i], oldPages[i]));
2029
+ });
2030
+ }
2031
+ }
2032
+
2033
+ const finalPromise = promise.then(pages => ({
2034
+ pages,
2035
+ pageParams: newPageParams
2036
+ }));
2037
+ return finalPromise;
2038
+ };
2039
+ }
2040
+ };
2041
+ }
2042
+ function getNextPageParam(options, pages) {
2043
+ return options.getNextPageParam == null ? void 0 : options.getNextPageParam(pages[pages.length - 1], pages);
2044
+ }
2045
+ function getPreviousPageParam(options, pages) {
2046
+ return options.getPreviousPageParam == null ? void 0 : options.getPreviousPageParam(pages[0], pages);
2047
+ }
2048
+
2049
+ // CLASS
2050
+ class QueryClient {
2051
+ constructor(config = {}) {
2052
+ this.queryCache = config.queryCache || new QueryCache();
2053
+ this.mutationCache = config.mutationCache || new MutationCache();
2054
+ this.logger = config.logger || defaultLogger;
2055
+ this.defaultOptions = config.defaultOptions || {};
2056
+ this.queryDefaults = [];
2057
+ this.mutationDefaults = [];
2058
+ this.mountCount = 0;
2059
+
2060
+ if (process.env.NODE_ENV !== 'production' && config.logger) {
2061
+ this.logger.error("Passing a custom logger has been deprecated and will be removed in the next major version.");
2062
+ }
2063
+ }
2064
+
2065
+ mount() {
2066
+ this.mountCount++;
2067
+ if (this.mountCount !== 1) return;
2068
+ this.unsubscribeFocus = focusManager.subscribe(() => {
2069
+ if (focusManager.isFocused()) {
2070
+ this.resumePausedMutations();
2071
+ this.queryCache.onFocus();
2072
+ }
2073
+ });
2074
+ this.unsubscribeOnline = onlineManager.subscribe(() => {
2075
+ if (onlineManager.isOnline()) {
2076
+ this.resumePausedMutations();
2077
+ this.queryCache.onOnline();
2078
+ }
2079
+ });
2080
+ }
2081
+
2082
+ unmount() {
2083
+ var _this$unsubscribeFocu, _this$unsubscribeOnli;
2084
+
2085
+ this.mountCount--;
2086
+ if (this.mountCount !== 0) return;
2087
+ (_this$unsubscribeFocu = this.unsubscribeFocus) == null ? void 0 : _this$unsubscribeFocu.call(this);
2088
+ this.unsubscribeFocus = undefined;
2089
+ (_this$unsubscribeOnli = this.unsubscribeOnline) == null ? void 0 : _this$unsubscribeOnli.call(this);
2090
+ this.unsubscribeOnline = undefined;
2091
+ }
2092
+
2093
+ isFetching(arg1, arg2) {
2094
+ const [filters] = parseFilterArgs(arg1, arg2);
2095
+ filters.fetchStatus = 'fetching';
2096
+ return this.queryCache.findAll(filters).length;
2097
+ }
2098
+
2099
+ isMutating(filters) {
2100
+ return this.mutationCache.findAll({ ...filters,
2101
+ fetching: true
2102
+ }).length;
2103
+ }
2104
+
2105
+ getQueryData(queryKey, filters) {
2106
+ var _this$queryCache$find;
2107
+
2108
+ return (_this$queryCache$find = this.queryCache.find(queryKey, filters)) == null ? void 0 : _this$queryCache$find.state.data;
2109
+ }
2110
+
2111
+ ensureQueryData(arg1, arg2, arg3) {
2112
+ const parsedOptions = parseQueryArgs(arg1, arg2, arg3);
2113
+ const cachedData = this.getQueryData(parsedOptions.queryKey);
2114
+ return cachedData ? Promise.resolve(cachedData) : this.fetchQuery(parsedOptions);
2115
+ }
2116
+
2117
+ getQueriesData(queryKeyOrFilters) {
2118
+ return this.getQueryCache().findAll(queryKeyOrFilters).map(({
2119
+ queryKey,
2120
+ state
2121
+ }) => {
2122
+ const data = state.data;
2123
+ return [queryKey, data];
2124
+ });
2125
+ }
2126
+
2127
+ setQueryData(queryKey, updater, options) {
2128
+ const query = this.queryCache.find(queryKey);
2129
+ const prevData = query == null ? void 0 : query.state.data;
2130
+ const data = functionalUpdate(updater, prevData);
2131
+
2132
+ if (typeof data === 'undefined') {
2133
+ return undefined;
2134
+ }
2135
+
2136
+ const parsedOptions = parseQueryArgs(queryKey);
2137
+ const defaultedOptions = this.defaultQueryOptions(parsedOptions);
2138
+ return this.queryCache.build(this, defaultedOptions).setData(data, { ...options,
2139
+ manual: true
2140
+ });
2141
+ }
2142
+
2143
+ setQueriesData(queryKeyOrFilters, updater, options) {
2144
+ return notifyManager.batch(() => this.getQueryCache().findAll(queryKeyOrFilters).map(({
2145
+ queryKey
2146
+ }) => [queryKey, this.setQueryData(queryKey, updater, options)]));
2147
+ }
2148
+
2149
+ getQueryState(queryKey, filters) {
2150
+ var _this$queryCache$find2;
2151
+
2152
+ return (_this$queryCache$find2 = this.queryCache.find(queryKey, filters)) == null ? void 0 : _this$queryCache$find2.state;
2153
+ }
2154
+
2155
+ removeQueries(arg1, arg2) {
2156
+ const [filters] = parseFilterArgs(arg1, arg2);
2157
+ const queryCache = this.queryCache;
2158
+ notifyManager.batch(() => {
2159
+ queryCache.findAll(filters).forEach(query => {
2160
+ queryCache.remove(query);
2161
+ });
2162
+ });
2163
+ }
2164
+
2165
+ resetQueries(arg1, arg2, arg3) {
2166
+ const [filters, options] = parseFilterArgs(arg1, arg2, arg3);
2167
+ const queryCache = this.queryCache;
2168
+ const refetchFilters = {
2169
+ type: 'active',
2170
+ ...filters
2171
+ };
2172
+ return notifyManager.batch(() => {
2173
+ queryCache.findAll(filters).forEach(query => {
2174
+ query.reset();
2175
+ });
2176
+ return this.refetchQueries(refetchFilters, options);
2177
+ });
2178
+ }
2179
+
2180
+ cancelQueries(arg1, arg2, arg3) {
2181
+ const [filters, cancelOptions = {}] = parseFilterArgs(arg1, arg2, arg3);
2182
+
2183
+ if (typeof cancelOptions.revert === 'undefined') {
2184
+ cancelOptions.revert = true;
2185
+ }
2186
+
2187
+ const promises = notifyManager.batch(() => this.queryCache.findAll(filters).map(query => query.cancel(cancelOptions)));
2188
+ return Promise.all(promises).then(noop$1).catch(noop$1);
2189
+ }
2190
+
2191
+ invalidateQueries(arg1, arg2, arg3) {
2192
+ const [filters, options] = parseFilterArgs(arg1, arg2, arg3);
2193
+ return notifyManager.batch(() => {
2194
+ var _ref, _filters$refetchType;
2195
+
2196
+ this.queryCache.findAll(filters).forEach(query => {
2197
+ query.invalidate();
2198
+ });
2199
+
2200
+ if (filters.refetchType === 'none') {
2201
+ return Promise.resolve();
2202
+ }
2203
+
2204
+ const refetchFilters = { ...filters,
2205
+ type: (_ref = (_filters$refetchType = filters.refetchType) != null ? _filters$refetchType : filters.type) != null ? _ref : 'active'
2206
+ };
2207
+ return this.refetchQueries(refetchFilters, options);
2208
+ });
2209
+ }
2210
+
2211
+ refetchQueries(arg1, arg2, arg3) {
2212
+ const [filters, options] = parseFilterArgs(arg1, arg2, arg3);
2213
+ const promises = notifyManager.batch(() => this.queryCache.findAll(filters).filter(query => !query.isDisabled()).map(query => {
2214
+ var _options$cancelRefetc;
2215
+
2216
+ return query.fetch(undefined, { ...options,
2217
+ cancelRefetch: (_options$cancelRefetc = options == null ? void 0 : options.cancelRefetch) != null ? _options$cancelRefetc : true,
2218
+ meta: {
2219
+ refetchPage: filters.refetchPage
2220
+ }
2221
+ });
2222
+ }));
2223
+ let promise = Promise.all(promises).then(noop$1);
2224
+
2225
+ if (!(options != null && options.throwOnError)) {
2226
+ promise = promise.catch(noop$1);
2227
+ }
2228
+
2229
+ return promise;
2230
+ }
2231
+
2232
+ fetchQuery(arg1, arg2, arg3) {
2233
+ const parsedOptions = parseQueryArgs(arg1, arg2, arg3);
2234
+ const defaultedOptions = this.defaultQueryOptions(parsedOptions); // https://github.com/tannerlinsley/react-query/issues/652
2235
+
2236
+ if (typeof defaultedOptions.retry === 'undefined') {
2237
+ defaultedOptions.retry = false;
2238
+ }
2239
+
2240
+ const query = this.queryCache.build(this, defaultedOptions);
2241
+ return query.isStaleByTime(defaultedOptions.staleTime) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);
2242
+ }
2243
+
2244
+ prefetchQuery(arg1, arg2, arg3) {
2245
+ return this.fetchQuery(arg1, arg2, arg3).then(noop$1).catch(noop$1);
2246
+ }
2247
+
2248
+ fetchInfiniteQuery(arg1, arg2, arg3) {
2249
+ const parsedOptions = parseQueryArgs(arg1, arg2, arg3);
2250
+ parsedOptions.behavior = infiniteQueryBehavior();
2251
+ return this.fetchQuery(parsedOptions);
2252
+ }
2253
+
2254
+ prefetchInfiniteQuery(arg1, arg2, arg3) {
2255
+ return this.fetchInfiniteQuery(arg1, arg2, arg3).then(noop$1).catch(noop$1);
2256
+ }
2257
+
2258
+ resumePausedMutations() {
2259
+ return this.mutationCache.resumePausedMutations();
2260
+ }
2261
+
2262
+ getQueryCache() {
2263
+ return this.queryCache;
2264
+ }
2265
+
2266
+ getMutationCache() {
2267
+ return this.mutationCache;
2268
+ }
2269
+
2270
+ getLogger() {
2271
+ return this.logger;
2272
+ }
2273
+
2274
+ getDefaultOptions() {
2275
+ return this.defaultOptions;
2276
+ }
2277
+
2278
+ setDefaultOptions(options) {
2279
+ this.defaultOptions = options;
2280
+ }
2281
+
2282
+ setQueryDefaults(queryKey, options) {
2283
+ const result = this.queryDefaults.find(x => hashQueryKey(queryKey) === hashQueryKey(x.queryKey));
2284
+
2285
+ if (result) {
2286
+ result.defaultOptions = options;
2287
+ } else {
2288
+ this.queryDefaults.push({
2289
+ queryKey,
2290
+ defaultOptions: options
2291
+ });
2292
+ }
2293
+ }
2294
+
2295
+ getQueryDefaults(queryKey) {
2296
+ if (!queryKey) {
2297
+ return undefined;
2298
+ } // Get the first matching defaults
2299
+
2300
+
2301
+ const firstMatchingDefaults = this.queryDefaults.find(x => partialMatchKey(queryKey, x.queryKey)); // Additional checks and error in dev mode
2302
+
2303
+ if (process.env.NODE_ENV !== 'production') {
2304
+ // Retrieve all matching defaults for the given key
2305
+ 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
2306
+
2307
+ if (matchingDefaults.length > 1) {
2308
+ 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.");
2309
+ }
2310
+ }
2311
+
2312
+ return firstMatchingDefaults == null ? void 0 : firstMatchingDefaults.defaultOptions;
2313
+ }
2314
+
2315
+ setMutationDefaults(mutationKey, options) {
2316
+ const result = this.mutationDefaults.find(x => hashQueryKey(mutationKey) === hashQueryKey(x.mutationKey));
2317
+
2318
+ if (result) {
2319
+ result.defaultOptions = options;
2320
+ } else {
2321
+ this.mutationDefaults.push({
2322
+ mutationKey,
2323
+ defaultOptions: options
2324
+ });
2325
+ }
2326
+ }
2327
+
2328
+ getMutationDefaults(mutationKey) {
2329
+ if (!mutationKey) {
2330
+ return undefined;
2331
+ } // Get the first matching defaults
2332
+
2333
+
2334
+ const firstMatchingDefaults = this.mutationDefaults.find(x => partialMatchKey(mutationKey, x.mutationKey)); // Additional checks and error in dev mode
2335
+
2336
+ if (process.env.NODE_ENV !== 'production') {
2337
+ // Retrieve all matching defaults for the given key
2338
+ 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
2339
+
2340
+ if (matchingDefaults.length > 1) {
2341
+ 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.");
2342
+ }
2343
+ }
2344
+
2345
+ return firstMatchingDefaults == null ? void 0 : firstMatchingDefaults.defaultOptions;
2346
+ }
2347
+
2348
+ defaultQueryOptions(options) {
2349
+ if (options != null && options._defaulted) {
2350
+ return options;
2351
+ }
2352
+
2353
+ const defaultedOptions = { ...this.defaultOptions.queries,
2354
+ ...this.getQueryDefaults(options == null ? void 0 : options.queryKey),
2355
+ ...options,
2356
+ _defaulted: true
2357
+ };
2358
+
2359
+ if (!defaultedOptions.queryHash && defaultedOptions.queryKey) {
2360
+ defaultedOptions.queryHash = hashQueryKeyByOptions(defaultedOptions.queryKey, defaultedOptions);
2361
+ } // dependent default values
2362
+
2363
+
2364
+ if (typeof defaultedOptions.refetchOnReconnect === 'undefined') {
2365
+ defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== 'always';
2366
+ }
2367
+
2368
+ if (typeof defaultedOptions.useErrorBoundary === 'undefined') {
2369
+ defaultedOptions.useErrorBoundary = !!defaultedOptions.suspense;
2370
+ }
2371
+
2372
+ return defaultedOptions;
2373
+ }
2374
+
2375
+ defaultMutationOptions(options) {
2376
+ if (options != null && options._defaulted) {
2377
+ return options;
2378
+ }
2379
+
2380
+ return { ...this.defaultOptions.mutations,
2381
+ ...this.getMutationDefaults(options == null ? void 0 : options.mutationKey),
2382
+ ...options,
2383
+ _defaulted: true
2384
+ };
2385
+ }
2386
+
2387
+ clear() {
2388
+ this.queryCache.clear();
2389
+ this.mutationCache.clear();
2390
+ }
2391
+
2392
+ }
2393
+
2394
+ class QueryObserver extends Subscribable {
2395
+ constructor(client, options) {
2396
+ super();
2397
+ this.client = client;
2398
+ this.options = options;
2399
+ this.trackedProps = new Set();
2400
+ this.selectError = null;
2401
+ this.bindMethods();
2402
+ this.setOptions(options);
2403
+ }
2404
+
2405
+ bindMethods() {
2406
+ this.remove = this.remove.bind(this);
2407
+ this.refetch = this.refetch.bind(this);
2408
+ }
2409
+
2410
+ onSubscribe() {
2411
+ if (this.listeners.size === 1) {
2412
+ this.currentQuery.addObserver(this);
2413
+
2414
+ if (shouldFetchOnMount(this.currentQuery, this.options)) {
2415
+ this.executeFetch();
2416
+ }
2417
+
2418
+ this.updateTimers();
2419
+ }
2420
+ }
2421
+
2422
+ onUnsubscribe() {
2423
+ if (!this.hasListeners()) {
2424
+ this.destroy();
2425
+ }
2426
+ }
2427
+
2428
+ shouldFetchOnReconnect() {
2429
+ return shouldFetchOn(this.currentQuery, this.options, this.options.refetchOnReconnect);
2430
+ }
2431
+
2432
+ shouldFetchOnWindowFocus() {
2433
+ return shouldFetchOn(this.currentQuery, this.options, this.options.refetchOnWindowFocus);
2434
+ }
2435
+
2436
+ destroy() {
2437
+ this.listeners = new Set();
2438
+ this.clearStaleTimeout();
2439
+ this.clearRefetchInterval();
2440
+ this.currentQuery.removeObserver(this);
2441
+ }
2442
+
2443
+ setOptions(options, notifyOptions) {
2444
+ const prevOptions = this.options;
2445
+ const prevQuery = this.currentQuery;
2446
+ this.options = this.client.defaultQueryOptions(options);
2447
+
2448
+ if (process.env.NODE_ENV !== 'production' && typeof (options == null ? void 0 : options.isDataEqual) !== 'undefined') {
2449
+ 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");
2450
+ }
2451
+
2452
+ if (!shallowEqualObjects(prevOptions, this.options)) {
2453
+ this.client.getQueryCache().notify({
2454
+ type: 'observerOptionsUpdated',
2455
+ query: this.currentQuery,
2456
+ observer: this
2457
+ });
2458
+ }
2459
+
2460
+ if (typeof this.options.enabled !== 'undefined' && typeof this.options.enabled !== 'boolean') {
2461
+ throw new Error('Expected enabled to be a boolean');
2462
+ } // Keep previous query key if the user does not supply one
2463
+
2464
+
2465
+ if (!this.options.queryKey) {
2466
+ this.options.queryKey = prevOptions.queryKey;
2467
+ }
2468
+
2469
+ this.updateQuery();
2470
+ const mounted = this.hasListeners(); // Fetch if there are subscribers
2471
+
2472
+ if (mounted && shouldFetchOptionally(this.currentQuery, prevQuery, this.options, prevOptions)) {
2473
+ this.executeFetch();
2474
+ } // Update result
2475
+
2476
+
2477
+ this.updateResult(notifyOptions); // Update stale interval if needed
2478
+
2479
+ if (mounted && (this.currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || this.options.staleTime !== prevOptions.staleTime)) {
2480
+ this.updateStaleTimeout();
2481
+ }
2482
+
2483
+ const nextRefetchInterval = this.computeRefetchInterval(); // Update refetch interval if needed
2484
+
2485
+ if (mounted && (this.currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || nextRefetchInterval !== this.currentRefetchInterval)) {
2486
+ this.updateRefetchInterval(nextRefetchInterval);
2487
+ }
2488
+ }
2489
+
2490
+ getOptimisticResult(options) {
2491
+ const query = this.client.getQueryCache().build(this.client, options);
2492
+ const result = this.createResult(query, options);
2493
+
2494
+ if (shouldAssignObserverCurrentProperties(this, result, options)) {
2495
+ // this assigns the optimistic result to the current Observer
2496
+ // because if the query function changes, useQuery will be performing
2497
+ // an effect where it would fetch again.
2498
+ // When the fetch finishes, we perform a deep data cloning in order
2499
+ // to reuse objects references. This deep data clone is performed against
2500
+ // the `observer.currentResult.data` property
2501
+ // When QueryKey changes, we refresh the query and get new `optimistic`
2502
+ // result, while we leave the `observer.currentResult`, so when new data
2503
+ // arrives, it finds the old `observer.currentResult` which is related
2504
+ // to the old QueryKey. Which means that currentResult and selectData are
2505
+ // out of sync already.
2506
+ // To solve this, we move the cursor of the currentResult everytime
2507
+ // an observer reads an optimistic value.
2508
+ // When keeping the previous data, the result doesn't change until new
2509
+ // data arrives.
2510
+ this.currentResult = result;
2511
+ this.currentResultOptions = this.options;
2512
+ this.currentResultState = this.currentQuery.state;
2513
+ }
2514
+
2515
+ return result;
2516
+ }
2517
+
2518
+ getCurrentResult() {
2519
+ return this.currentResult;
2520
+ }
2521
+
2522
+ trackResult(result) {
2523
+ const trackedResult = {};
2524
+ Object.keys(result).forEach(key => {
2525
+ Object.defineProperty(trackedResult, key, {
2526
+ configurable: false,
2527
+ enumerable: true,
2528
+ get: () => {
2529
+ this.trackedProps.add(key);
2530
+ return result[key];
2531
+ }
2532
+ });
2533
+ });
2534
+ return trackedResult;
2535
+ }
2536
+
2537
+ getCurrentQuery() {
2538
+ return this.currentQuery;
2539
+ }
2540
+
2541
+ remove() {
2542
+ this.client.getQueryCache().remove(this.currentQuery);
2543
+ }
2544
+
2545
+ refetch({
2546
+ refetchPage,
2547
+ ...options
2548
+ } = {}) {
2549
+ return this.fetch({ ...options,
2550
+ meta: {
2551
+ refetchPage
2552
+ }
2553
+ });
2554
+ }
2555
+
2556
+ fetchOptimistic(options) {
2557
+ const defaultedOptions = this.client.defaultQueryOptions(options);
2558
+ const query = this.client.getQueryCache().build(this.client, defaultedOptions);
2559
+ query.isFetchingOptimistic = true;
2560
+ return query.fetch().then(() => this.createResult(query, defaultedOptions));
2561
+ }
2562
+
2563
+ fetch(fetchOptions) {
2564
+ var _fetchOptions$cancelR;
2565
+
2566
+ return this.executeFetch({ ...fetchOptions,
2567
+ cancelRefetch: (_fetchOptions$cancelR = fetchOptions.cancelRefetch) != null ? _fetchOptions$cancelR : true
2568
+ }).then(() => {
2569
+ this.updateResult();
2570
+ return this.currentResult;
2571
+ });
2572
+ }
2573
+
2574
+ executeFetch(fetchOptions) {
2575
+ // Make sure we reference the latest query as the current one might have been removed
2576
+ this.updateQuery(); // Fetch
2577
+
2578
+ let promise = this.currentQuery.fetch(this.options, fetchOptions);
2579
+
2580
+ if (!(fetchOptions != null && fetchOptions.throwOnError)) {
2581
+ promise = promise.catch(noop$1);
2582
+ }
2583
+
2584
+ return promise;
2585
+ }
2586
+
2587
+ updateStaleTimeout() {
2588
+ this.clearStaleTimeout();
2589
+
2590
+ if (isServer || this.currentResult.isStale || !isValidTimeout(this.options.staleTime)) {
2591
+ return;
2592
+ }
2593
+
2594
+ const time = timeUntilStale(this.currentResult.dataUpdatedAt, this.options.staleTime); // The timeout is sometimes triggered 1 ms before the stale time expiration.
2595
+ // To mitigate this issue we always add 1 ms to the timeout.
2596
+
2597
+ const timeout = time + 1;
2598
+ this.staleTimeoutId = setTimeout(() => {
2599
+ if (!this.currentResult.isStale) {
2600
+ this.updateResult();
2601
+ }
2602
+ }, timeout);
2603
+ }
2604
+
2605
+ computeRefetchInterval() {
2606
+ var _this$options$refetch;
2607
+
2608
+ 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;
2609
+ }
2610
+
2611
+ updateRefetchInterval(nextInterval) {
2612
+ this.clearRefetchInterval();
2613
+ this.currentRefetchInterval = nextInterval;
2614
+
2615
+ if (isServer || this.options.enabled === false || !isValidTimeout(this.currentRefetchInterval) || this.currentRefetchInterval === 0) {
2616
+ return;
2617
+ }
2618
+
2619
+ this.refetchIntervalId = setInterval(() => {
2620
+ if (this.options.refetchIntervalInBackground || focusManager.isFocused()) {
2621
+ this.executeFetch();
2622
+ }
2623
+ }, this.currentRefetchInterval);
2624
+ }
2625
+
2626
+ updateTimers() {
2627
+ this.updateStaleTimeout();
2628
+ this.updateRefetchInterval(this.computeRefetchInterval());
2629
+ }
2630
+
2631
+ clearStaleTimeout() {
2632
+ if (this.staleTimeoutId) {
2633
+ clearTimeout(this.staleTimeoutId);
2634
+ this.staleTimeoutId = undefined;
2635
+ }
2636
+ }
2637
+
2638
+ clearRefetchInterval() {
2639
+ if (this.refetchIntervalId) {
2640
+ clearInterval(this.refetchIntervalId);
2641
+ this.refetchIntervalId = undefined;
2642
+ }
2643
+ }
2644
+
2645
+ createResult(query, options) {
2646
+ const prevQuery = this.currentQuery;
2647
+ const prevOptions = this.options;
2648
+ const prevResult = this.currentResult;
2649
+ const prevResultState = this.currentResultState;
2650
+ const prevResultOptions = this.currentResultOptions;
2651
+ const queryChange = query !== prevQuery;
2652
+ const queryInitialState = queryChange ? query.state : this.currentQueryInitialState;
2653
+ const prevQueryResult = queryChange ? this.currentResult : this.previousQueryResult;
2654
+ const {
2655
+ state
2656
+ } = query;
2657
+ let {
2658
+ dataUpdatedAt,
2659
+ error,
2660
+ errorUpdatedAt,
2661
+ fetchStatus,
2662
+ status
2663
+ } = state;
2664
+ let isPreviousData = false;
2665
+ let isPlaceholderData = false;
2666
+ let data; // Optimistically set result in fetching state if needed
2667
+
2668
+ if (options._optimisticResults) {
2669
+ const mounted = this.hasListeners();
2670
+ const fetchOnMount = !mounted && shouldFetchOnMount(query, options);
2671
+ const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
2672
+
2673
+ if (fetchOnMount || fetchOptionally) {
2674
+ fetchStatus = canFetch(query.options.networkMode) ? 'fetching' : 'paused';
2675
+
2676
+ if (!dataUpdatedAt) {
2677
+ status = 'loading';
2678
+ }
2679
+ }
2680
+
2681
+ if (options._optimisticResults === 'isRestoring') {
2682
+ fetchStatus = 'idle';
2683
+ }
2684
+ } // Keep previous data if needed
2685
+
2686
+
2687
+ if (options.keepPreviousData && !state.dataUpdatedAt && prevQueryResult != null && prevQueryResult.isSuccess && status !== 'error') {
2688
+ data = prevQueryResult.data;
2689
+ dataUpdatedAt = prevQueryResult.dataUpdatedAt;
2690
+ status = prevQueryResult.status;
2691
+ isPreviousData = true;
2692
+ } // Select data if needed
2693
+ else if (options.select && typeof state.data !== 'undefined') {
2694
+ // Memoize select result
2695
+ if (prevResult && state.data === (prevResultState == null ? void 0 : prevResultState.data) && options.select === this.selectFn) {
2696
+ data = this.selectResult;
2697
+ } else {
2698
+ try {
2699
+ this.selectFn = options.select;
2700
+ data = options.select(state.data);
2701
+ data = replaceData(prevResult == null ? void 0 : prevResult.data, data, options);
2702
+ this.selectResult = data;
2703
+ this.selectError = null;
2704
+ } catch (selectError) {
2705
+ if (process.env.NODE_ENV !== 'production') {
2706
+ this.client.getLogger().error(selectError);
2707
+ }
2708
+
2709
+ this.selectError = selectError;
2710
+ }
2711
+ }
2712
+ } // Use query data
2713
+ else {
2714
+ data = state.data;
2715
+ } // Show placeholder data if needed
2716
+
2717
+
2718
+ if (typeof options.placeholderData !== 'undefined' && typeof data === 'undefined' && status === 'loading') {
2719
+ let placeholderData; // Memoize placeholder data
2720
+
2721
+ if (prevResult != null && prevResult.isPlaceholderData && options.placeholderData === (prevResultOptions == null ? void 0 : prevResultOptions.placeholderData)) {
2722
+ placeholderData = prevResult.data;
2723
+ } else {
2724
+ placeholderData = typeof options.placeholderData === 'function' ? options.placeholderData() : options.placeholderData;
2725
+
2726
+ if (options.select && typeof placeholderData !== 'undefined') {
2727
+ try {
2728
+ placeholderData = options.select(placeholderData);
2729
+ this.selectError = null;
2730
+ } catch (selectError) {
2731
+ if (process.env.NODE_ENV !== 'production') {
2732
+ this.client.getLogger().error(selectError);
2733
+ }
2734
+
2735
+ this.selectError = selectError;
2736
+ }
2737
+ }
2738
+ }
2739
+
2740
+ if (typeof placeholderData !== 'undefined') {
2741
+ status = 'success';
2742
+ data = replaceData(prevResult == null ? void 0 : prevResult.data, placeholderData, options);
2743
+ isPlaceholderData = true;
2744
+ }
2745
+ }
2746
+
2747
+ if (this.selectError) {
2748
+ error = this.selectError;
2749
+ data = this.selectResult;
2750
+ errorUpdatedAt = Date.now();
2751
+ status = 'error';
2752
+ }
2753
+
2754
+ const isFetching = fetchStatus === 'fetching';
2755
+ const isLoading = status === 'loading';
2756
+ const isError = status === 'error';
2757
+ const result = {
2758
+ status,
2759
+ fetchStatus,
2760
+ isLoading,
2761
+ isSuccess: status === 'success',
2762
+ isError,
2763
+ isInitialLoading: isLoading && isFetching,
2764
+ data,
2765
+ dataUpdatedAt,
2766
+ error,
2767
+ errorUpdatedAt,
2768
+ failureCount: state.fetchFailureCount,
2769
+ failureReason: state.fetchFailureReason,
2770
+ errorUpdateCount: state.errorUpdateCount,
2771
+ isFetched: state.dataUpdateCount > 0 || state.errorUpdateCount > 0,
2772
+ isFetchedAfterMount: state.dataUpdateCount > queryInitialState.dataUpdateCount || state.errorUpdateCount > queryInitialState.errorUpdateCount,
2773
+ isFetching,
2774
+ isRefetching: isFetching && !isLoading,
2775
+ isLoadingError: isError && state.dataUpdatedAt === 0,
2776
+ isPaused: fetchStatus === 'paused',
2777
+ isPlaceholderData,
2778
+ isPreviousData,
2779
+ isRefetchError: isError && state.dataUpdatedAt !== 0,
2780
+ isStale: isStale(query, options),
2781
+ refetch: this.refetch,
2782
+ remove: this.remove
2783
+ };
2784
+ return result;
2785
+ }
2786
+
2787
+ updateResult(notifyOptions) {
2788
+ const prevResult = this.currentResult;
2789
+ const nextResult = this.createResult(this.currentQuery, this.options);
2790
+ this.currentResultState = this.currentQuery.state;
2791
+ this.currentResultOptions = this.options; // Only notify and update result if something has changed
2792
+
2793
+ if (shallowEqualObjects(nextResult, prevResult)) {
2794
+ return;
2795
+ }
2796
+
2797
+ this.currentResult = nextResult; // Determine which callbacks to trigger
2798
+
2799
+ const defaultNotifyOptions = {
2800
+ cache: true
2801
+ };
2802
+
2803
+ const shouldNotifyListeners = () => {
2804
+ if (!prevResult) {
2805
+ return true;
2806
+ }
2807
+
2808
+ const {
2809
+ notifyOnChangeProps
2810
+ } = this.options;
2811
+ const notifyOnChangePropsValue = typeof notifyOnChangeProps === 'function' ? notifyOnChangeProps() : notifyOnChangeProps;
2812
+
2813
+ if (notifyOnChangePropsValue === 'all' || !notifyOnChangePropsValue && !this.trackedProps.size) {
2814
+ return true;
2815
+ }
2816
+
2817
+ const includedProps = new Set(notifyOnChangePropsValue != null ? notifyOnChangePropsValue : this.trackedProps);
2818
+
2819
+ if (this.options.useErrorBoundary) {
2820
+ includedProps.add('error');
2821
+ }
2822
+
2823
+ return Object.keys(this.currentResult).some(key => {
2824
+ const typedKey = key;
2825
+ const changed = this.currentResult[typedKey] !== prevResult[typedKey];
2826
+ return changed && includedProps.has(typedKey);
2827
+ });
2828
+ };
2829
+
2830
+ if ((notifyOptions == null ? void 0 : notifyOptions.listeners) !== false && shouldNotifyListeners()) {
2831
+ defaultNotifyOptions.listeners = true;
2832
+ }
2833
+
2834
+ this.notify({ ...defaultNotifyOptions,
2835
+ ...notifyOptions
2836
+ });
2837
+ }
2838
+
2839
+ updateQuery() {
2840
+ const query = this.client.getQueryCache().build(this.client, this.options);
2841
+
2842
+ if (query === this.currentQuery) {
2843
+ return;
2844
+ }
2845
+
2846
+ const prevQuery = this.currentQuery;
2847
+ this.currentQuery = query;
2848
+ this.currentQueryInitialState = query.state;
2849
+ this.previousQueryResult = this.currentResult;
2850
+
2851
+ if (this.hasListeners()) {
2852
+ prevQuery == null ? void 0 : prevQuery.removeObserver(this);
2853
+ query.addObserver(this);
2854
+ }
2855
+ }
2856
+
2857
+ onQueryUpdate(action) {
2858
+ const notifyOptions = {};
2859
+
2860
+ if (action.type === 'success') {
2861
+ notifyOptions.onSuccess = !action.manual;
2862
+ } else if (action.type === 'error' && !isCancelledError(action.error)) {
2863
+ notifyOptions.onError = true;
2864
+ }
2865
+
2866
+ this.updateResult(notifyOptions);
2867
+
2868
+ if (this.hasListeners()) {
2869
+ this.updateTimers();
2870
+ }
2871
+ }
2872
+
2873
+ notify(notifyOptions) {
2874
+ notifyManager.batch(() => {
2875
+ // First trigger the configuration callbacks
2876
+ if (notifyOptions.onSuccess) {
2877
+ var _this$options$onSucce, _this$options, _this$options$onSettl, _this$options2;
2878
+
2879
+ (_this$options$onSucce = (_this$options = this.options).onSuccess) == null ? void 0 : _this$options$onSucce.call(_this$options, this.currentResult.data);
2880
+ (_this$options$onSettl = (_this$options2 = this.options).onSettled) == null ? void 0 : _this$options$onSettl.call(_this$options2, this.currentResult.data, null);
2881
+ } else if (notifyOptions.onError) {
2882
+ var _this$options$onError, _this$options3, _this$options$onSettl2, _this$options4;
2883
+
2884
+ (_this$options$onError = (_this$options3 = this.options).onError) == null ? void 0 : _this$options$onError.call(_this$options3, this.currentResult.error);
2885
+ (_this$options$onSettl2 = (_this$options4 = this.options).onSettled) == null ? void 0 : _this$options$onSettl2.call(_this$options4, undefined, this.currentResult.error);
2886
+ } // Then trigger the listeners
2887
+
2888
+
2889
+ if (notifyOptions.listeners) {
2890
+ this.listeners.forEach(({
2891
+ listener
2892
+ }) => {
2893
+ listener(this.currentResult);
2894
+ });
2895
+ } // Then the cache listeners
2896
+
2897
+
2898
+ if (notifyOptions.cache) {
2899
+ this.client.getQueryCache().notify({
2900
+ query: this.currentQuery,
2901
+ type: 'observerResultsUpdated'
2902
+ });
2903
+ }
2904
+ });
2905
+ }
2906
+
2907
+ }
2908
+
2909
+ function shouldLoadOnMount(query, options) {
2910
+ return options.enabled !== false && !query.state.dataUpdatedAt && !(query.state.status === 'error' && options.retryOnMount === false);
2911
+ }
2912
+
2913
+ function shouldFetchOnMount(query, options) {
2914
+ return shouldLoadOnMount(query, options) || query.state.dataUpdatedAt > 0 && shouldFetchOn(query, options, options.refetchOnMount);
2915
+ }
2916
+
2917
+ function shouldFetchOn(query, options, field) {
2918
+ if (options.enabled !== false) {
2919
+ const value = typeof field === 'function' ? field(query) : field;
2920
+ return value === 'always' || value !== false && isStale(query, options);
2921
+ }
2922
+
2923
+ return false;
2924
+ }
2925
+
2926
+ function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
2927
+ return options.enabled !== false && (query !== prevQuery || prevOptions.enabled === false) && (!options.suspense || query.state.status !== 'error') && isStale(query, options);
2928
+ }
2929
+
2930
+ function isStale(query, options) {
2931
+ return query.isStaleByTime(options.staleTime);
2932
+ } // this function would decide if we will update the observer's 'current'
2933
+ // properties after an optimistic reading via getOptimisticResult
2934
+
2935
+
2936
+ function shouldAssignObserverCurrentProperties(observer, optimisticResult, options) {
2937
+ // it is important to keep this condition like this for three reasons:
2938
+ // 1. It will get removed in the v5
2939
+ // 2. it reads: don't update the properties if we want to keep the previous
2940
+ // data.
2941
+ // 3. The opposite condition (!options.keepPreviousData) would fallthrough
2942
+ // and will result in a bad decision
2943
+ if (options.keepPreviousData) {
2944
+ return false;
2945
+ } // this means we want to put some placeholder data when pending and queryKey
2946
+ // changed.
2947
+
2948
+
2949
+ if (options.placeholderData !== undefined) {
2950
+ // re-assign properties only if current data is placeholder data
2951
+ // which means that data did not arrive yet, so, if there is some cached data
2952
+ // we need to "prepare" to receive it
2953
+ return optimisticResult.isPlaceholderData;
2954
+ } // if the newly created result isn't what the observer is holding as current,
2955
+ // then we'll need to update the properties as well
2956
+
2957
+
2958
+ if (!shallowEqualObjects(observer.getCurrentResult(), optimisticResult)) {
2959
+ return true;
2960
+ } // basically, just keep previous properties if nothing changed
2961
+
2962
+
2963
+ return false;
2964
+ }
2965
+
2966
+ class QueriesObserver extends Subscribable {
2967
+ constructor(client, queries) {
2968
+ super();
2969
+ this.client = client;
2970
+ this.queries = [];
2971
+ this.result = [];
2972
+ this.observers = [];
2973
+ this.observersMap = {};
2974
+
2975
+ if (queries) {
2976
+ this.setQueries(queries);
2977
+ }
2978
+ }
2979
+
2980
+ onSubscribe() {
2981
+ if (this.listeners.size === 1) {
2982
+ this.observers.forEach(observer => {
2983
+ observer.subscribe(result => {
2984
+ this.onUpdate(observer, result);
2985
+ });
2986
+ });
2987
+ }
2988
+ }
2989
+
2990
+ onUnsubscribe() {
2991
+ if (!this.listeners.size) {
2992
+ this.destroy();
2993
+ }
2994
+ }
2995
+
2996
+ destroy() {
2997
+ this.listeners = new Set();
2998
+ this.observers.forEach(observer => {
2999
+ observer.destroy();
3000
+ });
3001
+ }
3002
+
3003
+ setQueries(queries, notifyOptions) {
3004
+ this.queries = queries;
3005
+ notifyManager.batch(() => {
3006
+ const prevObservers = this.observers;
3007
+ const newObserverMatches = this.findMatchingObservers(this.queries); // set options for the new observers to notify of changes
3008
+
3009
+ newObserverMatches.forEach(match => match.observer.setOptions(match.defaultedQueryOptions, notifyOptions));
3010
+ const newObservers = newObserverMatches.map(match => match.observer);
3011
+ const newObserversMap = Object.fromEntries(newObservers.map(observer => [observer.options.queryHash, observer]));
3012
+ const newResult = newObservers.map(observer => observer.getCurrentResult());
3013
+ const hasIndexChange = newObservers.some((observer, index) => observer !== prevObservers[index]);
3014
+
3015
+ if (prevObservers.length === newObservers.length && !hasIndexChange) {
3016
+ return;
3017
+ }
3018
+
3019
+ this.observers = newObservers;
3020
+ this.observersMap = newObserversMap;
3021
+ this.result = newResult;
3022
+
3023
+ if (!this.hasListeners()) {
3024
+ return;
3025
+ }
3026
+
3027
+ difference(prevObservers, newObservers).forEach(observer => {
3028
+ observer.destroy();
3029
+ });
3030
+ difference(newObservers, prevObservers).forEach(observer => {
3031
+ observer.subscribe(result => {
3032
+ this.onUpdate(observer, result);
3033
+ });
3034
+ });
3035
+ this.notify();
3036
+ });
3037
+ }
3038
+
3039
+ getCurrentResult() {
3040
+ return this.result;
3041
+ }
3042
+
3043
+ getQueries() {
3044
+ return this.observers.map(observer => observer.getCurrentQuery());
3045
+ }
3046
+
3047
+ getObservers() {
3048
+ return this.observers;
3049
+ }
3050
+
3051
+ getOptimisticResult(queries) {
3052
+ return this.findMatchingObservers(queries).map(match => match.observer.getOptimisticResult(match.defaultedQueryOptions));
3053
+ }
3054
+
3055
+ findMatchingObservers(queries) {
3056
+ const prevObservers = this.observers;
3057
+ const prevObserversMap = new Map(prevObservers.map(observer => [observer.options.queryHash, observer]));
3058
+ const defaultedQueryOptions = queries.map(options => this.client.defaultQueryOptions(options));
3059
+ const matchingObservers = defaultedQueryOptions.flatMap(defaultedOptions => {
3060
+ const match = prevObserversMap.get(defaultedOptions.queryHash);
3061
+
3062
+ if (match != null) {
3063
+ return [{
3064
+ defaultedQueryOptions: defaultedOptions,
3065
+ observer: match
3066
+ }];
3067
+ }
3068
+
3069
+ return [];
3070
+ });
3071
+ const matchedQueryHashes = new Set(matchingObservers.map(match => match.defaultedQueryOptions.queryHash));
3072
+ const unmatchedQueries = defaultedQueryOptions.filter(defaultedOptions => !matchedQueryHashes.has(defaultedOptions.queryHash));
3073
+ const matchingObserversSet = new Set(matchingObservers.map(match => match.observer));
3074
+ const unmatchedObservers = prevObservers.filter(prevObserver => !matchingObserversSet.has(prevObserver));
3075
+
3076
+ const getObserver = options => {
3077
+ const defaultedOptions = this.client.defaultQueryOptions(options);
3078
+ const currentObserver = this.observersMap[defaultedOptions.queryHash];
3079
+ return currentObserver != null ? currentObserver : new QueryObserver(this.client, defaultedOptions);
3080
+ };
3081
+
3082
+ const newOrReusedObservers = unmatchedQueries.map((options, index) => {
3083
+ if (options.keepPreviousData) {
3084
+ // return previous data from one of the observers that no longer match
3085
+ const previouslyUsedObserver = unmatchedObservers[index];
3086
+
3087
+ if (previouslyUsedObserver !== undefined) {
3088
+ return {
3089
+ defaultedQueryOptions: options,
3090
+ observer: previouslyUsedObserver
3091
+ };
3092
+ }
3093
+ }
3094
+
3095
+ return {
3096
+ defaultedQueryOptions: options,
3097
+ observer: getObserver(options)
3098
+ };
3099
+ });
3100
+
3101
+ const sortMatchesByOrderOfQueries = (a, b) => defaultedQueryOptions.indexOf(a.defaultedQueryOptions) - defaultedQueryOptions.indexOf(b.defaultedQueryOptions);
3102
+
3103
+ return matchingObservers.concat(newOrReusedObservers).sort(sortMatchesByOrderOfQueries);
3104
+ }
3105
+
3106
+ onUpdate(observer, result) {
3107
+ const index = this.observers.indexOf(observer);
3108
+
3109
+ if (index !== -1) {
3110
+ this.result = replaceAt(this.result, index, result);
3111
+ this.notify();
3112
+ }
3113
+ }
3114
+
3115
+ notify() {
3116
+ notifyManager.batch(() => {
3117
+ this.listeners.forEach(({
3118
+ listener
3119
+ }) => {
3120
+ listener(this.result);
3121
+ });
3122
+ });
3123
+ }
3124
+
3125
+ }
3126
+
3127
+ // CLASS
3128
+ class MutationObserver extends Subscribable {
3129
+ constructor(client, options) {
3130
+ super();
3131
+ this.client = client;
3132
+ this.setOptions(options);
3133
+ this.bindMethods();
3134
+ this.updateResult();
3135
+ }
3136
+
3137
+ bindMethods() {
3138
+ this.mutate = this.mutate.bind(this);
3139
+ this.reset = this.reset.bind(this);
3140
+ }
3141
+
3142
+ setOptions(options) {
3143
+ var _this$currentMutation;
3144
+
3145
+ const prevOptions = this.options;
3146
+ this.options = this.client.defaultMutationOptions(options);
3147
+
3148
+ if (!shallowEqualObjects(prevOptions, this.options)) {
3149
+ this.client.getMutationCache().notify({
3150
+ type: 'observerOptionsUpdated',
3151
+ mutation: this.currentMutation,
3152
+ observer: this
3153
+ });
3154
+ }
3155
+
3156
+ (_this$currentMutation = this.currentMutation) == null ? void 0 : _this$currentMutation.setOptions(this.options);
3157
+ }
3158
+
3159
+ onUnsubscribe() {
3160
+ if (!this.hasListeners()) {
3161
+ var _this$currentMutation2;
3162
+
3163
+ (_this$currentMutation2 = this.currentMutation) == null ? void 0 : _this$currentMutation2.removeObserver(this);
3164
+ }
3165
+ }
3166
+
3167
+ onMutationUpdate(action) {
3168
+ this.updateResult(); // Determine which callbacks to trigger
3169
+
3170
+ const notifyOptions = {
3171
+ listeners: true
3172
+ };
3173
+
3174
+ if (action.type === 'success') {
3175
+ notifyOptions.onSuccess = true;
3176
+ } else if (action.type === 'error') {
3177
+ notifyOptions.onError = true;
3178
+ }
3179
+
3180
+ this.notify(notifyOptions);
3181
+ }
3182
+
3183
+ getCurrentResult() {
3184
+ return this.currentResult;
3185
+ }
3186
+
3187
+ reset() {
3188
+ this.currentMutation = undefined;
3189
+ this.updateResult();
3190
+ this.notify({
3191
+ listeners: true
3192
+ });
3193
+ }
3194
+
3195
+ mutate(variables, options) {
3196
+ this.mutateOptions = options;
3197
+
3198
+ if (this.currentMutation) {
3199
+ this.currentMutation.removeObserver(this);
218
3200
  }
3201
+
3202
+ this.currentMutation = this.client.getMutationCache().build(this.client, { ...this.options,
3203
+ variables: typeof variables !== 'undefined' ? variables : this.options.variables
3204
+ });
3205
+ this.currentMutation.addObserver(this);
3206
+ return this.currentMutation.execute();
3207
+ }
3208
+
3209
+ updateResult() {
3210
+ const state = this.currentMutation ? this.currentMutation.state : getDefaultState();
3211
+ const result = { ...state,
3212
+ isLoading: state.status === 'loading',
3213
+ isSuccess: state.status === 'success',
3214
+ isError: state.status === 'error',
3215
+ isIdle: state.status === 'idle',
3216
+ mutate: this.mutate,
3217
+ reset: this.reset
3218
+ };
3219
+ this.currentResult = result;
3220
+ }
3221
+
3222
+ notify(options) {
3223
+ notifyManager.batch(() => {
3224
+ // First trigger the mutate callbacks
3225
+ if (this.mutateOptions && this.hasListeners()) {
3226
+ if (options.onSuccess) {
3227
+ var _this$mutateOptions$o, _this$mutateOptions, _this$mutateOptions$o2, _this$mutateOptions2;
3228
+
3229
+ (_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);
3230
+ (_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);
3231
+ } else if (options.onError) {
3232
+ var _this$mutateOptions$o3, _this$mutateOptions3, _this$mutateOptions$o4, _this$mutateOptions4;
3233
+
3234
+ (_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);
3235
+ (_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);
3236
+ }
3237
+ } // Then trigger the listeners
3238
+
3239
+
3240
+ if (options.listeners) {
3241
+ this.listeners.forEach(({
3242
+ listener
3243
+ }) => {
3244
+ listener(this.currentResult);
3245
+ });
3246
+ }
3247
+ });
3248
+ }
3249
+
219
3250
  }
220
3251
 
221
3252
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
@@ -249,6 +3280,603 @@ function getAugmentedNamespace(n) {
249
3280
  return a;
250
3281
  }
251
3282
 
3283
+ var shim = {exports: {}};
3284
+
3285
+ var useSyncExternalStoreShim_production_min = {};
3286
+
3287
+ var require$$0$3 = /*@__PURE__*/getAugmentedNamespace(React);
3288
+
3289
+ /**
3290
+ * @license React
3291
+ * use-sync-external-store-shim.production.min.js
3292
+ *
3293
+ * Copyright (c) Facebook, Inc. and its affiliates.
3294
+ *
3295
+ * This source code is licensed under the MIT license found in the
3296
+ * LICENSE file in the root directory of this source tree.
3297
+ */
3298
+
3299
+ var hasRequiredUseSyncExternalStoreShim_production_min;
3300
+
3301
+ function requireUseSyncExternalStoreShim_production_min () {
3302
+ if (hasRequiredUseSyncExternalStoreShim_production_min) return useSyncExternalStoreShim_production_min;
3303
+ hasRequiredUseSyncExternalStoreShim_production_min = 1;
3304
+ var e=require$$0$3;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}
3305
+ function r(a){var b=a.getSnapshot;a=a.value;try{var d=b();return !k(a,d)}catch(f){return true}}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;
3306
+ return useSyncExternalStoreShim_production_min;
3307
+ }
3308
+
3309
+ var useSyncExternalStoreShim_development = {};
3310
+
3311
+ /**
3312
+ * @license React
3313
+ * use-sync-external-store-shim.development.js
3314
+ *
3315
+ * Copyright (c) Facebook, Inc. and its affiliates.
3316
+ *
3317
+ * This source code is licensed under the MIT license found in the
3318
+ * LICENSE file in the root directory of this source tree.
3319
+ */
3320
+
3321
+ var hasRequiredUseSyncExternalStoreShim_development;
3322
+
3323
+ function requireUseSyncExternalStoreShim_development () {
3324
+ if (hasRequiredUseSyncExternalStoreShim_development) return useSyncExternalStoreShim_development;
3325
+ hasRequiredUseSyncExternalStoreShim_development = 1;
3326
+
3327
+ if (process.env.NODE_ENV !== "production") {
3328
+ (function() {
3329
+
3330
+ /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
3331
+ if (
3332
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
3333
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===
3334
+ 'function'
3335
+ ) {
3336
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
3337
+ }
3338
+ var React = require$$0$3;
3339
+
3340
+ var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
3341
+
3342
+ function error(format) {
3343
+ {
3344
+ {
3345
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
3346
+ args[_key2 - 1] = arguments[_key2];
3347
+ }
3348
+
3349
+ printWarning('error', format, args);
3350
+ }
3351
+ }
3352
+ }
3353
+
3354
+ function printWarning(level, format, args) {
3355
+ // When changing this logic, you might want to also
3356
+ // update consoleWithStackDev.www.js as well.
3357
+ {
3358
+ var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
3359
+ var stack = ReactDebugCurrentFrame.getStackAddendum();
3360
+
3361
+ if (stack !== '') {
3362
+ format += '%s';
3363
+ args = args.concat([stack]);
3364
+ } // eslint-disable-next-line react-internal/safe-string-coercion
3365
+
3366
+
3367
+ var argsWithFormat = args.map(function (item) {
3368
+ return String(item);
3369
+ }); // Careful: RN currently depends on this prefix
3370
+
3371
+ argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
3372
+ // breaks IE9: https://github.com/facebook/react/issues/13610
3373
+ // eslint-disable-next-line react-internal/no-production-logging
3374
+
3375
+ Function.prototype.apply.call(console[level], console, argsWithFormat);
3376
+ }
3377
+ }
3378
+
3379
+ /**
3380
+ * inlined Object.is polyfill to avoid requiring consumers ship their own
3381
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
3382
+ */
3383
+ function is(x, y) {
3384
+ return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
3385
+ ;
3386
+ }
3387
+
3388
+ var objectIs = typeof Object.is === 'function' ? Object.is : is;
3389
+
3390
+ // dispatch for CommonJS interop named imports.
3391
+
3392
+ var useState = React.useState,
3393
+ useEffect = React.useEffect,
3394
+ useLayoutEffect = React.useLayoutEffect,
3395
+ useDebugValue = React.useDebugValue;
3396
+ var didWarnOld18Alpha = false;
3397
+ var didWarnUncachedGetSnapshot = false; // Disclaimer: This shim breaks many of the rules of React, and only works
3398
+ // because of a very particular set of implementation details and assumptions
3399
+ // -- change any one of them and it will break. The most important assumption
3400
+ // is that updates are always synchronous, because concurrent rendering is
3401
+ // only available in versions of React that also have a built-in
3402
+ // useSyncExternalStore API. And we only use this shim when the built-in API
3403
+ // does not exist.
3404
+ //
3405
+ // Do not assume that the clever hacks used by this hook also work in general.
3406
+ // The point of this shim is to replace the need for hacks by other libraries.
3407
+
3408
+ function useSyncExternalStore(subscribe, getSnapshot, // Note: The shim does not use getServerSnapshot, because pre-18 versions of
3409
+ // React do not expose a way to check if we're hydrating. So users of the shim
3410
+ // will need to track that themselves and return the correct value
3411
+ // from `getSnapshot`.
3412
+ getServerSnapshot) {
3413
+ {
3414
+ if (!didWarnOld18Alpha) {
3415
+ if (React.startTransition !== undefined) {
3416
+ didWarnOld18Alpha = true;
3417
+
3418
+ 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.');
3419
+ }
3420
+ }
3421
+ } // Read the current snapshot from the store on every render. Again, this
3422
+ // breaks the rules of React, and only works here because of specific
3423
+ // implementation details, most importantly that updates are
3424
+ // always synchronous.
3425
+
3426
+
3427
+ var value = getSnapshot();
3428
+
3429
+ {
3430
+ if (!didWarnUncachedGetSnapshot) {
3431
+ var cachedValue = getSnapshot();
3432
+
3433
+ if (!objectIs(value, cachedValue)) {
3434
+ error('The result of getSnapshot should be cached to avoid an infinite loop');
3435
+
3436
+ didWarnUncachedGetSnapshot = true;
3437
+ }
3438
+ }
3439
+ } // Because updates are synchronous, we don't queue them. Instead we force a
3440
+ // re-render whenever the subscribed state changes by updating an some
3441
+ // arbitrary useState hook. Then, during render, we call getSnapshot to read
3442
+ // the current value.
3443
+ //
3444
+ // Because we don't actually use the state returned by the useState hook, we
3445
+ // can save a bit of memory by storing other stuff in that slot.
3446
+ //
3447
+ // To implement the early bailout, we need to track some things on a mutable
3448
+ // object. Usually, we would put that in a useRef hook, but we can stash it in
3449
+ // our useState hook instead.
3450
+ //
3451
+ // To force a re-render, we call forceUpdate({inst}). That works because the
3452
+ // new object always fails an equality check.
3453
+
3454
+
3455
+ var _useState = useState({
3456
+ inst: {
3457
+ value: value,
3458
+ getSnapshot: getSnapshot
3459
+ }
3460
+ }),
3461
+ inst = _useState[0].inst,
3462
+ forceUpdate = _useState[1]; // Track the latest getSnapshot function with a ref. This needs to be updated
3463
+ // in the layout phase so we can access it during the tearing check that
3464
+ // happens on subscribe.
3465
+
3466
+
3467
+ useLayoutEffect(function () {
3468
+ inst.value = value;
3469
+ inst.getSnapshot = getSnapshot; // Whenever getSnapshot or subscribe changes, we need to check in the
3470
+ // commit phase if there was an interleaved mutation. In concurrent mode
3471
+ // this can happen all the time, but even in synchronous mode, an earlier
3472
+ // effect may have mutated the store.
3473
+
3474
+ if (checkIfSnapshotChanged(inst)) {
3475
+ // Force a re-render.
3476
+ forceUpdate({
3477
+ inst: inst
3478
+ });
3479
+ }
3480
+ }, [subscribe, value, getSnapshot]);
3481
+ useEffect(function () {
3482
+ // Check for changes right before subscribing. Subsequent changes will be
3483
+ // detected in the subscription handler.
3484
+ if (checkIfSnapshotChanged(inst)) {
3485
+ // Force a re-render.
3486
+ forceUpdate({
3487
+ inst: inst
3488
+ });
3489
+ }
3490
+
3491
+ var handleStoreChange = function () {
3492
+ // TODO: Because there is no cross-renderer API for batching updates, it's
3493
+ // up to the consumer of this library to wrap their subscription event
3494
+ // with unstable_batchedUpdates. Should we try to detect when this isn't
3495
+ // the case and print a warning in development?
3496
+ // The store changed. Check if the snapshot changed since the last time we
3497
+ // read from the store.
3498
+ if (checkIfSnapshotChanged(inst)) {
3499
+ // Force a re-render.
3500
+ forceUpdate({
3501
+ inst: inst
3502
+ });
3503
+ }
3504
+ }; // Subscribe to the store and return a clean-up function.
3505
+
3506
+
3507
+ return subscribe(handleStoreChange);
3508
+ }, [subscribe]);
3509
+ useDebugValue(value);
3510
+ return value;
3511
+ }
3512
+
3513
+ function checkIfSnapshotChanged(inst) {
3514
+ var latestGetSnapshot = inst.getSnapshot;
3515
+ var prevValue = inst.value;
3516
+
3517
+ try {
3518
+ var nextValue = latestGetSnapshot();
3519
+ return !objectIs(prevValue, nextValue);
3520
+ } catch (error) {
3521
+ return true;
3522
+ }
3523
+ }
3524
+
3525
+ function useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) {
3526
+ // Note: The shim does not use getServerSnapshot, because pre-18 versions of
3527
+ // React do not expose a way to check if we're hydrating. So users of the shim
3528
+ // will need to track that themselves and return the correct value
3529
+ // from `getSnapshot`.
3530
+ return getSnapshot();
3531
+ }
3532
+
3533
+ var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');
3534
+
3535
+ var isServerEnvironment = !canUseDOM;
3536
+
3537
+ var shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore;
3538
+ var useSyncExternalStore$2 = React.useSyncExternalStore !== undefined ? React.useSyncExternalStore : shim;
3539
+
3540
+ useSyncExternalStoreShim_development.useSyncExternalStore = useSyncExternalStore$2;
3541
+ /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
3542
+ if (
3543
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
3544
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===
3545
+ 'function'
3546
+ ) {
3547
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
3548
+ }
3549
+
3550
+ })();
3551
+ }
3552
+ return useSyncExternalStoreShim_development;
3553
+ }
3554
+
3555
+ if (process.env.NODE_ENV === 'production') {
3556
+ shim.exports = requireUseSyncExternalStoreShim_production_min();
3557
+ } else {
3558
+ shim.exports = requireUseSyncExternalStoreShim_development();
3559
+ }
3560
+
3561
+ var shimExports = shim.exports;
3562
+
3563
+ const useSyncExternalStore = shimExports.useSyncExternalStore;
3564
+
3565
+ const defaultContext = /*#__PURE__*/React.createContext(undefined);
3566
+ const QueryClientSharingContext = /*#__PURE__*/React.createContext(false); // If we are given a context, we will use it.
3567
+ // Otherwise, if contextSharing is on, we share the first and at least one
3568
+ // instance of the context across the window
3569
+ // to ensure that if React Query is used across
3570
+ // different bundles or microfrontends they will
3571
+ // all use the same **instance** of context, regardless
3572
+ // of module scoping.
3573
+
3574
+ function getQueryClientContext(context, contextSharing) {
3575
+ if (context) {
3576
+ return context;
3577
+ }
3578
+
3579
+ if (contextSharing && typeof window !== 'undefined') {
3580
+ if (!window.ReactQueryClientContext) {
3581
+ window.ReactQueryClientContext = defaultContext;
3582
+ }
3583
+
3584
+ return window.ReactQueryClientContext;
3585
+ }
3586
+
3587
+ return defaultContext;
3588
+ }
3589
+
3590
+ const useQueryClient = ({
3591
+ context
3592
+ } = {}) => {
3593
+ const queryClient = React.useContext(getQueryClientContext(context, React.useContext(QueryClientSharingContext)));
3594
+
3595
+ if (!queryClient) {
3596
+ throw new Error('No QueryClient set, use QueryClientProvider to set one');
3597
+ }
3598
+
3599
+ return queryClient;
3600
+ };
3601
+ const QueryClientProvider = ({
3602
+ client,
3603
+ children,
3604
+ context,
3605
+ contextSharing = false
3606
+ }) => {
3607
+ React.useEffect(() => {
3608
+ client.mount();
3609
+ return () => {
3610
+ client.unmount();
3611
+ };
3612
+ }, [client]);
3613
+
3614
+ if (process.env.NODE_ENV !== 'production' && contextSharing) {
3615
+ client.getLogger().error("The contextSharing option has been deprecated and will be removed in the next major version");
3616
+ }
3617
+
3618
+ const Context = getQueryClientContext(context, contextSharing);
3619
+ return /*#__PURE__*/React.createElement(QueryClientSharingContext.Provider, {
3620
+ value: !context && contextSharing
3621
+ }, /*#__PURE__*/React.createElement(Context.Provider, {
3622
+ value: client
3623
+ }, children));
3624
+ };
3625
+
3626
+ const IsRestoringContext = /*#__PURE__*/React.createContext(false);
3627
+ const useIsRestoring = () => React.useContext(IsRestoringContext);
3628
+ IsRestoringContext.Provider;
3629
+
3630
+ function createValue() {
3631
+ let isReset = false;
3632
+ return {
3633
+ clearReset: () => {
3634
+ isReset = false;
3635
+ },
3636
+ reset: () => {
3637
+ isReset = true;
3638
+ },
3639
+ isReset: () => {
3640
+ return isReset;
3641
+ }
3642
+ };
3643
+ }
3644
+
3645
+ const QueryErrorResetBoundaryContext = /*#__PURE__*/React.createContext(createValue()); // HOOK
3646
+
3647
+ const useQueryErrorResetBoundary = () => React.useContext(QueryErrorResetBoundaryContext); // COMPONENT
3648
+
3649
+ function shouldThrowError(_useErrorBoundary, params) {
3650
+ // Allow useErrorBoundary function to override throwing behavior on a per-error basis
3651
+ if (typeof _useErrorBoundary === 'function') {
3652
+ return _useErrorBoundary(...params);
3653
+ }
3654
+
3655
+ return !!_useErrorBoundary;
3656
+ }
3657
+
3658
+ const ensurePreventErrorBoundaryRetry = (options, errorResetBoundary) => {
3659
+ if (options.suspense || options.useErrorBoundary) {
3660
+ // Prevent retrying failed query if the error boundary has not been reset yet
3661
+ if (!errorResetBoundary.isReset()) {
3662
+ options.retryOnMount = false;
3663
+ }
3664
+ }
3665
+ };
3666
+ const useClearResetErrorBoundary = errorResetBoundary => {
3667
+ React.useEffect(() => {
3668
+ errorResetBoundary.clearReset();
3669
+ }, [errorResetBoundary]);
3670
+ };
3671
+ const getHasError = ({
3672
+ result,
3673
+ errorResetBoundary,
3674
+ useErrorBoundary,
3675
+ query
3676
+ }) => {
3677
+ return result.isError && !errorResetBoundary.isReset() && !result.isFetching && shouldThrowError(useErrorBoundary, [result.error, query]);
3678
+ };
3679
+
3680
+ const ensureStaleTime = defaultedOptions => {
3681
+ if (defaultedOptions.suspense) {
3682
+ // Always set stale time when using suspense to prevent
3683
+ // fetching again when directly mounting after suspending
3684
+ if (typeof defaultedOptions.staleTime !== 'number') {
3685
+ defaultedOptions.staleTime = 1000;
3686
+ }
3687
+ }
3688
+ };
3689
+ const willFetch = (result, isRestoring) => result.isLoading && result.isFetching && !isRestoring;
3690
+ const shouldSuspend = (defaultedOptions, result, isRestoring) => (defaultedOptions == null ? void 0 : defaultedOptions.suspense) && willFetch(result, isRestoring);
3691
+ const fetchOptimistic = (defaultedOptions, observer, errorResetBoundary) => observer.fetchOptimistic(defaultedOptions).then(({
3692
+ data
3693
+ }) => {
3694
+ defaultedOptions.onSuccess == null ? void 0 : defaultedOptions.onSuccess(data);
3695
+ defaultedOptions.onSettled == null ? void 0 : defaultedOptions.onSettled(data, null);
3696
+ }).catch(error => {
3697
+ errorResetBoundary.clearReset();
3698
+ defaultedOptions.onError == null ? void 0 : defaultedOptions.onError(error);
3699
+ defaultedOptions.onSettled == null ? void 0 : defaultedOptions.onSettled(undefined, error);
3700
+ });
3701
+
3702
+ function useQueries({
3703
+ queries,
3704
+ context
3705
+ }) {
3706
+ const queryClient = useQueryClient({
3707
+ context
3708
+ });
3709
+ const isRestoring = useIsRestoring();
3710
+ const errorResetBoundary = useQueryErrorResetBoundary();
3711
+ const defaultedQueries = React.useMemo(() => queries.map(options => {
3712
+ const defaultedOptions = queryClient.defaultQueryOptions(options); // Make sure the results are already in fetching state before subscribing or updating options
3713
+
3714
+ defaultedOptions._optimisticResults = isRestoring ? 'isRestoring' : 'optimistic';
3715
+ return defaultedOptions;
3716
+ }), [queries, queryClient, isRestoring]);
3717
+ defaultedQueries.forEach(query => {
3718
+ ensureStaleTime(query);
3719
+ ensurePreventErrorBoundaryRetry(query, errorResetBoundary);
3720
+ });
3721
+ useClearResetErrorBoundary(errorResetBoundary);
3722
+ const [observer] = React.useState(() => new QueriesObserver(queryClient, defaultedQueries));
3723
+ const optimisticResult = observer.getOptimisticResult(defaultedQueries);
3724
+ useSyncExternalStore(React.useCallback(onStoreChange => isRestoring ? () => undefined : observer.subscribe(notifyManager.batchCalls(onStoreChange)), [observer, isRestoring]), () => observer.getCurrentResult(), () => observer.getCurrentResult());
3725
+ React.useEffect(() => {
3726
+ // Do not notify on updates because of changes in the options because
3727
+ // these changes should already be reflected in the optimistic result.
3728
+ observer.setQueries(defaultedQueries, {
3729
+ listeners: false
3730
+ });
3731
+ }, [defaultedQueries, observer]);
3732
+ const shouldAtLeastOneSuspend = optimisticResult.some((result, index) => shouldSuspend(defaultedQueries[index], result, isRestoring));
3733
+ const suspensePromises = shouldAtLeastOneSuspend ? optimisticResult.flatMap((result, index) => {
3734
+ const options = defaultedQueries[index];
3735
+ const queryObserver = observer.getObservers()[index];
3736
+
3737
+ if (options && queryObserver) {
3738
+ if (shouldSuspend(options, result, isRestoring)) {
3739
+ return fetchOptimistic(options, queryObserver, errorResetBoundary);
3740
+ } else if (willFetch(result, isRestoring)) {
3741
+ void fetchOptimistic(options, queryObserver, errorResetBoundary);
3742
+ }
3743
+ }
3744
+
3745
+ return [];
3746
+ }) : [];
3747
+
3748
+ if (suspensePromises.length > 0) {
3749
+ throw Promise.all(suspensePromises);
3750
+ }
3751
+
3752
+ const observerQueries = observer.getQueries();
3753
+ const firstSingleResultWhichShouldThrow = optimisticResult.find((result, index) => {
3754
+ var _defaultedQueries$ind, _defaultedQueries$ind2;
3755
+
3756
+ return getHasError({
3757
+ result,
3758
+ errorResetBoundary,
3759
+ useErrorBoundary: (_defaultedQueries$ind = (_defaultedQueries$ind2 = defaultedQueries[index]) == null ? void 0 : _defaultedQueries$ind2.useErrorBoundary) != null ? _defaultedQueries$ind : false,
3760
+ query: observerQueries[index]
3761
+ });
3762
+ });
3763
+
3764
+ if (firstSingleResultWhichShouldThrow != null && firstSingleResultWhichShouldThrow.error) {
3765
+ throw firstSingleResultWhichShouldThrow.error;
3766
+ }
3767
+
3768
+ return optimisticResult;
3769
+ }
3770
+
3771
+ function useBaseQuery(options, Observer) {
3772
+ const queryClient = useQueryClient({
3773
+ context: options.context
3774
+ });
3775
+ const isRestoring = useIsRestoring();
3776
+ const errorResetBoundary = useQueryErrorResetBoundary();
3777
+ const defaultedOptions = queryClient.defaultQueryOptions(options); // Make sure results are optimistically set in fetching state before subscribing or updating options
3778
+
3779
+ defaultedOptions._optimisticResults = isRestoring ? 'isRestoring' : 'optimistic'; // Include callbacks in batch renders
3780
+
3781
+ if (defaultedOptions.onError) {
3782
+ defaultedOptions.onError = notifyManager.batchCalls(defaultedOptions.onError);
3783
+ }
3784
+
3785
+ if (defaultedOptions.onSuccess) {
3786
+ defaultedOptions.onSuccess = notifyManager.batchCalls(defaultedOptions.onSuccess);
3787
+ }
3788
+
3789
+ if (defaultedOptions.onSettled) {
3790
+ defaultedOptions.onSettled = notifyManager.batchCalls(defaultedOptions.onSettled);
3791
+ }
3792
+
3793
+ ensureStaleTime(defaultedOptions);
3794
+ ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary);
3795
+ useClearResetErrorBoundary(errorResetBoundary);
3796
+ const [observer] = React.useState(() => new Observer(queryClient, defaultedOptions));
3797
+ const result = observer.getOptimisticResult(defaultedOptions);
3798
+ useSyncExternalStore(React.useCallback(onStoreChange => {
3799
+ const unsubscribe = isRestoring ? () => undefined : observer.subscribe(notifyManager.batchCalls(onStoreChange)); // Update result to make sure we did not miss any query updates
3800
+ // between creating the observer and subscribing to it.
3801
+
3802
+ observer.updateResult();
3803
+ return unsubscribe;
3804
+ }, [observer, isRestoring]), () => observer.getCurrentResult(), () => observer.getCurrentResult());
3805
+ React.useEffect(() => {
3806
+ // Do not notify on updates because of changes in the options because
3807
+ // these changes should already be reflected in the optimistic result.
3808
+ observer.setOptions(defaultedOptions, {
3809
+ listeners: false
3810
+ });
3811
+ }, [defaultedOptions, observer]); // Handle suspense
3812
+
3813
+ if (shouldSuspend(defaultedOptions, result, isRestoring)) {
3814
+ throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary);
3815
+ } // Handle error boundary
3816
+
3817
+
3818
+ if (getHasError({
3819
+ result,
3820
+ errorResetBoundary,
3821
+ useErrorBoundary: defaultedOptions.useErrorBoundary,
3822
+ query: observer.getCurrentQuery()
3823
+ })) {
3824
+ throw result.error;
3825
+ } // Handle result property usage tracking
3826
+
3827
+
3828
+ return !defaultedOptions.notifyOnChangeProps ? observer.trackResult(result) : result;
3829
+ }
3830
+
3831
+ function useQuery(arg1, arg2, arg3) {
3832
+ const parsedOptions = parseQueryArgs(arg1, arg2, arg3);
3833
+ return useBaseQuery(parsedOptions, QueryObserver);
3834
+ }
3835
+
3836
+ function useMutation(arg1, arg2, arg3) {
3837
+ const options = parseMutationArgs(arg1, arg2, arg3);
3838
+ const queryClient = useQueryClient({
3839
+ context: options.context
3840
+ });
3841
+ const [observer] = React.useState(() => new MutationObserver(queryClient, options));
3842
+ React.useEffect(() => {
3843
+ observer.setOptions(options);
3844
+ }, [observer, options]);
3845
+ const result = useSyncExternalStore(React.useCallback(onStoreChange => observer.subscribe(notifyManager.batchCalls(onStoreChange)), [observer]), () => observer.getCurrentResult(), () => observer.getCurrentResult());
3846
+ const mutate = React.useCallback((variables, mutateOptions) => {
3847
+ observer.mutate(variables, mutateOptions).catch(noop);
3848
+ }, [observer]);
3849
+
3850
+ if (result.error && shouldThrowError(observer.options.useErrorBoundary, [result.error])) {
3851
+ throw result.error;
3852
+ }
3853
+
3854
+ return { ...result,
3855
+ mutate,
3856
+ mutateAsync: result.mutate
3857
+ };
3858
+ } // eslint-disable-next-line @typescript-eslint/no-empty-function
3859
+
3860
+ function noop() {}
3861
+
3862
+ var TransactionErrorType;
3863
+ (function (TransactionErrorType) {
3864
+ TransactionErrorType[TransactionErrorType["REJECTED_BY_USER"] = 0] = "REJECTED_BY_USER";
3865
+ TransactionErrorType[TransactionErrorType["CALL_EXCEPTION"] = 1] = "CALL_EXCEPTION";
3866
+ TransactionErrorType[TransactionErrorType["UNKNOWN"] = 2] = "UNKNOWN";
3867
+ TransactionErrorType[TransactionErrorType["WARNING"] = 3] = "WARNING";
3868
+ })(TransactionErrorType || (TransactionErrorType = {}));
3869
+ var SquidStatusErrorType;
3870
+ (function (SquidStatusErrorType) {
3871
+ SquidStatusErrorType["NotFoundError"] = "NotFoundError";
3872
+ })(SquidStatusErrorType || (SquidStatusErrorType = {}));
3873
+ class QrCodeGenerationError extends Error {
3874
+ constructor(message) {
3875
+ super(message);
3876
+ this.name = "QrCodeGenerationError";
3877
+ }
3878
+ }
3879
+
252
3880
  /**
253
3881
  * The base implementation of `_.slice` without an iteratee call guard.
254
3882
  *
@@ -20096,17 +23724,14 @@ function isXrplAddressValid(address) {
20096
23724
  return isValidXAddress(address) || isValidClassicAddress(address);
20097
23725
  }
20098
23726
  function buildXrplTrustSetTx({ amount, sourceAddress, token, }) {
20099
- const asset = parseXrplTokenAddress(token.address);
20100
- if (!asset) {
20101
- throw new Error("Invalid asset");
20102
- }
23727
+ const [currency, issuer] = token.address.split(".");
20103
23728
  return {
20104
23729
  TransactionType: XrplTransactionType.TRUST_SET,
20105
23730
  Flags: XrplTransactionFlag.tfSetNoRipple,
20106
23731
  Account: sourceAddress,
20107
23732
  LimitAmount: {
20108
- currency: asset.code,
20109
- issuer: asset.issuer,
23733
+ currency,
23734
+ issuer,
20110
23735
  value: amount,
20111
23736
  },
20112
23737
  };
@@ -20135,16 +23760,6 @@ function parseXrplPaymentTx(data) {
20135
23760
  throw new Error("Could not parse payment transaction");
20136
23761
  }
20137
23762
  }
20138
- function parseXrplTokenAddress(address) {
20139
- const [code, issuer] = address.split(".");
20140
- if (!code || !issuer) {
20141
- return null;
20142
- }
20143
- return {
20144
- code,
20145
- issuer,
20146
- };
20147
- }
20148
23763
 
20149
23764
  const chains = [XrplCAIP2ChainId.MAINNET, XrplCAIP2ChainId.TESTNET];
20150
23765
  class XrplWalletConnect {
@@ -21110,28 +24725,6 @@ const executeSolanaTransfer = async ({ amount, target, signer, connection, sourc
21110
24725
  return signature;
21111
24726
  };
21112
24727
 
21113
- var StellarHorizonAssetType;
21114
- (function (StellarHorizonAssetType) {
21115
- /**
21116
- * XLM native token
21117
- */
21118
- StellarHorizonAssetType["NATIVE"] = "native";
21119
- /**
21120
- * 1-4 char asset code (e.g. USDC)
21121
- */
21122
- StellarHorizonAssetType["ALPHANUM4"] = "credit_alphanum4";
21123
- /**
21124
- * 5-12 char asset code (e.g. wstETH)
21125
- */
21126
- StellarHorizonAssetType["ALPHANUM12"] = "credit_alphanum12";
21127
- })(StellarHorizonAssetType || (StellarHorizonAssetType = {}));
21128
- var StellarTokenType;
21129
- (function (StellarTokenType) {
21130
- StellarTokenType["NATIVE_TOKEN"] = "nativeToken";
21131
- StellarTokenType["ISSUER_TOKEN"] = "issuerToken";
21132
- StellarTokenType["CONTRACT_TOKEN"] = "contractToken";
21133
- })(StellarTokenType || (StellarTokenType = {}));
21134
-
21135
24728
  function isStellarAddressValid(address) {
21136
24729
  return StrKey.isValidEd25519PublicKey(address);
21137
24730
  }
@@ -21153,78 +24746,6 @@ function stellarAddressToScVal(addressString) {
21153
24746
  type: "address",
21154
24747
  });
21155
24748
  }
21156
- function getStellarTrustLineAsset(token) {
21157
- // The address format for issued assets is `CODE-ISSUER`
21158
- // Example: USDC-GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN
21159
- const [code, issuer] = token.address.split("-");
21160
- if (!code || !issuer) {
21161
- return null;
21162
- }
21163
- return {
21164
- code,
21165
- issuer,
21166
- };
21167
- }
21168
- function isStellarToken(token) {
21169
- try {
21170
- const stellarToken = token;
21171
- return (Object.values(StellarTokenType).includes(stellarToken.chainAssetConfig.stellar.assetType) &&
21172
- typeof stellarToken.chainAssetConfig.stellar.contractAddress === "string");
21173
- }
21174
- catch {
21175
- return false;
21176
- }
21177
- }
21178
- function isStellarIssuedToken(token) {
21179
- try {
21180
- return (isStellarToken(token) &&
21181
- token.chainAssetConfig.stellar.assetType === StellarTokenType.ISSUER_TOKEN);
21182
- }
21183
- catch {
21184
- return false;
21185
- }
21186
- }
21187
- function getStellarHorizonApiUrl(chain) {
21188
- try {
21189
- const stellarChain = chain;
21190
- const [horizonApiUrl] = stellarChain.horizonRpcList;
21191
- if (typeof horizonApiUrl !== "string") {
21192
- throw new Error("Invalid Horizon API URL");
21193
- }
21194
- return horizonApiUrl;
21195
- }
21196
- catch {
21197
- return null;
21198
- }
21199
- }
21200
- const VALID_ASSET_TYPES = new Set(Object.values(StellarHorizonAssetType));
21201
- function isValidNativeAsset(asset) {
21202
- return (typeof asset === "object" &&
21203
- asset !== null &&
21204
- "balance" in asset &&
21205
- typeof asset.balance === "string" &&
21206
- "asset_type" in asset &&
21207
- asset.asset_type === StellarHorizonAssetType.NATIVE);
21208
- }
21209
- function isValidIssuedAsset(asset) {
21210
- return (typeof asset === "object" &&
21211
- asset !== null &&
21212
- "balance" in asset &&
21213
- typeof asset.balance === "string" &&
21214
- "asset_type" in asset &&
21215
- typeof asset.asset_type === "string" &&
21216
- VALID_ASSET_TYPES.has(asset.asset_type) &&
21217
- asset.asset_type !== StellarHorizonAssetType.NATIVE &&
21218
- "asset_code" in asset &&
21219
- typeof asset.asset_code === "string" &&
21220
- "asset_issuer" in asset &&
21221
- typeof asset.asset_issuer === "string" &&
21222
- "limit" in asset &&
21223
- typeof asset.limit === "string");
21224
- }
21225
- function isValidHorizonAsset(asset) {
21226
- return isValidNativeAsset(asset) || isValidIssuedAsset(asset);
21227
- }
21228
24749
 
21229
24750
  const SUI_FEATURES = ["sui:signTransaction"];
21230
24751
  function isSuiStandardWallet(wallet) {
@@ -22303,8 +25824,6 @@ var QueryKeys;
22303
25824
  QueryKeys["XrplAccountActivatedInfo"] = "xrplAccountActivatedInfo";
22304
25825
  QueryKeys["FiatToCryptoPaymentMethods"] = "fiatToCryptoPaymentMethods";
22305
25826
  QueryKeys["Stellar"] = "stellar";
22306
- QueryKeys["StellarTrustLine"] = "stellarTrustLine";
22307
- QueryKeys["IsStellarTrustLineApproved"] = "isStellarTrustLineApproved";
22308
25827
  QueryKeys["StellarAccountActivatedInfo"] = "stellarAccountActivatedInfo";
22309
25828
  QueryKeys["Hedera"] = "hedera";
22310
25829
  QueryKeys["IsHederaTokenAssociated"] = "isHederaTokenAssociated";
@@ -22412,7 +25931,7 @@ const keys = () => ({
22412
25931
  // ============
22413
25932
  // Approval
22414
25933
  // ============
22415
- routeApproved: (routeData, allowanceInWei, isAllowanceQueryEnabled, hasAllowance) => [
25934
+ routeApproved: (routeData, allowanceInWei) => [
22416
25935
  ...keys().transactions(),
22417
25936
  QueryKeys.RouteApproved,
22418
25937
  routeData?.params.fromAddress,
@@ -22420,8 +25939,6 @@ const keys = () => ({
22420
25939
  routeData?.params.fromToken,
22421
25940
  routeData?.params.fromAmount,
22422
25941
  allowanceInWei?.toString(),
22423
- isAllowanceQueryEnabled,
22424
- hasAllowance,
22425
25942
  ],
22426
25943
  sendTransactionGas: (chainId, tokenAddress, from) => [
22427
25944
  QueryKeys.All,
@@ -22494,23 +26011,6 @@ const keys = () => ({
22494
26011
  // ============
22495
26012
  // Stellar
22496
26013
  // ============
22497
- stellarTrustLine: (tokenAddress, chainId, address) => [
22498
- ...keys().stellar(),
22499
- QueryKeys.StellarTrustLine,
22500
- tokenAddress,
22501
- chainId,
22502
- address,
22503
- ],
22504
- isStellarTrustLineApproved: (address, chainId, chainType, tokenAddress, trustLineLimit, amountToApprove) => [
22505
- ...keys().stellar(),
22506
- QueryKeys.IsStellarTrustLineApproved,
22507
- address,
22508
- chainId,
22509
- chainType,
22510
- tokenAddress,
22511
- trustLineLimit,
22512
- amountToApprove?.toString(),
22513
- ],
22514
26014
  stellarAccountActivatedInfo: (address, chainId, chainType) => [
22515
26015
  ...keys().stellar(),
22516
26016
  QueryKeys.StellarAccountActivatedInfo,
@@ -22546,8 +26046,6 @@ const getPrefixKey = (key) => {
22546
26046
  return [...keys().transactions(), key];
22547
26047
  case QueryKeys.XrplTrustLine:
22548
26048
  return [...keys().xrpl(), key];
22549
- case QueryKeys.StellarTrustLine:
22550
- return [...keys().stellar(), key];
22551
26049
  case QueryKeys.IsHederaTokenAssociated:
22552
26050
  return [...keys().hedera(), key];
22553
26051
  default:
@@ -23262,7 +26760,7 @@ const filterViewableTokens = (tokens, config, direction) => {
23262
26760
  };
23263
26761
  const getSecretNetworkBalances = async (chainData, cosmosAddress, squidTokens, keplrTypeWallet) => {
23264
26762
  const squidSecretTokens = squidTokens.filter((t) => t.chainId === CHAIN_IDS.SECRET);
23265
- const { fetchAllSecretBalances } = await import('./secretService-D8hWz2Gz.js');
26763
+ const { fetchAllSecretBalances } = await import('./secretService-BwFxfXV7.js');
23266
26764
  return fetchAllSecretBalances(chainData, cosmosAddress, squidSecretTokens, keplrTypeWallet);
23267
26765
  };
23268
26766
  function getTokenAssetsKey(token) {
@@ -26326,7 +29824,7 @@ function useBitcoin() {
26326
29824
  const BitcoinContext = createContext(undefined);
26327
29825
  const BitcoinProvider = ({ children, }) => {
26328
29826
  const bitcoinContext = useBitcoin();
26329
- return (React.createElement(BitcoinContext.Provider, { value: bitcoinContext }, children));
29827
+ return (React__default.createElement(BitcoinContext.Provider, { value: bitcoinContext }, children));
26330
29828
  };
26331
29829
  const useBitcoinContext = () => {
26332
29830
  const context = useContext(BitcoinContext);
@@ -26411,7 +29909,7 @@ function useEvm() {
26411
29909
  const EvmContext = createContext(undefined);
26412
29910
  const EvmProvider = ({ children, }) => {
26413
29911
  const evmContext = useEvm();
26414
- return (React.createElement(EvmContext.Provider, { value: evmContext }, children));
29912
+ return (React__default.createElement(EvmContext.Provider, { value: evmContext }, children));
26415
29913
  };
26416
29914
  const useEvmContext = () => {
26417
29915
  const context = useContext(EvmContext);
@@ -26528,7 +30026,7 @@ const useSolanaConnection = () => {
26528
30026
  const SolanaContext = createContext(undefined);
26529
30027
  const SolanaProvider = ({ children, }) => {
26530
30028
  const solanaHook = useSolana();
26531
- return (React.createElement(SolanaContext.Provider, { value: solanaHook }, children));
30029
+ return (React__default.createElement(SolanaContext.Provider, { value: solanaHook }, children));
26532
30030
  };
26533
30031
  const useSolanaContext = () => {
26534
30032
  const context = useContext(SolanaContext);
@@ -26547,7 +30045,7 @@ function useStellarWallets() {
26547
30045
  try {
26548
30046
  const { allowAllModules: initializeAllModules } = await import('@creit.tech/stellar-wallets-kit');
26549
30047
  const { LedgerModule } = await import('@creit.tech/stellar-wallets-kit/modules/ledger.module');
26550
- const { formatStellarWallet } = await import('./stellarService.client-Dve9IZZm.js');
30048
+ const { formatStellarWallet } = await import('./stellarService.client-OMPy5fjH.js');
26551
30049
  const modules = [...initializeAllModules(), new LedgerModule()];
26552
30050
  const promises = modules.map(async (module) => {
26553
30051
  const isAvailable = await module.isAvailable();
@@ -26596,7 +30094,7 @@ function useStellar() {
26596
30094
  const StellarContext = createContext(undefined);
26597
30095
  const StellarProvider = ({ children, }) => {
26598
30096
  const stellarContext = useStellar();
26599
- return (React.createElement(StellarContext.Provider, { value: stellarContext }, children));
30097
+ return (React__default.createElement(StellarContext.Provider, { value: stellarContext }, children));
26600
30098
  };
26601
30099
  const useStellarContext = () => {
26602
30100
  const context = useContext(StellarContext);
@@ -26705,7 +30203,7 @@ function useSui() {
26705
30203
  const SuiContext = createContext(undefined);
26706
30204
  const SuiProvider = ({ children, }) => {
26707
30205
  const suiContext = useSui();
26708
- return (React.createElement(SuiContext.Provider, { value: suiContext }, children));
30206
+ return (React__default.createElement(SuiContext.Provider, { value: suiContext }, children));
26709
30207
  };
26710
30208
  const useSuiContext = () => {
26711
30209
  const context = useContext(SuiContext);
@@ -27003,7 +30501,7 @@ function useXrpl() {
27003
30501
  const XrplContext = createContext(undefined);
27004
30502
  const XrplProvider = ({ children, }) => {
27005
30503
  const xrplContext = useXrpl();
27006
- return (React.createElement(XrplContext.Provider, { value: xrplContext }, children));
30504
+ return (React__default.createElement(XrplContext.Provider, { value: xrplContext }, children));
27007
30505
  };
27008
30506
  const useXrplContext = () => {
27009
30507
  const context = useContext(XrplContext);
@@ -27823,15 +31321,15 @@ function useCosmosSigner({ chain }) {
27823
31321
  return { signer, keplrTypeWallet: connector };
27824
31322
  }
27825
31323
 
27826
- const CosmosContext = React.createContext({
31324
+ const CosmosContext = React__default.createContext({
27827
31325
  getCosmosAddressForChain: async () => "",
27828
31326
  });
27829
31327
  const CosmosProvider = ({ children }) => {
27830
31328
  const cosmosContext = useCosmos();
27831
- return (React.createElement(CosmosContext.Provider, { value: cosmosContext }, children));
31329
+ return (React__default.createElement(CosmosContext.Provider, { value: cosmosContext }, children));
27832
31330
  };
27833
31331
  function useCosmosContext() {
27834
- return React.useContext(CosmosContext);
31332
+ return React__default.useContext(CosmosContext);
27835
31333
  }
27836
31334
 
27837
31335
  /**
@@ -28047,7 +31545,7 @@ function hederaWalletConnect(parameters) {
28047
31545
  const optionalChains = config.chains.map((x) => x.id);
28048
31546
  if (!optionalChains.length)
28049
31547
  return;
28050
- const { EthereumProvider } = await import('./index.es-CMuCSzqv.js');
31548
+ const { EthereumProvider } = await import('./index.es-C4uVlA0B.js');
28051
31549
  const rawProvider = await EthereumProvider.init({
28052
31550
  ...restParameters,
28053
31551
  disableProviderPing: true,
@@ -29410,15 +32908,12 @@ const getAllXrplTokensBalance = async (userAddress, xrplTokens, xrplChains) => {
29410
32908
  };
29411
32909
  const getStellarTokenBalance = async (userAddress, token, chain) => {
29412
32910
  const stellarClient = await getClient(chain);
29413
- if (!isStellarToken(token)) {
29414
- throw new Error("Token must be a Stellar token");
29415
- }
29416
- const balance = await stellarClient.getBalance(userAddress, token.chainAssetConfig.stellar.contractAddress, chain.chainId);
32911
+ const balance = await stellarClient.getBalance(userAddress, token.address, chain.chainId);
29417
32912
  return BigInt(balance);
29418
32913
  };
29419
32914
  const getAllStellarTokensBalance = async (userAddress, stellarTokens, stellarChains) => {
29420
32915
  const getBalancesForChain = async (chain) => {
29421
- const tokensForChain = stellarTokens.filter((t) => t.chainId === chain.chainId && isStellarToken(t));
32916
+ const tokensForChain = stellarTokens.filter((t) => t.chainId === chain.chainId);
29422
32917
  const stellarClient = await getClient(chain);
29423
32918
  const allBalances = await stellarClient.getAllBalances(userAddress, tokensForChain);
29424
32919
  return allBalances.map((token) => {
@@ -29473,7 +32968,7 @@ class StellarRpcClient {
29473
32968
  .build();
29474
32969
  const simulateTxResponse = await this.server.simulateTransaction(tx);
29475
32970
  if ("error" in simulateTxResponse) {
29476
- const isNoBalanceError = /trying to get non-existing value for contract instance|trustline entry is missing for account/.test(simulateTxResponse.error);
32971
+ const isNoBalanceError = simulateTxResponse.error.includes("trying to get non-existing value for contract instance");
29477
32972
  // If the error message indicates that the user has no balance just return 0
29478
32973
  // We don't want to spam with this error as it's pretty common
29479
32974
  if (isNoBalanceError) {
@@ -29489,7 +32984,7 @@ class StellarRpcClient {
29489
32984
  }
29490
32985
  async getAllBalances(userAddress, tokens) {
29491
32986
  const balancePromises = tokens.map((token) => {
29492
- return this.getBalance(userAddress, token.chainAssetConfig.stellar.contractAddress, token.chainId);
32987
+ return this.getBalance(userAddress, token.address, token.chainId);
29493
32988
  });
29494
32989
  const results = await Promise.allSettled(balancePromises);
29495
32990
  const balances = results.map((result) => {
@@ -29589,9 +33084,9 @@ class XrplRpcClient {
29589
33084
  },
29590
33085
  ]);
29591
33086
  }
29592
- async getTrustLine(address, asset) {
29593
- const response = await this.getTrustLines(address, asset.issuer);
29594
- const trustLine = response.lines.find((line) => line.currency === asset.code);
33087
+ async getTrustLine(address, issuer, currency) {
33088
+ const response = await this.getTrustLines(address, issuer);
33089
+ const trustLine = response.lines.find((line) => line.currency === currency);
29595
33090
  return trustLine ?? null;
29596
33091
  }
29597
33092
  async accountActivatedInfo(address) {
@@ -29767,26 +33262,9 @@ class StellarApiClient {
29767
33262
  const baseReserveBn = BigInt(latestLedger.base_reserve_in_stroops);
29768
33263
  return baseReserveBn;
29769
33264
  }
29770
- async getTrustLines(userAddress) {
29771
- const response = await fetch(`${this.apiUrl}/accounts/${userAddress}`);
29772
- if (!response.ok) {
29773
- throw new Error(`Failed to fetch account data: ${response.statusText}`);
29774
- }
29775
- const data = await response.json();
29776
- if (!Array.isArray(data?.balances)) {
29777
- throw new Error("Invalid response from Horizon API");
29778
- }
29779
- const assets = data.balances.filter(isValidHorizonAsset);
29780
- return assets.filter(isValidIssuedAsset);
29781
- }
29782
- async getTrustLine(address, asset) {
29783
- const trustLines = await this.getTrustLines(address);
29784
- const trustLine = trustLines.find((line) => line.asset_code === asset.code && line.asset_issuer === asset.issuer);
29785
- return trustLine ?? null;
29786
- }
29787
33265
  }
29788
33266
 
29789
- const DEFAULT_REFETCH_INTERVAL$2 = 20_000;
33267
+ const DEFAULT_REFETCH_INTERVAL$1 = 20_000;
29790
33268
  function useStellarAccountActivation({ address, chain, token, }) {
29791
33269
  /**
29792
33270
  * Checks if the destination account exists on the Stellar network
@@ -29802,8 +33280,9 @@ function useStellarAccountActivation({ address, chain, token, }) {
29802
33280
  if (!address) {
29803
33281
  throw new Error("Destination address is required");
29804
33282
  }
29805
- const horizonApiUrl = getStellarHorizonApiUrl(chain);
29806
- if (!horizonApiUrl) {
33283
+ // TODO: update types
33284
+ const [horizonApiUrl] = chain?.horizonRpcList;
33285
+ if (typeof horizonApiUrl !== "string") {
29807
33286
  throw new Error("Invalid Horizon API URL");
29808
33287
  }
29809
33288
  const stellarApiClient = new StellarApiClient(horizonApiUrl);
@@ -29819,7 +33298,7 @@ function useStellarAccountActivation({ address, chain, token, }) {
29819
33298
  };
29820
33299
  },
29821
33300
  enabled: !!address && chain?.chainType === ChainType.STELLAR,
29822
- refetchInterval: DEFAULT_REFETCH_INTERVAL$2,
33301
+ refetchInterval: DEFAULT_REFETCH_INTERVAL$1,
29823
33302
  refetchOnWindowFocus: true,
29824
33303
  });
29825
33304
  return {
@@ -29827,149 +33306,6 @@ function useStellarAccountActivation({ address, chain, token, }) {
29827
33306
  };
29828
33307
  }
29829
33308
 
29830
- /**
29831
- * Maximum asset amount on Stellar
29832
- * @see https://developers.stellar.org/docs/learn/fundamentals/stellar-data-structures/assets#amount-precision
29833
- */
29834
- const MAX_ASSET_AMOUNT = "922337203685.4775807";
29835
- const DEFAULT_REFETCH_INTERVAL$1 = 20_000;
29836
- function useStellarTrustLine({ address, chain, token, amount }) {
29837
- const { stellarSigner } = useSigner({ chain });
29838
- const queryClient = useQueryClient();
29839
- /**
29840
- * Retrieves the destination account's trust line data for the given token
29841
- */
29842
- const trustLineQuery = useQuery({
29843
- queryKey: keys().stellarTrustLine(token?.address, chain?.chainId, address),
29844
- queryFn: async () => {
29845
- if (chain?.chainType !== ChainType.STELLAR ||
29846
- token?.type !== ChainType.STELLAR) {
29847
- return null;
29848
- }
29849
- if (!address || !isStellarAddressValid(address)) {
29850
- return null;
29851
- }
29852
- // Only issued tokens require trust lines
29853
- // Other token types like contract tokens don't need trust lines
29854
- if (!isStellarIssuedToken(token)) {
29855
- return null;
29856
- }
29857
- const asset = getStellarTrustLineAsset(token);
29858
- if (!asset) {
29859
- throw new Error("Invalid asset");
29860
- }
29861
- const horizonApiUrl = getStellarHorizonApiUrl(chain);
29862
- if (!horizonApiUrl) {
29863
- throw new Error("Invalid Horizon API URL");
29864
- }
29865
- const stellarApiClient = new StellarApiClient(horizonApiUrl);
29866
- return stellarApiClient.getTrustLine(address, asset);
29867
- },
29868
- enabled: !!address &&
29869
- chain?.chainType === ChainType.STELLAR &&
29870
- token?.type === ChainType.STELLAR,
29871
- refetchInterval: DEFAULT_REFETCH_INTERVAL$1,
29872
- });
29873
- /**
29874
- * Creates a trust line where the destination account authorizes to receive the given token
29875
- */
29876
- const createTrustLine = useMutation({
29877
- mutationFn: async () => {
29878
- try {
29879
- if (!stellarSigner) {
29880
- throw new Error("Stellar signer not found");
29881
- }
29882
- if (!address) {
29883
- throw new Error("Destination address is required");
29884
- }
29885
- if (chain?.chainType !== ChainType.STELLAR ||
29886
- token?.type !== ChainType.STELLAR) {
29887
- throw new Error("Chain and token to approve must be a Stellar token");
29888
- }
29889
- if (!isStellarIssuedToken(token)) {
29890
- throw new Error("Token must be a Stellar issued token");
29891
- }
29892
- const assetInfo = getStellarTrustLineAsset(token);
29893
- if (!assetInfo) {
29894
- throw new Error("Invalid asset");
29895
- }
29896
- const network = getStellarNetwork(chain.chainId);
29897
- if (network == null) {
29898
- throw new Error(`Stellar network not found for chain ${chain.chainId}`);
29899
- }
29900
- const client = await getClient(chain);
29901
- const account = await client.getAccount(address);
29902
- const asset = new Asset(assetInfo.code, assetInfo.issuer);
29903
- const changeTrustOperation = Operation.changeTrust({
29904
- asset,
29905
- limit: MAX_ASSET_AMOUNT,
29906
- });
29907
- const builtTransaction = new TransactionBuilder(account, {
29908
- fee: (BigInt(BASE_FEE) * BigInt(2)).toString(),
29909
- networkPassphrase: network,
29910
- })
29911
- .addOperation(changeTrustOperation)
29912
- .setTimeout(300)
29913
- .build();
29914
- const { signedTxXdr } = await stellarSigner.signTransaction(builtTransaction.toXDR(), {
29915
- networkPassphrase: network,
29916
- });
29917
- const signedTransaction = new Transaction$1(signedTxXdr, network);
29918
- const sentTransaction = await client.sendTransaction(signedTransaction);
29919
- const txStatus = await client.waitForTransaction(sentTransaction.hash, {
29920
- interval: 1_000,
29921
- });
29922
- if (txStatus !== rpc.Api.GetTransactionStatus.SUCCESS) {
29923
- throw new Error(`Transaction failed with status: ${txStatus}`);
29924
- }
29925
- return true;
29926
- }
29927
- catch (error) {
29928
- console.error("Error creating trust line:", error);
29929
- return false;
29930
- }
29931
- },
29932
- async onSuccess() {
29933
- queryClient.invalidateQueries({
29934
- queryKey: getPrefixKey(QueryKeys.StellarTrustLine),
29935
- });
29936
- },
29937
- });
29938
- /**
29939
- * Checks if the destination account has created a trust line to receive the given token.
29940
- */
29941
- const isTrustLineApproved = useQuery({
29942
- queryKey: keys().isStellarTrustLineApproved(address, token?.chainId, token?.type, token?.address, trustLineQuery.data?.limit, amount),
29943
- queryFn: async () => {
29944
- if (token?.type !== ChainType.STELLAR) {
29945
- return true;
29946
- }
29947
- // The native Stellar token doesn't need a trust line
29948
- if (token.address.toLowerCase() === nativeStellarTokenAddress.toLowerCase()) {
29949
- return true;
29950
- }
29951
- if (!amount) {
29952
- throw new Error("Amount is required");
29953
- }
29954
- const limitBn = BigNumber$1(trustLineQuery.data?.limit || "0");
29955
- const balanceBn = BigNumber$1(trustLineQuery.data?.balance || "0");
29956
- const availableAllowanceBn = limitBn.minus(balanceBn);
29957
- const amountBn = BigNumber$1(formatBNToReadable(amount, token.decimals));
29958
- return availableAllowanceBn.gte(amountBn);
29959
- },
29960
- enabled: !!address &&
29961
- !!amount &&
29962
- !trustLineQuery?.isLoading &&
29963
- trustLineQuery?.isFetched &&
29964
- token?.type === ChainType.STELLAR,
29965
- });
29966
- return {
29967
- createTrustLine,
29968
- trustLineQuery,
29969
- isTrustLineApproved,
29970
- };
29971
- }
29972
-
29973
33309
  const useAddressBookStore = create(persist((set) => ({
29974
33310
  addressBook: [],
29975
33311
  add: (newAddressData) => {
@@ -31592,18 +34928,15 @@ async function sendTransactionXrpl({ amount, signer, to, token, from, }) {
31592
34928
  txHash: hash,
31593
34929
  };
31594
34930
  }
31595
- const asset = parseXrplTokenAddress(token.address);
31596
- if (!asset) {
31597
- throw new Error("Invalid asset");
31598
- }
34931
+ const [currency, issuer] = token.address.split(".");
31599
34932
  const amountFormatted = formatBNToReadable(amount, token.decimals);
31600
34933
  const { hash } = await signer.signAndSubmit({
31601
34934
  network: xrplNetwork,
31602
34935
  tx: {
31603
34936
  ...baseTransaction,
31604
34937
  Amount: {
31605
- currency: asset.code,
31606
- issuer: asset.issuer,
34938
+ currency,
34939
+ issuer,
31607
34940
  value: amountFormatted,
31608
34941
  },
31609
34942
  },
@@ -32336,7 +35669,7 @@ const useApproval = ({ squidRoute, }) => {
32336
35669
  * On Error: Showing the error message if any
32337
35670
  * @returns {boolean} approved
32338
35671
  */
32339
- const routeApproved = useQuery(keys().routeApproved(squidRoute, allowanceInWei, erc20AllowanceQueryEnabled, hasAllowance), async () => {
35672
+ const routeApproved = useQuery(keys().routeApproved(squidRoute, allowanceInWei), async () => {
32340
35673
  if (erc20AllowanceQueryEnabled) {
32341
35674
  return hasAllowance;
32342
35675
  }
@@ -36844,12 +40177,12 @@ function useXrplTrustLine({ address, chain, token, amount }) {
36844
40177
  if (!address || !isXrplAddressValid(address)) {
36845
40178
  return null;
36846
40179
  }
36847
- const trustLineAsset = parseXrplTokenAddress(token.address);
36848
- if (!trustLineAsset) {
40180
+ const [currency, issuer] = token.address.split(".");
40181
+ if (!currency || !issuer) {
36849
40182
  return null;
36850
40183
  }
36851
40184
  const xrplClient = await getClient(chain);
36852
- const trustLine = await xrplClient.getTrustLine(address, trustLineAsset);
40185
+ const trustLine = await xrplClient.getTrustLine(address, issuer, currency);
36853
40186
  return trustLine;
36854
40187
  },
36855
40188
  enabled: !!address &&
@@ -37076,16 +40409,16 @@ const SquidProvider = ({ children, config, placeholder, }) => {
37076
40409
  useEffect(() => {
37077
40410
  initializeSdk();
37078
40411
  }, [initializeSdk]);
37079
- return wagmiConfig ? (React.createElement(WagmiProvider, { reconnectOnMount: false, config: wagmiConfig },
37080
- React.createElement(QueryClientProvider, { client: queryClient },
37081
- React.createElement(StellarProvider, null,
37082
- React.createElement(EvmProvider, null,
37083
- React.createElement(XrplProvider, null,
37084
- React.createElement(SuiProvider, null,
37085
- React.createElement(SolanaProvider, null,
37086
- React.createElement(BitcoinProvider, null,
37087
- React.createElement(CosmosProvider, null, children)))))))))) : (placeholder);
37088
- };
37089
-
37090
- export { useAllConnectedWalletBalances as $, AxelarStatusResponseType as A, useSquidQueryClient as B, CHAIN_IDS as C, DEFAULT_LOCALE as D, useSquid as E, useStellarAccountActivation as F, useStellarTrustLine as G, HistoryTxType as H, useAddressBookStore as I, useAssetsColorsStore as J, useFavoriteTokensStore as K, useHistoryStore as L, useSendTransactionStore as M, Nr as N, useConfigStore as O, useSquidStore as P, QueryKeys as Q, useSwapRoutePersistStore as R, SquidStatusErrorType as S, TransactionErrorType as T, useTransactionStore as U, ConnectingWalletStatus as V, Wo as W, XamanXrplNetwork as X, useWalletStore as Y, useDepositAddress as Z, useSwap as _, WindowWalletFlag as a, getSupportedChainIdsForDirection as a$, useAllTokensWithBalanceForChainType as a0, useCosmosBalance as a1, useEvmBalance as a2, useMultiChainBalance as a3, useMultipleTokenPrices as a4, useNativeBalance as a5, useNativeTokenForChain as a6, useSingleTokenPrice as a7, useSquidTokens as a8, useHistoricalData as a9, useSigner as aA, useWallet as aB, useWallets as aC, useXrplTrustLine as aD, TX_STATUS_CONSTANTS as aE, FINAL_TRANSACTION_STATUSES as aF, useGetFiatQuote as aG, useGetOnRampConfig as aH, useExecuteFiatQuote as aI, useFiatOnRampTxStatus as aJ, useFiatTransactions as aK, useCurrencyDetails as aL, useCountryDetails as aM, useAvailableQuotes as aN, useRecommendedQuote as aO, useGetOnrampPaymentTypes as aP, useSuggestedFiatAmounts as aQ, SquidProvider as aR, EnsService as aS, getXummClient as aT, isXamanXAppContext as aU, getQueryHeaders as aV, getStatusCode as aW, is404Error as aX, assetsBaseUrl as aY, shareSubgraphId as aZ, sortTokensBySharedSubgraphIds as a_, useTokensData as aa, useEstimateSendTransaction as ab, useSendTransaction as ac, useSendTransactionGas as ad, useAllTransactionsStatus as ae, useApproval as af, useEstimate as ag, useEstimatePriceImpact as ah, useExecuteTransaction as ai, useGetRoute as aj, useGetRouteWrapper as ak, useRouteWarnings as al, useSendTransactionStatus as am, useSwapTransactionStatus as an, useAvatar as ao, useHistory as ap, useUserParams as aq, useDebouncedValue as ar, useAddToken as as, useAutoConnect as at, useEnsDataForAddress as au, useEnsSearch as av, useGnosisContext as aw, useIsSameAddressAndGnosisContext as ax, useIntegratorContext as ay, useMultiChainWallet as az, chainTypeToZeroAddressMap as b, formatTokenAmount as b$, filterChains as b0, filterTokens as b1, getTokenImage as b2, getNewSwapParamsFromInput as b3, sortAllTokens as b4, findToken as b5, findNativeToken as b6, normalizeIbcAddress as b7, groupTokensBySymbol as b8, groupTokensByChainId as b9, suggestChainOrThrow as bA, normalizeError as bB, transactionErrorCode as bC, isUserRejectionError as bD, getTransactionError as bE, handleTransactionErrorEvents as bF, isSwapRouteError as bG, isStatusError as bH, createQuoteRequestParamsHash as bI, WidgetEvents as bJ, EvmNetworkNotSupportedErrorCode as bK, addEthereumChain as bL, parseEvmAddress as bM, formatEvmWallet as bN, filterWagmiConnector as bO, waitForReceiptWithRetry as bP, getUserCountry as bQ, getCountryData as bR, getCurrencyData as bS, adaptiveRound as bT, getSuggestedAmountsForCurrency as bU, HederaExtensionHelper as bV, convertHederaAccountIdToEvmAddress as bW, convertEvmAddressToHederaAccountId as bX, parseToBigInt as bY, roundNumericValue as bZ, formatUnitsRounded as b_, filterViewableTokens as ba, getSecretNetworkBalances as bb, getTokenAssetsKey as bc, fetchAssetsColors as bd, initializeSquidWithAssetsColors as be, isEmptyObject as bf, normalizeTokenSymbol as bg, areTokenSymbolsCompatible as bh, isEvmosChain as bi, getConfigWithDefaults as bj, randomIntFromInterval as bk, getTokensForChain as bl, getFirstAvailableChainId as bm, fetchHighestBalanceToken as bn, getInitialOrDefaultTokenAddressForChain as bo, getInitialTokenAddressForChain as bp, filterTokensForDestination as bq, getInitialChainIdFromConfig as br, getCosmosKey as bs, getKeysSettled as bt, getAllKeysForSupportedCosmosChains as bu, isCosmosAddressValid as bv, getCosmosSigningClient as bw, getCosmosChainInfosObject as bx, connectCosmosWallet as by, isFallbackAddressNeeded as bz, chainTypeToNativeTokenAddressMap as c, walletSupportsChainType as c$, formatUsdAmount as c0, trimExtraDecimals as c1, getNumericValue as c2, cleanAmount as c3, convertTokenAmountToUSD as c4, convertUSDToTokenAmount as c5, calculateTotal24hChange as c6, searchTokens as c7, filterSolanaWallets as c8, isSolanaAddressValid as c9, getStepStatuses as cA, getHalfSuccessState as cB, getStepsInfos as cC, getSwapTxStatusRefetchInterval as cD, getSendTxStatusRefetchInterval as cE, chainflipMultihopBridgeType as cF, getBridgeType as cG, getTransactionStatus as cH, getTransactionEndStatus as cI, isHistoryTransactionPending as cJ, isHistoryTransactionFailed as cK, isHistoryTransactionWarning as cL, isHistoryTransactionEnded as cM, formatHash as cN, isWalletAddressValid as cO, redirectToExtensionsStore as cP, accessProperty as cQ, populateWallets as cR, getDefaultChain as cS, sortWallets as cT, areSameAddress as cU, sortAddressBook as cV, calculateTotalUsdBalanceUSD as cW, addTokenToWallet as cX, isEvmChainNotSupportedError as cY, getWalletSupportedChainTypes as cZ, getConnectorForChainType as c_, executeSolanaSwap as ca, executeSolanaTransfer as cb, isStellarAddressValid as cc, getStellarNetwork as cd, stellarAddressToScVal as ce, getStellarTrustLineAsset as cf, isStellarToken as cg, isStellarIssuedToken as ch, getStellarHorizonApiUrl as ci, isValidIssuedAsset as cj, isValidHorizonAsset as ck, formatTransactionHistoryDate as cl, getAxelarExplorerTxUrl as cm, getSourceExplorerTxUrl as cn, getMainExplorerUrl as co, formatDistance as cp, formatSeconds as cq, formatSwapTxStatusResponseForStorage as cr, simplifyRouteAction as cs, fetchSwapTransactionStatus as ct, compareTransactionIds as cu, isCoralBridgeAction as cv, sleep as cw, isDepositRoute as cx, isChainflipBridgeTransaction as cy, getHistoryTransactionId as cz, definedInWindow as d, connectWallet as d0, cancelConnectWallet as d1, isProblematicConnector as d2, mergeWallets as d3, isXionSmartContractAddress as d4, isXrplAddressValid as d5, buildXrplTrustSetTx as d6, getXrplNetwork as d7, parseXrplPaymentTx as d8, parseXrplTokenAddress as d9, er as e, formatBNToReadable as f, destinationAddressResetValue as g, fallbackAddressResetValue as h, nativeCosmosTokenAddress as i, nativeEvmTokenAddress as j, nativeSolanaTokenAddress as k, nativeStellarTokenAddress as l, nativeSuiTokenAddress as m, nativeBitcoinTokenAddress as n, nativeXrplTokenAddress as o, CosmosProvider as p, SendTransactionStatus as q, TransactionStatus as r, useTrackSearchEmpty as s, useSquidChains as t, useCosmosContext as u, useClient as v, walletIconBaseUrl as w, useCosmosForChain as x, useHederaTokenAssociations as y, useKeyboardNavigation as z };
37091
- //# sourceMappingURL=index-DPakWLan.js.map
40412
+ return wagmiConfig ? (React__default.createElement(WagmiProvider, { reconnectOnMount: false, config: wagmiConfig },
40413
+ React__default.createElement(QueryClientProvider, { client: queryClient },
40414
+ React__default.createElement(StellarProvider, null,
40415
+ React__default.createElement(EvmProvider, null,
40416
+ React__default.createElement(XrplProvider, null,
40417
+ React__default.createElement(SuiProvider, null,
40418
+ React__default.createElement(SolanaProvider, null,
40419
+ React__default.createElement(BitcoinProvider, null,
40420
+ React__default.createElement(CosmosProvider, null, children)))))))))) : (placeholder);
40421
+ };
40422
+
40423
+ export { useAllTokensWithBalanceForChainType as $, AxelarStatusResponseType as A, useSquidQueryClient as B, CHAIN_IDS as C, DEFAULT_LOCALE as D, useSquid as E, useStellarAccountActivation as F, useAddressBookStore as G, HistoryTxType as H, useAssetsColorsStore as I, useFavoriteTokensStore as J, useHistoryStore as K, useSendTransactionStore as L, useConfigStore as M, Nr as N, useSquidStore as O, useSwapRoutePersistStore as P, QueryKeys as Q, useTransactionStore as R, SquidStatusErrorType as S, TransactionErrorType as T, ConnectingWalletStatus as U, useWalletStore as V, Wo as W, XamanXrplNetwork as X, useDepositAddress as Y, useSwap as Z, useAllConnectedWalletBalances as _, WindowWalletFlag as a, filterChains as a$, useCosmosBalance as a0, useEvmBalance as a1, useMultiChainBalance as a2, useMultipleTokenPrices as a3, useNativeBalance as a4, useNativeTokenForChain as a5, useSingleTokenPrice as a6, useSquidTokens as a7, useHistoricalData as a8, useTokensData as a9, useWallet as aA, useWallets as aB, useXrplTrustLine as aC, TX_STATUS_CONSTANTS as aD, FINAL_TRANSACTION_STATUSES as aE, useGetFiatQuote as aF, useGetOnRampConfig as aG, useExecuteFiatQuote as aH, useFiatOnRampTxStatus as aI, useFiatTransactions as aJ, useCurrencyDetails as aK, useCountryDetails as aL, useAvailableQuotes as aM, useRecommendedQuote as aN, useGetOnrampPaymentTypes as aO, useSuggestedFiatAmounts as aP, SquidProvider as aQ, EnsService as aR, getXummClient as aS, isXamanXAppContext as aT, getQueryHeaders as aU, getStatusCode as aV, is404Error as aW, assetsBaseUrl as aX, shareSubgraphId as aY, sortTokensBySharedSubgraphIds as aZ, getSupportedChainIdsForDirection as a_, useEstimateSendTransaction as aa, useSendTransaction as ab, useSendTransactionGas as ac, useAllTransactionsStatus as ad, useApproval as ae, useEstimate as af, useEstimatePriceImpact as ag, useExecuteTransaction as ah, useGetRoute as ai, useGetRouteWrapper as aj, useRouteWarnings as ak, useSendTransactionStatus as al, useSwapTransactionStatus as am, useAvatar as an, useHistory as ao, useUserParams as ap, useDebouncedValue as aq, useAddToken as ar, useAutoConnect as as, useEnsDataForAddress as at, useEnsSearch as au, useGnosisContext as av, useIsSameAddressAndGnosisContext as aw, useIntegratorContext as ax, useMultiChainWallet as ay, useSigner as az, chainTypeToZeroAddressMap as b, formatUsdAmount as b$, filterTokens as b0, getTokenImage as b1, getNewSwapParamsFromInput as b2, sortAllTokens as b3, findToken as b4, findNativeToken as b5, normalizeIbcAddress as b6, groupTokensBySymbol as b7, groupTokensByChainId as b8, filterViewableTokens as b9, normalizeError as bA, transactionErrorCode as bB, isUserRejectionError as bC, getTransactionError as bD, handleTransactionErrorEvents as bE, isSwapRouteError as bF, isStatusError as bG, createQuoteRequestParamsHash as bH, WidgetEvents as bI, EvmNetworkNotSupportedErrorCode as bJ, addEthereumChain as bK, parseEvmAddress as bL, formatEvmWallet as bM, filterWagmiConnector as bN, waitForReceiptWithRetry as bO, getUserCountry as bP, getCountryData as bQ, getCurrencyData as bR, adaptiveRound as bS, getSuggestedAmountsForCurrency as bT, HederaExtensionHelper as bU, convertHederaAccountIdToEvmAddress as bV, convertEvmAddressToHederaAccountId as bW, parseToBigInt as bX, roundNumericValue as bY, formatUnitsRounded as bZ, formatTokenAmount as b_, getSecretNetworkBalances as ba, getTokenAssetsKey as bb, fetchAssetsColors as bc, initializeSquidWithAssetsColors as bd, isEmptyObject as be, normalizeTokenSymbol as bf, areTokenSymbolsCompatible as bg, isEvmosChain as bh, getConfigWithDefaults as bi, randomIntFromInterval as bj, getTokensForChain as bk, getFirstAvailableChainId as bl, fetchHighestBalanceToken as bm, getInitialOrDefaultTokenAddressForChain as bn, getInitialTokenAddressForChain as bo, filterTokensForDestination as bp, getInitialChainIdFromConfig as bq, getCosmosKey as br, getKeysSettled as bs, getAllKeysForSupportedCosmosChains as bt, isCosmosAddressValid as bu, getCosmosSigningClient as bv, getCosmosChainInfosObject as bw, connectCosmosWallet as bx, isFallbackAddressNeeded as by, suggestChainOrThrow as bz, chainTypeToNativeTokenAddressMap as c, trimExtraDecimals as c0, getNumericValue as c1, cleanAmount as c2, convertTokenAmountToUSD as c3, convertUSDToTokenAmount as c4, calculateTotal24hChange as c5, searchTokens as c6, filterSolanaWallets as c7, isSolanaAddressValid as c8, executeSolanaSwap as c9, isHistoryTransactionFailed as cA, isHistoryTransactionWarning as cB, isHistoryTransactionEnded as cC, formatHash as cD, isWalletAddressValid as cE, redirectToExtensionsStore as cF, accessProperty as cG, populateWallets as cH, getDefaultChain as cI, sortWallets as cJ, areSameAddress as cK, sortAddressBook as cL, calculateTotalUsdBalanceUSD as cM, addTokenToWallet as cN, isEvmChainNotSupportedError as cO, getWalletSupportedChainTypes as cP, getConnectorForChainType as cQ, walletSupportsChainType as cR, connectWallet as cS, cancelConnectWallet as cT, isProblematicConnector as cU, mergeWallets as cV, isXionSmartContractAddress as cW, isXrplAddressValid as cX, buildXrplTrustSetTx as cY, getXrplNetwork as cZ, parseXrplPaymentTx as c_, executeSolanaTransfer as ca, formatTransactionHistoryDate as cb, getAxelarExplorerTxUrl as cc, getSourceExplorerTxUrl as cd, getMainExplorerUrl as ce, formatDistance as cf, formatSeconds as cg, formatSwapTxStatusResponseForStorage as ch, simplifyRouteAction as ci, fetchSwapTransactionStatus as cj, compareTransactionIds as ck, isCoralBridgeAction as cl, sleep as cm, isDepositRoute as cn, isChainflipBridgeTransaction as co, getHistoryTransactionId as cp, getStepStatuses as cq, getHalfSuccessState as cr, getStepsInfos as cs, getSwapTxStatusRefetchInterval as ct, getSendTxStatusRefetchInterval as cu, chainflipMultihopBridgeType as cv, getBridgeType as cw, getTransactionStatus as cx, getTransactionEndStatus as cy, isHistoryTransactionPending as cz, definedInWindow as d, er as e, formatBNToReadable as f, destinationAddressResetValue as g, fallbackAddressResetValue as h, nativeCosmosTokenAddress as i, nativeEvmTokenAddress as j, nativeSolanaTokenAddress as k, nativeStellarTokenAddress as l, nativeSuiTokenAddress as m, nativeBitcoinTokenAddress as n, nativeXrplTokenAddress as o, CosmosProvider as p, SendTransactionStatus as q, TransactionStatus as r, useTrackSearchEmpty as s, useSquidChains as t, useCosmosContext as u, useClient as v, walletIconBaseUrl as w, useCosmosForChain as x, useHederaTokenAssociations as y, useKeyboardNavigation as z };
40424
+ //# sourceMappingURL=index-D3LtAuC9.js.map