reactjrx 1.111.0 → 1.112.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 (98) hide show
  1. package/dist/index.cjs +61 -2819
  2. package/dist/index.d.ts +1 -9
  3. package/dist/index.js +46 -2788
  4. package/dist/lib/{deprecated/client/utils → utils}/makeObservable.d.ts +8 -8
  5. package/dist/lib/utils/react/useLiveRef.d.ts +1 -1
  6. package/dist/tests/utils.d.ts +0 -10
  7. package/package.json +11 -9
  8. package/dist/lib/deprecated/client/QueryClient.d.ts +0 -48
  9. package/dist/lib/deprecated/client/QueryClient.rq.test.d.ts +0 -1
  10. package/dist/lib/deprecated/client/QueryClient.types.rq.test.d.ts +0 -1
  11. package/dist/lib/deprecated/client/focusManager.d.ts +0 -19
  12. package/dist/lib/deprecated/client/focusManager.rq.test.d.ts +0 -1
  13. package/dist/lib/deprecated/client/keys/hashKey.d.ts +0 -3
  14. package/dist/lib/deprecated/client/keys/hashKey.test.d.ts +0 -1
  15. package/dist/lib/deprecated/client/keys/matchKey.d.ts +0 -4
  16. package/dist/lib/deprecated/client/keys/matchKey.test.d.ts +0 -1
  17. package/dist/lib/deprecated/client/keys/nanoid.d.ts +0 -1
  18. package/dist/lib/deprecated/client/keys/partialMatchKey.d.ts +0 -5
  19. package/dist/lib/deprecated/client/keys/partialMatchKey.rq.test.d.ts +0 -1
  20. package/dist/lib/deprecated/client/keys/types.d.ts +0 -10
  21. package/dist/lib/deprecated/client/mutations/cache/MutationCache.d.ts +0 -24
  22. package/dist/lib/deprecated/client/mutations/cache/mutationCache.rq.test.d.ts +0 -1
  23. package/dist/lib/deprecated/client/mutations/cache/types.d.ts +0 -68
  24. package/dist/lib/deprecated/client/mutations/mutation/Mutation.d.ts +0 -35
  25. package/dist/lib/deprecated/client/mutations/mutation/delayWhenNetworkOnline.d.ts +0 -4
  26. package/dist/lib/deprecated/client/mutations/mutation/executeMutation.d.ts +0 -7
  27. package/dist/lib/deprecated/client/mutations/mutation/mutation.options.test.d.ts +0 -1
  28. package/dist/lib/deprecated/client/mutations/mutation/observeUntilFinished.d.ts +0 -3
  29. package/dist/lib/deprecated/client/mutations/mutation/types.d.ts +0 -53
  30. package/dist/lib/deprecated/client/mutations/mutation/waitForNetworkOnError.d.ts +0 -6
  31. package/dist/lib/deprecated/client/mutations/mutations.test.d.ts +0 -1
  32. package/dist/lib/deprecated/client/mutations/observers/MutationObserver.d.ts +0 -38
  33. package/dist/lib/deprecated/client/mutations/observers/mutationObserver.rq.test.d.ts +0 -1
  34. package/dist/lib/deprecated/client/mutations/observers/mutationObserver.test.d.ts +0 -1
  35. package/dist/lib/deprecated/client/mutations/observers/types.d.ts +0 -65
  36. package/dist/lib/deprecated/client/mutations/runner/MutationRunner.d.ts +0 -20
  37. package/dist/lib/deprecated/client/mutations/runner/mutationRunner.test.d.ts +0 -1
  38. package/dist/lib/deprecated/client/mutations/types.d.ts +0 -53
  39. package/dist/lib/deprecated/client/mutations/utils/defaultMutationState.d.ts +0 -2
  40. package/dist/lib/deprecated/client/mutations/utils/distinctUntilStateChanged.d.ts +0 -3
  41. package/dist/lib/deprecated/client/mutations/utils/filters.d.ts +0 -3
  42. package/dist/lib/deprecated/client/onlineManager.d.ts +0 -10
  43. package/dist/lib/deprecated/client/queries/cache/QueryCache.d.ts +0 -33
  44. package/dist/lib/deprecated/client/queries/cache/types.d.ts +0 -45
  45. package/dist/lib/deprecated/client/queries/observer/QueryObserver.d.ts +0 -65
  46. package/dist/lib/deprecated/client/queries/observer/QueryObserver.rq.test.d.ts +0 -1
  47. package/dist/lib/deprecated/client/queries/observer/QueryObserver.types.rq.test.d.ts +0 -1
  48. package/dist/lib/deprecated/client/queries/observer/queryStateHelpers.d.ts +0 -9
  49. package/dist/lib/deprecated/client/queries/observer/types.d.ts +0 -242
  50. package/dist/lib/deprecated/client/queries/query/Query.d.ts +0 -71
  51. package/dist/lib/deprecated/client/queries/query/delayOnNetworkMode.d.ts +0 -6
  52. package/dist/lib/deprecated/client/queries/query/delayUntilFocus.d.ts +0 -2
  53. package/dist/lib/deprecated/client/queries/query/execution/completeFnIfNotMoreObservers.d.ts +0 -2
  54. package/dist/lib/deprecated/client/queries/query/execution/executeQuery.d.ts +0 -20
  55. package/dist/lib/deprecated/client/queries/query/getDefaultState.d.ts +0 -4
  56. package/dist/lib/deprecated/client/queries/query/operators.d.ts +0 -14
  57. package/dist/lib/deprecated/client/queries/query/query.rq.test.d.ts +0 -1
  58. package/dist/lib/deprecated/client/queries/query/query.test.d.ts +0 -1
  59. package/dist/lib/deprecated/client/queries/query/state/whenNewData.d.ts +0 -8
  60. package/dist/lib/deprecated/client/queries/query/types.d.ts +0 -95
  61. package/dist/lib/deprecated/client/queries/retryer/CancelledError.d.ts +0 -6
  62. package/dist/lib/deprecated/client/queries/retryer/types.d.ts +0 -4
  63. package/dist/lib/deprecated/client/queries/retryer/utils.d.ts +0 -2
  64. package/dist/lib/deprecated/client/queries/types.d.ts +0 -113
  65. package/dist/lib/deprecated/client/queries/utils.d.ts +0 -16
  66. package/dist/lib/deprecated/client/store.d.ts +0 -25
  67. package/dist/lib/deprecated/client/tests/utils.d.ts +0 -10
  68. package/dist/lib/deprecated/client/types.d.ts +0 -80
  69. package/dist/lib/deprecated/client/utils/keepPreviousData.d.ts +0 -1
  70. package/dist/lib/deprecated/react/QueryClientProvider.d.ts +0 -7
  71. package/dist/lib/deprecated/react/QueryClientProvider.rq.test.d.ts +0 -1
  72. package/dist/lib/deprecated/react/mutations/types.d.ts +0 -18
  73. package/dist/lib/deprecated/react/mutations/useIsMutating.d.ts +0 -3
  74. package/dist/lib/deprecated/react/mutations/useIsMutating.test.d.ts +0 -1
  75. package/dist/lib/deprecated/react/mutations/useMutation.d.ts +0 -4
  76. package/dist/lib/deprecated/react/mutations/useMutation.keys.test.d.ts +0 -1
  77. package/dist/lib/deprecated/react/mutations/useMutation.rq.test.d.ts +0 -1
  78. package/dist/lib/deprecated/react/mutations/useMutation.switch.test.d.ts +0 -1
  79. package/dist/lib/deprecated/react/mutations/useMutation.test.d.ts +0 -1
  80. package/dist/lib/deprecated/react/mutations/useMutationState.d.ts +0 -9
  81. package/dist/lib/deprecated/react/mutations/useMutationState.test.d.ts +0 -1
  82. package/dist/lib/deprecated/react/queries/QueryErrorResetBoundary.d.ts +0 -11
  83. package/dist/lib/deprecated/react/queries/QueryOptions.rq.types.typeTest.d.ts +0 -1
  84. package/dist/lib/deprecated/react/queries/errorBoundaryUtils.d.ts +0 -12
  85. package/dist/lib/deprecated/react/queries/isRestoring.d.ts +0 -3
  86. package/dist/lib/deprecated/react/queries/queryOptions.d.ts +0 -18
  87. package/dist/lib/deprecated/react/queries/types.d.ts +0 -11
  88. package/dist/lib/deprecated/react/queries/useBaseQuery.d.ts +0 -6
  89. package/dist/lib/deprecated/react/queries/useForeverQuery.d.ts +0 -8
  90. package/dist/lib/deprecated/react/queries/useIsFetching.d.ts +0 -3
  91. package/dist/lib/deprecated/react/queries/useIsFetching.rq.test.d.ts +0 -1
  92. package/dist/lib/deprecated/react/queries/useQuery.d.ts +0 -8
  93. package/dist/lib/deprecated/react/queries/useQuery.deduplication.test.d.ts +0 -1
  94. package/dist/lib/deprecated/react/queries/useQuery.invalidation.test.d.ts +0 -1
  95. package/dist/lib/deprecated/react/queries/useQuery.keys.test.d.ts +0 -1
  96. package/dist/lib/deprecated/react/queries/useQuery.rq.types.test.d.ts +0 -1
  97. package/dist/lib/deprecated/react/queries/useQuery.test.d.ts +0 -1
  98. package/dist/lib/deprecated/react/useQueryClient.d.ts +0 -2
package/dist/index.cjs CHANGED
@@ -1,41 +1,16 @@
1
1
  "use strict";
2
2
  var __defProp = Object.defineProperty;
3
- var __typeError = (msg) => {
4
- throw TypeError(msg);
5
- };
6
3
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
4
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
8
- var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
9
- var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
10
- var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
11
- var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
12
- var _trigger$, _mutationRunner, _currentMutationSubject, _visibility$, _focusedSubject, _client, _currentQuery, _fetchSubject, _currentQueryInitialState, _lastResult, _lastQueryWithDefinedData, _observers, _observerCount, _cancelSubject, _executeSubject, _store, _defaultOptions, _initialState, _notifySubject, _store2, _mutationCache, _queryCache, _mutationDefaults, _queryDefaults, _defaultOptions2;
13
5
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
14
- const React = require("react");
6
+ const react = require("react");
15
7
  const rxjs = require("rxjs");
16
8
  const operators = require("rxjs/operators");
17
9
  const reactQuery = require("@tanstack/react-query");
18
10
  const jsxRuntime = require("react/jsx-runtime");
