reactjrx 1.61.0 → 1.65.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/index.cjs +667 -342
  2. package/dist/index.d.ts +1 -0
  3. package/dist/index.js +662 -337
  4. package/dist/lib/queries/client/createClient.d.ts +14 -3
  5. package/dist/lib/queries/client/mutations/Mutation.d.ts +23 -11
  6. package/dist/lib/queries/client/mutations/cache/MutationCache.d.ts +43 -0
  7. package/dist/lib/queries/client/mutations/cache/mutationCache.test.d.ts +1 -0
  8. package/dist/lib/queries/client/mutations/cache/types.d.ts +61 -0
  9. package/dist/lib/queries/client/mutations/defaultMutationState.d.ts +1 -1
  10. package/dist/lib/queries/client/mutations/filters.d.ts +1 -1
  11. package/dist/lib/queries/client/mutations/observers/MutationObserver.d.ts +25 -0
  12. package/dist/lib/queries/client/mutations/observers/mutationObserver.test.d.ts +1 -0
  13. package/dist/lib/queries/client/mutations/observers/types.d.ts +59 -0
  14. package/dist/lib/queries/client/mutations/operators.d.ts +2 -2
  15. package/dist/lib/queries/client/mutations/runners/MutationRunner.d.ts +19 -0
  16. package/dist/lib/queries/client/mutations/runners/MutationRunners.d.ts +54 -0
  17. package/dist/lib/queries/client/mutations/types.d.ts +21 -23
  18. package/dist/lib/queries/client/tests/utils.d.ts +4 -0
  19. package/dist/lib/queries/client/utils/functionAsObservable.d.ts +2 -0
  20. package/dist/lib/queries/client/utils/wrapInPromise.d.ts +3 -0
  21. package/dist/lib/queries/react/Provider.d.ts +3 -71
  22. package/dist/lib/queries/react/mutations/useIsMutating.d.ts +1 -1
  23. package/dist/lib/queries/react/mutations/useMutation.cancel.test.d.ts +1 -0
  24. package/dist/lib/queries/react/mutations/useMutation.d.ts +10 -7
  25. package/dist/lib/queries/react/mutations/useMutationState.d.ts +2 -1
  26. package/dist/lib/queries/react/{helpers.d.ts → queries/helpers.d.ts} +5 -5
  27. package/dist/lib/queries/react/{types.d.ts → queries/types.d.ts} +1 -1
  28. package/dist/lib/queries/react/queries/useQuery.d.ts +1 -1
  29. package/dist/lib/queries/react/triggers/activityTrigger.d.ts +1 -1
  30. package/dist/lib/queries/react/triggers/networkTrigger.d.ts +1 -1
  31. package/dist/tests/utils.d.ts +4 -1
  32. package/package.json +2 -1
  33. package/dist/lib/queries/client/mutations/MutationClient.d.ts +0 -103
  34. package/dist/lib/queries/client/mutations/createMutationRunner.d.ts +0 -15
  35. /package/dist/lib/queries/{react → client}/keys/nanoid.d.ts +0 -0
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ var __publicField = (obj, key, value) => {
5
5
  return value;
6
6
  };
7
7
  import { useRef, useMemo, useCallback, useSyncExternalStore, useEffect, createContext, memo, useContext } from "react";
8
- import { distinctUntilChanged, tap, finalize, catchError, EMPTY, Subject, identity, BehaviorSubject, map, of, zip, merge, throttleTime, asyncScheduler, switchMap, from, defer, iif, timer, throwError, fromEvent, filter, skip, withLatestFrom, scan, retry, shareReplay, endWith, delay, take, takeUntil, share, startWith, pairwise, mergeMap, NEVER, combineLatest, concatMap as concatMap$1, takeWhile } from "rxjs";
8
+ import { distinctUntilChanged, tap, finalize, catchError, EMPTY, Subject, identity, BehaviorSubject, map, of, zip, merge, throttleTime, asyncScheduler, switchMap, from, defer, iif, timer, throwError, fromEvent, filter, skip, withLatestFrom, scan, retry, shareReplay, endWith, delay, take, takeUntil, share, startWith, pairwise, mergeMap, NEVER, combineLatest, concatMap as concatMap$1, last, Observable, concat, toArray, takeWhile } from "rxjs";
9
9
  import { retryWhen, concatMap, tap as tap$1 } from "rxjs/operators";
10
10
  import { jsxs, jsx } from "react/jsx-runtime";
11
11
  const useLiveRef = (value) => {
@@ -72,6 +72,7 @@ function useObserve(source$, unsafeOptions, unsafeDeps) {
72
72
  sub.unsubscribe();
73
73
  };
74
74
  },
75
+ // eslint-disable-next-line react-hooks/exhaustive-deps
75
76
  [...deps]
76
77
  );
77
78
  const getSnapshot = useCallback(() => {
@@ -98,7 +99,12 @@ function useSubscribe(source, deps = []) {
98
99
  return () => {
99
100
  sub.unsubscribe();
100
101
  };
101
- }, [...deps, sourceAsObservable]);
102
+ }, [
103
+ // eslint-disable-next-line react-hooks/exhaustive-deps
104
+ ...deps,
105
+ sourceAsObservable,
106
+ sourceRef
107
+ ]);
102
108
  }
103
109
  const useConstant = (fn) => {
104
110
  const ref = useRef();
@@ -136,7 +142,7 @@ const useSubject = ({
136
142
  completed.current = true;
137
143
  }
138
144
  };
139
- }, []);
145
+ }, [completeOnUnmountRef, onBeforeCompleteRef, subject]);
140
146
  return subject;
141
147
  };
142
148
  const useObserveCallback = (callback, deps) => {
@@ -144,7 +150,7 @@ const useObserveCallback = (callback, deps) => {
144
150
  useSubscribe(() => callback(trigger$.current), [trigger$, ...deps]);
145
151
  const trigger2 = useCallback((arg) => {
146
152
  trigger$.current.next(arg);
147
- }, []);
153
+ }, [trigger$]);
148
154
  return [trigger2, trigger$];
149
155
  };
150
156
  function trigger(mapper = identity) {
@@ -159,9 +165,10 @@ function trigger(mapper = identity) {
159
165
  const useBehaviorSubject = (state) => {
160
166
  const subject = useConstant(() => new BehaviorSubject(state));
161
167
  const completed = useRef(false);
168
+ const stateRef = useRef(state);
162
169
  useEffect(() => {
163
170
  if (completed.current) {
164
- subject.current = new BehaviorSubject(state);
171
+ subject.current = new BehaviorSubject(stateRef.current);
165
172
  completed.current = false;
166
173
  }
167
174
  return () => {
@@ -170,7 +177,7 @@ const useBehaviorSubject = (state) => {
170
177
  completed.current = true;
171
178
  }
172
179
  };
173
- }, []);
180
+ }, [subject]);
174
181
  return subject;
175
182
  };
