reactjrx 1.62.0 → 1.67.3

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 (57) hide show
  1. package/dist/index.cjs +1 -2101
  2. package/dist/index.d.ts +2 -1
  3. package/dist/index.js +1641 -1801
  4. package/dist/lib/queries/client/cache/registerResultInCache.d.ts +1 -1
  5. package/dist/lib/queries/client/createClient.d.ts +20 -7
  6. package/dist/lib/queries/client/fetch/notifyQueryResult.d.ts +1 -1
  7. package/dist/lib/queries/client/fetch/queryFetch.d.ts +2 -2
  8. package/dist/lib/queries/client/mutations/cache/MutationCache.d.ts +35 -0
  9. package/dist/lib/queries/client/mutations/cache/mutationCache.test.d.ts +1 -0
  10. package/dist/lib/queries/client/mutations/cache/types.d.ts +68 -0
  11. package/dist/lib/queries/client/mutations/defaultMutationState.d.ts +2 -2
  12. package/dist/lib/queries/client/mutations/filters.d.ts +1 -1
  13. package/dist/lib/queries/client/mutations/mutation/Mutation.d.ts +36 -0
  14. package/dist/lib/queries/client/mutations/mutation/executeMutation.d.ts +6 -0
  15. package/dist/lib/queries/client/mutations/mutation/mutation.options.test.d.ts +1 -0
  16. package/dist/lib/queries/client/mutations/mutation/types.d.ts +51 -0
  17. package/dist/lib/queries/client/mutations/mutations.test.d.ts +1 -0
  18. package/dist/lib/queries/client/mutations/observers/MutationObserver.d.ts +42 -0
  19. package/dist/lib/queries/client/mutations/observers/mutationObserver.rq.test.d.ts +1 -0
  20. package/dist/lib/queries/client/mutations/observers/mutationObserver.test.d.ts +1 -0
  21. package/dist/lib/queries/client/mutations/observers/types.d.ts +65 -0
  22. package/dist/lib/queries/client/mutations/runner/MutationRunner.d.ts +17 -0
  23. package/dist/lib/queries/client/mutations/runner/mutationRunner.test.d.ts +1 -0
  24. package/dist/lib/queries/client/mutations/types.d.ts +7 -101
  25. package/dist/lib/queries/client/operators.d.ts +6 -2
  26. package/dist/lib/queries/client/refetch/client.d.ts +1 -1
  27. package/dist/lib/queries/client/store/createQueryStore.d.ts +1 -1
  28. package/dist/lib/queries/client/store/updateStoreWithNewQuery.d.ts +1 -1
  29. package/dist/lib/queries/client/tests/utils.d.ts +4 -0
  30. package/dist/lib/queries/client/triggers.d.ts +1 -1
  31. package/dist/lib/queries/client/types.d.ts +2 -1
  32. package/dist/lib/queries/client/utils/functionAsObservable.d.ts +2 -0
  33. package/dist/lib/queries/client/utils/wrapInPromise.d.ts +3 -0
  34. package/dist/lib/queries/react/Provider.d.ts +3 -71
  35. package/dist/lib/queries/react/mutations/types.d.ts +18 -0
  36. package/dist/lib/queries/react/mutations/useIsMutating.d.ts +1 -1
  37. package/dist/lib/queries/react/mutations/useMutation.d.ts +3 -19
  38. package/dist/lib/queries/react/mutations/useMutation.rq.test.d.ts +1 -0
  39. package/dist/lib/queries/react/mutations/useMutationState.d.ts +5 -3
  40. package/dist/lib/queries/react/{helpers.d.ts → queries/helpers.d.ts} +6 -5
  41. package/dist/lib/queries/react/{types.d.ts → queries/types.d.ts} +1 -1
  42. package/dist/lib/queries/react/queries/useQuery.d.ts +1 -1
  43. package/dist/lib/queries/react/triggers/activityTrigger.d.ts +1 -1
  44. package/dist/lib/queries/react/triggers/networkTrigger.d.ts +1 -1
  45. package/dist/lib/utils/{retryBackoff.d.ts → operators/retryBackoff.d.ts} +5 -3
  46. package/dist/lib/utils/operators/trackSubscriptions.d.ts +2 -0
  47. package/dist/tests/utils.d.ts +4 -1
  48. package/package.json +3 -1
  49. package/dist/lib/queries/client/mutations/Mutation.d.ts +0 -15
  50. package/dist/lib/queries/client/mutations/MutationClient.d.ts +0 -91
  51. package/dist/lib/queries/client/mutations/MutationResultObserver.d.ts +0 -32
  52. package/dist/lib/queries/client/mutations/createMutationRunner.d.ts +0 -15
  53. package/dist/lib/queries/client/mutations/operators.d.ts +0 -3
  54. package/dist/lib/utils/trackSubscriptions.d.ts +0 -2
  55. /package/dist/lib/queries/{react → client}/keys/nanoid.d.ts +0 -0
  56. /package/dist/lib/utils/{emitToSubject.d.ts → operators/emitToSubject.d.ts} +0 -0
  57. /package/dist/lib/utils/{shareLatest.d.ts → operators/shareLatest.d.ts} +0 -0
