@camstack/addon-pipeline-orchestrator 0.1.17 → 0.1.18

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 (68) hide show
  1. package/dist/@mf-types.zip +0 -0
  2. package/dist/ReactKonva-JXCACcqD.mjs +7267 -0
  3. package/dist/_CoreInternals-B7PHssO3.mjs +3808 -0
  4. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare___mf_0_camstack_mf_1_sdk__loadShare__.mjs-h5aXOPSA.mjs +12 -0
  5. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.mjs-UNj4rttw.mjs +20 -0
  6. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.mjs-XtEtGou1.mjs +34 -0
  7. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.mjs-DoWbefqS.mjs +104 -0
  8. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare___mf_0_trpc_mf_1_client__loadShare__.mjs-D4eEXltm.mjs +85 -0
  9. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.mjs-CVrnrGED.mjs +62 -0
  10. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare__konva__loadShare__.mjs-F783v1sm.mjs +8 -0
  11. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare__react__loadShare__.mjs-0qpbQxoV.mjs +88 -0
  12. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare__react__loadShare__.mjs_commonjs-proxy-DekuE8px.mjs +29 -0
  13. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare__react_mf_1_jsx_mf_2_runtime__loadShare__.mjs-Cg6QsnjR.mjs +36 -0
  14. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare__react_mf_2_dom__loadShare__.mjs-Dp8hqYOB.mjs +45 -0
  15. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-Ba_7PYkj.mjs +6 -0
  16. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs-BBmNf5hf.mjs +34 -0
  17. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare__react_mf_2_konva__loadShare__.mjs-CJUQOcTE.mjs +18 -0
  18. package/dist/_stub.js +1047 -21451
  19. package/dist/{_virtual_mf-localSharedImportMap___mfe_internal__addon_pipeline_orchestrator_widgets-D4U9-5a3.mjs → _virtual_mf-localSharedImportMap___mfe_internal__addon_pipeline_orchestrator_widgets-GASHflbS.mjs} +75 -66
  20. package/dist/client-CzjQ3uuI.mjs +9836 -0
  21. package/dist/getErrorShape-BPSzUA7W-TlK8ipWe.mjs +211 -0
  22. package/dist/hostInit-B0XiFU2K.mjs +196 -0
  23. package/dist/index-BD2XShwZ.mjs +20965 -0
  24. package/dist/index-BIlr4dIX.mjs +1655 -0
  25. package/dist/index-BP1Nti7b.mjs +13431 -0
  26. package/dist/index-C1DnrJuR.mjs +2603 -0
  27. package/dist/index-C52WDzRJ.mjs +3842 -0
  28. package/dist/index-CWkKuNLr.mjs +232 -0
  29. package/dist/index-Cbqs9uJn.mjs +725 -0
  30. package/dist/index-DOuehnyb.mjs +185 -0
  31. package/dist/index-DaulYonp.mjs +435 -0
  32. package/dist/index-xncRG7-x.mjs +2713 -0
  33. package/dist/index.js +6 -1
  34. package/dist/index.js.map +1 -1
  35. package/dist/index.mjs +6 -1
  36. package/dist/index.mjs.map +1 -1
  37. package/dist/jsx-runtime-DACJhJOv.mjs +55 -0
  38. package/dist/remoteEntry.js +2327 -3351
  39. package/dist/schemas-ChN4Ih0h.mjs +3584 -0
  40. package/dist/virtualExposes-8FzWTdq3.mjs +42 -0
  41. package/package.json +1 -1
  42. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare___mf_0_camstack_mf_1_sdk__loadShare__.mjs-Dn6pffG6.mjs +0 -14
  43. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.mjs-DrteYOPu.mjs +0 -22
  44. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.mjs-DfNJpPfu.mjs +0 -36
  45. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.mjs-CaQq3kr4.mjs +0 -112
  46. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare___mf_0_trpc_mf_1_client__loadShare__.mjs-DhUh9Qzt.mjs +0 -93
  47. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.mjs-DOHfklLX.mjs +0 -70
  48. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare__react__loadShare__.mjs-BX5snCRm.mjs +0 -96
  49. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare__react__loadShare__.mjs_commonjs-proxy-Bg2N8TAe.mjs +0 -34
  50. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare__react_mf_1_jsx_mf_2_runtime__loadShare__.mjs-CO0PugXp.mjs +0 -44
  51. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare__react_mf_2_dom__loadShare__.mjs-Cqpb8kvp.mjs +0 -53
  52. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-DnIwYUrp.mjs +0 -6
  53. package/dist/__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs-Iv-aGQ4k.mjs +0 -42
  54. package/dist/client-TtgJQfbd.mjs +0 -11569
  55. package/dist/getErrorShape-BPSzUA7W-D5KpHcIj.mjs +0 -244
  56. package/dist/hostInit-C89SX6z4.mjs +0 -198
  57. package/dist/index-0-mfXOlq.mjs +0 -899
  58. package/dist/index-BKVjF_OI.mjs +0 -14804
  59. package/dist/index-BN2rV_KJ.mjs +0 -463
  60. package/dist/index-BepH9mzJ.mjs +0 -3536
  61. package/dist/index-BxLvm_gu.mjs +0 -267
  62. package/dist/index-CVOLs7Aq.mjs +0 -24402
  63. package/dist/index-Cfo7sGh_.mjs +0 -2054
  64. package/dist/index-CrGKNQoE.mjs +0 -3260
  65. package/dist/index-sCAUpX2M.mjs +0 -197
  66. package/dist/jsx-runtime-D2w1zDMK.mjs +0 -67
  67. package/dist/schemas-DihhZLrP.mjs +0 -5087
  68. package/dist/virtualExposes-D_9EJnra.mjs +0 -59
