@tanstack/query-core 5.105.1 → 5.105.2

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 (139) hide show
  1. package/build/legacy/{hydration-DdkP3REv.d.cts → hydration-BXjqUj_D.d.cts} +25 -14
  2. package/build/legacy/hydration-BXjqUj_D.d.cts.map +1 -0
  3. package/build/legacy/{hydration-gHEs4kLM.d.ts → hydration-vgIjIhk6.d.ts} +25 -14
  4. package/build/legacy/hydration-vgIjIhk6.d.ts.map +1 -0
  5. package/build/legacy/hydration.d.cts +1 -1
  6. package/build/legacy/hydration.d.ts +1 -1
  7. package/build/legacy/index.d.cts +1 -1
  8. package/build/legacy/index.d.ts +1 -1
  9. package/build/legacy/infiniteQueryBehavior.cjs +2 -1
  10. package/build/legacy/infiniteQueryBehavior.cjs.map +1 -1
  11. package/build/legacy/infiniteQueryBehavior.d.cts +1 -1
  12. package/build/legacy/infiniteQueryBehavior.d.cts.map +1 -1
  13. package/build/legacy/infiniteQueryBehavior.d.ts +1 -1
  14. package/build/legacy/infiniteQueryBehavior.d.ts.map +1 -1
  15. package/build/legacy/infiniteQueryBehavior.js +3 -2
  16. package/build/legacy/infiniteQueryBehavior.js.map +1 -1
  17. package/build/legacy/infiniteQueryObserver.d.cts +1 -1
  18. package/build/legacy/infiniteQueryObserver.d.ts +1 -1
  19. package/build/legacy/mutation.cjs +1 -0
  20. package/build/legacy/mutation.cjs.map +1 -1
  21. package/build/legacy/mutation.d.cts +1 -1
  22. package/build/legacy/mutation.d.ts +1 -1
  23. package/build/legacy/mutation.js +1 -0
  24. package/build/legacy/mutation.js.map +1 -1
  25. package/build/legacy/mutationCache.d.cts +1 -1
  26. package/build/legacy/mutationCache.d.ts +1 -1
  27. package/build/legacy/mutationObserver.d.cts +1 -1
  28. package/build/legacy/mutationObserver.d.ts +1 -1
  29. package/build/legacy/queriesObserver.d.cts +1 -1
  30. package/build/legacy/queriesObserver.d.ts +1 -1
  31. package/build/legacy/query.cjs +54 -36
  32. package/build/legacy/query.cjs.map +1 -1
  33. package/build/legacy/query.d.cts +1 -1
  34. package/build/legacy/query.d.ts +1 -1
  35. package/build/legacy/query.js +55 -37
  36. package/build/legacy/query.js.map +1 -1
  37. package/build/legacy/queryCache.d.cts +1 -1
  38. package/build/legacy/queryCache.d.ts +1 -1
  39. package/build/legacy/queryClient.cjs +11 -6
  40. package/build/legacy/queryClient.cjs.map +1 -1
  41. package/build/legacy/queryClient.d.cts +1 -1
  42. package/build/legacy/queryClient.d.ts +1 -1
  43. package/build/legacy/queryClient.js +11 -6
  44. package/build/legacy/queryClient.js.map +1 -1
  45. package/build/legacy/queryObserver.d.cts +1 -1
  46. package/build/legacy/queryObserver.d.ts +1 -1
  47. package/build/legacy/retryer.d.cts +1 -1
  48. package/build/legacy/retryer.d.ts +1 -1
  49. package/build/legacy/streamedQuery.cjs +10 -4
  50. package/build/legacy/streamedQuery.cjs.map +1 -1
  51. package/build/legacy/streamedQuery.d.cts +3 -1
  52. package/build/legacy/streamedQuery.d.cts.map +1 -1
  53. package/build/legacy/streamedQuery.d.ts +3 -1
  54. package/build/legacy/streamedQuery.d.ts.map +1 -1
  55. package/build/legacy/streamedQuery.js +11 -5
  56. package/build/legacy/streamedQuery.js.map +1 -1
  57. package/build/legacy/types.d.cts +1 -1
  58. package/build/legacy/types.d.ts +1 -1
  59. package/build/legacy/utils.cjs +23 -19
  60. package/build/legacy/utils.cjs.map +1 -1
  61. package/build/legacy/utils.d.cts +2 -2
  62. package/build/legacy/utils.d.ts +2 -2
  63. package/build/legacy/utils.js +23 -20
  64. package/build/legacy/utils.js.map +1 -1
  65. package/build/modern/{hydration-DdkP3REv.d.cts → hydration-BXjqUj_D.d.cts} +25 -14
  66. package/build/modern/hydration-BXjqUj_D.d.cts.map +1 -0
  67. package/build/modern/{hydration-gHEs4kLM.d.ts → hydration-vgIjIhk6.d.ts} +25 -14
  68. package/build/modern/hydration-vgIjIhk6.d.ts.map +1 -0
  69. package/build/modern/hydration.d.cts +1 -1
  70. package/build/modern/hydration.d.ts +1 -1
  71. package/build/modern/index.d.cts +1 -1
  72. package/build/modern/index.d.ts +1 -1
  73. package/build/modern/infiniteQueryBehavior.cjs +2 -1
  74. package/build/modern/infiniteQueryBehavior.cjs.map +1 -1
  75. package/build/modern/infiniteQueryBehavior.d.cts +1 -1
  76. package/build/modern/infiniteQueryBehavior.d.cts.map +1 -1
  77. package/build/modern/infiniteQueryBehavior.d.ts +1 -1
  78. package/build/modern/infiniteQueryBehavior.d.ts.map +1 -1
  79. package/build/modern/infiniteQueryBehavior.js +3 -2
  80. package/build/modern/infiniteQueryBehavior.js.map +1 -1
  81. package/build/modern/infiniteQueryObserver.d.cts +1 -1
  82. package/build/modern/infiniteQueryObserver.d.ts +1 -1
  83. package/build/modern/mutation.cjs +1 -0
  84. package/build/modern/mutation.cjs.map +1 -1
  85. package/build/modern/mutation.d.cts +1 -1
  86. package/build/modern/mutation.d.ts +1 -1
  87. package/build/modern/mutation.js +1 -0
  88. package/build/modern/mutation.js.map +1 -1
  89. package/build/modern/mutationCache.d.cts +1 -1
  90. package/build/modern/mutationCache.d.ts +1 -1
  91. package/build/modern/mutationObserver.d.cts +1 -1
  92. package/build/modern/mutationObserver.d.ts +1 -1
  93. package/build/modern/queriesObserver.d.cts +1 -1
  94. package/build/modern/queriesObserver.d.ts +1 -1
  95. package/build/modern/query.cjs +51 -34
  96. package/build/modern/query.cjs.map +1 -1
  97. package/build/modern/query.d.cts +1 -1
  98. package/build/modern/query.d.ts +1 -1
  99. package/build/modern/query.js +52 -35
  100. package/build/modern/query.js.map +1 -1
  101. package/build/modern/queryCache.d.cts +1 -1
  102. package/build/modern/queryCache.d.ts +1 -1
  103. package/build/modern/queryClient.cjs +11 -6
  104. package/build/modern/queryClient.cjs.map +1 -1
  105. package/build/modern/queryClient.d.cts +1 -1
  106. package/build/modern/queryClient.d.ts +1 -1
  107. package/build/modern/queryClient.js +11 -6
  108. package/build/modern/queryClient.js.map +1 -1
  109. package/build/modern/queryObserver.d.cts +1 -1
  110. package/build/modern/queryObserver.d.ts +1 -1
  111. package/build/modern/retryer.d.cts +1 -1
  112. package/build/modern/retryer.d.ts +1 -1
  113. package/build/modern/streamedQuery.cjs +10 -4
  114. package/build/modern/streamedQuery.cjs.map +1 -1
  115. package/build/modern/streamedQuery.d.cts +3 -1
  116. package/build/modern/streamedQuery.d.cts.map +1 -1
  117. package/build/modern/streamedQuery.d.ts +3 -1
  118. package/build/modern/streamedQuery.d.ts.map +1 -1
  119. package/build/modern/streamedQuery.js +11 -5
  120. package/build/modern/streamedQuery.js.map +1 -1
  121. package/build/modern/types.d.cts +1 -1
  122. package/build/modern/types.d.ts +1 -1
  123. package/build/modern/utils.cjs +23 -19
  124. package/build/modern/utils.cjs.map +1 -1
  125. package/build/modern/utils.d.cts +2 -2
  126. package/build/modern/utils.d.ts +2 -2
  127. package/build/modern/utils.js +23 -20
  128. package/build/modern/utils.js.map +1 -1
  129. package/package.json +1 -1
  130. package/src/infiniteQueryBehavior.ts +5 -1
  131. package/src/mutation.ts +4 -0
  132. package/src/query.ts +78 -64
  133. package/src/queryClient.ts +16 -10
  134. package/src/streamedQuery.ts +14 -3
  135. package/src/utils.ts +39 -26
  136. package/build/legacy/hydration-DdkP3REv.d.cts.map +0 -1
  137. package/build/legacy/hydration-gHEs4kLM.d.ts.map +0 -1
  138. package/build/modern/hydration-DdkP3REv.d.cts.map +0 -1
  139. package/build/modern/hydration-gHEs4kLM.d.ts.map +0 -1
@@ -6,6 +6,8 @@ const require_utils = require("./utils.cjs");
6
6
  * Data will be an Array of all the chunks received.
7
7
  * The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.
8
8
  * The query will stay in fetchStatus 'fetching' until the stream ends.
9
+ * Explicit cancellation stops further cache updates, even if `streamFn` does not read `signal`.
10
+ * If `streamFn` does not read `signal`, the stream continues after the last observer unsubscribes.
9
11
  * @param options - The `streamFn` that returns an AsyncIterable to stream data from, and the optional
10
12
  * `refetchMode`, `reducer`, and `initialValue` options.
11
13
  * @returns A query function to pass as `queryFn`.
@@ -21,6 +23,8 @@ const require_utils = require("./utils.cjs");
21
23
  */
