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