@verii/components-organizations-registrar 1.1.0-pre.1762411615 → 1.1.0-pre.1763452964

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.
package/dist/index.js CHANGED
@@ -37,6 +37,68 @@ var Subscribable = class {
37
37
  onUnsubscribe() {
38
38
  }
39
39
  };
40
+ var defaultTimeoutProvider = {
41
+ // We need the wrapper function syntax below instead of direct references to
42
+ // global setTimeout etc.
43
+ //
44
+ // BAD: `setTimeout: setTimeout`
45
+ // GOOD: `setTimeout: (cb, delay) => setTimeout(cb, delay)`
46
+ //
47
+ // If we use direct references here, then anything that wants to spy on or
48
+ // replace the global setTimeout (like tests) won't work since we'll already
49
+ // have a hard reference to the original implementation at the time when this
50
+ // file was imported.
51
+ setTimeout: (callback, delay) => setTimeout(callback, delay),
52
+ clearTimeout: (timeoutId) => clearTimeout(timeoutId),
53
+ setInterval: (callback, delay) => setInterval(callback, delay),
54
+ clearInterval: (intervalId) => clearInterval(intervalId)
55
+ };
56
+ var TimeoutManager = class {
57
+ // We cannot have TimeoutManager<T> as we must instantiate it with a concrete
58
+ // type at app boot; and if we leave that type, then any new timer provider
59
+ // would need to support ReturnType<typeof setTimeout>, which is infeasible.
60
+ //
61
+ // We settle for type safety for the TimeoutProvider type, and accept that
62
+ // this class is unsafe internally to allow for extension.
63
+ #provider = defaultTimeoutProvider;
64
+ #providerCalled = false;
65
+ setTimeoutProvider(provider) {
66
+ if (process.env.NODE_ENV !== "production") {
67
+ if (this.#providerCalled && provider !== this.#provider) {
68
+ console.error(
69
+ `[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.`,
70
+ { previous: this.#provider, provider }
71
+ );
72
+ }
73
+ }
74
+ this.#provider = provider;
75
+ if (process.env.NODE_ENV !== "production") {
76
+ this.#providerCalled = false;
77
+ }
78
+ }
79
+ setTimeout(callback, delay) {
80
+ if (process.env.NODE_ENV !== "production") {
81
+ this.#providerCalled = true;
82
+ }
83
+ return this.#provider.setTimeout(callback, delay);
84
+ }
85
+ clearTimeout(timeoutId) {
86
+ this.#provider.clearTimeout(timeoutId);
87
+ }
88
+ setInterval(callback, delay) {
89
+ if (process.env.NODE_ENV !== "production") {
90
+ this.#providerCalled = true;
91
+ }
92
+ return this.#provider.setInterval(callback, delay);
93
+ }
94
+ clearInterval(intervalId) {
95
+ this.#provider.clearInterval(intervalId);
96
+ }
97
+ };
98
+ var timeoutManager = new TimeoutManager();
99
+ function systemSetTimeoutZero(callback) {
100
+ setTimeout(callback, 0);
101
+ }
40
102
  var isServer = typeof window === "undefined" || "Deno" in globalThis;
41
103
  function noop() {
42
104
  }
@@ -140,34 +202,37 @@ function partialMatchKey(a2, b) {
140
202
  }
141
203
  return false;
142
204
  }
205
+ var hasOwn = Object.prototype.hasOwnProperty;
143
206
  function replaceEqualDeep(a2, b) {
144
207
  if (a2 === b) {
145
208
  return a2;
146
209
  }
147
210
  const array = isPlainArray(a2) && isPlainArray(b);
148
- if (array || isPlainObject(a2) && isPlainObject(b)) {
149
- const aItems = array ? a2 : Object.keys(a2);
150
- const aSize = aItems.length;
151
- const bItems = array ? b : Object.keys(b);
152
- const bSize = bItems.length;
153
- const copy = array ? [] : {};
154
- const aItemsSet = new Set(aItems);
155
- let equalItems = 0;
156
- for (let i = 0; i < bSize; i++) {
157
- const key = array ? i : bItems[i];
158
- if ((!array && aItemsSet.has(key) || array) && a2[key] === void 0 && b[key] === void 0) {
159
- copy[key] = void 0;
160
- equalItems++;
161
- } else {
162
- copy[key] = replaceEqualDeep(a2[key], b[key]);
163
- if (copy[key] === a2[key] && a2[key] !== void 0) {
164
- equalItems++;
165
- }
166
- }
167
- }
168
- return aSize === bSize && equalItems === aSize ? a2 : copy;
169
- }
170
- return b;
211
+ if (!array && !(isPlainObject(a2) && isPlainObject(b))) return b;
212
+ const aItems = array ? a2 : Object.keys(a2);
213
+ const aSize = aItems.length;
214
+ const bItems = array ? b : Object.keys(b);
215
+ const bSize = bItems.length;
216
+ const copy = array ? new Array(bSize) : {};
217
+ let equalItems = 0;
218
+ for (let i = 0; i < bSize; i++) {
219
+ const key = array ? i : bItems[i];
220
+ const aItem = a2[key];
221
+ const bItem = b[key];
222
+ if (aItem === bItem) {
223
+ copy[key] = aItem;
224
+ if (array ? i < aSize : hasOwn.call(a2, key)) equalItems++;
225
+ continue;
226
+ }
227
+ if (aItem === null || bItem === null || typeof aItem !== "object" || typeof bItem !== "object") {
228
+ copy[key] = bItem;
229
+ continue;
230
+ }
231
+ const v = replaceEqualDeep(aItem, bItem);
232
+ copy[key] = v;
233
+ if (v === aItem) equalItems++;
234
+ }
235
+ return aSize === bSize && equalItems === aSize ? a2 : copy;
171
236
  }