package/dist/index.js CHANGED
@@ -1,642 +1,670 @@
1
- var __defProp = Object.defineProperty;
2
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
- var __publicField = (obj, key, value) => {
4
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
- return value;
1
+ var ze = Object.defineProperty;
2
+ var Je = (t, e, r) => e in t ? ze(t, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : t[e] = r;
3
+ var y = (t, e, r) => (Je(t, typeof e != "symbol" ? e + "" : e, r), r), We = (t, e, r) => {
4
+ if (!e.has(t))
5
+ throw TypeError("Cannot " + r);
6
6
  };
7
- import { useRef, useMemo, useCallback, useSyncExternalStore, useEffect, createContext, memo, useContext } from "react";
8
- import { distinctUntilChanged, tap, finalize, catchError, EMPTY, Subject, identity, BehaviorSubject, map, of, zip, merge, throttleTime, asyncScheduler, switchMap, from, defer, iif, timer, throwError, fromEvent, filter, skip, withLatestFrom, scan, retry, shareReplay, endWith, delay, take, takeUntil, share, startWith, pairwise, mergeMap, NEVER, combineLatest, ReplaySubject, concatMap as concatMap$1, takeWhile } from "rxjs";
9
- import { retryWhen, concatMap, tap as tap$1 } from "rxjs/operators";
10
- import { jsxs, jsx } from "react/jsx-runtime";
11
- const useLiveRef = (value) => {
12
- const ref = useRef(value);
13
- useMemo(() => {
14
- ref.current = value;
15
- }, [value]);
16
- return ref;
7
+ var k = (t, e, r) => (We(t, e, "read from private field"), r ? r.call(t) : e.get(t)), de = (t, e, r) => {
8
+ if (e.has(t))
9
+ throw TypeError("Cannot add the same private member more than once");
10
+ e instanceof WeakSet ? e.add(t) : e.set(t, r);
17
11
  };
18
- function primitiveEqual(objA, objB) {
19
- if (typeof objA === "string" && objA === objB)
20
- return true;
21
- if (typeof objA === "number" && objA === objB)
22
- return true;
23
- if (typeof objA === "boolean" && objA === objB)
24
- return true;
25
- if (typeof objA === "symbol" && objA === objB)
26
- return true;
27
- if (typeof objA === "bigint" && objA === objB)
28
- return true;
29
- if (typeof objA === "undefined" && objA === objB)
30
- return true;
31
- if (objA === null && objA === objB)
32
- return true;
33
- return false;
12
+ import { useRef as H, useMemo as ye, useCallback as Y, useSyncExternalStore as Ye, useEffect as K, createContext as Ge, memo as He, useContext as De, useState as Xe } from "react";
13
+ import { distinctUntilChanged as C, tap as x, finalize as ae, catchError as j, EMPTY as T, Subject as F, identity as le, BehaviorSubject as I, map as p, of as S, zip as Ze, merge as E, throttleTime as Ve, asyncScheduler as qe, switchMap as w, from as re, defer as ne, throwError as Ce, iif as Me, timer as se, Observable as Te, filter as $, mergeMap as _, takeUntil as P, skip as B, last as ge, scan as pe, shareReplay as $e, concatMap as Be, fromEvent as me, withLatestFrom as D, retry as et, endWith as tt, delay as rt, take as be, share as J, startWith as Ie, pairwise as ce, NEVER as Qe, combineLatest as Fe, takeWhile as ve, concat as ie, toArray as ue, lastValueFrom as nt } from "rxjs";
14
+ import { catchError as Re, retryWhen as st, concatMap as it, tap as ut } from "rxjs/operators";
15
+ import { jsxs as ct, jsx as ot } from "react/jsx-runtime";
16
+ const U = (t) => {
17
+ const e = H(t);
18
+ return ye(() => {
19
+ e.current = t;
20
+ }, [t]), e;
21
+ };
22
+ function at(t, e) {
23
+ return typeof t == "string" && t === e || typeof t == "number" && t === e || typeof t == "boolean" && t === e || typeof t == "symbol" && t === e || typeof t == "bigint" && t === e || typeof t > "u" && t === e || t === null && t === e;
34
24
  }
35
- function useObserve(source$, unsafeOptions, unsafeDeps) {
36
- const options = unsafeOptions != null && !Array.isArray(unsafeOptions) ? unsafeOptions : {
25
+ function fe(t, e, r) {
26
+ const n = e != null && !Array.isArray(e) ? e : {
37
27
  defaultValue: void 0,
38
28
  key: "",
39
- unsubscribeOnUnmount: true
40
- };
41
- const deps = unsafeDeps == null && Array.isArray(unsafeOptions) ? unsafeOptions : typeof source$ === "function" ? unsafeDeps ?? [] : [source$];
42
- const valueRef = useRef(
43
- "getValue" in source$ && typeof source$.getValue === "function" ? source$.getValue() : options.defaultValue
44
- );
45
- const sourceRef = useLiveRef(source$);
46
- const optionsRef = useLiveRef(options);
47
- const subscribe = useCallback(
48
- (next) => {
49
- const source = sourceRef.current;
50
- const makeObservable = typeof source === "function" ? source : () => source;
51
- const sub = makeObservable().pipe(
29
+ unsubscribeOnUnmount: !0
30
+ }, s = r == null && Array.isArray(e) ? e : typeof t == "function" ? r ?? [] : [t], i = H(
31
+ "getValue" in t && typeof t.getValue == "function" ? t.getValue() : n.defaultValue
32
+ ), u = U(t), l = U(n), f = Y(
33
+ (g) => {
34
+ const a = u.current, o = (typeof a == "function" ? a : () => a)().pipe(
52
35
  /**
53
36
  * @important
54
37
  * We only check primitives because underlying subscription might
55
38
  * be using objects and keeping same reference but pushing new
56
39
  * properties values
57
40
  */
58
- distinctUntilChanged(primitiveEqual),
59
- tap((value) => {
60
- valueRef.current = value;
41
+ C(at),
42
+ x((m) => {
43
+ i.current = m;
61
44
  }),
62
- finalize(next),
63
- catchError((error) => {
64
- console.error(error);
65
- valueRef.current = void 0;
66
- return EMPTY;
67
- })
68
- ).subscribe(next);
45
+ ae(g),
46
+ j((m) => (console.error(m), i.current = void 0, T))
47
+ ).subscribe(g);
69
48
  return () => {
70
- if (optionsRef.current.unsubscribeOnUnmount === false)
71
- return;
72
- sub.unsubscribe();
49
+ l.current.unsubscribeOnUnmount !== !1 && o.unsubscribe();
73
50
  };
74
51
  },
75
- [...deps]
76
- );
77
- const getSnapshot = useCallback(() => {
78
- return valueRef.current;
79
- }, []);
80
- const result = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
81
- return result;
52
+ // eslint-disable-next-line react-hooks/exhaustive-deps
53
+ [...s]
54
+ ), d = Y(() => i.current, []);
55
+ return Ye(f, d, d);
82
56
  }
83
- function useSubscribe(source, deps = []) {
84
- const sourceRef = useLiveRef(source);
85
- const sourceAsObservable = typeof source === "function" ? void 0 : source;
86
- useEffect(() => {
87
- const source2 = sourceRef.current;
88
- const makeObservable = typeof source2 === "function" ? source2 : () => source2;
89
- const sub = makeObservable().pipe(
90
- catchError((error) => {
91
- console.error(
92
- "Uncaught error at useSubscribe. Please consider adding a catchError or other handling."
93
- );
94
- console.error(error);
95
- return EMPTY;
96
- })
57
+ function Se(t, e = []) {
58
+ const r = U(t), n = typeof t == "function" ? void 0 : t;
59
+ K(() => {
60
+ const s = r.current, u = (typeof s == "function" ? s : () => s)().pipe(
61
+ j((l) => (console.error(
62
+ "Uncaught error at useSubscribe. Please consider adding a catchError or other handling."
63
+ ), console.error(l), T))
97
64
  ).subscribe();
98
65
  return () => {
99
- sub.unsubscribe();
66
+ u.unsubscribe();
100
67
  };
101
- }, [...deps, sourceAsObservable]);
68
+ }, [
69
+ // eslint-disable-next-line react-hooks/exhaustive-deps
70
+ ...e,
71
+ n,
72
+ r
73
+ ]);
102
74
  }
103
- const useConstant = (fn) => {
104
- const ref = useRef();
105
- if (!ref.current) {
106
- ref.current = fn();
107
- }
108
- useEffect(() => {
109
- if (process.env.NODE_ENV === "development")
110
- ;
111
- }, []);
112
- return ref;
113
- };
114
- const useSubject = ({
115
- onBeforeComplete,
116
- completeOnUnmount = true
75
+ const we = (t) => {
76
+ const e = H();
77
+ return e.current || (e.current = t()), K(() => {
78
+ process.env.NODE_ENV;
79
+ }, []), e;
80
+ }, Ee = ({
81
+ onBeforeComplete: t,
82
+ completeOnUnmount: e = !0
117
83
  } = {}) => {
118
- const subject = useConstant(() => new Subject());
119
- const completed = useRef(false);
120
- const onBeforeCompleteRef = useLiveRef(onBeforeComplete);
121
- const completeOnUnmountRef = useLiveRef(completeOnUnmount);
122
- useEffect(() => {
123
- if (completed.current) {
124
- subject.current = new Subject();
125
- completed.current = false;
84
+ const r = we(() => new F()), n = H(!1), s = U(t), i = U(e);
85
+ return K(() => (n.current && (r.current = new F(), n.current = !1), () => {
86
+ if (!i.current) {
87
+ n.current = !0;
88
+ return;
126
89
  }
127
- return () => {
128
- if (!completeOnUnmountRef.current) {
129
- completed.current = true;
130
- return;
131
- }
132
- if (!completed.current) {
133
- if (onBeforeCompleteRef.current != null)
134
- onBeforeCompleteRef.current();
135
- subject.current.complete();
136
- completed.current = true;
137
- }
138
- };
139
- }, []);
140
- return subject;
90
+ n.current || (s.current != null && s.current(), r.current.complete(), n.current = !0);
91
+ }), [i, s, r]), r;
92
+ }, ar = (t, e) => {
93
+ const r = Ee();
94
+ return Se(() => t(r.current), [r, ...e]), [Y((s) => {
95
+ r.current.next(s);
96
+ }, [r]), r];
141
97
  };
142
- const useObserveCallback = (callback, deps) => {
143
- const trigger$ = useSubject();
144
- useSubscribe(() => callback(trigger$.current), [trigger$, ...deps]);
145
- const trigger2 = useCallback((arg) => {
146
- trigger$.current.next(arg);
147
- }, []);
148
- return [trigger2, trigger$];
149
- };
150
- function trigger(mapper = identity) {
151
- const subject = new Subject();
98
+ function lr(t = le) {
99
+ const e = new F();
152
100
  return [
153
- subject.asObservable(),
154
- (...args) => {
155
- subject.next(mapper(...args));
101
+ e.asObservable(),
102
+ (...r) => {
103
+ e.next(t(...r));
156
104
  }
157
105
  ];
158
106
  }
159
- const useBehaviorSubject = (state) => {
160
- const subject = useConstant(() => new BehaviorSubject(state));
161
- const completed = useRef(false);
162
- useEffect(() => {
163
- if (completed.current) {
164
- subject.current = new BehaviorSubject(state);
165
- completed.current = false;
166
- }
167
- return () => {
168
- if (!completed.current) {
169
- subject.current.complete();
170
- completed.current = true;
107
+ const lt = (t) => {
108
+ const e = we(() => new I(t)), r = H(!1), n = H(t);
109
+ return K(() => (r.current && (e.current = new I(n.current), r.current = !1), () => {
110
+ r.current || (e.current.complete(), r.current = !0);
111
+ }), [e]), e;
112
+ }, pt = Symbol("SIGNAL_RESET");
113
+ function pr(t) {
114
+ const { default: e } = t ?? {}, r = new I(e);
115
+ return {
116
+ setValue: (i) => {
117
+ if (typeof i == "function") {
118
+ const u = i(r.getValue());
119
+ if (u === r.getValue())
120
+ return;
121
+ r.next(u);
122
+ return;
171
123
  }
172
- };
173
- }, []);
174
- return subject;
175
- };
176
- const SIGNAL_RESET = Symbol("SIGNAL_RESET");
177
- function signal(config) {
178
- const { default: defaultValue2 } = config ?? {};
179
- const subject = new BehaviorSubject(defaultValue2);
180
- const setValue = (arg) => {
181
- if (typeof arg === "function") {
182
- const change = arg(subject.getValue());
183
- if (change === subject.getValue())
124
+ if (i === pt) {
125
+ r.next(e ?? void 0);
184
126
  return;
185
- subject.next(change);
186
- return;
187
- }
188
- if (arg === SIGNAL_RESET) {
189
- subject.next(defaultValue2 ?? void 0);
190
- return;
191
- }
192
- subject.next(arg);
193
- };
194
- const getValue = () => subject.getValue();
195
- return {
196
- setValue,
197
- getValue,
198
- config,
199
- subject
127
+ }
128
+ r.next(i);
129
+ },
130
+ getValue: () => r.getValue(),
131
+ config: t,
132
+ subject: r
200
133
  };
201
134
  }
202
- function useSignalValue(signal2, selector) {
203
- const selectorOrDefault = selector ?? ((v) => v);
204
- return useObserve(
205
- () => signal2.subject.pipe(
206
- map((value) => selectorOrDefault(value)),
207
- distinctUntilChanged()
135
+ function fr(t, e) {
136
+ const r = e ?? ((n) => n);
137
+ return fe(
138
+ () => t.subject.pipe(
139
+ p((n) => r(n)),
140
+ C()
208
141
  ),
209
142
  {
210
- defaultValue: selectorOrDefault(signal2.getValue())
143
+ defaultValue: r(t.getValue())
211
144
  },
212
145
  []
213
146
  );
214
147
  }
215
- const normalizeStore = (store) => {
216
- if (!store || typeof store !== "object") {
217
- return void 0;
218
- }
219
- return store;
220
- };
221
- const createSharedStoreAdapter = ({
222
- adapter,
223
- key
148
+ const xe = (t) => {
149
+ if (!(!t || typeof t != "object"))
150
+ return t;
151
+ }, dr = ({
152
+ adapter: t,
153
+ key: e
224
154
  }) => ({
225
- getItem: async (itemKey) => {
226
- const unsafeStore = await adapter.getItem(key);
227
- const store = normalizeStore(unsafeStore) ?? {};
228
- if (itemKey in store) {
229
- return store[itemKey];
230
- }
231
- return void 0;
155
+ getItem: async (r) => {
156
+ const n = await t.getItem(e), s = xe(n) ?? {};
157
+ if (r in s)
158
+ return s[r];
232
159
  },
233
- setItem: async (itemKey, value) => {
234
- const unsafeStore = await adapter.getItem(key);
235
- const store = normalizeStore(unsafeStore) ?? {};
236
- await adapter.setItem(key, { ...store, [itemKey]: value });
160
+ setItem: async (r, n) => {
161
+ const s = await t.getItem(e), i = xe(s) ?? {};
162
+ await t.setItem(e, { ...i, [r]: n });
237
163
  }
238
- });
239
- const createLocalforageAdapter = (forage) => ({
240
- getItem: async (key) => {
241
- const serializedValue = await forage.getItem(key);
242
- if (!serializedValue)
243
- return void 0;
244
- return JSON.parse(serializedValue);
164
+ }), hr = (t) => ({
165
+ getItem: async (e) => {
166
+ const r = await t.getItem(e);
167
+ if (r)
168
+ return JSON.parse(r);
245
169
  },
246
- setItem: async (key, value) => {
247
- await forage.setItem(key, JSON.stringify(value));
170
+ setItem: async (e, r) => {
171
+ await t.setItem(e, JSON.stringify(r));
248
172
  }
249
- });
250
- const createLocalStorageAdapter = (forage) => ({
251
- getItem: async (key) => {
252
- const serializedValue = forage.getItem(key);
253
- if (!serializedValue)
254
- return void 0;
255
- return JSON.parse(serializedValue);
173
+ }), ft = (t) => ({
174
+ getItem: async (e) => {
175
+ const r = t.getItem(e);
176
+ if (r)
177
+ return JSON.parse(r);
256
178
  },
257
- setItem: async (key, value) => {
258
- forage.setItem(key, JSON.stringify(value));
259
- }
260
- });
261
- const IDENTIFIER_PERSISTANCE_KEY = "__reactjrx";
262
- const getNormalizedPersistanceValue = (unknownValue) => {
263
- if (typeof unknownValue === "object" && unknownValue !== null && IDENTIFIER_PERSISTANCE_KEY in unknownValue && unknownValue[IDENTIFIER_PERSISTANCE_KEY] === IDENTIFIER_PERSISTANCE_KEY) {
264
- return unknownValue;
179
+ setItem: async (e, r) => {
180
+ t.setItem(e, JSON.stringify(r));
265
181
  }
266
- return void 0;
267
- };
268
- const persistValue = async ({
269
- adapter,
270
- signal: signal2,
271
- version
182
+ }), Z = "__reactjrx", dt = (t) => {
183
+ if (typeof t == "object" && t !== null && Z in t && t[Z] === Z)
184
+ return t;
185
+ }, ht = async ({
186
+ adapter: t,
187
+ signal: e,
188
+ version: r
272
189
  }) => {
273
- const state = signal2.getValue();
274
- const value = {
275
- value: state,
276
- [IDENTIFIER_PERSISTANCE_KEY]: IDENTIFIER_PERSISTANCE_KEY,
277
- migrationVersion: version
190
+ const s = {
191
+ value: e.getValue(),
192
+ [Z]: Z,
193
+ migrationVersion: r
278
194
  };
279
- await adapter.setItem(signal2.config.key, value);
280
- };
281
- const hydrateValueToSignal = ({
282
- adapter,
283
- version,
284
- signal: signal2
285
- }) => {
286
- return from(adapter.getItem(signal2.config.key)).pipe(
287
- switchMap((value) => {
288
- const normalizedValue = getNormalizedPersistanceValue(value);
289
- if (!normalizedValue)
290
- return of(value);
291
- if (normalizedValue.migrationVersion !== void 0 && version > normalizedValue.migrationVersion) {
292
- return of(value);
293
- }
294
- signal2.setValue(value.value);
295
- return of(value);
296
- })
297
- );
298
- };
299
- const usePersistSignals = ({
300
- entries = [],
301
- onReady,
302
- adapter = createLocalStorageAdapter(localStorage)
195
+ await t.setItem(e.config.key, s);
196
+ }, gt = ({
197
+ adapter: t,
198
+ version: e,
199
+ signal: r
200
+ }) => re(t.getItem(r.config.key)).pipe(
201
+ w((n) => {
202
+ const s = dt(n);
203
+ return s ? s.migrationVersion !== void 0 && e > s.migrationVersion ? S(n) : (r.setValue(n.value), S(n)) : S(n);
204
+ })
205
+ ), gr = ({
206
+ entries: t = [],
207
+ onReady: e,
208
+ adapter: r = ft(localStorage)
303
209
  }) => {
304
- const entriesRef = useLiveRef(entries);
305
- const onReadyRef = useLiveRef(onReady);
306
- const adapterRef = useLiveRef(adapter);
307
- const isHydrated = useObserve(
210
+ const n = U(t), s = U(e), i = U(r), u = fe(
308
211
  () => {
309
- const entries2 = entriesRef.current;
310
- const stream = entries2.length === 0 ? of(true) : zip(
311
- ...entries2.map(
312
- ({ signal: signal2, version }) => hydrateValueToSignal({
313
- adapter: adapterRef.current,
314
- signal: signal2,
315
- version
212
+ const l = n.current;
213
+ return (l.length === 0 ? S(!0) : Ze(
214
+ ...l.map(
215
+ ({ signal: d, version: h }) => gt({
216
+ adapter: i.current,
217
+ signal: d,
218
+ version: h
316
219
  })
317
220
  )
318
- ).pipe(map(() => true));
319
- return stream.pipe(
320
- tap(() => {
321
- if (onReadyRef.current != null)
322
- onReadyRef.current();
221
+ ).pipe(p(() => !0))).pipe(
222
+ x(() => {
223
+ s.current != null && s.current();
323
224
  }),
324
- catchError((error) => {
325
- console.error("Unable to hydrate", error);
326
- return EMPTY;
327
- })
225
+ j((d) => (console.error("Unable to hydrate", d), T))
328
226
  );
329
227
  },
330
- { defaultValue: false },
228
+ { defaultValue: !1 },
331
229
  []
332
230
  );
333
- useSubscribe(() => {
334
- return !isHydrated ? EMPTY : merge(
335
- ...entriesRef.current.map(
336
- ({ signal: signal2, version }) => signal2.subject.pipe(
337
- throttleTime(500, asyncScheduler, {
338
- trailing: true
339
- }),
340
- switchMap(
341
- () => from(
342
- persistValue({ adapter: adapterRef.current, signal: signal2, version })
343
- )
231
+ return Se(() => u ? E(
232
+ ...n.current.map(
233
+ ({ signal: l, version: f }) => l.subject.pipe(
234
+ Ve(500, qe, {
235
+ trailing: !0
236
+ }),
237
+ w(
238
+ () => re(
239
+ ht({ adapter: i.current, signal: l, version: f })
344
240
  )
345
241
  )
346
242
  )
347
- );
348
- }, [isHydrated, adapterRef]);
349
- return { isHydrated };
350
- };
351
- const useUnmountObservable = () => {
352
- const subject = useSubject({
243
+ )
244
+ ) : T, [u, i]), { isHydrated: u };
245
+ }, mr = () => {
246
+ const t = Ee({
353
247
  onBeforeComplete: () => {
354
- subject.current.next();
248
+ t.current.next();
355
249
  }
356
250
  });
357
- return subject;
251
+ return t;
358
252
  };
359
- function getDelay(backoffDelay, maxInterval) {
360
- return Math.min(backoffDelay, maxInterval);
253
+ function mt(t, e) {
254
+ return Math.min(t, e);
361
255
  }
362
- function exponentialBackoffDelay(iteration, initialInterval) {
363
- return Math.pow(2, iteration) * initialInterval;
256
+ function bt(t, e) {
257
+ return Math.pow(2, t) * e;
364
258
  }
365
- function retryBackoff(config) {
259
+ function yt(t) {
366
260
  const {
367
- initialInterval,
368
- maxRetries = Infinity,
369
- maxInterval = Infinity,
370
- shouldRetry = () => true,
371
- resetOnSuccess = false,
372
- backoffDelay = exponentialBackoffDelay
373
- } = typeof config === "number" ? { initialInterval: config } : config;
374
- return (source) => defer(() => {
375
- let index = 0;
376
- return source.pipe(
377
- retryWhen((errors) => {
378
- return errors.pipe(
379
- concatMap((error) => {
380
- const attempt = index++;
381
- return iif(
382
- () => attempt < maxRetries && shouldRetry(attempt, error),
383
- timer(
384
- getDelay(backoffDelay(attempt, initialInterval), maxInterval)
385
- ),
386
- throwError(error)
387
- );
388
- })
261
+ initialInterval: e,
262
+ maxRetries: r = 1 / 0,
263
+ maxInterval: n = 1 / 0,
264
+ shouldRetry: s = () => !0,
265
+ resetOnSuccess: i = !1,
266
+ backoffDelay: u = bt
267
+ } = t;
268
+ return (l) => ne(() => {
269
+ let f = 0;
270
+ const d = (h, g) => h < r && s(h, g);
271
+ return l.pipe(
272
+ Re((h) => {
273
+ var a;
274
+ if (f++, !d(f - 1, h))
275
+ throw h;
276
+ const g = (a = t.caughtError) == null ? void 0 : a.call(t, f, h);
277
+ if (!g)
278
+ throw h;
279
+ return E(
280
+ g,
281
+ Ce(() => h)
389
282
  );
390
283
  }),
391
- tap$1(() => {
392
- if (resetOnSuccess) {
393
- index = 0;
394
- }
284
+ st((h) => h.pipe(
285
+ it((g) => {
286
+ const a = f - 1;
287
+ return Me(
288
+ () => d(a, g),
289
+ se(
290
+ mt(u(a, e), n)
291
+ ),
292
+ Ce(() => g)
293
+ );
294
+ })
295
+ )),
296
+ Re((h) => {
297
+ if (t.catchError)
298
+ return t.catchError(f, h);
299
+ throw h;
300
+ }),
301
+ ut(() => {
302
+ i && (f = 0);
395
303
  })
396
304
  );
397
305
  });
398
306
  }
399
- const Context = createContext({
307
+ const _e = Ge({
400
308
  client: null
401
- });
402
- const ClientEffect = ({
403
- client
404
- }) => {
405
- useEffect(() => {
406
- const destroy = client.start();
407
- return () => {
408
- destroy();
409
- };
410
- }, [client]);
411
- return null;
412
- };
413
- const QueryClientProvider = memo(
414
- ({ children, client }) => {
415
- const value = useMemo(() => ({ client: client.client }), [client]);
416
- return /* @__PURE__ */ jsxs(Context.Provider, { value, children: [
417
- /* @__PURE__ */ jsx(ClientEffect, { client: value.client }),
418
- children
309
+ }), $t = ({ client: t }) => (K(() => {
310
+ const e = t.mount();
311
+ return () => {
312
+ e();
313
+ };
314
+ }, [t]), null), br = He(
315
+ ({ children: t, client: e }) => {
316
+ const r = ye(() => ({ client: e }), [e]);
317
+ return /* @__PURE__ */ ct(_e.Provider, { value: r, children: [
318
+ /* @__PURE__ */ ot($t, { client: r.client }),
319
+ t
419
320
  ] });
420
321
  }
421
- );
422
- const useQueryClient = ({ unsafe = false } = {}) => {
423
- const context = useContext(Context);
424
- if (!unsafe && context.client === null) {
322
+ ), Pe = ({
323
+ unsafe: t = !1
324
+ } = {}) => {
325
+ const e = De(_e);
326
+ if (!t && e.client === null)
425
327
  throw new Error("You forgot to register the provider");
328
+ return e.client;
329
+ }, ee = (t) => Array.isArray(t) ? t.reduce((e, r, n) => n === t.length - 1 ? `${e}${ee(r)}]` : `${e}${ee(r)},`, "[") : t === void 0 ? "" : JSON.stringify(t, Object.keys(t).sort()), N = (t) => t.length === 0 ? "[]" : ee(t), Ne = (t = 21) => crypto.getRandomValues(new Uint8Array(t)).reduce((e, r) => (r &= 63, r < 36 ? e += r.toString(36) : r < 62 ? e += (r - 26).toString(36).toUpperCase() : r > 62 ? e += "-" : e += "_", e), ""), W = () => ({
330
+ context: void 0,
331
+ data: void 0,
332
+ error: null,
333
+ status: "idle",
334
+ submittedAt: 0,
335
+ variables: void 0,
336
+ failureCount: 0,
337
+ failureReason: null,
338
+ isPaused: !1
339
+ });
340
+ function G(t) {
341
+ return t != null;
342
+ }
343
+ function M(t, e) {
344
+ if (t == null || e === void 0 || typeof t != "object" || typeof e != "object")
345
+ return t === e;
346
+ if (t.constructor !== (e == null ? void 0 : e.constructor))
347
+ return !1;
348
+ const r = Object.keys(t), n = Object.keys(e);
349
+ if (r.length !== n.length)
350
+ return !1;
351
+ for (const s of r)
352
+ if (!e.hasOwnProperty(s) || t[s] !== e[s])
353
+ return !1;
354
+ return !0;
355
+ }
356
+ function ke(t) {
357
+ let e = 0;
358
+ return function(n) {
359
+ return new Te((s) => {
360
+ e++, t(e);
361
+ const i = n.subscribe(s);
362
+ return () => {
363
+ e--, t(e), i.unsubscribe();
364
+ };
365
+ });
366
+ };
367
+ }
368
+ class vt {
369
+ constructor({
370
+ __queryFinalizeHook: e
371
+ } = {}) {
372
+ y(this, "trigger$", new F());
373
+ y(this, "mapOperator$", new I("merge"));
374
+ y(this, "state$");
375
+ const r = new I(0), n = r.pipe(
376
+ $((i) => i === 0)
377
+ ), s = this.mapOperator$.pipe(
378
+ $(G),
379
+ C()
380
+ );
381
+ this.state$ = s.pipe(
382
+ _((i) => {
383
+ const u = i === "concat" ? Be : i === "switch" ? w : _, l = this.trigger$.pipe(
384
+ $(() => i === "merge")
385
+ );
386
+ return this.trigger$.pipe(
387
+ P(s.pipe(B(1))),
388
+ u(({ args: f, mutation: d }) => {
389
+ const h = ne(() => (d.execute(f), T)), g = d.observeTillFinished().pipe(
390
+ ge(),
391
+ _(() => d.state$),
392
+ P(this.trigger$)
393
+ ), a = d.observeTillFinished().pipe(B(1));
394
+ return E(a, g, h).pipe(
395
+ e ?? le,
396
+ P(E(n, l))
397
+ );
398
+ }),
399
+ pe((f, d) => ({
400
+ ...f,
401
+ ...d,
402
+ ...d.status === "pending" && {
403
+ data: d.data ?? f.data
404
+ },
405
+ ...d.status === "pending" && {
406
+ error: d.error ?? f.error
407
+ }
408
+ }), W()),
409
+ C(
410
+ ({ data: f, ...d }, { data: h, ...g }) => M(d, g) && M(f, h)
411
+ )
412
+ );
413
+ }),
414
+ $e({
415
+ refCount: !0,
416
+ bufferSize: 1
417
+ }),
418
+ ke((i) => {
419
+ r.next(i);
420
+ })
421
+ );
426
422
  }
427
- return context.client;
428
- };
429
- const serializeObject = (object) => {
430
- if (Array.isArray(object)) {
431
- return object.reduce((acc, value, index) => {
432
- if (index === object.length - 1)
433
- return `${acc}${serializeObject(value)}]`;
434
- return `${acc}${serializeObject(value)},`;
435
- }, "[");
423
+ trigger({ args: e, options: r, mutation: n }) {
424
+ r.mapOperator && this.mapOperator$.next(r.mapOperator), this.trigger$.next({ args: e, options: r, mutation: n });
436
425
  }
437
- if (object === void 0)
438
- return "";
439
- return JSON.stringify(object, Object.keys(object).sort());
440
- };
441
- const serializeKey = (key) => {
442
- if (key.length === 0)
443
- return "[]";
444
- return serializeObject(key);
445
- };
446
- const nanoid = (size = 21) => crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
447
- byte &= 63;
448
- if (byte < 36) {
449
- id += byte.toString(36);
450
- } else if (byte < 62) {
451
- id += (byte - 26).toString(36).toUpperCase();
452
- } else if (byte > 62) {
453
- id += "-";
454
- } else {
455
- id += "_";
426
+ }
427
+ var L;
428
+ class St {
429
+ constructor(e, r = {}, n) {
430
+ y(this, "numberOfObservers", 0);
431
+ y(this, "mutationRunner");
432
+ de(this, L, new I(void 0));
433
+ y(this, "observed$");
434
+ y(this, "result$");
435
+ y(this, "getObserverResultFromState", (e) => ({
436
+ ...W(),
437
+ ...e,
438
+ isSuccess: e.status === "success",
439
+ isPending: e.status === "pending",
440
+ isIdle: e.status === "idle",
441
+ isError: e.status === "error",
442
+ mutate: this.mutate,
443
+ reset: this.reset
444
+ }));
445
+ var s;
446
+ this.client = e, this.options = r, this.options.mutationKey = ((s = this.options) == null ? void 0 : s.mutationKey) ?? [Ne()], this.mutationRunner = n ?? new vt(this.options), this.mutate = this.mutate.bind(this), this.reset = this.reset.bind(this), this.result$ = this.mutationRunner.state$.pipe(
447
+ p((i) => ({
448
+ state: this.getObserverResultFromState(i),
449
+ options: {}
450
+ }))
451
+ ), k(this, L).pipe(
452
+ $(G),
453
+ _(
454
+ (i) => this.mutationRunner.state$.pipe(
455
+ P(i.mutation.observeTillFinished().pipe(ge()))
456
+ )
457
+ )
458
+ ).subscribe(), this.observed$ = k(this, L).pipe(
459
+ w(
460
+ (i) => (i == null ? void 0 : i.mutation.state$.pipe(
461
+ p((u) => ({
462
+ state: this.getObserverResultFromState(u),
463
+ options: i.options
464
+ }))
465
+ )) ?? T
466
+ ),
467
+ _(({ state: i, options: u }) => (i.status === "error" && (u != null && u.onError && (u == null || u.onError(
468
+ i.error,
469
+ i.variables,
470
+ i.context
471
+ )), u != null && u.onSettled && (u == null || u.onSettled(
472
+ i.data,
473
+ i.error,
474
+ i.variables,
475
+ i.context
476
+ ))), i.status === "success" && (u != null && u.onSuccess && (u == null || u.onSuccess(
477
+ i.data,
478
+ i.variables,
479
+ i.context
480
+ )), u != null && u.onSettled && (u == null || u.onSettled(
481
+ i.data,
482
+ i.error,
483
+ i.variables,
484
+ i.context
485
+ ))), T))
486
+ );
456
487
  }
457
- return id;
458
- }, "");
459
- function useMutation(options, queryClient) {
460
- const defaultQueryClient = useQueryClient({ unsafe: !!queryClient });
461
- const finalQueryClient = (queryClient == null ? void 0 : queryClient.client) ?? defaultQueryClient;
462
- const optionsRef = useLiveRef(options);
463
- const defaultKey = useConstant(() => [nanoid()]);
464
- const key = serializeKey(options.mutationKey ?? defaultKey.current);
465
- const observedMutation = useMemo(
466
- () => finalQueryClient.mutationClient.mutationResultObserver.observe({
467
- key
468
- }),
469
- [key]
470
- );
471
- const result = useObserve(observedMutation.result$) ?? observedMutation.lastValue;
472
- const mutate = useCallback(
473
- (mutationArgs) => {
474
- finalQueryClient.mutationClient.mutate({
475
- options: {
476
- ...optionsRef.current,
477
- mutationKey: optionsRef.current.mutationKey ?? defaultKey.current
478
- },
479
- args: mutationArgs
480
- });
481
- },
482
- [finalQueryClient, key]
483
- );
484
- const cancel = useCallback(() => {
485
- finalQueryClient.mutationClient.cancel({
486
- key: optionsRef.current.mutationKey ?? defaultKey.current
488
+ setOptions(e) {
489
+ this.options = this.client.defaultMutationOptions({
490
+ mutationKey: this.options.mutationKey,
491
+ ...e
492
+ }), this.options.mutationKey && this.client.getMutationCache().findAll({
493
+ exact: !0,
494
+ mutationKey: this.options.mutationKey
495
+ }).forEach((r) => {
496
+ r.setOptions(e);
497
+ });
498
+ }
499
+ observe() {
500
+ var n;
501
+ const e = this.getObserverResultFromState(
502
+ ((n = k(this, L).getValue()) == null ? void 0 : n.mutation.state) ?? W()
503
+ );
504
+ return { result$: E(this.observed$, this.result$).pipe(
505
+ p(({ state: s }) => (console.log({ state: s }), s))
506
+ ), lastValue: e };
507
+ }
508
+ /**
509
+ * @important
510
+ * Compliance react-query only
511
+ */
512
+ subscribe(e) {
513
+ const r = this.observe().result$.subscribe((n) => {
514
+ e(n);
487
515
  });
488
- }, [finalQueryClient]);
489
- useEffect(() => {
490
516
  return () => {
491
- if (optionsRef.current.cancelOnUnMount) {
492
- finalQueryClient.mutationClient.cancel({
493
- key: optionsRef.current.mutationKey ?? defaultKey.current
494
- });
495
- }
517
+ r.unsubscribe();
496
518
  };
497
- }, []);
498
- return { mutate, cancel, ...result };
499
- }
500
- const arrayEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
501
- function shallowEqual(objA, objB) {
502
- if (objA === null || objA === void 0 || objB === void 0) {
503
- return objA === objB;
504
519
  }
505
- if (typeof objA !== "object" || typeof objB !== "object") {
506
- return objA === objB;
520
+ async mutate(e, r = {}) {
521
+ const n = this.client.getMutationCache().build(this.client, this.options);
522
+ return k(this, L).next({ mutation: n, options: r }), this.mutationRunner.trigger({
523
+ args: e,
524
+ options: this.options,
525
+ mutation: n
526
+ }), await new Promise((s, i) => {
527
+ n.observeTillFinished().pipe(ge()).subscribe({
528
+ error: (u) => {
529
+ i(u);
530
+ },
531
+ next: (u) => {
532
+ u.error ? i(u.error) : s(u.data);
533
+ }
534
+ });
535
+ });
507
536
  }
508
- if (objA.constructor !== (objB == null ? void 0 : objB.constructor)) {
509
- return false;
537
+ getCurrentResult() {
538
+ var r;
539
+ const e = this.client.getMutationCache().find({ exact: !0, mutationKey: (r = this.options) == null ? void 0 : r.mutationKey });
540
+ return this.getObserverResultFromState(
541
+ (e == null ? void 0 : e.state) ?? W()
542
+ );
510
543
  }
511
- const keysA = Object.keys(objA);
512
- const keysB = Object.keys(objB);
513
- if (keysA.length !== keysB.length) {
514
- return false;
544
+ reset() {
545
+ var e;
546
+ (e = k(this, L).getValue()) == null || e.mutation.reset();
515
547
  }
516
- for (const key of keysA) {
517
- if (!objB.hasOwnProperty(key) || objA[key] !== objB[key]) {
518
- return false;
519
- }
548
+ cancel() {
549
+ var e;
550
+ console.log("cancel"), (e = k(this, L).getValue()) == null || e.mutation.destroy();
520
551
  }
521
- return true;
522
552
  }
523
- function isDefined(arg) {
524
- return arg !== null && arg !== void 0;
553
+ L = new WeakMap();
554
+ function wt() {
525
555
  }
526
- const createActivityTrigger = (params$) => {
527
- return params$.pipe(
528
- switchMap(({ options: { refetchOnWindowFocus = true } }) => {
529
- const shouldRunTrigger = typeof refetchOnWindowFocus === "function" ? refetchOnWindowFocus({}) : refetchOnWindowFocus;
530
- return shouldRunTrigger !== false ? merge(
531
- fromEvent(document, "visibilitychange").pipe(
532
- filter(() => !document.hidden),
533
- map(() => ({
534
- type: "refetch",
535
- ignoreStale: shouldRunTrigger === "always"
536
- }))
537
- ),
538
- fromEvent(window, "focus").pipe(
539
- map(() => ({
540
- type: "refetch",
541
- ignoreStale: shouldRunTrigger === "always"
542
- }))
543
- )
544
- ) : EMPTY;
545
- })
556
+ function yr(t, e) {
557
+ const r = Pe({ unsafe: !!e }), n = e ?? r, s = U(t), i = we(() => [Ne()]), u = N(t.mutationKey ?? i.current), [l] = Xe(
558
+ () => new St(
559
+ n,
560
+ t
561
+ )
546
562
  );
547
- };
548
- const createNetworkTrigger = (params$) => {
549
- return params$.pipe(
550
- switchMap(({ options: { refetchOnReconnect = true } }) => {
551
- const shouldRunTrigger = typeof refetchOnReconnect === "function" ? refetchOnReconnect({}) : refetchOnReconnect;
552
- return shouldRunTrigger !== false ? fromEvent(window, "online").pipe(
553
- map(() => ({
563
+ K(() => {
564
+ }, [l, t]);
565
+ const f = ye(() => l.observe(), [u, l]), d = fe(f.result$) ?? f.lastValue, h = Y(
566
+ (g, a) => {
567
+ l.mutate(g, a).catch(wt);
568
+ },
569
+ [l]
570
+ );
571
+ return K(() => () => {
572
+ s.current.cancelOnUnMount && l.cancel();
573
+ }, [l, s]), { ...d, mutate: h, mutateAsync: d.mutate };
574
+ }
575
+ const Le = (t, e) => t.length === e.length && t.every((r, n) => r === e[n]), Et = (t) => t.pipe(
576
+ w(({ options: { refetchOnWindowFocus: e = !0 } }) => {
577
+ const r = typeof e == "function" ? e({}) : e;
578
+ return r !== !1 ? E(
579
+ me(document, "visibilitychange").pipe(
580
+ $(() => !document.hidden),
581
+ p(() => ({
554
582
  type: "refetch",
555
- ignoreStale: shouldRunTrigger === "always"
583
+ ignoreStale: r === "always"
556
584
  }))
557
- ) : EMPTY;
558
- })
559
- );
560
- };
561
- const useQueryParams = ({
562
- queryKey,
563
- queryFn,
564
- ...options
585
+ ),
586
+ me(window, "focus").pipe(
587
+ p(() => ({
588
+ type: "refetch",
589
+ ignoreStale: r === "always"
590
+ }))
591
+ )
592
+ ) : T;
593
+ })
594
+ ), Ot = (t) => t.pipe(
595
+ w(({ options: { refetchOnReconnect: e = !0 } }) => {
596
+ const r = typeof e == "function" ? e({}) : e;
597
+ return r !== !1 ? me(window, "online").pipe(
598
+ p(() => ({
599
+ type: "refetch",
600
+ ignoreStale: r === "always"
601
+ }))
602
+ ) : T;
603
+ })
604
+ ), Ct = ({
605
+ queryKey: t,
606
+ queryFn: e,
607
+ ...r
565
608
  }) => {
566
- const params$ = useBehaviorSubject({ queryKey, options, queryFn });
567
- useEffect(() => {
568
- params$.current.next({
569
- queryKey,
570
- options,
571
- queryFn
609
+ const n = lt({ queryKey: t, options: r, queryFn: e });
610
+ return K(() => {
611
+ n.current.next({
612
+ queryKey: t,
613
+ options: r,
614
+ queryFn: e
572
615
  });
573
- }, [queryKey, options, queryFn]);
574
- return params$;
575
- };
576
- const defaultValue = {
616
+ }, [t, r, e, n]), n;
617
+ }, Rt = {
577
618
  data: void 0,
578
- isLoading: true,
619
+ isLoading: !0,
579
620
  error: void 0,
580
621
  status: "loading",
581
622
  fetchStatus: "idle"
582
623
  };
583
- function useQuery({
584
- queryKey,
585
- queryFn,
586
- ...options
624
+ function $r({
625
+ queryKey: t,
626
+ queryFn: e,
627
+ ...r
587
628
  }) {
588
- const internalRefresh$ = useSubject();
589
- const client = useQueryClient();
590
- const params$ = useQueryParams({ queryFn, queryKey, ...options });
591
- const result = useObserve(
629
+ const n = Ee(), s = Pe(), i = Ct({ queryFn: e, queryKey: t, ...r }), u = fe(
592
630
  () => {
593
- const key$ = params$.current.pipe(map(({ queryKey: queryKey2 }) => queryKey2 ?? []));
594
- const initialTrigger$ = of(null);
595
- const newKeyTrigger$ = key$.pipe(
596
- distinctUntilChanged(arrayEqual),
597
- skip(1)
598
- );
599
- const isQueryObject = (query) => !!query && typeof query !== "function";
600
- const newObservableObjectQuery$ = params$.current.pipe(
601
- map(({ queryFn: queryFn2 }) => queryFn2),
602
- filter(isQueryObject),
603
- distinctUntilChanged(shallowEqual),
604
- isQueryObject(params$.current.getValue().queryFn) ? skip(1) : identity
605
- );
606
- const fn$ = params$.current.pipe(
607
- map(({ queryFn: queryFn2 }) => queryFn2),
608
- filter(isDefined)
609
- );
610
- const options$ = params$.current.pipe(map(({ options: options2 }) => options2));
611
- const activityRefetch$ = createActivityTrigger(params$.current);
612
- const networkRefetch$ = createNetworkTrigger(params$.current);
613
- const newQueryTrigger$ = merge(
614
- initialTrigger$,
615
- newKeyTrigger$,
616
- newObservableObjectQuery$
617
- );
618
- const trigger$ = merge(
619
- internalRefresh$.current,
620
- merge(activityRefetch$, networkRefetch$).pipe(throttleTime(500))
631
+ const f = i.current.pipe(p(({ queryKey: v }) => v ?? [])), d = S(null), h = f.pipe(
632
+ C(Le),
633
+ B(1)
634
+ ), g = (v) => !!v && typeof v != "function", a = i.current.pipe(
635
+ p(({ queryFn: v }) => v),
636
+ $(g),
637
+ C(M),
638
+ g(i.current.getValue().queryFn) ? B(1) : le
639
+ ), c = i.current.pipe(
640
+ p(({ queryFn: v }) => v),
641
+ $(G)
642
+ ), o = i.current.pipe(p(({ options: v }) => v)), m = Et(i.current), R = Ot(i.current), b = E(
643
+ d,
644
+ h,
645
+ a
646
+ ), A = E(
647
+ n.current,
648
+ E(m, R).pipe(Ve(500))
621
649
  );
622
- return newQueryTrigger$.pipe(
623
- withLatestFrom(key$),
624
- switchMap(([, key]) => {
625
- const { result$ } = client.query({
626
- key,
627
- fn$,
628
- options$,
629
- trigger$
650
+ return b.pipe(
651
+ D(f),
652
+ w(([, v]) => {
653
+ const { result$: O } = s.client.query({
654
+ key: v,
655
+ fn$: c,
656
+ options$: o,
657
+ trigger$: A
630
658
  });
631
- return result$.pipe(
632
- scan(
633
- (previousValue, { data: currentData, ...currentValue }) => ({
659
+ return O.pipe(
660
+ pe(
661
+ (Q, { data: z, ...Oe }) => ({
634
662
  data: void 0,
635
- ...previousValue,
636
- ...currentValue,
637
- isLoading: currentValue.status === "loading",
638
- ...currentData && {
639
- data: currentData.result
663
+ ...Q,
664
+ ...Oe,
665
+ isLoading: Oe.status === "loading",
666
+ ...z && {
667
+ data: z.result
640
668
  }
641
669
  }),
642
670
  {}
@@ -656,53 +684,49 @@ function useQuery({
656
684
  },
657
685
  {
658
686
  defaultValue: {
659
- ...defaultValue,
660
- isLoading: params$.current.getValue().options.enabled !== false
687
+ ...Rt,
688
+ isLoading: i.current.getValue().options.enabled !== !1
661
689
  }
662
690
  },
663
- [client]
664
- );
665
- const refetch = useCallback(() => {
666
- internalRefresh$.current.next({ type: "refetch", ignoreStale: true });
667
- }, [client]);
668
- return { ...result, refetch };
691
+ [s]
692
+ ), l = Y(() => {
693
+ n.current.next({ type: "refetch", ignoreStale: !0 });
694
+ }, [n]);
695
+ return { ...u, refetch: l };
669
696
  }
670
- function useSubscribeEffect(source, unsafeOptions, deps = []) {
671
- const options = unsafeOptions != null && !Array.isArray(unsafeOptions) ? unsafeOptions : {};
672
- const retryOption = options.retry ?? true;
673
- const isSourceFn = typeof source === "function";
674
- const makeObservable = useCallback(
675
- isSourceFn ? source : () => source,
676
- isSourceFn ? deps : [source]
677
- );
678
- const enhancerMakeObservable = useCallback(
679
- () => makeObservable().pipe(
680
- catchError((error) => {
681
- console.error(error);
682
- throw error;
697
+ function vr(t, e, r = []) {
698
+ const s = (e != null && !Array.isArray(e) ? e : {}).retry ?? !0, i = typeof t == "function", u = Y(
699
+ i ? t : () => t,
700
+ i ? r : [t]
701
+ ), l = Y(
702
+ () => u().pipe(
703
+ j((f) => {
704
+ throw console.error(f), f;
683
705
  }),
684
- retryOption ? retry() : identity
706
+ s ? et() : le
685
707
  ),
686
- [makeObservable]
708
+ [u, s]
687
709
  );
688
- useSubscribe(enhancerMakeObservable, deps);
710
+ Se(l, r);
689
711
  }
690
- const retryOnError = (options) => retryBackoff({
691
- initialInterval: 100,
692
- ...typeof options.retry === "function" ? {
693
- shouldRetry: options.retry
712
+ const Ue = ({
713
+ retryDelay: t,
714
+ retry: e,
715
+ ...r
716
+ }) => yt({
717
+ initialInterval: typeof t == "number" ? t : 100,
718
+ ...typeof e == "function" ? {
719
+ shouldRetry: e
694
720
  } : {
695
- maxRetries: options.retry === false ? 0 : options.retry ?? 3
696
- }
697
- });
698
- const mergeResults$1 = (stream$) => stream$.pipe(
699
- scan(
700
- (acc, current) => {
701
- return {
702
- ...acc,
703
- ...current
704
- };
705
- },
721
+ maxRetries: e === !1 ? 0 : e ?? 0
722
+ },
723
+ ...r
724
+ }), xt = (t) => t.pipe(
725
+ pe(
726
+ (e, r) => ({
727
+ ...e,
728
+ ...r
729
+ }),
706
730
  {
707
731
  data: void 0,
708
732
  error: void 0,
@@ -710,347 +734,273 @@ const mergeResults$1 = (stream$) => stream$.pipe(
710
734
  status: "loading"
711
735
  }
712
736
  ),
713
- distinctUntilChanged(
714
- ({ data: prevData, ...prev }, { data: currData, ...curr }) => shallowEqual(prev, curr) && shallowEqual(prevData, currData)
737
+ C(
738
+ ({ data: e, ...r }, { data: n, ...s }) => M(r, s) && M(e, n)
715
739
  )
716
- );
717
- const resetStyle = { backgroundColor: "transparent", color: "inherit" };
718
- function createLogger(env) {
719
- const _logger = {
740
+ ), Vt = { backgroundColor: "transparent", color: "inherit" };
741
+ function Ae(t) {
742
+ const e = {
720
743
  namespaces: [
721
744
  {
722
745
  name: "@reactjrx",
723
746
  style: { backgroundColor: "#d02f4e", color: "white" }
724
747
  }
725
748
  ],
726
- namespace(name, style) {
727
- const logger2 = createLogger(env);
728
- logger2.namespaces.push({
729
- name,
730
- style: style ?? resetStyle
731
- });
732
- return logger2;
749
+ namespace(r, n) {
750
+ const s = Ae(t);
751
+ return s.namespaces.push({
752
+ name: r,
753
+ style: n ?? Vt
754
+ }), s;
733
755
  },
734
756
  printNamespaces() {
735
757
  return {
736
- namespaces: _logger.namespaces.map(({ name }) => `%c ${name} %c`).join(" "),
737
- styles: _logger.namespaces.reduce((acc, { style }) => {
738
- acc.push(
739
- `background-color: ${style.backgroundColor}; color: ${style.color};`
740
- );
741
- acc.push("background-color: transparent; color: inherit;");
742
- return acc;
743
- }, [])
758
+ namespaces: e.namespaces.map(({ name: r }) => `%c ${r} %c`).join(" "),
759
+ styles: e.namespaces.reduce((r, { style: n }) => (r.push(
760
+ `background-color: ${n.backgroundColor}; color: ${n.color};`
761
+ ), r.push("background-color: transparent; color: inherit;"), r), [])
744
762
  };
745
763
  },
746
- print(method, ...message) {
747
- if (env === "development") {
748
- const { namespaces, styles } = _logger.printNamespaces();
749
- console[method](namespaces, ...styles, ...message);
764
+ print(r, ...n) {
765
+ if (t === "development") {
766
+ const { namespaces: s, styles: i } = e.printNamespaces();
767
+ console[r](s, ...i, ...n);
750
768
  }
751
- return _logger;
769
+ return e;
752
770
  },
753
- printWithoutNamespace(method, ...message) {
754
- if (env === "development") {
755
- console[method](...message);
756
- }
757
- return _logger;
771
+ printWithoutNamespace(r, ...n) {
772
+ return t === "development" && console[r](...n), e;
758
773
  },
759
- log(...message) {
760
- return _logger.print("log", ...message);
774
+ log(...r) {
775
+ return e.print("log", ...r);
761
776
  },
762
- warn(...message) {
763
- return _logger.print("warn", ...message);
777
+ warn(...r) {
778
+ return e.print("warn", ...r);
764
779
  },
765
- error(...message) {
766
- return _logger.print("error", ...message);
780
+ error(...r) {
781
+ return e.print("error", ...r);
767
782
  },
768
- group(...message) {
769
- return _logger.print("group", ...message);
783
+ group(...r) {
784
+ return e.print("group", ...r);
770
785
  },
771
786
  groupEnd() {
772
- if (env === "development") {
773
- console.groupEnd();
774
- }
775
- return _logger;
787
+ return t === "development" && console.groupEnd(), e;
776
788
  }
777
789
  };
778
- return _logger;
790
+ return e;
779
791
  }
780
- const Logger = createLogger("production");
781
- const logger$3 = Logger.namespace("store");
782
- const createDebugger = (store$) => {
783
- return store$.pipe(
784
- map(
785
- (value) => [...value.keys()].reduce((acc, key) => {
786
- var _a;
787
- acc[key] = (_a = value.get(key)) == null ? void 0 : _a.getValue();
788
- return acc;
789
- }, {})
790
- ),
791
- distinctUntilChanged(shallowEqual)
792
- ).subscribe((value) => {
793
- logger$3.log("store", "update", value);
794
- });
795
- };
796
- const createQueryStore = () => {
797
- const store = /* @__PURE__ */ new Map();
798
- const store$ = new BehaviorSubject(store);
799
- const queryEventSubject = new Subject();
800
- const queryTriggerSubject = new Subject();
801
- const notify = () => {
802
- store$.next(store);
803
- };
804
- const setValue = (key, value) => {
805
- store.set(key, new BehaviorSubject(value));
806
- notify();
807
- };
808
- const getValue = (serializedKey) => {
809
- var _a;
810
- return (_a = store.get(serializedKey)) == null ? void 0 : _a.getValue();
811
- };
812
- const getValue$ = (key) => {
813
- return store$.pipe(
814
- map(() => store.get(key)),
815
- filter(isDefined),
816
- map((entry) => entry.getValue()),
817
- distinctUntilChanged(shallowEqual)
818
- );
819
- };
820
- const updateValue = (key, value) => {
821
- const existingObject = store.get(key);
822
- if (!existingObject)
823
- return;
824
- if (typeof value === "function") {
825
- existingObject.next({
826
- ...existingObject.getValue(),
827
- ...value(existingObject.getValue())
828
- });
829
- } else {
830
- existingObject.next({ ...existingObject.getValue(), ...value });
831
- }
832
- store$.next(store);
833
- };
834
- const updateMany = (value, predicate = () => true) => {
835
- store.forEach((oldValue$) => {
836
- const oldValue = oldValue$.getValue();
837
- if (predicate(oldValue)) {
838
- oldValue$.next({ ...oldValue, ...value });
839
- }
840
- });
841
- store$.next(store);
842
- };
843
- const deleteValue = (key) => {
844
- store.delete(key);
845
- store$.next(store);
846
- };
847
- const addRunner = (key, stream) => {
848
- updateValue(key, (old) => ({
849
- ...old,
850
- runners: [...old.runners, stream]
792
+ const X = Ae("production"), Mt = X.namespace("store"), Tt = (t) => t.pipe(
793
+ p(
794
+ (e) => [...e.keys()].reduce((r, n) => {
795
+ var s;
796
+ return r[n] = (s = e.get(n)) == null ? void 0 : s.getValue(), r;
797
+ }, {})
798
+ ),
799
+ C(M)
800
+ ).subscribe((e) => {
801
+ Mt.log("store", "update", e);
802
+ }), It = () => {
803
+ const t = /* @__PURE__ */ new Map(), e = new I(t), r = new F(), n = new F(), s = () => {
804
+ e.next(t);
805
+ }, i = (c, o) => {
806
+ t.set(c, new I(o)), s();
807
+ }, u = (c) => {
808
+ var o;
809
+ return (o = t.get(c)) == null ? void 0 : o.getValue();
810
+ }, l = (c) => e.pipe(
811
+ p(() => t.get(c)),
812
+ $(G),
813
+ p((o) => o.getValue()),
814
+ C(M)
815
+ ), f = (c, o) => {
816
+ const m = t.get(c);
817
+ m && (typeof o == "function" ? m.next({
818
+ ...m.getValue(),
819
+ ...o(m.getValue())
820
+ }) : m.next({ ...m.getValue(), ...o }), e.next(t));
821
+ }, d = (c, o = () => !0) => {
822
+ t.forEach((m) => {
823
+ const R = m.getValue();
824
+ o(R) && m.next({ ...R, ...c });
825
+ }), e.next(t);
826
+ }, h = (c) => {
827
+ t.delete(c), e.next(t);
828
+ }, g = (c, o) => (f(c, (m) => ({
829
+ ...m,
830
+ runners: [...m.runners, o]
831
+ })), () => {
832
+ var R;
833
+ const m = ((R = t.get(c)) == null ? void 0 : R.getValue().runners.filter((b) => b !== o)) ?? [];
834
+ f(c, (b) => ({
835
+ ...b,
836
+ runners: m
851
837
  }));
838
+ }), a = () => {
839
+ const c = Tt(e);
852
840
  return () => {
853
- var _a;
854
- const newListeners = ((_a = store.get(key)) == null ? void 0 : _a.getValue().runners.filter((reference) => reference !== stream)) ?? [];
855
- updateValue(key, (old) => ({
856
- ...old,
857
- runners: newListeners
858
- }));
859
- };
860
- };
861
- const start = () => {
862
- const debugger$ = createDebugger(store$);
863
- return () => {
864
- debugger$.unsubscribe();
841
+ c.unsubscribe();
865
842
  };
866
843
  };
867
844
  return {
868
- set: setValue,
869
- get: getValue,
870
- get$: getValue$,
871
- delete: deleteValue,
872
- update: updateValue,
873
- keys: () => store.keys(),
874
- updateMany,
875
- addRunner,
876
- store$,
877
- queryEvent$: queryEventSubject.asObservable(),
878
- dispatchQueryEvent: (event) => {
879
- queryEventSubject.next(event);
845
+ set: i,
846
+ get: u,
847
+ get$: l,
848
+ delete: h,
849
+ update: f,
850
+ keys: () => t.keys(),
851
+ updateMany: d,
852
+ addRunner: g,
853
+ store$: e,
854
+ queryEvent$: r.asObservable(),
855
+ dispatchQueryEvent: (c) => {
856
+ r.next(c);
880
857
  },
881
- queryTrigger$: queryTriggerSubject.asObservable(),
882
- dispatchQueryTrigger: (event) => {
883
- queryTriggerSubject.next(event);
858
+ queryTrigger$: n.asObservable(),
859
+ dispatchQueryTrigger: (c) => {
860
+ n.next(c);
884
861
  },
885
- size: () => store.size,
886
- start
862
+ size: () => t.size,
863
+ start: a
887
864
  };
888
- };
889
- const createQueryTrigger = ({
890
- options$,
891
- queryStore,
892
- key
865
+ }, Qt = ({
866
+ options$: t,
867
+ queryStore: e,
868
+ key: r
893
869
  }) => {
894
- const enabledOption$ = options$.pipe(
895
- map(({ enabled = true }) => enabled),
896
- distinctUntilChanged()
870
+ const s = t.pipe(
871
+ p(({ enabled: i = !0 }) => i),
872
+ C()
873
+ ).pipe(
874
+ B(1),
875
+ $((i) => i)
897
876
  );
898
- const enabledTrigger$ = enabledOption$.pipe(
899
- skip(1),
900
- filter((enabled) => enabled)
901
- );
902
- return merge(
903
- queryStore.queryTrigger$.pipe(
904
- filter((event) => key === event.key),
905
- map(({ trigger: trigger2 }) => trigger2)
877
+ return E(
878
+ e.queryTrigger$.pipe(
879
+ $((i) => r === i.key),
880
+ p(({ trigger: i }) => i)
906
881
  ),
907
- enabledTrigger$.pipe(
908
- map(() => ({
882
+ s.pipe(
883
+ p(() => ({
909
884
  type: "enabled",
910
- ignoreStale: false
885
+ ignoreStale: !1
911
886
  }))
912
887
  )
913
888
  );
914
- };
915
- const deduplicate = (key, queryStore) => (source) => {
916
- if (key === serializeKey([]))
917
- return source;
918
- return defer(() => {
919
- var _a;
920
- const sourceFromStore = (_a = queryStore.get(key)) == null ? void 0 : _a.deduplication_fn;
921
- if (sourceFromStore)
922
- return sourceFromStore;
923
- let sourceToDeduplicate;
924
- const deleteFromStore = () => {
925
- var _a2;
926
- if (((_a2 = queryStore.get(key)) == null ? void 0 : _a2.deduplication_fn) === sourceToDeduplicate) {
927
- queryStore.update(key, {
928
- deduplication_fn: void 0
929
- });
930
- }
931
- };
932
- sourceToDeduplicate = source.pipe(
933
- /**
934
- * Ideally we would want to remove the query from the store only on finalize,
935
- * which means whenever the query complete or error. Unfortunately finalize is
936
- * triggered after a new stream arrive which create a concurrency issue.
937
- * tap is triggered correctly synchronously and before a new query arrive.
938
- */
939
- tap({
940
- error: deleteFromStore,
941
- complete: deleteFromStore
942
- }),
943
- /**
944
- * Because tap is not called on unsubscription we still need to handle the case.
945
- */
946
- finalize(deleteFromStore),
947
- shareReplay({
948
- refCount: true,
949
- bufferSize: 1
950
- })
951
- );
952
- queryStore.update(key, {
953
- deduplication_fn: sourceToDeduplicate
889
+ }, Ft = (t, e) => (r) => t === N([]) ? r : ne(() => {
890
+ var u;
891
+ const n = (u = e.get(t)) == null ? void 0 : u.deduplication_fn;
892
+ if (n)
893
+ return n;
894
+ let s;
895
+ const i = () => {
896
+ var l;
897
+ ((l = e.get(t)) == null ? void 0 : l.deduplication_fn) === s && e.update(t, {
898
+ deduplication_fn: void 0
954
899
  });
955
- return sourceToDeduplicate;
956
- });
957
- };
958
- const notifyQueryResult = (options$) => (stream$) => stream$.pipe(
959
- withLatestFrom(options$),
960
- map(([result, options]) => {
961
- var _a, _b;
962
- if (result.error) {
963
- (_a = options.onError) == null ? void 0 : _a.call(options, result.error);
964
- } else {
965
- (_b = options.onSuccess) == null ? void 0 : _b.call(options, result);
966
- }
967
- return result;
900
+ };
901
+ return s = r.pipe(
902
+ /**
903
+ * Ideally we would want to remove the query from the store only on finalize,
904
+ * which means whenever the query complete or error. Unfortunately finalize is
905
+ * triggered after a new stream arrive which create a concurrency issue.
906
+ * tap is triggered correctly synchronously and before a new query arrive.
907
+ */
908
+ x({
909
+ error: i,
910
+ complete: i
911
+ }),
912
+ /**
913
+ * Because tap is not called on unsubscription we still need to handle the case.
914
+ */
915
+ ae(i),
916
+ $e({
917
+ refCount: !0,
918
+ bufferSize: 1
919
+ })
920
+ ), e.update(t, {
921
+ deduplication_fn: s
922
+ }), s;
923
+ }), _t = (t) => (e) => e.pipe(
924
+ D(t),
925
+ p(([r, n]) => {
926
+ var s, i;
927
+ return r.error ? (s = n.onError) == null || s.call(n, r.error) : (i = n.onSuccess) == null || i.call(n, r), r;
968
928
  })
969
- );
970
- const registerResultInCache = ({
971
- queryStore,
972
- serializedKey,
973
- options
974
- }) => (stream) => stream.pipe(
975
- tap(({ data }) => {
976
- if (data == null ? void 0 : data.result) {
977
- const result = data == null ? void 0 : data.result;
978
- queryStore.update(serializedKey, {
979
- ...options.cacheTime !== 0 && {
980
- cache_fnResult: { result }
929
+ ), Pt = ({
930
+ queryStore: t,
931
+ serializedKey: e,
932
+ options: r
933
+ }) => (n) => n.pipe(
934
+ x(({ data: s }) => {
935
+ if (s != null && s.result) {
936
+ const i = s == null ? void 0 : s.result;
937
+ t.update(e, {
938
+ ...r.cacheTime !== 0 && {
939
+ cache_fnResult: { result: i }
981
940
  }
982
941
  });
983
942
  }
984
943
  })
985
- );
986
- const createQueryFetch = ({
987
- options$,
988
- options,
989
- fn,
990
- queryStore,
991
- serializedKey,
992
- trigger: trigger2,
993
- trigger$
944
+ ), Nt = ({
945
+ options$: t,
946
+ options: e,
947
+ fn: r,
948
+ queryStore: n,
949
+ serializedKey: s,
950
+ trigger: i,
951
+ trigger$: u
994
952
  }) => {
995
- const enabledOption$ = options$.pipe(
996
- map(({ enabled = true }) => enabled),
997
- distinctUntilChanged()
998
- );
999
- const disabled$ = enabledOption$.pipe(
1000
- distinctUntilChanged(),
1001
- filter((enabled) => !enabled)
1002
- );
1003
- const deferredQuery = defer(() => {
1004
- const queryOrResponse = typeof fn === "function" ? fn() : fn;
1005
- return from(queryOrResponse);
1006
- });
1007
- const fnExecution$ = deferredQuery.pipe(
1008
- retryOnError(options),
1009
- deduplicate(serializedKey, queryStore),
1010
- tap(() => {
1011
- queryStore.dispatchQueryEvent({
1012
- key: serializedKey,
953
+ const f = t.pipe(
954
+ p(({ enabled: b = !0 }) => b),
955
+ C()
956
+ ).pipe(
957
+ C(),
958
+ $((b) => !b)
959
+ ), h = ne(() => {
960
+ const b = typeof r == "function" ? r() : r;
961
+ return re(b);
962
+ }).pipe(
963
+ Ue(e),
964
+ Ft(s, n),
965
+ x(() => {
966
+ n.dispatchQueryEvent({
967
+ key: s,
1013
968
  type: "fetchSuccess"
1014
- });
1015
- queryStore.update(serializedKey, {
969
+ }), n.update(s, {
1016
970
  lastFetchedAt: (/* @__PURE__ */ new Date()).getTime()
1017
971
  });
1018
972
  }),
1019
- map((result) => ({
973
+ p((b) => ({
1020
974
  status: "success",
1021
- data: { result },
975
+ data: { result: b },
1022
976
  error: void 0
1023
977
  })),
1024
- endWith({
978
+ tt({
1025
979
  fetchStatus: "idle"
1026
980
  }),
1027
- catchError((error) => {
1028
- queryStore.dispatchQueryEvent({
1029
- key: serializedKey,
1030
- type: "fetchError"
1031
- });
1032
- return of({
1033
- fetchStatus: "idle",
1034
- status: "error",
1035
- data: void 0,
1036
- error
1037
- });
1038
- }),
1039
- notifyQueryResult(options$),
1040
- registerResultInCache({ serializedKey, options, queryStore })
1041
- );
1042
- const newCache$ = queryStore.queryEvent$.pipe(
1043
- filter(
1044
- (event) => event.key === serializedKey && event.type === "queryDataSet"
981
+ j((b) => (n.dispatchQueryEvent({
982
+ key: s,
983
+ type: "fetchError"
984
+ }), S({
985
+ fetchStatus: "idle",
986
+ status: "error",
987
+ data: void 0,
988
+ error: b
989
+ }))),
990
+ _t(t),
991
+ Pt({ serializedKey: s, options: e, queryStore: n })
992
+ ), g = n.queryEvent$.pipe(
993
+ $(
994
+ (b) => b.key === s && b.type === "queryDataSet"
1045
995
  ),
1046
- map(() => {
1047
- var _a, _b;
1048
- return (_b = (_a = queryStore.get(serializedKey)) == null ? void 0 : _a.cache_fnResult) == null ? void 0 : _b.result;
996
+ p(() => {
997
+ var b, A;
998
+ return (A = (b = n.get(s)) == null ? void 0 : b.cache_fnResult) == null ? void 0 : A.result;
1049
999
  }),
1050
- filter(isDefined),
1051
- map((result) => ({
1000
+ $(G),
1001
+ p((b) => ({
1052
1002
  status: "success",
1053
- data: { result }
1003
+ data: { result: b }
1054
1004
  })),
1055
1005
  /**
1056
1006
  * @important
@@ -1058,1044 +1008,934 @@ const createQueryFetch = ({
1058
1008
  * For example if user set query data inside onSuccess callback, we simulate
1059
1009
  * a small delay to ensure it happens after.
1060
1010
  */
1061
- delay(1)
1062
- );
1063
- const execution$ = merge(
1064
- disabled$.pipe(
1065
- take(1),
1066
- map(() => ({
1011
+ rt(1)
1012
+ ), a = E(
1013
+ f.pipe(
1014
+ be(1),
1015
+ p(() => ({
1067
1016
  fetchStatus: "idle"
1068
1017
  }))
1069
1018
  ),
1070
- merge(
1071
- of({ fetchStatus: "fetching", error: void 0 }),
1072
- fnExecution$
1073
- ).pipe(takeUntil(disabled$)),
1074
- newCache$
1075
- ).pipe(takeUntil(trigger$));
1076
- const query = queryStore.get(serializedKey);
1077
- const cacheResult = query == null ? void 0 : query.cache_fnResult;
1078
- const hasCache = !!cacheResult;
1079
- const ignoreStale = trigger2.type === "refetch" && trigger2.ignoreStale;
1080
- if (hasCache) {
1081
- if (!(query == null ? void 0 : query.isStale) && !ignoreStale) {
1082
- return of({
1083
- fetchStatus: "idle",
1084
- status: "success",
1085
- data: { result: cacheResult.result },
1086
- error: void 0
1087
- });
1088
- } else {
1089
- return merge(
1090
- of({
1091
- fetchStatus: "fetching",
1092
- status: "success",
1093
- data: { result: cacheResult.result },
1094
- error: void 0
1095
- }),
1096
- execution$
1097
- );
1098
- }
1099
- }
1100
- return execution$;
1101
- };
1102
- const compareKeys = (keyA, keyB, { exact = false } = {}) => {
1103
- if (exact) {
1104
- return serializeKey(keyA) === serializeKey(keyB);
1105
- }
1106
- return keyA.reduce((acc, value, index) => {
1107
- if (!acc)
1108
- return false;
1109
- if (value === void 0) {
1110
- const hasNextItemInLineNotUndefined = keyA.slice(index, keyA.length - 1).some((item) => item !== void 0);
1111
- if (!hasNextItemInLineNotUndefined) {
1112
- return true;
1113
- }
1114
- }
1115
- return serializeObject(value) === serializeObject(keyB[index]);
1116
- }, true);
1117
- };
1118
- const logger$2 = Logger.namespace("invalidation");
1119
- const createInvalidationClient = ({
1120
- queryStore
1121
- }) => {
1122
- const invalidateQueries = ({
1123
- queryKey,
1124
- exact = false,
1125
- predicate
1019
+ E(
1020
+ S({ fetchStatus: "fetching", error: void 0 }),
1021
+ h
1022
+ ).pipe(P(f)),
1023
+ g
1024
+ ).pipe(P(u)), c = n.get(s), o = c == null ? void 0 : c.cache_fnResult, m = !!o, R = i.type === "refetch" && i.ignoreStale;
1025
+ return m ? !(c != null && c.isStale) && !R ? S({
1026
+ fetchStatus: "idle",
1027
+ status: "success",
1028
+ data: { result: o.result },
1029
+ error: void 0
1030
+ }) : E(
1031
+ S({
1032
+ fetchStatus: "fetching",
1033
+ status: "success",
1034
+ data: { result: o.result },
1035
+ error: void 0
1036
+ }),
1037
+ a
1038
+ ) : a;
1039
+ }, oe = (t, e, { exact: r = !1 } = {}) => r ? N(t) === N(e) : t.reduce((n, s, i) => n ? s === void 0 && !t.slice(i, t.length - 1).some((l) => l !== void 0) ? !0 : ee(s) === ee(e[i]) : !1, !0), q = X.namespace("invalidation"), kt = ({
1040
+ queryStore: t
1041
+ }) => ({
1042
+ invalidateQueries: ({
1043
+ queryKey: r,
1044
+ exact: n = !1,
1045
+ predicate: s
1126
1046
  } = {}) => {
1127
- let keysToRefetch = [];
1128
- if (queryKey) {
1129
- logger$2.log(`invalidation requested for`, queryKey);
1130
- queryStore.updateMany({ isStale: true }, (entry) => {
1131
- const isValid = compareKeys(queryKey, entry.queryKey, { exact });
1132
- if (isValid) {
1133
- keysToRefetch.push(serializeKey(entry.queryKey));
1134
- }
1135
- return isValid;
1136
- });
1137
- } else if (predicate) {
1138
- queryStore.updateMany({ isStale: true }, (entry) => {
1139
- const isValid = predicate(entry);
1140
- if (isValid) {
1141
- keysToRefetch.push(serializeKey(entry.queryKey));
1142
- }
1143
- return isValid;
1144
- });
1145
- } else {
1146
- logger$2.log(`Invalidation requested for all queries`);
1147
- queryStore.updateMany({ isStale: true });
1148
- keysToRefetch = Array.from(queryStore.keys());
1149
- }
1150
- keysToRefetch.forEach((key) => {
1151
- queryStore.update(key, {
1047
+ let i = [];
1048
+ r ? (q.log("invalidation requested for", r), t.updateMany({ isStale: !0 }, (u) => {
1049
+ const l = oe(r, u.queryKey, { exact: n });
1050
+ return l && i.push(N(u.queryKey)), l;
1051
+ })) : s ? t.updateMany({ isStale: !0 }, (u) => {
1052
+ const l = s(u);
1053
+ return l && i.push(N(u.queryKey)), l;
1054
+ }) : (q.log("Invalidation requested for all queries"), t.updateMany({ isStale: !0 }), i = Array.from(t.keys())), i.forEach((u) => {
1055
+ t.update(u, {
1152
1056
  deduplication_fn: void 0
1153
- });
1154
- queryStore.dispatchQueryTrigger({
1155
- key,
1156
- trigger: { ignoreStale: true, type: "refetch" }
1057
+ }), t.dispatchQueryTrigger({
1058
+ key: u,
1059
+ trigger: { ignoreStale: !0, type: "refetch" }
1157
1060
  });
1158
1061
  });
1159
- };
1160
- return {
1161
- invalidateQueries
1162
- };
1163
- };
1164
- const createRefetchClient = (_) => {
1165
- const pipeQueryResult = ({
1166
- options$
1167
- }) => (stream) => {
1168
- const sharedStream = stream.pipe(share());
1169
- return merge(
1170
- sharedStream,
1171
- sharedStream.pipe(
1172
- filter(
1173
- (result) => !!result.data && result.fetchStatus !== "fetching"
1062
+ }
1063
+ }), Lt = (t) => ({
1064
+ pipeQueryResult: ({
1065
+ options$: n
1066
+ }) => (s) => {
1067
+ const i = s.pipe(J());
1068
+ return E(
1069
+ i,
1070
+ i.pipe(
1071
+ $(
1072
+ (u) => !!u.data && u.fetchStatus !== "fetching"
1174
1073
  ),
1175
- distinctUntilChanged((prev, curr) => prev.data === curr.data),
1176
- withLatestFrom(options$),
1177
- map(([, { refetchInterval }]) => refetchInterval),
1178
- filter(isDefined),
1179
- switchMap((refetchInterval) => {
1180
- if (typeof refetchInterval === "number") {
1181
- return timer(refetchInterval).pipe(
1182
- map(() => ({
1183
- type: "refetch",
1184
- ignoreStale: true
1185
- })),
1186
- switchMap(() => EMPTY)
1187
- );
1188
- }
1189
- return EMPTY;
1190
- })
1074
+ C((u, l) => u.data === l.data),
1075
+ D(n),
1076
+ p(([, { refetchInterval: u }]) => u),
1077
+ $(G),
1078
+ w((u) => typeof u == "number" ? se(u).pipe(
1079
+ p(() => ({
1080
+ type: "refetch",
1081
+ ignoreStale: !0
1082
+ })),
1083
+ w(() => T)
1084
+ ) : T)
1191
1085
  )
1192
1086
  );
1193
- };
1194
- const refetchQueries = (_2) => {
1195
- };
1196
- return {
1197
- pipeQueryResult,
1198
- refetchQueries
1199
- };
1200
- };
1201
- const difference = (a, b) => a.filter((element) => !b.includes(element));
1202
- const createQueryListener = (store, onQuery) => store.store$.pipe(
1203
- map((store2) => [...store2.keys()]),
1204
- startWith([]),
1205
- pairwise(),
1206
- mergeMap(([previousKeys, currentKeys]) => {
1207
- const newKeys = difference(currentKeys, previousKeys);
1208
- return merge(
1209
- ...newKeys.map((key) => {
1210
- const deleted$ = store.store$.pipe(
1211
- map(() => store.get(key)),
1212
- filter((item) => item === void 0)
1087
+ },
1088
+ refetchQueries: (n) => {
1089
+ }
1090
+ }), Ut = (t, e) => t.filter((r) => !e.includes(r)), At = (t, e) => t.store$.pipe(
1091
+ p((r) => [...r.keys()]),
1092
+ Ie([]),
1093
+ ce(),
1094
+ _(([r, n]) => {
1095
+ const s = Ut(n, r);
1096
+ return E(
1097
+ ...s.map((i) => {
1098
+ const u = t.store$.pipe(
1099
+ p(() => t.get(i)),
1100
+ $((l) => l === void 0)
1213
1101
  );
1214
- return merge(NEVER, of(key)).pipe(
1215
- tap(() => {
1102
+ return E(Qe, S(i)).pipe(
1103
+ x(() => {
1216
1104
  }),
1217
- onQuery,
1218
- finalize(() => {
1105
+ e,
1106
+ ae(() => {
1219
1107
  }),
1220
- takeUntil(deleted$)
1108
+ P(u)
1221
1109
  );
1222
1110
  })
1223
1111
  );
1224
1112
  })
1225
- );
1226
- const mapStoreQueryToRunnerOptions = (stream) => stream.pipe(
1227
- switchMap((entry) => combineLatest(entry.runners)),
1228
- map((runnerValues) => runnerValues.map(({ options }) => options))
1229
- );
1230
- const mapOptionsToOption$1 = (stream) => stream.pipe(
1231
- map(
1232
- (options) => options.reduce(
1233
- (acc, value) => {
1234
- return {
1235
- ...acc,
1236
- lowestStaleTime: value.staleTime === void 0 ? acc.lowestStaleTime : Math.min(
1237
- value.staleTime ?? Infinity,
1238
- acc.lowestStaleTime ?? Infinity
1239
- )
1240
- };
1241
- },
1113
+ ), je = (t) => t.pipe(
1114
+ w((e) => Fe(e.runners)),
1115
+ p((e) => e.map(({ options: r }) => r))
1116
+ ), jt = (t) => t.pipe(
1117
+ p(
1118
+ (e) => e.reduce(
1119
+ (r, n) => ({
1120
+ ...r,
1121
+ lowestStaleTime: n.staleTime === void 0 ? r.lowestStaleTime : Math.min(
1122
+ n.staleTime ?? 1 / 0,
1123
+ r.lowestStaleTime ?? 1 / 0
1124
+ )
1125
+ }),
1242
1126
  { lowestStaleTime: void 0 }
1243
1127
  )
1244
1128
  ),
1245
- distinctUntilChanged(shallowEqual)
1246
- );
1247
- const onlyFetchEventDone = (key) => (stream) => stream.pipe(
1248
- filter(
1249
- (event) => event.key === key && (event.type === "fetchError" || event.type === "fetchSuccess")
1129
+ C(M)
1130
+ ), Kt = (t) => (e) => e.pipe(
1131
+ $(
1132
+ (r) => r.key === t && (r.type === "fetchError" || r.type === "fetchSuccess")
1250
1133
  )
1251
- );
1252
- const markAsStale = ({
1253
- queryStore
1254
- }) => (stream) => stream.pipe(
1255
- switchMap((key) => {
1256
- const query$ = queryStore.get$(key);
1257
- return queryStore.queryEvent$.pipe(
1258
- onlyFetchEventDone(key),
1259
- switchMap(
1260
- () => query$.pipe(
1261
- mapStoreQueryToRunnerOptions,
1262
- mapOptionsToOption$1,
1263
- tap(({ lowestStaleTime = 0 }) => {
1264
- var _a;
1265
- if (lowestStaleTime === 0) {
1266
- logger$2.log(key, "marked as stale!", {
1267
- staleTime: lowestStaleTime
1268
- });
1269
- queryStore.update(key, { isStale: true });
1270
- } else if ((_a = queryStore.get(key)) == null ? void 0 : _a.isStale) {
1271
- logger$2.log(key, "marked non stale", {
1272
- staleTime: lowestStaleTime
1273
- });
1274
- queryStore.update(key, { isStale: false });
1275
- }
1134
+ ), zt = ({
1135
+ queryStore: t
1136
+ }) => (e) => e.pipe(
1137
+ w((r) => {
1138
+ const n = t.get$(r);
1139
+ return t.queryEvent$.pipe(
1140
+ Kt(r),
1141
+ w(
1142
+ () => n.pipe(
1143
+ je,
1144
+ jt,
1145
+ x(({ lowestStaleTime: s = 0 }) => {
1146
+ var i;
1147
+ s === 0 ? (q.log(r, "marked as stale!", {
1148
+ staleTime: s
1149
+ }), t.update(r, { isStale: !0 })) : (i = t.get(r)) != null && i.isStale && (q.log(r, "marked non stale", {
1150
+ staleTime: s
1151
+ }), t.update(r, { isStale: !1 }));
1276
1152
  }),
1277
- filter(
1278
- ({ lowestStaleTime }) => lowestStaleTime !== Infinity && lowestStaleTime !== 0
1153
+ $(
1154
+ ({ lowestStaleTime: s }) => s !== 1 / 0 && s !== 0
1279
1155
  ),
1280
- switchMap(({ lowestStaleTime = 0 }) => timer(lowestStaleTime)),
1281
- tap(() => {
1282
- var _a;
1283
- if (!((_a = queryStore.get(key)) == null ? void 0 : _a.isStale)) {
1284
- logger$2.log(key, "marked as stale!");
1285
- queryStore.update(key, { isStale: true });
1286
- }
1156
+ w(({ lowestStaleTime: s = 0 }) => se(s)),
1157
+ x(() => {
1158
+ var s;
1159
+ (s = t.get(r)) != null && s.isStale || (q.log(r, "marked as stale!"), t.update(r, { isStale: !0 }));
1287
1160
  })
1288
1161
  )
1289
1162
  ),
1290
- map(() => key)
1163
+ p(() => r)
1291
1164
  );
1292
1165
  })
1293
- );
1294
- const mapOptionsToOption = (stream) => stream.pipe(
1295
- map(
1296
- (options) => options.reduce(
1297
- (acc, value) => {
1298
- return {
1299
- ...acc,
1300
- lowestCacheTime: value.cacheTime === void 0 ? acc.lowestCacheTime : Math.min(
1301
- value.cacheTime ?? Infinity,
1302
- acc.lowestCacheTime ?? Infinity
1303
- )
1304
- };
1305
- },
1166
+ ), Jt = (t) => t.pipe(
1167
+ p(
1168
+ (e) => e.reduce(
1169
+ (r, n) => ({
1170
+ ...r,
1171
+ lowestCacheTime: n.cacheTime === void 0 ? r.lowestCacheTime : Math.min(
1172
+ n.cacheTime ?? 1 / 0,
1173
+ r.lowestCacheTime ?? 1 / 0
1174
+ )
1175
+ }),
1306
1176
  { lowestCacheTime: void 0 }
1307
1177
  )
1308
1178
  ),
1309
- distinctUntilChanged(shallowEqual)
1310
- );
1311
- const onCacheUpdate = (stream) => stream.pipe(
1312
- map((item) => item.cache_fnResult),
1313
- distinctUntilChanged(shallowEqual)
1314
- );
1315
- const invalidateCache = ({
1316
- queryStore
1317
- }) => (stream) => stream.pipe(
1318
- switchMap((key) => {
1319
- const query$ = queryStore.get$(key);
1320
- const invalidateCache$ = query$.pipe(
1321
- onCacheUpdate,
1322
- switchMap(
1323
- () => query$.pipe(
1324
- mapStoreQueryToRunnerOptions,
1325
- mapOptionsToOption,
1326
- switchMap(
1179
+ C(M)
1180
+ ), Wt = (t) => t.pipe(
1181
+ p((e) => e.cache_fnResult),
1182
+ C(M)
1183
+ ), Yt = ({
1184
+ queryStore: t
1185
+ }) => (e) => e.pipe(
1186
+ w((r) => {
1187
+ const n = t.get$(r);
1188
+ return n.pipe(
1189
+ Wt,
1190
+ w(
1191
+ () => n.pipe(
1192
+ je,
1193
+ Jt,
1194
+ w(
1327
1195
  ({
1328
- lowestCacheTime = 5 * 60 * 1e3
1196
+ lowestCacheTime: i = 5 * 60 * 1e3
1329
1197
  /* 5mn */
1330
- }) => timer(lowestCacheTime).pipe(
1331
- tap(() => {
1332
- queryStore.update(key, { cache_fnResult: void 0 });
1198
+ }) => se(i).pipe(
1199
+ x(() => {
1200
+ t.update(r, { cache_fnResult: void 0 });
1333
1201
  })
1334
1202
  )
1335
1203
  )
1336
1204
  )
1337
1205
  )
1338
- );
1339
- return invalidateCache$.pipe(map(() => key));
1340
- })
1341
- );
1342
- const garbageCache = ({
1343
- queryStore
1344
- }) => (stream) => stream.pipe(
1345
- switchMap((key) => {
1346
- const query$ = queryStore.get$(key);
1347
- return query$.pipe(
1348
- filter((entry) => !entry.cache_fnResult),
1349
- map((entry) => entry.runners.length > 0),
1350
- pairwise(),
1351
- filter(([hadRunners, hasRunners]) => hadRunners && !hasRunners),
1352
- tap(() => {
1353
- queryStore.delete(key);
1354
- }),
1355
- map(() => key)
1356
- );
1206
+ ).pipe(p(() => r));
1357
1207
  })
1358
- );
1359
- const getInitialQueryEntity = ({ key }) => ({
1360
- isStale: true,
1361
- queryKey: key,
1208
+ ), Gt = ({
1209
+ queryStore: t
1210
+ }) => (e) => e.pipe(
1211
+ w((r) => t.get$(r).pipe(
1212
+ $((s) => !s.cache_fnResult),
1213
+ p((s) => s.runners.length > 0),
1214
+ ce(),
1215
+ $(([s, i]) => s && !i),
1216
+ x(() => {
1217
+ t.delete(r);
1218
+ }),
1219
+ p(() => r)
1220
+ ))
1221
+ ), Ke = ({ key: t }) => ({
1222
+ isStale: !0,
1223
+ queryKey: t,
1362
1224
  runners: []
1363
- });
1364
- const updateStoreWithNewQuery = ({
1365
- queryStore,
1366
- serializedKey,
1367
- runner$,
1368
- options$,
1369
- key
1370
- }) => (stream) => stream.pipe(
1371
- withLatestFrom(options$),
1372
- map(([trigger2, options]) => {
1373
- if (key.length === 0)
1374
- return [trigger2, void 0];
1375
- if (trigger2.type !== "initial")
1376
- return [trigger2, void 0];
1377
- if (!queryStore.get(serializedKey)) {
1378
- queryStore.set(serializedKey, getInitialQueryEntity({ key }));
1379
- } else {
1380
- queryStore.update(serializedKey, {
1381
- queryKey: key,
1382
- ...options.markStale && {
1383
- isStale: true
1384
- }
1385
- });
1225
+ }), Ht = ({
1226
+ queryStore: t,
1227
+ serializedKey: e,
1228
+ runner$: r,
1229
+ options$: n,
1230
+ key: s
1231
+ }) => (i) => i.pipe(
1232
+ D(n),
1233
+ p(([u, l]) => s.length === 0 ? [u, void 0] : u.type !== "initial" ? [u, void 0] : (t.get(e) ? t.update(e, {
1234
+ queryKey: s,
1235
+ ...l.markStale && {
1236
+ isStale: !0
1386
1237
  }
1387
- return [trigger2, queryStore.addRunner(serializedKey, runner$)];
1388
- })
1389
- );
1390
- const logger$1 = Logger.namespace("cache");
1391
- const createCacheClient = ({
1392
- queryStore
1393
- }) => {
1394
- const setQueryData = ({
1395
- queryKey,
1396
- updater
1238
+ }) : t.set(e, Ke({ key: s })), [u, t.addRunner(e, r)]))
1239
+ ), Dt = X.namespace("cache"), Xt = ({
1240
+ queryStore: t
1241
+ }) => ({
1242
+ setQueryData: ({
1243
+ queryKey: r,
1244
+ updater: n
1397
1245
  }) => {
1398
- const serializedKey = serializeKey(queryKey);
1399
- if (queryKey.length === 0)
1400
- return;
1401
- logger$1.log("set cache for query", serializeKey);
1402
- if (!queryStore.get(serializedKey)) {
1403
- queryStore.set(serializedKey, getInitialQueryEntity({ key: queryKey }));
1404
- }
1405
- queryStore.update(serializedKey, (entity) => {
1406
- var _a;
1407
- if (typeof updater === "function") {
1408
- const callableUpdater = updater;
1409
- return {
1410
- ...entity,
1411
- cache_fnResult: {
1412
- result: callableUpdater(
1413
- (_a = entity.cache_fnResult) == null ? void 0 : _a.result
1414
- )
1415
- }
1416
- };
1417
- }
1418
- return {
1419
- ...entity,
1246
+ const s = N(r);
1247
+ r.length !== 0 && (Dt.log("set cache for query", N), t.get(s) || t.set(s, Ke({ key: r })), t.update(s, (i) => {
1248
+ var u;
1249
+ return typeof n == "function" ? {
1250
+ ...i,
1251
+ cache_fnResult: {
1252
+ result: n(
1253
+ (u = i.cache_fnResult) == null ? void 0 : u.result
1254
+ )
1255
+ }
1256
+ } : {
1257
+ ...i,
1420
1258
  cache_fnResult: {
1421
- result: updater
1259
+ result: n
1422
1260
  }
1423
1261
  };
1424
- });
1425
- queryStore.dispatchQueryEvent({
1426
- key: serializedKey,
1262
+ }), t.dispatchQueryEvent({
1263
+ key: s,
1427
1264
  type: "queryDataSet"
1428
- });
1429
- };
1430
- return {
1431
- setQueryData
1432
- };
1433
- };
1434
- const logger = Logger.namespace("refetch");
1435
- const markQueryAsStaleIfRefetch = ({
1436
- key,
1437
- serializedKey,
1438
- queryStore
1439
- }) => (stream) => {
1440
- return stream.pipe(
1441
- tap((trigger2) => {
1442
- if (trigger2.type !== "refetch")
1443
- return;
1444
- const query = queryStore.get(serializedKey);
1445
- if (query && trigger2.ignoreStale && !query.isStale) {
1446
- logger.log(key, "marked stale by trigger!");
1447
- queryStore.update(serializedKey, {
1448
- isStale: true
1449
- });
1265
+ }));
1266
+ }
1267
+ }), Zt = X.namespace("refetch"), qt = ({
1268
+ key: t,
1269
+ serializedKey: e,
1270
+ queryStore: r
1271
+ }) => (n) => n.pipe(
1272
+ x((s) => {
1273
+ if (s.type !== "refetch")
1274
+ return;
1275
+ const i = r.get(e);
1276
+ i && s.ignoreStale && !i.isStale && (Zt.log(t, "marked stale by trigger!"), r.update(e, {
1277
+ isStale: !0
1278
+ }));
1279
+ })
1280
+ ), Bt = ({
1281
+ queryStore: t,
1282
+ serializedKey: e
1283
+ }) => (r) => r.pipe(
1284
+ x((n) => {
1285
+ n.type === "refetch" && (t.update(e, {
1286
+ deduplication_fn: void 0
1287
+ }), t.dispatchQueryTrigger({
1288
+ key: e,
1289
+ trigger: n
1290
+ }));
1291
+ }),
1292
+ $((n) => n.type !== "refetch")
1293
+ ), V = (t) => ne(() => {
1294
+ const e = t();
1295
+ return e instanceof Promise ? re(e) : e instanceof Te ? e : S(e);
1296
+ }), er = ({
1297
+ variables: t,
1298
+ state: e,
1299
+ options: r
1300
+ }) => {
1301
+ const n = e.isPaused, s = async () => await Promise.reject(new Error("No mutationFn found")), i = r.mutationFn ?? s, l = Me(
1302
+ () => n,
1303
+ S(e.context),
1304
+ V(
1305
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
1306
+ () => {
1307
+ var a;
1308
+ return ((a = r.onMutate) == null ? void 0 : a.call(r, t)) ?? void 0;
1450
1309
  }
1451
- })
1452
- );
1453
- };
1454
- const dispatchExternalRefetchToAllQueries = ({
1455
- queryStore,
1456
- serializedKey
1457
- }) => (stream) => stream.pipe(
1458
- tap((trigger2) => {
1459
- if (trigger2.type === "refetch") {
1460
- queryStore.update(serializedKey, {
1461
- deduplication_fn: void 0
1462
- });
1463
- queryStore.dispatchQueryTrigger({
1464
- key: serializedKey,
1465
- trigger: trigger2
1466
- });
1310
+ )
1311
+ ).pipe(J()), f = (a, c, o) => (console.error(a), V(
1312
+ () => {
1313
+ var R;
1314
+ return (R = r.onError) == null ? void 0 : R.call(r, a, t, c);
1467
1315
  }
1468
- }),
1469
- filter((trigger2) => trigger2.type !== "refetch")
1470
- );
1471
- const getDefaultMutationState = () => ({
1472
- context: void 0,
1473
- data: void 0,
1474
- error: null,
1475
- status: "idle",
1476
- submittedAt: 0,
1477
- variables: void 0
1478
- });
1479
- const mergeResults = (stream$) => stream$.pipe(
1480
- scan((acc, current) => {
1481
- return {
1482
- ...acc,
1483
- ...current,
1484
- data: current.data ?? acc.data,
1485
- error: current.error ?? acc.error
1486
- };
1487
- }, getDefaultMutationState()),
1488
- distinctUntilChanged(
1489
- ({ data: prevData, ...prev }, { data: currData, ...curr }) => shallowEqual(prev, curr) && shallowEqual(prevData, currData)
1490
- )
1491
- );
1492
- class Mutation {
1493
- constructor({
1494
- args,
1495
- ...options
1496
- }) {
1497
- __publicField(this, "stateSubject", new ReplaySubject(1));
1498
- /**
1499
- * @important
1500
- * convenience over usage of stateSubject for sync access
1501
- */
1502
- __publicField(this, "state", getDefaultMutationState());
1503
- __publicField(this, "options");
1504
- __publicField(this, "mutation$");
1505
- this.options = options;
1506
- const mutationFn = options.mutationFn;
1507
- this.state.variables = args;
1508
- this.stateSubject.next(this.state);
1509
- const mutationFnObservable = typeof mutationFn === "function" ? defer(() => from(mutationFn(args))) : mutationFn;
1510
- const queryRunner$ = mutationFnObservable.pipe(
1511
- retryOnError(options),
1512
- take(1),
1513
- map((data) => ({ data, isError: false })),
1514
- catchError((error) => {
1515
- console.error(error);
1516
- if (options.onError != null) {
1517
- options.onError(error, args);
1518
- }
1519
- return of({ data: error, isError: true });
1316
+ ).pipe(
1317
+ j(() => S(a)),
1318
+ p(
1319
+ () => ({
1320
+ failureCount: o,
1321
+ error: a,
1322
+ failureReason: a,
1323
+ context: c,
1324
+ status: "error"
1520
1325
  })
1521
- );
1522
- const initState$ = of({
1523
- ...this.state,
1524
- status: "pending",
1525
- submittedAt: (/* @__PURE__ */ new Date()).getTime()
1526
- });
1527
- this.mutation$ = merge(
1528
- initState$,
1529
- queryRunner$.pipe(
1530
- map(({ data, isError }) => {
1531
- if (!isError) {
1532
- if (options.onSuccess != null)
1533
- options.onSuccess(data, args);
1534
- }
1535
- return isError ? {
1536
- status: "error",
1537
- error: data,
1538
- data: void 0
1539
- } : {
1540
- status: "success",
1541
- error: null,
1542
- data
1543
- };
1326
+ )
1327
+ )), d = l.pipe(
1328
+ w((a) => (typeof i == "function" ? (
1329
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
1330
+ V(() => i(t))
1331
+ ) : i).pipe(
1332
+ p(
1333
+ (o) => ({
1334
+ result: {
1335
+ data: o
1336
+ },
1337
+ error: null,
1338
+ context: a
1544
1339
  })
1545
- )
1546
- ).pipe(
1547
- mergeResults,
1548
- tap((value) => {
1549
- this.state = { ...this.state, ...value };
1550
- this.stateSubject.next(this.state);
1340
+ ),
1341
+ Ue({
1342
+ ...r,
1343
+ caughtError: (o, m) => S({
1344
+ failureCount: o,
1345
+ failureReason: m
1346
+ }),
1347
+ catchError: (o, m) => f(m, a, o).pipe(
1348
+ p((R) => ({
1349
+ ...R,
1350
+ result: void 0
1351
+ }))
1352
+ )
1551
1353
  }),
1552
- options.__queryRunnerHook ?? identity,
1553
- share()
1554
- );
1555
- }
1556
- }
1557
- const createMutationRunner = ({
1558
- __queryFinalizeHook,
1559
- __queryInitHook,
1560
- __queryTriggerHook
1561
- }) => {
1562
- const trigger$ = new Subject();
1563
- const cancel$ = new Subject();
1564
- let closed = false;
1565
- const mapOperator$ = new BehaviorSubject("merge");
1566
- const mutationsSubject = new BehaviorSubject([]);
1567
- const destroy = () => {
1568
- if (closed) {
1569
- throw new Error("Trying to close an already closed mutation");
1570
- }
1571
- closed = true;
1572
- mapOperator$.complete();
1573
- mutationsSubject.complete();
1574
- trigger$.complete();
1575
- cancel$.next();
1576
- cancel$.complete();
1577
- };
1578
- const stableMapOperator$ = mapOperator$.pipe(
1579
- filter(isDefined),
1580
- distinctUntilChanged()
1581
- );
1582
- const mutation$ = stableMapOperator$.pipe(
1583
- __queryInitHook ?? identity,
1584
- mergeMap((mapOperator) => {
1585
- const switchOperator = mapOperator === "concat" ? concatMap$1 : mapOperator === "switch" ? switchMap : mergeMap;
1586
- let mutationsForCurrentMapOperatorSubject = [];
1587
- const removeMutation = (mutation) => {
1588
- mutationsForCurrentMapOperatorSubject = mutationsForCurrentMapOperatorSubject.filter(
1589
- (item) => item !== mutation
1354
+ ve(
1355
+ ({ result: o, error: m }) => (o == null ? void 0 : o.data) === void 0 && m === void 0,
1356
+ !0
1357
+ )
1358
+ ))
1359
+ ), h = S({
1360
+ ...e,
1361
+ variables: t,
1362
+ status: "pending",
1363
+ isPaused: !1,
1364
+ failureCount: 0,
1365
+ failureReason: null,
1366
+ submittedAt: e.submittedAt ?? (/* @__PURE__ */ new Date()).getTime()
1367
+ });
1368
+ return E(
1369
+ h,
1370
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
1371
+ l.pipe(p((a) => ({ context: a }))),
1372
+ d.pipe(
1373
+ w(({ result: a, error: c, ...o }) => {
1374
+ if (!a && !c)
1375
+ return S({
1376
+ ...o
1377
+ });
1378
+ const m = c ? S(null) : V(
1379
+ () => {
1380
+ var v;
1381
+ return (v = r.onSuccess) == null ? void 0 : v.call(
1382
+ r,
1383
+ a == null ? void 0 : a.data,
1384
+ t,
1385
+ o.context
1386
+ );
1387
+ }
1388
+ ), b = V(
1389
+ () => {
1390
+ var v;
1391
+ return (v = r.onSettled) == null ? void 0 : v.call(
1392
+ r,
1393
+ a == null ? void 0 : a.data,
1394
+ c,
1395
+ t,
1396
+ o.context
1397
+ );
1398
+ }
1399
+ ).pipe(
1400
+ j((v) => a ? S(a) : S(v))
1590
1401
  );
1591
- mutationsSubject.next(
1592
- mutationsSubject.getValue().filter((item) => item !== mutation)
1402
+ return ie(m, b).pipe(
1403
+ ue(),
1404
+ p(
1405
+ () => c ? {
1406
+ error: c,
1407
+ data: void 0,
1408
+ variables: t,
1409
+ ...o
1410
+ } : {
1411
+ status: "success",
1412
+ error: c,
1413
+ data: a == null ? void 0 : a.data,
1414
+ variables: t,
1415
+ ...o
1416
+ }
1417
+ ),
1418
+ j(
1419
+ (v) => f(v, o.context, 0).pipe(
1420
+ p((O) => ({
1421
+ ...O,
1422
+ data: void 0
1423
+ }))
1424
+ )
1425
+ )
1593
1426
  );
1594
- };
1595
- return trigger$.pipe(
1596
- takeUntil(stableMapOperator$.pipe(skip(1))),
1597
- map(({ args, options }) => {
1598
- const mutation = new Mutation({
1599
- args,
1600
- ...options,
1601
- mapOperator
1602
- });
1603
- mutationsForCurrentMapOperatorSubject = [
1604
- ...mutationsForCurrentMapOperatorSubject,
1605
- mutation
1606
- ];
1607
- mutationsSubject.next([...mutationsSubject.getValue(), mutation]);
1608
- return mutation;
1609
- }),
1610
- switchOperator((mutation) => {
1611
- if (!mutationsSubject.getValue().includes(mutation))
1612
- return of({});
1613
- const queryIsOver$ = mutation.mutation$.pipe(
1614
- map(({ data, error }) => error || data)
1615
- );
1616
- const isThisCurrentFunctionLastOneCalled = trigger$.pipe(
1617
- take(1),
1618
- map(() => mapOperator === "concat"),
1619
- startWith(true),
1620
- takeUntil(queryIsOver$)
1621
- );
1622
- const result$ = combineLatest([
1623
- mutation.mutation$,
1624
- isThisCurrentFunctionLastOneCalled
1625
- ]).pipe(
1626
- map(([result, isLastMutationCalled]) => {
1627
- if ((result.status === "success" || result.status === "error") && !isLastMutationCalled) {
1628
- return {};
1629
- }
1630
- return result;
1631
- }),
1632
- takeUntil(cancel$.pipe()),
1633
- mergeResults,
1634
- finalize(() => {
1635
- removeMutation(mutation);
1636
- })
1637
- );
1638
- return result$;
1639
- }),
1640
- mergeResults,
1641
- __queryTriggerHook ?? identity
1642
- );
1643
- }),
1644
- __queryFinalizeHook ?? identity,
1645
- shareReplay(1)
1427
+ })
1428
+ )
1429
+ ).pipe(
1430
+ pe((a, c) => ({
1431
+ ...a,
1432
+ ...c,
1433
+ data: c.data ?? a.data,
1434
+ error: c.error ?? a.error
1435
+ }), W()),
1436
+ C(
1437
+ ({ data: a, ...c }, { data: o, ...m }) => M(c, m) && M(a, o)
1438
+ )
1646
1439
  );
1647
- cancel$.subscribe(() => {
1648
- if (mutationsSubject.getValue().length === 0)
1649
- return;
1650
- mutationsSubject.next([]);
1651
- });
1652
- return {
1653
- mutation$,
1654
- trigger: ({
1655
- args,
1656
- options
1657
- }) => {
1658
- mapOperator$.next(options.mapOperator);
1659
- trigger$.next({ args, options });
1660
- },
1661
- cancel$,
1662
- destroy,
1663
- mutationsSubject,
1664
- getClosed: () => closed
1665
- };
1666
1440
  };
1667
- const createPredicateForFilters = ({
1668
- mutationKey,
1669
- status,
1670
- predicate
1671
- } = {}) => {
1672
- const defaultPredicate = (mutation) => {
1673
- if (mutationKey !== void 0 && // @todo optimize
1674
- serializeKey(mutation.options.mutationKey) !== serializeKey(mutationKey)) {
1675
- return false;
1676
- }
1677
- if (status && mutation.state.status !== status)
1678
- return false;
1679
- return true;
1680
- };
1681
- const finalPredicate = predicate ?? defaultPredicate;
1682
- return finalPredicate;
1683
- };
1684
- class MutationResultObserver {
1685
- constructor(mutationRunnersByKey$) {
1686
- /**
1687
- * Mutation result subject. It can be used whether there is a mutation
1688
- * running or not and can be directly observed.
1689
- *
1690
- * @important
1691
- * - automatically cleaned as soon as the last mutation is done for a given key
1692
- */
1693
- __publicField(this, "mutationResults$", new BehaviorSubject(/* @__PURE__ */ new Map()));
1694
- mutationRunnersByKey$.pipe(
1695
- switchMap((mapItem) => {
1696
- const runners = Array.from(mapItem.values()).map((runner) => {
1697
- const serializedMutationKey = serializeKey(runner.mutationKey);
1698
- return runner.mutation$.pipe(
1699
- tap((result) => {
1700
- this.updateResultForKey({
1701
- serializedMutationKey,
1702
- result
1703
- });
1704
- }),
1705
- finalize(() => {
1706
- this.deleteResultForKey({ serializedMutationKey });
1707
- })
1708
- );
1709
- });
1710
- return merge(...runners);
1441
+ class tr {
1442
+ constructor({
1443
+ options: e,
1444
+ mutationCache: r,
1445
+ state: n
1446
+ }) {
1447
+ y(this, "mutationCache");
1448
+ y(this, "observerCount", new I(0));
1449
+ y(this, "destroySubject", new F());
1450
+ y(this, "resetSubject", new F());
1451
+ y(this, "executeSubject", new F());
1452
+ y(this, "state", W());
1453
+ y(this, "state$");
1454
+ y(this, "options");
1455
+ y(this, "observerCount$", this.observerCount.asObservable());
1456
+ y(this, "destroyed$", this.destroySubject.asObservable());
1457
+ this.options = e, this.mutationCache = r, this.state = n ?? this.state;
1458
+ const s = S(this.state), i = this.resetSubject.pipe(
1459
+ p(() => W())
1460
+ ), u = this.executeSubject.pipe(
1461
+ w(
1462
+ (l) => er({
1463
+ options: {
1464
+ ...this.options,
1465
+ onMutate: (f) => {
1466
+ const d = V(
1467
+ () => {
1468
+ var g, a;
1469
+ return (a = (g = r.config).onMutate) == null ? void 0 : a.call(
1470
+ g,
1471
+ f,
1472
+ this
1473
+ );
1474
+ }
1475
+ ), h = V(
1476
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
1477
+ () => {
1478
+ var g, a;
1479
+ return ((a = (g = this.options).onMutate) == null ? void 0 : a.call(g, f)) ?? void 0;
1480
+ }
1481
+ );
1482
+ return d.pipe(_(() => h));
1483
+ },
1484
+ onError: (f, d, h) => {
1485
+ const g = V(
1486
+ () => {
1487
+ var c, o;
1488
+ return (o = (c = r.config).onError) == null ? void 0 : o.call(
1489
+ c,
1490
+ f,
1491
+ d,
1492
+ h,
1493
+ this
1494
+ );
1495
+ }
1496
+ ), a = V(
1497
+ () => {
1498
+ var c, o;
1499
+ return (o = (c = this.options).onError) == null ? void 0 : o.call(c, f, d, h);
1500
+ }
1501
+ );
1502
+ return ie(g, a).pipe(ue());
1503
+ },
1504
+ onSettled: (f, d, h, g) => {
1505
+ const a = V(
1506
+ () => {
1507
+ var o, m;
1508
+ return (m = (o = r.config).onSettled) == null ? void 0 : m.call(
1509
+ o,
1510
+ f,
1511
+ d,
1512
+ h,
1513
+ g,
1514
+ this
1515
+ );
1516
+ }
1517
+ ), c = V(
1518
+ () => {
1519
+ var o, m;
1520
+ return (m = (o = this.options).onSettled) == null ? void 0 : m.call(o, f, d, h, g);
1521
+ }
1522
+ );
1523
+ return ie(a, c).pipe(ue());
1524
+ },
1525
+ onSuccess: (f, d, h) => {
1526
+ const g = V(
1527
+ () => {
1528
+ var c, o;
1529
+ return (o = (c = r.config).onSuccess) == null ? void 0 : o.call(
1530
+ c,
1531
+ f,
1532
+ d,
1533
+ h,
1534
+ this
1535
+ );
1536
+ }
1537
+ ), a = V(
1538
+ () => {
1539
+ var c, o;
1540
+ return (o = (c = this.options).onSuccess) == null ? void 0 : o.call(c, f, d, h);
1541
+ }
1542
+ );
1543
+ return ie(g, a).pipe(ue());
1544
+ }
1545
+ },
1546
+ state: this.state,
1547
+ variables: l
1548
+ })
1549
+ ),
1550
+ x((l) => {
1551
+ this.state = { ...this.state, ...l };
1552
+ }),
1553
+ P(this.destroySubject)
1554
+ );
1555
+ this.state$ = E(s, u, i).pipe(
1556
+ /**
1557
+ * refCount as true somewhat make NEVER complete when there are
1558
+ * no more observers. I thought I should have to complete manually (which is
1559
+ * why we still cancel the observable when we remove it from cache)
1560
+ */
1561
+ $e({ bufferSize: 1, refCount: !1 }),
1562
+ P(this.destroySubject),
1563
+ ke((l) => {
1564
+ this.observerCount.next(l);
1711
1565
  })
1712
- ).subscribe();
1566
+ );
1713
1567
  }
1714
- getDefaultResultValue() {
1715
- return {
1716
- ...getDefaultMutationState(),
1717
- isSuccess: false,
1718
- isPending: false,
1719
- isIdle: true,
1720
- isError: false
1721
- };
1568
+ get meta() {
1569
+ return this.options.meta;
1722
1570
  }
1723
- deleteResultForKey({
1724
- serializedMutationKey
1725
- }) {
1726
- const resultMap = this.mutationResults$.getValue();
1727
- resultMap.delete(serializedMutationKey);
1728
- this.mutationResults$.next(resultMap);
1571
+ setOptions(e) {
1572
+ this.options = { ...this.options, ...e };
1729
1573
  }
1730
- updateResultForKey({
1731
- serializedMutationKey,
1732
- result
1733
- }) {
1734
- const resultForKeySubject = this.mutationResults$.getValue().get(serializedMutationKey);
1735
- const valueForResult = {
1736
- ...this.getDefaultResultValue(),
1737
- ...result,
1738
- isSuccess: result.status === "success",
1739
- isPending: result.status === "pending",
1740
- isIdle: result.status === "idle",
1741
- isError: result.status === "error"
1742
- };
1743
- if (!resultForKeySubject) {
1744
- const resultMap = this.mutationResults$.getValue();
1745
- resultMap.set(
1746
- serializedMutationKey,
1747
- new BehaviorSubject(valueForResult)
1748
- );
1749
- this.mutationResults$.next(resultMap);
1750
- } else {
1751
- resultForKeySubject == null ? void 0 : resultForKeySubject.next(valueForResult);
1752
- }
1574
+ observeTillFinished() {
1575
+ return this.state$.pipe(
1576
+ ve(
1577
+ (e) => e.status !== "error" && e.status !== "success",
1578
+ !0
1579
+ )
1580
+ );
1753
1581
  }
1754
- observe({ key }) {
1755
- var _a;
1756
- const currentResultValue = (_a = this.mutationResults$.getValue().get(key)) == null ? void 0 : _a.getValue();
1757
- const lastValue = currentResultValue ?? this.getDefaultResultValue();
1758
- const result$ = this.mutationResults$.pipe(
1759
- switchMap((resultMap) => {
1760
- const subject = resultMap.get(key);
1761
- return subject ?? EMPTY;
1762
- })
1763
- ).pipe(filter(isDefined));
1764
- return { result$, lastValue };
1582
+ /**
1583
+ * @important
1584
+ * The resulting observable will complete as soon as the mutation
1585
+ * is over, unlike the state which can be re-subscribed later.
1586
+ */
1587
+ execute(e) {
1588
+ return this.executeSubject.next(e), this.executeSubject.complete(), this.observeTillFinished();
1589
+ }
1590
+ continue() {
1591
+ return this.execute(this.state.variables);
1765
1592
  }
1766
1593
  destroy() {
1767
- this.mutationResults$.complete();
1594
+ this.destroySubject.next(), this.destroySubject.complete(), this.executeSubject.complete();
1595
+ }
1596
+ reset() {
1597
+ this.resetSubject.next(), this.resetSubject.complete(), this.destroy();
1768
1598
  }
1769
1599
  }
1770
- class MutationClient {
1771
- constructor() {
1772
- /**
1773
- * Contain all active mutation for a given key.
1774
- * A mutation ca have several triggers running (it is not necessarily one function running)
1775
- *
1776
- * @important
1777
- * - automatically cleaned as soon as the last mutation is done for a given key
1778
- */
1779
- __publicField(this, "mutationRunnersByKey$", new BehaviorSubject(/* @__PURE__ */ new Map()));
1780
- __publicField(this, "mutate$", new Subject());
1781
- __publicField(this, "cancel$", new Subject());
1782
- /**
1783
- * Observable to track how many running mutations per runner
1784
- */
1785
- __publicField(this, "isMutatingSubject", new BehaviorSubject([]));
1786
- /**
1787
- * List of all mutations running
1788
- */
1789
- __publicField(this, "mutationsSubject", new BehaviorSubject([]));
1790
- __publicField(this, "mutationResultObserver", new MutationResultObserver(
1791
- this.mutationRunnersByKey$
1600
+ const he = ({
1601
+ mutationKey: t,
1602
+ status: e,
1603
+ predicate: r,
1604
+ exact: n = !0
1605
+ } = {}) => (i) => n && t !== void 0 && i.options.mutationKey !== void 0 && !oe(i.options.mutationKey, t, { exact: n }) || !n && t !== void 0 && i.options.mutationKey !== void 0 && !oe(t, i.options.mutationKey, { exact: n }) || e && i.state.status !== e ? !1 : r ? r(i) : !0;
1606
+ class rr {
1607
+ constructor(e = {}) {
1608
+ y(this, "mutationsSubject", new I([]));
1609
+ y(this, "mutations$", this.mutationsSubject.pipe(
1610
+ p((e) => e.map((r) => r)),
1611
+ C(Le),
1612
+ J()
1792
1613
  ));
1793
- this.mutate$.pipe(
1794
- tap(({ options, args }) => {
1795
- const { mutationKey } = options;
1796
- const serializedMutationKey = serializeKey(mutationKey);
1797
- let mutationForKey = this.getMutationRunnersByKey(
1798
- serializedMutationKey
1799
- );
1800
- if (!mutationForKey) {
1801
- mutationForKey = {
1802
- ...createMutationRunner(options),
1803
- mutationKey
1804
- };
1805
- this.setMutationRunnersByKey(serializedMutationKey, mutationForKey);
1806
- mutationForKey.mutation$.subscribe();
1807
- mutationForKey.mutationsSubject.pipe(
1808
- distinctUntilChanged(shallowEqual),
1809
- skip(1),
1810
- filter((items) => items.length === 0)
1811
- ).subscribe(() => {
1812
- mutationForKey == null ? void 0 : mutationForKey.destroy();
1813
- this.deleteMutationRunnersByKey(serializedMutationKey);
1814
- });
1815
- }
1816
- mutationForKey.trigger({ args, options });
1817
- })
1818
- ).subscribe();
1819
- this.cancel$.pipe(
1820
- tap(({ key }) => {
1821
- var _a;
1822
- const serializedKey = serializeKey(key);
1823
- (_a = this.mutationRunnersByKey$.getValue().get(serializedKey)) == null ? void 0 : _a.cancel$.next();
1824
- })
1825
- ).subscribe();
1826
- this.mutationRunnersByKey$.pipe(
1827
- switchMap((mapItem) => {
1828
- const mutationRunners = Array.from(mapItem.values());
1829
- const mutations$ = combineLatest(
1830
- mutationRunners.map(
1831
- (runner) => runner.mutationsSubject.pipe(
1832
- map((mutations) => mutations.map((mutation) => mutation))
1614
+ y(this, "added$", this.mutations$.pipe(
1615
+ ce(),
1616
+ p(
1617
+ ([e, r]) => r.filter((n) => !e.includes(n))[0]
1618
+ ),
1619
+ $(G),
1620
+ J()
1621
+ ));
1622
+ y(this, "removed$", this.mutations$.pipe(
1623
+ ce(),
1624
+ p(
1625
+ ([e, r]) => e.filter((n) => !r.includes(n))
1626
+ ),
1627
+ _((e) => re(e)),
1628
+ J()
1629
+ ));
1630
+ y(this, "stateChange$", this.added$.pipe(
1631
+ _(
1632
+ (e) => e.state$.pipe(
1633
+ p(() => e),
1634
+ P(
1635
+ this.removed$.pipe(
1636
+ $((r) => r === e)
1833
1637
  )
1834
1638
  )
1639
+ )
1640
+ ),
1641
+ J()
1642
+ ));
1643
+ this.config = e;
1644
+ }
1645
+ build(e, r, n) {
1646
+ const s = new tr({
1647
+ mutationCache: this,
1648
+ options: e.defaultMutationOptions(r),
1649
+ state: n
1650
+ });
1651
+ return s.state$.pipe(
1652
+ /**
1653
+ * Once a mutation is finished and there are no more observers than us
1654
+ * we start the process of cleaning it up based on gc settings
1655
+ */
1656
+ $(({ status: i }) => i === "success" || i === "error"),
1657
+ w(
1658
+ () => s.observerCount$.pipe(
1659
+ $((i) => i <= 1),
1660
+ be(1)
1661
+ )
1662
+ ),
1663
+ // defaults to 5mn
1664
+ w(() => se(s.options.gcTime ?? 5 * 60 * 1e3)),
1665
+ be(1)
1666
+ ).subscribe({
1667
+ complete: () => {
1668
+ this.mutationsSubject.next(
1669
+ this.mutationsSubject.getValue().filter((i) => s !== i)
1835
1670
  );
1836
- return mutations$.pipe(
1837
- map(
1838
- (mutationsByKeys) => mutationsByKeys.reduce((acc, value) => [...acc, ...value], [])
1839
- )
1840
- );
1841
- }),
1842
- startWith([]),
1843
- distinctUntilChanged(shallowEqual)
1844
- ).subscribe(this.mutationsSubject);
1671
+ }
1672
+ }), this.mutationsSubject.next([...this.mutationsSubject.getValue(), s]), s;
1845
1673
  }
1846
- /**
1847
- * @helper
1848
- */
1849
- setMutationRunnersByKey(key, value) {
1850
- const map2 = this.mutationRunnersByKey$.getValue();
1851
- map2.set(key, value);
1852
- this.mutationRunnersByKey$.next(map2);
1674
+ getAll() {
1675
+ return this.findAll();
1853
1676
  }
1854
- /**
1855
- * @helper
1856
- */
1857
- deleteMutationRunnersByKey(key) {
1858
- const map2 = this.mutationRunnersByKey$.getValue();
1859
- map2.delete(key);
1860
- this.mutationRunnersByKey$.next(map2);
1677
+ remove(e) {
1678
+ const r = this.mutationsSubject.getValue().find((n) => n === e);
1679
+ r == null || r.destroy();
1861
1680
  }
1862
- /**
1863
- * @helper
1864
- */
1865
- getMutationRunnersByKey(key) {
1866
- return this.mutationRunnersByKey$.getValue().get(key);
1681
+ find(e) {
1682
+ const r = { exact: !0, ...e }, n = he(r);
1683
+ return this.mutationsSubject.getValue().find((s) => n(s));
1867
1684
  }
1868
- useIsMutating(filters = {}) {
1869
- const predicate = createPredicateForFilters(filters);
1870
- const reduceByNumber = (entries) => entries.reduce((acc, mutation) => {
1871
- return predicate(mutation) && mutation.state.status === "pending" ? 1 + acc : acc;
1872
- }, 0);
1873
- const lastValue = reduceByNumber(this.mutationsSubject.getValue());
1874
- const value$ = this.mutationsSubject.pipe(
1875
- switchMap((mutations) => {
1876
- const mutationsOnStateUpdate = mutations.map(
1877
- (mutation) => mutation.stateSubject.pipe(map(() => mutation))
1878
- );
1879
- return mutationsOnStateUpdate.length === 0 ? of([]) : combineLatest(mutationsOnStateUpdate);
1880
- }),
1881
- map(reduceByNumber),
1882
- distinctUntilChanged()
1883
- );
1884
- return { value$, lastValue };
1685
+ findAll(e = {}) {
1686
+ const r = { exact: !0, ...e }, n = he(r);
1687
+ return this.mutationsSubject.getValue().filter((s) => n(s)).map((s) => s);
1885
1688
  }
1886
- mutationState({
1887
- filters,
1888
- select
1689
+ observe({
1690
+ filters: e,
1691
+ select: r
1889
1692
  } = {}) {
1890
- const predicate = createPredicateForFilters(filters);
1891
- const finalSelect = select ?? ((mutation) => mutation.state);
1892
- const lastValue = this.mutationsSubject.getValue().reduce((acc, mutation) => {
1893
- const result = [...acc, mutation];
1894
- return result;
1895
- }, []).filter(predicate).map((mutation) => finalSelect(mutation));
1896
- const value$ = this.mutationsSubject.pipe(
1897
- switchMap((mutations) => {
1898
- const mutationsOnStateUpdate = mutations.map(
1899
- (mutation) => mutation.stateSubject.pipe(
1900
- filter(() => predicate(mutation)),
1901
- map(() => finalSelect(mutation))
1902
- )
1903
- );
1904
- return mutationsOnStateUpdate.length === 0 ? of([]) : combineLatest(mutationsOnStateUpdate);
1905
- }),
1906
- distinctUntilChanged(shallowEqual)
1907
- );
1908
- return { value$, lastValue };
1909
- }
1910
- mutate(params) {
1911
- this.mutate$.next(params);
1693
+ const n = he(e), s = r ?? ((l) => l.state), i = this.getAll().reduce((l, f) => [...l, f], []).filter(n).map((l) => s(l));
1694
+ return { value$: this.stateChange$.pipe(
1695
+ Ie(),
1696
+ p(() => this.getAll().filter(n).map(s)),
1697
+ C(M)
1698
+ ), lastValue: i };
1912
1699
  }
1913
1700
  /**
1914
- * This will cancel any current mutation runnings.
1915
- * No discrimination process
1701
+ * @important
1702
+ * ISO api react-query
1916
1703
  */
1917
- cancel(params) {
1918
- this.cancel$.next(params);
1704
+ subscribe(e) {
1705
+ const r = E(
1706
+ this.added$.pipe(
1707
+ x((n) => {
1708
+ e({
1709
+ type: "added",
1710
+ mutation: n
1711
+ });
1712
+ })
1713
+ ),
1714
+ this.removed$.pipe(
1715
+ x((n) => {
1716
+ e({
1717
+ type: "removed",
1718
+ mutation: n
1719
+ });
1720
+ })
1721
+ ),
1722
+ this.stateChange$.pipe(
1723
+ x((n) => {
1724
+ e({
1725
+ type: "updated",
1726
+ action: {
1727
+ ...n.state,
1728
+ type: "success"
1729
+ },
1730
+ mutation: n
1731
+ });
1732
+ })
1733
+ )
1734
+ ).subscribe();
1735
+ return () => {
1736
+ r.unsubscribe();
1737
+ };
1919
1738
  }
1920
- destroy() {
1921
- this.cancel$.complete();
1922
- this.mutate$.complete();
1923
- this.mutationResultObserver.destroy();
1924
- this.mutationRunnersByKey$.complete();
1925
- this.isMutatingSubject.complete();
1926
- this.mutationsSubject.complete();
1739
+ resumePausedMutations() {
1740
+ const e = this.findAll({
1741
+ predicate: (n) => n.state.isPaused
1742
+ });
1743
+ if (!e.length)
1744
+ return T;
1745
+ const r = e.map((n) => n.continue());
1746
+ return Fe(r);
1747
+ }
1748
+ clear() {
1749
+ this.getAll().forEach((e) => {
1750
+ this.remove(e);
1751
+ });
1927
1752
  }
1928
1753
  }
1929
- const createClient = () => {
1930
- const queryStore = createQueryStore();
1931
- const invalidationClient = createInvalidationClient({ queryStore });
1932
- const cacheClient = createCacheClient({ queryStore });
1933
- const refetchClient = createRefetchClient();
1934
- const mutationClient = new MutationClient();
1935
- let hasCalledStart = false;
1936
- const query = ({
1937
- key,
1938
- fn$: maybeFn$,
1939
- fn: maybeFn,
1940
- trigger$: externalTrigger$ = new Subject(),
1941
- options$ = new BehaviorSubject({})
1754
+ const nr = () => {
1755
+ const t = It(), e = kt({ queryStore: t }), r = Xt({ queryStore: t }), n = Lt();
1756
+ let s = !1;
1757
+ const i = ({
1758
+ key: d,
1759
+ fn$: h,
1760
+ fn: g,
1761
+ trigger$: a = new F(),
1762
+ options$: c = new I({})
1942
1763
  }) => {
1943
- if (!hasCalledStart) {
1764
+ if (!s)
1944
1765
  throw new Error("You forgot to start client");
1945
- }
1946
- const serializedKey = serializeKey(key);
1947
- const fn$ = maybeFn$ ?? (maybeFn ? of(maybeFn) : NEVER);
1948
- Logger.log("query$)", serializedKey);
1949
- const runner$ = options$.pipe(map((options) => ({ options })));
1950
- let deleteRunner = () => {
1766
+ const o = N(d), m = h ?? (g ? S(g) : Qe);
1767
+ X.log("query$)", o);
1768
+ const R = c.pipe(p((O) => ({ options: O })));
1769
+ let b = () => {
1951
1770
  };
1952
- const trigger$ = merge(
1953
- externalTrigger$.pipe(
1954
- dispatchExternalRefetchToAllQueries({
1955
- queryStore,
1956
- serializedKey
1957
- })
1958
- ),
1959
- createQueryTrigger({
1960
- options$,
1961
- key: serializedKey,
1962
- queryStore
1963
- })
1964
- ).pipe(share());
1965
- const result$ = merge(
1966
- of({
1967
- type: "initial"
1968
- }),
1969
- trigger$
1970
- ).pipe(
1971
- updateStoreWithNewQuery({
1972
- key,
1973
- queryStore,
1974
- runner$,
1975
- serializedKey,
1976
- options$
1977
- }),
1978
- map(([value, deleteRunnerFn]) => {
1979
- if (deleteRunnerFn) {
1980
- deleteRunner = deleteRunnerFn;
1981
- }
1982
- return value;
1983
- }),
1984
- markQueryAsStaleIfRefetch({
1985
- key,
1986
- options$,
1987
- queryStore,
1988
- serializedKey
1989
- }),
1990
- withLatestFrom(fn$, options$),
1991
- map(([trigger2, fn, options]) => ({ trigger: trigger2, fn, options })),
1992
- map((value) => {
1993
- Logger.log(serializedKey, "query trigger", {
1994
- trigger: value.trigger,
1995
- options: value.options
1996
- });
1997
- return value;
1998
- }),
1999
- filter(({ options }) => options.enabled !== false),
2000
- mergeMap(
2001
- ({ fn, options, trigger: trigger2 }) => createQueryFetch({
2002
- options$,
2003
- options,
2004
- fn,
2005
- queryStore,
2006
- serializedKey,
2007
- trigger: trigger2,
2008
- trigger$
1771
+ const A = E(
1772
+ a.pipe(
1773
+ Bt({
1774
+ queryStore: t,
1775
+ serializedKey: o
2009
1776
  })
2010
1777
  ),
2011
- mergeResults$1,
2012
- withLatestFrom(options$),
2013
- takeWhile(([result, options]) => {
2014
- const shouldStop = result.data !== void 0 && options.terminateOnFirstResult;
2015
- return !shouldStop;
2016
- }, true),
2017
- map(([result]) => result),
2018
- finalize(() => {
2019
- deleteRunner();
1778
+ Qt({
1779
+ options$: c,
1780
+ key: o,
1781
+ queryStore: t
2020
1782
  })
2021
- );
1783
+ ).pipe(J());
2022
1784
  return {
2023
- result$
1785
+ result$: E(
1786
+ S({
1787
+ type: "initial"
1788
+ }),
1789
+ A
1790
+ ).pipe(
1791
+ Ht({
1792
+ key: d,
1793
+ queryStore: t,
1794
+ runner$: R,
1795
+ serializedKey: o,
1796
+ options$: c
1797
+ }),
1798
+ p(([O, Q]) => (Q && (b = Q), O)),
1799
+ qt({
1800
+ key: d,
1801
+ options$: c,
1802
+ queryStore: t,
1803
+ serializedKey: o
1804
+ }),
1805
+ D(m, c),
1806
+ p(([O, Q, z]) => ({ trigger: O, fn: Q, options: z })),
1807
+ p((O) => (X.log(o, "query trigger", {
1808
+ trigger: O.trigger,
1809
+ options: O.options
1810
+ }), O)),
1811
+ $(({ options: O }) => O.enabled !== !1),
1812
+ _(
1813
+ ({ fn: O, options: Q, trigger: z }) => Nt({
1814
+ options$: c,
1815
+ options: Q,
1816
+ fn: O,
1817
+ queryStore: t,
1818
+ serializedKey: o,
1819
+ trigger: z,
1820
+ trigger$: A
1821
+ })
1822
+ ),
1823
+ xt,
1824
+ D(c),
1825
+ ve(([O, Q]) => !(O.data !== void 0 && Q.terminateOnFirstResult), !0),
1826
+ p(([O]) => O),
1827
+ ae(() => {
1828
+ b();
1829
+ })
1830
+ )
2024
1831
  };
2025
- };
2026
- const queryListener$ = createQueryListener(
2027
- queryStore,
2028
- (stream) => stream.pipe(
2029
- switchMap((key) => {
2030
- const key$ = of(key);
2031
- return merge(
2032
- invalidateCache({
2033
- queryStore
2034
- })(key$),
2035
- markAsStale({
2036
- queryStore
2037
- })(key$),
2038
- garbageCache({
2039
- queryStore
2040
- })(key$)
1832
+ }, u = At(
1833
+ t,
1834
+ (d) => d.pipe(
1835
+ w((h) => {
1836
+ const g = S(h);
1837
+ return E(
1838
+ Yt({
1839
+ queryStore: t
1840
+ })(g),
1841
+ zt({
1842
+ queryStore: t
1843
+ })(g),
1844
+ Gt({
1845
+ queryStore: t
1846
+ })(g)
2041
1847
  );
2042
1848
  })
2043
1849
  )
2044
1850
  );
2045
- const start = () => {
2046
- hasCalledStart = true;
2047
- const queryListenerSub = queryListener$.subscribe();
2048
- const started = [queryStore.start()];
2049
- return () => {
2050
- started.forEach((destroy2) => {
2051
- destroy2();
2052
- });
2053
- queryListenerSub.unsubscribe();
2054
- };
2055
- };
2056
- const destroy = () => {
2057
- mutationClient.destroy();
2058
- };
2059
1851
  return {
2060
- start,
2061
- query,
2062
- queryStore,
2063
- mutationClient,
2064
- ...invalidationClient,
2065
- ...cacheClient,
2066
- ...refetchClient,
2067
- destroy
1852
+ start: () => {
1853
+ s = !0;
1854
+ const d = u.subscribe(), h = [t.start()];
1855
+ return () => {
1856
+ h.forEach((g) => {
1857
+ g();
1858
+ }), d.unsubscribe();
1859
+ };
1860
+ },
1861
+ query: i,
1862
+ queryStore: t,
1863
+ ...e,
1864
+ ...r,
1865
+ ...n,
1866
+ destroy: () => {
1867
+ }
2068
1868
  };
2069
1869
  };
2070
- class QueryClient {
2071
- constructor() {
2072
- __publicField(this, "client");
2073
- this.client = createClient();
1870
+ var te;
1871
+ class Sr {
1872
+ constructor({ mutationCache: e } = {
1873
+ mutationCache: new rr()
1874
+ }) {
1875
+ y(this, "client");
1876
+ y(this, "mutationCache");
1877
+ de(this, te, /* @__PURE__ */ new Map());
1878
+ this.mutationCache = e, this.client = nr();
1879
+ }
1880
+ mount() {
1881
+ const e = this.client.start();
1882
+ return () => {
1883
+ e();
1884
+ };
1885
+ }
1886
+ getMutationCache() {
1887
+ return this.mutationCache;
1888
+ }
1889
+ defaultMutationOptions(e) {
1890
+ return {
1891
+ ...(e == null ? void 0 : e.mutationKey) && this.getMutationDefaults(e.mutationKey),
1892
+ ...e
1893
+ };
1894
+ }
1895
+ getMutationDefaults(e) {
1896
+ const r = [...k(this, te).values()];
1897
+ let n = {};
1898
+ return r.forEach((s) => {
1899
+ oe(e, s.mutationKey) && (n = { ...n, ...s.defaultOptions });
1900
+ }), n;
1901
+ }
1902
+ setMutationDefaults(e, r) {
1903
+ k(this, te).set(N(e), {
1904
+ mutationKey: e,
1905
+ defaultOptions: r
1906
+ });
1907
+ }
1908
+ async resumePausedMutations() {
1909
+ return await nt(this.mutationCache.resumePausedMutations());
1910
+ }
1911
+ clear() {
2074
1912
  }
2075
1913
  }
1914
+ te = new WeakMap();
2076
1915
  export {
2077
- QueryClient,
2078
- QueryClientProvider,
2079
- SIGNAL_RESET,
2080
- createClient,
2081
- createLocalforageAdapter,
2082
- createSharedStoreAdapter,
2083
- exponentialBackoffDelay,
2084
- getDelay,
2085
- retryBackoff,
2086
- signal,
2087
- trigger,
2088
- useBehaviorSubject,
2089
- useLiveRef,
2090
- useMutation,
2091
- useObserve,
2092
- useObserveCallback,
2093
- usePersistSignals,
2094
- useQuery,
2095
- useQueryClient,
2096
- useSignalValue,
2097
- useSubject,
2098
- useSubscribe,
2099
- useSubscribeEffect,
2100
- useUnmountObservable
1916
+ rr as MutationCache,
1917
+ Sr as QueryClient,
1918
+ br as QueryClientProvider,
1919
+ pt as SIGNAL_RESET,
1920
+ nr as createClient,
1921
+ hr as createLocalforageAdapter,
1922
+ dr as createSharedStoreAdapter,
1923
+ bt as exponentialBackoffDelay,
1924
+ mt as getDelay,
1925
+ yt as retryBackoff,
1926
+ pr as signal,
1927
+ lr as trigger,
1928
+ lt as useBehaviorSubject,
1929
+ U as useLiveRef,
1930
+ yr as useMutation,
1931
+ fe as useObserve,
1932
+ ar as useObserveCallback,
1933
+ gr as usePersistSignals,
1934
+ $r as useQuery,
1935
+ Pe as useQueryClient,
1936
+ fr as useSignalValue,
1937
+ Ee as useSubject,
1938
+ Se as useSubscribe,
1939
+ vr as useSubscribeEffect,
1940
+ mr as useUnmountObservable
2101
1941
  };