@@ -1,3536 +0,0 @@
1
- import { j as __mf_13, e as __mf_28, h as __mf_25, d as __mf_38, c as __mf_34, n as __mf_39, m as __mf_24, l as __mf_37 } from "./__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare__react__loadShare__.mjs-BX5snCRm.mjs";
2
- import { _ as __mf_1 } from "./__mfe_internal__addon_pipeline_orchestrator_widgets__loadShare__react_mf_1_jsx_mf_2_runtime__loadShare__.mjs-CO0PugXp.mjs";
3
- var Subscribable = class {
4
- constructor() {
5
- this.listeners = /* @__PURE__ */ new Set();
6
- this.subscribe = this.subscribe.bind(this);
7
- }
8
- subscribe(listener) {
9
- this.listeners.add(listener);
10
- this.onSubscribe();
11
- return () => {
12
- this.listeners.delete(listener);
13
- this.onUnsubscribe();
14
- };
15
- }
16
- hasListeners() {
17
- return this.listeners.size > 0;
18
- }
19
- onSubscribe() {
20
- }
21
- onUnsubscribe() {
22
- }
23
- };
24
- var FocusManager = class extends Subscribable {
25
- #focused;
26
- #cleanup;
27
- #setup;
28
- constructor() {
29
- super();
30
- this.#setup = (onFocus) => {
31
- if (typeof window !== "undefined" && window.addEventListener) {
32
- const listener = () => onFocus();
33
- window.addEventListener("visibilitychange", listener, false);
34
- return () => {
35
- window.removeEventListener("visibilitychange", listener);
36
- };
37
- }
38
- return;
39
- };
40
- }
41
- onSubscribe() {
42
- if (!this.#cleanup) {
43
- this.setEventListener(this.#setup);
44
- }
45
- }
46
- onUnsubscribe() {
47
- if (!this.hasListeners()) {
48
- this.#cleanup?.();
49
- this.#cleanup = void 0;
50
- }
51
- }
52
- setEventListener(setup) {
53
- this.#setup = setup;
54
- this.#cleanup?.();
55
- this.#cleanup = setup((focused) => {
56
- if (typeof focused === "boolean") {
57
- this.setFocused(focused);
58
- } else {
59
- this.onFocus();
60
- }
61
- });
62
- }
63
- setFocused(focused) {
64
- const changed = this.#focused !== focused;
65
- if (changed) {
66
- this.#focused = focused;
67
- this.onFocus();
68
- }
69
- }
70
- onFocus() {
71
- const isFocused = this.isFocused();
72
- this.listeners.forEach((listener) => {
73
- listener(isFocused);
74
- });
75
- }
76
- isFocused() {
77
- if (typeof this.#focused === "boolean") {
78
- return this.#focused;
79
- }
80
- return globalThis.document?.visibilityState !== "hidden";
81
- }
82
- };
83
- var focusManager = new FocusManager();
84
- var defaultTimeoutProvider = {
85
- // We need the wrapper function syntax below instead of direct references to
86
- // global setTimeout etc.
87
- //
88
- // BAD: `setTimeout: setTimeout`
89
- // GOOD: `setTimeout: (cb, delay) => setTimeout(cb, delay)`
90
- //
91
- // If we use direct references here, then anything that wants to spy on or
92
- // replace the global setTimeout (like tests) won't work since we'll already
93
- // have a hard reference to the original implementation at the time when this
94
- // file was imported.
95
- setTimeout: (callback, delay) => setTimeout(callback, delay),
96
- clearTimeout: (timeoutId) => clearTimeout(timeoutId),
97
- setInterval: (callback, delay) => setInterval(callback, delay),
98
- clearInterval: (intervalId) => clearInterval(intervalId)
99
- };
100
- var TimeoutManager = class {
101
- // We cannot have TimeoutManager<T> as we must instantiate it with a concrete
102
- // type at app boot; and if we leave that type, then any new timer provider
103
- // would need to support the default provider's concrete timer ID, which is
104
- // infeasible across environments.
105
- //
106
- // We settle for type safety for the TimeoutProvider type, and accept that
107
- // this class is unsafe internally to allow for extension.
108
- #provider = defaultTimeoutProvider;
109
- #providerCalled = false;
110
- setTimeoutProvider(provider) {
111
- this.#provider = provider;
112
- }
113
- setTimeout(callback, delay) {
114
- return this.#provider.setTimeout(callback, delay);
115
- }
116
- clearTimeout(timeoutId) {
117
- this.#provider.clearTimeout(timeoutId);
118
- }
119
- setInterval(callback, delay) {
120
- return this.#provider.setInterval(callback, delay);
121
- }
122
- clearInterval(intervalId) {
123
- this.#provider.clearInterval(intervalId);
124
- }
125
- };
126
- var timeoutManager = new TimeoutManager();
127
- function systemSetTimeoutZero(callback) {
128
- setTimeout(callback, 0);
129
- }
130
- var isServer = typeof window === "undefined" || "Deno" in globalThis;
131
- function noop() {
132
- }
133
- function functionalUpdate(updater, input) {
134
- return typeof updater === "function" ? updater(input) : updater;
135
- }
136
- function isValidTimeout(value) {
137
- return typeof value === "number" && value >= 0 && value !== Infinity;
138
- }
139
- function timeUntilStale(updatedAt, staleTime) {
140
- return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0);
141
- }
142
- function resolveStaleTime(staleTime, query) {
143
- return typeof staleTime === "function" ? staleTime(query) : staleTime;
144
- }
145
- function resolveQueryBoolean(option, query) {
146
- return typeof option === "function" ? option(query) : option;
147
- }
148
- function matchQuery(filters, query) {
149
- const {
150
- type = "all",
151
- exact,
152
- fetchStatus,
153
- predicate,
154
- queryKey,
155
- stale
156
- } = filters;
157
- if (queryKey) {
158
- if (exact) {
159
- if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
160
- return false;
161
- }
162
- } else if (!partialMatchKey(query.queryKey, queryKey)) {
163
- return false;
164
- }
165
- }
166
- if (type !== "all") {
167
- const isActive = query.isActive();
168
- if (type === "active" && !isActive) {
169
- return false;
170
- }
171
- if (type === "inactive" && isActive) {
172
- return false;
173
- }
174
- }
175
- if (typeof stale === "boolean" && query.isStale() !== stale) {
176
- return false;
177
- }
178
- if (fetchStatus && fetchStatus !== query.state.fetchStatus) {
179
- return false;
180
- }
181
- if (predicate && !predicate(query)) {
182
- return false;
183
- }
184
- return true;
185
- }
186
- function matchMutation(filters, mutation) {
187
- const { exact, status, predicate, mutationKey } = filters;
188
- if (mutationKey) {
189
- if (!mutation.options.mutationKey) {
190
- return false;
191
- }
192
- if (exact) {
193
- if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {
194
- return false;
195
- }
196
- } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {
197
- return false;
198
- }
199
- }
200
- if (status && mutation.state.status !== status) {
201
- return false;
202
- }
203
- if (predicate && !predicate(mutation)) {
204
- return false;
205
- }
206
- return true;
207
- }
208
- function hashQueryKeyByOptions(queryKey, options) {
209
- const hashFn = options?.queryKeyHashFn || hashKey;
210
- return hashFn(queryKey);
211
- }
212
- function hashKey(queryKey) {
213
- return JSON.stringify(
214
- queryKey,
215
- (_, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key) => {
216
- result[key] = val[key];
217
- return result;
218
- }, {}) : val
219
- );
220
- }
221
- function partialMatchKey(a, b) {
222
- if (a === b) {
223
- return true;
224
- }
225
- if (typeof a !== typeof b) {
226
- return false;
227
- }
228
- if (a && b && typeof a === "object" && typeof b === "object") {
229
- return Object.keys(b).every((key) => partialMatchKey(a[key], b[key]));
230
- }
231
- return false;
232
- }
233
- var hasOwn = Object.prototype.hasOwnProperty;
234
- function replaceEqualDeep(a, b, depth = 0) {
235
- if (a === b) {
236
- return a;
237
- }
238
- if (depth > 500) return b;
239
- const array = isPlainArray(a) && isPlainArray(b);
240
- if (!array && !(isPlainObject(a) && isPlainObject(b))) return b;
241
- const aItems = array ? a : Object.keys(a);
242
- const aSize = aItems.length;
243
- const bItems = array ? b : Object.keys(b);
244
- const bSize = bItems.length;
245
- const copy = array ? new Array(bSize) : {};
246
- let equalItems = 0;
247
- for (let i = 0; i < bSize; i++) {
248
- const key = array ? i : bItems[i];
249
- const aItem = a[key];
250
- const bItem = b[key];
251
- if (aItem === bItem) {
252
- copy[key] = aItem;
253
- if (array ? i < aSize : hasOwn.call(a, key)) equalItems++;
254
- continue;
255
- }
256
- if (aItem === null || bItem === null || typeof aItem !== "object" || typeof bItem !== "object") {
257
- copy[key] = bItem;
258
- continue;
259
- }
260
- const v = replaceEqualDeep(aItem, bItem, depth + 1);
261
- copy[key] = v;
262
- if (v === aItem) equalItems++;
263
- }
264
- return aSize === bSize && equalItems === aSize ? a : copy;
265
- }
266
- function shallowEqualObjects(a, b) {
267
- if (!b || Object.keys(a).length !== Object.keys(b).length) {
268
- return false;
269
- }
270
- for (const key in a) {
271
- if (a[key] !== b[key]) {
272
- return false;
273
- }
274
- }
275
- return true;
276
- }
277
- function isPlainArray(value) {
278
- return Array.isArray(value) && value.length === Object.keys(value).length;
279
- }
280
- function isPlainObject(o) {
281
- if (!hasObjectPrototype(o)) {
282
- return false;
283
- }
284
- const ctor = o.constructor;
285
- if (ctor === void 0) {
286
- return true;
287
- }
288
- const prot = ctor.prototype;
289
- if (!hasObjectPrototype(prot)) {
290
- return false;
291
- }
292
- if (!prot.hasOwnProperty("isPrototypeOf")) {
293
- return false;
294
- }
295
- if (Object.getPrototypeOf(o) !== Object.prototype) {
296
- return false;
297
- }
298
- return true;
299
- }
300
- function hasObjectPrototype(o) {
301
- return Object.prototype.toString.call(o) === "[object Object]";
302
- }
303
- function sleep(timeout) {
304
- return new Promise((resolve) => {
305
- timeoutManager.setTimeout(resolve, timeout);
306
- });
307
- }
308
- function replaceData(prevData, data, options) {
309
- if (typeof options.structuralSharing === "function") {
310
- return options.structuralSharing(prevData, data);
311
- } else if (options.structuralSharing !== false) {
312
- return replaceEqualDeep(prevData, data);
313
- }
314
- return data;
315
- }
316
- function keepPreviousData(previousData) {
317
- return previousData;
318
- }
319
- function addToEnd(items, item, max = 0) {
320
- const newItems = [...items, item];
321
- return max && newItems.length > max ? newItems.slice(1) : newItems;
322
- }
323
- function addToStart(items, item, max = 0) {
324
- const newItems = [item, ...items];
325
- return max && newItems.length > max ? newItems.slice(0, -1) : newItems;
326
- }
327
- var skipToken = /* @__PURE__ */ Symbol();
328
- function ensureQueryFn(options, fetchOptions) {
329
- if (!options.queryFn && fetchOptions?.initialPromise) {
330
- return () => fetchOptions.initialPromise;
331
- }
332
- if (!options.queryFn || options.queryFn === skipToken) {
333
- return () => Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`));
334
- }
335
- return options.queryFn;
336
- }
337
- function shouldThrowError(throwOnError, params) {
338
- if (typeof throwOnError === "function") {
339
- return throwOnError(...params);
340
- }
341
- return !!throwOnError;
342
- }
343
- function addConsumeAwareSignal(object, getSignal, onCancelled) {
344
- let consumed = false;
345
- let signal;
346
- Object.defineProperty(object, "signal", {
347
- enumerable: true,
348
- get: () => {
349
- signal ??= getSignal();
350
- if (consumed) {
351
- return signal;
352
- }
353
- consumed = true;
354
- if (signal.aborted) {
355
- onCancelled();
356
- } else {
357
- signal.addEventListener("abort", onCancelled, { once: true });
358
- }
359
- return signal;
360
- }
361
- });
362
- return object;
363
- }
364
- var environmentManager = /* @__PURE__ */ (() => {
365
- let isServerFn = () => isServer;
366
- return {
367
- /**
368
- * Returns whether the current runtime should be treated as a server environment.
369
- */
370
- isServer() {
371
- return isServerFn();
372
- },
373
- /**
374
- * Overrides the server check globally.
375
- */
376
- setIsServer(isServerValue) {
377
- isServerFn = isServerValue;
378
- }
379
- };
380
- })();
381
- function pendingThenable() {
382
- let resolve;
383
- let reject;
384
- const thenable = new Promise((_resolve, _reject) => {
385
- resolve = _resolve;
386
- reject = _reject;
387
- });
388
- thenable.status = "pending";
389
- thenable.catch(() => {
390
- });
391
- function finalize(data) {
392
- Object.assign(thenable, data);
393
- delete thenable.resolve;
394
- delete thenable.reject;
395
- }
396
- thenable.resolve = (value) => {
397
- finalize({
398
- status: "fulfilled",
399
- value
400
- });
401
- resolve(value);
402
- };
403
- thenable.reject = (reason) => {
404
- finalize({
405
- status: "rejected",
406
- reason
407
- });
408
- reject(reason);
409
- };
410
- return thenable;
411
- }
412
- function tryResolveSync(promise) {
413
- let data;
414
- promise.then((result) => {
415
- data = result;
416
- return result;
417
- }, noop)?.catch(noop);
418
- if (data !== void 0) {
419
- return { data };
420
- }
421
- return void 0;
422
- }
423
- function defaultTransformerFn(data) {
424
- return data;
425
- }
426
- function dehydrateMutation(mutation) {
427
- return {
428
- mutationKey: mutation.options.mutationKey,
429
- state: mutation.state,
430
- ...mutation.options.scope && { scope: mutation.options.scope },
431
- ...mutation.meta && { meta: mutation.meta }
432
- };
433
- }
434
- function dehydrateQuery(query, serializeData, shouldRedactErrors) {
435
- const dehydratePromise = () => {
436
- const promise = query.promise?.then(serializeData).catch((error) => {
437
- if (!shouldRedactErrors(error)) {
438
- return Promise.reject(error);
439
- }
440
- return Promise.reject(new Error("redacted"));
441
- });
442
- promise?.catch(noop);
443
- return promise;
444
- };
445
- return {
446
- dehydratedAt: Date.now(),
447
- state: {
448
- ...query.state,
449
- ...query.state.data !== void 0 && {
450
- data: serializeData(query.state.data)
451
- }
452
- },
453
- queryKey: query.queryKey,
454
- queryHash: query.queryHash,
455
- ...query.state.status === "pending" && {
456
- promise: dehydratePromise()
457
- },
458
- ...query.meta && { meta: query.meta },
459
- ...query.queryType && { queryType: query.queryType }
460
- };
461
- }
462
- function defaultShouldDehydrateMutation(mutation) {
463
- return mutation.state.isPaused;
464
- }
465
- function defaultShouldDehydrateQuery(query) {
466
- return query.state.status === "success";
467
- }
468
- function defaultShouldRedactErrors(_) {
469
- return true;
470
- }
471
- function dehydrate(client, options = {}) {
472
- const filterMutation = options.shouldDehydrateMutation ?? client.getDefaultOptions().dehydrate?.shouldDehydrateMutation ?? defaultShouldDehydrateMutation;
473
- const mutations = client.getMutationCache().getAll().flatMap(
474
- (mutation) => filterMutation(mutation) ? [dehydrateMutation(mutation)] : []
475
- );
476
- const filterQuery = options.shouldDehydrateQuery ?? client.getDefaultOptions().dehydrate?.shouldDehydrateQuery ?? defaultShouldDehydrateQuery;
477
- const shouldRedactErrors = options.shouldRedactErrors ?? client.getDefaultOptions().dehydrate?.shouldRedactErrors ?? defaultShouldRedactErrors;
478
- const serializeData = options.serializeData ?? client.getDefaultOptions().dehydrate?.serializeData ?? defaultTransformerFn;
479
- const queries = client.getQueryCache().getAll().flatMap(
480
- (query) => filterQuery(query) ? [dehydrateQuery(query, serializeData, shouldRedactErrors)] : []
481
- );
482
- return { mutations, queries };
483
- }
484
- function hydrate(client, dehydratedState, options) {
485
- if (typeof dehydratedState !== "object" || dehydratedState === null) {
486
- return;
487
- }
488
- const mutationCache = client.getMutationCache();
489
- const queryCache = client.getQueryCache();
490
- const deserializeData = options?.defaultOptions?.deserializeData ?? client.getDefaultOptions().hydrate?.deserializeData ?? defaultTransformerFn;
491
- const mutations = dehydratedState.mutations || [];
492
- const queries = dehydratedState.queries || [];
493
- mutations.forEach(({ state, ...mutationOptions2 }) => {
494
- mutationCache.build(
495
- client,
496
- {
497
- ...client.getDefaultOptions().hydrate?.mutations,
498
- ...options?.defaultOptions?.mutations,
499
- ...mutationOptions2
500
- },
501
- state
502
- );
503
- });
504
- queries.forEach(
505
- ({
506
- queryKey,
507
- state,
508
- queryHash,
509
- meta,
510
- promise,
511
- dehydratedAt,
512
- queryType
513
- }) => {
514
- const syncData = promise ? tryResolveSync(promise) : void 0;
515
- const rawData = state.data === void 0 ? syncData?.data : state.data;
516
- const data = rawData === void 0 ? rawData : deserializeData(rawData);
517
- let query = queryCache.get(queryHash);
518
- const existingQueryIsPending = query?.state.status === "pending";
519
- const existingQueryIsFetching = query?.state.fetchStatus === "fetching";
520
- if (query) {
521
- const hasNewerSyncData = syncData && // We only need this undefined check to handle older dehydration
522
- // payloads that might not have dehydratedAt
523
- dehydratedAt !== void 0 && dehydratedAt > query.state.dataUpdatedAt;
524
- if (state.dataUpdatedAt > query.state.dataUpdatedAt || hasNewerSyncData) {
525
- const { fetchStatus: _ignored, ...serializedState } = state;
526
- query.setState({
527
- ...serializedState,
528
- data,
529
- // If the query was pending at the moment of dehydration, but resolved to have data
530
- // before hydration, we can assume the query should be hydrated as successful.
531
- //
532
- // Since you can opt into dehydrating failed queries, and those can have data from
533
- // previous successful fetches, we make sure we only do this for pending queries.
534
- ...state.status === "pending" && data !== void 0 && {
535
- status: "success",
536
- // Preserve existing fetchStatus if the existing query is actively fetching.
537
- ...!existingQueryIsFetching && {
538
- fetchStatus: "idle"
539
- }
540
- }
541
- });
542
- }
543
- } else {
544
- query = queryCache.build(
545
- client,
546
- {
547
- ...client.getDefaultOptions().hydrate?.queries,
548
- ...options?.defaultOptions?.queries,
549
- queryKey,
550
- queryHash,
551
- meta,
552
- _type: queryType
553
- },
554
- // Reset fetch status to idle to avoid
555
- // query being stuck in fetching state upon hydration
556
- {
557
- ...state,
558
- data,
559
- fetchStatus: "idle",
560
- // Like above, if the query was pending at the moment of dehydration but has data,
561
- // we can assume it should be hydrated as successful.
562
- status: state.status === "pending" && data !== void 0 ? "success" : state.status
563
- }
564
- );
565
- }
566
- if (promise && // If the data was synchronously available, there is no need to set up
567
- // a retryer and thus no reason to call fetch
568
- !syncData && !existingQueryIsPending && !existingQueryIsFetching && // Only hydrate if dehydration is newer than any existing data,
569
- // this is always true for new queries
570
- (dehydratedAt === void 0 || dehydratedAt > query.state.dataUpdatedAt)) {
571
- query.fetch(void 0, {
572
- // RSC transformed promises are not thenable
573
- initialPromise: Promise.resolve(promise).then(deserializeData)
574
- }).catch(noop);
575
- }
576
- }
577
- );
578
- }
579
- var defaultScheduler = systemSetTimeoutZero;
580
- function createNotifyManager() {
581
- let queue = [];
582
- let transactions = 0;
583
- let notifyFn = (callback) => {
584
- callback();
585
- };
586
- let batchNotifyFn = (callback) => {
587
- callback();
588
- };
589
- let scheduleFn = defaultScheduler;
590
- const schedule = (callback) => {
591
- if (transactions) {
592
- queue.push(callback);
593
- } else {
594
- scheduleFn(() => {
595
- notifyFn(callback);
596
- });
597
- }
598
- };
599
- const flush = () => {
600
- const originalQueue = queue;
601
- queue = [];
602
- if (originalQueue.length) {
603
- scheduleFn(() => {
604
- batchNotifyFn(() => {
605
- originalQueue.forEach((callback) => {
606
- notifyFn(callback);
607
- });
608
- });
609
- });
610
- }
611
- };
612
- return {
613
- batch: (callback) => {
614
- let result;
615
- transactions++;
616
- try {
617
- result = callback();
618
- } finally {
619
- transactions--;
620
- if (!transactions) {
621
- flush();
622
- }
623
- }
624
- return result;
625
- },
626
- /**
627
- * All calls to the wrapped function will be batched.
628
- */
629
- batchCalls: (callback) => {
630
- return (...args) => {
631
- schedule(() => {
632
- callback(...args);
633
- });
634
- };
635
- },
636
- schedule,
637
- /**
638
- * Use this method to set a custom notify function.
639
- * This can be used to for example wrap notifications with `React.act` while running tests.
640
- */
641
- setNotifyFunction: (fn) => {
642
- notifyFn = fn;
643
- },
644
- /**
645
- * Use this method to set a custom function to batch notifications together into a single tick.
646
- * By default React Query will use the batch function provided by ReactDOM or React Native.
647
- */
648
- setBatchNotifyFunction: (fn) => {
649
- batchNotifyFn = fn;
650
- },
651
- setScheduler: (fn) => {
652
- scheduleFn = fn;
653
- }
654
- };
655
- }
656
- var notifyManager = createNotifyManager();
657
- var OnlineManager = class extends Subscribable {
658
- #online = true;
659
- #cleanup;
660
- #setup;
661
- constructor() {
662
- super();
663
- this.#setup = (onOnline) => {
664
- if (typeof window !== "undefined" && window.addEventListener) {
665
- const onlineListener = () => onOnline(true);
666
- const offlineListener = () => onOnline(false);
667
- window.addEventListener("online", onlineListener, false);
668
- window.addEventListener("offline", offlineListener, false);
669
- return () => {
670
- window.removeEventListener("online", onlineListener);
671
- window.removeEventListener("offline", offlineListener);
672
- };
673
- }
674
- return;
675
- };
676
- }
677
- onSubscribe() {
678
- if (!this.#cleanup) {
679
- this.setEventListener(this.#setup);
680
- }
681
- }
682
- onUnsubscribe() {
683
- if (!this.hasListeners()) {
684
- this.#cleanup?.();
685
- this.#cleanup = void 0;
686
- }
687
- }
688
- setEventListener(setup) {
689
- this.#setup = setup;
690
- this.#cleanup?.();
691
- this.#cleanup = setup(this.setOnline.bind(this));
692
- }
693
- setOnline(online) {
694
- const changed = this.#online !== online;
695
- if (changed) {
696
- this.#online = online;
697
- this.listeners.forEach((listener) => {
698
- listener(online);
699
- });
700
- }
701
- }
702
- isOnline() {
703
- return this.#online;
704
- }
705
- };
706
- var onlineManager = new OnlineManager();
707
- function defaultRetryDelay(failureCount) {
708
- return Math.min(1e3 * 2 ** failureCount, 3e4);
709
- }
710
- function canFetch(networkMode) {
711
- return (networkMode ?? "online") === "online" ? onlineManager.isOnline() : true;
712
- }
713
- var CancelledError = class extends Error {
714
- constructor(options) {
715
- super("CancelledError");
716
- this.revert = options?.revert;
717
- this.silent = options?.silent;
718
- }
719
- };
720
- function isCancelledError(value) {
721
- return value instanceof CancelledError;
722
- }
723
- function createRetryer(config) {
724
- let isRetryCancelled = false;
725
- let failureCount = 0;
726
- let continueFn;
727
- const thenable = pendingThenable();
728
- const isResolved = () => thenable.status !== "pending";
729
- const cancel = (cancelOptions) => {
730
- if (!isResolved()) {
731
- const error = new CancelledError(cancelOptions);
732
- reject(error);
733
- config.onCancel?.(error);
734
- }
735
- };
736
- const cancelRetry = () => {
737
- isRetryCancelled = true;
738
- };
739
- const continueRetry = () => {
740
- isRetryCancelled = false;
741
- };
742
- const canContinue = () => focusManager.isFocused() && (config.networkMode === "always" || onlineManager.isOnline()) && config.canRun();
743
- const canStart = () => canFetch(config.networkMode) && config.canRun();
744
- const resolve = (value) => {
745
- if (!isResolved()) {
746
- continueFn?.();
747
- thenable.resolve(value);
748
- }
749
- };
750
- const reject = (value) => {
751
- if (!isResolved()) {
752
- continueFn?.();
753
- thenable.reject(value);
754
- }
755
- };
756
- const pause = () => {
757
- return new Promise((continueResolve) => {
758
- continueFn = (value) => {
759
- if (isResolved() || canContinue()) {
760
- continueResolve(value);
761
- }
762
- };
763
- config.onPause?.();
764
- }).then(() => {
765
- continueFn = void 0;
766
- if (!isResolved()) {
767
- config.onContinue?.();
768
- }
769
- });
770
- };
771
- const run = () => {
772
- if (isResolved()) {
773
- return;
774
- }
775
- let promiseOrValue;
776
- const initialPromise = failureCount === 0 ? config.initialPromise : void 0;
777
- try {
778
- promiseOrValue = initialPromise ?? config.fn();
779
- } catch (error) {
780
- promiseOrValue = Promise.reject(error);
781
- }
782
- Promise.resolve(promiseOrValue).then(resolve).catch((error) => {
783
- if (isResolved()) {
784
- return;
785
- }
786
- const retry = config.retry ?? (environmentManager.isServer() ? 0 : 3);
787
- const retryDelay = config.retryDelay ?? defaultRetryDelay;
788
- const delay = typeof retryDelay === "function" ? retryDelay(failureCount, error) : retryDelay;
789
- const shouldRetry = retry === true || typeof retry === "number" && failureCount < retry || typeof retry === "function" && retry(failureCount, error);
790
- if (isRetryCancelled || !shouldRetry) {
791
- reject(error);
792
- return;
793
- }
794
- failureCount++;
795
- config.onFail?.(failureCount, error);
796
- sleep(delay).then(() => {
797
- return canContinue() ? void 0 : pause();
798
- }).then(() => {
799
- if (isRetryCancelled) {
800
- reject(error);
801
- } else {
802
- run();
803
- }
804
- });
805
- });
806
- };
807
- return {
808
- promise: thenable,
809
- status: () => thenable.status,
810
- cancel,
811
- continue: () => {
812
- continueFn?.();
813
- return thenable;
814
- },
815
- cancelRetry,
816
- continueRetry,
817
- canStart,
818
- start: () => {
819
- if (canStart()) {
820
- run();
821
- } else {
822
- pause().then(run);
823
- }
824
- return thenable;
825
- }
826
- };
827
- }
828
- var Removable = class {
829
- #gcTimeout;
830
- destroy() {
831
- this.clearGcTimeout();
832
- }
833
- scheduleGc() {
834
- this.clearGcTimeout();
835
- if (isValidTimeout(this.gcTime)) {
836
- this.#gcTimeout = timeoutManager.setTimeout(() => {
837
- this.optionalRemove();
838
- }, this.gcTime);
839
- }
840
- }
841
- updateGcTime(newGcTime) {
842
- this.gcTime = Math.max(
843
- this.gcTime || 0,
844
- newGcTime ?? (environmentManager.isServer() ? Infinity : 5 * 60 * 1e3)
845
- );
846
- }
847
- clearGcTimeout() {
848
- if (this.#gcTimeout !== void 0) {
849
- timeoutManager.clearTimeout(this.#gcTimeout);
850
- this.#gcTimeout = void 0;
851
- }
852
- }
853
- };
854
- function infiniteQueryBehavior(pages) {
855
- return {
856
- onFetch: (context, query) => {
857
- const options = context.options;
858
- const direction = context.fetchOptions?.meta?.fetchMore?.direction;
859
- const oldPages = context.state.data?.pages || [];
860
- const oldPageParams = context.state.data?.pageParams || [];
861
- let result = { pages: [], pageParams: [] };
862
- let currentPage = 0;
863
- const fetchFn = async () => {
864
- let cancelled = false;
865
- const addSignalProperty = (object) => {
866
- addConsumeAwareSignal(
867
- object,
868
- () => context.signal,
869
- () => cancelled = true
870
- );
871
- };
872
- const queryFn = ensureQueryFn(context.options, context.fetchOptions);
873
- const fetchPage = async (data, param, previous) => {
874
- if (cancelled) {
875
- return Promise.reject(context.signal.reason);
876
- }
877
- if (param == null && data.pages.length) {
878
- return Promise.resolve(data);
879
- }
880
- const createQueryFnContext = () => {
881
- const queryFnContext2 = {
882
- client: context.client,
883
- queryKey: context.queryKey,
884
- pageParam: param,
885
- direction: previous ? "backward" : "forward",
886
- meta: context.options.meta
887
- };
888
- addSignalProperty(queryFnContext2);
889
- return queryFnContext2;
890
- };
891
- const queryFnContext = createQueryFnContext();
892
- const page = await queryFn(queryFnContext);
893
- const { maxPages } = context.options;
894
- const addTo = previous ? addToStart : addToEnd;
895
- return {
896
- pages: addTo(data.pages, page, maxPages),
897
- pageParams: addTo(data.pageParams, param, maxPages)
898
- };
899
- };
900
- if (direction && oldPages.length) {
901
- const previous = direction === "backward";
902
- const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;
903
- const oldData = {
904
- pages: oldPages,
905
- pageParams: oldPageParams
906
- };
907
- const param = pageParamFn(options, oldData);
908
- result = await fetchPage(oldData, param, previous);
909
- } else {
910
- const remainingPages = pages ?? oldPages.length;
911
- do {
912
- const param = currentPage === 0 ? oldPageParams[0] ?? options.initialPageParam : getNextPageParam(options, result);
913
- if (currentPage > 0 && param == null) {
914
- break;
915
- }
916
- result = await fetchPage(result, param);
917
- currentPage++;
918
- } while (currentPage < remainingPages);
919
- }
920
- return result;
921
- };
922
- if (context.options.persister) {
923
- context.fetchFn = () => {
924
- return context.options.persister?.(
925
- fetchFn,
926
- {
927
- client: context.client,
928
- queryKey: context.queryKey,
929
- meta: context.options.meta,
930
- signal: context.signal
931
- },
932
- query
933
- );
934
- };
935
- } else {
936
- context.fetchFn = fetchFn;
937
- }
938
- }
939
- };
940
- }
941
- function getNextPageParam(options, { pages, pageParams }) {
942
- const lastIndex = pages.length - 1;
943
- return pages.length > 0 ? options.getNextPageParam(
944
- pages[lastIndex],
945
- pages,
946
- pageParams[lastIndex],
947
- pageParams
948
- ) : void 0;
949
- }
950
- function getPreviousPageParam(options, { pages, pageParams }) {
951
- return pages.length > 0 ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams) : void 0;
952
- }
953
- function hasNextPage(options, data) {
954
- if (!data) return false;
955
- return getNextPageParam(options, data) != null;
956
- }
957
- function hasPreviousPage(options, data) {
958
- if (!data || !options.getPreviousPageParam) return false;
959
- return getPreviousPageParam(options, data) != null;
960
- }
961
- var Query = class extends Removable {
962
- #queryType;
963
- #initialState;
964
- #revertState;
965
- #cache;
966
- #client;
967
- #retryer;
968
- #defaultOptions;
969
- #abortSignalConsumed;
970
- constructor(config) {
971
- super();
972
- this.#abortSignalConsumed = false;
973
- this.#defaultOptions = config.defaultOptions;
974
- this.setOptions(config.options);
975
- this.observers = [];
976
- this.#client = config.client;
977
- this.#cache = this.#client.getQueryCache();
978
- this.queryKey = config.queryKey;
979
- this.queryHash = config.queryHash;
980
- this.#initialState = getDefaultState$1(this.options);
981
- this.state = config.state ?? this.#initialState;
982
- this.scheduleGc();
983
- }
984
- get meta() {
985
- return this.options.meta;
986
- }
987
- get queryType() {
988
- return this.#queryType;
989
- }
990
- get promise() {
991
- return this.#retryer?.promise;
992
- }
993
- setOptions(options) {
994
- this.options = { ...this.#defaultOptions, ...options };
995
- if (options?._type) {
996
- this.#queryType = options._type;
997
- }
998
- this.updateGcTime(this.options.gcTime);
999
- if (this.state && this.state.data === void 0) {
1000
- const defaultState = getDefaultState$1(this.options);
1001
- if (defaultState.data !== void 0) {
1002
- this.setState(
1003
- successState(defaultState.data, defaultState.dataUpdatedAt)
1004
- );
1005
- this.#initialState = defaultState;
1006
- }
1007
- }
1008
- }
1009
- optionalRemove() {
1010
- if (!this.observers.length && this.state.fetchStatus === "idle") {
1011
- this.#cache.remove(this);
1012
- }
1013
- }
1014
- setData(newData, options) {
1015
- const data = replaceData(this.state.data, newData, this.options);
1016
- this.#dispatch({
1017
- data,
1018
- type: "success",
1019
- dataUpdatedAt: options?.updatedAt,
1020
- manual: options?.manual
1021
- });
1022
- return data;
1023
- }
1024
- setState(state) {
1025
- this.#dispatch({ type: "setState", state });
1026
- }
1027
- cancel(options) {
1028
- const promise = this.#retryer?.promise;
1029
- this.#retryer?.cancel(options);
1030
- return promise ? promise.then(noop).catch(noop) : Promise.resolve();
1031
- }
1032
- destroy() {
1033
- super.destroy();
1034
- this.cancel({ silent: true });
1035
- }
1036
- get resetState() {
1037
- return this.#initialState;
1038
- }
1039
- reset() {
1040
- this.destroy();
1041
- this.setState(this.resetState);
1042
- }
1043
- isActive() {
1044
- return this.observers.some(
1045
- (observer) => resolveQueryBoolean(observer.options.enabled, this) !== false
1046
- );
1047
- }
1048
- isDisabled() {
1049
- if (this.getObserversCount() > 0) {
1050
- return !this.isActive();
1051
- }
1052
- return this.options.queryFn === skipToken || !this.isFetched();
1053
- }
1054
- isFetched() {
1055
- return this.state.dataUpdateCount + this.state.errorUpdateCount > 0;
1056
- }
1057
- isStatic() {
1058
- if (this.getObserversCount() > 0) {
1059
- return this.observers.some(
1060
- (observer) => resolveStaleTime(observer.options.staleTime, this) === "static"
1061
- );
1062
- }
1063
- return false;
1064
- }
1065
- isStale() {
1066
- if (this.getObserversCount() > 0) {
1067
- return this.observers.some(
1068
- (observer) => observer.getCurrentResult().isStale
1069
- );
1070
- }
1071
- return this.state.data === void 0 || this.state.isInvalidated;
1072
- }
1073
- isStaleByTime(staleTime = 0) {
1074
- if (this.state.data === void 0) {
1075
- return true;
1076
- }
1077
- if (staleTime === "static") {
1078
- return false;
1079
- }
1080
- if (this.state.isInvalidated) {
1081
- return true;
1082
- }
1083
- return !timeUntilStale(this.state.dataUpdatedAt, staleTime);
1084
- }
1085
- onFocus() {
1086
- const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus());
1087
- observer?.refetch({ cancelRefetch: false });
1088
- this.#retryer?.continue();
1089
- }
1090
- onOnline() {
1091
- const observer = this.observers.find((x) => x.shouldFetchOnReconnect());
1092
- observer?.refetch({ cancelRefetch: false });
1093
- this.#retryer?.continue();
1094
- }
1095
- addObserver(observer) {
1096
- if (!this.observers.includes(observer)) {
1097
- this.observers.push(observer);
1098
- this.clearGcTimeout();
1099
- this.#cache.notify({ type: "observerAdded", query: this, observer });
1100
- }
1101
- }
1102
- removeObserver(observer) {
1103
- if (this.observers.includes(observer)) {
1104
- this.observers = this.observers.filter((x) => x !== observer);
1105
- if (!this.observers.length) {
1106
- if (this.#retryer) {
1107
- if (this.#abortSignalConsumed || this.#isInitialPausedFetch()) {
1108
- this.#retryer.cancel({ revert: true });
1109
- } else {
1110
- this.#retryer.cancelRetry();
1111
- }
1112
- }
1113
- this.scheduleGc();
1114
- }
1115
- this.#cache.notify({ type: "observerRemoved", query: this, observer });
1116
- }
1117
- }
1118
- getObserversCount() {
1119
- return this.observers.length;
1120
- }
1121
- #isInitialPausedFetch() {
1122
- return this.state.fetchStatus === "paused" && this.state.status === "pending";
1123
- }
1124
- invalidate() {
1125
- if (!this.state.isInvalidated) {
1126
- this.#dispatch({ type: "invalidate" });
1127
- }
1128
- }
1129
- async fetch(options, fetchOptions) {
1130
- if (this.state.fetchStatus !== "idle" && // If the promise in the retryer is already rejected, we have to definitely
1131
- // re-start the fetch; there is a chance that the query is still in a
1132
- // pending state when that happens
1133
- this.#retryer?.status() !== "rejected") {
1134
- if (this.state.data !== void 0 && fetchOptions?.cancelRefetch) {
1135
- this.cancel({ silent: true });
1136
- } else if (this.#retryer) {
1137
- this.#retryer.continueRetry();
1138
- return this.#retryer.promise;
1139
- }
1140
- }
1141
- if (options) {
1142
- this.setOptions(options);
1143
- }
1144
- if (!this.options.queryFn) {
1145
- const observer = this.observers.find((x) => x.options.queryFn);
1146
- if (observer) {
1147
- this.setOptions(observer.options);
1148
- }
1149
- }
1150
- const abortController = new AbortController();
1151
- const addSignalProperty = (object) => {
1152
- Object.defineProperty(object, "signal", {
1153
- enumerable: true,
1154
- get: () => {
1155
- this.#abortSignalConsumed = true;
1156
- return abortController.signal;
1157
- }
1158
- });
1159
- };
1160
- const fetchFn = () => {
1161
- const queryFn = ensureQueryFn(this.options, fetchOptions);
1162
- const createQueryFnContext = () => {
1163
- const queryFnContext2 = {
1164
- client: this.#client,
1165
- queryKey: this.queryKey,
1166
- meta: this.meta
1167
- };
1168
- addSignalProperty(queryFnContext2);
1169
- return queryFnContext2;
1170
- };
1171
- const queryFnContext = createQueryFnContext();
1172
- this.#abortSignalConsumed = false;
1173
- if (this.options.persister) {
1174
- return this.options.persister(
1175
- queryFn,
1176
- queryFnContext,
1177
- this
1178
- );
1179
- }
1180
- return queryFn(queryFnContext);
1181
- };
1182
- const createFetchContext = () => {
1183
- const context2 = {
1184
- fetchOptions,
1185
- options: this.options,
1186
- queryKey: this.queryKey,
1187
- client: this.#client,
1188
- state: this.state,
1189
- fetchFn
1190
- };
1191
- addSignalProperty(context2);
1192
- return context2;
1193
- };
1194
- const context = createFetchContext();
1195
- const behavior = this.#queryType === "infinite" ? infiniteQueryBehavior(
1196
- this.options.pages
1197
- ) : this.options.behavior;
1198
- behavior?.onFetch(context, this);
1199
- this.#revertState = this.state;
1200
- if (this.state.fetchStatus === "idle" || this.state.fetchMeta !== context.fetchOptions?.meta) {
1201
- this.#dispatch({ type: "fetch", meta: context.fetchOptions?.meta });
1202
- }
1203
- this.#retryer = createRetryer({
1204
- initialPromise: fetchOptions?.initialPromise,
1205
- fn: context.fetchFn,
1206
- onCancel: (error) => {
1207
- if (error instanceof CancelledError && error.revert) {
1208
- this.setState({
1209
- ...this.#revertState,
1210
- fetchStatus: "idle"
1211
- });
1212
- }
1213
- abortController.abort();
1214
- },
1215
- onFail: (failureCount, error) => {
1216
- this.#dispatch({ type: "failed", failureCount, error });
1217
- },
1218
- onPause: () => {
1219
- this.#dispatch({ type: "pause" });
1220
- },
1221
- onContinue: () => {
1222
- this.#dispatch({ type: "continue" });
1223
- },
1224
- retry: context.options.retry,
1225
- retryDelay: context.options.retryDelay,
1226
- networkMode: context.options.networkMode,
1227
- canRun: () => true
1228
- });
1229
- try {
1230
- const data = await this.#retryer.start();
1231
- if (data === void 0) {
1232
- if (false) ;
1233
- throw new Error(`${this.queryHash} data is undefined`);
1234
- }
1235
- this.setData(data);
1236
- this.#cache.config.onSuccess?.(data, this);
1237
- this.#cache.config.onSettled?.(
1238
- data,
1239
- this.state.error,
1240
- this
1241
- );
1242
- return data;
1243
- } catch (error) {
1244
- if (error instanceof CancelledError) {
1245
- if (error.silent) {
1246
- return this.#retryer.promise;
1247
- } else if (error.revert) {
1248
- if (this.state.data === void 0) {
1249
- throw error;
1250
- }
1251
- return this.state.data;
1252
- }
1253
- }
1254
- this.#dispatch({
1255
- type: "error",
1256
- error
1257
- });
1258
- this.#cache.config.onError?.(
1259
- error,
1260
- this
1261
- );
1262
- this.#cache.config.onSettled?.(
1263
- this.state.data,
1264
- error,
1265
- this
1266
- );
1267
- throw error;
1268
- } finally {
1269
- this.scheduleGc();
1270
- }
1271
- }
1272
- #dispatch(action) {
1273
- const reducer = (state) => {
1274
- switch (action.type) {
1275
- case "failed":
1276
- return {
1277
- ...state,
1278
- fetchFailureCount: action.failureCount,
1279
- fetchFailureReason: action.error
1280
- };
1281
- case "pause":
1282
- return {
1283
- ...state,
1284
- fetchStatus: "paused"
1285
- };
1286
- case "continue":
1287
- return {
1288
- ...state,
1289
- fetchStatus: "fetching"
1290
- };
1291
- case "fetch":
1292
- return {
1293
- ...state,
1294
- ...fetchState(state.data, this.options),
1295
- fetchMeta: action.meta ?? null
1296
- };
1297
- case "success":
1298
- const newState = {
1299
- ...state,
1300
- ...successState(action.data, action.dataUpdatedAt),
1301
- dataUpdateCount: state.dataUpdateCount + 1,
1302
- ...!action.manual && {
1303
- fetchStatus: "idle",
1304
- fetchFailureCount: 0,
1305
- fetchFailureReason: null
1306
- }
1307
- };
1308
- this.#revertState = action.manual ? newState : void 0;
1309
- return newState;
1310
- case "error":
1311
- const error = action.error;
1312
- return {
1313
- ...state,
1314
- error,
1315
- errorUpdateCount: state.errorUpdateCount + 1,
1316
- errorUpdatedAt: Date.now(),
1317
- fetchFailureCount: state.fetchFailureCount + 1,
1318
- fetchFailureReason: error,
1319
- fetchStatus: "idle",
1320
- status: "error",
1321
- // flag existing data as invalidated if we get a background error
1322
- // note that "no data" always means stale so we can set unconditionally here
1323
- isInvalidated: true
1324
- };
1325
- case "invalidate":
1326
- return {
1327
- ...state,
1328
- isInvalidated: true
1329
- };
1330
- case "setState":
1331
- return {
1332
- ...state,
1333
- ...action.state
1334
- };
1335
- }
1336
- };
1337
- this.state = reducer(this.state);
1338
- notifyManager.batch(() => {
1339
- this.observers.forEach((observer) => {
1340
- observer.onQueryUpdate();
1341
- });
1342
- this.#cache.notify({ query: this, type: "updated", action });
1343
- });
1344
- }
1345
- };
1346
- function fetchState(data, options) {
1347
- return {
1348
- fetchFailureCount: 0,
1349
- fetchFailureReason: null,
1350
- fetchStatus: canFetch(options.networkMode) ? "fetching" : "paused",
1351
- ...data === void 0 && {
1352
- error: null,
1353
- status: "pending"
1354
- }
1355
- };
1356
- }
1357
- function successState(data, dataUpdatedAt) {
1358
- return {
1359
- data,
1360
- dataUpdatedAt: dataUpdatedAt ?? Date.now(),
1361
- error: null,
1362
- isInvalidated: false,
1363
- status: "success"
1364
- };
1365
- }
1366
- function getDefaultState$1(options) {
1367
- const data = typeof options.initialData === "function" ? options.initialData() : options.initialData;
1368
- const hasData = data !== void 0;
1369
- const initialDataUpdatedAt = hasData ? typeof options.initialDataUpdatedAt === "function" ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;
1370
- return {
1371
- data,
1372
- dataUpdateCount: 0,
1373
- dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0,
1374
- error: null,
1375
- errorUpdateCount: 0,
1376
- errorUpdatedAt: 0,
1377
- fetchFailureCount: 0,
1378
- fetchFailureReason: null,
1379
- fetchMeta: null,
1380
- isInvalidated: false,
1381
- status: hasData ? "success" : "pending",
1382
- fetchStatus: "idle"
1383
- };
1384
- }
1385
- var QueryObserver = class extends Subscribable {
1386
- constructor(client, options) {
1387
- super();
1388
- this.options = options;
1389
- this.#client = client;
1390
- this.#selectError = null;
1391
- this.#currentThenable = pendingThenable();
1392
- this.bindMethods();
1393
- this.setOptions(options);
1394
- }
1395
- #client;
1396
- #currentQuery = void 0;
1397
- #currentQueryInitialState = void 0;
1398
- #currentResult = void 0;
1399
- #currentResultState;
1400
- #currentResultOptions;
1401
- #currentThenable;
1402
- #selectError;
1403
- #selectFn;
1404
- #selectResult;
1405
- // This property keeps track of the last query with defined data.
1406
- // It will be used to pass the previous data and query to the placeholder function between renders.
1407
- #lastQueryWithDefinedData;
1408
- #staleTimeoutId;
1409
- #refetchIntervalId;
1410
- #currentRefetchInterval;
1411
- #trackedProps = /* @__PURE__ */ new Set();
1412
- bindMethods() {
1413
- this.refetch = this.refetch.bind(this);
1414
- }
1415
- onSubscribe() {
1416
- if (this.listeners.size === 1) {
1417
- this.#currentQuery.addObserver(this);
1418
- if (shouldFetchOnMount(this.#currentQuery, this.options)) {
1419
- this.#executeFetch();
1420
- } else {
1421
- this.updateResult();
1422
- }
1423
- this.#updateTimers();
1424
- }
1425
- }
1426
- onUnsubscribe() {
1427
- if (!this.hasListeners()) {
1428
- this.destroy();
1429
- }
1430
- }
1431
- shouldFetchOnReconnect() {
1432
- return shouldFetchOn(
1433
- this.#currentQuery,
1434
- this.options,
1435
- this.options.refetchOnReconnect
1436
- );
1437
- }
1438
- shouldFetchOnWindowFocus() {
1439
- return shouldFetchOn(
1440
- this.#currentQuery,
1441
- this.options,
1442
- this.options.refetchOnWindowFocus
1443
- );
1444
- }
1445
- destroy() {
1446
- this.listeners = /* @__PURE__ */ new Set();
1447
- this.#clearStaleTimeout();
1448
- this.#clearRefetchInterval();
1449
- this.#currentQuery.removeObserver(this);
1450
- }
1451
- setOptions(options) {
1452
- const prevOptions = this.options;
1453
- const prevQuery = this.#currentQuery;
1454
- this.options = this.#client.defaultQueryOptions(options);
1455
- if (this.options.enabled !== void 0 && typeof this.options.enabled !== "boolean" && typeof this.options.enabled !== "function" && typeof resolveQueryBoolean(this.options.enabled, this.#currentQuery) !== "boolean") {
1456
- throw new Error(
1457
- "Expected enabled to be a boolean or a callback that returns a boolean"
1458
- );
1459
- }
1460
- this.#updateQuery();
1461
- this.#currentQuery.setOptions(this.options);
1462
- if (prevOptions._defaulted && !shallowEqualObjects(this.options, prevOptions)) {
1463
- this.#client.getQueryCache().notify({
1464
- type: "observerOptionsUpdated",
1465
- query: this.#currentQuery,
1466
- observer: this
1467
- });
1468
- }
1469
- const mounted = this.hasListeners();
1470
- if (mounted && shouldFetchOptionally(
1471
- this.#currentQuery,
1472
- prevQuery,
1473
- this.options,
1474
- prevOptions
1475
- )) {
1476
- this.#executeFetch();
1477
- }
1478
- this.updateResult();
1479
- if (mounted && (this.#currentQuery !== prevQuery || resolveQueryBoolean(this.options.enabled, this.#currentQuery) !== resolveQueryBoolean(prevOptions.enabled, this.#currentQuery) || resolveStaleTime(this.options.staleTime, this.#currentQuery) !== resolveStaleTime(prevOptions.staleTime, this.#currentQuery))) {
1480
- this.#updateStaleTimeout();
1481
- }
1482
- const nextRefetchInterval = this.#computeRefetchInterval();
1483
- if (mounted && (this.#currentQuery !== prevQuery || resolveQueryBoolean(this.options.enabled, this.#currentQuery) !== resolveQueryBoolean(prevOptions.enabled, this.#currentQuery) || nextRefetchInterval !== this.#currentRefetchInterval)) {
1484
- this.#updateRefetchInterval(nextRefetchInterval);
1485
- }
1486
- }
1487
- getOptimisticResult(options) {
1488
- const query = this.#client.getQueryCache().build(this.#client, options);
1489
- const result = this.createResult(query, options);
1490
- if (shouldAssignObserverCurrentProperties(this, result)) {
1491
- this.#currentResult = result;
1492
- this.#currentResultOptions = this.options;
1493
- this.#currentResultState = this.#currentQuery.state;
1494
- }
1495
- return result;
1496
- }
1497
- getCurrentResult() {
1498
- return this.#currentResult;
1499
- }
1500
- trackResult(result, onPropTracked) {
1501
- return new Proxy(result, {
1502
- get: (target, key) => {
1503
- this.trackProp(key);
1504
- onPropTracked?.(key);
1505
- if (key === "promise") {
1506
- this.trackProp("data");
1507
- if (!this.options.experimental_prefetchInRender && this.#currentThenable.status === "pending") {
1508
- this.#currentThenable.reject(
1509
- new Error(
1510
- "experimental_prefetchInRender feature flag is not enabled"
1511
- )
1512
- );
1513
- }
1514
- }
1515
- return Reflect.get(target, key);
1516
- }
1517
- });
1518
- }
1519
- trackProp(key) {
1520
- this.#trackedProps.add(key);
1521
- }
1522
- getCurrentQuery() {
1523
- return this.#currentQuery;
1524
- }
1525
- refetch({ ...options } = {}) {
1526
- return this.fetch({
1527
- ...options
1528
- });
1529
- }
1530
- fetchOptimistic(options) {
1531
- const defaultedOptions = this.#client.defaultQueryOptions(options);
1532
- const query = this.#client.getQueryCache().build(this.#client, defaultedOptions);
1533
- return query.fetch().then(() => this.createResult(query, defaultedOptions));
1534
- }
1535
- fetch(fetchOptions) {
1536
- return this.#executeFetch({
1537
- ...fetchOptions,
1538
- cancelRefetch: fetchOptions.cancelRefetch ?? true
1539
- }).then(() => {
1540
- this.updateResult();
1541
- return this.#currentResult;
1542
- });
1543
- }
1544
- #executeFetch(fetchOptions) {
1545
- this.#updateQuery();
1546
- let promise = this.#currentQuery.fetch(
1547
- this.options,
1548
- fetchOptions
1549
- );
1550
- if (!fetchOptions?.throwOnError) {
1551
- promise = promise.catch(noop);
1552
- }
1553
- return promise;
1554
- }
1555
- #updateStaleTimeout() {
1556
- this.#clearStaleTimeout();
1557
- const staleTime = resolveStaleTime(
1558
- this.options.staleTime,
1559
- this.#currentQuery
1560
- );
1561
- if (environmentManager.isServer() || this.#currentResult.isStale || !isValidTimeout(staleTime)) {
1562
- return;
1563
- }
1564
- const time = timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime);
1565
- const timeout = time + 1;
1566
- this.#staleTimeoutId = timeoutManager.setTimeout(() => {
1567
- if (!this.#currentResult.isStale) {
1568
- this.updateResult();
1569
- }
1570
- }, timeout);
1571
- }
1572
- #computeRefetchInterval() {
1573
- return (typeof this.options.refetchInterval === "function" ? this.options.refetchInterval(this.#currentQuery) : this.options.refetchInterval) ?? false;
1574
- }
1575
- #updateRefetchInterval(nextInterval) {
1576
- this.#clearRefetchInterval();
1577
- this.#currentRefetchInterval = nextInterval;
1578
- if (environmentManager.isServer() || resolveQueryBoolean(this.options.enabled, this.#currentQuery) === false || !isValidTimeout(this.#currentRefetchInterval) || this.#currentRefetchInterval === 0) {
1579
- return;
1580
- }
1581
- this.#refetchIntervalId = timeoutManager.setInterval(() => {
1582
- if (this.options.refetchIntervalInBackground || focusManager.isFocused()) {
1583
- this.#executeFetch();
1584
- }
1585
- }, this.#currentRefetchInterval);
1586
- }
1587
- #updateTimers() {
1588
- this.#updateStaleTimeout();
1589
- this.#updateRefetchInterval(this.#computeRefetchInterval());
1590
- }
1591
- #clearStaleTimeout() {
1592
- if (this.#staleTimeoutId !== void 0) {
1593
- timeoutManager.clearTimeout(this.#staleTimeoutId);
1594
- this.#staleTimeoutId = void 0;
1595
- }
1596
- }
1597
- #clearRefetchInterval() {
1598
- if (this.#refetchIntervalId !== void 0) {
1599
- timeoutManager.clearInterval(this.#refetchIntervalId);
1600
- this.#refetchIntervalId = void 0;
1601
- }
1602
- }
1603
- createResult(query, options) {
1604
- const prevQuery = this.#currentQuery;
1605
- const prevOptions = this.options;
1606
- const prevResult = this.#currentResult;
1607
- const prevResultState = this.#currentResultState;
1608
- const prevResultOptions = this.#currentResultOptions;
1609
- const queryChange = query !== prevQuery;
1610
- const queryInitialState = queryChange ? query.state : this.#currentQueryInitialState;
1611
- const { state } = query;
1612
- let newState = { ...state };
1613
- let isPlaceholderData = false;
1614
- let data;
1615
- if (options._optimisticResults) {
1616
- const mounted = this.hasListeners();
1617
- const fetchOnMount = !mounted && shouldFetchOnMount(query, options);
1618
- const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
1619
- if (fetchOnMount || fetchOptionally) {
1620
- newState = {
1621
- ...newState,
1622
- ...fetchState(state.data, query.options)
1623
- };
1624
- }
1625
- if (options._optimisticResults === "isRestoring") {
1626
- newState.fetchStatus = "idle";
1627
- }
1628
- }
1629
- let { error, errorUpdatedAt, status } = newState;
1630
- data = newState.data;
1631
- let skipSelect = false;
1632
- if (options.placeholderData !== void 0 && data === void 0 && status === "pending") {
1633
- let placeholderData;
1634
- if (prevResult?.isPlaceholderData && options.placeholderData === prevResultOptions?.placeholderData) {
1635
- placeholderData = prevResult.data;
1636
- skipSelect = true;
1637
- } else {
1638
- placeholderData = typeof options.placeholderData === "function" ? options.placeholderData(
1639
- this.#lastQueryWithDefinedData?.state.data,
1640
- this.#lastQueryWithDefinedData
1641
- ) : options.placeholderData;
1642
- }
1643
- if (placeholderData !== void 0) {
1644
- status = "success";
1645
- data = replaceData(
1646
- prevResult?.data,
1647
- placeholderData,
1648
- options
1649
- );
1650
- isPlaceholderData = true;
1651
- }
1652
- }
1653
- if (options.select && data !== void 0 && !skipSelect) {
1654
- if (prevResult && data === prevResultState?.data && options.select === this.#selectFn) {
1655
- data = this.#selectResult;
1656
- } else {
1657
- try {
1658
- this.#selectFn = options.select;
1659
- data = options.select(data);
1660
- data = replaceData(prevResult?.data, data, options);
1661
- this.#selectResult = data;
1662
- this.#selectError = null;
1663
- } catch (selectError) {
1664
- this.#selectError = selectError;
1665
- }
1666
- }
1667
- }
1668
- if (this.#selectError) {
1669
- error = this.#selectError;
1670
- data = this.#selectResult;
1671
- errorUpdatedAt = Date.now();
1672
- status = "error";
1673
- }
1674
- const isFetching = newState.fetchStatus === "fetching";
1675
- const isPending = status === "pending";
1676
- const isError = status === "error";
1677
- const isLoading = isPending && isFetching;
1678
- const hasData = data !== void 0;
1679
- const result = {
1680
- status,
1681
- fetchStatus: newState.fetchStatus,
1682
- isPending,
1683
- isSuccess: status === "success",
1684
- isError,
1685
- isInitialLoading: isLoading,
1686
- isLoading,
1687
- data,
1688
- dataUpdatedAt: newState.dataUpdatedAt,
1689
- error,
1690
- errorUpdatedAt,
1691
- failureCount: newState.fetchFailureCount,
1692
- failureReason: newState.fetchFailureReason,
1693
- errorUpdateCount: newState.errorUpdateCount,
1694
- isFetched: query.isFetched(),
1695
- isFetchedAfterMount: newState.dataUpdateCount > queryInitialState.dataUpdateCount || newState.errorUpdateCount > queryInitialState.errorUpdateCount,
1696
- isFetching,
1697
- isRefetching: isFetching && !isPending,
1698
- isLoadingError: isError && !hasData,
1699
- isPaused: newState.fetchStatus === "paused",
1700
- isPlaceholderData,
1701
- isRefetchError: isError && hasData,
1702
- isStale: isStale(query, options),
1703
- refetch: this.refetch,
1704
- promise: this.#currentThenable,
1705
- isEnabled: resolveQueryBoolean(options.enabled, query) !== false
1706
- };
1707
- const nextResult = result;
1708
- if (this.options.experimental_prefetchInRender) {
1709
- const hasResultData = nextResult.data !== void 0;
1710
- const isErrorWithoutData = nextResult.status === "error" && !hasResultData;
1711
- const finalizeThenableIfPossible = (thenable) => {
1712
- if (isErrorWithoutData) {
1713
- thenable.reject(nextResult.error);
1714
- } else if (hasResultData) {
1715
- thenable.resolve(nextResult.data);
1716
- }
1717
- };
1718
- const recreateThenable = () => {
1719
- const pending = this.#currentThenable = nextResult.promise = pendingThenable();
1720
- finalizeThenableIfPossible(pending);
1721
- };
1722
- const prevThenable = this.#currentThenable;
1723
- switch (prevThenable.status) {
1724
- case "pending":
1725
- if (query.queryHash === prevQuery.queryHash) {
1726
- finalizeThenableIfPossible(prevThenable);
1727
- }
1728
- break;
1729
- case "fulfilled":
1730
- if (isErrorWithoutData || nextResult.data !== prevThenable.value) {
1731
- recreateThenable();
1732
- }
1733
- break;
1734
- case "rejected":
1735
- if (!isErrorWithoutData || nextResult.error !== prevThenable.reason) {
1736
- recreateThenable();
1737
- }
1738
- break;
1739
- }
1740
- }
1741
- return nextResult;
1742
- }
1743
- updateResult() {
1744
- const prevResult = this.#currentResult;
1745
- const nextResult = this.createResult(this.#currentQuery, this.options);
1746
- this.#currentResultState = this.#currentQuery.state;
1747
- this.#currentResultOptions = this.options;
1748
- if (this.#currentResultState.data !== void 0) {
1749
- this.#lastQueryWithDefinedData = this.#currentQuery;
1750
- }
1751
- if (shallowEqualObjects(nextResult, prevResult)) {
1752
- return;
1753
- }
1754
- this.#currentResult = nextResult;
1755
- const shouldNotifyListeners = () => {
1756
- if (!prevResult) {
1757
- return true;
1758
- }
1759
- const { notifyOnChangeProps } = this.options;
1760
- const notifyOnChangePropsValue = typeof notifyOnChangeProps === "function" ? notifyOnChangeProps() : notifyOnChangeProps;
1761
- if (notifyOnChangePropsValue === "all" || !notifyOnChangePropsValue && !this.#trackedProps.size) {
1762
- return true;
1763
- }
1764
- const includedProps = new Set(
1765
- notifyOnChangePropsValue ?? this.#trackedProps
1766
- );
1767
- if (this.options.throwOnError) {
1768
- includedProps.add("error");
1769
- }
1770
- return Object.keys(this.#currentResult).some((key) => {
1771
- const typedKey = key;
1772
- const changed = this.#currentResult[typedKey] !== prevResult[typedKey];
1773
- return changed && includedProps.has(typedKey);
1774
- });
1775
- };
1776
- this.#notify({ listeners: shouldNotifyListeners() });
1777
- }
1778
- #updateQuery() {
1779
- const query = this.#client.getQueryCache().build(this.#client, this.options);
1780
- if (query === this.#currentQuery) {
1781
- return;
1782
- }
1783
- const prevQuery = this.#currentQuery;
1784
- this.#currentQuery = query;
1785
- this.#currentQueryInitialState = query.state;
1786
- if (this.hasListeners()) {
1787
- prevQuery?.removeObserver(this);
1788
- query.addObserver(this);
1789
- }
1790
- }
1791
- onQueryUpdate() {
1792
- this.updateResult();
1793
- if (this.hasListeners()) {
1794
- this.#updateTimers();
1795
- }
1796
- }
1797
- #notify(notifyOptions) {
1798
- notifyManager.batch(() => {
1799
- if (notifyOptions.listeners) {
1800
- this.listeners.forEach((listener) => {
1801
- listener(this.#currentResult);
1802
- });
1803
- }
1804
- this.#client.getQueryCache().notify({
1805
- query: this.#currentQuery,
1806
- type: "observerResultsUpdated"
1807
- });
1808
- });
1809
- }
1810
- };
1811
- function shouldLoadOnMount(query, options) {
1812
- return resolveQueryBoolean(options.enabled, query) !== false && query.state.data === void 0 && !(query.state.status === "error" && resolveQueryBoolean(options.retryOnMount, query) === false);
1813
- }
1814
- function shouldFetchOnMount(query, options) {
1815
- return shouldLoadOnMount(query, options) || query.state.data !== void 0 && shouldFetchOn(query, options, options.refetchOnMount);
1816
- }
1817
- function shouldFetchOn(query, options, field) {
1818
- if (resolveQueryBoolean(options.enabled, query) !== false && resolveStaleTime(options.staleTime, query) !== "static") {
1819
- const value = typeof field === "function" ? field(query) : field;
1820
- return value === "always" || value !== false && isStale(query, options);
1821
- }
1822
- return false;
1823
- }
1824
- function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
1825
- return (query !== prevQuery || resolveQueryBoolean(prevOptions.enabled, query) === false) && (!options.suspense || query.state.status !== "error") && isStale(query, options);
1826
- }
1827
- function isStale(query, options) {
1828
- return resolveQueryBoolean(options.enabled, query) !== false && query.isStaleByTime(resolveStaleTime(options.staleTime, query));
1829
- }
1830
- function shouldAssignObserverCurrentProperties(observer, optimisticResult) {
1831
- if (!shallowEqualObjects(observer.getCurrentResult(), optimisticResult)) {
1832
- return true;
1833
- }
1834
- return false;
1835
- }
1836
- var InfiniteQueryObserver = class extends QueryObserver {
1837
- constructor(client, options) {
1838
- super(client, options);
1839
- }
1840
- bindMethods() {
1841
- super.bindMethods();
1842
- this.fetchNextPage = this.fetchNextPage.bind(this);
1843
- this.fetchPreviousPage = this.fetchPreviousPage.bind(this);
1844
- }
1845
- setOptions(options) {
1846
- options._type = "infinite";
1847
- super.setOptions(options);
1848
- }
1849
- getOptimisticResult(options) {
1850
- options._type = "infinite";
1851
- return super.getOptimisticResult(options);
1852
- }
1853
- fetchNextPage(options) {
1854
- return this.fetch({
1855
- ...options,
1856
- meta: {
1857
- fetchMore: { direction: "forward" }
1858
- }
1859
- });
1860
- }
1861
- fetchPreviousPage(options) {
1862
- return this.fetch({
1863
- ...options,
1864
- meta: {
1865
- fetchMore: { direction: "backward" }
1866
- }
1867
- });
1868
- }
1869
- createResult(query, options) {
1870
- const { state } = query;
1871
- const parentResult = super.createResult(query, options);
1872
- const { isFetching, isRefetching, isError, isRefetchError } = parentResult;
1873
- const fetchDirection = state.fetchMeta?.fetchMore?.direction;
1874
- const isFetchNextPageError = isError && fetchDirection === "forward";
1875
- const isFetchingNextPage = isFetching && fetchDirection === "forward";
1876
- const isFetchPreviousPageError = isError && fetchDirection === "backward";
1877
- const isFetchingPreviousPage = isFetching && fetchDirection === "backward";
1878
- const result = {
1879
- ...parentResult,
1880
- fetchNextPage: this.fetchNextPage,
1881
- fetchPreviousPage: this.fetchPreviousPage,
1882
- hasNextPage: hasNextPage(options, state.data),
1883
- hasPreviousPage: hasPreviousPage(options, state.data),
1884
- isFetchNextPageError,
1885
- isFetchingNextPage,
1886
- isFetchPreviousPageError,
1887
- isFetchingPreviousPage,
1888
- isRefetchError: isRefetchError && !isFetchNextPageError && !isFetchPreviousPageError,
1889
- isRefetching: isRefetching && !isFetchingNextPage && !isFetchingPreviousPage
1890
- };
1891
- return result;
1892
- }
1893
- };
1894
- var Mutation = class extends Removable {
1895
- #client;
1896
- #observers;
1897
- #mutationCache;
1898
- #retryer;
1899
- constructor(config) {
1900
- super();
1901
- this.#client = config.client;
1902
- this.mutationId = config.mutationId;
1903
- this.#mutationCache = config.mutationCache;
1904
- this.#observers = [];
1905
- this.state = config.state || getDefaultState();
1906
- this.setOptions(config.options);
1907
- this.scheduleGc();
1908
- }
1909
- setOptions(options) {
1910
- this.options = options;
1911
- this.updateGcTime(this.options.gcTime);
1912
- }
1913
- get meta() {
1914
- return this.options.meta;
1915
- }
1916
- addObserver(observer) {
1917
- if (!this.#observers.includes(observer)) {
1918
- this.#observers.push(observer);
1919
- this.clearGcTimeout();
1920
- this.#mutationCache.notify({
1921
- type: "observerAdded",
1922
- mutation: this,
1923
- observer
1924
- });
1925
- }
1926
- }
1927
- removeObserver(observer) {
1928
- this.#observers = this.#observers.filter((x) => x !== observer);
1929
- this.scheduleGc();
1930
- this.#mutationCache.notify({
1931
- type: "observerRemoved",
1932
- mutation: this,
1933
- observer
1934
- });
1935
- }
1936
- optionalRemove() {
1937
- if (!this.#observers.length) {
1938
- if (this.state.status === "pending") {
1939
- this.scheduleGc();
1940
- } else {
1941
- this.#mutationCache.remove(this);
1942
- }
1943
- }
1944
- }
1945
- continue() {
1946
- return this.#retryer?.continue() ?? // continuing a mutation assumes that variables are set, mutation must have been dehydrated before
1947
- this.execute(this.state.variables);
1948
- }
1949
- async execute(variables) {
1950
- const onContinue = () => {
1951
- this.#dispatch({ type: "continue" });
1952
- };
1953
- const mutationFnContext = {
1954
- client: this.#client,
1955
- meta: this.options.meta,
1956
- mutationKey: this.options.mutationKey
1957
- };
1958
- this.#retryer = createRetryer({
1959
- fn: () => {
1960
- if (!this.options.mutationFn) {
1961
- return Promise.reject(new Error("No mutationFn found"));
1962
- }
1963
- return this.options.mutationFn(variables, mutationFnContext);
1964
- },
1965
- onFail: (failureCount, error) => {
1966
- this.#dispatch({ type: "failed", failureCount, error });
1967
- },
1968
- onPause: () => {
1969
- this.#dispatch({ type: "pause" });
1970
- },
1971
- onContinue,
1972
- retry: this.options.retry ?? 0,
1973
- retryDelay: this.options.retryDelay,
1974
- networkMode: this.options.networkMode,
1975
- canRun: () => this.#mutationCache.canRun(this)
1976
- });
1977
- const restored = this.state.status === "pending";
1978
- const isPaused = !this.#retryer.canStart();
1979
- try {
1980
- if (restored) {
1981
- onContinue();
1982
- } else {
1983
- this.#dispatch({ type: "pending", variables, isPaused });
1984
- if (this.#mutationCache.config.onMutate) {
1985
- await this.#mutationCache.config.onMutate(
1986
- variables,
1987
- this,
1988
- mutationFnContext
1989
- );
1990
- }
1991
- const context = await this.options.onMutate?.(
1992
- variables,
1993
- mutationFnContext
1994
- );
1995
- if (context !== this.state.context) {
1996
- this.#dispatch({
1997
- type: "pending",
1998
- context,
1999
- variables,
2000
- isPaused
2001
- });
2002
- }
2003
- }
2004
- const data = await this.#retryer.start();
2005
- await this.#mutationCache.config.onSuccess?.(
2006
- data,
2007
- variables,
2008
- this.state.context,
2009
- this,
2010
- mutationFnContext
2011
- );
2012
- await this.options.onSuccess?.(
2013
- data,
2014
- variables,
2015
- this.state.context,
2016
- mutationFnContext
2017
- );
2018
- await this.#mutationCache.config.onSettled?.(
2019
- data,
2020
- null,
2021
- this.state.variables,
2022
- this.state.context,
2023
- this,
2024
- mutationFnContext
2025
- );
2026
- await this.options.onSettled?.(
2027
- data,
2028
- null,
2029
- variables,
2030
- this.state.context,
2031
- mutationFnContext
2032
- );
2033
- this.#dispatch({ type: "success", data });
2034
- return data;
2035
- } catch (error) {
2036
- try {
2037
- await this.#mutationCache.config.onError?.(
2038
- error,
2039
- variables,
2040
- this.state.context,
2041
- this,
2042
- mutationFnContext
2043
- );
2044
- } catch (e) {
2045
- void Promise.reject(e);
2046
- }
2047
- try {
2048
- await this.options.onError?.(
2049
- error,
2050
- variables,
2051
- this.state.context,
2052
- mutationFnContext
2053
- );
2054
- } catch (e) {
2055
- void Promise.reject(e);
2056
- }
2057
- try {
2058
- await this.#mutationCache.config.onSettled?.(
2059
- void 0,
2060
- error,
2061
- this.state.variables,
2062
- this.state.context,
2063
- this,
2064
- mutationFnContext
2065
- );
2066
- } catch (e) {
2067
- void Promise.reject(e);
2068
- }
2069
- try {
2070
- await this.options.onSettled?.(
2071
- void 0,
2072
- error,
2073
- variables,
2074
- this.state.context,
2075
- mutationFnContext
2076
- );
2077
- } catch (e) {
2078
- void Promise.reject(e);
2079
- }
2080
- this.#dispatch({ type: "error", error });
2081
- throw error;
2082
- } finally {
2083
- this.#mutationCache.runNext(this);
2084
- }
2085
- }
2086
- #dispatch(action) {
2087
- const reducer = (state) => {
2088
- switch (action.type) {
2089
- case "failed":
2090
- return {
2091
- ...state,
2092
- failureCount: action.failureCount,
2093
- failureReason: action.error
2094
- };
2095
- case "pause":
2096
- return {
2097
- ...state,
2098
- isPaused: true
2099
- };
2100
- case "continue":
2101
- return {
2102
- ...state,
2103
- isPaused: false
2104
- };
2105
- case "pending":
2106
- return {
2107
- ...state,
2108
- context: action.context,
2109
- data: void 0,
2110
- failureCount: 0,
2111
- failureReason: null,
2112
- error: null,
2113
- isPaused: action.isPaused,
2114
- status: "pending",
2115
- variables: action.variables,
2116
- submittedAt: Date.now()
2117
- };
2118
- case "success":
2119
- return {
2120
- ...state,
2121
- data: action.data,
2122
- failureCount: 0,
2123
- failureReason: null,
2124
- error: null,
2125
- status: "success",
2126
- isPaused: false
2127
- };
2128
- case "error":
2129
- return {
2130
- ...state,
2131
- data: void 0,
2132
- error: action.error,
2133
- failureCount: state.failureCount + 1,
2134
- failureReason: action.error,
2135
- isPaused: false,
2136
- status: "error"
2137
- };
2138
- }
2139
- };
2140
- this.state = reducer(this.state);
2141
- notifyManager.batch(() => {
2142
- this.#observers.forEach((observer) => {
2143
- observer.onMutationUpdate(action);
2144
- });
2145
- this.#mutationCache.notify({
2146
- mutation: this,
2147
- type: "updated",
2148
- action
2149
- });
2150
- });
2151
- }
2152
- };
2153
- function getDefaultState() {
2154
- return {
2155
- context: void 0,
2156
- data: void 0,
2157
- error: null,
2158
- failureCount: 0,
2159
- failureReason: null,
2160
- isPaused: false,
2161
- status: "idle",
2162
- variables: void 0,
2163
- submittedAt: 0
2164
- };
2165
- }
2166
- var MutationCache = class extends Subscribable {
2167
- constructor(config = {}) {
2168
- super();
2169
- this.config = config;
2170
- this.#mutations = /* @__PURE__ */ new Set();
2171
- this.#scopes = /* @__PURE__ */ new Map();
2172
- this.#mutationId = 0;
2173
- }
2174
- #mutations;
2175
- #scopes;
2176
- #mutationId;
2177
- build(client, options, state) {
2178
- const mutation = new Mutation({
2179
- client,
2180
- mutationCache: this,
2181
- mutationId: ++this.#mutationId,
2182
- options: client.defaultMutationOptions(options),
2183
- state
2184
- });
2185
- this.add(mutation);
2186
- return mutation;
2187
- }
2188
- add(mutation) {
2189
- this.#mutations.add(mutation);
2190
- const scope = scopeFor(mutation);
2191
- if (typeof scope === "string") {
2192
- const scopedMutations = this.#scopes.get(scope);
2193
- if (scopedMutations) {
2194
- scopedMutations.push(mutation);
2195
- } else {
2196
- this.#scopes.set(scope, [mutation]);
2197
- }
2198
- }
2199
- this.notify({ type: "added", mutation });
2200
- }
2201
- remove(mutation) {
2202
- if (this.#mutations.delete(mutation)) {
2203
- const scope = scopeFor(mutation);
2204
- if (typeof scope === "string") {
2205
- const scopedMutations = this.#scopes.get(scope);
2206
- if (scopedMutations) {
2207
- if (scopedMutations.length > 1) {
2208
- const index = scopedMutations.indexOf(mutation);
2209
- if (index !== -1) {
2210
- scopedMutations.splice(index, 1);
2211
- }
2212
- } else if (scopedMutations[0] === mutation) {
2213
- this.#scopes.delete(scope);
2214
- }
2215
- }
2216
- }
2217
- }
2218
- this.notify({ type: "removed", mutation });
2219
- }
2220
- canRun(mutation) {
2221
- const scope = scopeFor(mutation);
2222
- if (typeof scope === "string") {
2223
- const mutationsWithSameScope = this.#scopes.get(scope);
2224
- const firstPendingMutation = mutationsWithSameScope?.find(
2225
- (m) => m.state.status === "pending"
2226
- );
2227
- return !firstPendingMutation || firstPendingMutation === mutation;
2228
- } else {
2229
- return true;
2230
- }
2231
- }
2232
- runNext(mutation) {
2233
- const scope = scopeFor(mutation);
2234
- if (typeof scope === "string") {
2235
- const foundMutation = this.#scopes.get(scope)?.find((m) => m !== mutation && m.state.isPaused);
2236
- return foundMutation?.continue() ?? Promise.resolve();
2237
- } else {
2238
- return Promise.resolve();
2239
- }
2240
- }
2241
- clear() {
2242
- notifyManager.batch(() => {
2243
- this.#mutations.forEach((mutation) => {
2244
- this.notify({ type: "removed", mutation });
2245
- });
2246
- this.#mutations.clear();
2247
- this.#scopes.clear();
2248
- });
2249
- }
2250
- getAll() {
2251
- return Array.from(this.#mutations);
2252
- }
2253
- find(filters) {
2254
- const defaultedFilters = { exact: true, ...filters };
2255
- return this.getAll().find(
2256
- (mutation) => matchMutation(defaultedFilters, mutation)
2257
- );
2258
- }
2259
- findAll(filters = {}) {
2260
- return this.getAll().filter((mutation) => matchMutation(filters, mutation));
2261
- }
2262
- notify(event) {
2263
- notifyManager.batch(() => {
2264
- this.listeners.forEach((listener) => {
2265
- listener(event);
2266
- });
2267
- });
2268
- }
2269
- resumePausedMutations() {
2270
- const pausedMutations = this.getAll().filter((x) => x.state.isPaused);
2271
- return notifyManager.batch(
2272
- () => Promise.all(
2273
- pausedMutations.map((mutation) => mutation.continue().catch(noop))
2274
- )
2275
- );
2276
- }
2277
- };
2278
- function scopeFor(mutation) {
2279
- return mutation.options.scope?.id;
2280
- }
2281
- var MutationObserver = class extends Subscribable {
2282
- #client;
2283
- #currentResult = void 0;
2284
- #currentMutation;
2285
- #mutateOptions;
2286
- constructor(client, options) {
2287
- super();
2288
- this.#client = client;
2289
- this.setOptions(options);
2290
- this.bindMethods();
2291
- this.#updateResult();
2292
- }
2293
- bindMethods() {
2294
- this.mutate = this.mutate.bind(this);
2295
- this.reset = this.reset.bind(this);
2296
- }
2297
- setOptions(options) {
2298
- const prevOptions = this.options;
2299
- this.options = this.#client.defaultMutationOptions(options);
2300
- if (!shallowEqualObjects(this.options, prevOptions)) {
2301
- this.#client.getMutationCache().notify({
2302
- type: "observerOptionsUpdated",
2303
- mutation: this.#currentMutation,
2304
- observer: this
2305
- });
2306
- }
2307
- if (prevOptions?.mutationKey && this.options.mutationKey && hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)) {
2308
- this.reset();
2309
- } else if (this.#currentMutation?.state.status === "pending") {
2310
- this.#currentMutation.setOptions(this.options);
2311
- }
2312
- }
2313
- onUnsubscribe() {
2314
- if (!this.hasListeners()) {
2315
- this.#currentMutation?.removeObserver(this);
2316
- }
2317
- }
2318
- onMutationUpdate(action) {
2319
- this.#updateResult();
2320
- this.#notify(action);
2321
- }
2322
- getCurrentResult() {
2323
- return this.#currentResult;
2324
- }
2325
- reset() {
2326
- this.#currentMutation?.removeObserver(this);
2327
- this.#currentMutation = void 0;
2328
- this.#updateResult();
2329
- this.#notify();
2330
- }
2331
- mutate(variables, options) {
2332
- this.#mutateOptions = options;
2333
- this.#currentMutation?.removeObserver(this);
2334
- this.#currentMutation = this.#client.getMutationCache().build(this.#client, this.options);
2335
- this.#currentMutation.addObserver(this);
2336
- return this.#currentMutation.execute(variables);
2337
- }
2338
- #updateResult() {
2339
- const state = this.#currentMutation?.state ?? getDefaultState();
2340
- this.#currentResult = {
2341
- ...state,
2342
- isPending: state.status === "pending",
2343
- isSuccess: state.status === "success",
2344
- isError: state.status === "error",
2345
- isIdle: state.status === "idle",
2346
- mutate: this.mutate,
2347
- reset: this.reset
2348
- };
2349
- }
2350
- #notify(action) {
2351
- notifyManager.batch(() => {
2352
- if (this.#mutateOptions && this.hasListeners()) {
2353
- const variables = this.#currentResult.variables;
2354
- const onMutateResult = this.#currentResult.context;
2355
- const context = {
2356
- client: this.#client,
2357
- meta: this.options.meta,
2358
- mutationKey: this.options.mutationKey
2359
- };
2360
- if (action?.type === "success") {
2361
- try {
2362
- this.#mutateOptions.onSuccess?.(
2363
- action.data,
2364
- variables,
2365
- onMutateResult,
2366
- context
2367
- );
2368
- } catch (e) {
2369
- void Promise.reject(e);
2370
- }
2371
- try {
2372
- this.#mutateOptions.onSettled?.(
2373
- action.data,
2374
- null,
2375
- variables,
2376
- onMutateResult,
2377
- context
2378
- );
2379
- } catch (e) {
2380
- void Promise.reject(e);
2381
- }
2382
- } else if (action?.type === "error") {
2383
- try {
2384
- this.#mutateOptions.onError?.(
2385
- action.error,
2386
- variables,
2387
- onMutateResult,
2388
- context
2389
- );
2390
- } catch (e) {
2391
- void Promise.reject(e);
2392
- }
2393
- try {
2394
- this.#mutateOptions.onSettled?.(
2395
- void 0,
2396
- action.error,
2397
- variables,
2398
- onMutateResult,
2399
- context
2400
- );
2401
- } catch (e) {
2402
- void Promise.reject(e);
2403
- }
2404
- }
2405
- }
2406
- this.listeners.forEach((listener) => {
2407
- listener(this.#currentResult);
2408
- });
2409
- });
2410
- }
2411
- };
2412
- function difference(array1, array2) {
2413
- const excludeSet = new Set(array2);
2414
- return array1.filter((x) => !excludeSet.has(x));
2415
- }
2416
- function replaceAt(array, index, value) {
2417
- const copy = array.slice(0);
2418
- copy[index] = value;
2419
- return copy;
2420
- }
2421
- var QueriesObserver = class extends Subscribable {
2422
- #client;
2423
- #result;
2424
- #queries;
2425
- #options;
2426
- #observers;
2427
- #combinedResult;
2428
- #lastCombine;
2429
- #lastResult;
2430
- #lastQueryHashes;
2431
- #observerMatches = [];
2432
- constructor(client, queries, options) {
2433
- super();
2434
- this.#client = client;
2435
- this.#options = options;
2436
- this.#queries = [];
2437
- this.#observers = [];
2438
- this.#result = [];
2439
- this.setQueries(queries);
2440
- }
2441
- onSubscribe() {
2442
- if (this.listeners.size === 1) {
2443
- this.#observers.forEach((observer) => {
2444
- observer.subscribe((result) => {
2445
- this.#onUpdate(observer, result);
2446
- });
2447
- });
2448
- }
2449
- }
2450
- onUnsubscribe() {
2451
- if (!this.listeners.size) {
2452
- this.destroy();
2453
- }
2454
- }
2455
- destroy() {
2456
- this.listeners = /* @__PURE__ */ new Set();
2457
- this.#observers.forEach((observer) => {
2458
- observer.destroy();
2459
- });
2460
- }
2461
- setQueries(queries, options) {
2462
- this.#queries = queries;
2463
- this.#options = options;
2464
- notifyManager.batch(() => {
2465
- const prevObservers = this.#observers;
2466
- const newObserverMatches = this.#findMatchingObservers(this.#queries);
2467
- newObserverMatches.forEach(
2468
- (match) => match.observer.setOptions(match.defaultedQueryOptions)
2469
- );
2470
- const newObservers = newObserverMatches.map((match) => match.observer);
2471
- const newResult = newObservers.map(
2472
- (observer) => observer.getCurrentResult()
2473
- );
2474
- const hasLengthChange = prevObservers.length !== newObservers.length;
2475
- const hasIndexChange = newObservers.some(
2476
- (observer, index) => observer !== prevObservers[index]
2477
- );
2478
- const hasStructuralChange = hasLengthChange || hasIndexChange;
2479
- const hasResultChange = hasStructuralChange ? true : newResult.some((result, index) => {
2480
- const prev = this.#result[index];
2481
- return !prev || !shallowEqualObjects(result, prev);
2482
- });
2483
- if (!hasStructuralChange && !hasResultChange) return;
2484
- if (hasStructuralChange) {
2485
- this.#observerMatches = newObserverMatches;
2486
- this.#observers = newObservers;
2487
- }
2488
- this.#result = newResult;
2489
- if (!this.hasListeners()) return;
2490
- if (hasStructuralChange) {
2491
- difference(prevObservers, newObservers).forEach((observer) => {
2492
- observer.destroy();
2493
- });
2494
- difference(newObservers, prevObservers).forEach((observer) => {
2495
- observer.subscribe((result) => {
2496
- this.#onUpdate(observer, result);
2497
- });
2498
- });
2499
- }
2500
- this.#notify();
2501
- });
2502
- }
2503
- getCurrentResult() {
2504
- return this.#result;
2505
- }
2506
- getQueries() {
2507
- return this.#observers.map((observer) => observer.getCurrentQuery());
2508
- }
2509
- getObservers() {
2510
- return this.#observers;
2511
- }
2512
- getOptimisticResult(queries, combine) {
2513
- const matches = this.#findMatchingObservers(queries);
2514
- const result = matches.map(
2515
- (match) => match.observer.getOptimisticResult(match.defaultedQueryOptions)
2516
- );
2517
- const queryHashes = matches.map(
2518
- (match) => match.defaultedQueryOptions.queryHash
2519
- );
2520
- return [
2521
- result,
2522
- (r) => {
2523
- return this.#combineResult(r ?? result, combine, queryHashes);
2524
- },
2525
- () => {
2526
- return this.#trackResult(result, matches);
2527
- }
2528
- ];
2529
- }
2530
- #trackResult(result, matches) {
2531
- return matches.map((match, index) => {
2532
- const observerResult = result[index];
2533
- return !match.defaultedQueryOptions.notifyOnChangeProps ? match.observer.trackResult(observerResult, (accessedProp) => {
2534
- matches.forEach((m) => {
2535
- m.observer.trackProp(accessedProp);
2536
- });
2537
- }) : observerResult;
2538
- });
2539
- }
2540
- #combineResult(input, combine, queryHashes) {
2541
- if (combine) {
2542
- const lastHashes = this.#lastQueryHashes;
2543
- const queryHashesChanged = queryHashes !== void 0 && lastHashes !== void 0 && (lastHashes.length !== queryHashes.length || queryHashes.some((hash, i) => hash !== lastHashes[i]));
2544
- if (!this.#combinedResult || this.#result !== this.#lastResult || queryHashesChanged || combine !== this.#lastCombine) {
2545
- this.#lastCombine = combine;
2546
- this.#lastResult = this.#result;
2547
- if (queryHashes !== void 0) {
2548
- this.#lastQueryHashes = queryHashes;
2549
- }
2550
- this.#combinedResult = replaceEqualDeep(
2551
- this.#combinedResult,
2552
- combine(input)
2553
- );
2554
- }
2555
- return this.#combinedResult;
2556
- }
2557
- return input;
2558
- }
2559
- #shouldSkipCombine() {
2560
- return this.#options?.combine !== void 0 && this.#observers.some((observer, index) => {
2561
- return observer.options.suspense && this.#result[index]?.data === void 0;
2562
- });
2563
- }
2564
- #findMatchingObservers(queries) {
2565
- const prevObserversMap = /* @__PURE__ */ new Map();
2566
- this.#observers.forEach((observer) => {
2567
- const key = observer.options.queryHash;
2568
- if (!key) return;
2569
- const previousObservers = prevObserversMap.get(key);
2570
- if (previousObservers) {
2571
- previousObservers.push(observer);
2572
- } else {
2573
- prevObserversMap.set(key, [observer]);
2574
- }
2575
- });
2576
- const observers = [];
2577
- queries.forEach((options) => {
2578
- const defaultedOptions = this.#client.defaultQueryOptions(options);
2579
- const match = prevObserversMap.get(defaultedOptions.queryHash)?.shift();
2580
- const observer = match ?? new QueryObserver(this.#client, defaultedOptions);
2581
- observers.push({
2582
- defaultedQueryOptions: defaultedOptions,
2583
- observer
2584
- });
2585
- });
2586
- return observers;
2587
- }
2588
- #onUpdate(observer, result) {
2589
- const index = this.#observers.indexOf(observer);
2590
- if (index !== -1) {
2591
- this.#result = replaceAt(this.#result, index, result);
2592
- this.#notify();
2593
- }
2594
- }
2595
- #notify() {
2596
- if (this.hasListeners()) {
2597
- const newTracked = this.#trackResult(this.#result, this.#observerMatches);
2598
- const shouldSkipCombine = this.#shouldSkipCombine();
2599
- const previousResult = this.#combinedResult;
2600
- const newResult = shouldSkipCombine ? previousResult : this.#combineResult(newTracked, this.#options?.combine);
2601
- if (shouldSkipCombine || previousResult !== newResult) {
2602
- notifyManager.batch(() => {
2603
- this.listeners.forEach((listener) => {
2604
- listener(this.#result);
2605
- });
2606
- });
2607
- }
2608
- }
2609
- }
2610
- };
2611
- var QueryCache = class extends Subscribable {
2612
- constructor(config = {}) {
2613
- super();
2614
- this.config = config;
2615
- this.#queries = /* @__PURE__ */ new Map();
2616
- }
2617
- #queries;
2618
- build(client, options, state) {
2619
- const queryKey = options.queryKey;
2620
- const queryHash = options.queryHash ?? hashQueryKeyByOptions(queryKey, options);
2621
- let query = this.get(queryHash);
2622
- if (!query) {
2623
- query = new Query({
2624
- client,
2625
- queryKey,
2626
- queryHash,
2627
- options: client.defaultQueryOptions(options),
2628
- state,
2629
- defaultOptions: client.getQueryDefaults(queryKey)
2630
- });
2631
- this.add(query);
2632
- }
2633
- return query;
2634
- }
2635
- add(query) {
2636
- if (!this.#queries.has(query.queryHash)) {
2637
- this.#queries.set(query.queryHash, query);
2638
- this.notify({
2639
- type: "added",
2640
- query
2641
- });
2642
- }
2643
- }
2644
- remove(query) {
2645
- const queryInMap = this.#queries.get(query.queryHash);
2646
- if (queryInMap) {
2647
- query.destroy();
2648
- if (queryInMap === query) {
2649
- this.#queries.delete(query.queryHash);
2650
- }
2651
- this.notify({ type: "removed", query });
2652
- }
2653
- }
2654
- clear() {
2655
- notifyManager.batch(() => {
2656
- this.getAll().forEach((query) => {
2657
- this.remove(query);
2658
- });
2659
- });
2660
- }
2661
- get(queryHash) {
2662
- return this.#queries.get(queryHash);
2663
- }
2664
- getAll() {
2665
- return [...this.#queries.values()];
2666
- }
2667
- find(filters) {
2668
- const defaultedFilters = { exact: true, ...filters };
2669
- return this.getAll().find(
2670
- (query) => matchQuery(defaultedFilters, query)
2671
- );
2672
- }
2673
- findAll(filters = {}) {
2674
- const queries = this.getAll();
2675
- return Object.keys(filters).length > 0 ? queries.filter((query) => matchQuery(filters, query)) : queries;
2676
- }
2677
- notify(event) {
2678
- notifyManager.batch(() => {
2679
- this.listeners.forEach((listener) => {
2680
- listener(event);
2681
- });
2682
- });
2683
- }
2684
- onFocus() {
2685
- notifyManager.batch(() => {
2686
- this.getAll().forEach((query) => {
2687
- query.onFocus();
2688
- });
2689
- });
2690
- }
2691
- onOnline() {
2692
- notifyManager.batch(() => {
2693
- this.getAll().forEach((query) => {
2694
- query.onOnline();
2695
- });
2696
- });
2697
- }
2698
- };
2699
- var QueryClient = class {
2700
- #queryCache;
2701
- #mutationCache;
2702
- #defaultOptions;
2703
- #queryDefaults;
2704
- #mutationDefaults;
2705
- #mountCount;
2706
- #unsubscribeFocus;
2707
- #unsubscribeOnline;
2708
- constructor(config = {}) {
2709
- this.#queryCache = config.queryCache || new QueryCache();
2710
- this.#mutationCache = config.mutationCache || new MutationCache();
2711
- this.#defaultOptions = config.defaultOptions || {};
2712
- this.#queryDefaults = /* @__PURE__ */ new Map();
2713
- this.#mutationDefaults = /* @__PURE__ */ new Map();
2714
- this.#mountCount = 0;
2715
- }
2716
- mount() {
2717
- this.#mountCount++;
2718
- if (this.#mountCount !== 1) return;
2719
- this.#unsubscribeFocus = focusManager.subscribe(async (focused) => {
2720
- if (focused) {
2721
- await this.resumePausedMutations();
2722
- this.#queryCache.onFocus();
2723
- }
2724
- });
2725
- this.#unsubscribeOnline = onlineManager.subscribe(async (online) => {
2726
- if (online) {
2727
- await this.resumePausedMutations();
2728
- this.#queryCache.onOnline();
2729
- }
2730
- });
2731
- }
2732
- unmount() {
2733
- this.#mountCount--;
2734
- if (this.#mountCount !== 0) return;
2735
- this.#unsubscribeFocus?.();
2736
- this.#unsubscribeFocus = void 0;
2737
- this.#unsubscribeOnline?.();
2738
- this.#unsubscribeOnline = void 0;
2739
- }
2740
- isFetching(filters) {
2741
- return this.#queryCache.findAll({ ...filters, fetchStatus: "fetching" }).length;
2742
- }
2743
- isMutating(filters) {
2744
- return this.#mutationCache.findAll({ ...filters, status: "pending" }).length;
2745
- }
2746
- /**
2747
- * Imperative (non-reactive) way to retrieve data for a QueryKey.
2748
- * Should only be used in callbacks or functions where reading the latest data is necessary, e.g. for optimistic updates.
2749
- *
2750
- * Hint: Do not use this function inside a component, because it won't receive updates.
2751
- * Use `useQuery` to create a `QueryObserver` that subscribes to changes.
2752
- */
2753
- getQueryData(queryKey) {
2754
- const options = this.defaultQueryOptions({ queryKey });
2755
- return this.#queryCache.get(options.queryHash)?.state.data;
2756
- }
2757
- ensureQueryData(options) {
2758
- const defaultedOptions = this.defaultQueryOptions(options);
2759
- const query = this.#queryCache.build(this, defaultedOptions);
2760
- const cachedData = query.state.data;
2761
- if (cachedData === void 0) {
2762
- return this.fetchQuery(options);
2763
- }
2764
- if (options.revalidateIfStale && query.isStaleByTime(resolveStaleTime(defaultedOptions.staleTime, query))) {
2765
- void this.prefetchQuery(defaultedOptions);
2766
- }
2767
- return Promise.resolve(cachedData);
2768
- }
2769
- getQueriesData(filters) {
2770
- return this.#queryCache.findAll(filters).map(({ queryKey, state }) => {
2771
- const data = state.data;
2772
- return [queryKey, data];
2773
- });
2774
- }
2775
- setQueryData(queryKey, updater, options) {
2776
- const defaultedOptions = this.defaultQueryOptions({ queryKey });
2777
- const query = this.#queryCache.get(
2778
- defaultedOptions.queryHash
2779
- );
2780
- const prevData = query?.state.data;
2781
- const data = functionalUpdate(updater, prevData);
2782
- if (data === void 0) {
2783
- return void 0;
2784
- }
2785
- return this.#queryCache.build(this, defaultedOptions).setData(data, { ...options, manual: true });
2786
- }
2787
- setQueriesData(filters, updater, options) {
2788
- return notifyManager.batch(
2789
- () => this.#queryCache.findAll(filters).map(({ queryKey }) => [
2790
- queryKey,
2791
- this.setQueryData(queryKey, updater, options)
2792
- ])
2793
- );
2794
- }
2795
- getQueryState(queryKey) {
2796
- const options = this.defaultQueryOptions({ queryKey });
2797
- return this.#queryCache.get(
2798
- options.queryHash
2799
- )?.state;
2800
- }
2801
- removeQueries(filters) {
2802
- const queryCache = this.#queryCache;
2803
- notifyManager.batch(() => {
2804
- queryCache.findAll(filters).forEach((query) => {
2805
- queryCache.remove(query);
2806
- });
2807
- });
2808
- }
2809
- resetQueries(filters, options) {
2810
- const queryCache = this.#queryCache;
2811
- return notifyManager.batch(() => {
2812
- queryCache.findAll(filters).forEach((query) => {
2813
- query.reset();
2814
- });
2815
- return this.refetchQueries(
2816
- {
2817
- type: "active",
2818
- ...filters
2819
- },
2820
- options
2821
- );
2822
- });
2823
- }
2824
- cancelQueries(filters, cancelOptions = {}) {
2825
- const defaultedCancelOptions = { revert: true, ...cancelOptions };
2826
- const promises = notifyManager.batch(
2827
- () => this.#queryCache.findAll(filters).map((query) => query.cancel(defaultedCancelOptions))
2828
- );
2829
- return Promise.all(promises).then(noop).catch(noop);
2830
- }
2831
- invalidateQueries(filters, options = {}) {
2832
- return notifyManager.batch(() => {
2833
- this.#queryCache.findAll(filters).forEach((query) => {
2834
- query.invalidate();
2835
- });
2836
- if (filters?.refetchType === "none") {
2837
- return Promise.resolve();
2838
- }
2839
- return this.refetchQueries(
2840
- {
2841
- ...filters,
2842
- type: filters?.refetchType ?? filters?.type ?? "active"
2843
- },
2844
- options
2845
- );
2846
- });
2847
- }
2848
- refetchQueries(filters, options = {}) {
2849
- const fetchOptions = {
2850
- ...options,
2851
- cancelRefetch: options.cancelRefetch ?? true
2852
- };
2853
- const promises = notifyManager.batch(
2854
- () => this.#queryCache.findAll(filters).filter((query) => !query.isDisabled() && !query.isStatic()).map((query) => {
2855
- let promise = query.fetch(void 0, fetchOptions);
2856
- if (!fetchOptions.throwOnError) {
2857
- promise = promise.catch(noop);
2858
- }
2859
- return query.state.fetchStatus === "paused" ? Promise.resolve() : promise;
2860
- })
2861
- );
2862
- return Promise.all(promises).then(noop);
2863
- }
2864
- fetchQuery(options) {
2865
- const defaultedOptions = this.defaultQueryOptions(options);
2866
- if (defaultedOptions.retry === void 0) {
2867
- defaultedOptions.retry = false;
2868
- }
2869
- const query = this.#queryCache.build(this, defaultedOptions);
2870
- return query.isStaleByTime(
2871
- resolveStaleTime(defaultedOptions.staleTime, query)
2872
- ) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);
2873
- }
2874
- prefetchQuery(options) {
2875
- return this.fetchQuery(options).then(noop).catch(noop);
2876
- }
2877
- fetchInfiniteQuery(options) {
2878
- options._type = "infinite";
2879
- return this.fetchQuery(options);
2880
- }
2881
- prefetchInfiniteQuery(options) {
2882
- return this.fetchInfiniteQuery(options).then(noop).catch(noop);
2883
- }
2884
- ensureInfiniteQueryData(options) {
2885
- options._type = "infinite";
2886
- return this.ensureQueryData(options);
2887
- }
2888
- resumePausedMutations() {
2889
- if (onlineManager.isOnline()) {
2890
- return this.#mutationCache.resumePausedMutations();
2891
- }
2892
- return Promise.resolve();
2893
- }
2894
- getQueryCache() {
2895
- return this.#queryCache;
2896
- }
2897
- getMutationCache() {
2898
- return this.#mutationCache;
2899
- }
2900
- getDefaultOptions() {
2901
- return this.#defaultOptions;
2902
- }
2903
- setDefaultOptions(options) {
2904
- this.#defaultOptions = options;
2905
- }
2906
- setQueryDefaults(queryKey, options) {
2907
- this.#queryDefaults.set(hashKey(queryKey), {
2908
- queryKey,
2909
- defaultOptions: options
2910
- });
2911
- }
2912
- getQueryDefaults(queryKey) {
2913
- const defaults = [...this.#queryDefaults.values()];
2914
- const result = {};
2915
- defaults.forEach((queryDefault) => {
2916
- if (partialMatchKey(queryKey, queryDefault.queryKey)) {
2917
- Object.assign(result, queryDefault.defaultOptions);
2918
- }
2919
- });
2920
- return result;
2921
- }
2922
- setMutationDefaults(mutationKey, options) {
2923
- this.#mutationDefaults.set(hashKey(mutationKey), {
2924
- mutationKey,
2925
- defaultOptions: options
2926
- });
2927
- }
2928
- getMutationDefaults(mutationKey) {
2929
- const defaults = [...this.#mutationDefaults.values()];
2930
- const result = {};
2931
- defaults.forEach((queryDefault) => {
2932
- if (partialMatchKey(mutationKey, queryDefault.mutationKey)) {
2933
- Object.assign(result, queryDefault.defaultOptions);
2934
- }
2935
- });
2936
- return result;
2937
- }
2938
- defaultQueryOptions(options) {
2939
- if (options._defaulted) {
2940
- return options;
2941
- }
2942
- const defaultedOptions = {
2943
- ...this.#defaultOptions.queries,
2944
- ...this.getQueryDefaults(options.queryKey),
2945
- ...options,
2946
- _defaulted: true
2947
- };
2948
- if (!defaultedOptions.queryHash) {
2949
- defaultedOptions.queryHash = hashQueryKeyByOptions(
2950
- defaultedOptions.queryKey,
2951
- defaultedOptions
2952
- );
2953
- }
2954
- if (defaultedOptions.refetchOnReconnect === void 0) {
2955
- defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== "always";
2956
- }
2957
- if (defaultedOptions.throwOnError === void 0) {
2958
- defaultedOptions.throwOnError = !!defaultedOptions.suspense;
2959
- }
2960
- if (!defaultedOptions.networkMode && defaultedOptions.persister) {
2961
- defaultedOptions.networkMode = "offlineFirst";
2962
- }
2963
- if (defaultedOptions.queryFn === skipToken) {
2964
- defaultedOptions.enabled = false;
2965
- }
2966
- return defaultedOptions;
2967
- }
2968
- defaultMutationOptions(options) {
2969
- if (options?._defaulted) {
2970
- return options;
2971
- }
2972
- return {
2973
- ...this.#defaultOptions.mutations,
2974
- ...options?.mutationKey && this.getMutationDefaults(options.mutationKey),
2975
- ...options,
2976
- _defaulted: true
2977
- };
2978
- }
2979
- clear() {
2980
- this.#queryCache.clear();
2981
- this.#mutationCache.clear();
2982
- }
2983
- };
2984
- function streamedQuery({
2985
- streamFn,
2986
- refetchMode = "reset",
2987
- reducer = (items, chunk) => addToEnd(items, chunk),
2988
- initialValue = []
2989
- }) {
2990
- return async (context) => {
2991
- const query = context.client.getQueryCache().find({ queryKey: context.queryKey, exact: true });
2992
- const isRefetch = !!query && query.isFetched();
2993
- if (isRefetch && refetchMode === "reset") {
2994
- query.setState({
2995
- ...query.resetState,
2996
- fetchStatus: "fetching"
2997
- });
2998
- }
2999
- let result = initialValue;
3000
- let cancelled = false;
3001
- const streamFnContext = addConsumeAwareSignal(
3002
- {
3003
- client: context.client,
3004
- meta: context.meta,
3005
- queryKey: context.queryKey,
3006
- pageParam: context.pageParam,
3007
- direction: context.direction
3008
- },
3009
- () => context.signal,
3010
- () => cancelled = true
3011
- );
3012
- const stream = await streamFn(streamFnContext);
3013
- const isReplaceRefetch = isRefetch && refetchMode === "replace";
3014
- for await (const chunk of stream) {
3015
- if (cancelled) {
3016
- break;
3017
- }
3018
- if (isReplaceRefetch) {
3019
- result = reducer(result, chunk);
3020
- } else {
3021
- context.client.setQueryData(
3022
- context.queryKey,
3023
- (prev) => reducer(prev === void 0 ? initialValue : prev, chunk)
3024
- );
3025
- }
3026
- }
3027
- if (isReplaceRefetch && !cancelled) {
3028
- context.client.setQueryData(context.queryKey, result);
3029
- }
3030
- return context.client.getQueryData(context.queryKey) ?? initialValue;
3031
- };
3032
- }
3033
- var dataTagSymbol = /* @__PURE__ */ Symbol("dataTagSymbol");
3034
- var dataTagErrorSymbol = /* @__PURE__ */ Symbol("dataTagErrorSymbol");
3035
- var unsetMarker = /* @__PURE__ */ Symbol("unsetMarker");
3036
- var QueryClientContext = __mf_13(
3037
- void 0
3038
- );
3039
- var useQueryClient = (queryClient) => {
3040
- const client = __mf_25(QueryClientContext);
3041
- if (queryClient) {
3042
- return queryClient;
3043
- }
3044
- if (!client) {
3045
- throw new Error("No QueryClient set, use QueryClientProvider to set one");
3046
- }
3047
- return client;
3048
- };
3049
- var QueryClientProvider = ({
3050
- client,
3051
- children
3052
- }) => {
3053
- __mf_28(() => {
3054
- client.mount();
3055
- return () => {
3056
- client.unmount();
3057
- };
3058
- }, [client]);
3059
- return /* @__PURE__ */ __mf_1(QueryClientContext.Provider, { value: client, children });
3060
- };
3061
- var IsRestoringContext = __mf_13(false);
3062
- var useIsRestoring = () => __mf_25(IsRestoringContext);
3063
- var IsRestoringProvider = IsRestoringContext.Provider;
3064
- function createValue() {
3065
- let isReset = false;
3066
- return {
3067
- clearReset: () => {
3068
- isReset = false;
3069
- },
3070
- reset: () => {
3071
- isReset = true;
3072
- },
3073
- isReset: () => {
3074
- return isReset;
3075
- }
3076
- };
3077
- }
3078
- var QueryErrorResetBoundaryContext = __mf_13(createValue());
3079
- var useQueryErrorResetBoundary = () => __mf_25(QueryErrorResetBoundaryContext);
3080
- var QueryErrorResetBoundary = ({
3081
- children
3082
- }) => {
3083
- const [value] = __mf_38(() => createValue());
3084
- return /* @__PURE__ */ __mf_1(QueryErrorResetBoundaryContext.Provider, { value, children: typeof children === "function" ? children(value) : children });
3085
- };
3086
- var ensurePreventErrorBoundaryRetry = (options, errorResetBoundary, query) => {
3087
- const throwOnError = query?.state.error && typeof options.throwOnError === "function" ? shouldThrowError(options.throwOnError, [query.state.error, query]) : options.throwOnError;
3088
- if (options.suspense || options.experimental_prefetchInRender || throwOnError) {
3089
- if (!errorResetBoundary.isReset()) {
3090
- options.retryOnMount = false;
3091
- }
3092
- }
3093
- };
3094
- var useClearResetErrorBoundary = (errorResetBoundary) => {
3095
- __mf_28(() => {
3096
- errorResetBoundary.clearReset();
3097
- }, [errorResetBoundary]);
3098
- };
3099
- var getHasError = ({
3100
- result,
3101
- errorResetBoundary,
3102
- throwOnError,
3103
- query,
3104
- suspense
3105
- }) => {
3106
- return result.isError && !errorResetBoundary.isReset() && !result.isFetching && query && (suspense && result.data === void 0 || shouldThrowError(throwOnError, [result.error, query]));
3107
- };
3108
- var defaultThrowOnError = (_error, query) => query.state.data === void 0;
3109
- var ensureSuspenseTimers = (defaultedOptions) => {
3110
- if (defaultedOptions.suspense) {
3111
- const MIN_SUSPENSE_TIME_MS = 1e3;
3112
- const clamp = (value) => value === "static" ? value : Math.max(value ?? MIN_SUSPENSE_TIME_MS, MIN_SUSPENSE_TIME_MS);
3113
- const originalStaleTime = defaultedOptions.staleTime;
3114
- defaultedOptions.staleTime = typeof originalStaleTime === "function" ? (...args) => clamp(originalStaleTime(...args)) : clamp(originalStaleTime);
3115
- if (typeof defaultedOptions.gcTime === "number") {
3116
- defaultedOptions.gcTime = Math.max(
3117
- defaultedOptions.gcTime,
3118
- MIN_SUSPENSE_TIME_MS
3119
- );
3120
- }
3121
- }
3122
- };
3123
- var willFetch = (result, isRestoring) => result.isLoading && result.isFetching && !isRestoring;
3124
- var shouldSuspend = (defaultedOptions, result) => defaultedOptions?.suspense && result.isPending;
3125
- var fetchOptimistic = (defaultedOptions, observer, errorResetBoundary) => observer.fetchOptimistic(defaultedOptions).catch(() => {
3126
- errorResetBoundary.clearReset();
3127
- });
3128
- function useQueries({
3129
- queries,
3130
- ...options
3131
- }, queryClient) {
3132
- const client = useQueryClient(queryClient);
3133
- const isRestoring = useIsRestoring();
3134
- const errorResetBoundary = useQueryErrorResetBoundary();
3135
- const defaultedQueries = __mf_34(
3136
- () => queries.map((opts) => {
3137
- const defaultedOptions = client.defaultQueryOptions(
3138
- opts
3139
- );
3140
- defaultedOptions._optimisticResults = isRestoring ? "isRestoring" : "optimistic";
3141
- return defaultedOptions;
3142
- }),
3143
- [queries, client, isRestoring]
3144
- );
3145
- defaultedQueries.forEach((queryOptions2) => {
3146
- ensureSuspenseTimers(queryOptions2);
3147
- const query = client.getQueryCache().get(queryOptions2.queryHash);
3148
- ensurePreventErrorBoundaryRetry(queryOptions2, errorResetBoundary, query);
3149
- });
3150
- useClearResetErrorBoundary(errorResetBoundary);
3151
- const [observer] = __mf_38(
3152
- () => new QueriesObserver(
3153
- client,
3154
- defaultedQueries,
3155
- options
3156
- )
3157
- );
3158
- const [optimisticResult, getCombinedResult, trackResult] = observer.getOptimisticResult(
3159
- defaultedQueries,
3160
- options.combine
3161
- );
3162
- const shouldSubscribe = !isRestoring && options.subscribed !== false;
3163
- __mf_39(
3164
- __mf_24(
3165
- (onStoreChange) => shouldSubscribe ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) : noop,
3166
- [observer, shouldSubscribe]
3167
- ),
3168
- () => observer.getCurrentResult(),
3169
- () => observer.getCurrentResult()
3170
- );
3171
- __mf_28(() => {
3172
- observer.setQueries(
3173
- defaultedQueries,
3174
- options
3175
- );
3176
- }, [defaultedQueries, options, observer]);
3177
- const shouldAtLeastOneSuspend = optimisticResult.some(
3178
- (result, index) => shouldSuspend(defaultedQueries[index], result)
3179
- );
3180
- const suspensePromises = shouldAtLeastOneSuspend ? optimisticResult.flatMap((result, index) => {
3181
- const opts = defaultedQueries[index];
3182
- if (opts && shouldSuspend(opts, result)) {
3183
- const queryObserver = new QueryObserver(client, opts);
3184
- return fetchOptimistic(opts, queryObserver, errorResetBoundary);
3185
- }
3186
- return [];
3187
- }) : [];
3188
- if (suspensePromises.length > 0) {
3189
- throw Promise.all(suspensePromises);
3190
- }
3191
- const firstSingleResultWhichShouldThrow = optimisticResult.find(
3192
- (result, index) => {
3193
- const query = defaultedQueries[index];
3194
- return query && getHasError({
3195
- result,
3196
- errorResetBoundary,
3197
- throwOnError: query.throwOnError,
3198
- query: client.getQueryCache().get(query.queryHash),
3199
- suspense: query.suspense
3200
- });
3201
- }
3202
- );
3203
- if (firstSingleResultWhichShouldThrow?.error) {
3204
- throw firstSingleResultWhichShouldThrow.error;
3205
- }
3206
- return getCombinedResult(trackResult());
3207
- }
3208
- function useBaseQuery(options, Observer, queryClient) {
3209
- const isRestoring = useIsRestoring();
3210
- const errorResetBoundary = useQueryErrorResetBoundary();
3211
- const client = useQueryClient(queryClient);
3212
- const defaultedOptions = client.defaultQueryOptions(options);
3213
- client.getDefaultOptions().queries?._experimental_beforeQuery?.(
3214
- defaultedOptions
3215
- );
3216
- const query = client.getQueryCache().get(defaultedOptions.queryHash);
3217
- defaultedOptions._optimisticResults = isRestoring ? "isRestoring" : "optimistic";
3218
- ensureSuspenseTimers(defaultedOptions);
3219
- ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query);
3220
- useClearResetErrorBoundary(errorResetBoundary);
3221
- const isNewCacheEntry = !client.getQueryCache().get(defaultedOptions.queryHash);
3222
- const [observer] = __mf_38(
3223
- () => new Observer(
3224
- client,
3225
- defaultedOptions
3226
- )
3227
- );
3228
- const result = observer.getOptimisticResult(defaultedOptions);
3229
- const shouldSubscribe = !isRestoring && options.subscribed !== false;
3230
- __mf_39(
3231
- __mf_24(
3232
- (onStoreChange) => {
3233
- const unsubscribe = shouldSubscribe ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) : noop;
3234
- observer.updateResult();
3235
- return unsubscribe;
3236
- },
3237
- [observer, shouldSubscribe]
3238
- ),
3239
- () => observer.getCurrentResult(),
3240
- () => observer.getCurrentResult()
3241
- );
3242
- __mf_28(() => {
3243
- observer.setOptions(defaultedOptions);
3244
- }, [defaultedOptions, observer]);
3245
- if (shouldSuspend(defaultedOptions, result)) {
3246
- throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary);
3247
- }
3248
- if (getHasError({
3249
- result,
3250
- errorResetBoundary,
3251
- throwOnError: defaultedOptions.throwOnError,
3252
- query,
3253
- suspense: defaultedOptions.suspense
3254
- })) {
3255
- throw result.error;
3256
- }
3257
- client.getDefaultOptions().queries?._experimental_afterQuery?.(
3258
- defaultedOptions,
3259
- result
3260
- );
3261
- if (defaultedOptions.experimental_prefetchInRender && !environmentManager.isServer() && willFetch(result, isRestoring)) {
3262
- const promise = isNewCacheEntry ? (
3263
- // Fetch immediately on render in order to ensure `.promise` is resolved even if the component is unmounted
3264
- fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
3265
- ) : (
3266
- // subscribe to the "cache promise" so that we can finalize the currentThenable once data comes in
3267
- query?.promise
3268
- );
3269
- promise?.catch(noop).finally(() => {
3270
- observer.updateResult();
3271
- });
3272
- }
3273
- return !defaultedOptions.notifyOnChangeProps ? observer.trackResult(result) : result;
3274
- }
3275
- function useQuery(options, queryClient) {
3276
- return useBaseQuery(options, QueryObserver, queryClient);
3277
- }
3278
- function useSuspenseQuery(options, queryClient) {
3279
- return useBaseQuery(
3280
- {
3281
- ...options,
3282
- enabled: true,
3283
- suspense: true,
3284
- throwOnError: defaultThrowOnError,
3285
- placeholderData: void 0
3286
- },
3287
- QueryObserver,
3288
- queryClient
3289
- );
3290
- }
3291
- function useSuspenseInfiniteQuery(options, queryClient) {
3292
- return useBaseQuery(
3293
- {
3294
- ...options,
3295
- enabled: true,
3296
- suspense: true,
3297
- throwOnError: defaultThrowOnError
3298
- },
3299
- InfiniteQueryObserver,
3300
- queryClient
3301
- );
3302
- }
3303
- function useSuspenseQueries(options, queryClient) {
3304
- return useQueries(
3305
- {
3306
- ...options,
3307
- queries: options.queries.map((query) => {
3308
- return {
3309
- ...query,
3310
- suspense: true,
3311
- throwOnError: defaultThrowOnError,
3312
- enabled: true,
3313
- placeholderData: void 0
3314
- };
3315
- })
3316
- },
3317
- queryClient
3318
- );
3319
- }
3320
- function usePrefetchQuery(options, queryClient) {
3321
- const client = useQueryClient(queryClient);
3322
- if (!client.getQueryState(options.queryKey)) {
3323
- client.prefetchQuery(options);
3324
- }
3325
- }
3326
- function usePrefetchInfiniteQuery(options, queryClient) {
3327
- const client = useQueryClient(queryClient);
3328
- if (!client.getQueryState(options.queryKey)) {
3329
- client.prefetchInfiniteQuery(options);
3330
- }
3331
- }
3332
- function queryOptions(options) {
3333
- return options;
3334
- }
3335
- function infiniteQueryOptions(options) {
3336
- return options;
3337
- }
3338
- var HydrationBoundary = ({
3339
- children,
3340
- options = {},
3341
- state,
3342
- queryClient
3343
- }) => {
3344
- const client = useQueryClient(queryClient);
3345
- const optionsRef = __mf_37(options);
3346
- __mf_28(() => {
3347
- optionsRef.current = options;
3348
- });
3349
- const hydrationQueue = __mf_34(() => {
3350
- if (state) {
3351
- if (typeof state !== "object") {
3352
- return;
3353
- }
3354
- const queryCache = client.getQueryCache();
3355
- const queries = state.queries || [];
3356
- const newQueries = [];
3357
- const existingQueries = [];
3358
- for (const dehydratedQuery of queries) {
3359
- const existingQuery = queryCache.get(dehydratedQuery.queryHash);
3360
- if (!existingQuery) {
3361
- newQueries.push(dehydratedQuery);
3362
- } else {
3363
- const hydrationIsNewer = dehydratedQuery.state.dataUpdatedAt > existingQuery.state.dataUpdatedAt || dehydratedQuery.promise && existingQuery.state.status !== "pending" && existingQuery.state.fetchStatus !== "fetching" && dehydratedQuery.dehydratedAt !== void 0 && dehydratedQuery.dehydratedAt > existingQuery.state.dataUpdatedAt;
3364
- if (hydrationIsNewer) {
3365
- existingQueries.push(dehydratedQuery);
3366
- }
3367
- }
3368
- }
3369
- if (newQueries.length > 0) {
3370
- hydrate(client, { queries: newQueries }, optionsRef.current);
3371
- }
3372
- if (existingQueries.length > 0) {
3373
- return existingQueries;
3374
- }
3375
- }
3376
- return void 0;
3377
- }, [client, state]);
3378
- __mf_28(() => {
3379
- if (hydrationQueue) {
3380
- hydrate(client, { queries: hydrationQueue }, optionsRef.current);
3381
- }
3382
- }, [client, hydrationQueue]);
3383
- return children;
3384
- };
3385
- function useIsFetching(filters, queryClient) {
3386
- const client = useQueryClient(queryClient);
3387
- const queryCache = client.getQueryCache();
3388
- return __mf_39(
3389
- __mf_24(
3390
- (onStoreChange) => queryCache.subscribe(notifyManager.batchCalls(onStoreChange)),
3391
- [queryCache]
3392
- ),
3393
- () => client.isFetching(filters),
3394
- () => client.isFetching(filters)
3395
- );
3396
- }
3397
- function useIsMutating(filters, queryClient) {
3398
- const client = useQueryClient(queryClient);
3399
- return useMutationState(
3400
- { filters: { ...filters, status: "pending" } },
3401
- client
3402
- ).length;
3403
- }
3404
- function getResult(mutationCache, options) {
3405
- return mutationCache.findAll(options.filters).map(
3406
- (mutation) => options.select ? options.select(mutation) : mutation.state
3407
- );
3408
- }
3409
- function useMutationState(options = {}, queryClient) {
3410
- const mutationCache = useQueryClient(queryClient).getMutationCache();
3411
- const optionsRef = __mf_37(options);
3412
- const result = __mf_37(null);
3413
- if (result.current === null) {
3414
- result.current = getResult(mutationCache, options);
3415
- }
3416
- __mf_28(() => {
3417
- optionsRef.current = options;
3418
- });
3419
- return __mf_39(
3420
- __mf_24(
3421
- (onStoreChange) => mutationCache.subscribe(() => {
3422
- const nextResult = replaceEqualDeep(
3423
- result.current,
3424
- getResult(mutationCache, optionsRef.current)
3425
- );
3426
- if (result.current !== nextResult) {
3427
- result.current = nextResult;
3428
- notifyManager.schedule(onStoreChange);
3429
- }
3430
- }),
3431
- [mutationCache]
3432
- ),
3433
- () => result.current,
3434
- () => result.current
3435
- );
3436
- }
3437
- function useMutation(options, queryClient) {
3438
- const client = useQueryClient(queryClient);
3439
- const [observer] = __mf_38(
3440
- () => new MutationObserver(
3441
- client,
3442
- options
3443
- )
3444
- );
3445
- __mf_28(() => {
3446
- observer.setOptions(options);
3447
- }, [observer, options]);
3448
- const result = __mf_39(
3449
- __mf_24(
3450
- (onStoreChange) => observer.subscribe(notifyManager.batchCalls(onStoreChange)),
3451
- [observer]
3452
- ),
3453
- () => observer.getCurrentResult(),
3454
- () => observer.getCurrentResult()
3455
- );
3456
- const mutate = __mf_24(
3457
- (variables, mutateOptions) => {
3458
- observer.mutate(variables, mutateOptions).catch(noop);
3459
- },
3460
- [observer]
3461
- );
3462
- if (result.error && shouldThrowError(observer.options.throwOnError, [result.error])) {
3463
- throw result.error;
3464
- }
3465
- return { ...result, mutate, mutateAsync: result.mutate };
3466
- }
3467
- function mutationOptions(options) {
3468
- return options;
3469
- }
3470
- function useInfiniteQuery(options, queryClient) {
3471
- return useBaseQuery(
3472
- options,
3473
- InfiniteQueryObserver,
3474
- queryClient
3475
- );
3476
- }
3477
- export {
3478
- CancelledError,
3479
- HydrationBoundary,
3480
- InfiniteQueryObserver,
3481
- IsRestoringProvider,
3482
- Mutation,
3483
- MutationCache,
3484
- MutationObserver,
3485
- QueriesObserver,
3486
- Query,
3487
- QueryCache,
3488
- QueryClient,
3489
- QueryClientContext,
3490
- QueryClientProvider,
3491
- QueryErrorResetBoundary,
3492
- QueryObserver,
3493
- dataTagErrorSymbol,
3494
- dataTagSymbol,
3495
- defaultScheduler,
3496
- defaultShouldDehydrateMutation,
3497
- defaultShouldDehydrateQuery,
3498
- dehydrate,
3499
- environmentManager,
3500
- streamedQuery as experimental_streamedQuery,
3501
- focusManager,
3502
- hashKey,
3503
- hydrate,
3504
- infiniteQueryOptions,
3505
- isCancelledError,
3506
- isServer,
3507
- keepPreviousData,
3508
- matchMutation,
3509
- matchQuery,
3510
- mutationOptions,
3511
- noop,
3512
- notifyManager,
3513
- onlineManager,
3514
- partialMatchKey,
3515
- queryOptions,
3516
- replaceEqualDeep,
3517
- shouldThrowError,
3518
- skipToken,
3519
- timeoutManager,
3520
- unsetMarker,
3521
- useInfiniteQuery,
3522
- useIsFetching,
3523
- useIsMutating,
3524
- useIsRestoring,
3525
- useMutation,
3526
- useMutationState,
3527
- usePrefetchInfiniteQuery,
3528
- usePrefetchQuery,
3529
- useQueries,
3530
- useQuery,
3531
- useQueryClient,
3532
- useQueryErrorResetBoundary,
3533
- useSuspenseInfiniteQuery,
3534
- useSuspenseQueries,
3535
- useSuspenseQuery
3536
- };