172
237
  function isPlainArray(value) {
173
238
  return Array.isArray(value) && value.length === Object.keys(value).length;
@@ -197,7 +262,7 @@ function hasObjectPrototype(o) {
197
262
  }
198
263
  function sleep(timeout) {
199
264
  return new Promise((resolve) => {
200
- setTimeout(resolve, timeout);
265
+ timeoutManager.setTimeout(resolve, timeout);
201
266
  });
202
267
  }
203
268
  function replaceData(prevData, data, options) {
@@ -303,6 +368,115 @@ var FocusManager = class extends Subscribable {
303
368
  }
304
369
  };
305
370
  var focusManager = new FocusManager();
371
+ function pendingThenable() {
372
+ let resolve;
373
+ let reject;
374
+ const thenable = new Promise((_resolve, _reject) => {
375
+ resolve = _resolve;
376
+ reject = _reject;
377
+ });
378
+ thenable.status = "pending";
379
+ thenable.catch(() => {
380
+ });
381
+ function finalize(data) {
382
+ Object.assign(thenable, data);
383
+ delete thenable.resolve;
384
+ delete thenable.reject;
385
+ }
386
+ thenable.resolve = (value) => {
387
+ finalize({
388
+ status: "fulfilled",
389
+ value
390
+ });
391
+ resolve(value);
392
+ };
393
+ thenable.reject = (reason) => {
394
+ finalize({
395
+ status: "rejected",
396
+ reason
397
+ });
398
+ reject(reason);
399
+ };
400
+ return thenable;
401
+ }
402
+ var defaultScheduler = systemSetTimeoutZero;
403
+ function createNotifyManager() {
404
+ let queue = [];
405
+ let transactions = 0;
406
+ let notifyFn = (callback) => {
407
+ callback();
408
+ };
409
+ let batchNotifyFn = (callback) => {
410
+ callback();
411
+ };
412
+ let scheduleFn = defaultScheduler;
413
+ const schedule = (callback) => {
414
+ if (transactions) {
415
+ queue.push(callback);
416
+ } else {
417
+ scheduleFn(() => {
418
+ notifyFn(callback);
419
+ });
420
+ }
421
+ };
422
+ const flush = () => {
423
+ const originalQueue = queue;
424
+ queue = [];
425
+ if (originalQueue.length) {
426
+ scheduleFn(() => {
427
+ batchNotifyFn(() => {
428
+ originalQueue.forEach((callback) => {
429
+ notifyFn(callback);
430
+ });
431
+ });
432
+ });
433
+ }
434
+ };
435
+ return {
436
+ batch: (callback) => {
437
+ let result;
438
+ transactions++;
439
+ try {
440
+ result = callback();
441
+ } finally {
442
+ transactions--;
443
+ if (!transactions) {
444
+ flush();
445
+ }
446
+ }
447
+ return result;
448
+ },
449
+ /**
450
+ * All calls to the wrapped function will be batched.
451
+ */
452
+ batchCalls: (callback) => {
453
+ return (...args) => {
454
+ schedule(() => {
455
+ callback(...args);
456
+ });
457
+ };
458
+ },
459
+ schedule,
460
+ /**
461
+ * Use this method to set a custom notify function.
462
+ * This can be used to for example wrap notifications with `React.act` while running tests.
463
+ */
464
+ setNotifyFunction: (fn) => {
465
+ notifyFn = fn;
466
+ },
467
+ /**
468
+ * Use this method to set a custom function to batch notifications together into a single tick.
469
+ * By default React Query will use the batch function provided by ReactDOM or React Native.
470
+ */
471
+ setBatchNotifyFunction: (fn) => {
472
+ batchNotifyFn = fn;
473
+ },
474
+ setScheduler: (fn) => {
475
+ scheduleFn = fn;
476
+ }
477
+ };
478
+ }
479
+ var notifyManager = createNotifyManager();
306
480
  var OnlineManager = class extends Subscribable {
307
481
  #online = true;
308
482
  #cleanup;
@@ -353,37 +527,6 @@ var OnlineManager = class extends Subscribable {
353
527
  }
354
528
  };
355
529
  var onlineManager = new OnlineManager();
356
- function pendingThenable() {
357
- let resolve;
358
- let reject;
359
- const thenable = new Promise((_resolve, _reject) => {
360
- resolve = _resolve;
361
- reject = _reject;
362
- });
363
- thenable.status = "pending";
364
- thenable.catch(() => {
365
- });
366
- function finalize(data) {
367
- Object.assign(thenable, data);
368
- delete thenable.resolve;
369
- delete thenable.reject;
370
- }
371
- thenable.resolve = (value) => {
372
- finalize({
373
- status: "fulfilled",
374
- value
375
- });
376
- resolve(value);
377
- };
378
- thenable.reject = (reason) => {
379
- finalize({
380
- status: "rejected",
381
- reason
382
- });
383
- reject(reason);
384
- };
385
- return thenable;
386
- }
387
530
  function defaultRetryDelay(failureCount) {
388
531
  return Math.min(1e3 * 2 ** failureCount, 3e4);
389
532
  }
@@ -397,19 +540,17 @@ var CancelledError = class extends Error {
397
540
  this.silent = options?.silent;
398
541
  }
399
542
  };