22
24
  function streamedQuery({ streamFn, refetchMode = "reset", reducer = (items, chunk) => require_utils.addToEnd(items, chunk), initialValue = [] }) {
23
25
  return async (context) => {
26
+ const signal = context[require_utils.fetchSignal];
27
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted) return initialValue;
24
28
  const query = context.client.getQueryCache().find({
25
29
  queryKey: context.queryKey,
26
30
  exact: true
@@ -32,20 +36,22 @@ function streamedQuery({ streamFn, refetchMode = "reset", reducer = (items, chun
32
36
  });
33
37
  let result = initialValue;
34
38
  let cancelled = false;
35
- const stream = await streamFn(require_utils.addConsumeAwareSignal({
39
+ const streamFnContext = require_utils.addConsumeAwareSignal({
36
40
  client: context.client,
37
41
  meta: context.meta,
38
42
  queryKey: context.queryKey,
39
43
  pageParam: context.pageParam,
40
44
  direction: context.direction
41
- }, () => context.signal, () => cancelled = true));
45
+ }, () => context.signal, () => cancelled = true, signal);
46
+ const isStreamInactive = () => cancelled || (signal === null || signal === void 0 ? void 0 : signal.aborted) === true;
47
+ const stream = await streamFn(streamFnContext);
42
48
  const isReplaceRefetch = isRefetch && refetchMode === "replace";
43
49
  for await (const chunk of stream) {
44
- if (cancelled) break;
50
+ if (isStreamInactive()) break;
45
51
  if (isReplaceRefetch) result = reducer(result, chunk);
46
52
  else context.client.setQueryData(context.queryKey, (prev) => reducer(prev === void 0 ? initialValue : prev, chunk));
47
53
  }
48
- if (isReplaceRefetch && !cancelled) context.client.setQueryData(context.queryKey, result);
54
+ if (isReplaceRefetch && !isStreamInactive()) context.client.setQueryData(context.queryKey, result);
49
55
  const data = context.client.getQueryData(context.queryKey);
50
56
  return data === void 0 ? initialValue : data;
51
57
  };
@@ -1 +1 @@
1
- {"version":3,"file":"streamedQuery.cjs","names":["addToEnd","addConsumeAwareSignal"],"sources":["../../src/streamedQuery.ts"],"sourcesContent":["import { addConsumeAwareSignal, addToEnd } from './utils'\nimport type {\n OmitKeyof,\n QueryFunction,\n QueryFunctionContext,\n QueryKey,\n} from './types'\n\ntype BaseStreamedQueryParams<TQueryFnData, TQueryKey extends QueryKey> = {\n /** The function that returns an `AsyncIterable` to stream data from. */\n streamFn: (\n context: QueryFunctionContext<TQueryKey>,\n ) => AsyncIterable<TQueryFnData> | Promise<AsyncIterable<TQueryFnData>>\n /**\n * Defines how refetches are handled.\n * - `'reset'` (default): erases all data and puts the query back into `pending` state.\n * - `'append'`: appends new data to the existing data.\n * - `'replace'`: writes all data to the cache once the stream ends.\n */\n refetchMode?: 'append' | 'reset' | 'replace'\n}\n\ntype SimpleStreamedQueryParams<\n TQueryFnData,\n TQueryKey extends QueryKey,\n> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {\n reducer?: never\n initialValue?: never\n}\n\ntype ReducibleStreamedQueryParams<\n TQueryFnData,\n TData,\n TQueryKey extends QueryKey,\n> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {\n /**\n * Reduces streamed chunks into the final data shape. Required whenever `TData` is not an\n * array, since there is no default way to accumulate non-array chunks.\n */\n reducer: (acc: TData, chunk: TQueryFnData) => TData\n /**\n * The value used while the first chunk is being fetched, and returned if the stream yields no\n * values. Required together with a custom `reducer`.\n */\n initialValue: TData\n}\n\ntype StreamedQueryParams<TQueryFnData, TData, TQueryKey extends QueryKey> =\n | SimpleStreamedQueryParams<TQueryFnData, TQueryKey>\n | ReducibleStreamedQueryParams<TQueryFnData, TData, TQueryKey>\n\n/**\n * This is a helper function to create a query function that streams data from an AsyncIterable.\n * Data will be an Array of all the chunks received.\n * The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.\n * The query will stay in fetchStatus 'fetching' until the stream ends.\n * @param options - The `streamFn` that returns an AsyncIterable to stream data from, and the optional\n * `refetchMode`, `reducer`, and `initialValue` options.\n * @returns A query function to pass as `queryFn`.\n * @example\n * ```ts\n * await queryClient.query({\n * queryKey: ['data'],\n * queryFn: streamedQuery({\n * streamFn: fetchDataInChunks,\n * }),\n * })\n * ```\n */\nexport function streamedQuery<\n TQueryFnData = unknown,\n TData = Array<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n>({\n streamFn,\n refetchMode = 'reset',\n reducer = (items, chunk) =>\n addToEnd(items as Array<TQueryFnData>, chunk) as TData,\n initialValue = [] as TData,\n}: StreamedQueryParams<TQueryFnData, TData, TQueryKey>): QueryFunction<\n TData,\n TQueryKey\n> {\n return async (context) => {\n const query = context.client\n .getQueryCache()\n .find({ queryKey: context.queryKey, exact: true })\n const isRefetch = !!query && query.isFetched()\n if (isRefetch && refetchMode === 'reset') {\n query.setState({\n ...query.resetState,\n fetchStatus: 'fetching',\n })\n }\n\n let result = initialValue\n\n let cancelled = false as boolean\n const streamFnContext = addConsumeAwareSignal<\n OmitKeyof<typeof context, 'signal'>\n >(\n {\n client: context.client,\n meta: context.meta,\n queryKey: context.queryKey,\n pageParam: context.pageParam,\n direction: context.direction,\n },\n () => context.signal,\n () => (cancelled = true),\n )\n\n const stream = await streamFn(streamFnContext)\n\n const isReplaceRefetch = isRefetch && refetchMode === 'replace'\n\n for await (const chunk of stream) {\n if (cancelled) {\n break\n }\n\n if (isReplaceRefetch) {\n // don't append to the cache directly when replace-refetching\n result = reducer(result, chunk)\n } else {\n context.client.setQueryData<TData>(context.queryKey, (prev) =>\n reducer(prev === undefined ? initialValue : prev, chunk),\n )\n }\n }\n\n // finalize result: replace-refetching needs to write to the cache\n if (isReplaceRefetch && !cancelled) {\n context.client.setQueryData<TData>(context.queryKey, result)\n }\n\n const data = context.client.getQueryData<TData>(context.queryKey)\n return data === undefined ? initialValue : data\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqEA,SAAgB,cAId,EACA,UACA,cAAc,SACd,WAAW,OAAO,UAChBA,cAAAA,SAAS,OAA8B,KAAK,GAC9C,eAAe,CAAC,KAIhB;CACA,OAAO,OAAO,YAAY;EACxB,MAAM,QAAQ,QAAQ,OACnB,cAAc,CAAC,CACf,KAAK;GAAE,UAAU,QAAQ;GAAU,OAAO;EAAK,CAAC;EACnD,MAAM,YAAY,CAAC,CAAC,SAAS,MAAM,UAAU;EAC7C,IAAI,aAAa,gBAAgB,SAC/B,MAAM,SAAS;GACb,GAAG,MAAM;GACT,aAAa;EACf,CAAC;EAGH,IAAI,SAAS;EAEb,IAAI,YAAY;EAehB,MAAM,SAAS,MAAM,SAdGC,cAAAA,sBAGtB;GACE,QAAQ,QAAQ;GAChB,MAAM,QAAQ;GACd,UAAU,QAAQ;GAClB,WAAW,QAAQ;GACnB,WAAW,QAAQ;EACrB,SACM,QAAQ,cACP,YAAY,IAGuB,CAAC;EAE7C,MAAM,mBAAmB,aAAa,gBAAgB;EAEtD,WAAW,MAAM,SAAS,QAAQ;GAChC,IAAI,WACF;GAGF,IAAI,kBAEF,SAAS,QAAQ,QAAQ,KAAK;QAE9B,QAAQ,OAAO,aAAoB,QAAQ,WAAW,SACpD,QAAQ,SAAS,KAAA,IAAY,eAAe,MAAM,KAAK,CACzD;EAEJ;EAGA,IAAI,oBAAoB,CAAC,WACvB,QAAQ,OAAO,aAAoB,QAAQ,UAAU,MAAM;EAG7D,MAAM,OAAO,QAAQ,OAAO,aAAoB,QAAQ,QAAQ;EAChE,OAAO,SAAS,KAAA,IAAY,eAAe;CAC7C;AACF"}
1
+ {"version":3,"file":"streamedQuery.cjs","names":["addToEnd","signalContext","fetchSignal","addConsumeAwareSignal"],"sources":["../../src/streamedQuery.ts"],"sourcesContent":["import { addConsumeAwareSignal, addToEnd, fetchSignal } from './utils'\nimport type { FetchSignalContext } from './utils'\nimport type {\n OmitKeyof,\n QueryFunction,\n QueryFunctionContext,\n QueryKey,\n} from './types'\n\ntype BaseStreamedQueryParams<TQueryFnData, TQueryKey extends QueryKey> = {\n /** The function that returns an `AsyncIterable` to stream data from. */\n streamFn: (\n context: QueryFunctionContext<TQueryKey>,\n ) => AsyncIterable<TQueryFnData> | Promise<AsyncIterable<TQueryFnData>>\n /**\n * Defines how refetches are handled.\n * - `'reset'` (default): erases all data and puts the query back into `pending` state.\n * - `'append'`: appends new data to the existing data.\n * - `'replace'`: writes all data to the cache once the stream ends.\n */\n refetchMode?: 'append' | 'reset' | 'replace'\n}\n\ntype SimpleStreamedQueryParams<\n TQueryFnData,\n TQueryKey extends QueryKey,\n> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {\n reducer?: never\n initialValue?: never\n}\n\ntype ReducibleStreamedQueryParams<\n TQueryFnData,\n TData,\n TQueryKey extends QueryKey,\n> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {\n /**\n * Reduces streamed chunks into the final data shape. Required whenever `TData` is not an\n * array, since there is no default way to accumulate non-array chunks.\n */\n reducer: (acc: TData, chunk: TQueryFnData) => TData\n /**\n * The value used while the first chunk is being fetched, and returned if the stream yields no\n * values. Required together with a custom `reducer`.\n */\n initialValue: TData\n}\n\ntype StreamedQueryParams<TQueryFnData, TData, TQueryKey extends QueryKey> =\n | SimpleStreamedQueryParams<TQueryFnData, TQueryKey>\n | ReducibleStreamedQueryParams<TQueryFnData, TData, TQueryKey>\n\n/**\n * This is a helper function to create a query function that streams data from an AsyncIterable.\n * Data will be an Array of all the chunks received.\n * The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.\n * The query will stay in fetchStatus 'fetching' until the stream ends.\n * Explicit cancellation stops further cache updates, even if `streamFn` does not read `signal`.\n * If `streamFn` does not read `signal`, the stream continues after the last observer unsubscribes.\n * @param options - The `streamFn` that returns an AsyncIterable to stream data from, and the optional\n * `refetchMode`, `reducer`, and `initialValue` options.\n * @returns A query function to pass as `queryFn`.\n * @example\n * ```ts\n * await queryClient.query({\n * queryKey: ['data'],\n * queryFn: streamedQuery({\n * streamFn: fetchDataInChunks,\n * }),\n * })\n * ```\n */\nexport function streamedQuery<\n TQueryFnData = unknown,\n TData = Array<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n>({\n streamFn,\n refetchMode = 'reset',\n reducer = (items, chunk) =>\n addToEnd(items as Array<TQueryFnData>, chunk) as TData,\n initialValue = [] as TData,\n}: StreamedQueryParams<TQueryFnData, TData, TQueryKey>): QueryFunction<\n TData,\n TQueryKey\n> {\n return async (context) => {\n const signalContext: FetchSignalContext = context\n const signal = signalContext[fetchSignal]\n if (signal?.aborted) {\n return initialValue\n }\n\n const query = context.client\n .getQueryCache()\n .find({ queryKey: context.queryKey, exact: true })\n const isRefetch = !!query && query.isFetched()\n if (isRefetch && refetchMode === 'reset') {\n query.setState({\n ...query.resetState,\n fetchStatus: 'fetching',\n })\n }\n\n let result = initialValue\n\n let cancelled = false as boolean\n const streamFnContext = addConsumeAwareSignal<\n OmitKeyof<typeof context, 'signal'>\n >(\n {\n client: context.client,\n meta: context.meta,\n queryKey: context.queryKey,\n pageParam: context.pageParam,\n direction: context.direction,\n },\n () => context.signal,\n () => (cancelled = true),\n signal,\n )\n\n const isStreamInactive = () => cancelled || signal?.aborted === true\n const stream = await streamFn(streamFnContext)\n\n const isReplaceRefetch = isRefetch && refetchMode === 'replace'\n\n for await (const chunk of stream) {\n if (isStreamInactive()) {\n break\n }\n\n if (isReplaceRefetch) {\n // don't append to the cache directly when replace-refetching\n result = reducer(result, chunk)\n } else {\n context.client.setQueryData<TData>(context.queryKey, (prev) =>\n reducer(prev === undefined ? initialValue : prev, chunk),\n )\n }\n }\n\n // finalize result: replace-refetching needs to write to the cache\n if (isReplaceRefetch && !isStreamInactive()) {\n context.client.setQueryData<TData>(context.queryKey, result)\n }\n\n const data = context.client.getQueryData<TData>(context.queryKey)\n return data === undefined ? initialValue : data\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwEA,SAAgB,cAId,EACA,UACA,cAAc,SACd,WAAW,OAAO,UAChBA,cAAAA,SAAS,OAA8B,KAAK,GAC9C,eAAe,CAAC,KAIhB;CACA,OAAO,OAAO,YAAY;EAExB,MAAM,SAASC,QAAcC,cAAAA;EAC7B,IAAA,WAAA,QAAA,WAAA,KAAA,IAAA,KAAA,IAAI,OAAQ,SACV,OAAO;EAGT,MAAM,QAAQ,QAAQ,OACnB,cAAc,CAAC,CACf,KAAK;GAAE,UAAU,QAAQ;GAAU,OAAO;EAAK,CAAC;EACnD,MAAM,YAAY,CAAC,CAAC,SAAS,MAAM,UAAU;EAC7C,IAAI,aAAa,gBAAgB,SAC/B,MAAM,SAAS;GACb,GAAG,MAAM;GACT,aAAa;EACf,CAAC;EAGH,IAAI,SAAS;EAEb,IAAI,YAAY;EAChB,MAAM,kBAAkBC,cAAAA,sBAGtB;GACE,QAAQ,QAAQ;GAChB,MAAM,QAAQ;GACd,UAAU,QAAQ;GAClB,WAAW,QAAQ;GACnB,WAAW,QAAQ;EACrB,SACM,QAAQ,cACP,YAAY,MACnB,MACF;EAEA,MAAM,yBAAyB,cAAA,WAAA,QAAA,WAAA,KAAA,IAAA,KAAA,IAAa,OAAQ,aAAY;EAChE,MAAM,SAAS,MAAM,SAAS,eAAe;EAE7C,MAAM,mBAAmB,aAAa,gBAAgB;EAEtD,WAAW,MAAM,SAAS,QAAQ;GAChC,IAAI,iBAAiB,GACnB;GAGF,IAAI,kBAEF,SAAS,QAAQ,QAAQ,KAAK;QAE9B,QAAQ,OAAO,aAAoB,QAAQ,WAAW,SACpD,QAAQ,SAAS,KAAA,IAAY,eAAe,MAAM,KAAK,CACzD;EAEJ;EAGA,IAAI,oBAAoB,CAAC,iBAAiB,GACxC,QAAQ,OAAO,aAAoB,QAAQ,UAAU,MAAM;EAG7D,MAAM,OAAO,QAAQ,OAAO,aAAoB,QAAQ,QAAQ;EAChE,OAAO,SAAS,KAAA,IAAY,eAAe;CAC7C;AACF"}
@@ -1,4 +1,4 @@
1
- import { Ct as QueryKey, St as QueryFunctionContext, xt as QueryFunction } from "./hydration-DdkP3REv.cjs";
1
+ import { Ct as QueryKey, St as QueryFunctionContext, xt as QueryFunction } from "./hydration-BXjqUj_D.cjs";
2
2
  type BaseStreamedQueryParams<TQueryFnData, TQueryKey extends QueryKey> = {
3
3
  /** The function that returns an `AsyncIterable` to stream data from. */
4
4
  streamFn: (context: QueryFunctionContext<TQueryKey>) => AsyncIterable<TQueryFnData> | Promise<AsyncIterable<TQueryFnData>>;
@@ -32,6 +32,8 @@ type StreamedQueryParams<TQueryFnData, TData, TQueryKey extends QueryKey> = Simp
32
32
  * Data will be an Array of all the chunks received.
33
33
  * The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.
34
34
  * The query will stay in fetchStatus 'fetching' until the stream ends.
35
+ * Explicit cancellation stops further cache updates, even if `streamFn` does not read `signal`.
36
+ * If `streamFn` does not read `signal`, the stream continues after the last observer unsubscribes.
35
37
  * @param options - The `streamFn` that returns an AsyncIterable to stream data from, and the optional
36
38
  * `refetchMode`, `reducer`, and `initialValue` options.
37
39
  * @returns A query function to pass as `queryFn`.
@@ -1 +1 @@
1
- {"version":3,"file":"streamedQuery.d.cts","names":[],"sources":["../../src/streamedQuery.ts"],"mappings":";KAQK,wBAAwB,cAAc,kBAAkB;;EAE3D,WACE,SAAS,qBAAqB,eAC3B,cAAc,gBAAgB,QAAQ,cAAc;;;;;;;EAOzD;;KAGG,0BACH,cACA,kBAAkB,YAChB,wBAAwB,cAAc;EACxC;EACA;;KAGG,6BACH,cACA,OACA,kBAAkB,YAChB,wBAAwB,cAAc;;;;;EAKxC,UAAU,KAAK,OAAO,OAAO,iBAAiB;;;;;EAK9C,cAAc;;KAGX,oBAAoB,cAAc,OAAO,kBAAkB,YAC5D,0BAA0B,cAAc,aACxC,6BAA6B,cAAc,OAAO;;;;;;;;;;;;;;;;;;;wBAoBtC,cACd,wBACA,QAAQ,MAAM,eACd,kBAAkB,WAAW,YAE7B,UACA,aACA,SAEA,gBACC,oBAAoB,cAAc,OAAO,aAAa,cACvD,OACA"}
1
+ {"version":3,"file":"streamedQuery.d.cts","names":[],"sources":["../../src/streamedQuery.ts"],"mappings":";KASK,wBAAwB,cAAc,kBAAkB;;EAE3D,WACE,SAAS,qBAAqB,eAC3B,cAAc,gBAAgB,QAAQ,cAAc;;;;;;;EAOzD;;KAGG,0BACH,cACA,kBAAkB,YAChB,wBAAwB,cAAc;EACxC;EACA;;KAGG,6BACH,cACA,OACA,kBAAkB,YAChB,wBAAwB,cAAc;;;;;EAKxC,UAAU,KAAK,OAAO,OAAO,iBAAiB;;;;;EAK9C,cAAc;;KAGX,oBAAoB,cAAc,OAAO,kBAAkB,YAC5D,0BAA0B,cAAc,aACxC,6BAA6B,cAAc,OAAO;;;;;;;;;;;;;;;;;;;;;wBAsBtC,cACd,wBACA,QAAQ,MAAM,eACd,kBAAkB,WAAW,YAE7B,UACA,aACA,SAEA,gBACC,oBAAoB,cAAc,OAAO,aAAa,cACvD,OACA"}
@@ -1,4 +1,4 @@
1
- import { Ct as QueryKey, St as QueryFunctionContext, xt as QueryFunction } from "./hydration-gHEs4kLM.js";
1
+ import { Ct as QueryKey, St as QueryFunctionContext, xt as QueryFunction } from "./hydration-vgIjIhk6.js";
2
2
  type BaseStreamedQueryParams<TQueryFnData, TQueryKey extends QueryKey> = {
3
3
  /** The function that returns an `AsyncIterable` to stream data from. */
4
4
  streamFn: (context: QueryFunctionContext<TQueryKey>) => AsyncIterable<TQueryFnData> | Promise<AsyncIterable<TQueryFnData>>;
@@ -32,6 +32,8 @@ type StreamedQueryParams<TQueryFnData, TData, TQueryKey extends QueryKey> = Simp
32
32
  * Data will be an Array of all the chunks received.
33
33
  * The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.
34
34
  * The query will stay in fetchStatus 'fetching' until the stream ends.
35
+ * Explicit cancellation stops further cache updates, even if `streamFn` does not read `signal`.
36
+ * If `streamFn` does not read `signal`, the stream continues after the last observer unsubscribes.
35
37
  * @param options - The `streamFn` that returns an AsyncIterable to stream data from, and the optional
36
38
  * `refetchMode`, `reducer`, and `initialValue` options.
37
39
  * @returns A query function to pass as `queryFn`.
@@ -1 +1 @@
1
- {"version":3,"file":"streamedQuery.d.ts","names":[],"sources":["../../src/streamedQuery.ts"],"mappings":";KAQK,wBAAwB,cAAc,kBAAkB;;EAE3D,WACE,SAAS,qBAAqB,eAC3B,cAAc,gBAAgB,QAAQ,cAAc;;;;;;;EAOzD;;KAGG,0BACH,cACA,kBAAkB,YAChB,wBAAwB,cAAc;EACxC;EACA;;KAGG,6BACH,cACA,OACA,kBAAkB,YAChB,wBAAwB,cAAc;;;;;EAKxC,UAAU,KAAK,OAAO,OAAO,iBAAiB;;;;;EAK9C,cAAc;;KAGX,oBAAoB,cAAc,OAAO,kBAAkB,YAC5D,0BAA0B,cAAc,aACxC,6BAA6B,cAAc,OAAO;;;;;;;;;;;;;;;;;;;wBAoBtC,cACd,wBACA,QAAQ,MAAM,eACd,kBAAkB,WAAW,YAE7B,UACA,aACA,SAEA,gBACC,oBAAoB,cAAc,OAAO,aAAa,cACvD,OACA"}
1
+ {"version":3,"file":"streamedQuery.d.ts","names":[],"sources":["../../src/streamedQuery.ts"],"mappings":";KASK,wBAAwB,cAAc,kBAAkB;;EAE3D,WACE,SAAS,qBAAqB,eAC3B,cAAc,gBAAgB,QAAQ,cAAc;;;;;;;EAOzD;;KAGG,0BACH,cACA,kBAAkB,YAChB,wBAAwB,cAAc;EACxC;EACA;;KAGG,6BACH,cACA,OACA,kBAAkB,YAChB,wBAAwB,cAAc;;;;;EAKxC,UAAU,KAAK,OAAO,OAAO,iBAAiB;;;;;EAK9C,cAAc;;KAGX,oBAAoB,cAAc,OAAO,kBAAkB,YAC5D,0BAA0B,cAAc,aACxC,6BAA6B,cAAc,OAAO;;;;;;;;;;;;;;;;;;;;;wBAsBtC,cACd,wBACA,QAAQ,MAAM,eACd,kBAAkB,WAAW,YAE7B,UACA,aACA,SAEA,gBACC,oBAAoB,cAAc,OAAO,aAAa,cACvD,OACA"}
@@ -1,10 +1,12 @@
1
- import { addConsumeAwareSignal, addToEnd } from "./utils.js";
1
+ import { addConsumeAwareSignal, addToEnd, fetchSignal } from "./utils.js";
2
2
  // src/streamedQuery.ts
3
3
  /**
4
4
  * This is a helper function to create a query function that streams data from an AsyncIterable.
5
5
  * Data will be an Array of all the chunks received.
6
6
  * The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.
7
7
  * The query will stay in fetchStatus 'fetching' until the stream ends.
8
+ * Explicit cancellation stops further cache updates, even if `streamFn` does not read `signal`.
9
+ * If `streamFn` does not read `signal`, the stream continues after the last observer unsubscribes.
8
10
  * @param options - The `streamFn` that returns an AsyncIterable to stream data from, and the optional
9
11
  * `refetchMode`, `reducer`, and `initialValue` options.
10
12
  * @returns A query function to pass as `queryFn`.
@@ -20,6 +22,8 @@ import { addConsumeAwareSignal, addToEnd } from "./utils.js";
20
22
  */
21
23
  function streamedQuery({ streamFn, refetchMode = "reset", reducer = (items, chunk) => addToEnd(items, chunk), initialValue = [] }) {
22
24
  return async (context) => {
25
+ const signal = context[fetchSignal];
26
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted) return initialValue;
23
27
  const query = context.client.getQueryCache().find({
24
28
  queryKey: context.queryKey,
25
29
  exact: true
@@ -31,20 +35,22 @@ function streamedQuery({ streamFn, refetchMode = "reset", reducer = (items, chun
31
35
  });
32
36
  let result = initialValue;
33
37
  let cancelled = false;
34
- const stream = await streamFn(addConsumeAwareSignal({
38
+ const streamFnContext = addConsumeAwareSignal({
35
39
  client: context.client,
36
40
  meta: context.meta,
37
41
  queryKey: context.queryKey,
38
42
  pageParam: context.pageParam,
39
43
  direction: context.direction
40
- }, () => context.signal, () => cancelled = true));
44
+ }, () => context.signal, () => cancelled = true, signal);
45
+ const isStreamInactive = () => cancelled || (signal === null || signal === void 0 ? void 0 : signal.aborted) === true;
46
+ const stream = await streamFn(streamFnContext);
41
47
  const isReplaceRefetch = isRefetch && refetchMode === "replace";
42
48
  for await (const chunk of stream) {
43
- if (cancelled) break;
49
+ if (isStreamInactive()) break;
44
50
  if (isReplaceRefetch) result = reducer(result, chunk);
45
51
  else context.client.setQueryData(context.queryKey, (prev) => reducer(prev === void 0 ? initialValue : prev, chunk));
46
52
  }
47
- if (isReplaceRefetch && !cancelled) context.client.setQueryData(context.queryKey, result);
53
+ if (isReplaceRefetch && !isStreamInactive()) context.client.setQueryData(context.queryKey, result);
48
54
  const data = context.client.getQueryData(context.queryKey);
49
55
  return data === void 0 ? initialValue : data;
50
56
  };
@@ -1 +1 @@
1
- {"version":3,"file":"streamedQuery.js","names":[],"sources":["../../src/streamedQuery.ts"],"sourcesContent":["import { addConsumeAwareSignal, addToEnd } from './utils'\nimport type {\n OmitKeyof,\n QueryFunction,\n QueryFunctionContext,\n QueryKey,\n} from './types'\n\ntype BaseStreamedQueryParams<TQueryFnData, TQueryKey extends QueryKey> = {\n /** The function that returns an `AsyncIterable` to stream data from. */\n streamFn: (\n context: QueryFunctionContext<TQueryKey>,\n ) => AsyncIterable<TQueryFnData> | Promise<AsyncIterable<TQueryFnData>>\n /**\n * Defines how refetches are handled.\n * - `'reset'` (default): erases all data and puts the query back into `pending` state.\n * - `'append'`: appends new data to the existing data.\n * - `'replace'`: writes all data to the cache once the stream ends.\n */\n refetchMode?: 'append' | 'reset' | 'replace'\n}\n\ntype SimpleStreamedQueryParams<\n TQueryFnData,\n TQueryKey extends QueryKey,\n> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {\n reducer?: never\n initialValue?: never\n}\n\ntype ReducibleStreamedQueryParams<\n TQueryFnData,\n TData,\n TQueryKey extends QueryKey,\n> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {\n /**\n * Reduces streamed chunks into the final data shape. Required whenever `TData` is not an\n * array, since there is no default way to accumulate non-array chunks.\n */\n reducer: (acc: TData, chunk: TQueryFnData) => TData\n /**\n * The value used while the first chunk is being fetched, and returned if the stream yields no\n * values. Required together with a custom `reducer`.\n */\n initialValue: TData\n}\n\ntype StreamedQueryParams<TQueryFnData, TData, TQueryKey extends QueryKey> =\n | SimpleStreamedQueryParams<TQueryFnData, TQueryKey>\n | ReducibleStreamedQueryParams<TQueryFnData, TData, TQueryKey>\n\n/**\n * This is a helper function to create a query function that streams data from an AsyncIterable.\n * Data will be an Array of all the chunks received.\n * The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.\n * The query will stay in fetchStatus 'fetching' until the stream ends.\n * @param options - The `streamFn` that returns an AsyncIterable to stream data from, and the optional\n * `refetchMode`, `reducer`, and `initialValue` options.\n * @returns A query function to pass as `queryFn`.\n * @example\n * ```ts\n * await queryClient.query({\n * queryKey: ['data'],\n * queryFn: streamedQuery({\n * streamFn: fetchDataInChunks,\n * }),\n * })\n * ```\n */\nexport function streamedQuery<\n TQueryFnData = unknown,\n TData = Array<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n>({\n streamFn,\n refetchMode = 'reset',\n reducer = (items, chunk) =>\n addToEnd(items as Array<TQueryFnData>, chunk) as TData,\n initialValue = [] as TData,\n}: StreamedQueryParams<TQueryFnData, TData, TQueryKey>): QueryFunction<\n TData,\n TQueryKey\n> {\n return async (context) => {\n const query = context.client\n .getQueryCache()\n .find({ queryKey: context.queryKey, exact: true })\n const isRefetch = !!query && query.isFetched()\n if (isRefetch && refetchMode === 'reset') {\n query.setState({\n ...query.resetState,\n fetchStatus: 'fetching',\n })\n }\n\n let result = initialValue\n\n let cancelled = false as boolean\n const streamFnContext = addConsumeAwareSignal<\n OmitKeyof<typeof context, 'signal'>\n >(\n {\n client: context.client,\n meta: context.meta,\n queryKey: context.queryKey,\n pageParam: context.pageParam,\n direction: context.direction,\n },\n () => context.signal,\n () => (cancelled = true),\n )\n\n const stream = await streamFn(streamFnContext)\n\n const isReplaceRefetch = isRefetch && refetchMode === 'replace'\n\n for await (const chunk of stream) {\n if (cancelled) {\n break\n }\n\n if (isReplaceRefetch) {\n // don't append to the cache directly when replace-refetching\n result = reducer(result, chunk)\n } else {\n context.client.setQueryData<TData>(context.queryKey, (prev) =>\n reducer(prev === undefined ? initialValue : prev, chunk),\n )\n }\n }\n\n // finalize result: replace-refetching needs to write to the cache\n if (isReplaceRefetch && !cancelled) {\n context.client.setQueryData<TData>(context.queryKey, result)\n }\n\n const data = context.client.getQueryData<TData>(context.queryKey)\n return data === undefined ? initialValue : data\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAqEA,SAAgB,cAId,EACA,UACA,cAAc,SACd,WAAW,OAAO,UAChB,SAAS,OAA8B,KAAK,GAC9C,eAAe,CAAC,KAIhB;CACA,OAAO,OAAO,YAAY;EACxB,MAAM,QAAQ,QAAQ,OACnB,cAAc,CAAC,CACf,KAAK;GAAE,UAAU,QAAQ;GAAU,OAAO;EAAK,CAAC;EACnD,MAAM,YAAY,CAAC,CAAC,SAAS,MAAM,UAAU;EAC7C,IAAI,aAAa,gBAAgB,SAC/B,MAAM,SAAS;GACb,GAAG,MAAM;GACT,aAAa;EACf,CAAC;EAGH,IAAI,SAAS;EAEb,IAAI,YAAY;EAehB,MAAM,SAAS,MAAM,SAdG,sBAGtB;GACE,QAAQ,QAAQ;GAChB,MAAM,QAAQ;GACd,UAAU,QAAQ;GAClB,WAAW,QAAQ;GACnB,WAAW,QAAQ;EACrB,SACM,QAAQ,cACP,YAAY,IAGuB,CAAC;EAE7C,MAAM,mBAAmB,aAAa,gBAAgB;EAEtD,WAAW,MAAM,SAAS,QAAQ;GAChC,IAAI,WACF;GAGF,IAAI,kBAEF,SAAS,QAAQ,QAAQ,KAAK;QAE9B,QAAQ,OAAO,aAAoB,QAAQ,WAAW,SACpD,QAAQ,SAAS,KAAA,IAAY,eAAe,MAAM,KAAK,CACzD;EAEJ;EAGA,IAAI,oBAAoB,CAAC,WACvB,QAAQ,OAAO,aAAoB,QAAQ,UAAU,MAAM;EAG7D,MAAM,OAAO,QAAQ,OAAO,aAAoB,QAAQ,QAAQ;EAChE,OAAO,SAAS,KAAA,IAAY,eAAe;CAC7C;AACF"}
1
+ {"version":3,"file":"streamedQuery.js","names":["signalContext"],"sources":["../../src/streamedQuery.ts"],"sourcesContent":["import { addConsumeAwareSignal, addToEnd, fetchSignal } from './utils'\nimport type { FetchSignalContext } from './utils'\nimport type {\n OmitKeyof,\n QueryFunction,\n QueryFunctionContext,\n QueryKey,\n} from './types'\n\ntype BaseStreamedQueryParams<TQueryFnData, TQueryKey extends QueryKey> = {\n /** The function that returns an `AsyncIterable` to stream data from. */\n streamFn: (\n context: QueryFunctionContext<TQueryKey>,\n ) => AsyncIterable<TQueryFnData> | Promise<AsyncIterable<TQueryFnData>>\n /**\n * Defines how refetches are handled.\n * - `'reset'` (default): erases all data and puts the query back into `pending` state.\n * - `'append'`: appends new data to the existing data.\n * - `'replace'`: writes all data to the cache once the stream ends.\n */\n refetchMode?: 'append' | 'reset' | 'replace'\n}\n\ntype SimpleStreamedQueryParams<\n TQueryFnData,\n TQueryKey extends QueryKey,\n> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {\n reducer?: never\n initialValue?: never\n}\n\ntype ReducibleStreamedQueryParams<\n TQueryFnData,\n TData,\n TQueryKey extends QueryKey,\n> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {\n /**\n * Reduces streamed chunks into the final data shape. Required whenever `TData` is not an\n * array, since there is no default way to accumulate non-array chunks.\n */\n reducer: (acc: TData, chunk: TQueryFnData) => TData\n /**\n * The value used while the first chunk is being fetched, and returned if the stream yields no\n * values. Required together with a custom `reducer`.\n */\n initialValue: TData\n}\n\ntype StreamedQueryParams<TQueryFnData, TData, TQueryKey extends QueryKey> =\n | SimpleStreamedQueryParams<TQueryFnData, TQueryKey>\n | ReducibleStreamedQueryParams<TQueryFnData, TData, TQueryKey>\n\n/**\n * This is a helper function to create a query function that streams data from an AsyncIterable.\n * Data will be an Array of all the chunks received.\n * The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.\n * The query will stay in fetchStatus 'fetching' until the stream ends.\n * Explicit cancellation stops further cache updates, even if `streamFn` does not read `signal`.\n * If `streamFn` does not read `signal`, the stream continues after the last observer unsubscribes.\n * @param options - The `streamFn` that returns an AsyncIterable to stream data from, and the optional\n * `refetchMode`, `reducer`, and `initialValue` options.\n * @returns A query function to pass as `queryFn`.\n * @example\n * ```ts\n * await queryClient.query({\n * queryKey: ['data'],\n * queryFn: streamedQuery({\n * streamFn: fetchDataInChunks,\n * }),\n * })\n * ```\n */\nexport function streamedQuery<\n TQueryFnData = unknown,\n TData = Array<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n>({\n streamFn,\n refetchMode = 'reset',\n reducer = (items, chunk) =>\n addToEnd(items as Array<TQueryFnData>, chunk) as TData,\n initialValue = [] as TData,\n}: StreamedQueryParams<TQueryFnData, TData, TQueryKey>): QueryFunction<\n TData,\n TQueryKey\n> {\n return async (context) => {\n const signalContext: FetchSignalContext = context\n const signal = signalContext[fetchSignal]\n if (signal?.aborted) {\n return initialValue\n }\n\n const query = context.client\n .getQueryCache()\n .find({ queryKey: context.queryKey, exact: true })\n const isRefetch = !!query && query.isFetched()\n if (isRefetch && refetchMode === 'reset') {\n query.setState({\n ...query.resetState,\n fetchStatus: 'fetching',\n })\n }\n\n let result = initialValue\n\n let cancelled = false as boolean\n const streamFnContext = addConsumeAwareSignal<\n OmitKeyof<typeof context, 'signal'>\n >(\n {\n client: context.client,\n meta: context.meta,\n queryKey: context.queryKey,\n pageParam: context.pageParam,\n direction: context.direction,\n },\n () => context.signal,\n () => (cancelled = true),\n signal,\n )\n\n const isStreamInactive = () => cancelled || signal?.aborted === true\n const stream = await streamFn(streamFnContext)\n\n const isReplaceRefetch = isRefetch && refetchMode === 'replace'\n\n for await (const chunk of stream) {\n if (isStreamInactive()) {\n break\n }\n\n if (isReplaceRefetch) {\n // don't append to the cache directly when replace-refetching\n result = reducer(result, chunk)\n } else {\n context.client.setQueryData<TData>(context.queryKey, (prev) =>\n reducer(prev === undefined ? initialValue : prev, chunk),\n )\n }\n }\n\n // finalize result: replace-refetching needs to write to the cache\n if (isReplaceRefetch && !isStreamInactive()) {\n context.client.setQueryData<TData>(context.queryKey, result)\n }\n\n const data = context.client.getQueryData<TData>(context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AO,SAAS,KAAA,IAAY,eAAe;CAC7C;AACF"}
@@ -1,2 +1,2 @@
1
- import { $ as MutationObserverBaseResult, A as InfiniteData, At as QueryObserverOptions, B as InfiniteQueryObserverSuccessResult, Bt as RefetchQueryFilters, C as FetchPreviousPageOptions, Ct as QueryKey, D as GetPreviousPageParamFunction, Dt as QueryObserverBaseResult, E as GetNextPageParamFunction, Et as QueryMeta, F as InfiniteQueryObserverOptions, Ft as QueryObserverSuccessResult, G as InvalidateQueryFilters, Gt as StaleTime, H as InitialDataFunction, Ht as ResetOptions, I as InfiniteQueryObserverPendingResult, It as QueryOptions, J as MutateOptions, Jt as UnsetMarker, K as MutateFunction, Kt as StaleTimeFunction, L as InfiniteQueryObserverPlaceholderResult, Lt as QueryPersister, M as InfiniteQueryObserverBaseResult, Mt as QueryObserverPlaceholderResult, N as InfiniteQueryObserverLoadingErrorResult, Nt as QueryObserverRefetchErrorResult, O as InferDataFromTag, Ot as QueryObserverLoadingErrorResult, P as InfiniteQueryObserverLoadingResult, Pt as QueryObserverResult, Q as MutationMeta, Qt as unsetMarker, R as InfiniteQueryObserverRefetchErrorResult, Rt as QueryStatus, S as FetchNextPageOptions, St as QueryFunctionContext, T as FetchStatus, Tt as QueryKeyWithDataTag, U as InitialPageParam, Ut as ResultOptions, V as InfiniteQueryPageParamsOptions, Vt as Register, W as InvalidateOptions, Wt as SetDataOptions, X as MutationFunctionContext, Xt as dataTagErrorSymbol, Y as MutationFunction, Yt as WithRequired, Z as MutationKey, Zt as dataTagSymbol, _ as DefinedQueryObserverResult, _t as QueriesPlaceholderDataFunction, at as MutationObserverSuccessResult, b as EnsureQueryDataOptions, bt as QueryExecuteOptions, ct as MutationStatus, d as DataTag, dt as NotifyEvent, et as MutationObserverErrorResult, f as DefaultError, ft as NotifyEventType, g as DefinedInfiniteQueryObserverResult, gt as PlaceholderDataFunction, h as DefaultedQueryObserverOptions, ht as Override, it as MutationObserverResult, j as InfiniteQueryExecuteOptions, jt as QueryObserverPendingResult, k as InferErrorFromTag, kt as QueryObserverLoadingResult, l as AnyDataTag, lt as NetworkMode, m as DefaultedInfiniteQueryObserverOptions, mt as OmitKeyof, nt as MutationObserverLoadingResult, ot as MutationOptions, p as DefaultOptions, pt as NotifyOnChangeProps, q as MutateFunctionRest, qt as ThrowOnError, rt as MutationObserverOptions, st as MutationScope, tt as MutationObserverIdleResult, u as CancelOptions, ut as NonUndefinedGuard, v as DistributiveOmit, vt as QueryBooleanOption, w as FetchQueryOptions, wt as QueryKeyHashFunction, x as FetchInfiniteQueryOptions, xt as QueryFunction, y as EnsureInfiniteQueryDataOptions, yt as QueryClientConfig, z as InfiniteQueryObserverResult, zt as RefetchOptions } from "./hydration-DdkP3REv.cjs";
1
+ import { $ as MutationObserverBaseResult, A as InfiniteData, At as QueryObserverOptions, B as InfiniteQueryObserverSuccessResult, Bt as RefetchQueryFilters, C as FetchPreviousPageOptions, Ct as QueryKey, D as GetPreviousPageParamFunction, Dt as QueryObserverBaseResult, E as GetNextPageParamFunction, Et as QueryMeta, F as InfiniteQueryObserverOptions, Ft as QueryObserverSuccessResult, G as InvalidateQueryFilters, Gt as StaleTime, H as InitialDataFunction, Ht as ResetOptions, I as InfiniteQueryObserverPendingResult, It as QueryOptions, J as MutateOptions, Jt as UnsetMarker, K as MutateFunction, Kt as StaleTimeFunction, L as InfiniteQueryObserverPlaceholderResult, Lt as QueryPersister, M as InfiniteQueryObserverBaseResult, Mt as QueryObserverPlaceholderResult, N as InfiniteQueryObserverLoadingErrorResult, Nt as QueryObserverRefetchErrorResult, O as InferDataFromTag, Ot as QueryObserverLoadingErrorResult, P as InfiniteQueryObserverLoadingResult, Pt as QueryObserverResult, Q as MutationMeta, Qt as unsetMarker, R as InfiniteQueryObserverRefetchErrorResult, Rt as QueryStatus, S as FetchNextPageOptions, St as QueryFunctionContext, T as FetchStatus, Tt as QueryKeyWithDataTag, U as InitialPageParam, Ut as ResultOptions, V as InfiniteQueryPageParamsOptions, Vt as Register, W as InvalidateOptions, Wt as SetDataOptions, X as MutationFunctionContext, Xt as dataTagErrorSymbol, Y as MutationFunction, Yt as WithRequired, Z as MutationKey, Zt as dataTagSymbol, _ as DefinedQueryObserverResult, _t as QueriesPlaceholderDataFunction, at as MutationObserverSuccessResult, b as EnsureQueryDataOptions, bt as QueryExecuteOptions, ct as MutationStatus, d as DataTag, dt as NotifyEvent, et as MutationObserverErrorResult, f as DefaultError, ft as NotifyEventType, g as DefinedInfiniteQueryObserverResult, gt as PlaceholderDataFunction, h as DefaultedQueryObserverOptions, ht as Override, it as MutationObserverResult, j as InfiniteQueryExecuteOptions, jt as QueryObserverPendingResult, k as InferErrorFromTag, kt as QueryObserverLoadingResult, l as AnyDataTag, lt as NetworkMode, m as DefaultedInfiniteQueryObserverOptions, mt as OmitKeyof, nt as MutationObserverLoadingResult, ot as MutationOptions, p as DefaultOptions, pt as NotifyOnChangeProps, q as MutateFunctionRest, qt as ThrowOnError, rt as MutationObserverOptions, st as MutationScope, tt as MutationObserverIdleResult, u as CancelOptions, ut as NonUndefinedGuard, v as DistributiveOmit, vt as QueryBooleanOption, w as FetchQueryOptions, wt as QueryKeyHashFunction, x as FetchInfiniteQueryOptions, xt as QueryFunction, y as EnsureInfiniteQueryDataOptions, yt as QueryClientConfig, z as InfiniteQueryObserverResult, zt as RefetchOptions } from "./hydration-BXjqUj_D.cjs";
2
2
  export { AnyDataTag, CancelOptions, DataTag, DefaultError, DefaultOptions, DefaultedInfiniteQueryObserverOptions, DefaultedQueryObserverOptions, DefinedInfiniteQueryObserverResult, DefinedQueryObserverResult, DistributiveOmit, EnsureInfiniteQueryDataOptions, EnsureQueryDataOptions, FetchInfiniteQueryOptions, FetchNextPageOptions, FetchPreviousPageOptions, FetchQueryOptions, FetchStatus, GetNextPageParamFunction, GetPreviousPageParamFunction, InferDataFromTag, InferErrorFromTag, InfiniteData, InfiniteQueryExecuteOptions, InfiniteQueryObserverBaseResult, InfiniteQueryObserverLoadingErrorResult, InfiniteQueryObserverLoadingResult, InfiniteQueryObserverOptions, InfiniteQueryObserverPendingResult, InfiniteQueryObserverPlaceholderResult, InfiniteQueryObserverRefetchErrorResult, InfiniteQueryObserverResult, InfiniteQueryObserverSuccessResult, InfiniteQueryPageParamsOptions, InitialDataFunction, InitialPageParam, InvalidateOptions, InvalidateQueryFilters, MutateFunction, MutateFunctionRest, MutateOptions, MutationFunction, MutationFunctionContext, MutationKey, MutationMeta, MutationObserverBaseResult, MutationObserverErrorResult, MutationObserverIdleResult, MutationObserverLoadingResult, MutationObserverOptions, MutationObserverResult, MutationObserverSuccessResult, MutationOptions, MutationScope, MutationStatus, NetworkMode, NonUndefinedGuard, NotifyEvent, NotifyEventType, NotifyOnChangeProps, OmitKeyof, Override, PlaceholderDataFunction, QueriesPlaceholderDataFunction, QueryBooleanOption, QueryClientConfig, QueryExecuteOptions, QueryFunction, QueryFunctionContext, QueryKey, QueryKeyHashFunction, QueryKeyWithDataTag, QueryMeta, QueryObserverBaseResult, QueryObserverLoadingErrorResult, QueryObserverLoadingResult, QueryObserverOptions, QueryObserverPendingResult, QueryObserverPlaceholderResult, QueryObserverRefetchErrorResult, QueryObserverResult, QueryObserverSuccessResult, QueryOptions, QueryPersister, QueryStatus, RefetchOptions, RefetchQueryFilters, Register, ResetOptions, ResultOptions, SetDataOptions, StaleTime, StaleTimeFunction, ThrowOnError, UnsetMarker, WithRequired, dataTagErrorSymbol, dataTagSymbol, unsetMarker };
@@ -1,2 +1,2 @@
1
- import { $ as MutationObserverBaseResult, A as InfiniteData, At as QueryObserverOptions, B as InfiniteQueryObserverSuccessResult, Bt as RefetchQueryFilters, C as FetchPreviousPageOptions, Ct as QueryKey, D as GetPreviousPageParamFunction, Dt as QueryObserverBaseResult, E as GetNextPageParamFunction, Et as QueryMeta, F as InfiniteQueryObserverOptions, Ft as QueryObserverSuccessResult, G as InvalidateQueryFilters, Gt as StaleTime, H as InitialDataFunction, Ht as ResetOptions, I as InfiniteQueryObserverPendingResult, It as QueryOptions, J as MutateOptions, Jt as UnsetMarker, K as MutateFunction, Kt as StaleTimeFunction, L as InfiniteQueryObserverPlaceholderResult, Lt as QueryPersister, M as InfiniteQueryObserverBaseResult, Mt as QueryObserverPlaceholderResult, N as InfiniteQueryObserverLoadingErrorResult, Nt as QueryObserverRefetchErrorResult, O as InferDataFromTag, Ot as QueryObserverLoadingErrorResult, P as InfiniteQueryObserverLoadingResult, Pt as QueryObserverResult, Q as MutationMeta, Qt as unsetMarker, R as InfiniteQueryObserverRefetchErrorResult, Rt as QueryStatus, S as FetchNextPageOptions, St as QueryFunctionContext, T as FetchStatus, Tt as QueryKeyWithDataTag, U as InitialPageParam, Ut as ResultOptions, V as InfiniteQueryPageParamsOptions, Vt as Register, W as InvalidateOptions, Wt as SetDataOptions, X as MutationFunctionContext, Xt as dataTagErrorSymbol, Y as MutationFunction, Yt as WithRequired, Z as MutationKey, Zt as dataTagSymbol, _ as DefinedQueryObserverResult, _t as QueriesPlaceholderDataFunction, at as MutationObserverSuccessResult, b as EnsureQueryDataOptions, bt as QueryExecuteOptions, ct as MutationStatus, d as DataTag, dt as NotifyEvent, et as MutationObserverErrorResult, f as DefaultError, ft as NotifyEventType, g as DefinedInfiniteQueryObserverResult, gt as PlaceholderDataFunction, h as DefaultedQueryObserverOptions, ht as Override, it as MutationObserverResult, j as InfiniteQueryExecuteOptions, jt as QueryObserverPendingResult, k as InferErrorFromTag, kt as QueryObserverLoadingResult, l as AnyDataTag, lt as NetworkMode, m as DefaultedInfiniteQueryObserverOptions, mt as OmitKeyof, nt as MutationObserverLoadingResult, ot as MutationOptions, p as DefaultOptions, pt as NotifyOnChangeProps, q as MutateFunctionRest, qt as ThrowOnError, rt as MutationObserverOptions, st as MutationScope, tt as MutationObserverIdleResult, u as CancelOptions, ut as NonUndefinedGuard, v as DistributiveOmit, vt as QueryBooleanOption, w as FetchQueryOptions, wt as QueryKeyHashFunction, x as FetchInfiniteQueryOptions, xt as QueryFunction, y as EnsureInfiniteQueryDataOptions, yt as QueryClientConfig, z as InfiniteQueryObserverResult, zt as RefetchOptions } from "./hydration-gHEs4kLM.js";
1
+ import { $ as MutationObserverBaseResult, A as InfiniteData, At as QueryObserverOptions, B as InfiniteQueryObserverSuccessResult, Bt as RefetchQueryFilters, C as FetchPreviousPageOptions, Ct as QueryKey, D as GetPreviousPageParamFunction, Dt as QueryObserverBaseResult, E as GetNextPageParamFunction, Et as QueryMeta, F as InfiniteQueryObserverOptions, Ft as QueryObserverSuccessResult, G as InvalidateQueryFilters, Gt as StaleTime, H as InitialDataFunction, Ht as ResetOptions, I as InfiniteQueryObserverPendingResult, It as QueryOptions, J as MutateOptions, Jt as UnsetMarker, K as MutateFunction, Kt as StaleTimeFunction, L as InfiniteQueryObserverPlaceholderResult, Lt as QueryPersister, M as InfiniteQueryObserverBaseResult, Mt as QueryObserverPlaceholderResult, N as InfiniteQueryObserverLoadingErrorResult, Nt as QueryObserverRefetchErrorResult, O as InferDataFromTag, Ot as QueryObserverLoadingErrorResult, P as InfiniteQueryObserverLoadingResult, Pt as QueryObserverResult, Q as MutationMeta, Qt as unsetMarker, R as InfiniteQueryObserverRefetchErrorResult, Rt as QueryStatus, S as FetchNextPageOptions, St as QueryFunctionContext, T as FetchStatus, Tt as QueryKeyWithDataTag, U as InitialPageParam, Ut as ResultOptions, V as InfiniteQueryPageParamsOptions, Vt as Register, W as InvalidateOptions, Wt as SetDataOptions, X as MutationFunctionContext, Xt as dataTagErrorSymbol, Y as MutationFunction, Yt as WithRequired, Z as MutationKey, Zt as dataTagSymbol, _ as DefinedQueryObserverResult, _t as QueriesPlaceholderDataFunction, at as MutationObserverSuccessResult, b as EnsureQueryDataOptions, bt as QueryExecuteOptions, ct as MutationStatus, d as DataTag, dt as NotifyEvent, et as MutationObserverErrorResult, f as DefaultError, ft as NotifyEventType, g as DefinedInfiniteQueryObserverResult, gt as PlaceholderDataFunction, h as DefaultedQueryObserverOptions, ht as Override, it as MutationObserverResult, j as InfiniteQueryExecuteOptions, jt as QueryObserverPendingResult, k as InferErrorFromTag, kt as QueryObserverLoadingResult, l as AnyDataTag, lt as NetworkMode, m as DefaultedInfiniteQueryObserverOptions, mt as OmitKeyof, nt as MutationObserverLoadingResult, ot as MutationOptions, p as DefaultOptions, pt as NotifyOnChangeProps, q as MutateFunctionRest, qt as ThrowOnError, rt as MutationObserverOptions, st as MutationScope, tt as MutationObserverIdleResult, u as CancelOptions, ut as NonUndefinedGuard, v as DistributiveOmit, vt as QueryBooleanOption, w as FetchQueryOptions, wt as QueryKeyHashFunction, x as FetchInfiniteQueryOptions, xt as QueryFunction, y as EnsureInfiniteQueryDataOptions, yt as QueryClientConfig, z as InfiniteQueryObserverResult, zt as RefetchOptions } from "./hydration-vgIjIhk6.js";
2
2
  export { AnyDataTag, CancelOptions, DataTag, DefaultError, DefaultOptions, DefaultedInfiniteQueryObserverOptions, DefaultedQueryObserverOptions, DefinedInfiniteQueryObserverResult, DefinedQueryObserverResult, DistributiveOmit, EnsureInfiniteQueryDataOptions, EnsureQueryDataOptions, FetchInfiniteQueryOptions, FetchNextPageOptions, FetchPreviousPageOptions, FetchQueryOptions, FetchStatus, GetNextPageParamFunction, GetPreviousPageParamFunction, InferDataFromTag, InferErrorFromTag, InfiniteData, InfiniteQueryExecuteOptions, InfiniteQueryObserverBaseResult, InfiniteQueryObserverLoadingErrorResult, InfiniteQueryObserverLoadingResult, InfiniteQueryObserverOptions, InfiniteQueryObserverPendingResult, InfiniteQueryObserverPlaceholderResult, InfiniteQueryObserverRefetchErrorResult, InfiniteQueryObserverResult, InfiniteQueryObserverSuccessResult, InfiniteQueryPageParamsOptions, InitialDataFunction, InitialPageParam, InvalidateOptions, InvalidateQueryFilters, MutateFunction, MutateFunctionRest, MutateOptions, MutationFunction, MutationFunctionContext, MutationKey, MutationMeta, MutationObserverBaseResult, MutationObserverErrorResult, MutationObserverIdleResult, MutationObserverLoadingResult, MutationObserverOptions, MutationObserverResult, MutationObserverSuccessResult, MutationOptions, MutationScope, MutationStatus, NetworkMode, NonUndefinedGuard, NotifyEvent, NotifyEventType, NotifyOnChangeProps, OmitKeyof, Override, PlaceholderDataFunction, QueriesPlaceholderDataFunction, QueryBooleanOption, QueryClientConfig, QueryExecuteOptions, QueryFunction, QueryFunctionContext, QueryKey, QueryKeyHashFunction, QueryKeyWithDataTag, QueryMeta, QueryObserverBaseResult, QueryObserverLoadingErrorResult, QueryObserverLoadingResult, QueryObserverOptions, QueryObserverPendingResult, QueryObserverPlaceholderResult, QueryObserverRefetchErrorResult, QueryObserverResult, QueryObserverSuccessResult, QueryOptions, QueryPersister, QueryStatus, RefetchOptions, RefetchQueryFilters, Register, ResetOptions, ResultOptions, SetDataOptions, StaleTime, StaleTimeFunction, ThrowOnError, UnsetMarker, WithRequired, dataTagErrorSymbol, dataTagSymbol, unsetMarker };
@@ -183,7 +183,7 @@ function replaceEqualDeep(a, b, depth = 0) {
183
183
  */
184
184
  function shallowEqualObjects(a, b) {
185
185
  if (!b || Object.keys(a).length !== Object.keys(b).length) return false;
186
- for (const key in a) if (a[key] !== b[key]) return false;
186
+ for (const key of Object.keys(a)) if (!hasOwn.call(b, key) || a[key] !== b[key]) return false;
187
187
  return true;
188
188
  }
189
189
  /**
@@ -273,29 +273,27 @@ function keepPreviousData(previousData) {
273
273
  }
274
274
  /**
275
275
  * Returns a new array with `item` added at the end. If that makes the array longer than `max`,
276
- * the first item is dropped. Only one item is dropped, so the result can still exceed `max` if
277
- * `items` already did.
276
+ * excess items are removed from the start.
278
277
  * @param items - The current items.
279
278
  * @param item - The value to append.
280
- * @param max - The length above which an item is dropped. `0` (the default) means no limit.
279
+ * @param max - The maximum number of items to keep. `0` (the default) means no limit.
281
280
  * @returns A new array with `item` added.
282
281
  */
283
282
  function addToEnd(items, item, max = 0) {
284
283
  const newItems = [...items, item];
285
- return max && newItems.length > max ? newItems.slice(1) : newItems;
284
+ return max && newItems.length > max ? newItems.slice(-max) : newItems;
286
285
  }
287
286
  /**
288
287
  * Returns a new array with `item` added at the start. If that makes the array longer than `max`,
289
- * the last item is dropped. Only one item is dropped, so the result can still exceed `max` if
290
- * `items` already did.
288
+ * excess items are removed from the end.
291
289
  * @param items - The current items.
292
290
  * @param item - The value to prepend.
293
- * @param max - The length above which an item is dropped. `0` (the default) means no limit.
291
+ * @param max - The maximum number of items to keep. `0` (the default) means no limit.
294
292
  * @returns A new array with `item` added.
295
293
  */
296
294
  function addToStart(items, item, max = 0) {
297
295
  const newItems = [item, ...items];
298
- return max && newItems.length > max ? newItems.slice(0, -1) : newItems;
296
+ return max && newItems.length > max ? newItems.slice(0, max) : newItems;
299
297
  }
300
298
  /**
301
299
  * Sentinel value that can be passed as a query's `queryFn` to conditionally disable the query (equivalent
@@ -348,6 +346,7 @@ function shouldThrowError(throwOnError, params) {
348
346
  if (typeof throwOnError === "function") return throwOnError(...params);
349
347
  return !!throwOnError;
350
348
  }
349
+ const fetchSignal = Symbol();
351
350
  /**
352
351
  * Adds a lazy `signal` getter to an object, such as a query function context. The first time
353
352
  * `signal` is read, `onCancelled` is registered for the signal's `abort` event (or called right
@@ -355,20 +354,24 @@ function shouldThrowError(throwOnError, params) {
355
354
  * @param object - The object to add the `signal` property to.
356
355
  * @param getSignal - Returns the `AbortSignal`. Called once, when `signal` is first read.
357
356
  * @param onCancelled - Called when the signal is aborted, if `signal` was read.
357
+ * @param internalSignal - The fetch signal to forward without consuming the getter.
358
358
  * @returns The same object, with the `signal` property added.
359
359
  */
360
- function addConsumeAwareSignal(object, getSignal, onCancelled) {
360
+ function addConsumeAwareSignal(object, getSignal, onCancelled, internalSignal) {
361
361
  let consumed = false;
362
362
  let signal;
363
- Object.defineProperty(object, "signal", {
364
- enumerable: true,
365
- get: () => {
366
- signal ?? (signal = getSignal());
367
- if (consumed) return signal;
368
- consumed = true;
369
- if (signal.aborted) onCancelled();
370
- else signal.addEventListener("abort", onCancelled, { once: true });
371
- return signal;
363
+ Object.defineProperties(object, {
364
+ [fetchSignal]: { value: internalSignal },
365
+ signal: {
366
+ enumerable: true,
367
+ get: () => {
368
+ signal ?? (signal = getSignal());
369
+ if (consumed) return signal;
370
+ consumed = true;
371
+ if (signal.aborted) onCancelled();
372
+ else signal.addEventListener("abort", onCancelled, { once: true });
373
+ return signal;
374
+ }
372
375
  }
373
376
  });
374
377
  return object;
@@ -377,6 +380,7 @@ exports.addConsumeAwareSignal = addConsumeAwareSignal;
377
380
  exports.addToEnd = addToEnd;
378
381
  exports.addToStart = addToStart;
379
382
  exports.ensureQueryFn = ensureQueryFn;
383
+ exports.fetchSignal = fetchSignal;
380
384
  exports.functionalUpdate = functionalUpdate;
381
385
  exports.hashKey = hashKey;
382
386
  exports.hashQueryKeyByOptions = hashQueryKeyByOptions;
@@ -1 +1 @@
1
- {"version":3,"file":"utils.cjs","names":[],"sources":["../../src/utils.ts"],"sourcesContent":["import { timeoutManager } from './timeoutManager'\nimport type {\n DefaultError,\n FetchStatus,\n MutationKey,\n MutationStatus,\n QueryFunction,\n QueryKey,\n QueryOptions,\n} from './types'\nimport type { Mutation } from './mutation'\nimport type { FetchOptions, Query } from './query'\n\n// TYPES\n\ntype DropLast<T extends ReadonlyArray<unknown>> = T extends readonly [\n ...infer R,\n unknown,\n]\n ? readonly [...R]\n : never\n\ntype TuplePrefixes<T extends ReadonlyArray<unknown>> = T extends readonly []\n ? readonly []\n : TuplePrefixes<DropLast<T>> | T\n\n/**\n * Filters used to select queries, for example in `queryClient.getQueriesData` or `queryClient.invalidateQueries`.\n * All provided filters must match; filters that are left unspecified are ignored.\n */\nexport interface QueryFilters<TQueryKey extends QueryKey = QueryKey> {\n /**\n * Filter to active queries, inactive queries or all queries\n * @defaultValue 'all'\n */\n type?: QueryTypeFilter\n /**\n * Match query key exactly\n */\n exact?: boolean\n /**\n * Include queries matching this predicate function\n */\n predicate?: (query: Query) => boolean\n /**\n * Include queries matching this query key\n */\n queryKey?: TQueryKey | TuplePrefixes<TQueryKey>\n /**\n * Include or exclude stale queries\n */\n stale?: boolean\n /**\n * Include queries matching their fetchStatus\n */\n fetchStatus?: FetchStatus\n}\n\n/**\n * Filters used to select mutations, for example in `mutationCache.findAll` or `queryClient.isMutating`.\n * All provided filters must match; filters that are left unspecified are ignored.\n */\nexport interface MutationFilters<\n TData = unknown,\n TError = DefaultError,\n TVariables = unknown,\n TOnMutateResult = unknown,\n> {\n /**\n * Match mutation key exactly\n */\n exact?: boolean\n /**\n * Include mutations matching this predicate function\n */\n predicate?: (\n mutation: Mutation<TData, TError, TVariables, TOnMutateResult>,\n ) => boolean\n /**\n * Include mutations matching this mutation key\n */\n mutationKey?: TuplePrefixes<MutationKey>\n /**\n * Filter by mutation status\n */\n status?: MutationStatus\n}\n\n/**\n * Either a plain value of type `TOutput`, or a function that receives `TInput` and returns `TOutput`.\n * Used for example by `setQueryData`-style updaters, which accept either the new data directly or a\n * function that computes it from the previous data. See {@link functionalUpdate}.\n * @example\n * ```ts\n * queryClient.setQueryData(['posts'], newPosts)\n *\n * // Or, using an updater function that receives the current data:\n * queryClient.setQueryData(['posts'], (oldPosts) =>\n * oldPosts ? [...oldPosts, newPost] : oldPosts,\n * )\n * ```\n */\nexport type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput)\n\n/**\n * Which queries a filter matches: all of them, only active ones (with enabled observers), or only\n * inactive ones.\n */\nexport type QueryTypeFilter = 'all' | 'active' | 'inactive'\n\n// UTILS\n\n/**\n * @deprecated use `environmentManager.isServer()` instead.\n */\nexport const isServer = typeof window === 'undefined' || 'Deno' in globalThis\n\n/**\n * A function that does nothing.\n */\nexport function noop(): void\nexport function noop(): undefined\nexport function noop() {}\n\n/**\n * Resolves an {@link Updater}: calls it with `input` if it is a function, otherwise returns it as\n * is.\n * @param updater - The new value, or a function that receives `input` and returns the new value.\n * @param input - The current value, passed to `updater` if it is a function.\n * @returns The new value.\n */\nexport function functionalUpdate<TInput, TOutput>(\n updater: Updater<TInput, TOutput>,\n input: TInput,\n): TOutput {\n return typeof updater === 'function'\n ? (updater as (_: TInput) => TOutput)(input)\n : updater\n}\n\n/**\n * Checks whether a value can be used as a timeout: a non-negative, finite number.\n * @param value - The value to check.\n * @returns `true` if `value` is a number that is `>= 0` and not `Infinity`.\n */\nexport function isValidTimeout(value: unknown): value is number {\n return typeof value === 'number' && value >= 0 && value !== Infinity\n}\n\n/**\n * Calculates how long until data updated at `updatedAt` becomes stale.\n * @param updatedAt - The timestamp, in milliseconds, at which the data was last updated.\n * @param staleTime - The time, in milliseconds, after which data is considered stale. Defaults to\n * `0`.\n * @returns The remaining time in milliseconds, or `0` if the data is already stale.\n */\nexport function timeUntilStale(updatedAt: number, staleTime?: number): number {\n return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)\n}\n\n/**\n * Resolves an option that can be given either as a value or as a function of the query, such as\n * `staleTime`.\n * @param value - The option value, or a function that receives `query` and returns the value.\n * @param query - The query passed to `value` if it is a function.\n * @returns The resolved value, or `undefined` if `value` is `undefined`.\n */\nexport function resolveQueryValue<\n TValue,\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n value:\n | undefined\n | TValue\n | ((query: Query<TQueryFnData, TError, TData, TQueryKey>) => TValue),\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n): TValue | undefined {\n return typeof value === 'function'\n ? (\n value as (\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n ) => TValue\n )(query)\n : value\n}\n\n/**\n * Checks whether a query matches the given {@link QueryFilters}.\n * Every filter that is specified must match; filters that are left unspecified are ignored.\n * @param filters - The filters to check the query against.\n * @param query - The query to check.\n * @returns `true` if the query matches every specified filter.\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n *\n * const matchingQueries = queryCache\n * .getAll()\n * .filter((query) => matchQuery({ queryKey: ['posts'] }, query))\n * ```\n */\nexport function matchQuery(\n filters: QueryFilters,\n query: Query<any, any, any, any>,\n): boolean {\n const {\n type = 'all',\n exact,\n fetchStatus,\n predicate,\n queryKey,\n stale,\n } = filters\n\n if (queryKey) {\n if (exact) {\n if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {\n return false\n }\n } else if (!partialMatchKey(query.queryKey, queryKey)) {\n return false\n }\n }\n\n if (type !== 'all') {\n const isActive = query.isActive()\n if (type === 'active' && !isActive) {\n return false\n }\n if (type === 'inactive' && isActive) {\n return false\n }\n }\n\n if (typeof stale === 'boolean' && query.isStale() !== stale) {\n return false\n }\n\n if (fetchStatus && fetchStatus !== query.state.fetchStatus) {\n return false\n }\n\n if (predicate && !predicate(query)) {\n return false\n }\n\n return true\n}\n\n/**\n * Checks whether a mutation matches the given {@link MutationFilters}.\n * Every filter that is specified must match; filters that are left unspecified are ignored.\n * If a `mutationKey` filter is provided but the mutation has no `mutationKey` of its own, it does not match.\n * @param filters - The filters to check the mutation against.\n * @param mutation - The mutation to check.\n * @returns `true` if the mutation matches every specified filter.\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * const matchingMutations = mutationCache\n * .getAll()\n * .filter((mutation) => matchMutation({ mutationKey: ['addPost'] }, mutation))\n * ```\n */\nexport function matchMutation(\n filters: MutationFilters,\n mutation: Mutation<any, any>,\n): boolean {\n const { exact, status, predicate, mutationKey } = filters\n if (mutationKey) {\n if (!mutation.options.mutationKey) {\n return false\n }\n if (exact) {\n if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {\n return false\n }\n } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {\n return false\n }\n }\n\n if (status && mutation.state.status !== status) {\n return false\n }\n\n if (predicate && !predicate(mutation)) {\n return false\n }\n\n return true\n}\n\n/**\n * Hashes a query key with the query's `queryKeyHashFn` option, falling back to {@link hashKey}.\n * @param queryKey - The query key to hash.\n * @param options - The query options that may provide a custom `queryKeyHashFn`.\n * @returns The query hash, a string that identifies the query in the cache.\n */\nexport function hashQueryKeyByOptions<TQueryKey extends QueryKey = QueryKey>(\n queryKey: TQueryKey,\n options?: Pick<QueryOptions<any, any, any, any>, 'queryKeyHashFn'>,\n): string {\n const hashFn = options?.queryKeyHashFn || hashKey\n return hashFn(queryKey)\n}\n\n/**\n * Default query & mutation keys hash function.\n * Hashes the value into a stable hash.\n * @param queryKey - The query or mutation key to hash.\n * @returns The stable hash of the key, as a JSON string.\n * @example\n * ```ts\n * // Object keys are sorted, so key order doesn't affect the hash:\n * hashKey(['todos', { page: 1, filter: 'done' }]) // === '[\"todos\",{\"filter\":\"done\",\"page\":1}]'\n * ```\n */\nexport function hashKey(queryKey: QueryKey | MutationKey): string {\n return JSON.stringify(queryKey, (_, val) =>\n isPlainObject(val)\n ? Object.keys(val)\n .sort()\n .reduce((result, key) => {\n result[key] = val[key]\n return result\n }, {} as any)\n : val,\n )\n}\n\n/**\n * Checks if key `b` partially matches with key `a`.\n * @param a - The key to check, e.g. a query's own key.\n * @param b - The (partial) key to match against `a`.\n * @returns `true` if every array element or object property in `b` matches the one at the same\n * position in `a`.\n */\nexport function partialMatchKey(a: QueryKey, b: QueryKey): boolean\nexport function partialMatchKey(a: any, b: any): boolean {\n if (a === b) {\n return true\n }\n\n if (typeof a !== typeof b) {\n return false\n }\n\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n if (Array.isArray(a) && Array.isArray(b)) {\n if (b.length > a.length) return false\n for (let i = 0; i < b.length; i++) {\n if (!partialMatchKey(a[i], b[i])) {\n return false\n }\n }\n return true\n }\n\n const bKeys = Object.keys(b)\n for (const key of bKeys) {\n if (!partialMatchKey(a[key], b[key])) {\n return false\n }\n }\n return true\n }\n\n return false\n}\n\nconst hasOwn = Object.prototype.hasOwnProperty\n\n/**\n * This function returns `a` if `b` is deeply equal.\n * If not, it will replace any deeply equal children of `b` with those of `a`.\n * This can be used for structural sharing between JSON values for example.\n * @param a - The previous value, whose deeply equal parts are reused.\n * @param b - The new value.\n * @param depth - The current recursion depth. Past a depth of `500`, `b` is returned as is.\n * @returns `a` if `b` is deeply equal to it, otherwise `b` with its deeply equal parts replaced by\n * those of `a`.\n */\nexport function replaceEqualDeep<T>(a: unknown, b: T, depth?: number): T\nexport function replaceEqualDeep(a: any, b: any, depth = 0): any {\n if (a === b) {\n return a\n }\n\n if (depth > 500) return b\n\n const array = isPlainArray(a) && isPlainArray(b)\n\n if (!array && !(isPlainObject(a) && isPlainObject(b))) return b\n\n const aItems = array ? a : Object.keys(a)\n const aSize = aItems.length\n const bItems = array ? b : Object.keys(b)\n const bSize = bItems.length\n const copy: any = array ? new Array(bSize) : {}\n\n let equalItems = 0\n\n for (let i = 0; i < bSize; i++) {\n const key: any = array ? i : bItems[i]\n const aItem = a[key]\n const bItem = b[key]\n\n if (aItem === bItem) {\n copy[key] = aItem\n if (array ? i < aSize : hasOwn.call(a, key)) equalItems++\n continue\n }\n\n if (\n aItem === null ||\n bItem === null ||\n typeof aItem !== 'object' ||\n typeof bItem !== 'object'\n ) {\n copy[key] = bItem\n continue\n }\n\n const v = replaceEqualDeep(aItem, bItem, depth + 1)\n copy[key] = v\n if (v === aItem) equalItems++\n }\n\n return aSize === bSize && equalItems === aSize ? a : copy\n}\n\n/**\n * Shallow compare objects.\n * @param a - The first object.\n * @param b - The second object, or `undefined`.\n * @returns `true` if both objects have the same keys, with strictly equal values for each key.\n */\nexport function shallowEqualObjects<T extends Record<string, any>>(\n a: T,\n b: T | undefined,\n): boolean {\n if (!b || Object.keys(a).length !== Object.keys(b).length) {\n return false\n }\n\n for (const key in a) {\n if (a[key] !== b[key]) {\n return false\n }\n }\n\n return true\n}\n\n/**\n * Checks whether a value is an array with no holes and no extra properties.\n * @param value - The value to check.\n * @returns `true` if `value` is an array whose number of own keys equals its `length`.\n */\nexport function isPlainArray(value: unknown): value is Array<unknown> {\n return Array.isArray(value) && value.length === Object.keys(value).length\n}\n\n// Copied from: https://github.com/jonschlinkert/is-plain-object\n/**\n * Checks whether a value is a plain object, e.g. created with an object literal or\n * `Object.create(null)`.\n * @param o - The value to check.\n * @returns `true` if `o` is a plain object.\n */\nexport function isPlainObject(o: any): o is Record<PropertyKey, unknown> {\n if (!hasObjectPrototype(o)) {\n return false\n }\n\n // If has no constructor\n const objectPrototype = Object.getPrototypeOf(o)\n const ctor = objectPrototype?.constructor\n if (ctor === undefined) {\n return true\n }\n\n if (typeof ctor !== 'function') {\n return false\n }\n\n // If has modified prototype\n const prot = ctor.prototype\n if (!hasObjectPrototype(prot)) {\n return false\n }\n\n // If constructor does not have an Object-specific method\n if (!prot.hasOwnProperty('isPrototypeOf')) {\n return false\n }\n\n // Handles Objects created by Object.create(<arbitrary prototype>)\n if (objectPrototype !== Object.prototype) {\n return false\n }\n\n // Most likely a plain Object\n return true\n}\n\n/**\n * Checks whether a value's `Object.prototype.toString` tag is `[object Object]`.\n * @param o - The value to check.\n * @returns `true` if the tag is `[object Object]`.\n */\nfunction hasObjectPrototype(o: any): boolean {\n return Object.prototype.toString.call(o) === '[object Object]'\n}\n\n/**\n * Waits for the given time, using the configured {@link timeoutManager}.\n * @param timeout - The time to wait, in milliseconds.\n * @returns A promise that resolves after `timeout` milliseconds.\n */\nexport function sleep(timeout: number): Promise<void> {\n return new Promise((resolve) => {\n timeoutManager.setTimeout(resolve, timeout)\n })\n}\n\n/**\n * Applies a query's `structuralSharing` option when writing new data.\n * @param prevData - The previously cached data.\n * @param data - The new data.\n * @param options - The query options, whose `structuralSharing` decides how the data is merged.\n * @returns The result of a custom `structuralSharing` function, `data` with its unchanged parts\n * replaced by those of `prevData` by default, or `data` as is if `structuralSharing` is `false`.\n * @throws {Error} The error from the default structural sharing, e.g. when the data is not JSON serializable.\n * Outside production, it is also logged to the console.\n */\nexport function replaceData<\n TData,\n TOptions extends QueryOptions<any, any, any, any>,\n>(prevData: TData | undefined, data: TData, options: TOptions): TData {\n if (typeof options.structuralSharing === 'function') {\n return options.structuralSharing(prevData, data) as TData\n } else if (options.structuralSharing !== false) {\n if (process.env.NODE_ENV !== 'production') {\n try {\n return replaceEqualDeep(prevData, data)\n } catch (error) {\n console.error(\n `Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`,\n )\n\n // Prevent the replaceEqualDeep from being called again down below.\n throw error\n }\n }\n // Structurally share data between prev and new data if needed\n return replaceEqualDeep(prevData, data)\n }\n return data\n}\n\n/**\n * Intended to be passed as a query's `placeholderData` option, for example\n * `placeholderData: keepPreviousData`. Instead of resetting the query's data to `undefined` while a new\n * query key is fetching, it keeps displaying the previously fetched data until the new data arrives.\n * @param previousData - The data of the previous query key, passed by the observer.\n * @returns The previous data, unchanged.\n * @example\n * ```ts\n * new QueryObserver(queryClient, {\n * queryKey: ['posts', page],\n * queryFn: () => fetchPosts(page),\n * placeholderData: keepPreviousData,\n * })\n * ```\n */\nexport function keepPreviousData<T>(\n previousData: T | undefined,\n): T | undefined {\n return previousData\n}\n\n/**\n * Returns a new array with `item` added at the end. If that makes the array longer than `max`,\n * the first item is dropped. Only one item is dropped, so the result can still exceed `max` if\n * `items` already did.\n * @param items - The current items.\n * @param item - The value to append.\n * @param max - The length above which an item is dropped. `0` (the default) means no limit.\n * @returns A new array with `item` added.\n */\nexport function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [...items, item]\n return max && newItems.length > max ? newItems.slice(1) : newItems\n}\n\n/**\n * Returns a new array with `item` added at the start. If that makes the array longer than `max`,\n * the last item is dropped. Only one item is dropped, so the result can still exceed `max` if\n * `items` already did.\n * @param items - The current items.\n * @param item - The value to prepend.\n * @param max - The length above which an item is dropped. `0` (the default) means no limit.\n * @returns A new array with `item` added.\n */\nexport function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [item, ...items]\n return max && newItems.length > max ? newItems.slice(0, -1) : newItems\n}\n\n/**\n * Sentinel value that can be passed as a query's `queryFn` to conditionally disable the query (equivalent\n * to `enabled: false`) while preserving full type inference for the query's data. Unlike `enabled: false`,\n * a query disabled via `skipToken` cannot be triggered with `refetch`.\n * @example\n * ```ts\n * new QueryObserver(queryClient, {\n * queryKey: ['post', postId],\n * queryFn: postId != null ? () => fetchPost(postId) : skipToken,\n * })\n * ```\n */\nexport const skipToken = Symbol()\n/**\n * The type of the {@link skipToken} sentinel value.\n */\nexport type SkipToken = typeof skipToken\n\n/**\n * Returns the function to call for a fetch. If there is no `queryFn` but the fetch was started from\n * an `initialPromise`, that promise is returned instead. If there is no usable `queryFn` (missing or\n * {@link skipToken}), the returned function rejects with a `Missing queryFn` error.\n * @param options - The query options with the `queryFn`, and the `queryHash` used in error messages.\n * @param fetchOptions - The fetch options, which may carry an `initialPromise`.\n * @returns The function to call for the fetch.\n */\nexport function ensureQueryFn<\n TQueryFnData = unknown,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: {\n queryFn?: QueryFunction<TQueryFnData, TQueryKey> | SkipToken\n queryHash?: string\n },\n fetchOptions?: FetchOptions<TQueryFnData>,\n): QueryFunction<TQueryFnData, TQueryKey> {\n if (process.env.NODE_ENV !== 'production') {\n if (options.queryFn === skipToken) {\n console.error(\n `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`,\n )\n }\n }\n\n // if we attempt to retry a fetch that was triggered from an initialPromise\n // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise\n // if an observer has already mounted, we will be able to retry with that queryFn\n if (!options.queryFn && fetchOptions?.initialPromise) {\n return () => fetchOptions.initialPromise!\n }\n\n if (!options.queryFn || options.queryFn === skipToken) {\n return () =>\n Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`))\n }\n\n return options.queryFn\n}\n\n/**\n * Resolves a `throwOnError` option to a boolean.\n * If `throwOnError` is a function, it is called with `params` (e.g. the error and, depending on the caller,\n * additional context such as the query or mutation) and its result is returned, allowing the throwing\n * behavior to be decided per error. Otherwise, `throwOnError` itself is coerced to a boolean (`undefined`\n * resolves to `false`).\n * @param throwOnError - The `throwOnError` option: a boolean, a function that decides per error, or\n * `undefined`.\n * @param params - The arguments passed to `throwOnError` if it is a function.\n * @returns Whether the error should be thrown.\n * @example\n * ```ts\n * const throwOnError =\n * query.state.error && typeof options.throwOnError === 'function'\n * ? shouldThrowError(options.throwOnError, [query.state.error, query])\n * : options.throwOnError\n * ```\n */\nexport function shouldThrowError<T extends (...args: Array<any>) => boolean>(\n throwOnError: boolean | T | undefined,\n params: Parameters<T>,\n): boolean {\n // Allow throwOnError function to override throwing behavior on a per-error basis\n if (typeof throwOnError === 'function') {\n return throwOnError(...params)\n }\n\n return !!throwOnError\n}\n\n/**\n * Adds a lazy `signal` getter to an object, such as a query function context. The first time\n * `signal` is read, `onCancelled` is registered for the signal's `abort` event (or called right\n * away if it is already aborted), so cancellation is only tracked when the signal is actually used.\n * @param object - The object to add the `signal` property to.\n * @param getSignal - Returns the `AbortSignal`. Called once, when `signal` is first read.\n * @param onCancelled - Called when the signal is aborted, if `signal` was read.\n * @returns The same object, with the `signal` property added.\n */\nexport function addConsumeAwareSignal<T>(\n object: T,\n getSignal: () => AbortSignal,\n onCancelled: VoidFunction,\n): T & { signal: AbortSignal } {\n let consumed = false\n let signal: AbortSignal | undefined\n\n Object.defineProperty(object, 'signal', {\n enumerable: true,\n get: () => {\n signal ??= getSignal()\n if (consumed) {\n return signal\n }\n\n consumed = true\n if (signal.aborted) {\n onCancelled()\n } else {\n signal.addEventListener('abort', onCancelled, { once: true })\n }\n\n return signal\n },\n })\n\n return object as T & { signal: AbortSignal }\n}\n"],"mappings":";;;;;;AAmHA,MAAa,WAAW,OAAO,WAAW,eAAe,UAAU;AAOnE,SAAgB,OAAO,CAAC;;;;;;;;AASxB,SAAgB,iBACd,SACA,OACS;CACT,OAAO,OAAO,YAAY,aACrB,QAAmC,KAAK,IACzC;AACN;;;;;;AAOA,SAAgB,eAAe,OAAiC;CAC9D,OAAO,OAAO,UAAU,YAAY,SAAS,KAAK,UAAU;AAC9D;;;;;;;;AASA,SAAgB,eAAe,WAAmB,WAA4B;CAC5E,OAAO,KAAK,IAAI,aAAa,aAAa,KAAK,KAAK,IAAI,GAAG,CAAC;AAC9D;;;;;;;;AASA,SAAgB,kBAOd,OAIA,OAC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,QAAQ,YAAA,iBAAA,QAAA,iBAAA,KAAA,IAAA,KAAA,IAAW,aAAc,iBACpC,aAAa,aAAa;CAG5B,IAAI,CAAC,QAAQ,WAAW,QAAQ,YAAY,WAC1C,aACE,QAAQ,uBAAO,IAAI,MAAM,qBAAqB,QAAQ,UAAU,EAAE,CAAC;CAGvE,OAAO,QAAQ;AACjB;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,iBACd,cACA,QACS;CAET,IAAI,OAAO,iBAAiB,YAC1B,OAAO,aAAa,GAAG,MAAM;CAG/B,OAAO,CAAC,CAAC;AACX;;;;;;;;;;AAWA,SAAgB,sBACd,QACA,WACA,aAC6B;CAC7B,IAAI,WAAW;CACf,IAAI;CAEJ,OAAO,eAAe,QAAQ,UAAU;EACtC,YAAY;EACZ,WAAW;GACT,WAAA,SAAW,UAAU;GACrB,IAAI,UACF,OAAO;GAGT,WAAW;GACX,IAAI,OAAO,SACT,YAAY;QAEZ,OAAO,iBAAiB,SAAS,aAAa,EAAE,MAAM,KAAK,CAAC;GAG9D,OAAO;EACT;CACF,CAAC;CAED,OAAO;AACT"}
1
+ {"version":3,"file":"utils.cjs","names":[],"sources":["../../src/utils.ts"],"sourcesContent":["import { timeoutManager } from './timeoutManager'\nimport type {\n DefaultError,\n FetchStatus,\n MutationKey,\n MutationStatus,\n QueryFunction,\n QueryKey,\n QueryOptions,\n} from './types'\nimport type { Mutation } from './mutation'\nimport type { FetchOptions, Query } from './query'\n\n// TYPES\n\ntype DropLast<T extends ReadonlyArray<unknown>> = T extends readonly [\n ...infer R,\n unknown,\n]\n ? readonly [...R]\n : never\n\ntype TuplePrefixes<T extends ReadonlyArray<unknown>> = T extends readonly []\n ? readonly []\n : TuplePrefixes<DropLast<T>> | T\n\n/**\n * Filters used to select queries, for example in `queryClient.getQueriesData` or `queryClient.invalidateQueries`.\n * All provided filters must match; filters that are left unspecified are ignored.\n */\nexport interface QueryFilters<TQueryKey extends QueryKey = QueryKey> {\n /**\n * Filter to active queries, inactive queries or all queries\n * @defaultValue 'all'\n */\n type?: QueryTypeFilter\n /**\n * Match query key exactly\n */\n exact?: boolean\n /**\n * Include queries matching this predicate function\n */\n predicate?: (query: Query) => boolean\n /**\n * Include queries matching this query key\n */\n queryKey?: TQueryKey | TuplePrefixes<TQueryKey>\n /**\n * Include or exclude stale queries\n */\n stale?: boolean\n /**\n * Include queries matching their fetchStatus\n */\n fetchStatus?: FetchStatus\n}\n\n/**\n * Filters used to select mutations, for example in `mutationCache.findAll` or `queryClient.isMutating`.\n * All provided filters must match; filters that are left unspecified are ignored.\n */\nexport interface MutationFilters<\n TData = unknown,\n TError = DefaultError,\n TVariables = unknown,\n TOnMutateResult = unknown,\n> {\n /**\n * Match mutation key exactly\n */\n exact?: boolean\n /**\n * Include mutations matching this predicate function\n */\n predicate?: (\n mutation: Mutation<TData, TError, TVariables, TOnMutateResult>,\n ) => boolean\n /**\n * Include mutations matching this mutation key\n */\n mutationKey?: TuplePrefixes<MutationKey>\n /**\n * Filter by mutation status\n */\n status?: MutationStatus\n}\n\n/**\n * Either a plain value of type `TOutput`, or a function that receives `TInput` and returns `TOutput`.\n * Used for example by `setQueryData`-style updaters, which accept either the new data directly or a\n * function that computes it from the previous data. See {@link functionalUpdate}.\n * @example\n * ```ts\n * queryClient.setQueryData(['posts'], newPosts)\n *\n * // Or, using an updater function that receives the current data:\n * queryClient.setQueryData(['posts'], (oldPosts) =>\n * oldPosts ? [...oldPosts, newPost] : oldPosts,\n * )\n * ```\n */\nexport type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput)\n\n/**\n * Which queries a filter matches: all of them, only active ones (with enabled observers), or only\n * inactive ones.\n */\nexport type QueryTypeFilter = 'all' | 'active' | 'inactive'\n\n// UTILS\n\n/**\n * @deprecated use `environmentManager.isServer()` instead.\n */\nexport const isServer = typeof window === 'undefined' || 'Deno' in globalThis\n\n/**\n * A function that does nothing.\n */\nexport function noop(): void\nexport function noop(): undefined\nexport function noop() {}\n\n/**\n * Resolves an {@link Updater}: calls it with `input` if it is a function, otherwise returns it as\n * is.\n * @param updater - The new value, or a function that receives `input` and returns the new value.\n * @param input - The current value, passed to `updater` if it is a function.\n * @returns The new value.\n */\nexport function functionalUpdate<TInput, TOutput>(\n updater: Updater<TInput, TOutput>,\n input: TInput,\n): TOutput {\n return typeof updater === 'function'\n ? (updater as (_: TInput) => TOutput)(input)\n : updater\n}\n\n/**\n * Checks whether a value can be used as a timeout: a non-negative, finite number.\n * @param value - The value to check.\n * @returns `true` if `value` is a number that is `>= 0` and not `Infinity`.\n */\nexport function isValidTimeout(value: unknown): value is number {\n return typeof value === 'number' && value >= 0 && value !== Infinity\n}\n\n/**\n * Calculates how long until data updated at `updatedAt` becomes stale.\n * @param updatedAt - The timestamp, in milliseconds, at which the data was last updated.\n * @param staleTime - The time, in milliseconds, after which data is considered stale. Defaults to\n * `0`.\n * @returns The remaining time in milliseconds, or `0` if the data is already stale.\n */\nexport function timeUntilStale(updatedAt: number, staleTime?: number): number {\n return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)\n}\n\n/**\n * Resolves an option that can be given either as a value or as a function of the query, such as\n * `staleTime`.\n * @param value - The option value, or a function that receives `query` and returns the value.\n * @param query - The query passed to `value` if it is a function.\n * @returns The resolved value, or `undefined` if `value` is `undefined`.\n */\nexport function resolveQueryValue<\n TValue,\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n value:\n | undefined\n | TValue\n | ((query: Query<TQueryFnData, TError, TData, TQueryKey>) => TValue),\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n): TValue | undefined {\n return typeof value === 'function'\n ? (\n value as (\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n ) => TValue\n )(query)\n : value\n}\n\n/**\n * Checks whether a query matches the given {@link QueryFilters}.\n * Every filter that is specified must match; filters that are left unspecified are ignored.\n * @param filters - The filters to check the query against.\n * @param query - The query to check.\n * @returns `true` if the query matches every specified filter.\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n *\n * const matchingQueries = queryCache\n * .getAll()\n * .filter((query) => matchQuery({ queryKey: ['posts'] }, query))\n * ```\n */\nexport function matchQuery(\n filters: QueryFilters,\n query: Query<any, any, any, any>,\n): boolean {\n const {\n type = 'all',\n exact,\n fetchStatus,\n predicate,\n queryKey,\n stale,\n } = filters\n\n if (queryKey) {\n if (exact) {\n if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {\n return false\n }\n } else if (!partialMatchKey(query.queryKey, queryKey)) {\n return false\n }\n }\n\n if (type !== 'all') {\n const isActive = query.isActive()\n if (type === 'active' && !isActive) {\n return false\n }\n if (type === 'inactive' && isActive) {\n return false\n }\n }\n\n if (typeof stale === 'boolean' && query.isStale() !== stale) {\n return false\n }\n\n if (fetchStatus && fetchStatus !== query.state.fetchStatus) {\n return false\n }\n\n if (predicate && !predicate(query)) {\n return false\n }\n\n return true\n}\n\n/**\n * Checks whether a mutation matches the given {@link MutationFilters}.\n * Every filter that is specified must match; filters that are left unspecified are ignored.\n * If a `mutationKey` filter is provided but the mutation has no `mutationKey` of its own, it does not match.\n * @param filters - The filters to check the mutation against.\n * @param mutation - The mutation to check.\n * @returns `true` if the mutation matches every specified filter.\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * const matchingMutations = mutationCache\n * .getAll()\n * .filter((mutation) => matchMutation({ mutationKey: ['addPost'] }, mutation))\n * ```\n */\nexport function matchMutation(\n filters: MutationFilters,\n mutation: Mutation<any, any>,\n): boolean {\n const { exact, status, predicate, mutationKey } = filters\n if (mutationKey) {\n if (!mutation.options.mutationKey) {\n return false\n }\n if (exact) {\n if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {\n return false\n }\n } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {\n return false\n }\n }\n\n if (status && mutation.state.status !== status) {\n return false\n }\n\n if (predicate && !predicate(mutation)) {\n return false\n }\n\n return true\n}\n\n/**\n * Hashes a query key with the query's `queryKeyHashFn` option, falling back to {@link hashKey}.\n * @param queryKey - The query key to hash.\n * @param options - The query options that may provide a custom `queryKeyHashFn`.\n * @returns The query hash, a string that identifies the query in the cache.\n */\nexport function hashQueryKeyByOptions<TQueryKey extends QueryKey = QueryKey>(\n queryKey: TQueryKey,\n options?: Pick<QueryOptions<any, any, any, any>, 'queryKeyHashFn'>,\n): string {\n const hashFn = options?.queryKeyHashFn || hashKey\n return hashFn(queryKey)\n}\n\n/**\n * Default query & mutation keys hash function.\n * Hashes the value into a stable hash.\n * @param queryKey - The query or mutation key to hash.\n * @returns The stable hash of the key, as a JSON string.\n * @example\n * ```ts\n * // Object keys are sorted, so key order doesn't affect the hash:\n * hashKey(['todos', { page: 1, filter: 'done' }]) // === '[\"todos\",{\"filter\":\"done\",\"page\":1}]'\n * ```\n */\nexport function hashKey(queryKey: QueryKey | MutationKey): string {\n return JSON.stringify(queryKey, (_, val) =>\n isPlainObject(val)\n ? Object.keys(val)\n .sort()\n .reduce((result, key) => {\n result[key] = val[key]\n return result\n }, {} as any)\n : val,\n )\n}\n\n/**\n * Checks if key `b` partially matches with key `a`.\n * @param a - The key to check, e.g. a query's own key.\n * @param b - The (partial) key to match against `a`.\n * @returns `true` if every array element or object property in `b` matches the one at the same\n * position in `a`.\n */\nexport function partialMatchKey(a: QueryKey, b: QueryKey): boolean\nexport function partialMatchKey(a: any, b: any): boolean {\n if (a === b) {\n return true\n }\n\n if (typeof a !== typeof b) {\n return false\n }\n\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n if (Array.isArray(a) && Array.isArray(b)) {\n if (b.length > a.length) return false\n for (let i = 0; i < b.length; i++) {\n if (!partialMatchKey(a[i], b[i])) {\n return false\n }\n }\n return true\n }\n\n const bKeys = Object.keys(b)\n for (const key of bKeys) {\n if (!partialMatchKey(a[key], b[key])) {\n return false\n }\n }\n return true\n }\n\n return false\n}\n\nconst hasOwn = Object.prototype.hasOwnProperty\n\n/**\n * This function returns `a` if `b` is deeply equal.\n * If not, it will replace any deeply equal children of `b` with those of `a`.\n * This can be used for structural sharing between JSON values for example.\n * @param a - The previous value, whose deeply equal parts are reused.\n * @param b - The new value.\n * @param depth - The current recursion depth. Past a depth of `500`, `b` is returned as is.\n * @returns `a` if `b` is deeply equal to it, otherwise `b` with its deeply equal parts replaced by\n * those of `a`.\n */\nexport function replaceEqualDeep<T>(a: unknown, b: T, depth?: number): T\nexport function replaceEqualDeep(a: any, b: any, depth = 0): any {\n if (a === b) {\n return a\n }\n\n if (depth > 500) return b\n\n const array = isPlainArray(a) && isPlainArray(b)\n\n if (!array && !(isPlainObject(a) && isPlainObject(b))) return b\n\n const aItems = array ? a : Object.keys(a)\n const aSize = aItems.length\n const bItems = array ? b : Object.keys(b)\n const bSize = bItems.length\n const copy: any = array ? new Array(bSize) : {}\n\n let equalItems = 0\n\n for (let i = 0; i < bSize; i++) {\n const key: any = array ? i : bItems[i]\n const aItem = a[key]\n const bItem = b[key]\n\n if (aItem === bItem) {\n copy[key] = aItem\n if (array ? i < aSize : hasOwn.call(a, key)) equalItems++\n continue\n }\n\n if (\n aItem === null ||\n bItem === null ||\n typeof aItem !== 'object' ||\n typeof bItem !== 'object'\n ) {\n copy[key] = bItem\n continue\n }\n\n const v = replaceEqualDeep(aItem, bItem, depth + 1)\n copy[key] = v\n if (v === aItem) equalItems++\n }\n\n return aSize === bSize && equalItems === aSize ? a : copy\n}\n\n/**\n * Shallow compare objects.\n * @param a - The first object.\n * @param b - The second object, or `undefined`.\n * @returns `true` if both objects have the same keys, with strictly equal values for each key.\n */\nexport function shallowEqualObjects<T extends Record<string, any>>(\n a: T,\n b: T | undefined,\n): boolean {\n if (!b || Object.keys(a).length !== Object.keys(b).length) {\n return false\n }\n\n for (const key of Object.keys(a)) {\n if (!hasOwn.call(b, key) || a[key] !== b[key]) {\n return false\n }\n }\n\n return true\n}\n\n/**\n * Checks whether a value is an array with no holes and no extra properties.\n * @param value - The value to check.\n * @returns `true` if `value` is an array whose number of own keys equals its `length`.\n */\nexport function isPlainArray(value: unknown): value is Array<unknown> {\n return Array.isArray(value) && value.length === Object.keys(value).length\n}\n\n// Copied from: https://github.com/jonschlinkert/is-plain-object\n/**\n * Checks whether a value is a plain object, e.g. created with an object literal or\n * `Object.create(null)`.\n * @param o - The value to check.\n * @returns `true` if `o` is a plain object.\n */\nexport function isPlainObject(o: any): o is Record<PropertyKey, unknown> {\n if (!hasObjectPrototype(o)) {\n return false\n }\n\n // If has no constructor\n const objectPrototype = Object.getPrototypeOf(o)\n const ctor = objectPrototype?.constructor\n if (ctor === undefined) {\n return true\n }\n\n if (typeof ctor !== 'function') {\n return false\n }\n\n // If has modified prototype\n const prot = ctor.prototype\n if (!hasObjectPrototype(prot)) {\n return false\n }\n\n // If constructor does not have an Object-specific method\n if (!prot.hasOwnProperty('isPrototypeOf')) {\n return false\n }\n\n // Handles Objects created by Object.create(<arbitrary prototype>)\n if (objectPrototype !== Object.prototype) {\n return false\n }\n\n // Most likely a plain Object\n return true\n}\n\n/**\n * Checks whether a value's `Object.prototype.toString` tag is `[object Object]`.\n * @param o - The value to check.\n * @returns `true` if the tag is `[object Object]`.\n */\nfunction hasObjectPrototype(o: any): boolean {\n return Object.prototype.toString.call(o) === '[object Object]'\n}\n\n/**\n * Waits for the given time, using the configured {@link timeoutManager}.\n * @param timeout - The time to wait, in milliseconds.\n * @returns A promise that resolves after `timeout` milliseconds.\n */\nexport function sleep(timeout: number): Promise<void> {\n return new Promise((resolve) => {\n timeoutManager.setTimeout(resolve, timeout)\n })\n}\n\n/**\n * Applies a query's `structuralSharing` option when writing new data.\n * @param prevData - The previously cached data.\n * @param data - The new data.\n * @param options - The query options, whose `structuralSharing` decides how the data is merged.\n * @returns The result of a custom `structuralSharing` function, `data` with its unchanged parts\n * replaced by those of `prevData` by default, or `data` as is if `structuralSharing` is `false`.\n * @throws {Error} The error from the default structural sharing, e.g. when the data is not JSON serializable.\n * Outside production, it is also logged to the console.\n */\nexport function replaceData<\n TData,\n TOptions extends QueryOptions<any, any, any, any>,\n>(prevData: TData | undefined, data: TData, options: TOptions): TData {\n if (typeof options.structuralSharing === 'function') {\n return options.structuralSharing(prevData, data) as TData\n } else if (options.structuralSharing !== false) {\n if (process.env.NODE_ENV !== 'production') {\n try {\n return replaceEqualDeep(prevData, data)\n } catch (error) {\n console.error(\n `Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`,\n )\n\n // Prevent the replaceEqualDeep from being called again down below.\n throw error\n }\n }\n // Structurally share data between prev and new data if needed\n return replaceEqualDeep(prevData, data)\n }\n return data\n}\n\n/**\n * Intended to be passed as a query's `placeholderData` option, for example\n * `placeholderData: keepPreviousData`. Instead of resetting the query's data to `undefined` while a new\n * query key is fetching, it keeps displaying the previously fetched data until the new data arrives.\n * @param previousData - The data of the previous query key, passed by the observer.\n * @returns The previous data, unchanged.\n * @example\n * ```ts\n * new QueryObserver(queryClient, {\n * queryKey: ['posts', page],\n * queryFn: () => fetchPosts(page),\n * placeholderData: keepPreviousData,\n * })\n * ```\n */\nexport function keepPreviousData<T>(\n previousData: T | undefined,\n): T | undefined {\n return previousData\n}\n\n/**\n * Returns a new array with `item` added at the end. If that makes the array longer than `max`,\n * excess items are removed from the start.\n * @param items - The current items.\n * @param item - The value to append.\n * @param max - The maximum number of items to keep. `0` (the default) means no limit.\n * @returns A new array with `item` added.\n */\nexport function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [...items, item]\n return max && newItems.length > max ? newItems.slice(-max) : newItems\n}\n\n/**\n * Returns a new array with `item` added at the start. If that makes the array longer than `max`,\n * excess items are removed from the end.\n * @param items - The current items.\n * @param item - The value to prepend.\n * @param max - The maximum number of items to keep. `0` (the default) means no limit.\n * @returns A new array with `item` added.\n */\nexport function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [item, ...items]\n return max && newItems.length > max ? newItems.slice(0, max) : newItems\n}\n\n/**\n * Sentinel value that can be passed as a query's `queryFn` to conditionally disable the query (equivalent\n * to `enabled: false`) while preserving full type inference for the query's data. Unlike `enabled: false`,\n * a query disabled via `skipToken` cannot be triggered with `refetch`.\n * @example\n * ```ts\n * new QueryObserver(queryClient, {\n * queryKey: ['post', postId],\n * queryFn: postId != null ? () => fetchPost(postId) : skipToken,\n * })\n * ```\n */\nexport const skipToken = Symbol()\n/**\n * The type of the {@link skipToken} sentinel value.\n */\nexport type SkipToken = typeof skipToken\n\n/**\n * Returns the function to call for a fetch. If there is no `queryFn` but the fetch was started from\n * an `initialPromise`, that promise is returned instead. If there is no usable `queryFn` (missing or\n * {@link skipToken}), the returned function rejects with a `Missing queryFn` error.\n * @param options - The query options with the `queryFn`, and the `queryHash` used in error messages.\n * @param fetchOptions - The fetch options, which may carry an `initialPromise`.\n * @returns The function to call for the fetch.\n */\nexport function ensureQueryFn<\n TQueryFnData = unknown,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: {\n queryFn?: QueryFunction<TQueryFnData, TQueryKey> | SkipToken\n queryHash?: string\n },\n fetchOptions?: FetchOptions<TQueryFnData>,\n): QueryFunction<TQueryFnData, TQueryKey> {\n if (process.env.NODE_ENV !== 'production') {\n if (options.queryFn === skipToken) {\n console.error(\n `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`,\n )\n }\n }\n\n // if we attempt to retry a fetch that was triggered from an initialPromise\n // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise\n // if an observer has already mounted, we will be able to retry with that queryFn\n if (!options.queryFn && fetchOptions?.initialPromise) {\n return () => fetchOptions.initialPromise!\n }\n\n if (!options.queryFn || options.queryFn === skipToken) {\n return () =>\n Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`))\n }\n\n return options.queryFn\n}\n\n/**\n * Resolves a `throwOnError` option to a boolean.\n * If `throwOnError` is a function, it is called with `params` (e.g. the error and, depending on the caller,\n * additional context such as the query or mutation) and its result is returned, allowing the throwing\n * behavior to be decided per error. Otherwise, `throwOnError` itself is coerced to a boolean (`undefined`\n * resolves to `false`).\n * @param throwOnError - The `throwOnError` option: a boolean, a function that decides per error, or\n * `undefined`.\n * @param params - The arguments passed to `throwOnError` if it is a function.\n * @returns Whether the error should be thrown.\n * @example\n * ```ts\n * const throwOnError =\n * query.state.error && typeof options.throwOnError === 'function'\n * ? shouldThrowError(options.throwOnError, [query.state.error, query])\n * : options.throwOnError\n * ```\n */\nexport function shouldThrowError<T extends (...args: Array<any>) => boolean>(\n throwOnError: boolean | T | undefined,\n params: Parameters<T>,\n): boolean {\n // Allow throwOnError function to override throwing behavior on a per-error basis\n if (typeof throwOnError === 'function') {\n return throwOnError(...params)\n }\n\n return !!throwOnError\n}\n\nexport const fetchSignal = Symbol()\n\n/** Internal view of a context that can expose its signal without consuming it. */\nexport type FetchSignalContext = {\n /** The public signal, whose getter can mark it consumed. */\n readonly signal: AbortSignal\n /** The original fetch signal, absent on application-created contexts. */\n readonly [fetchSignal]?: AbortSignal\n}\n\n/**\n * Adds a lazy `signal` getter to an object, such as a query function context. The first time\n * `signal` is read, `onCancelled` is registered for the signal's `abort` event (or called right\n * away if it is already aborted), so cancellation is only tracked when the signal is actually used.\n * @param object - The object to add the `signal` property to.\n * @param getSignal - Returns the `AbortSignal`. Called once, when `signal` is first read.\n * @param onCancelled - Called when the signal is aborted, if `signal` was read.\n * @param internalSignal - The fetch signal to forward without consuming the getter.\n * @returns The same object, with the `signal` property added.\n */\nexport function addConsumeAwareSignal<T extends object>(\n object: T,\n getSignal: () => AbortSignal,\n onCancelled: () => void,\n internalSignal?: AbortSignal,\n): T & { signal: AbortSignal } {\n let consumed = false\n let signal: AbortSignal | undefined\n\n Object.defineProperties(object, {\n [fetchSignal]: { value: internalSignal },\n signal: {\n enumerable: true,\n get: () => {\n signal ??= getSignal()\n if (consumed) {\n return signal\n }\n\n consumed = true\n if (signal.aborted) {\n onCancelled()\n } else {\n signal.addEventListener('abort', onCancelled,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E,MAAM,KAAK,CAAC;IAG9D,OAAO;GACT;EACF;CACF,CAAC;CAED,OAAO;AACT"}
@@ -1,2 +1,2 @@
1
- import { An as noop, Cn as isPlainArray, Dn as keepPreviousData, En as isValidTimeout, Fn as shallowEqualObjects, In as shouldThrowError, Ln as skipToken, Mn as replaceData, Nn as replaceEqualDeep, On as matchMutation, Pn as resolveQueryValue, Rn as sleep, Sn as hashQueryKeyByOptions, Tn as isServer, _n as addToEnd, bn as functionalUpdate, dn as MutationFilters, fn as QueryFilters, gn as addConsumeAwareSignal, hn as Updater, jn as partialMatchKey, kn as matchQuery, mn as SkipToken, pn as QueryTypeFilter, vn as addToStart, wn as isPlainObject, xn as hashKey, yn as ensureQueryFn, zn as timeUntilStale } from "./hydration-DdkP3REv.cjs";
2
- export { MutationFilters, QueryFilters, QueryTypeFilter, SkipToken, Updater, addConsumeAwareSignal, addToEnd, addToStart, ensureQueryFn, functionalUpdate, hashKey, hashQueryKeyByOptions, isPlainArray, isPlainObject, isServer, isValidTimeout, keepPreviousData, matchMutation, matchQuery, noop, partialMatchKey, replaceData, replaceEqualDeep, resolveQueryValue, shallowEqualObjects, shouldThrowError, skipToken, sleep, timeUntilStale };
1
+ import { An as matchMutation, Bn as sleep, Cn as hashKey, Dn as isServer, En as isPlainObject, Fn as replaceEqualDeep, In as resolveQueryValue, Ln as shallowEqualObjects, Mn as noop, Nn as partialMatchKey, On as isValidTimeout, Pn as replaceData, Rn as shouldThrowError, Sn as functionalUpdate, Tn as isPlainArray, Vn as timeUntilStale, _n as addConsumeAwareSignal, bn as ensureQueryFn, dn as FetchSignalContext, fn as MutationFilters, gn as Updater, hn as SkipToken, jn as matchQuery, kn as keepPreviousData, mn as QueryTypeFilter, pn as QueryFilters, vn as addToEnd, wn as hashQueryKeyByOptions, xn as fetchSignal, yn as addToStart, zn as skipToken } from "./hydration-BXjqUj_D.cjs";
2
+ export { FetchSignalContext, MutationFilters, QueryFilters, QueryTypeFilter, SkipToken, Updater, addConsumeAwareSignal, addToEnd, addToStart, ensureQueryFn, fetchSignal, functionalUpdate, hashKey, hashQueryKeyByOptions, isPlainArray, isPlainObject, isServer, isValidTimeout, keepPreviousData, matchMutation, matchQuery, noop, partialMatchKey, replaceData, replaceEqualDeep, resolveQueryValue, shallowEqualObjects, shouldThrowError, skipToken, sleep, timeUntilStale };
@@ -1,2 +1,2 @@
1
- import { An as noop, Cn as isPlainArray, Dn as keepPreviousData, En as isValidTimeout, Fn as shallowEqualObjects, In as shouldThrowError, Ln as skipToken, Mn as replaceData, Nn as replaceEqualDeep, On as matchMutation, Pn as resolveQueryValue, Rn as sleep, Sn as hashQueryKeyByOptions, Tn as isServer, _n as addToEnd, bn as functionalUpdate, dn as MutationFilters, fn as QueryFilters, gn as addConsumeAwareSignal, hn as Updater, jn as partialMatchKey, kn as matchQuery, mn as SkipToken, pn as QueryTypeFilter, vn as addToStart, wn as isPlainObject, xn as hashKey, yn as ensureQueryFn, zn as timeUntilStale } from "./hydration-gHEs4kLM.js";
2
- export { MutationFilters, QueryFilters, QueryTypeFilter, SkipToken, Updater, addConsumeAwareSignal, addToEnd, addToStart, ensureQueryFn, functionalUpdate, hashKey, hashQueryKeyByOptions, isPlainArray, isPlainObject, isServer, isValidTimeout, keepPreviousData, matchMutation, matchQuery, noop, partialMatchKey, replaceData, replaceEqualDeep, resolveQueryValue, shallowEqualObjects, shouldThrowError, skipToken, sleep, timeUntilStale };
1
+ import { An as matchMutation, Bn as sleep, Cn as hashKey, Dn as isServer, En as isPlainObject, Fn as replaceEqualDeep, In as resolveQueryValue, Ln as shallowEqualObjects, Mn as noop, Nn as partialMatchKey, On as isValidTimeout, Pn as replaceData, Rn as shouldThrowError, Sn as functionalUpdate, Tn as isPlainArray, Vn as timeUntilStale, _n as addConsumeAwareSignal, bn as ensureQueryFn, dn as FetchSignalContext, fn as MutationFilters, gn as Updater, hn as SkipToken, jn as matchQuery, kn as keepPreviousData, mn as QueryTypeFilter, pn as QueryFilters, vn as addToEnd, wn as hashQueryKeyByOptions, xn as fetchSignal, yn as addToStart, zn as skipToken } from "./hydration-vgIjIhk6.js";
2
+ export { FetchSignalContext, MutationFilters, QueryFilters, QueryTypeFilter, SkipToken, Updater, addConsumeAwareSignal, addToEnd, addToStart, ensureQueryFn, fetchSignal, functionalUpdate, hashKey, hashQueryKeyByOptions, isPlainArray, isPlainObject, isServer, isValidTimeout, keepPreviousData, matchMutation, matchQuery, noop, partialMatchKey, replaceData, replaceEqualDeep, resolveQueryValue, shallowEqualObjects, shouldThrowError, skipToken, sleep, timeUntilStale };
@@ -182,7 +182,7 @@ function replaceEqualDeep(a, b, depth = 0) {
182
182
  */
183
183
  function shallowEqualObjects(a, b) {
184
184
  if (!b || Object.keys(a).length !== Object.keys(b).length) return false;
185
- for (const key in a) if (a[key] !== b[key]) return false;
185
+ for (const key of Object.keys(a)) if (!hasOwn.call(b, key) || a[key] !== b[key]) return false;
186
186
  return true;
187
187
  }
188
188
  /**
@@ -272,29 +272,27 @@ function keepPreviousData(previousData) {
272
272
  }
273
273
  /**
274
274
  * Returns a new array with `item` added at the end. If that makes the array longer than `max`,
275
- * the first item is dropped. Only one item is dropped, so the result can still exceed `max` if
276
- * `items` already did.
275
+ * excess items are removed from the start.
277
276
  * @param items - The current items.
278
277
  * @param item - The value to append.
279
- * @param max - The length above which an item is dropped. `0` (the default) means no limit.
278
+ * @param max - The maximum number of items to keep. `0` (the default) means no limit.
280
279
  * @returns A new array with `item` added.
281
280
  */
282
281
  function addToEnd(items, item, max = 0) {
283
282
  const newItems = [...items, item];
284
- return max && newItems.length > max ? newItems.slice(1) : newItems;
283
+ return max && newItems.length > max ? newItems.slice(-max) : newItems;
285
284
  }
286
285
  /**
287
286
  * Returns a new array with `item` added at the start. If that makes the array longer than `max`,
288
- * the last item is dropped. Only one item is dropped, so the result can still exceed `max` if
289
- * `items` already did.
287
+ * excess items are removed from the end.
290
288
  * @param items - The current items.
291
289
  * @param item - The value to prepend.
292
- * @param max - The length above which an item is dropped. `0` (the default) means no limit.
290
+ * @param max - The maximum number of items to keep. `0` (the default) means no limit.
293
291
  * @returns A new array with `item` added.
294
292
  */
295
293
  function addToStart(items, item, max = 0) {
296
294
  const newItems = [item, ...items];
297
- return max && newItems.length > max ? newItems.slice(0, -1) : newItems;
295
+ return max && newItems.length > max ? newItems.slice(0, max) : newItems;
298
296
  }
299
297
  /**
300
298
  * Sentinel value that can be passed as a query's `queryFn` to conditionally disable the query (equivalent
@@ -347,6 +345,7 @@ function shouldThrowError(throwOnError, params) {
347
345
  if (typeof throwOnError === "function") return throwOnError(...params);
348
346
  return !!throwOnError;
349
347
  }
348
+ const fetchSignal = Symbol();
350
349
  /**
351
350
  * Adds a lazy `signal` getter to an object, such as a query function context. The first time
352
351
  * `signal` is read, `onCancelled` is registered for the signal's `abort` event (or called right
@@ -354,24 +353,28 @@ function shouldThrowError(throwOnError, params) {
354
353
  * @param object - The object to add the `signal` property to.
355
354
  * @param getSignal - Returns the `AbortSignal`. Called once, when `signal` is first read.
356
355
  * @param onCancelled - Called when the signal is aborted, if `signal` was read.
356
+ * @param internalSignal - The fetch signal to forward without consuming the getter.
357
357
  * @returns The same object, with the `signal` property added.
358
358
  */
359
- function addConsumeAwareSignal(object, getSignal, onCancelled) {
359
+ function addConsumeAwareSignal(object, getSignal, onCancelled, internalSignal) {
360
360
  let consumed = false;
361
361
  let signal;
362
- Object.defineProperty(object, "signal", {
363
- enumerable: true,
364
- get: () => {
365
- signal ?? (signal = getSignal());
366
- if (consumed) return signal;
367
- consumed = true;
368
- if (signal.aborted) onCancelled();
369
- else signal.addEventListener("abort", onCancelled, { once: true });
370
- return signal;
362
+ Object.defineProperties(object, {
363
+ [fetchSignal]: { value: internalSignal },
364
+ signal: {
365
+ enumerable: true,
366
+ get: () => {
367
+ signal ?? (signal = getSignal());
368
+ if (consumed) return signal;
369
+ consumed = true;
370
+ if (signal.aborted) onCancelled();
371
+ else signal.addEventListener("abort", onCancelled, { once: true });
372
+ return signal;
373
+ }
371
374
  }
372
375
  });
373
376
  return object;
374
377
  }
375
- export { addConsumeAwareSignal, addToEnd, addToStart, ensureQueryFn, functionalUpdate, hashKey, hashQueryKeyByOptions, isPlainArray, isPlainObject, isServer, isValidTimeout, keepPreviousData, matchMutation, matchQuery, noop, partialMatchKey, replaceData, replaceEqualDeep, resolveQueryValue, shallowEqualObjects, shouldThrowError, skipToken, sleep, timeUntilStale };
378
+ export { addConsumeAwareSignal, addToEnd, addToStart, ensureQueryFn, fetchSignal, functionalUpdate, hashKey, hashQueryKeyByOptions, isPlainArray, isPlainObject, isServer, isValidTimeout, keepPreviousData, matchMutation, matchQuery, noop, partialMatchKey, replaceData, replaceEqualDeep, resolveQueryValue, shallowEqualObjects, shouldThrowError, skipToken, sleep, timeUntilStale };
376
379
 
377
380
  //# sourceMappingURL=utils.js.map