176
183
  const SIGNAL_RESET = Symbol("SIGNAL_RESET");
@@ -399,27 +406,27 @@ function retryBackoff(config) {
399
406
  const Context = createContext({
400
407
  client: null
401
408
  });
402
- const ClientEffect = ({
403
- client
404
- }) => {
409
+ const ClientEffect = ({ client }) => {
405
410
  useEffect(() => {
406
- const destroy = client.start();
411
+ const stop = client.mount();
407
412
  return () => {
408
- destroy();
413
+ stop();
409
414
  };
410
415
  }, [client]);
411
416
  return null;
412
417
  };
413
418
  const QueryClientProvider = memo(
414
419
  ({ children, client }) => {
415
- const value = useMemo(() => ({ client: client.client }), [client]);
420
+ const value = useMemo(() => ({ client }), [client]);
416
421
  return /* @__PURE__ */ jsxs(Context.Provider, { value, children: [
417
422
  /* @__PURE__ */ jsx(ClientEffect, { client: value.client }),
418
423
  children
419
424
  ] });
420
425
  }
421
426
  );
422
- const useQueryClient = ({ unsafe = false } = {}) => {
427
+ const useQueryClient = ({
428
+ unsafe = false
429
+ } = {}) => {
423
430
  const context = useContext(Context);
424
431
  if (!unsafe && context.client === null) {
425
432
  throw new Error("You forgot to register the provider");
@@ -456,43 +463,51 @@ const nanoid = (size = 21) => crypto.getRandomValues(new Uint8Array(size)).reduc
456
463
  }
457
464
  return id;
458
465
  }, "");
466
+ function noop() {
467
+ }
459
468
  function useMutation(options, queryClient) {
460
469
  const defaultQueryClient = useQueryClient({ unsafe: !!queryClient });
461
- const finalQueryClient = (queryClient == null ? void 0 : queryClient.client) ?? defaultQueryClient;
470
+ const finalQueryClient = queryClient ?? defaultQueryClient;
462
471
  const optionsRef = useLiveRef(options);
463
472
  const defaultKey = useConstant(() => [nanoid()]);
464
- const key = serializeKey(options.mutationKey ?? defaultKey.current);
465
- const observedMutation = useMemo(
466
- () => finalQueryClient.mutationClient.observe({ key }),
467
- [key]
468
- );
473
+ const serializedKey = serializeKey(options.mutationKey ?? defaultKey.current);
474
+ const mutationsToCancel = useRef([]);
475
+ const observedMutation = useMemo(() => {
476
+ return finalQueryClient.mutationObserver.observeBy({
477
+ mutationKey: optionsRef.current.mutationKey ?? defaultKey.current
478
+ });
479
+ }, [serializedKey, defaultKey, finalQueryClient, optionsRef]);
469
480
  const result = useObserve(observedMutation.result$) ?? observedMutation.lastValue;
470
481
  const mutate = useCallback(
471
482
  (mutationArgs) => {
472
- finalQueryClient.mutationClient.mutate({
483
+ finalQueryClient.mutationRunners.mutate({
473
484
  options: {
474
485
  ...optionsRef.current,
475
486
  mutationKey: optionsRef.current.mutationKey ?? defaultKey.current
476
487
  },
477
488
  args: mutationArgs
489
+ }).catch(noop);
490
+ const mutation = finalQueryClient.getMutationCache().findLatest({
491
+ mutationKey: optionsRef.current.mutationKey ?? defaultKey.current
478
492
  });
493
+ if (mutation) {
494
+ mutationsToCancel.current.push(mutation);
495
+ }
479
496
  },
480
- [finalQueryClient, key]
497
+ [finalQueryClient, serializedKey, defaultKey, optionsRef]
481
498
  );
482
499
  const cancel = useCallback(() => {
483
- finalQueryClient.mutationClient.cancel({
484
- key: optionsRef.current.mutationKey ?? defaultKey.current
500
+ mutationsToCancel.current.forEach((mutation) => {
501
+ mutation.cancel();
485
502
  });
486
- }, [finalQueryClient]);
503
+ }, []);
487
504
  useEffect(() => {
488
505
  return () => {
489
506
  if (optionsRef.current.cancelOnUnMount) {
490
- finalQueryClient.mutationClient.cancel({
491
- key: optionsRef.current.mutationKey ?? defaultKey.current
492
- });
507
+ cancel();
493
508
  }
494
509
  };
495
- }, []);
510
+ }, [cancel, optionsRef]);
496
511
  return { mutate, cancel, ...result };
497
512
  }
498
513
  const arrayEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
@@ -568,7 +583,7 @@ const useQueryParams = ({
568
583
  options,
569
584
  queryFn
570
585
  });
571
- }, [queryKey, options, queryFn]);
586
+ }, [queryKey, options, queryFn, params$]);
572
587
  return params$;
573
588
  };