400
- function isCancelledError(value) {
401
- return value instanceof CancelledError;
402
- }
403
543
  function createRetryer(config) {
404
544
  let isRetryCancelled = false;
405
545
  let failureCount = 0;
406
- let isResolved = false;
407
546
  let continueFn;
408
547
  const thenable = pendingThenable();
548
+ const isResolved = () => thenable.status !== "pending";
409
549
  const cancel = (cancelOptions) => {
410
- if (!isResolved) {
411
- reject(new CancelledError(cancelOptions));
412
- config.abort?.();
550
+ if (!isResolved()) {
551
+ const error = new CancelledError(cancelOptions);
552
+ reject(error);
553
+ config.onCancel?.(error);
413
554
  }
414
555
  };
415
556
  const cancelRetry = () => {
@@ -421,17 +562,13 @@ function createRetryer(config) {
421
562
  const canContinue = () => focusManager.isFocused() && (config.networkMode === "always" || onlineManager.isOnline()) && config.canRun();
422
563
  const canStart = () => canFetch(config.networkMode) && config.canRun();
423
564
  const resolve = (value) => {
424
- if (!isResolved) {
425
- isResolved = true;
426
- config.onSuccess?.(value);
565
+ if (!isResolved()) {
427
566
  continueFn?.();
428
567
  thenable.resolve(value);
429
568
  }
430
569
  };
431
570
  const reject = (value) => {
432
- if (!isResolved) {
433
- isResolved = true;
434
- config.onError?.(value);
571
+ if (!isResolved()) {
435
572
  continueFn?.();
436
573
  thenable.reject(value);
437
574
  }
@@ -439,20 +576,20 @@ function createRetryer(config) {
439
576
  const pause = () => {
440
577
  return new Promise((continueResolve) => {
441
578
  continueFn = (value) => {
442
- if (isResolved || canContinue()) {
579
+ if (isResolved() || canContinue()) {
443
580
  continueResolve(value);
444
581
  }
445
582
  };
446
583
  config.onPause?.();
447
584
  }).then(() => {
448
585
  continueFn = void 0;
449
- if (!isResolved) {
586
+ if (!isResolved()) {
450
587
  config.onContinue?.();
451
588
  }
452
589
  });
453
590
  };
454
591
  const run = () => {
455
- if (isResolved) {
592
+ if (isResolved()) {
456
593
  return;
457
594
  }
458
595
  let promiseOrValue;
@@ -463,7 +600,7 @@ function createRetryer(config) {
463
600
  promiseOrValue = Promise.reject(error);
464
601
  }
465
602
  Promise.resolve(promiseOrValue).then(resolve).catch((error) => {
466
- if (isResolved) {
603
+ if (isResolved()) {
467
604
  return;
468
605
  }
469
606
  const retry = config.retry ?? (isServer ? 0 : 3);
@@ -489,6 +626,7 @@ function createRetryer(config) {
489
626
  };
490
627
  return {
491
628
  promise: thenable,
629
+ status: () => thenable.status,
492
630
  cancel,
493
631
  continue: () => {
494
632
  continueFn?.();
@@ -507,84 +645,6 @@ function createRetryer(config) {
507
645
  }
508
646
  };
509
647
  }
510
- var defaultScheduler = (cb) => setTimeout(cb, 0);
511
- function createNotifyManager() {
512
- let queue = [];
513
- let transactions = 0;
514
- let notifyFn = (callback) => {
515
- callback();
516
- };
517
- let batchNotifyFn = (callback) => {
518
- callback();
519
- };
520
- let scheduleFn = defaultScheduler;
521
- const schedule = (callback) => {
522
- if (transactions) {
523
- queue.push(callback);
524
- } else {
525
- scheduleFn(() => {
526
- notifyFn(callback);
527
- });
528
- }
529
- };
530
- const flush = () => {
531
- const originalQueue = queue;
532
- queue = [];
533
- if (originalQueue.length) {
534
- scheduleFn(() => {
535
- batchNotifyFn(() => {
536
- originalQueue.forEach((callback) => {
537
- notifyFn(callback);
538
- });
539
- });
540
- });
541
- }
542
- };
543
- return {
544
- batch: (callback) => {
545
- let result;
546
- transactions++;
547
- try {
548
- result = callback();
549
- } finally {
550
- transactions--;
551
- if (!transactions) {
552
- flush();
553
- }
554
- }
555
- return result;
556
- },
557
- /**
558
- * All calls to the wrapped function will be batched.
559
- */
560
- batchCalls: (callback) => {
561
- return (...args) => {
562
- schedule(() => {
563
- callback(...args);
564
- });
565
- };
566
- },
567
- schedule,
568
- /**
569
- * Use this method to set a custom notify function.
570
- * This can be used to for example wrap notifications with `React.act` while running tests.
571
- */
572
- setNotifyFunction: (fn) => {
573
- notifyFn = fn;
574
- },
575
- /**
576
- * Use this method to set a custom function to batch notifications together into a single tick.
577
- * By default React Query will use the batch function provided by ReactDOM or React Native.
578
- */
579
- setBatchNotifyFunction: (fn) => {
580
- batchNotifyFn = fn;
581
- },
582
- setScheduler: (fn) => {
583
- scheduleFn = fn;
584
- }
585
- };
586
- }
587
- var notifyManager = createNotifyManager();
588
648
  var Removable = class {
589
649
  #gcTimeout;
590
650
  destroy() {
@@ -593,7 +653,7 @@ var Removable = class {
593
653
  scheduleGc() {
594
654
  this.clearGcTimeout();
595
655
  if (isValidTimeout(this.gcTime)) {
596
- this.#gcTimeout = setTimeout(() => {
656
+ this.#gcTimeout = timeoutManager.setTimeout(() => {
597
657
  this.optionalRemove();
598
658
  }, this.gcTime);
599
659
  }
@@ -606,7 +666,7 @@ var Removable = class {
606
666
  }
607
667
  clearGcTimeout() {
608
668
  if (this.#gcTimeout) {
609
- clearTimeout(this.#gcTimeout);
669
+ timeoutManager.clearTimeout(this.#gcTimeout);
610
670
  this.#gcTimeout = void 0;
611
671
  }
612
672
  }
@@ -642,6 +702,15 @@ var Query = class extends Removable {
642
702
  setOptions(options) {
643
703
  this.options = { ...this.#defaultOptions, ...options };
644
704
  this.updateGcTime(this.options.gcTime);
705
+ if (this.state && this.state.data === void 0) {
706
+ const defaultState = getDefaultState$1(this.options);
707
+ if (defaultState.data !== void 0) {
708
+ this.setState(
709
+ successState(defaultState.data, defaultState.dataUpdatedAt)
710
+ );
711
+ this.#initialState = defaultState;
712
+ }
713
+ }
645
714
  }
646
715
  optionalRemove() {
647
716
  if (!this.observers.length && this.state.fetchStatus === "idle") {
@@ -754,8 +823,11 @@ var Query = class extends Removable {
754
823
  this.#dispatch({ type: "invalidate" });
755
824
  }
756
825
  }
757
- fetch(options, fetchOptions) {
758
- if (this.state.fetchStatus !== "idle") {
826
+ async fetch(options, fetchOptions) {
827
+ if (this.state.fetchStatus !== "idle" && // If the promise in the retyer is already rejected, we have to definitely
828
+ // re-start the fetch; there is a chance that the query is still in a
829
+ // pending state when that happens
830
+ this.#retryer?.status() !== "rejected") {
759
831
  if (this.state.data !== void 0 && fetchOptions?.cancelRefetch) {
760
832
  this.cancel({ silent: true });
761
833
  } else if (this.#retryer) {
@@ -829,55 +901,18 @@ var Query = class extends Removable {
829
901
  if (this.state.fetchStatus === "idle" || this.state.fetchMeta !== context.fetchOptions?.meta) {
830
902
  this.#dispatch({ type: "fetch", meta: context.fetchOptions?.meta });
831
903
  }
832
- const onError = (error) => {
833
- if (!(isCancelledError(error) && error.silent)) {
834
- this.#dispatch({
835
- type: "error",
836
- error
837
- });
838
- }
839
- if (!isCancelledError(error)) {
840
- this.#cache.config.onError?.(
841
- error,
842
- this
843
- );
844
- this.#cache.config.onSettled?.(
845
- this.state.data,
846
- error,
847
- this
848
- );
849
- }
850
- this.scheduleGc();
851
- };
852
904
  this.#retryer = createRetryer({
853
905
  initialPromise: fetchOptions?.initialPromise,
854
906
  fn: context.fetchFn,
855
- abort: abortController.abort.bind(abortController),
856
- onSuccess: (data) => {
857
- if (data === void 0) {
858
- if (process.env.NODE_ENV !== "production") {
859
- console.error(
860
- `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`
861
- );
862
- }
863
- onError(new Error(`${this.queryHash} data is undefined`));
864
- return;
865
- }
866
- try {
867
- this.setData(data);
868
- } catch (error) {
869
- onError(error);
870
- return;
907
+ onCancel: (error) => {
908
+ if (error instanceof CancelledError && error.revert) {
909
+ this.setState({
910
+ ...this.#revertState,
911
+ fetchStatus: "idle"
912
+ });
871
913
  }
872
- this.#cache.config.onSuccess?.(data, this);
873
- this.#cache.config.onSettled?.(
874
- data,
875
- this.state.error,
876
- this
877
- );
878
- this.scheduleGc();
914
+ abortController.abort();
879
915
  },
880
- onError,
881
916
  onFail: (failureCount, error) => {
882
917
  this.#dispatch({ type: "failed", failureCount, error });
883
918
  },
@@ -892,7 +927,52 @@ var Query = class extends Removable {
892
927
  networkMode: context.options.networkMode,
893
928
  canRun: () => true
894
929
  });
895
- return this.#retryer.start();
930
+ try {
931
+ const data = await this.#retryer.start();
932
+ if (data === void 0) {
933
+ if (process.env.NODE_ENV !== "production") {
934
+ console.error(
935
+ `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`
936
+ );
937
+ }
938
+ throw new Error(`${this.queryHash} data is undefined`);
939
+ }
940
+ this.setData(data);
941
+ this.#cache.config.onSuccess?.(data, this);
942
+ this.#cache.config.onSettled?.(
943
+ data,
944
+ this.state.error,
945
+ this
946
+ );
947
+ return data;
948
+ } catch (error) {
949
+ if (error instanceof CancelledError) {
950
+ if (error.silent) {
951
+ return this.#retryer.promise;
952
+ } else if (error.revert) {
953
+ if (this.state.data === void 0) {
954
+ throw error;
955
+ }
956
+ return this.state.data;
957
+ }
958
+ }
959
+ this.#dispatch({
960
+ type: "error",
961
+ error
962
+ });
963
+ this.#cache.config.onError?.(
964
+ error,
965
+ this
966
+ );
967
+ this.#cache.config.onSettled?.(
968
+ this.state.data,
969
+ error,
970
+ this
971
+ );
972
+ throw error;
973
+ } finally {
974
+ this.scheduleGc();
975
+ }
896
976
  }
897
977
  #dispatch(action) {
898
978
  const reducer = (state) => {
@@ -920,26 +1000,20 @@ var Query = class extends Removable {
920
1000
  fetchMeta: action.meta ?? null
921
1001
  };
922
1002
  case "success":
923
- this.#revertState = void 0;
924
- return {
1003
+ const newState = {
925
1004
  ...state,
926
- data: action.data,
1005
+ ...successState(action.data, action.dataUpdatedAt),
927
1006
  dataUpdateCount: state.dataUpdateCount + 1,
928
- dataUpdatedAt: action.dataUpdatedAt ?? Date.now(),
929
- error: null,
930
- isInvalidated: false,
931
- status: "success",
932
1007
  ...!action.manual && {
933
1008
  fetchStatus: "idle",
934
1009
  fetchFailureCount: 0,
935
1010
  fetchFailureReason: null
936
1011
  }
937
1012
  };
1013
+ this.#revertState = action.manual ? newState : void 0;
1014
+ return newState;
938
1015
  case "error":
939
1016
  const error = action.error;
940
- if (isCancelledError(error) && error.revert && this.#revertState) {
941
- return { ...this.#revertState, fetchStatus: "idle" };
942
- }
943
1017
  return {
944
1018
  ...state,
945
1019
  error,
@@ -982,6 +1056,15 @@ function fetchState(data, options) {
982
1056
  }
983
1057
  };
984
1058
  }
1059
+ function successState(data, dataUpdatedAt) {
1060
+ return {
1061
+ data,
1062
+ dataUpdatedAt: dataUpdatedAt ?? Date.now(),
1063
+ error: null,
1064
+ isInvalidated: false,
1065
+ status: "success"
1066
+ };
1067
+ }
985
1068
  function getDefaultState$1(options) {
986
1069
  const data = typeof options.initialData === "function" ? options.initialData() : options.initialData;
987
1070
  const hasData = data !== void 0;
@@ -1001,100 +1084,121 @@ function getDefaultState$1(options) {
1001
1084
  fetchStatus: "idle"
1002
1085
  };
1003
1086
  }
1004
- var QueryCache = class extends Subscribable {
1005
- constructor(config = {}) {
1006
- super();
1007
- this.config = config;
1008
- this.#queries = /* @__PURE__ */ new Map();
1009
- }
1010
- #queries;
1011
- build(client, options, state) {
1012
- const queryKey = options.queryKey;
1013
- const queryHash = options.queryHash ?? hashQueryKeyByOptions(queryKey, options);
1014
- let query = this.get(queryHash);
1015
- if (!query) {
1016
- query = new Query({
1017
- client,
1018
- queryKey,
1019
- queryHash,
1020
- options: client.defaultQueryOptions(options),
1021
- state,
1022
- defaultOptions: client.getQueryDefaults(queryKey)
1023
- });
1024
- this.add(query);
1025
- }
1026
- return query;
1027
- }
1028
- add(query) {
1029
- if (!this.#queries.has(query.queryHash)) {
1030
- this.#queries.set(query.queryHash, query);
1031
- this.notify({
1032
- type: "added",
1033
- query
1034
- });
1035
- }
1036
- }
1037
- remove(query) {
1038
- const queryInMap = this.#queries.get(query.queryHash);
1039
- if (queryInMap) {
1040
- query.destroy();
1041
- if (queryInMap === query) {
1042
- this.#queries.delete(query.queryHash);
1087
+ function infiniteQueryBehavior(pages) {
1088
+ return {
1089
+ onFetch: (context, query) => {
1090
+ const options = context.options;
1091
+ const direction = context.fetchOptions?.meta?.fetchMore?.direction;
1092
+ const oldPages = context.state.data?.pages || [];
1093
+ const oldPageParams = context.state.data?.pageParams || [];
1094
+ let result = { pages: [], pageParams: [] };
1095
+ let currentPage = 0;
1096
+ const fetchFn = async () => {
1097
+ let cancelled = false;
1098
+ const addSignalProperty = (object) => {
1099
+ Object.defineProperty(object, "signal", {
1100
+ enumerable: true,
1101
+ get: () => {
1102
+ if (context.signal.aborted) {
1103
+ cancelled = true;
1104
+ } else {
1105
+ context.signal.addEventListener("abort", () => {
1106
+ cancelled = true;
1107
+ });
1108
+ }
1109
+ return context.signal;
1110
+ }
1111
+ });
1112
+ };
1113
+ const queryFn = ensureQueryFn(context.options, context.fetchOptions);
1114
+ const fetchPage = async (data, param, previous) => {
1115
+ if (cancelled) {
1116
+ return Promise.reject();
1117
+ }
1118
+ if (param == null && data.pages.length) {
1119
+ return Promise.resolve(data);
1120
+ }
1121
+ const createQueryFnContext = () => {
1122
+ const queryFnContext2 = {
1123
+ client: context.client,
1124
+ queryKey: context.queryKey,
1125
+ pageParam: param,
1126
+ direction: previous ? "backward" : "forward",
1127
+ meta: context.options.meta
1128
+ };
1129
+ addSignalProperty(queryFnContext2);
1130
+ return queryFnContext2;
1131
+ };
1132
+ const queryFnContext = createQueryFnContext();
1133
+ const page = await queryFn(queryFnContext);
1134
+ const { maxPages } = context.options;
1135
+ const addTo = previous ? addToStart : addToEnd;
1136
+ return {
1137
+ pages: addTo(data.pages, page, maxPages),
1138
+ pageParams: addTo(data.pageParams, param, maxPages)
1139
+ };
1140
+ };
1141
+ if (direction && oldPages.length) {
1142
+ const previous = direction === "backward";
1143
+ const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;
1144
+ const oldData = {
1145
+ pages: oldPages,
1146
+ pageParams: oldPageParams
1147
+ };
1148
+ const param = pageParamFn(options, oldData);
1149
+ result = await fetchPage(oldData, param, previous);
1150
+ } else {
1151
+ const remainingPages = pages ?? oldPages.length;
1152
+ do {
1153
+ const param = currentPage === 0 ? oldPageParams[0] ?? options.initialPageParam : getNextPageParam(options, result);
1154
+ if (currentPage > 0 && param == null) {
1155
+ break;
1156
+ }
1157
+ result = await fetchPage(result, param);
1158
+ currentPage++;
1159
+ } while (currentPage < remainingPages);
1160
+ }
1161
+ return result;
1162
+ };
1163
+ if (context.options.persister) {
1164
+ context.fetchFn = () => {
1165
+ return context.options.persister?.(
1166
+ fetchFn,
1167
+ {
1168
+ client: context.client,
1169
+ queryKey: context.queryKey,
1170
+ meta: context.options.meta,
1171
+ signal: context.signal
1172
+ },
1173
+ query
1174
+ );
1175
+ };
1176
+ } else {
1177
+ context.fetchFn = fetchFn;
1043
1178
  }
1044
- this.notify({ type: "removed", query });
1045
1179
  }
1046
- }
1047
- clear() {
1048
- notifyManager.batch(() => {
1049
- this.getAll().forEach((query) => {
1050
- this.remove(query);
1051
- });
1052
- });
1053
- }
1054
- get(queryHash) {
1055
- return this.#queries.get(queryHash);
1056
- }
1057
- getAll() {
1058
- return [...this.#queries.values()];
1059
- }
1060
- find(filters) {
1061
- const defaultedFilters = { exact: true, ...filters };
1062
- return this.getAll().find(
1063
- (query) => matchQuery(defaultedFilters, query)
1064
- );
1065
- }
1066
- findAll(filters = {}) {
1067
- const queries = this.getAll();
1068
- return Object.keys(filters).length > 0 ? queries.filter((query) => matchQuery(filters, query)) : queries;
1069
- }
1070
- notify(event) {
1071
- notifyManager.batch(() => {
1072
- this.listeners.forEach((listener) => {
1073
- listener(event);
1074
- });
1075
- });
1076
- }
1077
- onFocus() {
1078
- notifyManager.batch(() => {
1079
- this.getAll().forEach((query) => {
1080
- query.onFocus();
1081
- });
1082
- });
1083
- }
1084
- onOnline() {
1085
- notifyManager.batch(() => {
1086
- this.getAll().forEach((query) => {
1087
- query.onOnline();
1088
- });
1089
- });
1090
- }
1091
- };
1180
+ };
1181
+ }
1182
+ function getNextPageParam(options, { pages, pageParams }) {
1183
+ const lastIndex = pages.length - 1;
1184
+ return pages.length > 0 ? options.getNextPageParam(
1185
+ pages[lastIndex],
1186
+ pages,
1187
+ pageParams[lastIndex],
1188
+ pageParams
1189
+ ) : void 0;
1190
+ }
1191
+ function getPreviousPageParam(options, { pages, pageParams }) {
1192
+ return pages.length > 0 ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams) : void 0;
1193
+ }
1092
1194
  var Mutation = class extends Removable {
1195
+ #client;
1093
1196
  #observers;
1094
1197
  #mutationCache;
1095
1198
  #retryer;
1096
1199
  constructor(config) {
1097
1200
  super();
1201
+ this.#client = config.client;
1098
1202
  this.mutationId = config.mutationId;
1099
1203
  this.#mutationCache = config.mutationCache;
1100
1204
  this.#observers = [];
@@ -1146,12 +1250,17 @@ var Mutation = class extends Removable {
1146
1250
  const onContinue = () => {
1147
1251
  this.#dispatch({ type: "continue" });
1148
1252
  };
1253
+ const mutationFnContext = {
1254
+ client: this.#client,
1255
+ meta: this.options.meta,
1256
+ mutationKey: this.options.mutationKey
1257
+ };
1149
1258
  this.#retryer = createRetryer({
1150
1259
  fn: () => {
1151
1260
  if (!this.options.mutationFn) {
1152
1261
  return Promise.reject(new Error("No mutationFn found"));
1153
1262
  }
1154
- return this.options.mutationFn(variables);
1263
+ return this.options.mutationFn(variables, mutationFnContext);
1155
1264
  },
1156
1265
  onFail: (failureCount, error) => {
1157
1266
  this.#dispatch({ type: "failed", failureCount, error });
@@ -1174,9 +1283,13 @@ var Mutation = class extends Removable {
1174
1283
  this.#dispatch({ type: "pending", variables, isPaused });
1175
1284
  await this.#mutationCache.config.onMutate?.(
1176
1285
  variables,
1177
- this
1286
+ this,
1287
+ mutationFnContext
1288
+ );
1289
+ const context = await this.options.onMutate?.(
1290
+ variables,
1291
+ mutationFnContext
1178
1292
  );
1179
- const context = await this.options.onMutate?.(variables);
1180
1293
  if (context !== this.state.context) {
1181
1294
  this.#dispatch({
1182
1295
  type: "pending",
@@ -1191,17 +1304,30 @@ var Mutation = class extends Removable {
1191
1304
  data,
1192
1305
  variables,
1193
1306
  this.state.context,
1194
- this
1307
+ this,
1308
+ mutationFnContext
1309
+ );
1310
+ await this.options.onSuccess?.(
1311
+ data,
1312
+ variables,
1313
+ this.state.context,
1314
+ mutationFnContext
1195
1315
  );
1196
- await this.options.onSuccess?.(data, variables, this.state.context);
1197
1316
  await this.#mutationCache.config.onSettled?.(
1198
1317
  data,
1199
1318
  null,
1200
1319
  this.state.variables,
1201
1320
  this.state.context,
1202
- this
1321
+ this,
1322
+ mutationFnContext
1323
+ );
1324
+ await this.options.onSettled?.(
1325
+ data,
1326
+ null,
1327
+ variables,
1328
+ this.state.context,
1329
+ mutationFnContext
1203
1330
  );
1204
- await this.options.onSettled?.(data, null, variables, this.state.context);
1205
1331
  this.#dispatch({ type: "success", data });
1206
1332
  return data;
1207
1333
  } catch (error) {
@@ -1210,25 +1336,29 @@ var Mutation = class extends Removable {
1210
1336
  error,
1211
1337
  variables,
1212
1338
  this.state.context,
1213
- this
1339
+ this,
1340
+ mutationFnContext
1214
1341
  );
1215
1342
  await this.options.onError?.(
1216
1343
  error,
1217
1344
  variables,
1218
- this.state.context
1345
+ this.state.context,
1346
+ mutationFnContext
1219
1347
  );
1220
1348
  await this.#mutationCache.config.onSettled?.(
1221
1349
  void 0,
1222
1350
  error,
1223
1351
  this.state.variables,
1224
1352
  this.state.context,
1225
- this
1353
+ this,
1354
+ mutationFnContext
1226
1355
  );
1227
1356
  await this.options.onSettled?.(
1228
1357
  void 0,
1229
1358
  error,
1230
1359
  variables,
1231
- this.state.context
1360
+ this.state.context,
1361
+ mutationFnContext
1232
1362
  );
1233
1363
  throw error;
1234
1364
  } finally {
@@ -1331,6 +1461,7 @@ var MutationCache = class extends Subscribable {
1331
1461
  #mutationId;
1332
1462
  build(client, options, state) {
1333
1463
  const mutation = new Mutation({
1464
+ client,
1334
1465
  mutationCache: this,
1335
1466
  mutationId: ++this.#mutationId,
1336
1467
  options: client.defaultMutationOptions(options),
@@ -1432,113 +1563,94 @@ var MutationCache = class extends Subscribable {
1432
1563
  function scopeFor(mutation) {
1433
1564
  return mutation.options.scope?.id;
1434
1565
  }
1435
- function infiniteQueryBehavior(pages) {
1436
- return {
1437
- onFetch: (context, query) => {
1438
- const options = context.options;
1439
- const direction = context.fetchOptions?.meta?.fetchMore?.direction;
1440
- const oldPages = context.state.data?.pages || [];
1441
- const oldPageParams = context.state.data?.pageParams || [];
1442
- let result = { pages: [], pageParams: [] };
1443
- let currentPage = 0;
1444
- const fetchFn = async () => {
1445
- let cancelled = false;
1446
- const addSignalProperty = (object) => {
1447
- Object.defineProperty(object, "signal", {
1448
- enumerable: true,
1449
- get: () => {
1450
- if (context.signal.aborted) {
1451
- cancelled = true;
1452
- } else {
1453
- context.signal.addEventListener("abort", () => {
1454
- cancelled = true;
1455
- });
1456
- }
1457
- return context.signal;
1458
- }
1459
- });
1460
- };
1461
- const queryFn = ensureQueryFn(context.options, context.fetchOptions);
1462
- const fetchPage = async (data, param, previous) => {
1463
- if (cancelled) {
1464
- return Promise.reject();
1465
- }
1466
- if (param == null && data.pages.length) {
1467
- return Promise.resolve(data);
1468
- }
1469
- const createQueryFnContext = () => {
1470
- const queryFnContext2 = {
1471
- client: context.client,
1472
- queryKey: context.queryKey,
1473
- pageParam: param,
1474
- direction: previous ? "backward" : "forward",
1475
- meta: context.options.meta
1476
- };
1477
- addSignalProperty(queryFnContext2);
1478
- return queryFnContext2;
1479
- };
1480
- const queryFnContext = createQueryFnContext();
1481
- const page = await queryFn(queryFnContext);
1482
- const { maxPages } = context.options;
1483
- const addTo = previous ? addToStart : addToEnd;
1484
- return {
1485
- pages: addTo(data.pages, page, maxPages),
1486
- pageParams: addTo(data.pageParams, param, maxPages)
1487
- };
1488
- };
1489
- if (direction && oldPages.length) {
1490
- const previous = direction === "backward";
1491
- const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;
1492
- const oldData = {
1493
- pages: oldPages,
1494
- pageParams: oldPageParams
1495
- };
1496
- const param = pageParamFn(options, oldData);
1497
- result = await fetchPage(oldData, param, previous);
1498
- } else {
1499
- const remainingPages = pages ?? oldPages.length;
1500
- do {
1501
- const param = currentPage === 0 ? oldPageParams[0] ?? options.initialPageParam : getNextPageParam(options, result);
1502
- if (currentPage > 0 && param == null) {
1503
- break;
1504
- }
1505
- result = await fetchPage(result, param);
1506
- currentPage++;
1507
- } while (currentPage < remainingPages);
1508
- }
1509
- return result;
1510
- };
1511
- if (context.options.persister) {
1512
- context.fetchFn = () => {
1513
- return context.options.persister?.(
1514
- fetchFn,
1515
- {
1516
- client: context.client,
1517
- queryKey: context.queryKey,
1518
- meta: context.options.meta,
1519
- signal: context.signal
1520
- },
1521
- query
1522
- );
1523
- };
1524
- } else {
1525
- context.fetchFn = fetchFn;
1566
+ var QueryCache = class extends Subscribable {
1567
+ constructor(config = {}) {
1568
+ super();
1569
+ this.config = config;
1570
+ this.#queries = /* @__PURE__ */ new Map();
1571
+ }
1572
+ #queries;
1573
+ build(client, options, state) {
1574
+ const queryKey = options.queryKey;
1575
+ const queryHash = options.queryHash ?? hashQueryKeyByOptions(queryKey, options);
1576
+ let query = this.get(queryHash);
1577
+ if (!query) {
1578
+ query = new Query({
1579
+ client,
1580
+ queryKey,
1581
+ queryHash,
1582
+ options: client.defaultQueryOptions(options),
1583
+ state,
1584
+ defaultOptions: client.getQueryDefaults(queryKey)
1585
+ });
1586
+ this.add(query);
1587
+ }
1588
+ return query;
1589
+ }
1590
+ add(query) {
1591
+ if (!this.#queries.has(query.queryHash)) {
1592
+ this.#queries.set(query.queryHash, query);
1593
+ this.notify({
1594
+ type: "added",
1595
+ query
1596
+ });
1597
+ }
1598
+ }
1599
+ remove(query) {
1600
+ const queryInMap = this.#queries.get(query.queryHash);
1601
+ if (queryInMap) {
1602
+ query.destroy();
1603
+ if (queryInMap === query) {
1604
+ this.#queries.delete(query.queryHash);
1526
1605
  }
1606
+ this.notify({ type: "removed", query });
1527
1607
  }
1528
- };
1529
- }
1530
- function getNextPageParam(options, { pages, pageParams }) {
1531
- const lastIndex = pages.length - 1;
1532
- return pages.length > 0 ? options.getNextPageParam(
1533
- pages[lastIndex],
1534
- pages,
1535
- pageParams[lastIndex],
1536
- pageParams
1537
- ) : void 0;
1538
- }
1539
- function getPreviousPageParam(options, { pages, pageParams }) {
1540
- return pages.length > 0 ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams) : void 0;
1541
- }
1608
+ }
1609
+ clear() {
1610
+ notifyManager.batch(() => {
1611
+ this.getAll().forEach((query) => {
1612
+ this.remove(query);
1613
+ });
1614
+ });
1615
+ }
1616
+ get(queryHash) {
1617
+ return this.#queries.get(queryHash);
1618
+ }
1619
+ getAll() {
1620
+ return [...this.#queries.values()];
1621
+ }
1622
+ find(filters) {
1623
+ const defaultedFilters = { exact: true, ...filters };
1624
+ return this.getAll().find(
1625
+ (query) => matchQuery(defaultedFilters, query)
1626
+ );
1627
+ }
1628
+ findAll(filters = {}) {
1629
+ const queries = this.getAll();
1630
+ return Object.keys(filters).length > 0 ? queries.filter((query) => matchQuery(filters, query)) : queries;
1631
+ }
1632
+ notify(event) {
1633
+ notifyManager.batch(() => {
1634
+ this.listeners.forEach((listener) => {
1635
+ listener(event);
1636
+ });
1637
+ });
1638
+ }
1639
+ onFocus() {
1640
+ notifyManager.batch(() => {
1641
+ this.getAll().forEach((query) => {
1642
+ query.onFocus();
1643
+ });
1644
+ });
1645
+ }
1646
+ onOnline() {
1647
+ notifyManager.batch(() => {
1648
+ this.getAll().forEach((query) => {
1649
+ query.onOnline();
1650
+ });
1651
+ });
1652
+ }
1653
+ };
1542
1654
  var QueryClient = class {
1543
1655
  #queryCache;
1544
1656
  #mutationCache;