19
- function _interopNamespaceDefault(e) {
20
- const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
21
- if (e) {
22
- for (const k in e) {
23
- if (k !== "default") {
24
- const d = Object.getOwnPropertyDescriptor(e, k);
25
- Object.defineProperty(n, k, d.get ? d : {
26
- enumerable: true,
27
- get: () => e[k]
28
- });
29
- }
30
- }
31
- }
32
- n.default = e;
33
- return Object.freeze(n);
34
- }
35
- const React__namespace = /* @__PURE__ */ _interopNamespaceDefault(React);
36
11
  const useLiveRef = (value) => {
37
- const ref = React.useRef(value);
38
- React.useMemo(() => {
12
+ const ref = react.useRef(value);
13
+ react.useMemo(() => {
39
14
  ref.current = value;
40
15
  }, [value]);
41
16
  return ref;
@@ -44,12 +19,12 @@ function isPromiseLike(value) {
44
19
  return value instanceof Promise || value && typeof value === "object" && "then" in value && typeof value.then === "function" && "catch" in value && value.catch === "function";
45
20
  }
46
21
  function makeObservable(something) {
47
- if (rxjs.isObservable(something)) return something;
48
- if (isPromiseLike(something)) return rxjs.from(something);
49
- if (typeof something !== "function") return rxjs.of(something);
22
+ if (rxjs.isObservable(something)) return () => something;
23
+ if (isPromiseLike(something)) return () => rxjs.from(something);
24
+ if (typeof something !== "function") return () => rxjs.of(something);
50
25
  const somethingAsFunction = something;
51
- return rxjs.defer(() => {
52
- const result = somethingAsFunction();
26
+ return (params) => rxjs.defer(() => {
27
+ const result = somethingAsFunction(params);
53
28
  if (isPromiseLike(result)) {
54
29
  return rxjs.from(result);
55
30
  }
@@ -66,18 +41,18 @@ function useObserve(source$, optionsOrDeps, maybeDeps) {
66
41
  compareFn: void 0
67
42
  };
68
43
  const deps = !maybeDeps && Array.isArray(optionsOrDeps) ? optionsOrDeps : typeof source$ === "function" ? maybeDeps ?? [] : [source$];
69
- const valueRef = React.useRef(
44
+ const valueRef = react.useRef(
70
45
  "getValue" in source$ && typeof source$.getValue === "function" ? source$.getValue() : options.defaultValue
71
46
  );
72
47
  const sourceRef = useLiveRef(source$);
73
48
  const optionsRef = useLiveRef(options);
74
- const getSnapshot = React.useCallback(() => {
49
+ const getSnapshot = react.useCallback(() => {
75
50
  return valueRef.current;
76
51
  }, []);
77
- const subscribe = React.useCallback(
52
+ const subscribe = react.useCallback(
78
53
  (next) => {
79
54
  const source = sourceRef.current;
80
- const sub = makeObservable(source).pipe(
55
+ const sub = makeObservable(source)().pipe(
81
56
  optionsRef.current.defaultValue ? rxjs.startWith(optionsRef.current.defaultValue) : rxjs.identity,
82
57
  /**
83
58
  * @important there is already a Object.is comparison in place from react
@@ -103,13 +78,13 @@ function useObserve(source$, optionsOrDeps, maybeDeps) {
103
78
  // eslint-disable-next-line react-hooks/exhaustive-deps
104
79
  [...deps]
105
80
  );
106
- const result = React.useSyncExternalStore(subscribe, getSnapshot);
81
+ const result = react.useSyncExternalStore(subscribe, getSnapshot);
107
82
  return result;
108
83
  }
109
84
  function useSubscribe(source, deps = []) {
110
85
  const sourceRef = useLiveRef(source);
111
- React.useEffect(() => {
112
- const sub = makeObservable(sourceRef.current).pipe(
86
+ react.useEffect(() => {
87
+ const sub = makeObservable(sourceRef.current)().pipe(
113
88
  rxjs.catchError((error) => {
114
89
  console.error(error);
115
90
  return rxjs.EMPTY;
@@ -125,11 +100,11 @@ function useSubscribe(source, deps = []) {
125
100
  ]);
126
101
  }
127
102
  const useConstant = (fn) => {
128
- const ref = React.useRef();
103
+ const ref = react.useRef(void 0);
129
104
  if (!ref.current) {
130
105
  ref.current = fn();
131
106
  }
132
- React.useEffect(() => {
107
+ react.useEffect(() => {
133
108
  if (process.env.NODE_ENV === "development") ;
134
109
  }, []);
135
110
  return ref;
@@ -139,10 +114,10 @@ const useSubject = ({
139
114
  completeOnUnmount = true
140
115
  } = {}) => {
141
116
  const subject = useConstant(() => new rxjs.Subject());
142
- const completed = React.useRef(false);
117
+ const completed = react.useRef(false);
143
118
  const onBeforeCompleteRef = useLiveRef(onBeforeComplete);
144
119
  const completeOnUnmountRef = useLiveRef(completeOnUnmount);
145
- React.useEffect(() => {
120
+ react.useEffect(() => {
146
121
  if (completed.current) {
147
122
  subject.current = new rxjs.Subject();
148
123
  completed.current = false;
@@ -163,7 +138,7 @@ const useSubject = ({
163
138
  };
164
139
  const useObservableCallback = () => {
165
140
  const subject = useSubject();
166
- const trigger = React.useCallback(
141
+ const trigger = react.useCallback(
167
142
  (arg) => {
168
143
  subject.current.next(arg);
169
144
  },
@@ -174,9 +149,9 @@ const useObservableCallback = () => {
174
149
  };
175
150
  const useBehaviorSubject = (state) => {
176
151
  const subject = useConstant(() => new rxjs.BehaviorSubject(state));
177
- const completed = React.useRef(false);
178
- const stateRef = React.useRef(state);
179
- React.useEffect(() => {
152
+ const completed = react.useRef(false);
153
+ const stateRef = react.useRef(state);
154
+ react.useEffect(() => {
180
155
  if (completed.current) {
181
156
  subject.current = new rxjs.BehaviorSubject(stateRef.current);
182
157
  completed.current = false;
@@ -193,7 +168,7 @@ const useBehaviorSubject = (state) => {
193
168
  const useObservableState = (defaultValue) => {
194
169
  const subject = useBehaviorSubject(defaultValue);
195
170
  const subject$ = useLiveRef(subject.current.asObservable());
196
- const setState = React.useCallback(
171
+ const setState = react.useCallback(
197
172
  (value) => {
198
173
  subject.current.next(value);
199
174
  },
@@ -204,11 +179,32 @@ const useObservableState = (defaultValue) => {
204
179
  };
205
180
  const useLiveBehaviorSubject = (state) => {
206
181
  const subject = useBehaviorSubject(state);
207
- React.useEffect(() => {
182
+ react.useEffect(() => {
208
183
  subject.current.next(state);
209
184
  }, [state, subject]);
210
185
  return subject;
211
186
  };
187
+ function useSubscribeEffect(source, unsafeOptions, deps = []) {
188
+ const options = unsafeOptions != null && !Array.isArray(unsafeOptions) ? unsafeOptions : {};
189
+ const retryOption = options.retry ?? true;
190
+ const onErrorRef = useLiveRef(
191
+ options.onError ?? ((error) => {
192
+ console.error(error);
193
+ })
194
+ );
195
+ const sourceAsObservable = react.useCallback(() => makeObservable(source)(), deps);
196
+ const enhancerMakeObservable = react.useCallback(
197
+ () => sourceAsObservable().pipe(
198
+ rxjs.catchError((error) => {
199
+ onErrorRef.current(error);
200
+ throw error;
201
+ }),
202
+ retryOption ? rxjs.retry() : rxjs.identity
203
+ ),
204
+ [sourceAsObservable, retryOption, onErrorRef]
205
+ );
206
+ useSubscribe(enhancerMakeObservable, deps);
207
+ }
212
208
  const SIGNAL_RESET = Symbol("SIGNAL_RESET");
213
209
  function signal(config = {}) {
214
210
  const normalizedConfig = {
@@ -286,7 +282,7 @@ function useSignalValue(signal2, selector) {
286
282
  );
287
283
  }
288
284
  const useSignal = (config) => {
289
- const [stateSignal] = React.useState(() => signal(config));
285
+ const [stateSignal] = react.useState(() => signal(config));
290
286
  const value = useSignalValue(stateSignal);
291
287
  return [value, stateSignal];
292
288
  };
@@ -555,7 +551,7 @@ const useUnmountObservable = () => {
555
551
  return subject;
556
552
  };
557
553
  const useEffectOnce = (effect) => {
558
- React.useEffect(effect, []);
554
+ react.useEffect(effect, []);
559
555
  };
560
556
  const useMount = (fn) => {
561
557
  useEffectOnce(() => {
@@ -709,23 +705,23 @@ class QueryClient$ {
709
705
  });
710
706
  }
711
707
  }
712
- const Context$1 = React.createContext(void 0);
713
- const QueryClientProvider$ = React.memo(
708
+ const Context = react.createContext(void 0);
709
+ const QueryClientProvider$ = react.memo(
714
710
  ({
715
711
  children,
716
- client: _client2
712
+ client: _client
717
713
  }) => {
718
- const [client] = React.useState(() => _client2 ?? new QueryClient$());
719
- React.useEffect(() => {
714
+ const [client] = react.useState(() => _client ?? new QueryClient$());
715
+ react.useEffect(() => {
720
716
  return () => {
721
717
  client.destroy();
722
718
  };
723
719
  }, [client]);
724
- return /* @__PURE__ */ jsxRuntime.jsx(Context$1.Provider, { value: client, children });
720
+ return /* @__PURE__ */ jsxRuntime.jsx(Context.Provider, { value: client, children });
725
721
  }
726
722
  );
727
723
  const useQueryClient$ = () => {
728
- const client = React.useContext(Context$1);
724
+ const client = react.useContext(Context);
729
725
  if (!client) {
730
726
  throw new Error(
731
727
  "useReactJrxQueryClient must be used within a ReactJrxQueryProvider"
@@ -827,7 +823,7 @@ function useMutation$(options, queryClient) {
827
823
  queryClient
828
824
  );
829
825
  const { status, isPending, isError, isSuccess, isIdle } = result;
830
- React.useEffect(() => {
826
+ react.useEffect(() => {
831
827
  stateSubject.current.next({ status, isPending, isError, isSuccess, isIdle });
832
828
  }, [status, isPending, isError, isSuccess, isIdle, stateSubject]);
833
829
  return { ...result, state$: stateSubject.current };
@@ -844,14 +840,14 @@ function useSwitchMutation$(options, queryClient) {
844
840
  },
845
841
  queryClient
846
842
  );
847
- const mutateSwitch = React.useCallback(
843
+ const mutateSwitch = react.useCallback(
848
844
  (variables) => {
849
845
  cancel();
850
846
  return mutate(variables);
851
847
  },
852
848
  [mutate, cancel]
853
849
  );
854
- const mutateAsyncSwitch = React.useCallback(
850
+ const mutateAsyncSwitch = react.useCallback(
855
851
  (variables) => {
856
852
  cancel();
857
853
  return mutateAsync(variables);
@@ -893,7 +889,7 @@ function useContactMutation$(options, queryClient) {
893
889
  },
894
890
  queryClient
895
891
  );
896
- const mutateAsyncConcat = React.useCallback(
892
+ const mutateAsyncConcat = react.useCallback(
897
893
  async (variables) => {
898
894
  const mutations = client.getMutationCache().findAll({
899
895
  mutationKey,
@@ -911,7 +907,7 @@ function useContactMutation$(options, queryClient) {
911
907
  },
912
908
  [mutateAsync, client, mutationKey]
913
909
  );
914
- const mutateConcat = React.useCallback(
910
+ const mutateConcat = react.useCallback(
915
911
  (variables) => {
916
912
  mutateAsyncConcat(variables).catch(rxjs.noop);
917
913
  },
@@ -919,2758 +915,8 @@ function useContactMutation$(options, queryClient) {
919
915
  );
920
916
  return { ...rest, mutate: mutateConcat, mutateAsync: mutateAsyncConcat };
921
917
  }
922
- function hasObjectPrototype(o) {
923
- return Object.prototype.toString.call(o) === "[object Object]";
924
- }
925
- function isPlainObject(o) {
926
- if (!hasObjectPrototype(o)) {
927
- return false;
928
- }
929
- const ctor = o.constructor;
930
- if (typeof ctor === "undefined") {
931
- return true;
932
- }
933
- const prot = ctor.prototype;
934
- if (!hasObjectPrototype(prot)) {
935
- return false;
936
- }
937
- if (!prot.hasOwnProperty("isPrototypeOf")) {
938
- return false;
939
- }
940
- return true;
941
- }
942
- const hashKey = (queryKey) => {
943
- return JSON.stringify(
944
- queryKey,
945
- (_, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key) => {
946
- result[key] = val[key];
947
- return result;
948
- }, {}) : val
949
- );
950
- };
951
- const nanoid = (size = 21) => crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
952
- byte &= 63;
953
- if (byte < 36) {
954
- id += byte.toString(36);
955
- } else if (byte < 62) {
956
- id += (byte - 26).toString(36).toUpperCase();
957
- } else if (byte > 62) {
958
- id += "-";
959
- } else {
960
- id += "_";
961
- }
962
- return id;
963
- }, "");
964
- const getDefaultMutationState = () => ({
965
- context: void 0,
966
- data: void 0,
967
- error: null,
968
- status: "idle",
969
- submittedAt: 0,
970
- variables: void 0,
971
- failureCount: 0,
972
- failureReason: null,
973
- isPaused: false
974
- });
975
- function trackSubscriptions(onCountUpdate) {
976
- let count = 0;
977
- return function refCountOperatorFunction(source) {
978
- return new rxjs.Observable((observer) => {
979
- count++;
980
- const sub = source.subscribe(observer);
981
- onCountUpdate(count);
982
- return () => {
983
- count--;
984
- onCountUpdate(count);
985
- sub.unsubscribe();
986
- };
987
- });
988
- };
989
- }
990
- const observeUntilFinished = (source) => source.pipe(
991
- rxjs.takeWhile(
992
- (result) => result.status !== "error" && result.status !== "success",
993
- true
994
- )
995
- );
996
- class MutationRunner {
997
- constructor({
998
- __queryFinalizeHook
999
- } = {}) {
1000
- __privateAdd(this, _trigger$, new rxjs.Subject());
1001
- __publicField(this, "state$");
1002
- const refCountSubject = new rxjs.BehaviorSubject(0);
1003
- const noMoreObservers$ = refCountSubject.pipe(
1004
- rxjs.filter((value) => value === 0)
1005
- );
1006
- this.state$ = __privateGet(this, _trigger$).pipe(
1007
- rxjs.concatMap(({ args, mutation, options }) => {
1008
- const mapOperator = options.mapOperator ?? "merge";
1009
- const mergeTrigger$ = __privateGet(this, _trigger$).pipe(
1010
- rxjs.filter(() => mapOperator === "merge")
1011
- );
1012
- const switchTrigger$ = __privateGet(this, _trigger$).pipe(
1013
- rxjs.filter(() => mapOperator === "switch"),
1014
- rxjs.tap(() => {
1015
- mutation.cancel();
1016
- })
1017
- );
1018
- const deferExecution$ = rxjs.defer(() => {
1019
- mutation.execute(args);
1020
- return rxjs.EMPTY;
1021
- });
1022
- const resetState$ = mutation.state$.pipe(
1023
- observeUntilFinished,
1024
- rxjs.last(),
1025
- rxjs.mergeMap(() => mutation.state$),
1026
- rxjs.takeUntil(__privateGet(this, _trigger$))
1027
- );
1028
- const stateUntilFinished$ = mutation.state$.pipe(
1029
- observeUntilFinished,
1030
- rxjs.skip(1)
1031
- );
1032
- const observeUntil$ = rxjs.merge(
1033
- noMoreObservers$,
1034
- mergeTrigger$,
1035
- switchTrigger$,
1036
- mutation.cancelled$
1037
- );
1038
- return rxjs.merge(
1039
- stateUntilFinished$,
1040
- resetState$,
1041
- /**
1042
- * We defer execution so that we return at least
1043
- * the current state first (same mechanism is used for query)
1044
- */
1045
- deferExecution$
1046
- ).pipe(
1047
- rxjs.map((state) => ({ state, mutation })),
1048
- __queryFinalizeHook ?? rxjs.identity,
1049
- rxjs.takeUntil(observeUntil$)
1050
- );
1051
- }),
1052
- rxjs.shareReplay({
1053
- refCount: true,
1054
- bufferSize: 1
1055
- }),
1056
- trackSubscriptions((count) => {
1057
- refCountSubject.next(count);
1058
- })
1059
- );
1060
- }
1061
- trigger({
1062
- args,
1063
- options,
1064
- mutation
1065
- }) {
1066
- __privateGet(this, _trigger$).next({ args, options, mutation });
1067
- }
1068
- }
1069
- _trigger$ = new WeakMap();
1070
- function partialMatchKey(a, b) {
1071
- if (a === b) {
1072
- return true;
1073
- }
1074
- if (typeof a !== typeof b) {
1075
- return false;
1076
- }
1077
- if (a && b && typeof a === "object" && typeof b === "object") {
1078
- return !Object.keys(b).some((key) => !partialMatchKey(a[key], b[key]));
1079
- }
1080
- return false;
1081
- }
1082
- const matchKey = (keyA, keyB, { exact = false } = {}) => {
1083
- if (exact) {
1084
- return hashKey(keyA) === hashKey(keyB);
1085
- }
1086
- return partialMatchKey(keyA, keyB);
1087
- };
1088
- const distinctUntilStateChanged = (stream) => stream.pipe(
1089
- rxjs.distinctUntilChanged(
1090
- ({ data: prevData, ...prev }, { data: currData, ...curr }) => shallowEqual(prev, curr) && shallowEqual(prevData, currData)
1091
- )
1092
- );
1093
- class MutationObserver {
1094
- constructor(client, options = {}, mutationRunner) {
1095
- __privateAdd(this, _mutationRunner);
1096
- __privateAdd(this, _currentMutationSubject, new rxjs.BehaviorSubject(void 0));
1097
- /**
1098
- * @important
1099
- * Used to maintain persistance to latest mutation. This ensure
1100
- * - mutation does not get garbage collected
1101
- * - mutation mutate options are run on finish
1102
- */
1103
- __publicField(this, "observed$");
1104
- __publicField(this, "getObserverResultFromState", (state) => {
1105
- return {
1106
- ...getDefaultMutationState(),
1107
- ...state,
1108
- isSuccess: state.status === "success",
1109
- isPending: state.status === "pending",
1110
- isIdle: state.status === "idle",
1111
- isError: state.status === "error",
1112
- // eslint-disable-next-line @typescript-eslint/unbound-method
1113
- mutate: this.mutate,
1114
- // eslint-disable-next-line @typescript-eslint/unbound-method
1115
- reset: this.reset
1116
- };
1117
- });
1118
- var _a;
1119
- this.client = client;
1120
- this.options = options;
1121
- this.options.mutationKey = ((_a = this.options) == null ? void 0 : _a.mutationKey) ?? [nanoid()];
1122
- __privateSet(this, _mutationRunner, mutationRunner ?? new MutationRunner(this.options));
1123
- this.mutate = this.mutate.bind(this);
1124
- this.reset = this.reset.bind(this);
1125
- __privateGet(this, _currentMutationSubject).pipe(
1126
- rxjs.filter(isDefined),
1127
- rxjs.mergeMap(
1128
- (mutation) => __privateGet(this, _mutationRunner).state$.pipe(
1129
- rxjs.takeUntil(
1130
- mutation.mutation.state$.pipe(observeUntilFinished, rxjs.last())
1131
- )
1132
- )
1133
- )
1134
- ).subscribe();
1135
- this.observed$ = __privateGet(this, _currentMutationSubject).pipe(
1136
- rxjs.switchMap((maybeMutation) => {
1137
- return (maybeMutation == null ? void 0 : maybeMutation.mutation.state$.pipe(
1138
- // last(),
1139
- rxjs.map((state) => ({
1140
- state,
1141
- options: maybeMutation.options
1142
- }))
1143
- )) ?? rxjs.EMPTY;
1144
- }),
1145
- rxjs.tap(({ state, options: options2 }) => {
1146
- if (state.status === "error") {
1147
- (options2 == null ? void 0 : options2.onError) && (options2 == null ? void 0 : options2.onError(
1148
- state.error,
1149
- state.variables,
1150
- state.context
1151
- ));
1152
- (options2 == null ? void 0 : options2.onSettled) && (options2 == null ? void 0 : options2.onSettled(
1153
- state.data,
1154
- state.error,
1155
- state.variables,
1156
- state.context
1157
- ));
1158
- }
1159
- if (state.status === "success") {
1160
- (options2 == null ? void 0 : options2.onSuccess) && (options2 == null ? void 0 : options2.onSuccess(
1161
- state.data,
1162
- state.variables,
1163
- state.context
1164
- ));
1165
- (options2 == null ? void 0 : options2.onSettled) && (options2 == null ? void 0 : options2.onSettled(
1166
- state.data,
1167
- state.error,
1168
- state.variables,
1169
- state.context
1170
- ));
1171
- }
1172
- }),
1173
- rxjs.ignoreElements()
1174
- );
1175
- }
1176
- setOptions(options) {
1177
- var _a;
1178
- const prevOptions = this.options;
1179
- this.options = this.client.defaultMutationOptions({
1180
- mutationKey: this.options.mutationKey,
1181
- ...options
1182
- });
1183
- const currentMutation = (_a = __privateGet(this, _currentMutationSubject).getValue()) == null ? void 0 : _a.mutation;
1184
- if (this.options.mutationKey && prevOptions.mutationKey && !matchKey(this.options.mutationKey, prevOptions.mutationKey, {
1185
- exact: true
1186
- })) {
1187
- this.reset();
1188
- } else {
1189
- currentMutation == null ? void 0 : currentMutation.setOptions(this.options);
1190
- }
1191
- }
1192
- observe() {
1193
- var _a;
1194
- const lastValue = this.getObserverResultFromState(
1195
- ((_a = __privateGet(this, _currentMutationSubject).getValue()) == null ? void 0 : _a.mutation.state) ?? getDefaultMutationState()
1196
- );
1197
- const mutationResult$ = __privateGet(this, _mutationRunner).state$.pipe(
1198
- rxjs.distinctUntilChanged(
1199
- ({ mutation: prevMutation, state: { data: prevData, ...prev } }, { mutation: currentMutation, state: { data: currData, ...curr } }) => prevMutation === currentMutation && shallowEqual(prev, curr) && shallowEqual(prevData, currData)
1200
- ),
1201
- rxjs.map(({ state }) => state),
1202
- rxjs.scan((acc, current) => {
1203
- return {
1204
- ...acc,
1205
- ...current,
1206
- ...current.status === "pending" && {
1207
- data: current.data ?? acc.data
1208
- },
1209
- ...current.status === "pending" && {
1210
- error: current.error ?? acc.error
1211
- }
1212
- };
1213
- }),
1214
- rxjs.map((state) => this.getObserverResultFromState(state))
1215
- );
1216
- const defaultStateOnMutationCancel$ = __privateGet(this, _currentMutationSubject).pipe(
1217
- rxjs.filter(isDefined),
1218
- rxjs.switchMap((mutation) => mutation.mutation.cancelled$),
1219
- rxjs.map(() => this.getObserverResultFromState(getDefaultMutationState()))
1220
- );
1221
- const result$ = rxjs.merge(
1222
- this.observed$,
1223
- mutationResult$,
1224
- defaultStateOnMutationCancel$
1225
- ).pipe(distinctUntilStateChanged);
1226
- return { result$, lastValue };
1227
- }
1228
- /**
1229
- * @important
1230
- * Compliance react-query only
1231
- */
1232
- subscribe(subscription) {
1233
- const sub = this.observe().result$.subscribe((result) => {
1234
- subscription(result);
1235
- });
1236
- return () => {
1237
- sub.unsubscribe();
1238
- };
1239
- }
1240
- async mutate(variables, options = {}) {
1241
- const mutation = this.client.getMutationCache().build(this.client, this.options);
1242
- __privateGet(this, _currentMutationSubject).next({ mutation, options });
1243
- __privateGet(this, _mutationRunner).trigger({
1244
- args: variables,
1245
- options: this.options,
1246
- mutation
1247
- });
1248
- return await new Promise((resolve, reject) => {
1249
- mutation.state$.pipe(observeUntilFinished, rxjs.last()).subscribe({
1250
- error: (error) => {
1251
- reject(error);
1252
- },
1253
- next: (data) => {
1254
- if (data.error) {
1255
- reject(data.error);
1256
- } else {
1257
- resolve(data.data);
1258
- }
1259
- }
1260
- });
1261
- });
1262
- }
1263
- getCurrentResult() {
1264
- var _a;
1265
- const mutation = this.client.getMutationCache().find({ exact: true, mutationKey: (_a = this.options) == null ? void 0 : _a.mutationKey });
1266
- return this.getObserverResultFromState(
1267
- (mutation == null ? void 0 : mutation.state) ?? getDefaultMutationState()
1268
- );
1269
- }
1270
- reset() {
1271
- const { mutation } = __privateGet(this, _currentMutationSubject).getValue() ?? {};
1272
- __privateGet(this, _currentMutationSubject).next(void 0);
1273
- mutation == null ? void 0 : mutation.cancel();
1274
- }
1275
- }
1276
- _mutationRunner = new WeakMap();
1277
- _currentMutationSubject = new WeakMap();
1278
- const Context = React.createContext(void 0);
1279
- const ClientEffect = ({ client }) => {
1280
- React.useEffect(() => {
1281
- client.mount();
1282
- return () => {
1283
- client.unmount();
1284
- };
1285
- }, [client]);
1286
- return null;
1287
- };
1288
- const QueryClientProvider = React.memo(
1289
- ({ children, client }) => {
1290
- const value = React.useMemo(() => client, [client]);
1291
- return /* @__PURE__ */ jsxRuntime.jsxs(Context.Provider, { value, children: [
1292
- /* @__PURE__ */ jsxRuntime.jsx(ClientEffect, { client }),
1293
- children
1294
- ] });
1295
- }
1296
- );
1297
- const useQueryClient = (queryClient) => {
1298
- const client = React.useContext(Context);
1299
- if (queryClient) {
1300
- return queryClient;
1301
- }
1302
- if (!client) {
1303
- throw new Error("No QueryClient set, use QueryClientProvider to set one");
1304
- }
1305
- return client;
1306
- };
1307
- function noop() {
1308
- }
1309
- function useMutation(options, queryClient) {
1310
- const defaultQueryClient = useQueryClient(queryClient);
1311
- const optionsRef = useLiveRef(options);
1312
- const defaultKey = useConstant(() => [nanoid()]);
1313
- const serializedKey = hashKey(options.mutationKey ?? defaultKey.current);
1314
- const [mutationObserver] = React.useState(
1315
- () => new MutationObserver(
1316
- defaultQueryClient,
1317
- options
1318
- )
1319
- );
1320
- React.useEffect(() => {
1321
- mutationObserver.setOptions(options);
1322
- }, [mutationObserver, options]);
1323
- const observedMutation = React.useMemo(() => {
1324
- return mutationObserver.observe();
1325
- }, [serializedKey, mutationObserver]);
1326
- const result = useObserve(observedMutation.result$) ?? observedMutation.lastValue;
1327
- const mutate = React.useCallback(
1328
- (variables, mutateOptions) => {
1329
- mutationObserver.mutate(variables, mutateOptions).catch(noop);
1330
- },
1331
- [mutationObserver]
1332
- );
1333
- React.useEffect(() => {
1334
- return () => {
1335
- if (optionsRef.current.cancelOnUnMount) {
1336
- mutationObserver.reset();
1337
- }
1338
- };
1339
- }, [mutationObserver, optionsRef]);
1340
- return { ...result, mutate, mutateAsync: result.mutate };
1341
- }
1342
- function emitToSubject(subject) {
1343
- return (source$) => source$.pipe(
1344
- operators.tap((value) => {
1345
- subject.next(value);
1346
- })
1347
- );
1348
- }
1349
- class OnlineManager {
1350
- constructor() {
1351
- __publicField(this, "isOnlineSubject", new rxjs.BehaviorSubject(true));
1352
- __publicField(this, "online$", this.isOnlineSubject.pipe(rxjs.distinctUntilChanged()));
1353
- __publicField(this, "backToOnline$", this.online$.pipe(
1354
- rxjs.filter((isOnline) => isOnline),
1355
- rxjs.first()
1356
- ));
1357
- rxjs.merge(
1358
- isServer ? rxjs.EMPTY : rxjs.fromEvent(window, "offline").pipe(rxjs.map(() => false)),
1359
- isServer ? rxjs.EMPTY : rxjs.fromEvent(window, "online").pipe(rxjs.map(() => true))
1360
- ).pipe(emitToSubject(this.isOnlineSubject)).subscribe();
1361
- }
1362
- isOnline() {
1363
- return this.isOnlineSubject.getValue();
1364
- }
1365
- setOnline(online) {
1366
- const changed = this.isOnlineSubject.getValue() !== online;
1367
- if (changed) {
1368
- this.isOnlineSubject.next(online);
1369
- }
1370
- }
1371
- }
1372
- const onlineManager = new OnlineManager();
1373
- function isStale(query, options) {
1374
- return query.isStaleByTime(options.staleTime);
1375
- }
1376
- function shouldLoadOnMount(query, options) {
1377
- return options.enabled !== false && !query.state.dataUpdatedAt && !(query.state.status === "error" && options.retryOnMount === false) && query.state.fetchStatus !== "fetching";
1378
- }
1379
- function shouldFetchOnMount(query, options) {
1380
- return shouldLoadOnMount(query, options) || query.state.dataUpdatedAt > 0 && shouldFetchOn(query, options, options.refetchOnMount);
1381
- }
1382
- function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
1383
- return query.state.fetchStatus !== "fetching" && options.enabled !== false && (query !== prevQuery || prevOptions.enabled === false) && (!options.suspense || query.state.status !== "error") && isStale(query, options);
1384
- }
1385
- function shouldFetchOnWindowFocus(query, options) {
1386
- return shouldFetchOn(query, options, options.refetchOnWindowFocus);
1387
- }
1388
- function shouldFetchOn(query, options, field) {
1389
- if (options.enabled !== false) {
1390
- const value = typeof field === "function" ? field(query) : field;
1391
- if (value === "idle") {
1392
- return query.state.fetchStatus === "idle";
1393
- }
1394
- return value === "always" || value !== false && isStale(query, options);
1395
- }
1396
- return false;
1397
- }
1398
- function canFetch(networkMode) {
1399
- return (networkMode ?? "online") === "online" ? onlineManager.isOnline() : true;
1400
- }
1401
- function filterObjectByKey(obj, keys) {
1402
- return keys.reduce(
1403
- (acc, key) => {
1404
- if (key in obj) {
1405
- return { ...acc, [key]: obj[key] };
1406
- }
1407
- return acc;
1408
- },
1409
- {}
1410
- );
1411
- }
1412
- function isPlainArray(value) {
1413
- return Array.isArray(value) && value.length === Object.keys(value).length;
1414
- }
1415
- function replaceEqualDeep(a, b) {
1416
- if (a === b) {
1417
- return a;
1418
- }
1419
- const array = isPlainArray(a) && isPlainArray(b);
1420
- if (array || isPlainObject(a) && isPlainObject(b)) {
1421
- const aItems = array ? a : Object.keys(a);
1422
- const aSize = aItems.length;
1423
- const bItems = array ? b : Object.keys(b);
1424
- const bSize = bItems.length;
1425
- const copy = array ? [] : {};
1426
- let equalItems = 0;
1427
- for (let i = 0; i < bSize; i++) {
1428
- const key = array ? i : bItems[i];
1429
- if (!array && a[key] === void 0 && b[key] === void 0 && aItems.includes(key)) {
1430
- copy[key] = void 0;
1431
- equalItems++;
1432
- } else {
1433
- copy[key] = replaceEqualDeep(a[key], b[key]);
1434
- if (copy[key] === a[key] && a[key] !== void 0) {
1435
- equalItems++;
1436
- }
1437
- }
1438
- }
1439
- return aSize === bSize && equalItems === aSize ? a : copy;
1440
- }
1441
- return b;
1442
- }
1443
- function hashQueryKeyByOptions(queryKey, options) {
1444
- const hashFn = (options == null ? void 0 : options.queryKeyHashFn) ?? hashKey;
1445
- return hashFn(queryKey);
1446
- }
1447
- function matchQuery(filters, query) {
1448
- const {
1449
- type = "all",
1450
- exact,
1451
- fetchStatus,
1452
- predicate,
1453
- queryKey,
1454
- stale
1455
- } = filters;
1456
- if (queryKey) {
1457
- if (exact) {
1458
- if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
1459
- return false;
1460
- }
1461
- } else if (!partialMatchKey(query.queryKey, queryKey)) {
1462
- return false;
1463
- }
1464
- }
1465
- if (type !== "all") {
1466
- const isActive = query.isActive();
1467
- if (type === "active" && !isActive) {
1468
- return false;
1469
- }
1470
- if (type === "inactive" && isActive) {
1471
- return false;
1472
- }
1473
- }
1474
- if (typeof stale === "boolean" && query.isStale() !== stale) {
1475
- return false;
1476
- }
1477
- if (typeof fetchStatus !== "undefined" && fetchStatus !== query.state.fetchStatus) {
1478
- return false;
1479
- }
1480
- if (predicate && !predicate(query)) {
1481
- return false;
1482
- }
1483
- return true;
1484
- }
1485
- function timeUntilStale(updatedAt, staleTime) {
1486
- return Math.max(updatedAt + (staleTime ?? 0) - Date.now(), 0);
1487
- }
1488
- function functionalUpdate(updater, input) {
1489
- return typeof updater === "function" ? updater(input) : updater;
1490
- }
1491
- function replaceData(prevData, data, options) {
1492
- if (typeof options.structuralSharing === "function") {
1493
- return options.structuralSharing(prevData, data);
1494
- } else if (options.structuralSharing !== false) {
1495
- return replaceEqualDeep(prevData, data);
1496
- }
1497
- return data;
1498
- }
1499
- const skipToken = Symbol();
1500
- const reduceState = ({
1501
- getOptions,
1502
- getState,
1503
- initialState
1504
- }) => (source) => source.pipe(
1505
- rxjs.scan((acc, { command, state: current }) => {
1506
- if (command === "reset") return { ...acc, ...current };
1507
- if (command === "cancel") {
1508
- const status2 = acc.status === "pending" ? "pending" : current.status ?? acc.status;
1509
- return { ...acc, ...current, status: status2 };
1510
- }
1511
- const currentData = current.data;
1512
- const weHaveNewData = currentData !== void 0 && currentData !== acc.data;
1513
- const weHaveDataKeyInCurrent = "data" in current;
1514
- const newSuccessStatus = current.status === "success";
1515
- const hasData = acc.data !== void 0;
1516
- const hasError = acc.error !== void 0 || acc.error !== null;
1517
- const status = current.status ?? acc.status;
1518
- const newData = weHaveNewData ? replaceData(getState().data, currentData, getOptions()) : weHaveDataKeyInCurrent ? current.data : acc.data;
1519
- const previousStatusIsSuccessOrError = acc.status === "error" || acc.status === "success";
1520
- const errorUpdateCount = current.status === "error" && (acc.status === "error" && acc.fetchStatus === "fetching" || acc.status !== "error") ? acc.errorUpdateCount + 1 : acc.errorUpdateCount;
1521
- const dataUpdateCount = weHaveNewData ? acc.dataUpdateCount + 1 : current.dataUpdateCount ?? acc.dataUpdateCount;
1522
- const newPendingStatusOnHold = current.status === "pending" && previousStatusIsSuccessOrError && // (dataUpdateCount !== 0 || errorUpdateCount !== 0)
1523
- (hasData || hasError);
1524
- const error = status === "pending" ? null : current.error ?? acc.error;
1525
- return {
1526
- ...acc,
1527
- ...current,
1528
- status,
1529
- error,
1530
- errorUpdateCount,
1531
- ...newSuccessStatus && {
1532
- isInvalidated: false
1533
- },
1534
- data: newData,
1535
- dataUpdateCount,
1536
- ...newPendingStatusOnHold && {
1537
- status: acc.status
1538
- }
1539
- };
1540
- }, initialState)
1541
- );
1542
- const isQueryFinished = (source) => source.pipe(
1543
- rxjs.map(
1544
- ({ status, fetchStatus }) => fetchStatus === "idle" && (status === "success" || status === "error")
1545
- )
1546
- );
1547
- const takeUntilFinished = (source) => source.pipe(
1548
- rxjs.takeWhile((result) => {
1549
- const isFetchingOrPaused = result.fetchStatus !== "idle";
1550
- return isFetchingOrPaused;
1551
- }, true)
1552
- );
1553
- class FocusManager {
1554
- constructor() {
1555
- __privateAdd(this, _visibility$, rxjs.merge(
1556
- isServer ? rxjs.EMPTY : rxjs.fromEvent(document, "visibilitychange"),
1557
- isServer ? rxjs.EMPTY : rxjs.fromEvent(window, "visibilitychange")
1558
- ).pipe(rxjs.map(() => document.visibilityState)));
1559
- __privateAdd(this, _focusedSubject, new rxjs.BehaviorSubject(
1560
- isServer ? true : document.visibilityState === "visible"
1561
- ));
1562
- // public readonly focused$ = this.#focusedSubject.pipe(distinctUntilChanged())
1563
- __publicField(this, "focused$", __privateGet(this, _focusedSubject));
1564
- __publicField(this, "focusRegained$", this.focused$.pipe(
1565
- rxjs.skip(1),
1566
- rxjs.filter((visibility) => visibility)
1567
- ));
1568
- __privateGet(this, _visibility$).pipe(
1569
- rxjs.tap((value) => {
1570
- __privateGet(this, _focusedSubject).next(value === "visible");
1571
- })
1572
- ).subscribe();
1573
- }
1574
- isFocused() {
1575
- return __privateGet(this, _focusedSubject).getValue();
1576
- }
1577
- setFocused(focused) {
1578
- const changed = __privateGet(this, _focusedSubject).getValue() !== (focused ?? true);
1579
- if (changed) {
1580
- __privateGet(this, _focusedSubject).next(focused ?? true);
1581
- }
1582
- }
1583
- subscribe(fn) {
1584
- const sub = this.focused$.subscribe(fn);
1585
- return () => {
1586
- sub.unsubscribe();
1587
- };
1588
- }
1589
- /**
1590
- * @important
1591
- * You do not need that outside of testing. This is bad practice but necessary in order
1592
- * to not mess too much with rq tests files.
1593
- *
1594
- * Use it after mocking to force the manager to hold mocked value.
1595
- */
1596
- refresh() {
1597
- document.dispatchEvent(new Event("visibilitychange"));
1598
- }
1599
- }
1600
- _visibility$ = new WeakMap();
1601
- _focusedSubject = new WeakMap();
1602
- const focusManager = new FocusManager();
1603
- const whenNewData = (source) => source.pipe(
1604
- rxjs.filter((state) => state.status === "success"),
1605
- rxjs.map((state) => ({
1606
- data: state.data,
1607
- status: state.status,
1608
- dataUpdatedAt: state.dataUpdatedAt
1609
- })),
1610
- rxjs.distinctUntilChanged(shallowEqual)
1611
- );
1612
- class QueryObserver {
1613
- constructor(client, options) {
1614
- __privateAdd(this, _client);
1615
- __privateAdd(this, _currentQuery);
1616
- __privateAdd(this, _fetchSubject, new rxjs.Subject());
1617
- /**
1618
- * Used to subscribe to changes in either query or options (or both).
1619
- * We need to be able to track change to both of them at the same time
1620
- * in order to react accordingly and in order (such as refetch on options change)
1621
- */
1622
- __publicField(this, "queryUpdateSubject", new rxjs.Subject());
1623
- /**
1624
- * Mostly used to compare the state before and after mount
1625
- */
1626
- __privateAdd(this, _currentQueryInitialState);
1627
- /**
1628
- * Mostly used for internal optimization such as not
1629
- * running selectors twice, etc
1630
- */
1631
- __privateAdd(this, _lastResult);
1632
- // This property keeps track of the last query with defined data.
1633
- // It will be used to pass the previous data and query to the placeholder function between renders.
1634
- __privateAdd(this, _lastQueryWithDefinedData);
1635
- __privateAdd(this, _observers, 0);
1636
- __publicField(this, "getObserverResultFromQuery", ({
1637
- options,
1638
- query,
1639
- optimisticResult,
1640
- prevResult: {
1641
- result: prevResult,
1642
- options: prevResultOptions,
1643
- state: prevResultState,
1644
- select: prevSelect,
1645
- selectError: prevSelectError,
1646
- selectResult: prevSelectResult
1647
- }
1648
- }) => {
1649
- var _a;
1650
- const state = query.state;
1651
- const isPending = query.state.status === "pending";
1652
- const prevQuery = __privateGet(this, _currentQuery);
1653
- const prevOptions = this.options;
1654
- const queryChange = query !== prevQuery;
1655
- const queryInitialState = queryChange ? query.state : __privateGet(this, _currentQueryInitialState);
1656
- let { errorUpdatedAt, fetchStatus, error } = state;
1657
- if (optimisticResult) {
1658
- const mounted = !!__privateGet(this, _observers);
1659
- const fetchOnMount = !mounted && shouldFetchOnMount(query, options);
1660
- const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
1661
- if (fetchOnMount || fetchOptionally) {
1662
- fetchStatus = canFetch(query.options.networkMode) ? "fetching" : "paused";
1663
- }
1664
- }
1665
- const isLoading = isPending && fetchStatus === "fetching";
1666
- let data;
1667
- let selectError = prevSelectError;
1668
- let selectFn = prevSelect ?? null;
1669
- let selectResult = prevSelectResult;
1670
- if (options.select && typeof state.data !== "undefined") {
1671
- if (prevResult && state.data === (prevResultState == null ? void 0 : prevResultState.data) && options.select === prevSelect) {
1672
- data = prevSelectResult;
1673
- } else {
1674
- try {
1675
- selectFn = options.select;
1676
- data = options.select(state.data);
1677
- data = replaceData(prevResult == null ? void 0 : prevResult.data, data, options);
1678
- selectResult = data;
1679
- selectError = null;
1680
- } catch (error2) {
1681
- data = prevSelectResult;
1682
- selectError = error2;
1683
- }
1684
- }
1685
- } else {
1686
- data = state.data;
1687
- selectError = null;
1688
- }
1689
- let status = fetchStatus !== "idle" && !state.dataUpdatedAt ? "pending" : state.status;
1690
- if (selectError) {
1691
- error = selectError;
1692
- data = prevSelectResult;
1693
- errorUpdatedAt = (prevResult == null ? void 0 : prevResult.errorUpdatedAt) ?? errorUpdatedAt;
1694
- status = "error";
1695
- }
1696
- const isError = status === "error";
1697
- let isPlaceholderData = false;
1698
- if (typeof options.placeholderData !== "undefined" && typeof data === "undefined" && status === "pending") {
1699
- let placeholderData;
1700
- if ((prevResult == null ? void 0 : prevResult.isPlaceholderData) && options.placeholderData === (prevResultOptions == null ? void 0 : prevResultOptions.placeholderData)) {
1701
- placeholderData = prevResult.data;
1702
- } else {
1703
- placeholderData = typeof options.placeholderData === "function" ? options.placeholderData(
1704
- (_a = __privateGet(this, _lastQueryWithDefinedData)) == null ? void 0 : _a.state.data,
1705
- __privateGet(this, _lastQueryWithDefinedData)
1706
- ) : options.placeholderData;
1707
- if (options.select && typeof placeholderData !== "undefined") {
1708
- try {
1709
- placeholderData = options.select(placeholderData);
1710
- } catch (selectError2) {
1711
- }
1712
- }
1713
- }
1714
- if (typeof placeholderData !== "undefined") {
1715
- status = "success";
1716
- data = replaceData(
1717
- prevResult == null ? void 0 : prevResult.data,
1718
- placeholderData,
1719
- options
1720
- );
1721
- isPlaceholderData = true;
1722
- }
1723
- }
1724
- const isFetching = fetchStatus === "fetching";
1725
- const result = {
1726
- status,
1727
- fetchStatus,
1728
- isPending,
1729
- isSuccess: status === "success",
1730
- isError,
1731
- isInitialLoading: isLoading,
1732
- isLoading,
1733
- data,
1734
- dataUpdatedAt: state.dataUpdatedAt,
1735
- error,
1736
- errorUpdatedAt,
1737
- failureCount: state.fetchFailureCount,
1738
- failureReason: state.fetchFailureReason,
1739
- errorUpdateCount: state.errorUpdateCount,
1740
- isFetched: state.dataUpdateCount > 0 || state.errorUpdateCount > 0,
1741
- isFetchedAfterMount: state.dataUpdateCount > queryInitialState.dataUpdateCount || state.errorUpdateCount > queryInitialState.errorUpdateCount,
1742
- isFetching,
1743
- isRefetching: isFetching && !isPending,
1744
- isLoadingError: isError && state.dataUpdatedAt === 0,
1745
- isPaused: fetchStatus === "paused",
1746
- isPlaceholderData,
1747
- isRefetchError: isError && state.dataUpdatedAt !== 0,
1748
- isStale: isStale(query, options),
1749
- // eslint-disable-next-line @typescript-eslint/unbound-method
1750
- refetch: this.refetch
1751
- };
1752
- return {
1753
- result,
1754
- selectError,
1755
- select: selectFn,
1756
- selectResult
1757
- };
1758
- });
1759
- this.options = options;
1760
- __privateSet(this, _client, client);
1761
- this.bindMethods();
1762
- __privateSet(this, _currentQuery, this.setOptions(options));
1763
- const query = __privateGet(this, _currentQuery);
1764
- __privateSet(this, _currentQueryInitialState, query.state);
1765
- const { result, select } = this.getObserverResultFromQuery({
1766
- query,
1767
- options: this.options,
1768
- prevResult: {
1769
- options: this.options,
1770
- state: query.state
1771
- }
1772
- });
1773
- __privateSet(this, _lastResult, {
1774
- state: query.state,
1775
- options,
1776
- result,
1777
- select
1778
- });
1779
- }
1780
- bindMethods() {
1781
- this.refetch = this.refetch.bind(this);
1782
- }
1783
- setOptions(options) {
1784
- const prevOptions = this.options;
1785
- this.options = __privateGet(this, _client).defaultQueryOptions(options);
1786
- if (!shallowEqual(this.options, prevOptions)) {
1787
- __privateGet(this, _client).getQueryCache().notify({
1788
- type: "observerOptionsUpdated",
1789
- query: __privateGet(this, _currentQuery),
1790
- observer: this
1791
- });
1792
- }
1793
- if (typeof this.options.enabled !== "undefined" && typeof this.options.enabled !== "boolean") {
1794
- throw new Error("Expected enabled to be a boolean");
1795
- }
1796
- const query = this.buildQuery(this.options);
1797
- if (query !== __privateGet(this, _currentQuery)) {
1798
- __privateSet(this, _currentQueryInitialState, query.state);
1799
- __privateSet(this, _currentQuery, query);
1800
- }
1801
- this.queryUpdateSubject.next({
1802
- options: this.options,
1803
- query
1804
- });
1805
- return query;
1806
- }
1807
- buildQuery(options) {
1808
- const query = __privateGet(this, _client).getQueryCache().build(__privateGet(this, _client), options);
1809
- if (!query.options.queryFn && this.options.queryFn) {
1810
- query.setOptions(options);
1811
- }
1812
- return query;
1813
- }
1814
- getCurrentResult() {
1815
- const result = this.getObserverResultFromQuery({
1816
- options: this.options,
1817
- prevResult: __privateGet(this, _lastResult),
1818
- query: __privateGet(this, _currentQuery)
1819
- });
1820
- return result.result;
1821
- }
1822
- getCurrentQuery() {
1823
- return __privateGet(this, _currentQuery);
1824
- }
1825
- getOptimisticResult(options) {
1826
- const query = this.buildQuery(options);
1827
- const observedResult = this.getObserverResultFromQuery({
1828
- query,
1829
- options,
1830
- optimisticResult: true,
1831
- prevResult: __privateGet(this, _lastResult)
1832
- });
1833
- if (shouldAssignObserverCurrentProperties(this, observedResult.result)) {
1834
- this.updateResult({ query, ...observedResult });
1835
- }
1836
- return observedResult.result;
1837
- }
1838
- updateResult({
1839
- query,
1840
- result,
1841
- selectError,
1842
- select,
1843
- selectResult
1844
- }) {
1845
- __privateGet(this, _lastResult).state = query.state;
1846
- __privateGet(this, _lastResult).result = result;
1847
- __privateGet(this, _lastResult).selectResult = selectResult;
1848
- if (selectError !== void 0) {
1849
- __privateGet(this, _lastResult).selectError = selectError;
1850
- }
1851
- if (select !== void 0) {
1852
- __privateGet(this, _lastResult).select = select;
1853
- }
1854
- __privateGet(this, _lastResult).options = this.options;
1855
- if (query.state.data !== void 0) {
1856
- __privateSet(this, _lastQueryWithDefinedData, query);
1857
- }
1858
- __privateGet(this, _client).getQueryCache().notify({
1859
- query: __privateGet(this, _currentQuery),
1860
- type: "observerResultsUpdated"
1861
- });
1862
- }
1863
- async refetch({ ...options } = {}) {
1864
- return await this.fetch({
1865
- ...options
1866
- });
1867
- }
1868
- async fetch(fetchOptions) {
1869
- const query = this.buildQuery(this.options);
1870
- if (query !== __privateGet(this, _currentQuery)) {
1871
- __privateSet(this, _currentQuery, query);
1872
- __privateSet(this, _currentQueryInitialState, query.state);
1873
- this.queryUpdateSubject.next({
1874
- options: this.options,
1875
- query
1876
- });
1877
- }
1878
- const finalFetchOptions = {
1879
- ...fetchOptions,
1880
- cancelRefetch: (fetchOptions == null ? void 0 : fetchOptions.cancelRefetch) ?? true
1881
- };
1882
- __privateGet(this, _currentQuery).fetch(this.options, finalFetchOptions).catch(rxjs.noop);
1883
- __privateGet(this, _fetchSubject).next({
1884
- query,
1885
- fetchOptions: finalFetchOptions
1886
- });
1887
- await query.getFetchResultAsPromise();
1888
- const { result } = this.getObserverResultFromQuery({
1889
- query,
1890
- options: this.options,
1891
- prevResult: __privateGet(this, _lastResult)
1892
- });
1893
- return result;
1894
- }
1895
- /**
1896
- * feature parity with rq, not used internally
1897
- */
1898
- subscribe(listener) {
1899
- const sub = this.observe().subscribe(listener);
1900
- return () => {
1901
- sub.unsubscribe();
1902
- };
1903
- }
1904
- observe() {
1905
- const observedQuery = __privateGet(this, _currentQuery);
1906
- const currentQuery$ = this.queryUpdateSubject.pipe(
1907
- rxjs.map(({ query }) => query),
1908
- rxjs.startWith(__privateGet(this, _currentQuery)),
1909
- rxjs.distinctUntilChanged()
1910
- );
1911
- const watchForImplicitRefetch$ = this.queryUpdateSubject.pipe(
1912
- rxjs.startWith({
1913
- query: __privateGet(this, _currentQuery),
1914
- options: this.options
1915
- }),
1916
- rxjs.pairwise(),
1917
- rxjs.tap(
1918
- ([{ options: prevOptions, query: prevQuery }, { options, query }]) => {
1919
- if (shouldFetchOptionally(query, prevQuery, options, prevOptions)) {
1920
- this.fetch().catch(rxjs.noop);
1921
- }
1922
- }
1923
- ),
1924
- rxjs.ignoreElements()
1925
- );
1926
- const observedQuery$ = currentQuery$.pipe(
1927
- rxjs.switchMap((query) => query.observe(this)),
1928
- rxjs.ignoreElements()
1929
- );
1930
- const result$ = rxjs.merge(
1931
- /**
1932
- * It's important to observe the query before we subscribe to its result
1933
- * later in the chain of merge to get the first result right after fetch
1934
- */
1935
- observedQuery$,
1936
- watchForImplicitRefetch$,
1937
- currentQuery$.pipe(
1938
- rxjs.switchMap((query) => {
1939
- const options = this.options;
1940
- const options$ = this.queryUpdateSubject.pipe(
1941
- rxjs.startWith({ query, options }),
1942
- rxjs.filter((update) => update.query === query),
1943
- rxjs.map((update) => update.options),
1944
- rxjs.distinctUntilChanged(),
1945
- rxjs.shareReplay(1)
1946
- );
1947
- const queryFetch$ = __privateGet(this, _fetchSubject).pipe(
1948
- rxjs.filter((update) => update.query === query)
1949
- );
1950
- const currentQueryIsStale$ = query.state$.pipe(
1951
- whenNewData,
1952
- rxjs.switchMap(
1953
- (state) => this.options.staleTime === Infinity ? rxjs.NEVER : (this.options.staleTime ?? 0) <= 0 ? rxjs.of(state).pipe(rxjs.delay(1)) : rxjs.timer(this.options.staleTime ?? 1)
1954
- ),
1955
- rxjs.takeWhile(() => this.options.enabled ?? true)
1956
- );
1957
- const comparisonFunction = (objA, objB) => {
1958
- const notifyOnChangeProps = options.notifyOnChangeProps;
1959
- const notifyOnChangePropsValue = typeof notifyOnChangeProps === "function" ? notifyOnChangeProps() : notifyOnChangeProps;
1960
- const reducedFunction = Array.isArray(notifyOnChangePropsValue) ? notifyOnChangePropsValue.length === 0 ? () => true : (objA2, objB2) => {
1961
- const reducedObjA = filterObjectByKey(
1962
- objA2,
1963
- notifyOnChangePropsValue
1964
- );
1965
- const reducedObjB = filterObjectByKey(
1966
- objB2,
1967
- notifyOnChangePropsValue
1968
- );
1969
- return shallowEqual(reducedObjA, reducedObjB);
1970
- } : shallowEqual;
1971
- return reducedFunction(objA, objB);
1972
- };
1973
- const queryInternallyFetchedUpdate$ = queryFetch$.pipe(
1974
- rxjs.switchMap(() => query.state$),
1975
- takeUntilFinished
1976
- );
1977
- const refetchInterval$ = options$.pipe(
1978
- rxjs.map(({ refetchInterval, refetchIntervalInBackground }) => {
1979
- const computedRefetchInterval = (typeof refetchInterval === "function" ? refetchInterval(__privateGet(this, _currentQuery)) : refetchInterval) ?? false;
1980
- return {
1981
- refetchInterval: computedRefetchInterval,
1982
- refetchIntervalInBackground
1983
- };
1984
- }),
1985
- rxjs.distinctUntilChanged(shallowEqual),
1986
- rxjs.switchMap(({ refetchInterval, refetchIntervalInBackground }) => {
1987
- return !refetchInterval ? rxjs.NEVER : rxjs.interval(refetchInterval).pipe(
1988
- rxjs.tap(() => {
1989
- if (
1990
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
1991
- refetchIntervalInBackground || focusManager.isFocused()
1992
- ) {
1993
- this.fetch({ cancelRefetch: false }).catch(rxjs.noop);
1994
- }
1995
- })
1996
- );
1997
- }),
1998
- rxjs.ignoreElements()
1999
- );
2000
- const isMaybeEnabled$ = options$.pipe(
2001
- rxjs.map(({ enabled }) => enabled ?? true),
2002
- rxjs.distinctUntilChanged()
2003
- );
2004
- const disabled$ = isMaybeEnabled$.pipe(
2005
- rxjs.filter((enabled) => !enabled),
2006
- rxjs.map(() => query.state)
2007
- );
2008
- const onFocusRegain$ = isMaybeEnabled$.pipe(
2009
- rxjs.filter((enabled) => enabled),
2010
- rxjs.switchMap(() => focusManager.focusRegained$),
2011
- rxjs.withLatestFrom(options$),
2012
- rxjs.tap(([, options2]) => {
2013
- if (shouldFetchOnWindowFocus(query, options2)) {
2014
- this.fetch({ cancelRefetch: false }).catch(rxjs.noop);
2015
- }
2016
- }),
2017
- rxjs.ignoreElements()
2018
- );
2019
- const stateObservedOnDisabled$ = disabled$.pipe(
2020
- rxjs.map(() => query.state)
2021
- );
2022
- const updateResult = (source) => {
2023
- return source.pipe(
2024
- rxjs.withLatestFrom(options$),
2025
- rxjs.map(([, currentOptions]) => {
2026
- const result = this.getObserverResultFromQuery({
2027
- query,
2028
- options: currentOptions,
2029
- prevResult: __privateGet(this, _lastResult)
2030
- });
2031
- this.updateResult({ query, ...result });
2032
- return result.result;
2033
- })
2034
- );
2035
- };
2036
- const stateUpdate$ = rxjs.merge(
2037
- stateObservedOnDisabled$,
2038
- queryInternallyFetchedUpdate$,
2039
- query.state$,
2040
- // options$,
2041
- currentQueryIsStale$
2042
- );
2043
- const observedResult$ = stateUpdate$.pipe(
2044
- updateResult,
2045
- // This one ensure we don't re-trigger same state
2046
- rxjs.distinctUntilChanged(shallowEqual),
2047
- // This one make sure we dispatch based on user preference
2048
- rxjs.distinctUntilChanged(comparisonFunction)
2049
- );
2050
- return rxjs.merge(refetchInterval$, onFocusRegain$, observedResult$);
2051
- })
2052
- ).pipe(
2053
- trackSubscriptions((count) => __privateSet(this, _observers, count)),
2054
- rxjs.tap({
2055
- subscribe: () => {
2056
- if (shouldFetchOnMount(observedQuery, this.options)) {
2057
- this.fetch().catch(rxjs.noop);
2058
- }
2059
- }
2060
- })
2061
- )
2062
- );
2063
- return result$;
2064
- }
2065
- destroy() {
2066
- }
2067
- }
2068
- _client = new WeakMap();
2069
- _currentQuery = new WeakMap();
2070
- _fetchSubject = new WeakMap();
2071
- _currentQueryInitialState = new WeakMap();
2072
- _lastResult = new WeakMap();
2073
- _lastQueryWithDefinedData = new WeakMap();
2074
- _observers = new WeakMap();
2075
- function shouldAssignObserverCurrentProperties(observer, optimisticResult) {
2076
- if (!shallowEqual(observer.getCurrentResult(), optimisticResult)) {
2077
- return true;
2078
- }
2079
- return false;
2080
- }
2081
- const IsRestoringContext = React__namespace.createContext(false);
2082
- const useIsRestoring = () => React__namespace.useContext(IsRestoringContext);
2083
- IsRestoringContext.Provider;
2084
- function createValue() {
2085
- let isReset = false;
2086
- return {
2087
- clearReset: () => {
2088
- isReset = false;
2089
- },
2090
- reset: () => {
2091
- isReset = true;
2092
- },
2093
- isReset: () => {
2094
- return isReset;
2095
- }
2096
- };
2097
- }
2098
- const QueryErrorResetBoundaryContext = React__namespace.createContext(createValue());
2099
- const useQueryErrorResetBoundary = () => React__namespace.useContext(QueryErrorResetBoundaryContext);
2100
- function shouldThrowError(throwError, params) {
2101
- if (typeof throwError === "function") {
2102
- return throwError(...params);
2103
- }
2104
- return !!throwError;
2105
- }
2106
- const getHasError = ({
2107
- result,
2108
- errorResetBoundary,
2109
- throwOnError,
2110
- query
2111
- }) => {
2112
- return result.isError && !errorResetBoundary.isReset() && !result.isFetching && query && shouldThrowError(throwOnError, [result.error, query]);
2113
- };
2114
- function useBaseQuery(options, Observer, queryClient) {
2115
- if (process.env.NODE_ENV !== "production") {
2116
- if (typeof options !== "object" || Array.isArray(options)) {
2117
- throw new Error(
2118
- 'Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object'
2119
- );
2120
- }
2121
- }
2122
- const client = useQueryClient(queryClient);
2123
- const isRestoring = useIsRestoring();
2124
- const errorResetBoundary = useQueryErrorResetBoundary();
2125
- const defaultedOptions = client.defaultQueryOptions(options);
2126
- defaultedOptions._optimisticResults = isRestoring ? "isRestoring" : "optimistic";
2127
- const [observer] = React.useState(
2128
- () => new Observer(
2129
- client,
2130
- defaultedOptions
2131
- )
2132
- );
2133
- const result$ = useConstant(() => observer.observe());
2134
- const optimisticResult = useLiveRef(
2135
- observer.getOptimisticResult(defaultedOptions)
2136
- );
2137
- const result = optimisticResult.current;
2138
- useObserve(
2139
- () => result$.current.pipe(
2140
- /**
2141
- * By the time this observer runs the result may have changed (eg: synchronous setData).
2142
- * It's important to not skip the first result (even tho most of the time they are equal).
2143
- * We only skip if they are the same.
2144
- */
2145
- rxjs.filter((result2) => !shallowEqual(result2, optimisticResult.current))
2146
- ),
2147
- []
2148
- );
2149
- React.useEffect(() => {
2150
- observer.setOptions(defaultedOptions);
2151
- }, [defaultedOptions, observer]);
2152
- const error = result.error;
2153
- if (error && getHasError({
2154
- result,
2155
- errorResetBoundary,
2156
- throwOnError: defaultedOptions.throwOnError,
2157
- query: client.getQueryCache().get(defaultedOptions.queryHash)
2158
- })) {
2159
- throw error;
2160
- }
2161
- return optimisticResult.current;
2162
- }
2163
- function useQuery(options, queryClient) {
2164
- return useBaseQuery(options, QueryObserver, queryClient);
2165
- }
2166
- function useForeverQuery(options, queryClient) {
2167
- return useBaseQuery(
2168
- {
2169
- refetchOnMount: "idle",
2170
- refetchOnReconnect: false,
2171
- refetchInterval: false,
2172
- refetchOnWindowFocus: false,
2173
- ...options
2174
- },
2175
- QueryObserver,
2176
- queryClient
2177
- );
2178
- }
2179
- function useSubscribeEffect(source, unsafeOptions, deps = []) {
2180
- const options = unsafeOptions != null && !Array.isArray(unsafeOptions) ? unsafeOptions : {};
2181
- const retryOption = options.retry ?? true;
2182
- const onErrorRef = useLiveRef(
2183
- options.onError ?? ((error) => {
2184
- console.error(error);
2185
- })
2186
- );
2187
- const sourceAsObservable = React.useCallback(() => makeObservable(source), deps);
2188
- const enhancerMakeObservable = React.useCallback(
2189
- () => sourceAsObservable().pipe(
2190
- rxjs.catchError((error) => {
2191
- onErrorRef.current(error);
2192
- throw error;
2193
- }),
2194
- retryOption ? rxjs.retry() : rxjs.identity
2195
- ),
2196
- [sourceAsObservable, retryOption, onErrorRef]
2197
- );
2198
- useSubscribe(enhancerMakeObservable, deps);
2199
- }
2200
- const delayWhenNetworkOnline = () => (source) => {
2201
- return rxjs.merge(
2202
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
2203
- rxjs.of({ isPaused: true }),
2204
- onlineManager.backToOnline$.pipe(
2205
- rxjs.mergeMap(
2206
- () => (
2207
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
2208
- rxjs.merge(rxjs.of({ isPaused: false }), source)
2209
- )
2210
- )
2211
- )
2212
- );
2213
- };
2214
- const waitForNetworkOnError = (source) => {
2215
- let attempt = 0;
2216
- return source.pipe(
2217
- rxjs.catchError((error) => {
2218
- attempt++;
2219
- if (attempt <= 1 && !onlineManager.isOnline()) {
2220
- return rxjs.merge(
2221
- rxjs.of({
2222
- failureCount: attempt,
2223
- failureReason: error
2224
- }),
2225
- /**
2226
- * @important
2227
- * timer needed to be iso RQ, so the state returned by mutation include both previous and next one
2228
- */
2229
- rxjs.timer(1).pipe(
2230
- rxjs.mergeMap(
2231
- () => rxjs.throwError(() => error).pipe(delayWhenNetworkOnline())
2232
- )
2233
- )
2234
- );
2235
- } else {
2236
- return rxjs.throwError(() => error);
2237
- }
2238
- })
2239
- );
2240
- };
2241
- const executeMutation = ({
2242
- variables,
2243
- state,
2244
- options
2245
- }) => {
2246
- const isPaused = state.isPaused;
2247
- const defaultFn = async () => await Promise.reject(new Error("No mutationFn found"));
2248
- const mutationFn = options.mutationFn ?? defaultFn;
2249
- const onMutateFactory = () => {
2250
- var _a;
2251
- return ((_a = options.onMutate) == null ? void 0 : _a.call(options, variables)) ?? void 0;
2252
- };
2253
- const contextFromOnMutate$ = makeObservable(onMutateFactory);
2254
- contextFromOnMutate$.pipe(
2255
- rxjs.tap((context) => {
2256
- if (context === void 0) {
2257
- throw new Error("onMutate returned undefined");
2258
- }
2259
- })
2260
- );
2261
- const rawContext$ = rxjs.of(state.context);
2262
- const context$ = rxjs.iif(() => isPaused, rawContext$, contextFromOnMutate$).pipe(
2263
- rxjs.shareReplay(1)
2264
- );
2265
- const onError = (error, context, attempt) => {
2266
- const onError$ = makeObservable(
2267
- () => {
2268
- var _a;
2269
- return (_a = options.onError) == null ? void 0 : _a.call(options, error, variables, context);
2270
- }
2271
- );
2272
- return onError$.pipe(
2273
- rxjs.catchError(() => rxjs.of(error)),
2274
- rxjs.map(
2275
- () => ({
2276
- failureCount: attempt,
2277
- error,
2278
- failureReason: error,
2279
- context,
2280
- status: "error"
2281
- })
2282
- )
2283
- );
2284
- };
2285
- const queryRunner$ = context$.pipe(
2286
- rxjs.switchMap((context) => {
2287
- const fn$ = typeof mutationFn === "function" ? makeObservable(() => mutationFn(variables)) : mutationFn;
2288
- const sharedFn$ = fn$.pipe(rxjs.share());
2289
- const completeWithoutValue$ = sharedFn$.pipe(
2290
- rxjs.isEmpty(),
2291
- rxjs.tap((isEmppty) => {
2292
- if (isEmppty) {
2293
- throw new Error("Mutation completed without any emission (EMPTY)");
2294
- }
2295
- }),
2296
- rxjs.ignoreElements()
2297
- );
2298
- const finalFn$ = rxjs.merge(sharedFn$, completeWithoutValue$).pipe(
2299
- rxjs.map(
2300
- (data) => ({
2301
- result: {
2302
- data
2303
- },
2304
- error: null,
2305
- context
2306
- })
2307
- ),
2308
- waitForNetworkOnError,
2309
- retryBackoff({
2310
- ...options,
2311
- retry: (attempt, error) => {
2312
- const retry = options.retry ?? 0;
2313
- if (typeof retry === "function") return retry(attempt, error);
2314
- if (typeof retry === "boolean") return retry;
2315
- return attempt < retry;
2316
- },
2317
- caughtError: (attempt, error) => (
2318
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
2319
- rxjs.of({
2320
- failureCount: attempt,
2321
- failureReason: error
2322
- })
2323
- ),
2324
- catchError: (attempt, error) => onError(error, context, attempt).pipe(
2325
- rxjs.map((data) => ({
2326
- ...data,
2327
- result: void 0
2328
- }))
2329
- )
2330
- }),
2331
- rxjs.takeWhile(
2332
- ({ result, error }) => (result == null ? void 0 : result.data) === void 0 && error === void 0,
2333
- true
2334
- )
2335
- );
2336
- if (onlineManager.isOnline() || options.networkMode === "offlineFirst" || options.networkMode === "always") {
2337
- return finalFn$;
2338
- } else {
2339
- return finalFn$.pipe(delayWhenNetworkOnline());
2340
- }
2341
- })
2342
- );
2343
- const initState$ = rxjs.of({
2344
- ...state,
2345
- variables,
2346
- status: "pending",
2347
- isPaused: false,
2348
- failureCount: 0,
2349
- failureReason: null,
2350
- submittedAt: state.submittedAt ?? (/* @__PURE__ */ new Date()).getTime()
2351
- });
2352
- const mutation$ = rxjs.merge(
2353
- initState$,
2354
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
2355
- context$.pipe(rxjs.map((context) => ({ context }))),
2356
- queryRunner$.pipe(
2357
- rxjs.switchMap(({ result: mutationData, error, ...restState }) => {
2358
- if (!mutationData && !error)
2359
- return rxjs.of({
2360
- ...restState
2361
- });
2362
- const success$ = error ? rxjs.of(null) : makeObservable(
2363
- () => {
2364
- var _a;
2365
- return (_a = options.onSuccess) == null ? void 0 : _a.call(
2366
- options,
2367
- mutationData == null ? void 0 : mutationData.data,
2368
- variables,
2369
- restState.context
2370
- );
2371
- }
2372
- );
2373
- const onOptionSettled$ = makeObservable(
2374
- () => {
2375
- var _a;
2376
- return (_a = options.onSettled) == null ? void 0 : _a.call(
2377
- options,
2378
- mutationData == null ? void 0 : mutationData.data,
2379
- error,
2380
- variables,
2381
- restState.context
2382
- );
2383
- }
2384
- );
2385
- const settled$ = onOptionSettled$.pipe(
2386
- rxjs.catchError((error2) => mutationData ? rxjs.of(mutationData) : rxjs.of(error2))
2387
- );
2388
- const result$ = rxjs.concat(success$, settled$).pipe(
2389
- rxjs.toArray(),
2390
- rxjs.map(
2391
- () => error ? {
2392
- error,
2393
- data: void 0,
2394
- variables,
2395
- ...restState
2396
- } : {
2397
- status: "success",
2398
- error,
2399
- data: mutationData == null ? void 0 : mutationData.data,
2400
- variables,
2401
- failureCount: 0,
2402
- failureReason: null,
2403
- ...restState
2404
- }
2405
- ),
2406
- rxjs.catchError(
2407
- (error2) => onError(error2, restState.context, 0).pipe(
2408
- rxjs.map((data) => ({
2409
- ...data,
2410
- data: void 0
2411
- }))
2412
- )
2413
- )
2414
- );
2415
- return result$;
2416
- })
2417
- )
2418
- ).pipe(
2419
- rxjs.scan((acc, current) => {
2420
- return {
2421
- ...acc,
2422
- ...current,
2423
- data: current.data ?? acc.data,
2424
- error: current.error ?? acc.error
2425
- };
2426
- }, getDefaultMutationState())
2427
- );
2428
- return mutation$;
2429
- };
2430
- class Mutation {
2431
- constructor({
2432
- options,
2433
- mutationCache,
2434
- state
2435
- }) {
2436
- __privateAdd(this, _observerCount, new rxjs.BehaviorSubject(0));
2437
- __privateAdd(this, _cancelSubject, new rxjs.Subject());
2438
- __privateAdd(this, _executeSubject, new rxjs.Subject());
2439
- __publicField(this, "state", getDefaultMutationState());
2440
- __publicField(this, "state$");
2441
- __publicField(this, "options");
2442
- __publicField(this, "observerCount$", __privateGet(this, _observerCount).asObservable());
2443
- __publicField(this, "cancelled$", __privateGet(this, _cancelSubject).asObservable());
2444
- this.options = options;
2445
- this.state = state ?? this.state;
2446
- const resetPendingState$ = __privateGet(this, _cancelSubject).pipe(
2447
- rxjs.filter(() => this.state.status === "pending"),
2448
- rxjs.map(() => ({
2449
- status: "idle"
2450
- }))
2451
- );
2452
- const executionState$ = __privateGet(this, _executeSubject).pipe(
2453
- rxjs.switchMap(
2454
- (variables) => executeMutation({
2455
- options: {
2456
- ...this.options,
2457
- onMutate: (variables2) => {
2458
- const onCacheMutate$ = makeObservable(
2459
- () => {
2460
- var _a, _b;
2461
- return (_b = (_a = mutationCache.config).onMutate) == null ? void 0 : _b.call(
2462
- _a,
2463
- variables2,
2464
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2465
- this
2466
- );
2467
- }
2468
- );
2469
- const optionsOnMutate = () => {
2470
- var _a, _b;
2471
- return (_b = (_a = this.options).onMutate) == null ? void 0 : _b.call(_a, variables2);
2472
- };
2473
- const onOptionMutate$ = makeObservable(optionsOnMutate);
2474
- const context$ = onCacheMutate$.pipe(
2475
- rxjs.mergeMap(() => onOptionMutate$)
2476
- );
2477
- return context$;
2478
- },
2479
- onError: (error, variables2, context) => {
2480
- const onCacheError$ = makeObservable(
2481
- () => {
2482
- var _a, _b;
2483
- return (_b = (_a = mutationCache.config).onError) == null ? void 0 : _b.call(
2484
- _a,
2485
- error,
2486
- variables2,
2487
- context,
2488
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2489
- this
2490
- );
2491
- }
2492
- );
2493
- const onOptionError$ = makeObservable(
2494
- () => {
2495
- var _a, _b;
2496
- return (_b = (_a = this.options).onError) == null ? void 0 : _b.call(_a, error, variables2, context);
2497
- }
2498
- );
2499
- return rxjs.concat(onCacheError$, onOptionError$).pipe(rxjs.toArray());
2500
- },
2501
- onSettled: (data, error, variables2, context) => {
2502
- const onCacheSuccess$ = makeObservable(
2503
- () => {
2504
- var _a, _b;
2505
- return (_b = (_a = mutationCache.config).onSettled) == null ? void 0 : _b.call(
2506
- _a,
2507
- data,
2508
- error,
2509
- variables2,
2510
- context,
2511
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2512
- this
2513
- );
2514
- }
2515
- );
2516
- const onOptionSettled$ = makeObservable(
2517
- () => {
2518
- var _a, _b;
2519
- return (_b = (_a = this.options).onSettled) == null ? void 0 : _b.call(_a, data, error, variables2, context);
2520
- }
2521
- );
2522
- return rxjs.concat(onCacheSuccess$, onOptionSettled$).pipe(rxjs.toArray());
2523
- },
2524
- onSuccess: (data, variables2, context) => {
2525
- const onCacheSuccess$ = makeObservable(
2526
- () => {
2527
- var _a, _b;
2528
- return (_b = (_a = mutationCache.config).onSuccess) == null ? void 0 : _b.call(
2529
- _a,
2530
- data,
2531
- variables2,
2532
- context,
2533
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2534
- this
2535
- );
2536
- }
2537
- );
2538
- const onOptionSuccess$ = makeObservable(
2539
- () => {
2540
- var _a, _b;
2541
- return (_b = (_a = this.options).onSuccess) == null ? void 0 : _b.call(_a, data, variables2, context);
2542
- }
2543
- );
2544
- return rxjs.concat(onCacheSuccess$, onOptionSuccess$).pipe(rxjs.toArray());
2545
- }
2546
- },
2547
- state: this.state,
2548
- variables
2549
- }).pipe(rxjs.takeUntil(__privateGet(this, _cancelSubject)))
2550
- )
2551
- );
2552
- const stateChange$ = rxjs.merge(resetPendingState$, executionState$);
2553
- this.state$ = stateChange$.pipe(
2554
- rxjs.startWith(this.state),
2555
- rxjs.scan(
2556
- (acc, partialState) => ({
2557
- ...acc,
2558
- ...partialState
2559
- }),
2560
- this.state
2561
- ),
2562
- distinctUntilStateChanged,
2563
- rxjs.tap((value) => {
2564
- this.state = value;
2565
- }),
2566
- rxjs.shareReplay(1),
2567
- trackSubscriptions((count) => {
2568
- __privateGet(this, _observerCount).next(count);
2569
- })
2570
- );
2571
- }
2572
- get meta() {
2573
- return this.options.meta;
2574
- }
2575
- setOptions(options) {
2576
- this.options = { ...this.options, ...options };
2577
- }
2578
- /**
2579
- * @important
2580
- * The resulting observable will complete as soon as the mutation
2581
- * is over, unlike the state which can be re-subscribed later.
2582
- */
2583
- execute(variables) {
2584
- __privateGet(this, _executeSubject).next(variables);
2585
- __privateGet(this, _executeSubject).complete();
2586
- return this.state$.pipe(observeUntilFinished);
2587
- }
2588
- continue() {
2589
- return this.execute(this.state.variables);
2590
- }
2591
- /**
2592
- * Cancel if needed and finalize the mutation.
2593
- * The mutation will be garbage collected automatically
2594
- * when no more observers are listening
2595
- */
2596
- cancel() {
2597
- __privateGet(this, _cancelSubject).next();
2598
- __privateGet(this, _cancelSubject).complete();
2599
- }
2600
- }
2601
- _observerCount = new WeakMap();
2602
- _cancelSubject = new WeakMap();
2603
- _executeSubject = new WeakMap();
2604
- const createPredicateForFilters = ({
2605
- mutationKey,
2606
- status,
2607
- predicate,
2608
- exact = true
2609
- } = {}) => {
2610
- const finalPredicate = (mutation) => {
2611
- if (exact && mutationKey !== void 0 && mutation.options.mutationKey !== void 0 && !matchKey(mutation.options.mutationKey, mutationKey, { exact })) {
2612
- return false;
2613
- }
2614
- if (!exact && mutationKey !== void 0 && mutation.options.mutationKey !== void 0 && !matchKey(mutation.options.mutationKey, mutationKey, { exact })) {
2615
- return false;
2616
- }
2617
- if (status && mutation.state.status !== status) return false;
2618
- if (predicate) {
2619
- return predicate(mutation);
2620
- }
2621
- return true;
2622
- };
2623
- return finalPredicate;
2624
- };
2625
- class Store {
2626
- constructor() {
2627
- /**
2628
- * @important
2629
- * Query store. Could be turned into a map for more performance.
2630
- */
2631
- __publicField(this, "entriesSubject", new rxjs.BehaviorSubject([]));
2632
- __publicField(this, "changeSubject", new rxjs.Subject());
2633
- __publicField(this, "entries$", this.entriesSubject.pipe(rxjs.share()));
2634
- __publicField(this, "added$", this.changeSubject.pipe(
2635
- rxjs.filter(({ type }) => type === "added"),
2636
- rxjs.map(({ entity }) => entity),
2637
- rxjs.share()
2638
- ));
2639
- __publicField(this, "removed$", this.changeSubject.pipe(
2640
- rxjs.filter(({ type }) => type === "removed"),
2641
- rxjs.map(({ entity }) => entity),
2642
- rxjs.share()
2643
- ));
2644
- __publicField(this, "stateChange$", rxjs.merge(
2645
- this.entriesSubject.pipe(
2646
- rxjs.first(),
2647
- rxjs.mergeMap((entities) => rxjs.from(entities))
2648
- ),
2649
- this.added$
2650
- ).pipe(
2651
- rxjs.mergeMap(
2652
- (entity) => entity.state$.pipe(
2653
- rxjs.map(() => entity),
2654
- rxjs.takeUntil(
2655
- this.removed$.pipe(
2656
- rxjs.filter((removedMutation) => removedMutation === entity)
2657
- )
2658
- )
2659
- )
2660
- ),
2661
- rxjs.share()
2662
- ));
2663
- }
2664
- getValues() {
2665
- return this.entriesSubject.getValue();
2666
- }
2667
- remove(entity) {
2668
- this.entriesSubject.next(
2669
- this.entriesSubject.getValue().filter((toRemove) => entity !== toRemove)
2670
- );
2671
- this.changeSubject.next({ type: "removed", entity });
2672
- }
2673
- add(entity) {
2674
- this.entriesSubject.next([...this.entriesSubject.getValue(), entity]);
2675
- this.changeSubject.next({ type: "added", entity });
2676
- }
2677
- find(predicate) {
2678
- return this.entriesSubject.getValue().find(predicate);
2679
- }
2680
- }
2681
- class MutationCache {
2682
- constructor(config = {}) {
2683
- __privateAdd(this, _store, new Store());
2684
- this.config = config;
2685
- }
2686
- build(client, options, state) {
2687
- const mutation = new Mutation({
2688
- mutationCache: this,
2689
- options: client.defaultMutationOptions(options),
2690
- state
2691
- });
2692
- mutation.state$.pipe(
2693
- /**
2694
- * Once a mutation is finished and there are no more observers than us
2695
- * we start the process of cleaning it up based on gc settings
2696
- */
2697
- rxjs.filter(({ status }) => status === "success" || status === "error"),
2698
- rxjs.switchMap(
2699
- () => mutation.observerCount$.pipe(
2700
- rxjs.filter((count) => count <= 1),
2701
- rxjs.take(1)
2702
- )
2703
- ),
2704
- // defaults to 5mn
2705
- rxjs.switchMap(() => {
2706
- return rxjs.timer(mutation.options.gcTime ?? 5 * 60 * 1e3);
2707
- }),
2708
- rxjs.take(1)
2709
- ).subscribe({
2710
- complete: () => {
2711
- this.remove(mutation);
2712
- }
2713
- });
2714
- __privateGet(this, _store).add(mutation);
2715
- return mutation;
2716
- }
2717
- getAll() {
2718
- return this.findAll();
2719
- }
2720
- remove(mutationToRemove) {
2721
- const toRemove = __privateGet(this, _store).getValues().find((mutation) => {
2722
- return mutation === mutationToRemove;
2723
- });
2724
- toRemove == null ? void 0 : toRemove.cancel();
2725
- __privateGet(this, _store).remove(mutationToRemove);
2726
- }
2727
- find(filters) {
2728
- const defaultedFilters = { exact: true, ...filters };
2729
- const predicate = createPredicateForFilters(defaultedFilters);
2730
- return __privateGet(this, _store).getValues().find((mutation) => predicate(mutation));
2731
- }
2732
- findAll(filters = {}) {
2733
- const defaultedFilters = { exact: true, ...filters };
2734
- const predicate = createPredicateForFilters(defaultedFilters);
2735
- return __privateGet(this, _store).getValues().filter((mutation) => predicate(mutation)).map((mutation) => mutation);
2736
- }
2737
- observe() {
2738
- const value$ = __privateGet(this, _store).stateChange$.pipe(rxjs.startWith());
2739
- return value$;
2740
- }
2741
- /**
2742
- * @important
2743
- * ISO api react-query
2744
- */
2745
- subscribe(listener) {
2746
- const sub = rxjs.merge(
2747
- __privateGet(this, _store).added$.pipe(
2748
- rxjs.tap((mutation) => {
2749
- listener({
2750
- type: "added",
2751
- mutation
2752
- });
2753
- })
2754
- ),
2755
- __privateGet(this, _store).removed$.pipe(
2756
- rxjs.tap((mutation) => {
2757
- listener({
2758
- type: "removed",
2759
- mutation
2760
- });
2761
- })
2762
- ),
2763
- __privateGet(this, _store).stateChange$.pipe(
2764
- rxjs.tap((mutation) => {
2765
- listener({
2766
- type: "updated",
2767
- action: {
2768
- ...mutation.state,
2769
- type: "success"
2770
- },
2771
- mutation
2772
- });
2773
- })
2774
- )
2775
- ).subscribe();
2776
- return () => {
2777
- sub.unsubscribe();
2778
- };
2779
- }
2780
- resumePausedMutations() {
2781
- const pausedMutations = this.findAll({
2782
- predicate: (mutation) => mutation.state.isPaused
2783
- });
2784
- if (!pausedMutations.length) return rxjs.EMPTY;
2785
- const mutations$ = pausedMutations.map((mutation) => mutation.continue());
2786
- return rxjs.combineLatest(mutations$);
2787
- }
2788
- clear() {
2789
- this.getAll().forEach((mutation) => {
2790
- this.remove(mutation);
2791
- });
2792
- }
2793
- }
2794
- _store = new WeakMap();
2795
- function getDefaultState(options) {
2796
- const data = typeof options.initialData === "function" ? options.initialData() : options.initialData;
2797
- const hasData = typeof data !== "undefined";
2798
- const initialDataUpdatedAt = hasData ? typeof options.initialDataUpdatedAt === "function" ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;
2799
- return {
2800
- data,
2801
- dataUpdateCount: 0,
2802
- dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0,
2803
- error: null,
2804
- errorUpdateCount: 0,
2805
- errorUpdatedAt: 0,
2806
- fetchFailureCount: 0,
2807
- fetchFailureReason: null,
2808
- fetchMeta: null,
2809
- isInvalidated: false,
2810
- status: hasData ? "success" : "pending",
2811
- fetchStatus: "idle"
2812
- };
2813
- }
2814
- const delayUntilFocus = (source) => {
2815
- return rxjs.defer(() => {
2816
- if (!focusManager.isFocused()) {
2817
- return focusManager.focusRegained$.pipe(rxjs.mergeMap(() => source));
2818
- }
2819
- return source;
2820
- });
2821
- };
2822
- const delayOnNetworkMode = (options) => {
2823
- let attempts = 0;
2824
- return (source) => {
2825
- const runWhenOnline$ = onlineManager.backToOnline$.pipe(
2826
- rxjs.mergeMap(
2827
- () => rxjs.merge(
2828
- rxjs.of({ fetchStatus: "fetching" }),
2829
- source
2830
- )
2831
- )
2832
- );
2833
- return rxjs.defer(() => {
2834
- attempts++;
2835
- if (!onlineManager.isOnline() && options.networkMode === "offlineFirst" && attempts > 1) {
2836
- return rxjs.merge(
2837
- rxjs.of({ fetchStatus: "paused" }),
2838
- runWhenOnline$
2839
- );
2840
- }
2841
- if (!onlineManager.isOnline() && options.networkMode !== "always" && options.networkMode !== "offlineFirst") {
2842
- return rxjs.merge(
2843
- rxjs.of({ fetchStatus: "paused" }),
2844
- runWhenOnline$
2845
- );
2846
- }
2847
- return source;
2848
- });
2849
- };
2850
- };
2851
- const completeFnIfNotMoreObservers = (observers$) => (source) => {
2852
- const hasDataSubject = new rxjs.Subject();
2853
- const hasDataAndNoObservers$ = hasDataSubject.pipe(
2854
- rxjs.first(),
2855
- /**
2856
- * Since we set hasDataSubject synchronously, we need to wait
2857
- * for the next tick to make sure observable chain received this data at least
2858
- */
2859
- rxjs.delay(1),
2860
- rxjs.mergeMap(() => observers$.pipe(rxjs.filter((value) => value === 0)))
2861
- );
2862
- return source.pipe(
2863
- rxjs.tap(() => {
2864
- hasDataSubject.next();
2865
- }),
2866
- rxjs.takeUntil(hasDataAndNoObservers$)
2867
- );
2868
- };
2869
- const executeQuery = (options) => {
2870
- const defaultFn = async () => await Promise.reject(new Error("No query found"));
2871
- if (process.env.NODE_ENV !== "production") {
2872
- if (options.queryFn === skipToken) {
2873
- console.error(
2874
- `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`
2875
- );
2876
- }
2877
- }
2878
- let fnIsComplete = false;
2879
- const queryFn = options.queryFn && options.queryFn !== skipToken ? options.queryFn : defaultFn;
2880
- const abortController = new AbortController();
2881
- const queryFnContext = {
2882
- meta: options.meta,
2883
- queryKey: options.queryKey
2884
- };
2885
- const addSignalProperty = (object) => {
2886
- Object.defineProperty(object, "signal", {
2887
- enumerable: true,
2888
- get: () => {
2889
- options.onSignalConsumed();
2890
- return abortController.signal;
2891
- }
2892
- });
2893
- };
2894
- addSignalProperty(queryFnContext);
2895
- const fn$ = typeof queryFn === "function" ? (
2896
- // eslint-disable-next-line @typescript-eslint/promise-function-async
2897
- makeObservable(
2898
- () => queryFn(queryFnContext)
2899
- )
2900
- ) : queryFn;
2901
- const execution$ = fn$.pipe(
2902
- completeFnIfNotMoreObservers(options.observers$),
2903
- rxjs.tap({
2904
- complete: () => {
2905
- fnIsComplete = true;
2906
- }
2907
- }),
2908
- rxjs.map(
2909
- (data) => ({
2910
- data
2911
- })
2912
- ),
2913
- // takeUntil(hasDataAndNoObservers$),
2914
- delayOnNetworkMode(options),
2915
- retryBackoff({
2916
- ...options,
2917
- retryAfter: () => rxjs.of(true).pipe(delayUntilFocus),
2918
- catchError: (attempt, error) => rxjs.of({
2919
- status: "error",
2920
- fetchStatus: "idle",
2921
- fetchFailureCount: attempt,
2922
- fetchFailureReason: error,
2923
- error
2924
- }),
2925
- caughtError: (attempt, error) => (
2926
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
2927
- rxjs.of({
2928
- fetchFailureCount: attempt,
2929
- fetchFailureReason: error
2930
- })
2931
- )
2932
- }),
2933
- rxjs.mergeMap((state) => {
2934
- if (!("data" in state)) return rxjs.of(state);
2935
- return rxjs.of({
2936
- ...state,
2937
- status: "success",
2938
- fetchStatus: "idle",
2939
- fetchFailureCount: 0,
2940
- fetchFailureReason: null,
2941
- dataUpdatedAt: (/* @__PURE__ */ new Date()).getTime()
2942
- }).pipe(
2943
- /**
2944
- * Because we don't know yet whether the fn is an observable or a promise we wait
2945
- * for next tick and check if the function has been complete. This prevent having
2946
- * two dispatch for promise where we would have extra "fetching" & "idle" dispatch
2947
- *
2948
- * @important
2949
- * Another reason why this delay is necessary is to pass RQ tests. This is because
2950
- * their flow expect a sequence of results to sometimes happens in a specific
2951
- * way. If we have non promise function, we have results faster than what RQ expect
2952
- * due to this library architecture and some variables are impossible to determine
2953
- * correctly (eg: isFetchedAfterMount). There is nothing wrong, it's just a way to
2954
- * force any function as promise (or more specifically to return in next tick).
2955
- *
2956
- * There is in theory no problem associated to that.
2957
- */
2958
- rxjs.delay(1),
2959
- rxjs.map(
2960
- (state2) => fnIsComplete ? state2 : { ...state2, fetchStatus: "fetching" }
2961
- )
2962
- );
2963
- }),
2964
- /**
2965
- * When the fn complete we can release the fetch status, if it was already released
2966
- * before shallow compare will not update the state, otherwise it's our chance to catch
2967
- * the end of observable fn.
2968
- */
2969
- rxjs.endWith({ fetchStatus: "idle" }),
2970
- rxjs.share()
2971
- );
2972
- const initialResult$ = rxjs.of({
2973
- status: "pending",
2974
- fetchStatus: onlineManager.isOnline() ? "fetching" : "paused"
2975
- });
2976
- return {
2977
- state$: rxjs.merge(
2978
- initialResult$,
2979
- execution$
2980
- // emitOnComplete$
2981
- ).pipe(rxjs.share()),
2982
- abortController
2983
- };
2984
- };
2985
- class CancelledError {
2986
- constructor(options) {
2987
- __publicField(this, "revert");
2988
- __publicField(this, "silent");
2989
- this.revert = options == null ? void 0 : options.revert;
2990
- this.silent = options == null ? void 0 : options.silent;
2991
- }
2992
- }
2993
- const resetStyle = { backgroundColor: "transparent", color: "inherit" };
2994
- function createLogger(env) {
2995
- const _logger = {
2996
- namespaces: [
2997
- {
2998
- name: "@reactjrx",
2999
- style: { backgroundColor: "#d02f4e", color: "white" }
3000
- }
3001
- ],
3002
- namespace(name, style) {
3003
- const logger = createLogger();
3004
- logger.namespaces.push({
3005
- name,
3006
- style: style ?? resetStyle
3007
- });
3008
- return logger;
3009
- },
3010
- printNamespaces() {
3011
- return {
3012
- namespaces: _logger.namespaces.map(({ name }) => `%c ${name} %c`).join(" "),
3013
- styles: _logger.namespaces.reduce((acc, { style }) => {
3014
- acc.push(
3015
- `background-color: ${style.backgroundColor}; color: ${style.color};`
3016
- );
3017
- acc.push("background-color: transparent; color: inherit;");
3018
- return acc;
3019
- }, [])
3020
- };
3021
- },
3022
- print(method, ...message) {
3023
- return _logger;
3024
- },
3025
- printWithoutNamespace(method, ...message) {
3026
- return _logger;
3027
- },
3028
- log(...message) {
3029
- return _logger.print("log", ...message);
3030
- },
3031
- warn(...message) {
3032
- return _logger.print("warn", ...message);
3033
- },
3034
- error(...message) {
3035
- return _logger.print("error", ...message);
3036
- },
3037
- group(...message) {
3038
- return _logger.print("group", ...message);
3039
- },
3040
- groupEnd() {
3041
- return _logger;
3042
- }
3043
- };
3044
- return _logger;
3045
- }
3046
- const Logger = createLogger();
3047
- class Query {
3048
- constructor(config) {
3049
- __publicField(this, "queryKey");
3050
- __publicField(this, "queryHash");
3051
- __publicField(this, "gcTime");
3052
- __publicField(this, "options");
3053
- __privateAdd(this, _defaultOptions);
3054
- __privateAdd(this, _initialState);
3055
- __publicField(this, "state");
3056
- // @todo to share with mutation
3057
- __publicField(this, "executeSubject", new rxjs.Subject());
3058
- __publicField(this, "cancelSubject", new rxjs.Subject());
3059
- __publicField(this, "setDataSubject", new rxjs.Subject());
3060
- __publicField(this, "invalidatedSubject", new rxjs.Subject());
3061
- __publicField(this, "resetSubject", new rxjs.Subject());
3062
- __publicField(this, "destroySubject", new rxjs.Subject());
3063
- __publicField(this, "observersSubject", new rxjs.BehaviorSubject([]));
3064
- __publicField(this, "abortSignalConsumed", false);
3065
- __publicField(this, "observerCount$", this.observersSubject.asObservable().pipe(rxjs.map((observers) => observers.length)));
3066
- __publicField(this, "observers$", this.observersSubject.asObservable());
3067
- __publicField(this, "state$");
3068
- __privateSet(this, _defaultOptions, config.defaultOptions);
3069
- this.options = this.setOptions(config.options);
3070
- this.queryKey = config.queryKey;
3071
- this.queryHash = config.queryHash;
3072
- __privateSet(this, _initialState, config.state ?? getDefaultState(this.options));
3073
- this.state = __privateGet(this, _initialState);
3074
- this.gcTime = this.updateGcTime(this.options.gcTime);
3075
- this.state$ = rxjs.merge(
3076
- this.resetSubject.pipe(
3077
- rxjs.map(() => ({ command: "reset", state: __privateGet(this, _initialState) }))
3078
- ),
3079
- this.invalidatedSubject.pipe(
3080
- rxjs.filter(() => !this.state.isInvalidated),
3081
- rxjs.map(() => ({
3082
- command: "invalidate",
3083
- state: {
3084
- isInvalidated: true
3085
- }
3086
- }))
3087
- ),
3088
- this.cancelSubject.pipe(
3089
- rxjs.filter(() => {
3090
- const isQueryOnError = this.state.error && this.state.status === "error";
3091
- return !isQueryOnError;
3092
- }),
3093
- rxjs.map((options) => ({
3094
- command: "cancel",
3095
- state: {
3096
- status: (options == null ? void 0 : options.revert) ? this.state.status : "error",
3097
- fetchStatus: "idle",
3098
- error: new CancelledError(options)
3099
- }
3100
- }))
3101
- ),
3102
- this.executeSubject.pipe(
3103
- rxjs.mergeMap(() => {
3104
- let noMoreObserversActive = false;
3105
- const cancelFromNewRefetch$ = this.executeSubject.pipe(
3106
- // should not be needed since the fetch return current promise
3107
- // in case we don't cancel
3108
- rxjs.filter((options) => (options == null ? void 0 : options.cancelRefetch) !== false)
3109
- );
3110
- const detectNoMoreObserversActive$ = this.observers$.pipe(
3111
- rxjs.pairwise(),
3112
- rxjs.tap(([prevObservers, currentObservers]) => {
3113
- if (currentObservers.length === 0 && prevObservers.length > 0) {
3114
- noMoreObserversActive = true;
3115
- } else {
3116
- noMoreObserversActive = false;
3117
- }
3118
- }),
3119
- rxjs.ignoreElements()
3120
- );
3121
- const { state$: functionExecution$, abortController } = executeQuery({
3122
- ...this.options,
3123
- observers$: this.observerCount$,
3124
- queryKey: this.queryKey,
3125
- retry: (attempt, error) => {
3126
- const retry = this.options.retry ?? true;
3127
- if (typeof retry === "function") return retry(attempt, error);
3128
- if (typeof retry === "boolean") return retry;
3129
- return attempt < retry;
3130
- },
3131
- retryAfterDelay: () => {
3132
- if (noMoreObserversActive) return false;
3133
- return true;
3134
- },
3135
- onSignalConsumed: () => {
3136
- this.abortSignalConsumed = true;
3137
- }
3138
- });
3139
- const executionAbortedFromSignal$ = this.observerCount$.pipe(
3140
- rxjs.filter((count) => count === 0 && this.abortSignalConsumed),
3141
- rxjs.tap(() => {
3142
- this.cancelSubject.next({ revert: true });
3143
- })
3144
- );
3145
- const cancelExecution$ = rxjs.merge(
3146
- this.cancelSubject,
3147
- cancelFromNewRefetch$,
3148
- this.resetSubject,
3149
- executionAbortedFromSignal$
3150
- ).pipe(
3151
- rxjs.tap(() => {
3152
- if (this.abortSignalConsumed) {
3153
- abortController.abort();
3154
- }
3155
- })
3156
- );
3157
- return rxjs.merge(functionExecution$, detectNoMoreObserversActive$).pipe(
3158
- rxjs.map((state) => ({
3159
- command: "execute",
3160
- state
3161
- })),
3162
- rxjs.takeUntil(cancelExecution$)
3163
- );
3164
- })
3165
- ),
3166
- this.setDataSubject.pipe(
3167
- rxjs.map(({ data, options }) => ({
3168
- command: "setData",
3169
- state: {
3170
- status: "success",
3171
- data,
3172
- dataUpdatedAt: (options == null ? void 0 : options.updatedAt) !== void 0 ? options.updatedAt : (/* @__PURE__ */ new Date()).getTime()
3173
- }
3174
- }))
3175
- )
3176
- ).pipe(
3177
- reduceState({
3178
- initialState: this.state,
3179
- getOptions: () => this.options,
3180
- getState: () => this.state
3181
- }),
3182
- rxjs.startWith(__privateGet(this, _initialState)),
3183
- rxjs.distinctUntilChanged(shallowEqual),
3184
- rxjs.tap((state) => {
3185
- this.state = state;
3186
- }),
3187
- rxjs.catchError((e) => {
3188
- Logger.error(e);
3189
- throw e;
3190
- }),
3191
- rxjs.takeUntil(this.destroySubject),
3192
- rxjs.shareReplay({ bufferSize: 1, refCount: false })
3193
- );
3194
- }
3195
- setOptions(options) {
3196
- this.options = { ...__privateGet(this, _defaultOptions), ...options };
3197
- this.updateGcTime(this.options.gcTime);
3198
- return this.options;
3199
- }
3200
- get meta() {
3201
- return this.options.meta;
3202
- }
3203
- get success$() {
3204
- return this.state$.pipe(
3205
- rxjs.map(({ data, status }) => ({ data, status })),
3206
- rxjs.distinctUntilChanged(shallowEqual),
3207
- rxjs.filter(({ status }) => status === "success")
3208
- );
3209
- }
3210
- get error$() {
3211
- return this.state$.pipe(
3212
- rxjs.map(({ error, status }) => ({ error, status })),
3213
- rxjs.distinctUntilChanged(shallowEqual),
3214
- rxjs.filter(({ status }) => status === "error")
3215
- );
3216
- }
3217
- get settled$() {
3218
- return this.state$.pipe(
3219
- rxjs.map(({ status }) => ({ status })),
3220
- rxjs.distinctUntilChanged(shallowEqual),
3221
- rxjs.filter(({ status }) => status === "success" || status === "error")
3222
- );
3223
- }
3224
- observe(observer) {
3225
- const state$ = this.state$.pipe(
3226
- rxjs.tap({
3227
- subscribe: () => {
3228
- this.observersSubject.next([
3229
- observer,
3230
- ...this.observersSubject.getValue()
3231
- ]);
3232
- },
3233
- unsubscribe: () => {
3234
- this.observersSubject.next(
3235
- this.observersSubject.getValue().filter((item) => item !== observer)
3236
- );
3237
- }
3238
- })
3239
- );
3240
- return state$;
3241
- }
3242
- getObserversCount() {
3243
- return this.observersSubject.getValue().length;
3244
- }
3245
- // @todo this can be shared with mutation
3246
- updateGcTime(newGcTime) {
3247
- this.gcTime = Math.max(
3248
- this.gcTime || 0,
3249
- newGcTime ?? (isServer ? Infinity : 5 * 60 * 1e3)
3250
- );
3251
- return this.gcTime;
3252
- }
3253
- isActive() {
3254
- return this.observersSubject.getValue().some((observer) => observer.options.enabled !== false);
3255
- }
3256
- isDisabled() {
3257
- return this.getObserversCount() > 0 && !this.isActive();
3258
- }
3259
- isStale() {
3260
- return this.state.isInvalidated || !this.state.dataUpdatedAt || this.observersSubject.getValue().some((observer) => observer.getCurrentResult().isStale);
3261
- }
3262
- isStaleByTime(staleTime = 0) {
3263
- return this.state.isInvalidated || !this.state.dataUpdatedAt || !timeUntilStale(this.state.dataUpdatedAt, staleTime);
3264
- }
3265
- async getFetchResultAsPromise() {
3266
- return await new Promise((resolve, reject) => {
3267
- this.state$.pipe(takeUntilFinished, rxjs.last()).subscribe({
3268
- error: reject,
3269
- next: (data) => {
3270
- if (data.error) {
3271
- reject(data.error);
3272
- } else {
3273
- resolve(data.data);
3274
- }
3275
- }
3276
- });
3277
- });
3278
- }
3279
- async fetch(options, fetchOptions) {
3280
- const { cancelRefetch } = fetchOptions ?? {};
3281
- if (this.state.fetchStatus !== "idle") {
3282
- const shouldCancelRequest = !!this.state.dataUpdatedAt && cancelRefetch;
3283
- if (!shouldCancelRequest) {
3284
- return await this.getFetchResultAsPromise();
3285
- }
3286
- }
3287
- if (options) {
3288
- this.setOptions(options);
3289
- }
3290
- this.executeSubject.next(fetchOptions);
3291
- return await this.getFetchResultAsPromise();
3292
- }
3293
- setData(newData, options) {
3294
- const data = replaceData(this.state.data, newData, this.options);
3295
- this.setDataSubject.next({ data, options });
3296
- return data;
3297
- }
3298
- invalidate() {
3299
- this.invalidatedSubject.next();
3300
- }
3301
- async cancel(options) {
3302
- this.cancelSubject.next(options);
3303
- }
3304
- // @todo merge with mutation
3305
- destroy() {
3306
- this.destroySubject.next();
3307
- this.destroySubject.complete();
3308
- this.executeSubject.complete();
3309
- }
3310
- // @todo merge with mutation
3311
- reset() {
3312
- this.resetSubject.next();
3313
- }
3314
- }
3315
- _defaultOptions = new WeakMap();
3316
- _initialState = new WeakMap();
3317
- class QueryCache {
3318
- // protected mountSubscriptions: Subscription[]
3319
- constructor(config = {}) {
3320
- // readonly #queries: QueryStore = new Map<string, Query>()
3321
- __privateAdd(this, _notifySubject, new rxjs.Subject());
3322
- __privateAdd(this, _store2, new Store());
3323
- this.config = config;
3324
- }
3325
- mount() {
3326
- }
3327
- unmount() {
3328
- }
3329
- notify(event) {
3330
- __privateGet(this, _notifySubject).next(event);
3331
- }
3332
- observeIsFetching(filters) {
3333
- const value$ = __privateGet(this, _store2).stateChange$.pipe(
3334
- // we force a first result
3335
- rxjs.startWith(),
3336
- rxjs.map(() => {
3337
- const filteredEntities = this.findAll({
3338
- ...filters,
3339
- fetchStatus: "fetching"
3340
- });
3341
- return filteredEntities.length;
3342
- }),
3343
- rxjs.distinctUntilChanged()
3344
- );
3345
- return value$;
3346
- }
3347
- getAll() {
3348
- return [...__privateGet(this, _store2).getValues()];
3349
- }
3350
- findAll(filters = {}) {
3351
- const queries = this.getAll();
3352
- return Object.keys(filters).length > 0 ? queries.filter((query) => matchQuery(filters, query)) : queries;
3353
- }
3354
- build(client, options, state) {
3355
- const queryKey = options.queryKey ?? [nanoid()];
3356
- const queryHash = options.queryHash ?? hashQueryKeyByOptions(queryKey, options);
3357
- let query = this.get(queryHash);
3358
- if (!query) {
3359
- query = new Query({
3360
- cache: this,
3361
- queryKey,
3362
- queryHash,
3363
- options: client.defaultQueryOptions(options),
3364
- state,
3365
- defaultOptions: client.getQueryDefaults(queryKey)
3366
- });
3367
- this.add(query);
3368
- }
3369
- return query;
3370
- }
3371
- add(query) {
3372
- if (!__privateGet(this, _store2).find((entity) => entity.queryHash === query.queryHash)) {
3373
- __privateGet(this, _store2).add(query);
3374
- const noMoreObservers$ = query.observerCount$.pipe(
3375
- rxjs.filter((count) => count < 1),
3376
- rxjs.take(1)
3377
- );
3378
- query.success$.subscribe(() => {
3379
- var _a, _b;
3380
- (_b = (_a = this.config).onSuccess) == null ? void 0 : _b.call(_a, query.state.data, query);
3381
- });
3382
- query.error$.subscribe(() => {
3383
- var _a, _b;
3384
- (_b = (_a = this.config).onError) == null ? void 0 : _b.call(_a, query.state.error, query);
3385
- });
3386
- query.settled$.subscribe(() => {
3387
- var _a, _b;
3388
- (_b = (_a = this.config).onSettled) == null ? void 0 : _b.call(
3389
- _a,
3390
- query.state.data,
3391
- query.state.error,
3392
- query
3393
- );
3394
- });
3395
- query.state$.pipe(
3396
- /**
3397
- * Once a mutation is finished and there are no more observers than us
3398
- * we start the process of cleaning it up based on gc settings
3399
- */
3400
- isQueryFinished,
3401
- rxjs.switchMap((isFinished) => {
3402
- return !isFinished ? rxjs.NEVER : noMoreObservers$.pipe(
3403
- // defaults to 5mn
3404
- rxjs.switchMap(() => {
3405
- if (query.gcTime === Infinity) return rxjs.NEVER;
3406
- setTimeout(rxjs.noop, query.gcTime);
3407
- return rxjs.timer(query.gcTime);
3408
- })
3409
- );
3410
- }),
3411
- rxjs.take(1)
3412
- ).subscribe({
3413
- complete: () => {
3414
- this.remove(query);
3415
- }
3416
- });
3417
- }
3418
- }
3419
- get(queryHash) {
3420
- return __privateGet(this, _store2).find((query) => query.queryHash === queryHash);
3421
- }
3422
- find(filters) {
3423
- const defaultedFilters = { exact: true, ...filters };
3424
- return this.getAll().find(
3425
- (query) => matchQuery(defaultedFilters, query)
3426
- );
3427
- }
3428
- subscribe(fn) {
3429
- const sub = rxjs.merge(
3430
- __privateGet(this, _notifySubject).pipe(rxjs.tap(fn))
3431
- // this.#store.added$.pipe(
3432
- // mergeMap((query) => {
3433
- // fn({
3434
- // query,
3435
- // type: "added"
3436
- // })
3437
- // return query.observers$.pipe(
3438
- // tap((observer) => {
3439
- // fn({
3440
- // type: "observerAdded",
3441
- // observer: observer as unknown as QueryObserver<
3442
- // any,
3443
- // any,
3444
- // any,
3445
- // any,
3446
- // any
3447
- // >,
3448
- // query
3449
- // })
3450
- // })
3451
- // )
3452
- // })
3453
- // )
3454
- ).subscribe();
3455
- return () => {
3456
- sub.unsubscribe();
3457
- };
3458
- }
3459
- remove(query) {
3460
- const queryInMap = __privateGet(this, _store2).find((entity) => entity === query);
3461
- if (queryInMap) {
3462
- query.destroy();
3463
- if (queryInMap === query) {
3464
- __privateGet(this, _store2).remove(query);
3465
- }
3466
- }
3467
- }
3468
- clear() {
3469
- }
3470
- }
3471
- _notifySubject = new WeakMap();
3472
- _store2 = new WeakMap();
3473
- class QueryClient {
3474
- // #destroy = () => {}
3475
- constructor({
3476
- mutationCache,
3477
- queryCache,
3478
- defaultOptions
3479
- } = {}) {
3480
- __privateAdd(this, _mutationCache);
3481
- __privateAdd(this, _queryCache);
3482
- __privateAdd(this, _mutationDefaults, /* @__PURE__ */ new Map());
3483
- __privateAdd(this, _queryDefaults, /* @__PURE__ */ new Map());
3484
- __privateAdd(this, _defaultOptions2);
3485
- __privateSet(this, _mutationCache, mutationCache ?? new MutationCache());
3486
- __privateSet(this, _queryCache, queryCache ?? new QueryCache());
3487
- __privateSet(this, _defaultOptions2, defaultOptions ?? {});
3488
- }
3489
- mount() {
3490
- }
3491
- unmount() {
3492
- }
3493
- getMutationCache() {
3494
- return __privateGet(this, _mutationCache);
3495
- }
3496
- getQueryCache() {
3497
- return __privateGet(this, _queryCache);
3498
- }
3499
- defaultMutationOptions(options) {
3500
- return {
3501
- ...__privateGet(this, _defaultOptions2).mutations,
3502
- ...(options == null ? void 0 : options.mutationKey) && this.getMutationDefaults(options.mutationKey),
3503
- ...options
3504
- };
3505
- }
3506
- defaultQueryOptions(options) {
3507
- if (options._defaulted) {
3508
- return options;
3509
- }
3510
- const defaultedOptions = {
3511
- ...__privateGet(this, _defaultOptions2).queries,
3512
- ...this.getQueryDefaults(options.queryKey),
3513
- ...options,
3514
- _defaulted: true
3515
- };
3516
- if (!defaultedOptions.queryHash) {
3517
- defaultedOptions.queryHash = hashQueryKeyByOptions(
3518
- defaultedOptions.queryKey,
3519
- defaultedOptions
3520
- );
3521
- }
3522
- if (defaultedOptions.refetchOnReconnect === void 0) {
3523
- defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== "always";
3524
- }
3525
- if (defaultedOptions.throwOnError === void 0) {
3526
- defaultedOptions.throwOnError = !!defaultedOptions.suspense;
3527
- }
3528
- if (!defaultedOptions.networkMode && defaultedOptions.persister) {
3529
- defaultedOptions.networkMode = "offlineFirst";
3530
- }
3531
- if (defaultedOptions.enabled !== true && defaultedOptions.queryFn === skipToken) {
3532
- defaultedOptions.enabled = false;
3533
- }
3534
- return defaultedOptions;
3535
- }
3536
- async fetchQuery(options) {
3537
- const defaultedOptions = this.defaultQueryOptions(options);
3538
- if (typeof defaultedOptions.retry === "undefined") {
3539
- defaultedOptions.retry = false;
3540
- }
3541
- const query = __privateGet(this, _queryCache).build(this, defaultedOptions);
3542
- return query.isStaleByTime(defaultedOptions.staleTime) ? await query.fetch(defaultedOptions) : await Promise.resolve(query.state.data);
3543
- }
3544
- async prefetchQuery(options) {
3545
- await this.fetchQuery(options).then(rxjs.noop).catch(rxjs.noop);
3546
- }
3547
- async resetQueries(filters, options) {
3548
- const queryCache = __privateGet(this, _queryCache);
3549
- const refetchFilters = {
3550
- type: "active",
3551
- ...filters
3552
- };
3553
- queryCache.findAll(filters).forEach((query) => {
3554
- query.reset();
3555
- });
3556
- await this.refetchQueries(refetchFilters, options);
3557
- }
3558
- async refetchQueries(filters = {}, options) {
3559
- const fetchOptions = {
3560
- ...options,
3561
- cancelRefetch: (options == null ? void 0 : options.cancelRefetch) ?? true
3562
- };
3563
- const promises = __privateGet(this, _queryCache).findAll(filters).filter((query) => !query.isDisabled()).map(async (query) => {
3564
- let promise = query.fetch(void 0, fetchOptions);
3565
- if (!fetchOptions.throwOnError) {
3566
- promise = promise.catch(rxjs.noop);
3567
- }
3568
- return query.state.fetchStatus === "paused" ? void 0 : await promise;
3569
- });
3570
- await Promise.all(promises).then(rxjs.noop);
3571
- }
3572
- getQueryData(queryKey) {
3573
- var _a;
3574
- const options = this.defaultQueryOptions({ queryKey });
3575
- return (_a = __privateGet(this, _queryCache).get(options.queryHash)) == null ? void 0 : _a.state.data;
3576
- }
3577
- setQueryData(queryKey, updater, options) {
3578
- const defaultedOptions = this.defaultQueryOptions({ queryKey });
3579
- const query = __privateGet(this, _queryCache).get(
3580
- defaultedOptions.queryHash
3581
- );
3582
- const prevData = query == null ? void 0 : query.state.data;
3583
- const data = functionalUpdate(updater, prevData);
3584
- if (data === void 0) {
3585
- return void 0;
3586
- }
3587
- return __privateGet(this, _queryCache).build(this, defaultedOptions).setData(data, { ...options, manual: true });
3588
- }
3589
- getMutationDefaults(mutationKey) {
3590
- const defaults = [...__privateGet(this, _mutationDefaults).values()];
3591
- let result = {};
3592
- defaults.forEach((queryDefault) => {
3593
- if (matchKey(mutationKey, queryDefault.mutationKey)) {
3594
- result = { ...result, ...queryDefault.defaultOptions };
3595
- }
3596
- });
3597
- return result;
3598
- }
3599
- getQueryState(queryKey) {
3600
- var _a;
3601
- return (_a = __privateGet(this, _queryCache).find({ queryKey })) == null ? void 0 : _a.state;
3602
- }
3603
- setMutationDefaults(mutationKey, options) {
3604
- __privateGet(this, _mutationDefaults).set(hashKey(mutationKey), {
3605
- mutationKey,
3606
- defaultOptions: options
3607
- });
3608
- }
3609
- setQueryDefaults(queryKey, options) {
3610
- __privateGet(this, _queryDefaults).set(hashKey(queryKey), {
3611
- queryKey,
3612
- defaultOptions: options
3613
- });
3614
- }
3615
- getQueryDefaults(queryKey) {
3616
- const defaults = [...__privateGet(this, _queryDefaults).values()];
3617
- let result = {};
3618
- defaults.forEach((queryDefault) => {
3619
- if (partialMatchKey(queryKey, queryDefault.queryKey)) {
3620
- result = { ...result, ...queryDefault.defaultOptions };
3621
- }
3622
- });
3623
- return result;
3624
- }
3625
- removeQueries(filters) {
3626
- const queryCache = __privateGet(this, _queryCache);
3627
- queryCache.findAll(filters).forEach((query) => {
3628
- queryCache.remove(query);
3629
- });
3630
- }
3631
- async cancelQueries(filters = {}, cancelOptions = {}) {
3632
- const defaultedCancelOptions = { revert: true, ...cancelOptions };
3633
- const promises = __privateGet(this, _queryCache).findAll(filters).map(async (query) => {
3634
- await query.cancel(defaultedCancelOptions);
3635
- });
3636
- await Promise.all(promises).then(rxjs.noop).catch(rxjs.noop);
3637
- }
3638
- async invalidateQueries(filters = {}, options = {}) {
3639
- __privateGet(this, _queryCache).findAll(filters).forEach((query) => {
3640
- query.invalidate();
3641
- });
3642
- if (filters.refetchType === "none") {
3643
- await Promise.resolve();
3644
- return;
3645
- }
3646
- const refetchFilters = {
3647
- ...filters,
3648
- type: filters.refetchType ?? filters.type ?? "active"
3649
- };
3650
- await this.refetchQueries(refetchFilters, options);
3651
- }
3652
- async resumePausedMutations() {
3653
- return await rxjs.lastValueFrom(__privateGet(this, _mutationCache).resumePausedMutations());
3654
- }
3655
- isFetching(filters) {
3656
- return __privateGet(this, _queryCache).findAll({ ...filters, fetchStatus: "fetching" }).length;
3657
- }
3658
- clear() {
3659
- __privateGet(this, _queryCache).clear();
3660
- __privateGet(this, _mutationCache).clear();
3661
- }
3662
- }
3663
- _mutationCache = new WeakMap();
3664
- _queryCache = new WeakMap();
3665
- _mutationDefaults = new WeakMap();
3666
- _queryDefaults = new WeakMap();
3667
- _defaultOptions2 = new WeakMap();
3668
- exports.Context = Context$1;
3669
- exports.MutationCache = MutationCache;
3670
- exports.QueryCache = QueryCache;
3671
- exports.QueryClient = QueryClient;
918
+ exports.Context = Context;
3672
919
  exports.QueryClient$ = QueryClient$;
3673
- exports.QueryClientProvider = QueryClientProvider;
3674
920
  exports.QueryClientProvider$ = QueryClientProvider$;
3675
921
  exports.SIGNAL_RESET = SIGNAL_RESET;
3676
922
  exports.arrayEqual = arrayEqual;
@@ -3686,19 +932,15 @@ exports.signal = signal;
3686
932
  exports.useBehaviorSubject = useBehaviorSubject;
3687
933
  exports.useContactMutation$ = useContactMutation$;
3688
934
  exports.useEffectOnce = useEffectOnce;
3689
- exports.useForeverQuery = useForeverQuery;
3690
935
  exports.useLiveBehaviorSubject = useLiveBehaviorSubject;
3691
936
  exports.useLiveRef = useLiveRef;
3692
937
  exports.useMount = useMount;
3693
- exports.useMutation = useMutation;
3694
938
  exports.useMutation$ = useMutation$;
3695
939
  exports.useObservableCallback = useObservableCallback;
3696
940
  exports.useObservableState = useObservableState;
3697
941
  exports.useObserve = useObserve;
3698
942
  exports.usePersistSignals = usePersistSignals;
3699
- exports.useQuery = useQuery;
3700
943
  exports.useQuery$ = useQuery$;
3701
- exports.useQueryClient = useQueryClient;
3702
944
  exports.useQueryClient$ = useQueryClient$;
3703
945
  exports.useSignal = useSignal;
3704
946
  exports.useSignalValue = useSignalValue;