574
589
  const defaultValue = {
@@ -620,7 +635,7 @@ function useQuery({
620
635
  return newQueryTrigger$.pipe(
621
636
  withLatestFrom(key$),
622
637
  switchMap(([, key]) => {
623
- const { result$ } = client.query({
638
+ const { result$ } = client.client.query({
624
639
  key,
625
640
  fn$,
626
641
  options$,
@@ -662,7 +677,7 @@ function useQuery({
662
677
  );
663
678
  const refetch = useCallback(() => {
664
679
  internalRefresh$.current.next({ type: "refetch", ignoreStale: true });
665
- }, [client]);
680
+ }, [internalRefresh$]);
666
681
  return { ...result, refetch };
667
682
  }
668
683
  function useSubscribeEffect(source, unsafeOptions, deps = []) {
@@ -681,7 +696,7 @@ function useSubscribeEffect(source, unsafeOptions, deps = []) {
681
696
  }),
682
697
  retryOption ? retry() : identity
683
698
  ),
684
- [makeObservable]
699
+ [makeObservable, retryOption]
685
700
  );
686
701
  useSubscribe(enhancerMakeObservable, deps);
687
702
  }
@@ -1466,116 +1481,46 @@ const dispatchExternalRefetchToAllQueries = ({
1466
1481
  }),
1467
1482
  filter((trigger2) => trigger2.type !== "refetch")
1468
1483
  );
1469
- const mergeResults = (stream$) => stream$.pipe(
1470
- scan(
1471
- (acc, current) => {
1472
- return {
1473
- ...acc,
1474
- ...current,
1475
- data: current.data ?? acc.data,
1476
- error: current.error ?? acc.error
1477
- };
1478
- },
1479
- {
1480
- data: void 0,
1481
- error: void 0,
1482
- status: "pending"
1483
- }
1484
- ),
1485
- distinctUntilChanged(
1486
- ({ data: prevData, ...prev }, { data: currData, ...curr }) => shallowEqual(prev, curr) && shallowEqual(prevData, currData)
1487
- )
1488
- );
1489
1484
  const getDefaultMutationState = () => ({
1490
- context: {},
1485
+ context: void 0,
1491
1486
  data: void 0,
1492
1487
  error: null,
1493
1488
  status: "idle",
1494
1489
  submittedAt: 0,
1495
1490
  variables: void 0
1496
1491
  });
1497
- class Mutation {
1498
- constructor({
1499
- args,
1500
- ...options
1501
- }) {
1502
- __publicField(this, "stateSubject", new BehaviorSubject(
1503
- getDefaultMutationState()
1504
- ));
1505
- /**
1506
- * @important
1507
- * proxy for rect-query, not really useful
1508
- */
1509
- __publicField(this, "state", this.stateSubject.getValue());
1510
- __publicField(this, "options");
1511
- __publicField(this, "mutation$");
1512
- this.options = options;
1513
- const mutationFn = options.mutationFn;
1514
- this.state.variables = args;
1515
- this.stateSubject.next(this.state);
1516
- const mutationFnObservable = typeof mutationFn === "function" ? defer(() => from(mutationFn(args))) : mutationFn;
1517
- const queryRunner$ = mutationFnObservable.pipe(
1518
- retryOnError(options),
1519
- take(1),
1520
- map((data) => ({ data, isError: false })),
1521
- catchError((error) => {
1522
- console.error(error);
1523
- if (options.onError != null) {
1524
- options.onError(error, args);
1525
- }
1526
- return of({ data: error, isError: true });
1527
- })
1528
- );
1529
- const loading$ = of({
1530
- status: "pending"
1531
- });
1532
- this.mutation$ = merge(
1533
- loading$,
1534
- queryRunner$.pipe(
1535
- map(({ data, isError }) => {
1536
- if (!isError) {
1537
- if (options.onSuccess != null)
1538
- options.onSuccess(data, args);
1539
- }
1540
- return isError ? {
1541
- status: "error",
1542
- error: data,
1543
- data: void 0
1544
- } : {
1545
- status: "success",
1546
- error: null,
1547
- data
1548
- };
1549
- })
1550
- )
1551
- ).pipe(
1552
- mergeResults,
1553
- tap((value) => {
1554
- this.state = { ...this.state, ...value };
1555
- this.stateSubject.next(this.state);
1556
- }),
1557
- options.__queryRunnerHook ?? identity,
1558
- share()
1559
- );
1560
- }
1561
- }
1492
+ const mergeResults = (stream$) => stream$.pipe(
1493
+ scan((acc, current) => {
1494
+ return {
1495
+ ...acc,
1496
+ ...current,
1497
+ data: current.data ?? acc.data,
1498
+ error: current.error ?? acc.error
1499
+ };
1500
+ }, getDefaultMutationState()),
1501
+ distinctUntilChanged(
1502
+ ({ data: prevData, ...prev }, { data: currData, ...curr }) => shallowEqual(prev, curr) && shallowEqual(prevData, currData)
1503
+ )
1504
+ );
1562
1505
  const createMutationRunner = ({
1563
1506
  __queryFinalizeHook,
1564
1507
  __queryInitHook,
1565
- __queryTriggerHook
1508
+ __queryTriggerHook,
1509
+ mutationKey,
1510
+ mutationCache
1566
1511
  }) => {
1567
1512
  const trigger$ = new Subject();
1568
1513
  const cancel$ = new Subject();
1569
1514
  let closed = false;
1570
- const mapOperator$ = new BehaviorSubject("merge");
1571
- const mutationsSubject = new BehaviorSubject([]);
1515
+ const mapOperator$ = new BehaviorSubject(
1516
+ "merge"
1517
+ );
1572
1518
  const destroy = () => {
1573
1519
  if (closed) {
1574
1520
  throw new Error("Trying to close an already closed mutation");
1575
1521
  }
1576
1522
  closed = true;
1577
1523
  mapOperator$.complete();
1578
- mutationsSubject.complete();
1579
1524
  trigger$.complete();
1580
1525
  cancel$.next();
1581
1526
  cancel$.complete();
@@ -1584,39 +1529,26 @@ const createMutationRunner = ({
1584
1529
  filter(isDefined),
1585
1530
  distinctUntilChanged()
1586
1531
  );
1587
- const mutation$ = stableMapOperator$.pipe(
1532
+ const runner$ = stableMapOperator$.pipe(
1588
1533
  __queryInitHook ?? identity,
1589
1534
  mergeMap((mapOperator) => {
1590
1535
  const switchOperator = mapOperator === "concat" ? concatMap$1 : mapOperator === "switch" ? switchMap : mergeMap;
1591
- let mutationsForCurrentMapOperatorSubject = [];
1592
- const removeMutation = (mutation) => {
1593
- mutationsForCurrentMapOperatorSubject = mutationsForCurrentMapOperatorSubject.filter(
1594
- (item) => item !== mutation
1595
- );
1596
- mutationsSubject.next(
1597
- mutationsSubject.getValue().filter((item) => item !== mutation)
1598
- );
1599
- };
1600
1536
  return trigger$.pipe(
1601
1537
  takeUntil(stableMapOperator$.pipe(skip(1))),
1602
- map(({ args, options }) => {
1603
- const mutation = new Mutation({
1604
- args,
1605
- ...options,
1606
- mapOperator
1538
+ switchOperator(({ args }) => {
1539
+ const mutation = mutationCache.findLatest({
1540
+ exact: true,
1541
+ mutationKey
1607
1542
  });
1608
- mutationsForCurrentMapOperatorSubject = [
1609
- ...mutationsForCurrentMapOperatorSubject,
1610
- mutation
1611
- ];
1612
- mutationsSubject.next([...mutationsSubject.getValue(), mutation]);
1613
- return mutation;
1614
- }),
1615
- switchOperator((mutation) => {
1616
- if (!mutationsSubject.getValue().includes(mutation))
1543
+ if (!mutation) {
1617
1544
  return of({});
1618
- const queryIsOver$ = mutation.mutation$.pipe(
1619
- map(({ data, error }) => error || data)
1545
+ }
1546
+ const mutation$ = mutation.execute(args);
1547
+ const queryIsOver$ = merge(
1548
+ cancel$,
1549
+ mutation$.pipe(
1550
+ filter(({ status }) => status === "success" || status === "error")
1551
+ )
1620
1552
  );
1621
1553
  const isThisCurrentFunctionLastOneCalled = trigger$.pipe(
1622
1554
  take(1),
@@ -1625,7 +1557,7 @@ const createMutationRunner = ({
1625
1557
  takeUntil(queryIsOver$)
1626
1558
  );
1627
1559
  const result$ = combineLatest([
1628
- mutation.mutation$,
1560
+ mutation$,
1629
1561
  isThisCurrentFunctionLastOneCalled
1630
1562
  ]).pipe(
1631
1563
  map(([result, isLastMutationCalled]) => {
@@ -1634,11 +1566,7 @@ const createMutationRunner = ({
1634
1566
  }
1635
1567
  return result;
1636
1568
  }),
1637
- takeUntil(cancel$.pipe()),
1638
- mergeResults,
1639
- finalize(() => {
1640
- removeMutation(mutation);
1641
- })
1569
+ mergeResults
1642
1570
  );
1643
1571
  return result$;
1644
1572
  }),
@@ -1646,15 +1574,21 @@ const createMutationRunner = ({
1646
1574
  __queryTriggerHook ?? identity
1647
1575
  );
1648
1576
  }),
1649
- __queryFinalizeHook ?? identity
1577
+ __queryFinalizeHook ?? identity,
1578
+ shareReplay(1)
1650
1579
  );
1651
1580
  cancel$.subscribe(() => {
1652
- if (mutationsSubject.getValue().length === 0)
1653
- return;
1654
- mutationsSubject.next([]);
1581
+ var _a;
1582
+ (_a = mutationCache.findAll({
1583
+ mutationKey,
1584
+ exact: true
1585
+ })) == null ? void 0 : _a.forEach((mutation) => {
1586
+ mutation.cancel();
1587
+ });
1655
1588
  });
1656
1589
  return {
1657
- mutation$,
1590
+ mutationKey,
1591
+ runner$,
1658
1592
  trigger: ({
1659
1593
  args,
1660
1594
  options
@@ -1664,29 +1598,11 @@ const createMutationRunner = ({
1664
1598
  },
1665
1599
  cancel$,
1666
1600
  destroy,
1667
- mutationsSubject,
1668
1601
  getClosed: () => closed
1669
1602
  };
1670
1603
  };
1671
- const createPredicateForFilters = ({
1672
- mutationKey,
1673
- status,
1674
- predicate
1675
- } = {}) => {
1676
- const defaultPredicate = (mutation) => {
1677
- if (mutationKey !== void 0 && // @todo optimize
1678
- serializeKey(mutation.options.mutationKey) !== serializeKey(mutationKey)) {
1679
- return false;
1680
- }
1681
- if (status && mutation.stateSubject.getValue().status !== status)
1682
- return false;
1683
- return true;
1684
- };
1685
- const finalPredicate = predicate ?? defaultPredicate;
1686
- return finalPredicate;
1687
- };
1688
- class MutationClient {
1689
- constructor() {
1604
+ class MutationRunners {
1605
+ constructor(client) {
1690
1606
  /**
1691
1607
  * Contain all active mutation for a given key.
1692
1608
  * A mutation ca have several triggers running (it is not necessarily one function running)
@@ -1695,89 +1611,7 @@ class MutationClient {
1695
1611
  * - automatically cleaned as soon as the last mutation is done for a given key
1696
1612
  */
1697
1613
  __publicField(this, "mutationRunnersByKey$", new BehaviorSubject(/* @__PURE__ */ new Map()));
1698
- /**
1699
- * Mutation result subject. It can be used whether there is a mutation
1700
- * running or not and can be directly observed.
1701
- *
1702
- * @important
1703
- * - automatically cleaned as soon as the last mutation is done for a given key
1704
- */
1705
- __publicField(this, "mutationResults$", new BehaviorSubject(/* @__PURE__ */ new Map()));
1706
- __publicField(this, "mutate$", new Subject());
1707
- __publicField(this, "cancel$", new Subject());
1708
- /**
1709
- * Observable to track how many running mutations per runner
1710
- */
1711
- __publicField(this, "isMutatingSubject", new BehaviorSubject([]));
1712
- /**
1713
- * List of all mutations running
1714
- */
1715
- __publicField(this, "mutationsSubject", new BehaviorSubject([]));
1716
- this.mutate$.pipe(
1717
- tap(({ options, args }) => {
1718
- const { mutationKey } = options;
1719
- const serializedMutationKey = serializeKey(mutationKey);
1720
- let mutationForKey = this.getMutationRunnersByKey(
1721
- serializedMutationKey
1722
- );
1723
- if (!mutationForKey) {
1724
- mutationForKey = {
1725
- ...createMutationRunner(options),
1726
- mutationKey
1727
- };
1728
- this.setMutationRunnersByKey(serializedMutationKey, mutationForKey);
1729
- mutationForKey.mutation$.subscribe((result) => {
1730
- let resultForKeySubject = this.mutationResults$.getValue().get(serializedMutationKey);
1731
- if (!resultForKeySubject) {
1732
- resultForKeySubject = new BehaviorSubject(result);
1733
- const resultMap = this.mutationResults$.getValue();
1734
- resultMap.set(serializedMutationKey, resultForKeySubject);
1735
- this.mutationResults$.next(resultMap);
1736
- } else {
1737
- resultForKeySubject == null ? void 0 : resultForKeySubject.next(result);
1738
- }
1739
- });
1740
- mutationForKey.mutationsSubject.pipe(
1741
- distinctUntilChanged(shallowEqual),
1742
- skip(1),
1743
- filter((items) => items.length === 0)
1744
- ).subscribe(() => {
1745
- mutationForKey == null ? void 0 : mutationForKey.destroy();
1746
- const resultMap = this.mutationResults$.getValue();
1747
- resultMap.delete(serializedMutationKey);
1748
- this.mutationResults$.next(resultMap);
1749
- this.deleteMutationRunnersByKey(serializedMutationKey);
1750
- });
1751
- }
1752
- mutationForKey.trigger({ args, options });
1753
- })
1754
- ).subscribe();
1755
- this.cancel$.pipe(
1756
- tap(({ key }) => {
1757
- var _a;
1758
- const serializedKey = serializeKey(key);
1759
- (_a = this.mutationRunnersByKey$.getValue().get(serializedKey)) == null ? void 0 : _a.cancel$.next();
1760
- })
1761
- ).subscribe();
1762
- this.mutationRunnersByKey$.pipe(
1763
- switchMap((mapItem) => {
1764
- const mutationRunners = Array.from(mapItem.values());
1765
- const mutations$ = combineLatest(
1766
- mutationRunners.map(
1767
- (runner) => runner.mutationsSubject.pipe(
1768
- map((mutations) => mutations.map((mutation) => mutation))
1769
- )
1770
- )
1771
- );
1772
- return mutations$.pipe(
1773
- map(
1774
- (mutationsByKeys) => mutationsByKeys.reduce((acc, value) => [...acc, ...value], [])
1775
- )
1776
- );
1777
- }),
1778
- startWith([]),
1779
- distinctUntilChanged(shallowEqual)
1780
- ).subscribe(this.mutationsSubject);
1614
+ this.client = client;
1781
1615
  }
1782
1616
  /**
1783
1617
  * @helper
@@ -1801,99 +1635,569 @@ class MutationClient {
1801
1635
  getMutationRunnersByKey(key) {
1802
1636
  return this.mutationRunnersByKey$.getValue().get(key);
1803
1637
  }
1804
- useIsMutating(filters = {}) {
1805
- const predicate = createPredicateForFilters(filters);
1806
- const reduceByNumber = (entries) => entries.reduce((acc, mutation) => {
1807
- return predicate(mutation) && mutation.stateSubject.getValue().status === "pending" ? 1 + acc : acc;
1808
- }, 0);
1809
- const lastValue = reduceByNumber(this.mutationsSubject.getValue());
1810
- const value$ = this.mutationsSubject.pipe(
1811
- switchMap((mutations) => {
1812
- const mutationsOnStateUpdate = mutations.map(
1813
- (mutation) => mutation.stateSubject.pipe(map(() => mutation))
1638
+ async mutate(params) {
1639
+ const { mutationKey } = params.options;
1640
+ const serializedMutationKey = serializeKey(mutationKey);
1641
+ let mutationForKey = this.getMutationRunnersByKey(serializedMutationKey);
1642
+ if (!mutationForKey) {
1643
+ mutationForKey = {
1644
+ ...createMutationRunner({
1645
+ ...params.options,
1646
+ client: this.client,
1647
+ mutationCache: this.client.getMutationCache()
1648
+ }),
1649
+ mutationKey
1650
+ };
1651
+ this.setMutationRunnersByKey(serializedMutationKey, mutationForKey);
1652
+ mutationForKey.runner$.subscribe();
1653
+ this.client.getMutationCache().mutationsBy({
1654
+ exact: true,
1655
+ mutationKey
1656
+ }).pipe(
1657
+ distinctUntilChanged(shallowEqual),
1658
+ skip(1),
1659
+ filter((items) => items.length === 0),
1660
+ take(1)
1661
+ ).subscribe(() => {
1662
+ mutationForKey == null ? void 0 : mutationForKey.destroy();
1663
+ this.deleteMutationRunnersByKey(serializedMutationKey);
1664
+ });
1665
+ }
1666
+ const mutation = this.client.getMutationCache().build(this.client, params.options);
1667
+ mutationForKey.trigger(params);
1668
+ return await new Promise((resolve, reject) => {
1669
+ mutation.observeTillFinished().pipe(last()).subscribe({
1670
+ error: reject,
1671
+ next: resolve
1672
+ });
1673
+ });
1674
+ }
1675
+ destroy() {
1676
+ this.mutationRunnersByKey$.complete();
1677
+ }
1678
+ }
1679
+ const functionAsObservable = (fn) => {
1680
+ return defer(() => {
1681
+ const result = fn();
1682
+ if (result instanceof Promise) {
1683
+ return from(result);
1684
+ }
1685
+ if (result instanceof Observable) {
1686
+ return result;
1687
+ }
1688
+ return of(result);
1689
+ });
1690
+ };
1691
+ class Mutation {
1692
+ constructor({
1693
+ options,
1694
+ mutationCache
1695
+ }) {
1696
+ __publicField(this, "state", getDefaultMutationState());
1697
+ __publicField(this, "state$");
1698
+ __publicField(this, "options");
1699
+ __publicField(this, "mutationCache");
1700
+ __publicField(this, "observerCount", new BehaviorSubject(0));
1701
+ __publicField(this, "observerCount$", this.observerCount.asObservable());
1702
+ __publicField(this, "cancelSubject", new Subject());
1703
+ __publicField(this, "executeSubject", new Subject());
1704
+ this.options = options;
1705
+ this.mutationCache = mutationCache;
1706
+ this.state$ = merge(
1707
+ of(this.state),
1708
+ this.executeSubject.pipe(
1709
+ switchMap((variables) => this.createMutation(variables)),
1710
+ tap((value) => {
1711
+ this.state = { ...this.state, ...value };
1712
+ }),
1713
+ takeUntil(this.cancelSubject)
1714
+ ),
1715
+ NEVER
1716
+ ).pipe(
1717
+ /**
1718
+ * refCount as true somewhat make NEVER complete when there are
1719
+ * no more observers. I thought I should have to complete manually (which is
1720
+ * why we still cancel the observable when we remove it from cache)
1721
+ */
1722
+ shareReplay({ bufferSize: 1, refCount: true }),
1723
+ takeUntil(this.cancelSubject),
1724
+ (source) => {
1725
+ return new Observable(
1726
+ (observer) => {
1727
+ this.observerCount.next(this.observerCount.getValue() + 1);
1728
+ const sub = source.subscribe(observer);
1729
+ return () => {
1730
+ this.observerCount.next(this.observerCount.getValue() - 1);
1731
+ sub.unsubscribe();
1732
+ };
1733
+ }
1814
1734
  );
1815
- return mutationsOnStateUpdate.length === 0 ? of([]) : combineLatest(mutationsOnStateUpdate);
1816
- }),
1817
- map(reduceByNumber),
1818
- distinctUntilChanged()
1735
+ }
1819
1736
  );
1820
- return { value$, lastValue };
1821
1737
  }
1822
- mutationState({
1738
+ createMutation(variables) {
1739
+ const mutationFn = this.options.mutationFn;
1740
+ const onCacheMutate$ = functionAsObservable(
1741
+ () => {
1742
+ var _a, _b;
1743
+ return (_b = (_a = this.mutationCache.config).onMutate) == null ? void 0 : _b.call(
1744
+ _a,
1745
+ variables,
1746
+ this
1747
+ );
1748
+ }
1749
+ );
1750
+ const onMutate = concat(
1751
+ onCacheMutate$.pipe(
1752
+ mergeMap(() => {
1753
+ const onMutate$ = functionAsObservable(
1754
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
1755
+ () => {
1756
+ var _a, _b;
1757
+ return ((_b = (_a = this.options).onMutate) == null ? void 0 : _b.call(_a, variables)) ?? void 0;
1758
+ }
1759
+ );
1760
+ return onMutate$;
1761
+ })
1762
+ )
1763
+ );
1764
+ const queryRunner$ = onMutate.pipe(
1765
+ switchMap((context) => {
1766
+ const fn$ = typeof mutationFn === "function" ? (
1767
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
1768
+ functionAsObservable(() => mutationFn(variables))
1769
+ ) : mutationFn;
1770
+ return fn$.pipe(
1771
+ retryOnError(this.options),
1772
+ take(1),
1773
+ map((data) => ({ data, context, isError: false })),
1774
+ catchError((error) => {
1775
+ console.error(error);
1776
+ const onCacheError$ = functionAsObservable(
1777
+ () => {
1778
+ var _a, _b;
1779
+ return (_b = (_a = this.mutationCache.config).onError) == null ? void 0 : _b.call(_a, error, variables, context, this);
1780
+ }
1781
+ );
1782
+ const onError$ = functionAsObservable(
1783
+ () => {
1784
+ var _a, _b;
1785
+ return (_b = (_a = this.options).onError) == null ? void 0 : _b.call(_a, error, variables, context);
1786
+ }
1787
+ );
1788
+ return concat(onCacheError$, onError$).pipe(
1789
+ toArray(),
1790
+ map(() => ({ data: error, context, isError: true }))
1791
+ );
1792
+ })
1793
+ );
1794
+ })
1795
+ );
1796
+ const initState$ = of({
1797
+ ...this.state,
1798
+ variables,
1799
+ status: "pending",
1800
+ submittedAt: (/* @__PURE__ */ new Date()).getTime()
1801
+ });
1802
+ const mutation$ = merge(
1803
+ initState$,
1804
+ queryRunner$.pipe(
1805
+ switchMap(({ data: dataOrError, isError, context }) => {
1806
+ const error = isError ? dataOrError : null;
1807
+ const data = isError ? void 0 : dataOrError;
1808
+ const onCacheSuccess$ = isError ? of(null) : functionAsObservable(
1809
+ () => {
1810
+ var _a, _b;
1811
+ return (_b = (_a = this.mutationCache.config).onSuccess) == null ? void 0 : _b.call(
1812
+ _a,
1813
+ data,
1814
+ variables,
1815
+ context,
1816
+ this
1817
+ );
1818
+ }
1819
+ );
1820
+ const onSuccess$ = isError ? of(null) : functionAsObservable(
1821
+ () => {
1822
+ var _a, _b;
1823
+ return (_b = (_a = this.options).onSuccess) == null ? void 0 : _b.call(_a, data, variables, context);
1824
+ }
1825
+ );
1826
+ const onCacheSettled$ = functionAsObservable(
1827
+ () => {
1828
+ var _a, _b;
1829
+ return (_b = (_a = this.mutationCache.config).onSettled) == null ? void 0 : _b.call(
1830
+ _a,
1831
+ data,
1832
+ error,
1833
+ variables,
1834
+ context,
1835
+ this
1836
+ );
1837
+ }
1838
+ );
1839
+ const onSettled$ = functionAsObservable(
1840
+ () => {
1841
+ var _a, _b;
1842
+ return (_b = (_a = this.options).onSettled) == null ? void 0 : _b.call(_a, data, error, variables, context);
1843
+ }
1844
+ );
1845
+ const result$ = concat(
1846
+ onCacheSuccess$,
1847
+ onSuccess$,
1848
+ onCacheSettled$,
1849
+ onSettled$
1850
+ ).pipe(
1851
+ toArray(),
1852
+ map(
1853
+ () => isError ? {
1854
+ status: "error",
1855
+ error,
1856
+ data,
1857
+ context,
1858
+ variables
1859
+ } : {
1860
+ status: "success",
1861
+ error,
1862
+ data,
1863
+ context,
1864
+ variables
1865
+ }
1866
+ )
1867
+ );
1868
+ return result$;
1869
+ })
1870
+ )
1871
+ ).pipe(
1872
+ mergeResults,
1873
+ this.options.__queryRunnerHook ?? identity,
1874
+ takeUntil(this.cancelSubject)
1875
+ );
1876
+ return mutation$;
1877
+ }
1878
+ observeTillFinished() {
1879
+ return this.state$.pipe(
1880
+ takeWhile(
1881
+ (result) => result.status !== "error" && result.status !== "success",
1882
+ true
1883
+ )
1884
+ );
1885
+ }
1886
+ /**
1887
+ * @important
1888
+ * The resulting observable will complete as soon as the mutation
1889
+ * is over, unlike the state which can be re-subscribed later.
1890
+ */
1891
+ execute(variables) {
1892
+ this.executeSubject.next(variables);
1893
+ this.executeSubject.complete();
1894
+ return this.observeTillFinished();
1895
+ }
1896
+ cancel() {
1897
+ this.cancelSubject.next();
1898
+ this.cancelSubject.complete();
1899
+ this.executeSubject.complete();
1900
+ }
1901
+ }
1902
+ const createPredicateForFilters = ({
1903
+ mutationKey,
1904
+ status,
1905
+ predicate,
1906
+ exact = true
1907
+ } = {}) => {
1908
+ const finalPredicate = (mutation) => {
1909
+ if (exact && mutationKey !== void 0 && !compareKeys(mutation.options.mutationKey, mutationKey, { exact })) {
1910
+ return false;
1911
+ }
1912
+ if (!exact && mutationKey !== void 0 && !compareKeys(mutationKey, mutation.options.mutationKey, { exact })) {
1913
+ return false;
1914
+ }
1915
+ if (status && mutation.state.status !== status)
1916
+ return false;
1917
+ if (predicate) {
1918
+ return predicate(mutation);
1919
+ }
1920
+ return true;
1921
+ };
1922
+ return finalPredicate;
1923
+ };
1924
+ class MutationCache {
1925
+ constructor(config = {}) {
1926
+ __publicField(this, "mutationsSubject", new BehaviorSubject([]));
1927
+ __publicField(this, "mutations$", this.mutationsSubject.pipe(
1928
+ map((mutations) => mutations.map(({ mutation }) => mutation)),
1929
+ distinctUntilChanged(arrayEqual),
1930
+ share()
1931
+ ));
1932
+ __publicField(this, "added$", this.mutations$.pipe(
1933
+ pairwise(),
1934
+ map(
1935
+ ([previous, current]) => current.filter((mutation) => !previous.includes(mutation))[0]
1936
+ ),
1937
+ filter(isDefined),
1938
+ share()
1939
+ ));
1940
+ __publicField(this, "removed$", this.mutations$.pipe(
1941
+ pairwise(),
1942
+ map(
1943
+ ([previous, current]) => previous.filter((mutation) => !current.includes(mutation))
1944
+ ),
1945
+ mergeMap((removedItems) => from(removedItems)),
1946
+ share()
1947
+ ));
1948
+ __publicField(this, "stateChange$", this.added$.pipe(
1949
+ mergeMap(
1950
+ (mutation) => mutation.state$.pipe(
1951
+ map(() => mutation),
1952
+ takeUntil(
1953
+ this.removed$.pipe(
1954
+ filter((removedMutation) => removedMutation === mutation)
1955
+ )
1956
+ )
1957
+ )
1958
+ ),
1959
+ share()
1960
+ ));
1961
+ this.config = config;
1962
+ }
1963
+ subscribe(listener) {
1964
+ const sub = merge(
1965
+ this.added$.pipe(
1966
+ tap((mutation) => {
1967
+ listener({
1968
+ type: "added",
1969
+ mutation
1970
+ });
1971
+ })
1972
+ ),
1973
+ this.removed$.pipe(
1974
+ tap((mutation) => {
1975
+ listener({
1976
+ type: "removed",
1977
+ mutation
1978
+ });
1979
+ })
1980
+ ),
1981
+ this.stateChange$.pipe(
1982
+ tap((mutation) => {
1983
+ listener({
1984
+ type: "updated",
1985
+ action: {
1986
+ ...mutation.state,
1987
+ // @todo
1988
+ type: "success"
1989
+ },
1990
+ mutation
1991
+ });
1992
+ })
1993
+ )
1994
+ ).subscribe();
1995
+ return () => {
1996
+ sub.unsubscribe();
1997
+ };
1998
+ }
1999
+ build(client, options) {
2000
+ const mutation = new Mutation({
2001
+ mutationCache: this,
2002
+ // mutationId: ++this.#mutationId,
2003
+ options: client.defaultMutationOptions(options)
2004
+ // state
2005
+ });
2006
+ const sub = mutation.state$.pipe(
2007
+ /**
2008
+ * Once a mutation is finished and there are no more observers than us
2009
+ * we start the process of cleaning it up based on gc settings
2010
+ */
2011
+ filter(({ status }) => status === "success" || status === "error"),
2012
+ switchMap(
2013
+ () => mutation.observerCount$.pipe(
2014
+ filter((count) => count <= 1),
2015
+ take(1)
2016
+ )
2017
+ ),
2018
+ switchMap(() => timer(mutation.options.gcTime ?? 0)),
2019
+ take(1)
2020
+ ).subscribe({
2021
+ complete: () => {
2022
+ this.remove(mutation);
2023
+ }
2024
+ });
2025
+ this.mutationsSubject.next([
2026
+ ...this.mutationsSubject.getValue(),
2027
+ { mutation, sub }
2028
+ ]);
2029
+ return mutation;
2030
+ }
2031
+ getAll() {
2032
+ return this.findAll();
2033
+ }
2034
+ remove(mutation) {
2035
+ this.removeBy({ predicate: (item) => item === mutation });
2036
+ }
2037
+ removeBy(filters) {
2038
+ const defaultedFilters = { exact: true, ...filters };
2039
+ const predicate = createPredicateForFilters(defaultedFilters);
2040
+ const toRemove = this.mutationsSubject.getValue().filter(({ mutation }) => {
2041
+ return predicate(mutation);
2042
+ }).map(({ mutation, sub }) => {
2043
+ mutation.cancel();
2044
+ sub.unsubscribe();
2045
+ return mutation;
2046
+ });
2047
+ this.mutationsSubject.next(
2048
+ this.mutationsSubject.getValue().filter(({ mutation }) => !toRemove.includes(mutation))
2049
+ );
2050
+ }
2051
+ find(filters) {
2052
+ var _a;
2053
+ const defaultedFilters = { exact: true, ...filters };
2054
+ const predicate = createPredicateForFilters(defaultedFilters);
2055
+ return (_a = this.mutationsSubject.getValue().find(({ mutation }) => predicate(mutation))) == null ? void 0 : _a.mutation;
2056
+ }
2057
+ findLatest(filters) {
2058
+ var _a;
2059
+ const defaultedFilters = { exact: true, ...filters };
2060
+ const predicate = createPredicateForFilters(defaultedFilters);
2061
+ return (_a = this.mutationsSubject.getValue().slice().reverse().find(({ mutation }) => predicate(mutation))) == null ? void 0 : _a.mutation;
2062
+ }
2063
+ findAll(filters = {}) {
2064
+ const defaultedFilters = { exact: true, ...filters };
2065
+ const predicate = createPredicateForFilters(defaultedFilters);
2066
+ return this.mutationsSubject.getValue().filter(({ mutation }) => predicate(mutation)).map(({ mutation }) => mutation);
2067
+ }
2068
+ mutationsBy(filters) {
2069
+ const defaultedFilters = { exact: true, ...filters };
2070
+ const predicate = createPredicateForFilters(defaultedFilters);
2071
+ return this.mutations$.pipe(
2072
+ map((mutations) => mutations.filter(predicate)),
2073
+ distinctUntilChanged(arrayEqual)
2074
+ );
2075
+ }
2076
+ mutationStateBy({
1823
2077
  filters,
1824
2078
  select
1825
2079
  } = {}) {
1826
2080
  const predicate = createPredicateForFilters(filters);
1827
- const finalSelect = select ?? ((mutation) => mutation.stateSubject.getValue());
1828
- const lastValue = this.mutationsSubject.getValue().reduce((acc, mutation) => {
2081
+ const finalSelect = select ?? ((mutation) => mutation.state);
2082
+ const lastValue = this.getAll().reduce((acc, mutation) => {
1829
2083
  const result = [...acc, mutation];
1830
2084
  return result;
1831
2085
  }, []).filter(predicate).map((mutation) => finalSelect(mutation));
1832
- const value$ = this.mutationsSubject.pipe(
1833
- switchMap((mutations) => {
1834
- const mutationsOnStateUpdate = mutations.map(
1835
- (mutation) => mutation.stateSubject.pipe(
1836
- filter(() => predicate(mutation)),
1837
- map(() => finalSelect(mutation))
1838
- )
1839
- );
1840
- return mutationsOnStateUpdate.length === 0 ? of([]) : combineLatest(mutationsOnStateUpdate);
2086
+ const value$ = this.stateChange$.pipe(
2087
+ startWith(),
2088
+ map(() => {
2089
+ const filteredMutations = this.getAll().filter(predicate);
2090
+ return filteredMutations.map(finalSelect);
1841
2091
  }),
1842
2092
  distinctUntilChanged(shallowEqual)
1843
2093
  );
1844
2094
  return { value$, lastValue };
1845
2095
  }
1846
- observe({ key }) {
1847
- var _a;
1848
- const currentResultValue = (_a = this.mutationResults$.getValue().get(key)) == null ? void 0 : _a.getValue();
1849
- const mapResultToObservedResult = (value) => ({
1850
- ...value,
1851
- isIdle: value.status === "idle",
1852
- isPaused: false,
1853
- isError: value.error !== void 0,
1854
- isPending: false,
1855
- isSuccess: value.status === "success"
2096
+ cancelBy(filters) {
2097
+ this.findAll(filters).forEach((mutation) => {
2098
+ mutation.cancel();
1856
2099
  });
1857
- const lastValue = currentResultValue ? mapResultToObservedResult(currentResultValue) : mapResultToObservedResult({
1858
- data: void 0,
1859
- error: void 0,
1860
- status: "idle"
2100
+ }
2101
+ clear() {
2102
+ this.getAll().forEach((mutation) => {
2103
+ this.remove(mutation);
1861
2104
  });
1862
- const result$ = this.mutationResults$.pipe(
1863
- switchMap((resultMap) => {
1864
- const subject = resultMap.get(key);
1865
- return subject ?? EMPTY;
1866
- })
1867
- ).pipe(
2105
+ }
2106
+ }
2107
+ class MutationObserver {
2108
+ constructor(client, options) {
2109
+ __publicField(this, "getDerivedState", (state) => {
2110
+ return {
2111
+ ...getDefaultMutationState(),
2112
+ ...state,
2113
+ isSuccess: state.status === "success",
2114
+ isPending: state.status === "pending",
2115
+ isIdle: state.status === "idle",
2116
+ isError: state.status === "error"
2117
+ };
2118
+ });
2119
+ this.client = client;
2120
+ this.options = options;
2121
+ }
2122
+ observeBy(filters) {
2123
+ const reduceStateFromMutation = (values) => {
2124
+ var _a;
2125
+ return values.reduce(
2126
+ (acc, { state, options }) => {
2127
+ if (options.mapOperator === "switch")
2128
+ return state;
2129
+ if (acc && state.submittedAt >= acc.submittedAt) {
2130
+ return {
2131
+ ...state,
2132
+ data: state.data ?? acc.data,
2133
+ error: state.error ?? acc.error
2134
+ };
2135
+ }
2136
+ return acc;
2137
+ },
2138
+ ((_a = values[0]) == null ? void 0 : _a.state) ?? getDefaultMutationState()
2139
+ );
2140
+ };
2141
+ const mutations = this.client.getMutationCache().findAll(filters);
2142
+ const lastValue = this.getDerivedState(
2143
+ reduceStateFromMutation(mutations)
2144
+ );
2145
+ const result$ = this.client.getMutationCache().mutationsBy(filters).pipe(
2146
+ switchMap(
2147
+ (mutations2) => combineLatest(
2148
+ mutations2.map(
2149
+ (mutation) => this.observe(mutation).pipe(
2150
+ map((state) => ({ state, options: mutation.options }))
2151
+ )
2152
+ )
2153
+ )
2154
+ ),
2155
+ map(reduceStateFromMutation),
1868
2156
  filter(isDefined),
1869
- map((value) => ({
1870
- ...value,
1871
- isIdle: value.status === "idle",
1872
- isPaused: false,
1873
- isError: value.error !== void 0,
1874
- isPending: false,
1875
- isSuccess: value.status === "success"
1876
- }))
2157
+ map(this.getDerivedState),
2158
+ distinctUntilChanged(shallowEqual)
1877
2159
  );
1878
2160
  return { result$, lastValue };
1879
2161
  }
1880
- mutate(params) {
1881
- this.mutate$.next(params);
2162
+ observe(mutation) {
2163
+ return mutation.state$;
1882
2164
  }
1883
- /**
1884
- * This will cancel any current mutation runnings.
1885
- * No discrimination process
1886
- */
1887
- cancel(params) {
1888
- this.cancel$.next(params);
2165
+ subscribe(subscription) {
2166
+ const sub = this.client.getMutationCache().mutations$.pipe(
2167
+ mergeMap((mutations) => {
2168
+ const observed$ = mutations.map(
2169
+ (mutation) => this.observe(mutation).pipe(
2170
+ // we only want next changes
2171
+ skip(1)
2172
+ )
2173
+ );
2174
+ return merge(...observed$);
2175
+ })
2176
+ ).subscribe(subscription);
2177
+ return () => {
2178
+ sub.unsubscribe();
2179
+ };
2180
+ }
2181
+ async mutate(variables, options) {
2182
+ const mergedOptions = {
2183
+ ...this.options,
2184
+ ...options
2185
+ };
2186
+ return await this.client.mutationRunners.mutate({
2187
+ args: variables,
2188
+ options: {
2189
+ mutationFn: async () => void 0,
2190
+ ...mergedOptions,
2191
+ mutationKey: mergedOptions.mutationKey ?? [nanoid()]
2192
+ }
2193
+ });
2194
+ }
2195
+ reset() {
2196
+ this.client.getMutationCache().getAll().forEach((mutation) => {
2197
+ mutation.cancel();
2198
+ });
1889
2199
  }
1890
2200
  destroy() {
1891
- this.cancel$.complete();
1892
- this.mutate$.complete();
1893
- this.mutationResults$.complete();
1894
- this.mutationRunnersByKey$.complete();
1895
- this.isMutatingSubject.complete();
1896
- this.mutationsSubject.complete();
1897
2201
  }
1898
2202
  }
1899
2203
  const createClient = () => {
@@ -1901,7 +2205,6 @@ const createClient = () => {
1901
2205
  const invalidationClient = createInvalidationClient({ queryStore });
1902
2206
  const cacheClient = createCacheClient({ queryStore });
1903
2207
  const refetchClient = createRefetchClient();
1904
- const mutationClient = new MutationClient();
1905
2208
  let hasCalledStart = false;
1906
2209
  const query = ({
1907
2210
  key,
@@ -2012,6 +2315,8 @@ const createClient = () => {
2012
2315
  })
2013
2316
  )
2014
2317
  );
2318
+ const destroy = () => {
2319
+ };
2015
2320
  const start = () => {
2016
2321
  hasCalledStart = true;
2017
2322
  const queryListenerSub = queryListener$.subscribe();
@@ -2023,14 +2328,10 @@ const createClient = () => {
2023
2328
  queryListenerSub.unsubscribe();
2024
2329
  };
2025
2330
  };
2026
- const destroy = () => {
2027
- mutationClient.destroy();
2028
- };
2029
2331
  return {
2030
2332
  start,
2031
2333
  query,
2032
2334
  queryStore,
2033
- mutationClient,
2034
2335
  ...invalidationClient,
2035
2336
  ...cacheClient,
2036
2337
  ...refetchClient,
@@ -2038,12 +2339,36 @@ const createClient = () => {
2038
2339
  };
2039
2340
  };
2040
2341
  class QueryClient {
2041
- constructor() {
2342
+ constructor({ mutationCache } = {
2343
+ mutationCache: new MutationCache()
2344
+ }) {
2042
2345
  __publicField(this, "client");
2346
+ __publicField(this, "mutationCache");
2347
+ __publicField(this, "mutationRunners");
2348
+ __publicField(this, "mutationObserver");
2349
+ this.mutationCache = mutationCache;
2350
+ this.mutationRunners = new MutationRunners(this);
2351
+ this.mutationObserver = new MutationObserver(this);
2043
2352
  this.client = createClient();
2044
2353
  }
2354
+ mount() {
2355
+ const stop = this.client.start();
2356
+ return () => {
2357
+ this.mutationRunners.destroy();
2358
+ stop();
2359
+ };
2360
+ }
2361
+ getMutationCache() {
2362
+ return this.mutationCache;
2363
+ }
2364
+ defaultMutationOptions(options) {
2365
+ return options;
2366
+ }
2367
+ clear() {
2368
+ }
2045
2369
  }
2046
2370
  export {
2371
+ MutationCache,
2047
2372
  QueryClient,
2048
2373
  QueryClientProvider,
2049
2374
  SIGNAL_RESET,