{"version":3,"file":"index.mjs","names":[],"sources":["../src/entry-keys.ts","../src/utils.ts","../src/query-options.ts","../src/query-store.ts","../src/define-query.ts","../src/use-query.ts","../src/define-query-options.ts","../src/use-query-state.ts","../src/infinite-query.ts","../src/define-infinite-query-options.ts","../src/mutation-options.ts","../src/mutation-store.ts","../src/use-mutation.ts","../src/define-mutation.ts","../src/define-mutation-options.ts","../src/pinia-colada.ts","../src/plugins/query-hooks.ts","../src/plugins/no-gc-ssr.ts"],"sourcesContent":["import type { ErrorDefault } from './types-extension'\n\nexport function toCacheKey(key: undefined): undefined\nexport function toCacheKey(key: EntryKey): string\nexport function toCacheKey(key: EntryKey | undefined): string | undefined\n/**\n * Serializes the given {@link EntryKey | key} (query or mutation key) to a string.\n *\n * @param key - The key to serialize.\n *\n * @see {@link EntryKey}\n */\nexport function toCacheKey(key: EntryKey | undefined): string | undefined {\n  return (\n    key &&\n    JSON.stringify(key, (_, val) =>\n      !val || typeof val !== 'object' || Array.isArray(val)\n        ? val\n        : Object.keys(val)\n            .sort()\n            .reduce((result, key) => {\n              result[key] = val[key]\n              return result\n            }, {} as any),\n    )\n  )\n}\n\n/**\n * Checks whether `subsetKey` is a subset of `fullsetKey` by matching partially objects and arrays.\n *\n * @param subsetKey - subset key to check\n * @param fullsetKey - fullset key to check against\n */\nexport function isSubsetOf(subsetKey: EntryKey, fullsetKey: EntryKey): boolean {\n  return subsetKey === fullsetKey\n    ? true\n    : typeof subsetKey !== typeof fullsetKey\n      ? false\n      : subsetKey && fullsetKey && typeof subsetKey === 'object' && typeof fullsetKey === 'object'\n        ? Object.keys(subsetKey).every((key) =>\n            isSubsetOf(\n              // NOTE: this or making them `any` in the function signature\n              subsetKey[key as unknown as number] as EntryKey,\n              fullsetKey[key as unknown as number] as EntryKey,\n            ),\n          )\n        : false\n}\n\n/**\n * Used for keys\n *\n * @internal\n */\nexport type JSONPrimitive = string | number | boolean | null\n\n/**\n * Used for keys\n *\n * @internal\n */\nexport type JSONValue = JSONPrimitive | JSONObject | JSONArray\n\n/**\n * Used for keys. Interface to avoid deep recursion.\n *\n * @internal\n */\nexport type JSONObject = object\n// NOTE: this doesn't allow interfaces to be assigned to it due to its index signature\n// export interface JSONObject {\n//   readonly [key: string]: JSONValue | undefined\n// }\n\n/**\n * Used for keys. Interface to avoid deep recursion.\n *\n * @internal\n */\nexport interface JSONArray extends Array<JSONValue> {}\n\n/**\n * Key used to identify a query or a mutation. Must be a JSON serializable\n * value. Type is unknwon to avoid annoying type errors like recursive types\n * and not being able to assign an interface to it due to its index signature.\n */\nexport type EntryKey = readonly JSONValue[]\n\n/**\n * Internal symbol used to tag the data type of the entry key.\n *\n * @internal\n */\nexport const ENTRY_DATA_TAG = Symbol('Pinia Colada data tag')\n\n/**\n * Internal symbol used to tag the error type of the entry key.\n *\n * @internal\n */\nexport const ENTRY_ERROR_TAG = Symbol('Pinia Colada error tag')\n\n/**\n * Internal symbol used to tag the data initial type of the entry key.\n *\n * @internal\n */\nexport const ENTRY_DATA_INITIAL_TAG = Symbol('Pinia Colada data initial tag')\n\n/**\n * Same as {@link EntryKey} but with a data tag that allows inference of the data type.\n * Used by `defineQueryOptions()`.\n */\nexport type EntryKeyTagged<\n  TData,\n  TError = ErrorDefault,\n  TDataInitial extends TData | undefined = undefined,\n> = EntryKey & {\n  [ENTRY_DATA_TAG]: TData\n  [ENTRY_ERROR_TAG]: TError\n  [ENTRY_DATA_INITIAL_TAG]: TDataInitial\n}\n\n/**\n * Finds entries that partially match the given key. If no key is provided, all\n * entries are returned.\n *\n * @param map - The map to search in.\n * @param partialKey - The key to match against. If not provided, all entries are yield.\n *\n * @internal\n */\nexport function* find<T extends { key: EntryKey | undefined }>(\n  map: Map<string | number, T>,\n  partialKey?: EntryKey,\n) {\n  for (const entry of map.values()) {\n    if (!partialKey || (entry.key && isSubsetOf(partialKey, entry.key))) {\n      yield entry\n    }\n  }\n}\n\n/**\n * Empty starting object for extensions that allows to detect when to update.\n *\n * @internal\n */\nexport const START_EXT = Object.freeze(\n  process.env.NODE_ENV === 'production'\n    ? {}\n    : {\n        message:\n          'This is a placeholder object for Pinia Colada extensions, it should never be used directly, but only checked for identity. This is here to simplify debugging during dev.',\n      },\n)\n","import { computed, getCurrentScope, onScopeDispose } from 'vue'\nimport type { MaybeRefOrGetter, Ref, ShallowRef } from 'vue'\n\n/**\n * Adds an event listener to Window that is automatically removed on scope dispose.\n */\nexport function useEventListener<E extends keyof WindowEventMap>(\n  target: Window,\n  event: E,\n  listener: (this: Window, ev: WindowEventMap[E]) => any,\n  options?: boolean | AddEventListenerOptions,\n): void\n\n/**\n * Adds an event listener to Document that is automatically removed on scope dispose.\n */\nexport function useEventListener<E extends keyof DocumentEventMap>(\n  target: Document,\n  event: E,\n  listener: (this: Document, ev: DocumentEventMap[E]) => any,\n  options?: boolean | AddEventListenerOptions,\n): void\n\nexport function useEventListener(\n  target: Document | Window | EventTarget,\n  event: string,\n  listener: (this: EventTarget, ev: Event) => any,\n  options?: boolean | AddEventListenerOptions,\n) {\n  target.addEventListener(event, listener, options)\n  if (getCurrentScope()) {\n    onScopeDispose(() => {\n      target.removeEventListener(event, listener)\n    })\n  }\n}\n\nexport const IS_CLIENT = typeof window !== 'undefined'\n\n/**\n * Type that represents a value that can be an array or a single value.\n *\n * @internal\n */\nexport type _MaybeArray<T> = T | T[]\n\n/**\n * Checks if a type is exactly `any`.\n *\n * @internal\n */\nexport type IsAny<T> = 0 extends 1 & T ? true : false\n\n/**\n * Checks if a type is exactly `unknown`. This is useful to determine if a type is\n *\n * @internal\n */\nexport type IsUnknown<T> = IsAny<T> extends true ? false : unknown extends T ? true : false\n\n/**\n * Type that represents a value that can be a function or a single value. Used\n * for `defineQuery()` and `defineMutation()`.\n *\n * @internal\n */\nexport type _MaybeFunction<T, Args extends any[] = []> = T | ((...args: Args) => T)\n\n/**\n * Transforms a value or a function that returns a value to a value.\n *\n * @param valFn either a value or a function that returns a value\n * @param args  arguments to pass to the function if `valFn` is a function\n *\n * @internal\n */\nexport function toValueWithArgs<T, Args extends any[]>(\n  valFn: T | ((...args: Args) => T),\n  ...args: Args\n): T {\n  return typeof valFn === 'function' ? (valFn as (...args: Args) => T)(...args) : valFn\n}\n\n/**\n * Type that represents a value that can be a promise or a single value.\n *\n * @internal\n */\nexport type _Awaitable<T> = T | Promise<T>\n\n/**\n * Flattens an object type for readability.\n *\n * @internal\n */\nexport type _Simplify<T> = { [K in keyof T]: T[K] }\n\n/**\n * Converts a value to an array if necessary.\n *\n * @param value - value to convert\n */\nexport const toArray = <T>(value: _MaybeArray<T>): T[] => (Array.isArray(value) ? value : [value])\n\n/**\n * Valid primitives that can be stringified with `JSON.stringify`.\n *\n * @internal\n */\nexport type _JSONPrimitive = string | number | boolean | null | undefined\n\n/**\n * Utility type to represent a flat object that can be stringified with\n * `JSON.stringify` no matter the order of keys.\n *\n * @internal\n */\nexport interface _ObjectFlat {\n  [key: string]: _JSONPrimitive | Array<_JSONPrimitive>\n}\n\n/**\n * Valid values that can be stringified with `JSON.stringify`.\n *\n * @internal\n */\nexport type _JSONValue = _JSONPrimitive | _JSONValue[] | { [key: string]: _JSONValue }\n\n/**\n * Stringifies an object no matter the order of keys. This is used to create a\n * hash for a given object. It only works with flat objects. It can contain\n * arrays of primitives only. `undefined` values are skipped.\n *\n * @param obj - object to stringify\n */\nexport function stringifyFlatObject(obj: _ObjectFlat | _JSONPrimitive): string {\n  return obj && typeof obj === 'object' ? JSON.stringify(obj, Object.keys(obj).sort()) : String(obj)\n}\n\n/**\n * Merges two types when the second one can be null | undefined. Allows to safely use the returned type for { ...a,\n * ...undefined, ...null }\n * @internal\n */\nexport type _MergeObjects<Obj, MaybeNull> = MaybeNull extends undefined | null | void\n  ? Obj\n  : _Simplify<Obj & MaybeNull>\n\n/**\n * @internal\n */\nexport const noop = () => {}\n\n/**\n * Wraps a getter to be used as a ref. This is useful when you want to use a getter as a ref but you need to modify the\n * value.\n *\n * @internal\n * @param other - getter of the ref to compute\n * @returns a wrapper around a writable getter that can be used as a ref\n */\nexport const computedRef = <T>(other: () => Ref<T>): ShallowRef<T> =>\n  computed({\n    get: () => other().value,\n    set: (value) => (other().value = value),\n  })\n\n/**\n * Renames a property in an object type.\n */\nexport type _RenameProperty<T, Key extends keyof T, NewKey extends string> = {\n  [P in keyof T as P extends Key ? NewKey : P]: T[P]\n}\n\n/**\n * Type safe version of `Object.assign` that allows to set all properties of a reactive object at once. Used to set\n * {@link DataState} properties in a type safe way.\n */\nexport const setReactiveValue = Object.assign as <T>(value: T, ...args: T[]) => T\n\n/**\n * To avoid using `{}`\n * @internal\n */\nexport interface _EmptyObject {}\n\n/**\n * Dev only warning that is only shown once.\n */\nconst warnedMessages = new Set<string>()\n\n/**\n * Warns only once. This should only be used in dev\n *\n * @param message - Message to show\n * @param id - Unique id for the message, defaults to the message\n */\nexport function warnOnce(message: string, id: string = message) {\n  if (warnedMessages.has(id)) return\n  warnedMessages.add(id)\n  console.warn(`[@pinia/colada]: ${message}`)\n}\n\n/**\n * @internal\n */\nexport type _IsMaybeRefOrGetter<T> = [T] extends [MaybeRefOrGetter<infer U>]\n  ? MaybeRefOrGetter<U> extends T // must match the wrapper, not just any function\n    ? true\n    : false\n  : false\n\n/**\n * @internal\n */\nexport type _UnwrapMaybeRefOrGetter<T> = T extends MaybeRefOrGetter<infer U> ? U : T\n\n/**\n * Removes the `MaybeRefOrGetter` wrapper from all fields of an object,\n * except for fields specified in the `Ignore` type.\n * @internal\n */\nexport type _RemoveMaybeRef<T, Ignore extends keyof T = never> = {\n  [K in keyof T]: K extends Ignore\n    ? T[K]\n    : _IsMaybeRefOrGetter<NonNullable<T[K]>> extends true\n      ? _UnwrapMaybeRefOrGetter<T[K]>\n      : T[K]\n}\n","import { inject } from 'vue'\nimport type { InjectionKey, MaybeRefOrGetter } from 'vue'\nimport type { EntryKey } from './entry-keys'\nimport type { ErrorDefault, QueryMeta } from './types-extension'\nimport type { UseQueryEntry } from './query-store'\n\n/**\n * Possible values for `refetchOnMount`, `refetchOnWindowFocus`, and `refetchOnReconnect`.\n * `true` refetches if data is stale (calles `refresh()`), `false` never refetches, `'always'` always refetches.\n */\nexport type RefetchOnControl = boolean | 'always'\n\n/**\n * Options for queries that can be globally overridden.\n */\nexport interface UseQueryOptionsGlobal {\n  /**\n   * Whether the query should be enabled or not. If `false`, the query will not\n   * be executed until `refetch()` or `refresh()` is called. If it becomes\n   * `true`, the query will be refreshed.\n   */\n  enabled?: MaybeRefOrGetter<boolean>\n\n  /**\n   * Time in ms after which the data is considered stale and will be refreshed\n   * on next read.\n   *\n   * @default 5000 (5 seconds)\n   */\n  staleTime?: number\n\n  /**\n   * Time in ms after which, once the data is no longer being used, it will be\n   * garbage collected to free resources. Set to `false` to disable garbage\n   * collection.\n   *\n   * @default 300_000 (5 minutes)\n   */\n  gcTime?: number | false\n\n  /**\n   * Whether to refetch the query when the component is mounted.\n   * @default true\n   */\n  refetchOnMount?: MaybeRefOrGetter<RefetchOnControl>\n\n  /**\n   * Whether to refetch the query when the window regains focus.\n   * @default true\n   */\n  refetchOnWindowFocus?: MaybeRefOrGetter<RefetchOnControl>\n\n  /**\n   * Whether to refetch the query when the network reconnects.\n   * @default true\n   */\n  refetchOnReconnect?: MaybeRefOrGetter<RefetchOnControl>\n\n  /**\n   * A placeholder data that is initially shown while the query is loading for\n   * the first time. This will also show the `status` as `success` until the\n   * query finishes loading (no matter the outcome of the query). Note: unlike\n   * with `initialData`, the placeholder does not change the cache state.\n   */\n  placeholderData?: (previousData: unknown, previousEntry: UseQueryEntry | undefined) => any // any allows us to not worry about the types when merging options\n\n  /**\n   * Whether to catch errors during SSR (onServerPrefetch) when the query fails.\n   * @default false\n   */\n  ssrCatchError?: boolean\n}\n\n/**\n * Context object passed to the `query` function of `useQuery()`.\n * @see {@link UseQueryOptions}\n */\nexport interface UseQueryFnContext<\n  TData = unknown,\n  TError = unknown,\n  // allows for UseQueryEntry to have unknown everywhere (generic version)\n  TDataInitial extends TData | undefined = unknown extends TData ? unknown : undefined,\n> {\n  /**\n   * `AbortSignal` instance attached to the query call. If the call becomes\n   * outdated (e.g. due to a new call with the same key), the signal will be\n   * aborted.\n   */\n  signal: AbortSignal\n\n  /**\n   * The query entry associated with the current query.\n   */\n  entry: UseQueryEntry<TData, TError, TDataInitial>\n}\n\n/**\n * Type-only symbol to keep the type\n *\n * @internal\n */\nexport declare const tErrorSymbol: unique symbol\n\n/**\n * Helper function type to keep callback arguments bivariant in object properties.\n *\n * @internal\n */\ntype BivariantCallback<TArgs extends readonly unknown[], TResult> = {\n  bivarianceHack(...args: TArgs): TResult\n}['bivarianceHack']\n\n/**\n * Options for `useQuery()`. Can be extended by plugins.\n *\n * @example\n * ```ts\n * // use-query-plugin.d.ts\n * export {} // needed\n * declare module '@pinia/colada' {\n *   interface UseQueryOptions {\n *     // Whether to refresh the data when the component is mounted.\n *     refreshOnMount?: boolean\n *   }\n * }\n * ```\n */\nexport interface UseQueryOptions<\n  TData = unknown,\n  // eslint-disable-next-line unused-imports/no-unused-vars\n  TError = ErrorDefault,\n  TDataInitial extends TData | undefined = undefined,\n> extends Pick<\n  UseQueryOptionsGlobal,\n  | 'gcTime'\n  | 'enabled'\n  | 'refetchOnMount'\n  | 'refetchOnReconnect'\n  | 'refetchOnWindowFocus'\n  | 'staleTime'\n  | 'ssrCatchError'\n> {\n  /**\n   * The key used to identify the query. Array of primitives **without**\n   * reactive values or a reactive array or getter. It should be treaded as an\n   * array of dependencies of your queries, e.g. if you use the\n   * `route.params.id` property, it should also be part of the key:\n   *\n   * ```ts\n   * import { useRoute } from 'vue-router'\n   * import { useQuery } from '@pinia/colada'\n   *\n   * const route = useRoute()\n   * const { data } = useQuery({\n   *   // pass a getter function (or computed, ref, etc.) to ensure reactivity\n   *   key: () => ['user', route.params.id],\n   *   query: () => fetchUser(route.params.id),\n   * })\n   * ```\n   */\n  key: MaybeRefOrGetter<EntryKey>\n\n  /**\n   * The function that will be called to fetch the data. It **must** be async.\n   */\n  query(\n    // NOTE: we can't use TData in the argument because it's used from the return type\n    // https://github.com/microsoft/TypeScript/issues/49618\n    // https://github.com/microsoft/TypeScript/issues/47599\n    context: UseQueryFnContext<unknown, TError, TDataInitial>,\n  ): Promise<TData>\n\n  /**\n   * The data which is initially set to the query while the query is loading\n   * for the first time. Note: unlike with {@link placeholderData}, setting the\n   * initial data changes the state of the query (it will be set to `success`).\n   *\n   * @see {@link placeholderData}\n   */\n  initialData?: () => TDataInitial\n\n  /**\n   * The timestamp (in milliseconds) when the initial data was last updated.\n   * This determines the staleness of the {@link initialData}. If not provided,\n   * defaults to `Date.now()` when initial data is set.\n   *\n   * @default Date.now() when {@link initialData} is used\n   *\n   * @example\n   * ```ts\n   * // Using a static timestamp\n   * useQuery({\n   *   key: ['user'],\n   *   query: () => fetchUser(),\n   *   initialData: () => cachedUser,\n   *   initialDataUpdatedAt: 1234567890000\n   * })\n   *\n   * // Using a function\n   * useQuery({\n   *   key: ['user'],\n   *   query: () => fetchUser(),\n   *   initialData: () => cachedUser,\n   *   initialDataUpdatedAt: () => Number(localStorage.getItem('userTimestamp'))\n   * })\n   * ```\n   */\n  initialDataUpdatedAt?: number | (() => number)\n\n  /**\n   * A placeholder data that is initially shown while the query is loading for\n   * the first time. This will also show the `status` as `success` until the\n   * query finishes loading (no matter the outcome of the query). Note: unlike\n   * with {@link initialData}, the placeholder does not change the cache state.\n   *\n   * @see {@link initialData}\n   */\n  placeholderData?:\n    | NoInfer<TDataInitial>\n    | NoInfer<TData>\n    // NOTE: the generic here allows to make UseQueryOptions<T> assignable to UseQueryOptions<unknown>\n    // https://www.typescriptlang.org/play/?#code/JYOwLgpgTgZghgYwgAgPIAczAPYgM4A8AKsgLzICuIA1iNgO4gB8yA3gFDLICOAXMgAoAlGRYAFKNgC2wPBGJNOydAH5eSrgHpNyABZwAbqADmyMLpRwoxilIjhkAIygQ41PMmBgNyAD6CBdBcjbAo8ABE4MDh+ADlsAEkQGGgFP0oQABMIGFAITJFSFniklKgFIR9tZCJdWWQDaDwcEGR6bCh3Kp1-AWISCAAPSCyPIiZA4JwwyOj+IhJ-KmzckHzCliJKgF92dlBIWEQUAFFwKABPYjIM2gZmNiVsTBa8fgwsXEJx9JAKABt-uxduwYFQEJ9WggAPr2MCXBQCZ6Qt5oF5fNL+P6AoT8M7wq4-DhcFxgChQVqsZDI17IXa7BBfMDIDzkNb0ZAAZQgYAI+MuE0qeAAdHBMpkBDC4ZcBMSuDx+HA8BcQAhBBtkAAWABMABofOh+AIQBrWgBCNkA-7IFTIVoAKmQ2uQ-E1wKElSAA\n    | BivariantCallback<\n        [\n          previousData: TData | undefined,\n          previousEntry: UseQueryEntry<TData, TError, TDataInitial> | undefined,\n        ],\n        NoInfer<TDataInitial> | NoInfer<TData> | undefined\n      >\n\n  /**\n   * Meta information associated with the query. Can be a raw object, a function\n   * returning the meta object, or a ref containing the meta object.\n   * The meta is resolved when the entry is **created** and stored in\n   * `entry.meta`.\n   *\n   * **Note**: Meta is serialized during SSR, so it must be serializable (no functions,\n   * class instances, or circular references). You can also completely ignore\n   * it during SSR with a ternary: `meta: import.meta.ev.SSR ? {} : actualMeta`\n   *\n   * @example\n   * ```ts\n   * // SSR-safe: simple serializable data\n   * useQuery({\n   *   key: ['user', id],\n   *   query: () => fetchUser(id),\n   *   meta: { errorMessage: true }\n   * })\n   *\n   * // Using a function to compute meta\n   * useQuery({\n   *   key: ['user', id],\n   *   query: () => fetchUser(id),\n   *   meta: () => ({ timestamp: Date.now() })\n   * })\n   *\n   * // Skipping meta during SSR\n   * useQuery({\n   *   key: ['user', id],\n   *   query: () => fetchUser(id),\n   *   meta: {\n   *     onError: import.meta.env.SSR ? undefined : ((err) => console.log('error'))\n   *   }\n   * })\n   * ```\n   */\n  meta?: MaybeRefOrGetter<QueryMeta>\n\n  /**\n   * Ghost property to ensure TError generic parameter is included in the\n   * interface structure. This property should never be used directly and is\n   * only for type system correctness. it could be removed in the future if the\n   * type can be inferred in any other way.\n   *\n   * @internal\n   */\n  readonly [tErrorSymbol]?: TError\n}\n\n/**\n * Default options for `useQuery()`. Modifying this object will affect all the queries that don't override these\n */\nexport const USE_QUERY_DEFAULTS = {\n  staleTime: 1000 * 5, // 5 seconds\n  gcTime: (1000 * 60 * 5) as NonNullable<UseQueryOptions['gcTime']>, // 5 minutes\n  // avoid type narrowing to `true`\n  refetchOnWindowFocus: true as NonNullable<UseQueryOptions['refetchOnWindowFocus']>,\n  refetchOnReconnect: true as NonNullable<UseQueryOptions['refetchOnReconnect']>,\n  refetchOnMount: true as NonNullable<UseQueryOptions['refetchOnMount']>,\n  enabled: true as MaybeRefOrGetter<boolean>,\n} satisfies UseQueryOptionsGlobal\n\nexport type UseQueryOptionsWithDefaults<\n  TData = unknown,\n  TError = ErrorDefault,\n  TDataInitial extends TData | undefined = undefined,\n> = UseQueryOptions<TData, TError, TDataInitial> & typeof USE_QUERY_DEFAULTS\n\n/**\n * Global default options for `useQuery()`.\n * @internal\n */\nexport type UseQueryOptionsGlobalDefaults = Pick<\n  UseQueryOptionsGlobal,\n  | 'gcTime'\n  | 'enabled'\n  | 'refetchOnMount'\n  | 'refetchOnReconnect'\n  | 'refetchOnWindowFocus'\n  | 'staleTime'\n  | 'ssrCatchError'\n> &\n  typeof USE_QUERY_DEFAULTS\n\nexport const USE_QUERY_OPTIONS_KEY: InjectionKey<UseQueryOptionsGlobalDefaults> =\n  process.env.NODE_ENV !== 'production' ? Symbol('useQueryOptions') : Symbol()\n\n/**\n * Injects the global query options.\n *\n * @internal\n */\nexport const useQueryOptions = (): UseQueryOptionsGlobalDefaults =>\n  inject(USE_QUERY_OPTIONS_KEY, USE_QUERY_DEFAULTS)\n","import { defineStore, getActivePinia, skipHydrate } from 'pinia'\nimport {\n  effectScope,\n  getCurrentInstance,\n  getCurrentScope,\n  hasInjectionContext,\n  markRaw,\n  shallowRef,\n  toValue,\n  watch,\n  triggerRef,\n} from 'vue'\nimport type { App, ComponentInternalInstance, EffectScope, ShallowRef } from 'vue'\nimport type { AsyncStatus, DataState } from './data-state'\nimport type { EntryKeyTagged, EntryKey } from './entry-keys'\nimport { useQueryOptions } from './query-options'\nimport type { UseQueryOptions, UseQueryOptionsWithDefaults } from './query-options'\nimport type { EntryFilter } from './entry-filter'\nimport { find, START_EXT, toCacheKey } from './entry-keys'\nimport type { ErrorDefault, QueryMeta } from './types-extension'\nimport { toValueWithArgs, warnOnce } from './utils'\n\n/**\n * Allows defining extensions to the query entry that are returned by `useQuery()`.\n */\n\nexport interface UseQueryEntryExtensions<\n  TData,\n  /* eslint-disable-next-line unused-imports/no-unused-vars */\n  TError,\n  /* eslint-disable-next-line unused-imports/no-unused-vars */\n  TDataInitial extends TData | undefined = undefined,\n> {}\n\n/**\n * NOTE: Entries could be classes but the point of having all functions within the store is to allow plugins to hook\n * into actions.\n */\n\n/**\n * A query entry in the cache.\n */\nexport interface UseQueryEntry<\n  TData = unknown,\n  TError = unknown,\n  // allows for UseQueryEntry to have unknown everywhere (generic version)\n  TDataInitial extends TData | undefined = unknown extends TData ? unknown : undefined,\n> {\n  /**\n   * The state of the query. Contains the data, error and status.\n   */\n  state: ShallowRef<DataState<TData, TError, TDataInitial>>\n\n  /**\n   * A placeholder `data` that is initially shown while the query is loading for the first time. This will also show the\n   * `status` as `success` until the query finishes loading (no matter the outcome).\n   */\n  placeholderData: TDataInitial | TData | null | undefined\n\n  /**\n   * The status of the query.\n   */\n  asyncStatus: ShallowRef<AsyncStatus>\n\n  /**\n   * When was this data set in the entry for the last time in ms. It can also\n   * be 0 if the entry has been invalidated.\n   */\n  when: number\n\n  /**\n   * The serialized key associated with this query entry.\n   */\n  key: EntryKey\n\n  /**\n   * Seriaized version of the key. Used to retrieve the entry from the cache.\n   */\n  keyHash: string\n\n  /**\n   * Components and effects scopes that use this query entry.\n   */\n  deps: Set<EffectScope | ComponentInternalInstance>\n\n  /**\n   * Timeout id that scheduled a garbage collection. It is set here to clear it when the entry is used by a different component\n   */\n  gcTimeout: ReturnType<typeof setTimeout> | undefined\n\n  /**\n   * The current pending request.\n   */\n  pending: null | {\n    /**\n     * The abort controller used to cancel the request and which `signal` is passed to the query function.\n     */\n    abortController: AbortController\n    /**\n     * The promise created by `queryCache.fetch` that is currently pending.\n     */\n    refreshCall: Promise<DataState<TData, TError, TDataInitial>>\n    /**\n     * When was this `pending` object created.\n     */\n    when: number\n  }\n\n  /**\n   * Options used to create the query. They can be `null` during hydration but are needed for fetching. This is why\n   * `store.ensure()` sets this property. Note these options might be shared by multiple query entries when the key is\n   * dynamic and that's why some methods like {@link fetch} receive the options as an argument.\n   */\n  options: UseQueryOptionsWithDefaults<TData, TError, TDataInitial> | null\n\n  /**\n   * Whether the data is stale or not, requires `options.staleTime` to be set.\n   */\n  readonly stale: boolean\n\n  /**\n   * Whether the query is currently being used by a Component or EffectScope (e.g. a store).\n   */\n  readonly active: boolean\n\n  /**\n   * Resolved meta information for this query. This is the computed value\n   * from options.meta (function/ref resolved to raw object).\n   */\n  meta: QueryMeta\n\n  /**\n   * Extensions to the query entry added by plugins. You should only add\n   * properties to the object, not replace it.\n   */\n  readonly ext: UseQueryEntryExtensions<TData, TError, TDataInitial>\n\n  /**\n   * Internal property used in development to detect when a component with an\n   * active query was hot-updated and invalidate the entry. For each component\n   * type (keyed by `__hmrId`) we remember the identity of its `setup` and\n   * `render` functions; a real HMR reload replaces these references while a\n   * plain remount of the same component keeps them identical. Keying by\n   * `__hmrId` is required because multiple distinct component types can share\n   * the same query key — without it, alternating mounts would ping-pong a\n   * single snapshot and falsely invalidate the shared entry.\n   *\n   * @internal\n   */\n  __hmr?: {\n    /**\n     * Identity of the `setup` and `render` functions last seen for each\n     * component type (keyed by `__hmrId`) that uses this entry.\n     */\n    components: Map<string, { setup: unknown; render: unknown }>\n  }\n}\n\n/**\n * Keep track of the entry being defined so we can add the queries in ensure\n * this allows us to refresh the entry when a defined query is used again\n * and refetchOnMount is true\n *\n * @internal\n */\nexport let currentDefineQueryEntry: DefineQueryEntry | undefined | null\n\n/**\n * Returns whether the entry is using a placeholder data.\n *\n * @template TDataInitial - Initial data type\n * @param entry - entry to check\n */\nexport function isEntryUsingPlaceholderData<TDataInitial>(\n  entry: UseQueryEntry<unknown, unknown, TDataInitial> | undefined | null,\n): entry is UseQueryEntry<unknown, unknown, TDataInitial> & { placeholderData: TDataInitial } {\n  return entry?.placeholderData != null && entry.state.value.status === 'pending'\n}\n\n/**\n * Filter object to get entries from the query cache.\n *\n * @see {@link QueryCache.getEntries}\n * @see {@link QueryCache.cancelQueries}\n * @see {@link QueryCache#invalidateQueries}\n */\nexport type UseQueryEntryFilter = EntryFilter<UseQueryEntry>\n\n/**\n * UseQueryEntry method to serialize the entry to JSON.\n *\n * @param entry - entry to serialize\n * @returns Serialized version of the entry\n */\nexport const queryEntry_toJSON: <TData, TError>(\n  entry: UseQueryEntry<TData, TError>,\n) => UseQueryEntryNodeValueSerializd<TData, TError> = ({ state: { value }, when, meta }) => [\n  value.data,\n  value.error,\n  // because of time zones, we create a relative time\n  when ? Date.now() - when : -1,\n  meta,\n]\n// TODO: errors are not serializable by default. We should provide a way to serialize custom errors and, by default provide one that serializes the name and message\n\n/**\n * UseQueryEntry method to serialize the entry to a string.\n *\n * @internal\n * @param entry - entry to serialize\n * @returns Stringified version of the entry\n */\nexport const queryEntry_toString: <TData, TError>(entry: UseQueryEntry<TData, TError>) => string = (\n  entry,\n) => String(queryEntry_toJSON(entry))\n\n/**\n * The id of the store used for queries.\n * @internal\n */\nexport const QUERY_STORE_ID = '_pc_query'\n\n/**\n * A query entry that is defined with {@link defineQuery}.\n * @internal\n */\ntype DefineQueryEntry = [\n  lastEnsuredEntries: UseQueryEntry[],\n  returnValue: unknown,\n  effect: EffectScope,\n  paused: ShallowRef<boolean>,\n]\n\n/**\n * Composable to get the cache of the queries. As any other composable, it can\n * be used inside the `setup` function of a component, within another\n * composable, or in injectable contexts like stores and navigation guards.\n */\nexport const useQueryCache = /* @__PURE__ */ defineStore(QUERY_STORE_ID, ({ action }) => {\n  // We have two versions of the cache, one that track changes and another that doesn't so the actions can be used\n  // inside computed properties\n  const cachesRaw = new Map<string, UseQueryEntry<unknown, unknown, unknown>>()\n  const caches = skipHydrate(shallowRef(cachesRaw))\n\n  if (process.env.NODE_ENV !== 'production') {\n    watch(\n      () => caches.value !== cachesRaw,\n      (isDifferent) => {\n        if (isDifferent) {\n          console.error(\n            `[@pinia/colada] The query cache cannot be directly set, it must be modified only. This will fail on production`,\n          )\n        }\n      },\n    )\n  }\n\n  // this version of the cache cannot be hydrated because it would miss all of the actions\n  // and plugins won't be able to hook into entry creation and fetching\n  // this allows use to attach reactive effects to the scope later on\n  const scope = getCurrentScope()!\n  const app: App<unknown> =\n    // @ts-expect-error: internal\n    getActivePinia()!._a\n\n  if (process.env.NODE_ENV !== 'production') {\n    if (!hasInjectionContext()) {\n      warnOnce(\n        `useQueryCache() was called outside of an injection context (component setup, store, navigation guard) You will get a warning about \"inject\" being used incorrectly from Vue. Make sure to use it only in allowed places.\\n` +\n          `See https://vuejs.org/guide/reusability/composables.html#usage-restrictions`,\n      )\n    }\n  }\n\n  const optionDefaults = useQueryOptions()\n\n  /**\n   * Creates a new query entry in the cache. Shouldn't be called directly.\n   *\n   * @param key - Serialized key of the query\n   * @param [options] - options attached to the query\n   * @param [initialData] - initial data of the query if any\n   * @param [error] - initial error of the query if any\n   * @param [when] - relative when was the data or error fetched (will be substracted to Date.now())\n   * @param [meta] - resolved meta information for the query\n   */\n  const create = action(\n    <TData, TError, TDataInitial extends TData | undefined>(\n      key: EntryKey,\n      options: UseQueryOptionsWithDefaults<TData, TError, TDataInitial> | null = null,\n      initialData?: TDataInitial,\n      error: TError | null = null,\n      when: number = 0,\n      meta: QueryMeta = {},\n      // when: number = initialData === undefined ? 0 : Date.now(),\n    ): UseQueryEntry<TData, TError, TDataInitial> =>\n      scope.run(() => {\n        const state = shallowRef<DataState<TData, TError, TDataInitial>>(\n          // @ts-expect-error: to make the code shorter we are using one declaration instead of multiple ternaries\n          {\n            // NOTE: we could move the `initialData` parameter before `options` and make it required\n            // but that would force `create` call in `setQueryData` to pass an extra `undefined` argument\n            data: initialData as TDataInitial,\n            error,\n            status: error ? 'error' : initialData !== undefined ? 'success' : 'pending',\n          },\n        )\n        const asyncStatus = shallowRef<AsyncStatus>('idle')\n        // we markRaw to avoid unnecessary vue traversal\n        return markRaw<UseQueryEntry<TData, TError, TDataInitial>>({\n          key,\n          keyHash: toCacheKey(key),\n          state,\n          placeholderData: null,\n          when: initialData === undefined ? 0 : Date.now() - when,\n          asyncStatus,\n          pending: null,\n          // this set can contain components and effects and worsen the performance\n          // and create weird warnings\n          deps: markRaw(new Set()),\n          gcTimeout: undefined,\n          // eslint-disable-next-line ts/ban-ts-comment\n          // @ts-ignore: some plugins are adding properties to the entry type\n          ext: START_EXT,\n          options,\n          meta,\n          get stale() {\n            return !this.options || !this.when || Date.now() >= this.when + this.options.staleTime\n          },\n          get active() {\n            return this.deps.size > 0\n          },\n        } satisfies UseQueryEntry<TData, TError, TDataInitial>)\n      })!,\n  )\n\n  const defineQueryMap = new WeakMap<() => unknown, DefineQueryEntry>()\n\n  /**\n   * Ensures a query created with {@link defineQuery} is present in the cache. If it's not, it creates a new one.\n   * @param fn - function that defines the query\n   */\n  const ensureDefinedQuery = action(<T>(fn: () => T) => {\n    let defineQueryEntry = defineQueryMap.get(fn)\n    if (!defineQueryEntry) {\n      // create the entry first\n      currentDefineQueryEntry = defineQueryEntry = scope.run(() => [\n        [],\n        null,\n        effectScope(),\n        shallowRef(false),\n      ])!\n\n      // then run it so it can add the queries to the entry\n      // we use the app context for injections and the scope for effects\n      defineQueryEntry[1] = app.runWithContext(() => defineQueryEntry![2].run(fn)!)\n      currentDefineQueryEntry = null\n      defineQueryMap.set(fn, defineQueryEntry)\n    } else {\n      // ensure the scope is active so effects computing inside `useQuery()` run (e.g. the entry computed)\n      defineQueryEntry[2].resume()\n      defineQueryEntry[3].value = false\n      // if the entry already exists, we know the queries inside\n      // we should consider as if they are activated again\n      defineQueryEntry[0] = defineQueryEntry[0].map((oldEntry) =>\n        // the entries' key might have changed (e.g. Nuxt navigation)\n        // so we need to ensure them again\n        oldEntry.options ? ensure(oldEntry.options, oldEntry) : oldEntry,\n      )\n    }\n\n    return defineQueryEntry\n  })\n\n  /**\n   * Tracks an effect or component that uses a query.\n   *\n   * @param entry - the entry of the query\n   * @param effect - the effect or component to untrack\n   *\n   * @see {@link untrack}\n   */\n  function track(\n    entry: UseQueryEntry,\n    effect: EffectScope | ComponentInternalInstance | null | undefined,\n  ) {\n    if (!effect) return\n    entry.deps.add(effect)\n    // clearTimeout ignores anything that isn't a timerId\n    clearTimeout(entry.gcTimeout)\n    entry.gcTimeout = undefined\n    triggerRef(caches)\n  }\n\n  /**\n   * Untracks an effect or component that uses a query.\n   *\n   * @param entry - the entry of the query\n   * @param effect - the effect or component to untrack\n   *\n   * @see {@link track}\n   */\n  function untrack(\n    entry: UseQueryEntry,\n    effect: EffectScope | ComponentInternalInstance | undefined | null,\n  ) {\n    // avoid clearing an existing timeout\n    if (!effect || !entry.deps.has(effect)) return\n\n    entry.deps.delete(effect)\n    triggerRef(caches)\n\n    scheduleGarbageCollection(entry)\n  }\n\n  function scheduleGarbageCollection(entry: UseQueryEntry) {\n    // schedule a garbage collection if the entry is not active\n    // and we know its gcTime value\n    if (entry.deps.size > 0 || !entry.options) return\n    clearTimeout(entry.gcTimeout)\n    // only abort if the query hasn't settled yet because entry.pending might\n    // still be set (cleared in .finally()) but the state is already\n    // success/error\n    if (entry.state.value.status === 'pending') {\n      entry.pending?.abortController.abort()\n    }\n    // avoid setting a timeout with false, Infinity or NaN\n    if ((Number.isFinite as (val: unknown) => val is number)(entry.options.gcTime)) {\n      entry.gcTimeout = setTimeout(() => {\n        remove(entry)\n      }, entry.options.gcTime)\n    }\n  }\n\n  /**\n   * Invalidates and cancel matched queries, and then refetches (in parallel)\n   * all active ones. If you need to further control which queries are\n   * invalidated, canceled, and/or refetched, you can use the filters, you\n   * can direcly call {@link invalidate} on {@link getEntries}:\n   *\n   * ```ts\n   * // instead of doing\n   * await queryCache.invalidateQueries(filters)\n   * await Promise.all(queryCache.getEntries(filters).map(entry => {\n   *   queryCache.invalidate(entry)\n   *   // this is the default behavior of invalidateQueries\n   *   // return entry.active && queryCache.fetch(entry)\n   *   // here to refetch everything, even non active queries\n   *   return queryCache.fetch(entry)\n   * })\n   * ```\n   *\n   * @param filters - filters to apply to the entries\n   * @param refetchActive - whether to refetch active queries or not. Set\n   * to `'all'` to refetch all queries\n   *\n   * @see {@link invalidate}\n   * @see {@link cancel}\n   */\n  const invalidateQueries = action(\n    (filters?: UseQueryEntryFilter, refetchActive: boolean | 'all' = true): Promise<unknown> => {\n      return Promise.all(\n        getEntries(filters).map((entry) => {\n          invalidate(entry)\n          return (\n            (refetchActive === 'all' || (entry.active && refetchActive)) &&\n            toValue(entry.options?.enabled) &&\n            fetch(entry)\n          )\n        }),\n      )\n    },\n  )\n\n  /**\n   * Returns all the entries in the cache that match the filters.\n   *\n   * @param filters - filters to apply to the entries\n   */\n  const getEntries = action((filters: UseQueryEntryFilter = {}): UseQueryEntry[] => {\n    // TODO: Iterator.from(node) in 2028 once widely available? or maybe not worth it\n    return (\n      filters.exact\n        ? filters.key\n          ? [caches.value.get(toCacheKey(filters.key))].filter((v) => !!v)\n          : [] // exact with no key can't match anything\n        : [...find(caches.value, filters.key)]\n    ).filter(\n      (entry) =>\n        (filters.stale == null || entry.stale === filters.stale) &&\n        (filters.active == null || entry.active === filters.active) &&\n        (!filters.status || entry.state.value.status === filters.status) &&\n        (!filters.predicate || filters.predicate(entry)),\n    )\n  })\n\n  /**\n   * Ensures a query entry is present in the cache. If it's not, it creates a\n   * new one. The resulting entry is required to call other methods like\n   * {@link fetch}, {@link refresh}, or {@link invalidate}.\n   *\n   * @param opts - options to create the query\n   * @param previousEntry - the previous entry that was associated with the same options\n   */\n  const ensure = action(\n    <TData = unknown, TError = ErrorDefault, TDataInitial extends TData | undefined = undefined>(\n      opts: UseQueryOptions<TData, TError, TDataInitial>,\n      previousEntry?: UseQueryEntry<TData, TError, TDataInitial>,\n    ): UseQueryEntry<TData, TError, TDataInitial> => {\n      // NOTE: in the code we always pass the options with the defaults but it's convenient\n      // to allow ensure be called with just the user options\n      const options: UseQueryOptionsWithDefaults<TData, TError, TDataInitial> = {\n        ...optionDefaults,\n        ...opts,\n      }\n      const key = toValue(options.key)\n      const keyHash = toCacheKey(key)\n\n      if (process.env.NODE_ENV !== 'production' && keyHash === '[]') {\n        throw new Error(\n          `useQuery() was called with an empty array as the key. It must have at least one element.`,\n        )\n      }\n\n      // do not reinitialize the entry\n      // because of the immediate watcher in useQuery, the `ensure()` action is called twice on mount\n      // we return early to avoid pushing to currentDefineQueryEntry\n      if (previousEntry && keyHash === previousEntry.keyHash) {\n        // with defineQueryOptions fn syntax, we need to update the options\n        previousEntry.options = options\n        return previousEntry\n      }\n\n      // Since ensure() is called within a computed, we cannot let Vue track cache, so we use the raw version instead\n      let entry = cachesRaw.get(keyHash) as UseQueryEntry<TData, TError, TDataInitial> | undefined\n      // ensure the state\n      if (!entry) {\n        // Resolve the meta from options.meta (could be function, ref, or raw object)\n\n        const initialDataUpdatedAt = toValue(options.initialDataUpdatedAt)\n\n        cachesRaw.set(\n          keyHash,\n          (entry = create(\n            key,\n            options,\n            options.initialData?.(),\n            null,\n            initialDataUpdatedAt != null ? Date.now() - initialDataUpdatedAt : 0,\n            toValue(options.meta),\n          )),\n        )\n        // the placeholderData is only used if the entry is initially loading\n        if (options.placeholderData && entry.state.value.status === 'pending') {\n          entry.placeholderData = toValueWithArgs(\n            options.placeholderData,\n            // pass the previous entry placeholder data if it was in placeholder state\n            isEntryUsingPlaceholderData(previousEntry)\n              ? previousEntry.placeholderData\n              : previousEntry?.state.value.data,\n            previousEntry,\n          )\n        }\n        triggerRef(caches)\n      }\n\n      // during HMR, staleTime could be long and if we change the query function, the query won't trigger a refetch\n      // so we need to detect and trigger just in case. Vue's HMR reload mutates the component options object in place\n      // and swaps `setup`/`render` with new function references while keeping `__hmrId` stable. Comparing the function\n      // references lets us distinguish a real hot-update (invalidate) from a plain remount of the same component\n      // (skip) — remounting the same component across ticks in a `v-for` must not cancel the shared pending request.\n      // See https://github.com/posva/pinia-colada/issues/569.\n      if (process.env.NODE_ENV !== 'production') {\n        const currentInstance = getCurrentInstance()\n        if (currentInstance) {\n          const type = currentInstance.type as {\n            __hmrId?: string\n            setup?: unknown\n            render?: unknown\n          }\n          if (type.__hmrId) {\n            const components = (entry.__hmr ??= { components: new Map() }).components\n            const prev = components.get(type.__hmrId)\n            if (prev && (prev.setup !== type.setup || prev.render !== type.render)) {\n              invalidate(entry)\n            }\n            components.set(type.__hmrId, { setup: type.setup, render: type.render })\n          }\n        }\n      }\n\n      // we set it every time to ensure we are using up to date key getters and others options\n      entry.options = options\n\n      // extend the entry with plugins the first time only\n      if (entry.ext === START_EXT) {\n        ;(entry as { ext: object }).ext = {}\n        extend(entry)\n      }\n\n      // if this query was defined within a defineQuery call, add it to the list\n      currentDefineQueryEntry?.[0].push(entry)\n\n      return entry\n    },\n  )\n\n  /**\n   * Action called when an entry is ensured for the first time to allow plugins to extend it.\n   *\n   * @param _entry - the entry of the query to extend\n   */\n  const extend = action(\n    <TData = unknown, TError = ErrorDefault, TDataInitial extends TData | undefined = undefined>(\n      _entry: UseQueryEntry<TData, TError, TDataInitial>,\n    ) => {},\n  )\n\n  /**\n   * Invalidates and cancels a query entry. It effectively sets the `when`\n   * property to `0` and {@link cancel | cancels} the pending request.\n   *\n   * @param entry - the entry of the query to invalidate\n   *\n   * @see {@link cancel}\n   */\n  const invalidate = action((entry: UseQueryEntry) => {\n    // will force a fetch next time\n    entry.when = 0\n    // ignores the pending query\n    cancel(entry)\n  })\n\n  /**\n   * Ensures the current data is fresh. If the data is stale or if the status\n   * is 'error', calls {@link fetch}, if not return the current data. Can only\n   * be called if the entry has been initialized with `useQuery()` and has\n   * options.\n   *\n   * @param entry - the entry of the query to refresh\n   * @param options - the options to use for the fetch\n   *\n   * @see {@link fetch}\n   */\n  const refresh = action(\n    async <TData, TError, TDataInitial extends TData | undefined>(\n      entry: UseQueryEntry<TData, TError, TDataInitial>,\n      options = entry.options,\n    ): Promise<DataState<TData, TError, TDataInitial>> => {\n      if (process.env.NODE_ENV !== 'production' && !options) {\n        throw new Error(\n          `\"entry.refresh()\" was called but the entry has no options. This is probably a bug, report it to pinia-colada with a boiled down example to reproduce it. Thank you!`,\n        )\n      }\n\n      if (entry.state.value.error || entry.stale) {\n        return entry.pending?.refreshCall ?? fetch(entry, options)\n      }\n\n      return entry.state.value\n    },\n  )\n\n  /**\n   * Fetch an entry. Ignores fresh data and triggers a new fetch. Can only be called if the entry has options.\n   *\n   * @param entry - the entry of the query to fetch\n   * @param options - the options to use for the fetch\n   */\n  const fetch = action(\n    async <TData, TError, TDataInitial extends TData | undefined>(\n      entry: UseQueryEntry<TData, TError, TDataInitial>,\n      options = entry.options,\n    ): Promise<DataState<TData, TError, TDataInitial>> => {\n      if (process.env.NODE_ENV !== 'production' && !options) {\n        throw new Error(\n          `\"entry.fetch()\" was called but the entry has no options. This is probably a bug, report it to pinia-colada with a boiled down example to reproduce it. Thank you!`,\n        )\n      }\n\n      entry.asyncStatus.value = 'loading'\n\n      const abortController = new AbortController()\n      const { signal } = abortController\n      // Abort any ongoing request without a reason to keep `AbortError` even with\n      // signal.throwIfAborted() in the query function\n      entry.pending?.abortController.abort()\n\n      const pendingCall = (entry.pending = {\n        abortController,\n        // wrapping with async allows us to catch synchronous errors too\n        refreshCall: (async () => options!.query({ signal, entry }))()\n          .then((data) => {\n            if (pendingCall === entry.pending) {\n              setEntryState(entry, {\n                data,\n                error: null,\n                status: 'success',\n              })\n            }\n            return entry.state.value\n          })\n          .catch((error: unknown) => {\n            // we skip updating the state if a new request was made\n            // or if the error is from our own abort signal\n            if (\n              pendingCall === entry.pending &&\n              // does the error come from a different reason than the abort signal?\n              (error !== signal.reason || !signal.aborted)\n            ) {\n              setEntryState(entry, {\n                status: 'error',\n                data: entry.state.value.data,\n                error: error as any,\n              })\n            }\n\n            // always propagate up the error\n            throw error\n            // NOTE: other options included returning an ongoing request if the error was a cancellation but it seems not worth it\n          })\n          .finally(() => {\n            entry.asyncStatus.value = 'idle'\n            if (pendingCall === entry.pending) {\n              entry.pending = null\n              // there are cases when the result is ignored, in that case, we still\n              // do not have a real result so we keep the placeholder data\n              if (entry.state.value.status !== 'pending') {\n                // reset the placeholder data to free up memory\n                entry.placeholderData = null\n              }\n            }\n          }),\n        when: Date.now(),\n      })\n\n      return pendingCall.refreshCall\n    },\n  )\n\n  /**\n   * Cancels an entry's query if it's currently pending. This will effectively abort the `AbortSignal` of the query and any\n   * pending request will be ignored.\n   *\n   * @param entry - the entry of the query to cancel\n   * @param reason - the reason passed to the abort controller\n   */\n  const cancel = action((entry: UseQueryEntry, reason?: unknown) => {\n    entry.pending?.abortController.abort(reason)\n    // eagerly set the status to idle because the abort signal might not\n    // be consumed by the user's query\n    entry.asyncStatus.value = 'idle'\n    entry.pending = null\n  })\n\n  /**\n   * Cancels queries if they are currently pending. This will effectively abort the `AbortSignal` of the query and any\n   * pending request will be ignored.\n   *\n   * @param filters - filters to apply to the entries\n   * @param reason - the reason passed to the abort controller\n   *\n   * @see {@link cancel}\n   */\n  const cancelQueries = action((filters?: UseQueryEntryFilter, reason?: unknown) => {\n    getEntries(filters).forEach((entry) => cancel(entry, reason))\n  })\n\n  /**\n   * Sets the state of a query entry in the cache and updates the\n   * {@link UseQueryEntry['pending']['when'] | `when` property}. This action is\n   * called every time the cache state changes and can be used by plugins to\n   * detect changes.\n   *\n   * @param entry - the entry of the query to set the state\n   * @param state - the new state of the entry\n   */\n  const setEntryState = action(\n    <TData, TError, TDataInitial extends TData | undefined = TData | undefined>(\n      entry: UseQueryEntry<TData, TError, TDataInitial>,\n      // NOTE: NoInfer ensures correct inference of TData and TError\n      state: DataState<NoInfer<TData>, NoInfer<TError>, NoInfer<TDataInitial>>,\n    ) => {\n      entry.state.value = state\n      entry.when = Date.now()\n      // re-evaluate GC needs when the state is updated. One such scenario is\n      // prefetched queries that bypass track/untrack and would never be garbage collected otherwise\n      scheduleGarbageCollection(entry)\n    },\n  )\n\n  /**\n   * Gets a single query entry from the cache based on the key of the query.\n   *\n   * @param key - the key of the query\n   */\n  function get<\n    TData = unknown,\n    TError = ErrorDefault,\n    TDataInitial extends TData | undefined = undefined,\n  >(\n    key: EntryKeyTagged<TData, TError, TDataInitial> | EntryKey,\n  ): UseQueryEntry<TData, TError, TDataInitial> | undefined {\n    return caches.value.get(toCacheKey(key)) as\n      | UseQueryEntry<TData, TError, TDataInitial>\n      | undefined\n  }\n\n  /**\n   * Set the data of a query entry in the cache. It also sets the `status` to `success`.\n   *\n   * @param key - the key of the query\n   * @param data - the new data to set\n   *\n   * @see {@link setEntryState}\n   */\n  const setQueryData = action(\n    <TData = unknown, TError = ErrorDefault, TDataInitial extends TData | undefined = undefined>(\n      key: EntryKeyTagged<TData, TError, TDataInitial> | EntryKey,\n      data:\n        | NoInfer<TData>\n        // a success query cannot have undefined data\n        | Exclude<NoInfer<TDataInitial>, undefined>\n        // but could not be there and therefore have undefined here\n        | ((oldData: TData | TDataInitial | undefined) => TData | Exclude<TDataInitial, undefined>),\n    ) => {\n      const keyHash = toCacheKey(key)\n      let entry = cachesRaw.get(keyHash) as UseQueryEntry<TData, unknown, TDataInitial> | undefined\n\n      // if the entry doesn't exist, we create it to set the data\n      // it cannot be refreshed or fetched since the options\n      // will be missing\n      if (!entry) {\n        cachesRaw.set(keyHash, (entry = create<TData, unknown, TDataInitial>(key)))\n      }\n\n      setEntryState(entry, {\n        // we assume the data accounts for a successful state\n        error: null,\n        status: 'success',\n        data: toValueWithArgs(data, entry.state.value.data),\n      })\n      triggerRef(caches)\n    },\n  )\n\n  /**\n   * Sets the data of all queries in the cache that are children of a key. It\n   * also sets the `status` to `success`. Differently from {@link\n   * setQueryData}, this method recursively sets the data for all queries. This\n   * is why it requires a function to set the data.\n   *\n   * @param filters - filters used to get the entries\n   * @param updater - the function to set the data\n   *\n   * @example\n   * ```ts\n   * // let's suppose we want to optimistically update all contacts in the cache\n   * setQueriesData(['contacts', 'list'], (contactList: Contact[]) => {\n   *   const contactToReplaceIndex = contactList.findIndex(c => c.id === updatedContact.id)\n   *   return contactList.toSpliced(contactToReplaceIndex, 1, updatedContact)\n   * })\n   * ```\n   *\n   * @see {@link setQueryData}\n   */\n  function setQueriesData<TData = unknown>(\n    filters: UseQueryEntryFilter,\n    updater: (previous: TData | undefined) => TData,\n  ): void {\n    for (const entry of getEntries(filters)) {\n      setEntryState(entry, {\n        error: null,\n        status: 'success',\n        data: updater(entry.state.value.data as TData | undefined),\n      })\n    }\n    triggerRef(caches)\n  }\n\n  /**\n   * Gets the data of a query entry in the cache based on the key of the query.\n   *\n   * @param key - the key of the query\n   */\n  function getQueryData<\n    TData = unknown,\n    TError = ErrorDefault,\n    TDataInitial extends TData | undefined = undefined,\n  >(key: EntryKeyTagged<TData, TError, TDataInitial> | EntryKey): TData | TDataInitial | undefined {\n    return caches.value.get(toCacheKey(key))?.state.value.data as TData | TDataInitial | undefined\n  }\n\n  /**\n   * Removes a query entry from the cache.\n   *\n   * @param entry - the entry of the query to remove\n   */\n  const remove = action((entry: UseQueryEntry) => {\n    clearTimeout(entry.gcTimeout)\n    cachesRaw.delete(entry.keyHash)\n    triggerRef(caches)\n  })\n\n  return {\n    caches,\n\n    ensureDefinedQuery,\n    /**\n     * Scope to track effects and components that use the query cache.\n     * @internal\n     */\n    _s: markRaw(scope),\n    setQueryData,\n    setQueriesData,\n    getQueryData,\n\n    invalidateQueries,\n    cancelQueries,\n\n    // Actions for entries\n    invalidate,\n    fetch,\n    refresh,\n    ensure,\n    extend,\n    track,\n    untrack,\n    cancel,\n    create,\n    remove,\n    get,\n    setEntryState,\n    getEntries,\n  }\n})\n\n/**\n * The cache of the queries. It's the store returned by {@link useQueryCache}.\n */\nexport type QueryCache = ReturnType<typeof useQueryCache>\n\n/**\n * Checks if the given object is a query cache. Used in SSR to apply custom serialization.\n *\n * @param cache - the object to check\n *\n * @see {@link QueryCache}\n * @see {@link serializeQueryCache}\n */\nexport function isQueryCache(cache: unknown): cache is QueryCache {\n  return (\n    typeof cache === 'object' &&\n    !!cache &&\n    (cache as Record<string, unknown>).$id === QUERY_STORE_ID\n  )\n}\n\n/**\n * Raw data of a query entry. Can be serialized from the server and used to\n * hydrate the store. Internal because the format is considered an\n * implementation detail that prioritizes size and performance.\n *\n * @internal\n */\nexport type UseQueryEntryNodeValueSerializd<TData = unknown, TError = unknown> = [\n  /**\n   * The data returned by the query.\n   */\n  data: TData | undefined,\n\n  /**\n   * The error thrown by the query.\n   */\n  error: TError | null,\n\n  /**\n   * When was this data fetched the last time in ms\n   */\n  when?: number,\n\n  /**\n   * Meta information associated with the query\n   */\n  meta?: QueryMeta,\n]\n\n/**\n * Hydrates the query cache with the serialized cache. Used during SSR.\n *\n * @param queryCache - query cache\n * @param serializedCache - serialized cache\n */\nexport function hydrateQueryCache(\n  queryCache: QueryCache,\n  serializedCache: Record<string, UseQueryEntryNodeValueSerializd>,\n) {\n  for (const keyHash in serializedCache) {\n    queryCache.caches.set(\n      keyHash,\n      queryCache.create(\n        JSON.parse(keyHash),\n        undefined,\n        // data, error, when, meta\n        ...(serializedCache[keyHash] ?? []),\n      ),\n    )\n  }\n}\n\n/**\n * Serializes the query cache to a compressed version. Used during SSR.\n *\n * @param queryCache - query cache\n */\nexport function serializeQueryCache(\n  queryCache: QueryCache,\n): Record<string, UseQueryEntryNodeValueSerializd> {\n  return Object.fromEntries(\n    // TODO: 2028: directly use .map on the iterator\n    [...queryCache.caches.entries()].map(([keyHash, entry]) => [keyHash, queryEntry_toJSON(entry)]),\n  )\n}\n","import { getCurrentInstance, getCurrentScope, onScopeDispose, toValue } from 'vue'\nimport type { EffectScope } from 'vue'\nimport type { tErrorSymbol, UseQueryOptions } from './query-options'\nimport { useQueryCache } from './query-store'\nimport type { ErrorDefault } from './types-extension'\nimport type { UseQueryReturn } from './use-query'\nimport { useQuery } from './use-query'\nimport { noop } from './utils'\nimport type { _RemoveMaybeRef } from './utils'\n\n/**\n * The current effect scope where the function returned by `defineQuery` is\n * being called. This allows `useQuery()` to know if it should be attached to\n * an effect scope or not\n *\n * @internal\n */\nexport let currentDefineQueryEffect: undefined | EffectScope\n\n/**\n * Options to define a query with `defineQuery()`. Similar to\n * {@link UseQueryOptions} but disallows reactive values as `defineQuery()` is\n * used outside of an effect scope.\n */\nexport type DefineQueryOptions<\n  TData = unknown,\n  TError = ErrorDefault,\n  TDataInitial extends TData | undefined = undefined,\n> = _RemoveMaybeRef<\n  UseQueryOptions<TData, TError, TDataInitial>,\n  typeof tErrorSymbol | 'initialData' | 'placeholderData'\n>\n\n/**\n * Define a query with the given options. Similar to `useQuery(options)` but\n * allows you to reuse **all** of the query state in multiple places. It only\n * allow static values in options. If you need dynamic values, use the function\n * version.\n *\n * @param options - the options to define the query\n *\n * @example\n * ```ts\n * const useTodoList = defineQuery({\n *   key: ['todos'],\n *   query: () => fetch('/api/todos', { method: 'GET' }),\n * })\n * ```\n */\nexport function defineQuery<TData, TError = ErrorDefault>(\n  options: DefineQueryOptions<TData, TError>,\n): () => UseQueryReturn<TData, TError>\n\n/**\n * Define a query with a setup function. Allows to return arbitrary values from\n * the query function, create contextual refs, rename the returned values, etc.\n * The setup function will be called only once, like stores, and **must be\n * synchronous**.\n *\n * @param setup - a function to setup the query\n *\n * @example\n * ```ts\n * const useFilteredTodos = defineQuery(() => {\n *   const todoFilter = ref<'all' | 'finished' | 'unfinished'>('all')\n *   const { data, ...rest } = useQuery({\n *    key: ['todos', { filter: todoFilter.value }],\n *     query: () =>\n *       fetch(`/api/todos?filter=${todoFilter.value}`, { method: 'GET' }),\n *   })\n *   // expose the todoFilter ref and rename data for convenience\n *   return { ...rest, todoList: data, todoFilter }\n * })\n * ```\n */\nexport function defineQuery<T>(setup: () => T): () => T\nexport function defineQuery(optionsOrSetup: DefineQueryOptions | (() => unknown)): () => unknown {\n  const setupFn =\n    typeof optionsOrSetup === 'function' ? optionsOrSetup : () => useQuery(optionsOrSetup)\n\n  let hasBeenEnsured: boolean | undefined\n  // allows pausing the scope when the defined query is no used anymore\n  let refCount = 0\n  return () => {\n    const queryCache = useQueryCache()\n    // preserve any current effect to account for nested usage of these functions\n    const previousEffect = currentDefineQueryEffect\n    const currentScope = getCurrentInstance() || (currentDefineQueryEffect = getCurrentScope())\n\n    const [ensuredEntries, ret, scope, isPaused] = queryCache.ensureDefinedQuery(setupFn)\n\n    // subsequent calls to the composable returned by useQuery will not trigger the `useQuery()`,\n    // this ensures the refetchOnMount option is respected\n    if (hasBeenEnsured) {\n      ensuredEntries.forEach((entry) => {\n        // since defined query can be activated multiple times without executing useQuery,\n        // we need to execute it here too\n        if (entry.options?.refetchOnMount && toValue(entry.options.enabled)) {\n          if (toValue(entry.options.refetchOnMount) === 'always') {\n            // we catch the error to avoid unhandled rejections\n            queryCache.fetch(entry).catch(noop)\n          } else {\n            queryCache.refresh(entry).catch(noop)\n          }\n        }\n      })\n    }\n    hasBeenEnsured = true\n\n    // NOTE: most of the time this should be set, so maybe we should show a dev warning\n    // if it's not set instead\n    //\n    // Because `useQuery()` might already be called before and we might be reusing an existing query\n    // we need to manually track and untrack. When untracking, we cannot use the ensuredEntries because\n    // there might be another component using the defineQuery, so we simply count how many are using it\n    if (currentScope) {\n      refCount++\n      ensuredEntries.forEach((entry) => {\n        queryCache.track(entry, currentScope)\n      })\n      onScopeDispose(() => {\n        ensuredEntries.forEach((entry) => {\n          queryCache.untrack(entry, currentScope)\n        })\n        // if all entries become inactive, we pause the scope\n        // to avoid triggering the effects within useQuery. This immitates the behavior\n        // of a component that unmounts\n        if (--refCount < 1) {\n          scope.pause()\n          isPaused.value = true\n        }\n      })\n    }\n\n    // reset the previous effect\n    currentDefineQueryEffect = previousEffect\n\n    return ret\n  }\n}\n","import type { ComputedRef, Ref, ShallowRef } from 'vue'\nimport {\n  computed,\n  getCurrentInstance,\n  getCurrentScope,\n  isRef,\n  onMounted,\n  onScopeDispose,\n  onServerPrefetch,\n  onUnmounted,\n  toValue,\n  watch,\n} from 'vue'\nimport { IS_CLIENT, useEventListener } from './utils'\nimport type { UseQueryEntry, UseQueryEntryExtensions } from './query-store'\nimport { currentDefineQueryEntry, isEntryUsingPlaceholderData, useQueryCache } from './query-store'\nimport { useQueryOptions } from './query-options'\nimport type { UseQueryOptions, UseQueryOptionsWithDefaults } from './query-options'\nimport type { ErrorDefault } from './types-extension'\nimport { currentDefineQueryEffect } from './define-query'\nimport type { DefineQueryOptions } from './define-query'\nimport type { AsyncStatus, DataState, DataStateStatus, DataState_Success } from './data-state'\n\n/**\n * Return type of `useQuery()`.\n */\nexport interface UseQueryReturn<\n  TData = unknown,\n  TError = ErrorDefault,\n  TDataInitial extends TData | undefined = undefined,\n> extends UseQueryEntryExtensions<TData, TError, TDataInitial> {\n  /**\n   * The state of the query. Contains its data, error, and status.\n   */\n  state: ComputedRef<DataState<TData, TError, TDataInitial>>\n\n  /**\n   * Status of the query. Becomes `'loading'` while the query is being fetched, is `'idle'` otherwise.\n   */\n  asyncStatus: ComputedRef<AsyncStatus>\n\n  /**\n   * The last successful data resolved by the query. Alias for `state.value.data`.\n   *\n   * @see {@link state}\n   */\n  data: ShallowRef<TData | TDataInitial>\n\n  /**\n   * The error rejected by the query. Alias for `state.value.error`.\n   *\n   * @see {@link state}\n   */\n  error: ShallowRef<TError | null>\n\n  /**\n   * The status of the query. Alias for `state.value.status`.\n   *\n   * @see {@link state}\n   * @see {@link DataStateStatus}\n   */\n  status: ShallowRef<DataStateStatus>\n\n  /**\n   * Returns whether the request is still pending its first call. Alias for `status.value === 'pending'`\n   */\n  isPending: ComputedRef<boolean>\n\n  /**\n   * Returns whether the `data` is the `placeholderData`.\n   */\n  isPlaceholderData: ComputedRef<boolean>\n\n  /**\n   * Returns whether the request is currently fetching data. Alias for `asyncStatus.value === 'loading'`\n   */\n  isLoading: ShallowRef<boolean>\n\n  /**\n   * Ensures the current data is fresh. If the data is stale, refetch, if not return as is.\n   *\n   * @param throwOnError - whether to throw an error if the refresh fails. Defaults to `false`\n   * @returns a promise that resolves when the refresh is done\n   */\n  refresh: (throwOnError?: boolean) => Promise<DataState<TData, TError, TDataInitial>>\n\n  /**\n   * Ignores fresh data and triggers a new fetch\n   *\n   * @param throwOnError - whether to throw an error if the fetch fails. Defaults to `false`\n   * @returns a promise that resolves when the fetch is done\n   */\n  refetch: (throwOnError?: boolean) => Promise<DataState<TData, TError, TDataInitial>>\n}\n\n/**\n * Ensures and return a shared query state based on the `key` option.\n *\n * @param options - The options of the query\n *\n * @example\n * ```ts\n * const { state } = useQuery({\n *   key: ['documents'],\n *   query: () => getDocuments(),\n * })\n * ```\n */\nexport function useQuery<\n  TData,\n  TError = ErrorDefault,\n  TDataInitial extends TData | undefined = undefined,\n>(\n  options:\n    | UseQueryOptions<TData, TError, TDataInitial>\n    | (() => DefineQueryOptions<TData, TError, TDataInitial>),\n): UseQueryReturn<TData, TError, TDataInitial>\n\n/**\n * Ensures and return a shared query state based on the `key` option.\n *\n * @param _options - The options of the query\n */\nexport function useQuery<\n  TData,\n  TError = ErrorDefault,\n  TDataInitial extends TData | undefined = undefined,\n>(\n  _options:\n    | UseQueryOptions<TData, TError, TDataInitial>\n    | (() => DefineQueryOptions<TData, TError, TDataInitial>),\n): UseQueryReturn<TData, TError, TDataInitial> {\n  const queryCache = useQueryCache()\n  const optionDefaults = useQueryOptions()\n  const hasCurrentInstance = getCurrentInstance()\n  // this is the effect created by defineQuery in ensureDefinedQuery\n  // it shouldn't be tracked by the query cache otherwise it would never cleanup\n  const defineQueryEffect = currentDefineQueryEntry?.[2]\n  const currentEffect = currentDefineQueryEffect || getCurrentScope()\n  const isPaused = currentDefineQueryEntry?.[3]\n\n  const options = computed<UseQueryOptionsWithDefaults<TData, TError, TDataInitial>>(\n    () =>\n      ({\n        ...optionDefaults,\n        ...toValue(_options),\n      }) satisfies UseQueryOptionsWithDefaults<TData, TError, TDataInitial>,\n  )\n  const enabled = (): boolean => toValue(options.value.enabled)\n\n  // NOTE: here we used to check if the same key was previously called with a different query\n  // but it ended up creating too many false positives and was removed. We could add it back\n  // to at least warn against the cases shown in https://pinia-colada.esm.dev/guide/reusable-queries.html\n\n  // This plain variable is not reactive and allows us to use the currentEntry\n  // without triggering watchers and creating entries. It is used during\n  // unmounting and mounting\n  let lastEntry: UseQueryEntry<TData, TError, TDataInitial>\n  const entry = computed(() =>\n    // NOTE: there should be a `paused` property on the effect later on\n    // if the effect is paused, we don't want to compute the entry because its key\n    // might be referencing undefined values\n    // https://github.com/posva/pinia-colada/issues/227\n    // NOTE: _isPaused isn't reactive which meant that reentering a component\n    // would never recompute the entry, so _isPaused was replaced\n    // this makes the computed depend on nothing initially, but the `watch` on the entry\n    // with immediate: true will trigger it again\n    // https://github.com/posva/pinia-colada/issues/290\n    isPaused?.value // && currentEffect?._isPaused\n      ? lastEntry!\n      : (lastEntry = queryCache.ensure<TData, TError, TDataInitial>(options.value, lastEntry)),\n  )\n  // we compute the entry here and reuse this across\n  lastEntry = entry.value\n\n  // adapter that returns the entry state\n  const errorCatcher = () => entry.value.state.value\n  const refresh = (throwOnError?: boolean) =>\n    queryCache.refresh(entry.value, options.value).catch(\n      // true is not allowed but it works per spec as only callable onRejected are used\n      // https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-performpromisethen\n      // In other words `Promise.rejects('ok').catch(true)` still rejects\n      // anything other than `true` falls back to the `errorCatcher`\n      (throwOnError as false | undefined) || errorCatcher,\n    )\n  const refetch = (throwOnError?: boolean) =>\n    queryCache.fetch(entry.value, options.value).catch(\n      // same as above\n      (throwOnError as false | undefined) || errorCatcher,\n    )\n  const isPlaceholderData = computed(() => isEntryUsingPlaceholderData(entry.value))\n  const state = computed<DataState<TData, TError, TDataInitial>>(() =>\n    isPlaceholderData.value\n      ? ({\n          status: 'success',\n          data: entry.value.placeholderData!,\n          error: null,\n        } satisfies DataState_Success<TData, TDataInitial>)\n      : entry.value.state.value,\n  )\n\n  // TODO: find a way to allow a custom implementation for the returned value\n  const extensions = {} as Record<string, any>\n  for (const key in lastEntry.ext) {\n    extensions[key] = computed<unknown>({\n      get: () =>\n        toValue<unknown>(entry.value.ext[key as keyof UseQueryEntryExtensions<TData, TError>]),\n      set(value) {\n        const target = entry.value.ext[key as keyof UseQueryEntryExtensions<TData, TError>]\n        if (isRef(target)) {\n          ;(target as Ref | ShallowRef).value = value\n        } else {\n          ;(entry.value.ext[key as keyof UseQueryEntryExtensions<TData, TError>] as unknown) = value\n        }\n      },\n    })\n  }\n\n  const queryReturn = {\n    ...(extensions as UseQueryEntryExtensions<TData, TError, TDataInitial>),\n    state,\n\n    status: computed(() => state.value.status),\n    data: computed(() => state.value.data),\n    error: computed(() => entry.value.state.value.error),\n    asyncStatus: computed(() => entry.value.asyncStatus.value),\n\n    isPlaceholderData,\n    isPending: computed(() => state.value.status === 'pending'),\n    isLoading: computed(() => entry.value.asyncStatus.value === 'loading'),\n\n    refresh,\n    refetch,\n  } satisfies UseQueryReturn<TData, TError, TDataInitial>\n\n  if (hasCurrentInstance) {\n    // only happens on server, app awaits this\n    onServerPrefetch(async () => {\n      if (enabled()) await refresh(!options.value.ssrCatchError)\n    })\n  }\n\n  // should we be watching entry\n  // NOTE: this avoids fetching initially during SSR but it could be refactored to only use the watcher\n  let isActive = false\n  if (hasCurrentInstance) {\n    onMounted(() => {\n      isActive = true\n      queryCache.track(lastEntry, hasCurrentInstance)\n    })\n    onUnmounted(() => {\n      // remove instance from Set of refs\n      queryCache.untrack(lastEntry, hasCurrentInstance)\n    })\n  } else {\n    isActive = true\n    if (currentEffect !== defineQueryEffect) {\n      queryCache.track(lastEntry, currentEffect)\n      onScopeDispose(() => {\n        queryCache.untrack(lastEntry, currentEffect)\n      })\n    }\n  }\n\n  watch(\n    entry,\n    (entry, previousEntry) => {\n      if (!isActive) return\n      if (previousEntry) {\n        queryCache.untrack(previousEntry, hasCurrentInstance)\n        queryCache.untrack(previousEntry, currentEffect)\n      }\n      // track the current effect and component\n      queryCache.track(entry, hasCurrentInstance)\n      // if we have acurrent instance we don't track the effect because in Vue each component\n      // has its own scope that is detached\n      if (!hasCurrentInstance && currentEffect !== defineQueryEffect) {\n        queryCache.track(entry, currentEffect)\n      }\n\n      // TODO: does this trigger after unmount?\n      if (enabled()) refresh()\n    },\n    {\n      immediate: true,\n    },\n  )\n\n  // since options can be a getter, enabled might change\n  watch(enabled, (newEnabled) => {\n    // no need to check for the previous value since the watcher will only trigger if the value changed\n    if (newEnabled) refresh()\n  })\n\n  // only happens on client\n  // we could also call fetch instead but forcing a refresh is more interesting\n  if (hasCurrentInstance) {\n    onMounted(() => {\n      if (enabled()) {\n        const refetchControl = toValue(options.value.refetchOnMount)\n        if (refetchControl === 'always') {\n          refetch()\n        } else if (\n          refetchControl ||\n          // always refetch if the query has no real data (even if placeholderData is shown)\n          entry.value.state.value.status === 'pending'\n        ) {\n          refresh()\n        }\n      }\n    })\n  }\n  // TODO: we could save the time it was fetched to avoid fetching again. This is useful to not refetch during SSR app but do refetch in SSG apps if the data is stale. Careful with timers and timezones\n\n  if (IS_CLIENT) {\n    useEventListener(document, 'visibilitychange', () => {\n      const refetchControl = toValue(options.value.refetchOnWindowFocus)\n      if (document.visibilityState === 'visible' && enabled() && entry.value.active) {\n        if (refetchControl === 'always') {\n          refetch()\n        } else if (refetchControl) {\n          refresh()\n        }\n      }\n    })\n\n    useEventListener(window, 'online', () => {\n      if (enabled() && entry.value.active) {\n        const refetchControl = toValue(options.value.refetchOnReconnect)\n        if (refetchControl === 'always') {\n          refetch()\n        } else if (refetchControl) {\n          refresh()\n        }\n      }\n    })\n  }\n\n  return queryReturn\n}\n","import type { DefineQueryOptions } from './define-query'\nimport type { EntryKeyTagged } from './entry-keys'\nimport type { ErrorDefault } from './types-extension'\nimport { useQuery } from './use-query'\n\n/**\n * Tagged version of {@link DefineQueryOptions} that includes a key with\n * data type information.\n */\nexport interface DefineQueryOptionsTagged<\n  TData = unknown,\n  TError = ErrorDefault,\n  TDataInitial extends TData | undefined = undefined,\n> extends DefineQueryOptions<TData, TError, TDataInitial> {\n  key: EntryKeyTagged<TData, TError, TDataInitial>\n}\n\n/**\n * Define dynamic query options by passing a function that accepts an optional\n * arbitrary parameter and returns the query options. Enables type-safe query\n * keys. Pass to {@link useQuery} as a single function:\n * `useQuery(() => setupOptions(params))`.\n *\n * @param setupOptions - A function that returns the query options.\n */\nexport function defineQueryOptions<\n  Params,\n  TData,\n  TError = ErrorDefault,\n  TDataInitial extends TData | undefined = undefined,\n>(\n  setupOptions: (params?: Params) => DefineQueryOptions<TData, TError, TDataInitial>,\n): (params?: Params) => DefineQueryOptionsTagged<TData, TError, TDataInitial>\n\n/**\n * Define dynamic query options by passing a function that accepts an arbitrary\n * parameter and returns the query options. Enables type-safe query keys.\n * Pass to {@link useQuery} as a single function:\n * `useQuery(() => setupOptions(params))`.\n *\n * @param setupOptions - A function that returns the query options.\n */\nexport function defineQueryOptions<\n  Params,\n  TData,\n  TError = ErrorDefault,\n  TDataInitial extends TData | undefined = undefined,\n>(\n  setupOptions: (params: Params) => DefineQueryOptions<TData, TError, TDataInitial>,\n): (params: Params) => DefineQueryOptionsTagged<TData, TError, TDataInitial>\n\n/**\n * Define static query options that are type safe with\n * `queryCache.getQueryData()`. Can be passed directly to {@link useQuery}.\n *\n * @param options - The query options.\n */\nexport function defineQueryOptions<\n  TData,\n  TError = ErrorDefault,\n  TDataInitial extends TData | undefined = undefined,\n>(\n  options: DefineQueryOptions<TData, TError, TDataInitial>,\n): DefineQueryOptionsTagged<TData, TError, TDataInitial>\n\n/**\n * Define type-safe query options. Can be static or dynamic. Define the arguments based\n * on what's needed on the query and the key. Use an object if you need\n * multiple properties.\n *\n * @param setupOrOptions - The query options or a function that returns the query options.\n *\n * @example\n * ```ts\n * import { defineQueryOptions } from '@pinia/colada'\n *\n * const documentDetailsQuery = defineQueryOptions((id: number ) => ({\n *   key: ['documents', id],\n *   query: () => fetchDocument(id),\n * }))\n *\n * queryCache.getQueryData(documentDetailsQuery(4).key) // typed\n * ```\n *\n * @__NO_SIDE_EFFECTS__\n */\nexport function defineQueryOptions<const Options extends DefineQueryOptions, Params>(\n  setupOrOptions: Options | ((params: Params) => Options),\n): Options | ((params: Params) => Options) {\n  return setupOrOptions\n}\n","import type { ComputedRef, MaybeRefOrGetter } from 'vue'\nimport { computed, toValue } from 'vue'\nimport { useQueryCache } from './query-store'\nimport type { UseQueryReturn } from './use-query'\nimport type { EntryKey, EntryKeyTagged } from './entry-keys'\nimport type { AsyncStatus, DataState, DataStateStatus } from './data-state'\nimport type { ErrorDefault } from './types-extension'\n\n/**\n * Return type for the {@link useQueryState} composable.\n *\n * @see {@link useQueryState}\n */\nexport interface UseQueryStateReturn<\n  TData = unknown,\n  TError = ErrorDefault,\n  TDataInitial extends TData | undefined = undefined,\n> {\n  /**\n   * `state` of the query entry.\n   *\n   * @see {@link UseQueryReturn#state}\n   */\n  state: ComputedRef<DataState<TData, TError, TDataInitial> | undefined>\n\n  /**\n   * `data` of the query entry.\n   *\n   * @see {@link UseQueryReturn#data}\n   */\n  data: ComputedRef<TData | TDataInitial | undefined>\n\n  /**\n   * `error` of the query entry.\n   *\n   * @see {@link UseQueryReturn#error}\n   */\n  error: ComputedRef<TError | null | undefined>\n\n  /**\n   * `status` of the query entry.\n   *\n   * @see {@link DataStateStatus}\n   * @see {@link UseQueryReturn#status}\n   */\n  status: ComputedRef<DataStateStatus | undefined>\n\n  /**\n   * `asyncStatus` of the query entry.\n   *\n   * @see {@link AsyncStatus}\n   * @see {@link UseQueryReturn#asyncStatus}\n   */\n  asyncStatus: ComputedRef<AsyncStatus | undefined>\n\n  /**\n   * Is the query entry currently pending or non existent.\n   */\n  isPending: ComputedRef<boolean>\n}\n\n/**\n * Reactive access to the state of a query entry without fetching it.\n *\n * @param key - tagged key of the query entry to access\n */\nexport function useQueryState<\n  TData,\n  TError = ErrorDefault,\n  TDataInitial extends TData | undefined = undefined,\n>(\n  key: MaybeRefOrGetter<EntryKeyTagged<TData, TError, TDataInitial>>,\n): UseQueryStateReturn<TData, TError, TDataInitial>\n\n/**\n * Reactive access to the state of a query entry without fetching it.\n *\n * @param key - key of the query entry to access\n */\nexport function useQueryState<\n  TData,\n  TError = ErrorDefault,\n  TDataInitial extends TData | undefined = undefined,\n>(key: MaybeRefOrGetter<EntryKey>): UseQueryStateReturn<TData, TError, TDataInitial>\n\nexport function useQueryState<\n  TData,\n  TError = ErrorDefault,\n  TDataInitial extends TData | undefined = undefined,\n>(\n  key: MaybeRefOrGetter<EntryKeyTagged<TData, TError, TDataInitial> | EntryKey>,\n): UseQueryStateReturn<TData, TError, TDataInitial> {\n  const queryCache = useQueryCache()\n\n  const entry = computed(() => queryCache.get(toValue(key)))\n\n  const state = computed(() => entry.value?.state.value)\n  const data = computed(() => state.value?.data)\n  const error = computed(() => state.value?.error)\n  const status = computed(() => state.value?.status)\n  const asyncStatus = computed(() => entry.value?.asyncStatus.value)\n  const isPending = computed(() => !state.value || state.value.status === 'pending')\n\n  return {\n    state,\n    data,\n    error,\n    status,\n    asyncStatus,\n    isPending,\n  }\n}\n","import { computed, type EffectScope, shallowRef, toValue, type ShallowRef } from 'vue'\nimport type { tErrorSymbol, UseQueryFnContext, UseQueryOptions } from './query-options'\nimport { useQuery } from './use-query'\nimport type { UseQueryReturn } from './use-query'\nimport type { ErrorDefault } from './types-extension'\nimport { useQueryCache, type QueryCache, type UseQueryEntry } from './query-store'\nimport { noop, toValueWithArgs } from './utils'\nimport type { _RemoveMaybeRef } from './utils'\nimport type { EntryKey, EntryKeyTagged } from './entry-keys'\n\n/**\n * Structure of data stored for infinite queries.\n */\nexport interface UseInfiniteQueryData<TData, TPageParam> {\n  /**\n   * Each page of data fetched in order.\n   */\n  pages: TData[]\n\n  /**\n   * Each page parameter used to fetch the corresponding page in the same order.\n   */\n  pageParams: TPageParam[]\n}\n\nexport interface UseInfiniteQueryFnContext<\n  TData,\n  TError,\n  TDataInitial extends TData | undefined = undefined,\n  TPageParam = unknown,\n> extends UseQueryFnContext<TData, TError, TDataInitial> {\n  /**\n   * The page parameter for the current fetch.\n   */\n  pageParam: TPageParam\n}\n\n/**\n * Options for {@link useInfiniteQuery}.\n *\n */\nexport interface UseInfiniteQueryOptions<\n  TData,\n  TError,\n  TPageParam,\n  TDataInitial extends UseInfiniteQueryData<TData, TPageParam> | undefined,\n> extends Omit<\n  UseQueryOptions<UseInfiniteQueryData<TData, TPageParam>, TError, TDataInitial>,\n  'query' | 'key'\n> {\n  key: UseQueryOptions<UseInfiniteQueryData<TData, TPageParam>, TError, TDataInitial>['key']\n\n  /**\n   * The function that will be called to fetch the data. It **must** be async.\n   */\n  query: (\n    // NOTE: we can't use TData in the argument because it's used from the return type\n    // https://github.com/microsoft/TypeScript/issues/49618\n    // https://github.com/microsoft/TypeScript/issues/47599\n    context: UseInfiniteQueryFnContext<\n      UseInfiniteQueryData<unknown, TPageParam>,\n      TError,\n      TDataInitial,\n      TPageParam\n    >,\n  ) => Promise<TData>\n\n  /**\n   * Initial page parameter or function returning it. It's passed to the query\n   */\n  initialPageParam: TPageParam | (() => TPageParam)\n\n  /**\n   * Maximum number of pages to keep in the cache. Old pages will be removed\n   * from the cache when new pages are added. If not set, all pages will\n   * be kept.\n   */\n  maxPages?: number\n\n  /**\n   * Function to get the next page parameter based on the last page and all\n   * pages fetched so far. If it returns `undefined` or `null`, it will\n   * consider there are no more pages to fetch.\n   */\n  getNextPageParam: (\n    lastPage: NoInfer<TData>,\n    allPages: NoInfer<TData>[],\n    lastPageParam: NoInfer<TPageParam>,\n    allPageParams: NoInfer<TPageParam>[],\n  ) => NoInfer<TPageParam> | undefined | null\n\n  /**\n   * Function to get the previous page parameter based on the first page and\n   * all pages fetched so far. If it returns `undefined` or `null`, it will\n   * consider there are no more pages to fetch.\n   */\n  getPreviousPageParam?: (\n    firstPage: TData,\n    allPages: TData[],\n    firstPageParam: TPageParam,\n    allPageParams: TPageParam[],\n  ) => TPageParam | undefined | null\n\n  // TODO: placeholderData should be adapted to infinite queries\n  // TODO: initialData should be adapted to infinite queries\n}\n\n/**\n * Options to define an infinite query with `defineInfiniteQueryOptions()`.\n * Similar to {@link UseInfiniteQueryOptions} but disallows reactive values.\n */\nexport type DefineInfiniteQueryOptions<\n  TData = unknown,\n  TError = ErrorDefault,\n  TPageParam = unknown,\n  TDataInitial extends UseInfiniteQueryData<TData, TPageParam> | undefined = undefined,\n> = _RemoveMaybeRef<\n  UseInfiniteQueryOptions<TData, TError, TPageParam, TDataInitial>,\n  typeof tErrorSymbol | 'initialData' | 'placeholderData'\n>\n\n/**\n * Options for {@link UseInfiniteQueryReturn.loadNextPage} and\n * {@link UseInfiniteQueryReturn.loadPreviousPage}.\n */\nexport interface UseInfiniteQueryLoadMoreOptions {\n  /**\n   * Whether to throw an error if the fetch fails.\n   *\n   * @default false\n   */\n  throwOnError?: boolean\n\n  /**\n   * Whether to cancel an ongoing refetch when a new one is triggered.\n   * If set to `false`, a new load will be ignored if there's already one in\n   * progress.\n   *\n   * @default true\n   */\n  cancelRefetch?: boolean\n}\n\nexport interface UseInfiniteQueryReturn<\n  TData = unknown,\n  TError = ErrorDefault,\n  TPageParam = unknown,\n  TDataInitial extends UseInfiniteQueryData<TData, TPageParam> | undefined = undefined,\n> extends UseQueryReturn<UseInfiniteQueryData<TData, TPageParam>, TError, TDataInitial> {\n  /**\n   * Whether there is a next page to load. Defined based on the result of\n   * {@link UseInfiniteQueryOptions.getNextPageParam}.\n   */\n  hasNextPage: ShallowRef<boolean>\n\n  /**\n   * Load the next page of data.\n   */\n  loadNextPage: (options?: UseInfiniteQueryLoadMoreOptions) => Promise<unknown>\n\n  /**\n   * Whether there is a previous page to load. Defined based on the result of\n   * {@link UseInfiniteQueryOptions.getPreviousPageParam}.\n   */\n  hasPreviousPage: ShallowRef<boolean>\n\n  /**\n   * Load the previous page of data.\n   * Requires {@link UseInfiniteQueryOptions.getPreviousPageParam} to be defined.\n   */\n  loadPreviousPage: (options?: UseInfiniteQueryLoadMoreOptions) => Promise<unknown>\n}\n\n/**\n * Indicator for which page to load next. 0 means refetch all pages, 1 means\n * next page, -1 means previous page.\n *\n * @internal\n */\ntype NextPageIndicator = 0 | 1 | -1\n\n/**\n * Extensions added to the query entry for infinite queries. These are used to\n * store the next and previous page parameters and whether there are next or\n * previous pages. They are created in the cache when the entry is created and\n * updated when the query is fetched.\n */\ntype UseInfiniteQueryExtensions<TPageParam> = Pick<\n  UseInfiniteQueryReturn,\n  'hasNextPage' | 'hasPreviousPage'\n> & {\n  /**\n   * The next page parameter, computed based on the last page and all pages fetched\n   *\n   * @internal\n   */\n  nextPageParam: ShallowRef<TPageParam | null | undefined>\n\n  /**\n   * The previous page parameter, computed based on the first page and all pages fetched\n   *\n   * @internal\n   */\n  previousPageParam: ShallowRef<TPageParam | null | undefined>\n\n  /**\n   * The next page that will be loaded: 0 for all pages, 1 for next page, and -1 for previous page\n   *\n   * @internal\n   */\n  nextPageIndicator: NextPageIndicator\n}\n\n/**\n * Type guard to check if a query entry is an infinite query entry.\n *\n * @param entry - The query entry to check.\n *\n * @internal\n */\nfunction isInfiniteQueryEntry(\n  entry: UseQueryEntry<unknown, unknown, unknown>,\n): entry is UseQueryEntry<UseInfiniteQueryData<unknown, unknown>, unknown, any> & {\n  ext: UseInfiniteQueryExtensions<unknown>\n} {\n  return !!entry.meta.__i\n}\n\nconst installedMap = new WeakMap()\nfunction PiniaColadaInfiniteQueryPlugin(scope: EffectScope, queryCache: QueryCache) {\n  if (!installedMap.has(queryCache)) {\n    queryCache.$onAction(({ name, args }) => {\n      if (name === 'extend') {\n        const [entry] = args\n        if (isInfiniteQueryEntry(entry)) {\n          scope.run(() => {\n            const nextPageParam = shallowRef<unknown | null | undefined>()\n            const hasNextPage = computed(() => nextPageParam.value != null)\n            const previousPageParam = shallowRef<unknown | null | undefined>()\n            const hasPreviousPage = computed(() => previousPageParam.value != null)\n\n            entry.ext.nextPageParam = nextPageParam\n            entry.ext.hasNextPage = hasNextPage\n            entry.ext.previousPageParam = previousPageParam\n            entry.ext.hasPreviousPage = hasPreviousPage\n            entry.ext.nextPageIndicator = 0\n          })\n        }\n      }\n    }, true)\n\n    installedMap.set(queryCache, true)\n  }\n}\n\n/**\n * Creates the extensions for an infinite query entry. These are used to store the\n * next and previous page parameters and whether there are next or previous pages.\n *\n * @param extensions - The extensions object to create.\n * @internal\n */\nfunction createInfiniteQueryEntryExtensions(extensions: UseInfiniteQueryExtensions<unknown>): void {\n  extensions.nextPageParam = shallowRef<unknown | null | undefined>()\n  extensions.hasNextPage = computed(() => extensions.nextPageParam.value != null)\n  extensions.previousPageParam = shallowRef<unknown | null | undefined>()\n  extensions.hasPreviousPage = computed(() => extensions.previousPageParam.value != null)\n  extensions.nextPageIndicator = 0\n}\n\n/**\n * Sets the data of an infinite query entry in the cache. Unlike {@link QueryCache.setQueryData | `queryCache.setQueryData()`},\n * this function properly marks the entry as an infinite query and initializes the\n * infinite query extensions (`hasNextPage`, `hasPreviousPage`, etc.).\n *\n * Use this when you need to set infinite query data before `useInfiniteQuery()` is mounted\n * (e.g. optimistic updates from a mutation on a different page).\n *\n * @param queryCache - The query cache instance\n * @param key - The key of the infinite query\n * @param data - The data to set, or an updater function\n */\nexport function setInfiniteQueryData<TData = unknown, TError = ErrorDefault, TPageParam = unknown>(\n  queryCache: QueryCache,\n  key: EntryKeyTagged<UseInfiniteQueryData<TData, TPageParam>, TError> | EntryKey,\n  data:\n    | UseInfiniteQueryData<TData, TPageParam>\n    | ((\n        oldData: UseInfiniteQueryData<TData, TPageParam> | undefined,\n      ) => UseInfiniteQueryData<TData, TPageParam>),\n): void {\n  // Register the infinite query plugin (idempotent) so `ensure` creates\n  // the extra properties like hasNextPage, etc\n  PiniaColadaInfiniteQueryPlugin(queryCache._s, queryCache)\n\n  // Delegate to setQueryData for entry creation, state setting, and reactivity\n  queryCache.setQueryData(key, data)\n\n  // Mark the entry as an infinite query so the plugin recognizes it\n  queryCache.get(key)!.meta.__i = 1\n}\n\n/**\n * Store and merge paginated data into a single cache entry. Allows to handle\n * infinite scrolling.\n *\n * @param options - Options to configure the infinite query.\n */\nexport function useInfiniteQuery<\n  TData,\n  TError = ErrorDefault,\n  TPageParam = unknown,\n  TDataInitial extends UseInfiniteQueryData<TData, TPageParam> | undefined = undefined,\n>(\n  options: UseInfiniteQueryOptions<TData, TError, TPageParam, TDataInitial>,\n): UseInfiniteQueryReturn<TData, TError, TPageParam, TDataInitial>\n\n/**\n * Store and merge paginated data into a single cache entry. Allows to handle\n * infinite scrolling. Accepts a getter returning options defined with\n * {@link defineInfiniteQueryOptions}.\n *\n * @param options - A getter that returns the infinite query options.\n */\nexport function useInfiniteQuery<\n  TData,\n  TError = ErrorDefault,\n  TPageParam = unknown,\n  TDataInitial extends UseInfiniteQueryData<TData, TPageParam> | undefined = undefined,\n>(\n  options: () => DefineInfiniteQueryOptions<TData, TError, TPageParam, TDataInitial>,\n): UseInfiniteQueryReturn<TData, TError, TPageParam, TDataInitial>\n\nexport function useInfiniteQuery<\n  TData,\n  TError = ErrorDefault,\n  TPageParam = unknown,\n  TDataInitial extends UseInfiniteQueryData<TData, TPageParam> | undefined = undefined,\n>(\n  options:\n    | UseInfiniteQueryOptions<TData, TError, TPageParam, TDataInitial>\n    // NOTE: not true technically but makes typing easier while being correct\n    | (() => UseInfiniteQueryOptions<TData, TError, TPageParam, TDataInitial>),\n): UseInfiniteQueryReturn<TData, TError, TPageParam, TDataInitial> {\n  const queryCache = useQueryCache()\n  // adds hasNextPage and hasPreviousPage to the entry when it's created in the cache\n  PiniaColadaInfiniteQueryPlugin(queryCache._s, queryCache)\n\n  let entry:\n    | UseQueryEntry<UseInfiniteQueryData<TData, TPageParam>, TError, TDataInitial>\n    | undefined\n\n  const query = useQuery<UseInfiniteQueryData<TData, TPageParam>, TError, TDataInitial>(\n    // @ts-expect-error: FIXME: mismatch with TDataInitial and undefined somewhere\n    () => {\n      const opts = toValueWithArgs(options)\n      const key = toValue(opts.key)\n      entry = queryCache.get(key)\n      // TODO: compute initial values for hasNextPage and hasPreviousPage based on initialData\n      return {\n        ...opts,\n        key,\n        query: async (\n          context: UseQueryFnContext<UseInfiniteQueryData<TData, TPageParam>, TError, TDataInitial>,\n        ) => {\n          const currentEntry = (entry = context.entry)\n          const exts = currentEntry.ext as unknown as UseInfiniteQueryExtensions<TPageParam>\n          const state = currentEntry.state.value\n          const { data } = state\n\n          // result of pages and params\n          let pages: TData[]\n          let pageParams: TPageParam[]\n          let pageParam: TPageParam | null | undefined\n\n          // if we never loaded, consider we want to load the first page\n          if (\n            (state.status === 'pending' ||\n              // edge case: data is empty, we want to fetch normally\n              !data?.pages.length) &&\n            !exts.nextPageIndicator\n          ) {\n            exts.nextPageIndicator = 1\n          }\n\n          const position = exts.nextPageIndicator > 0 ? -1 : 0\n\n          // the status was not pending so this is a manual refetch\n          if (\n            !exts.nextPageIndicator &&\n            // NOTE: at this point data cannot be undefined but this makes TS happy\n            data\n          ) {\n            const pagesToRefetch = data.pages.length\n            pages = []\n            pageParams = []\n\n            // there is at least one page because we check for data.pages.length\n            // above, so there is at least 1 pageParam\n            pageParam = data.pageParams[0]!\n\n            for (let i = 0; i < pagesToRefetch; i++) {\n              // oxlint-disable-next-line: no-await-in-loop\n              const page = await opts.query({\n                ...context,\n                pageParam,\n              })\n\n              // TODO: throw if signal is aborted?\n\n              pages.push(page)\n              pageParams.push(pageParam)\n\n              if (i < pagesToRefetch - 1) {\n                const nextParam = opts.getNextPageParam(page, pages, pageParam, pageParams)\n\n                if (nextParam == null) {\n                  break\n                }\n                pageParam = nextParam\n              }\n            }\n          } else {\n            exts.nextPageIndicator = 0\n\n            if (process.env.NODE_ENV !== 'production') {\n              if (position === 0 && !opts.getPreviousPageParam) {\n                const msg =\n                  '[useInfiniteQuery] Trying to load previous page but `getPreviousPageParam` is not defined in options. This will fail in production.'\n                console.warn(msg)\n                throw new Error(msg)\n              }\n            }\n\n            computePageParams(currentEntry, data)\n\n            pageParam = (position ? exts.nextPageParam : exts.previousPageParam).value\n\n            // there is nothing to load\n            if (pageParam == null && data) {\n              return data\n            }\n\n            pageParam ??= toValue(opts.initialPageParam)\n\n            const page = await opts.query({\n              ...context,\n              pageParam,\n            })\n\n            // TODO: throw if signal is aborted?\n\n            // we create copies to ensure the old versions are preserved\n            // where they are needed (e.g. devtools)\n            pages = data?.pages.slice() ?? []\n            pageParams = data?.pageParams.slice() ?? []\n\n            const arrayMethod = position ? 'push' : 'unshift'\n            pages[arrayMethod](page)\n            pageParams[arrayMethod](pageParam)\n          }\n\n          // Apply maxPages limit\n          if (opts.maxPages && pages.length > opts.maxPages) {\n            if (position) {\n              // Loading next pages - trim from beginning (remove oldest pages)\n              pages.splice(0, pages.length - opts.maxPages)\n              pageParams.splice(0, pageParams.length - opts.maxPages)\n            } else {\n              // Loading previous pages - trim from end (remove newest pages)\n              pages.splice(opts.maxPages)\n              pageParams.splice(opts.maxPages)\n            }\n          }\n\n          computePageParams(currentEntry, { pages, pageParams })\n\n          return { pages, pageParams }\n        },\n\n        meta: {\n          ...toValue(opts.meta),\n          __i: 1,\n        },\n      }\n      // satisfies DefineQueryOptions<UseInfiniteQueryData<TData, TPageParam>, TError, TDataInitial>\n    },\n  )\n\n  function computePageParams(\n    entry: UseQueryEntry<UseInfiniteQueryData<TData, TPageParam>, TError, TDataInitial> | undefined,\n    data = entry?.state.value.data,\n  ) {\n    if (!entry?.options) return\n    const opts = entry.options as unknown as UseInfiniteQueryOptions<\n      TData,\n      TError,\n      TPageParam,\n      TDataInitial\n    >\n    const lastPageParam = data?.pageParams.at(-1)\n    const exts = entry.ext as unknown as UseInfiniteQueryExtensions<TPageParam>\n    exts.nextPageParam.value =\n      data && data.pages.length > 0\n        ? opts.getNextPageParam(data.pages.at(-1)!, data.pages, lastPageParam!, data.pageParams)\n        : null\n\n    const firstPageParam = data?.pageParams.at(0)\n    exts.previousPageParam.value =\n      data && data.pages.length > 0\n        ? opts.getPreviousPageParam?.(\n            data.pages.at(0)!,\n            data.pages,\n            firstPageParam!,\n            data.pageParams,\n          )\n        : null\n  }\n\n  // if we have initial data, we need to set the next and previous page params\n  computePageParams(entry)\n\n  async function loadPage(\n    page: NextPageIndicator,\n    { throwOnError, cancelRefetch = true }: UseInfiniteQueryLoadMoreOptions = {},\n  ): Promise<unknown> {\n    const opts = toValueWithArgs(options)\n    const entry = queryCache.get(toValue(opts.key))\n    if (!entry) {\n      if (process.env.NODE_ENV !== 'production') {\n        console.warn('[useInfiniteQuery] Cannot load next page: query entry not found in cache.')\n      }\n      return null\n    }\n\n    // cancel and reuse\n    if (!cancelRefetch && entry.pending) {\n      return entry.pending.refreshCall\n    }\n\n    ;(entry.ext as unknown as UseInfiniteQueryExtensions<TPageParam>).nextPageIndicator = page\n\n    return queryCache.fetch(entry).catch(throwOnError ? undefined : noop)\n  }\n\n  // @ts-expect-error: the query contains the missing properties\n  // and it's safer to add them in a plugin because they get scoped per entry\n  return {\n    ...query,\n    loadNextPage: (options?: UseInfiniteQueryLoadMoreOptions) => loadPage(1, options),\n    loadPreviousPage: (options?: UseInfiniteQueryLoadMoreOptions) => loadPage(-1, options),\n  }\n}\n","import type {\n  DefineInfiniteQueryOptions,\n  UseInfiniteQueryData,\n  UseInfiniteQueryOptions,\n} from './infinite-query'\nimport type { EntryKeyTagged } from './entry-keys'\nimport type { ErrorDefault } from './types-extension'\nimport { useInfiniteQuery } from './infinite-query'\n\n/**\n * Tagged version of {@link DefineInfiniteQueryOptions} that includes a key with\n * data type information.\n */\nexport interface DefineInfiniteQueryOptionsTagged<\n  TData = unknown,\n  TError = ErrorDefault,\n  TPageParam = unknown,\n  TDataInitial extends UseInfiniteQueryData<TData, TPageParam> | undefined = undefined,\n> extends DefineInfiniteQueryOptions<TData, TError, TPageParam, TDataInitial> {\n  key: EntryKeyTagged<UseInfiniteQueryData<TData, TPageParam>, TError, TDataInitial>\n}\n\n/**\n * Define dynamic infinite query options by passing a function that accepts an\n * optional arbitrary parameter and returns the query options. Enables type-safe\n * query keys. Pass to {@link useInfiniteQuery} as a single function:\n * `useInfiniteQuery(() => setupOptions(params))`.\n *\n * @param setupOptions - A function that returns the infinite query options.\n */\nexport function defineInfiniteQueryOptions<\n  Params,\n  TData,\n  TError = ErrorDefault,\n  TPageParam = unknown,\n  TDataInitial extends UseInfiniteQueryData<TData, TPageParam> | undefined = undefined,\n>(\n  setupOptions: (\n    params?: Params,\n  ) => UseInfiniteQueryOptions<TData, TError, TPageParam, TDataInitial>,\n): (params?: Params) => DefineInfiniteQueryOptionsTagged<TData, TError, TPageParam, TDataInitial>\n\n/**\n * Define dynamic infinite query options by passing a function that accepts an\n * arbitrary parameter and returns the query options. Enables type-safe query\n * keys. Pass to {@link useInfiniteQuery} as a single function:\n * `useInfiniteQuery(() => setupOptions(params))`.\n *\n * @param setupOptions - A function that returns the infinite query options.\n */\nexport function defineInfiniteQueryOptions<\n  Params,\n  TData,\n  TError = ErrorDefault,\n  TPageParam = unknown,\n  TDataInitial extends UseInfiniteQueryData<TData, TPageParam> | undefined = undefined,\n>(\n  setupOptions: (\n    params: Params,\n  ) => UseInfiniteQueryOptions<TData, TError, TPageParam, TDataInitial>,\n): (params: Params) => DefineInfiniteQueryOptionsTagged<TData, TError, TPageParam, TDataInitial>\n\n/**\n * Define static infinite query options that are type safe with\n * `queryCache.getQueryData()`. Can be passed directly to\n * {@link useInfiniteQuery}.\n *\n * @param options - The infinite query options.\n */\nexport function defineInfiniteQueryOptions<\n  TData,\n  TError = ErrorDefault,\n  TPageParam = unknown,\n  TDataInitial extends UseInfiniteQueryData<TData, TPageParam> | undefined = undefined,\n>(\n  options: UseInfiniteQueryOptions<TData, TError, TPageParam, TDataInitial>,\n): DefineInfiniteQueryOptionsTagged<TData, TError, TPageParam, TDataInitial>\n\n/**\n * Define type-safe infinite query options. Can be static or dynamic. Define the\n * arguments based on what's needed on the query and the key.\n *\n * @param setupOrOptions - The infinite query options or a function that returns\n *   them.\n *\n * @example\n * ```ts\n * import { defineInfiniteQueryOptions } from '@pinia/colada'\n *\n * const itemsQuery = defineInfiniteQueryOptions({\n *   key: ['items'],\n *   query: ({ pageParam }) => fetchItems(pageParam),\n *   initialPageParam: 0,\n *   getNextPageParam: (lastPage) => lastPage.nextCursor,\n * })\n *\n * queryCache.getQueryData(itemsQuery.key) // typed\n * ```\n *\n * @__NO_SIDE_EFFECTS__\n */\nexport function defineInfiniteQueryOptions(\n  setupOrOptions:\n    | UseInfiniteQueryOptions<any, any, any, any>\n    | ((...args: any[]) => UseInfiniteQueryOptions<any, any, any, any>),\n) {\n  return setupOrOptions\n}\n","import { inject } from 'vue'\nimport type { InjectionKey } from 'vue'\nimport type { ErrorDefault, MutationMeta } from './types-extension'\nimport type { _ReduceContext, _MutationKey, UseMutationGlobalContext } from './use-mutation'\nimport type { _EmptyObject, _Awaitable } from './utils'\nimport type { UseMutationEntry } from './mutation-store'\n\n/**\n * Common context properties shared by all mutation hooks. Contains the mutation entry with optional generics for\n * type-safe access in local hooks.\n */\nexport interface UseMutationContextCommon<\n  TData = unknown,\n  TVars = unknown,\n  TError = unknown,\n  TContext extends Record<any, any> = _EmptyObject,\n> {\n  /**\n   * The mutation entry associated with the current mutation call.\n   */\n  entry: UseMutationEntry<TData, TVars, TError, TContext>\n  // entry: Omit<UseMutationEntry<TData, TVars, TError, TContext>, 'options'>\n}\n\n/**\n * Options for mutations that can be globally overridden.\n */\nexport interface UseMutationOptionsGlobal {\n  /**\n   * Runs before a mutation is executed. It can return a value that will be\n   * passed to `mutation`, `onSuccess`, `onError` and `onSettled`. If it\n   * returns a promise, it will be awaited before running `mutation`.\n   */\n  onMutate?: (\n    /**\n     * The variables passed to the mutation.\n     */\n    vars: unknown,\n    /**\n     * The context seeded by the runtime, containing the mutation entry.\n     */\n    context: UseMutationContextCommon,\n  ) => _Awaitable<UseMutationGlobalContext | undefined | void | null>\n\n  /**\n   * Runs when a mutation is successful.\n   */\n  onSuccess?: (\n    /**\n     * The result of the mutation.\n     */\n    data: unknown,\n    /**\n     * The variables passed to the mutation.\n     */\n    vars: unknown,\n    /**\n     * The merged context from `onMutate` and the global context.\n     */\n    context: UseMutationContextCommon & UseMutationGlobalContext,\n  ) => unknown\n\n  /**\n   * Runs when a mutation encounters an error.\n   */\n  onError?: (\n    /**\n     * The error thrown by the mutation.\n     */\n    error: unknown,\n    /**\n     * The variables passed to the mutation.\n     */\n    vars: unknown,\n    /**\n     * The merged context from `onMutate` and the global context. Properties returned by `onMutate` can be `undefined`\n     * if `onMutate` throws.\n     */\n    context: UseMutationContextCommon &\n      (\n        | Partial<Record<keyof UseMutationGlobalContext, never>>\n        // this is the success case where everything is defined\n        // undefined if global onMutate throws\n        | UseMutationGlobalContext\n      ),\n  ) => unknown\n\n  /**\n   * Runs after the mutation is settled, regardless of the result.\n   */\n  onSettled?: (\n    /**\n     * The result of the mutation. `undefined` when a mutation failed.\n     */\n    data: unknown | undefined,\n    /**\n     * The error thrown by the mutation. `undefined` if the mutation was successful.\n     */\n    error: unknown | undefined,\n    /**\n     * The variables passed to the mutation.\n     */\n    vars: unknown,\n    /**\n     * The merged context from `onMutate` and the global context. Properties returned by `onMutate` can be `undefined`\n     * if `onMutate` throws.\n     */\n    context: UseMutationContextCommon &\n      (\n        | Partial<Record<keyof UseMutationGlobalContext, never>>\n        // this is the success case where everything is defined\n        // undefined if global onMutate throws\n        | UseMutationGlobalContext\n      ),\n  ) => unknown\n\n  /**\n   * Time in ms after which, once the mutation is no longer being used, it will be\n   * garbage collected to free resources. Set to `false` to disable garbage\n   * collection (not recommended).\n   *\n   * @default 60_000 (1 minute)\n   */\n  gcTime?: number | false\n}\n\n/**\n * Default options for `useMutation()`. Modifying this object will affect all mutations.\n */\nexport const USE_MUTATION_DEFAULTS = {\n  gcTime: (1000 * 60) as NonNullable<UseMutationOptions['gcTime']>, // 1 minute\n} satisfies UseMutationOptionsGlobal\n\nexport type UseMutationOptionsWithDefaults<\n  TData = unknown,\n  TVars = void,\n  TError = ErrorDefault,\n  TContext extends Record<any, any> = _EmptyObject,\n> = UseMutationOptions<TData, TVars, TError, TContext> & typeof USE_MUTATION_DEFAULTS\n\n/**\n * Options to create a mutation.\n */\nexport interface UseMutationOptions<\n  TData = unknown,\n  TVars = void,\n  TError = ErrorDefault,\n  TContext extends Record<any, any> = _EmptyObject,\n> extends Pick<UseMutationOptionsGlobal, 'gcTime'> {\n  /**\n   * The key of the mutation. If the mutation is successful, it will invalidate the mutation with the same key and refetch it\n   */\n  mutation: (vars: TVars, context: _ReduceContext<NoInfer<TContext>>) => Promise<TData>\n\n  /**\n   * Optional key to identify the mutation globally and access it through other\n   * methods in the mutation cache. If you don't need to reference the mutation\n   * elsewhere, you should ignore this option.\n   */\n  key?: _MutationKey<NoInfer<TVars>>\n\n  /**\n   * Meta information associated with the mutation. Can be used by plugins\n   * to store additional data alongside the mutation entry.\n   */\n  meta?: MutationMeta\n\n  /**\n   * Runs before the mutation is executed. **It should be placed before `mutation()` for `context` to be inferred**. It\n   * can return a value that will be passed to `mutation`, `onSuccess`, `onError` and `onSettled`. If it returns a\n   * promise, it will be awaited before running `mutation`.\n   *\n   * @param vars - The variables passed to the mutation.\n   *\n   * @example\n   * ```ts\n   * useMutation({\n   * // must appear before `mutation` for `{ foo: string }` to be inferred\n   * // within `mutation`\n   *   onMutate() {\n   *     return { foo: 'bar' }\n   *   },\n   *   mutation: (id: number, { foo }) => {\n   *     console.log(foo) // bar\n   *     return fetch(`/api/todos/${id}`)\n   *   },\n   *   onSuccess(data, vars, context) {\n   *     console.log(context.foo) // bar\n   *   },\n   * })\n   * ```\n   */\n  onMutate?: (\n    /**\n     * The variables passed to the mutation.\n     */\n    vars: TVars,\n    // we must use unknown and _EmptyObject to avoid inference and breaking types in other places\n    context: UseMutationContextCommon<unknown, unknown, NoInfer<TError>, _EmptyObject> &\n      UseMutationGlobalContext,\n  ) => _Awaitable<TContext | undefined | void | null>\n\n  /**\n   * Runs if the mutation is successful.\n   *\n   * @param data - The result of the mutation.\n   * @param vars - The variables passed to the mutation.\n   * @param context - The merged context from `onMutate` and the global context.\n   * Properties returned by `onMutate` can be `undefined` if `onMutate` throws.\n   */\n  onSuccess?: (\n    data: NoInfer<TData>,\n    vars: NoInfer<TVars>,\n    context: UseMutationContextCommon<\n      NoInfer<TData>,\n      NoInfer<TVars>,\n      NoInfer<TError>,\n      NoInfer<TContext>\n    > &\n      UseMutationGlobalContext &\n      _ReduceContext<NoInfer<TContext>>,\n  ) => unknown\n\n  /**\n   * Runs if the mutation encounters an error.\n   */\n  onError?: (\n    /**\n     * The error thrown by the mutation.\n     */\n    error: TError,\n    /**\n     * The variables passed to the mutation.\n     */\n    vars: NoInfer<TVars>,\n    /**\n     * The merged context from `onMutate` and the global context. Properties returned by `onMutate` can be `undefined`\n     * if `onMutate` throws.\n     */\n    context: UseMutationContextCommon<TData, TVars, TError, TContext> &\n      (\n        | (Partial<Record<keyof UseMutationGlobalContext, never>> &\n            Partial<Record<keyof _ReduceContext<NoInfer<TContext>>, never>>)\n        // this is the success case where everything is defined\n        // undefined if global onMutate throws\n        | (UseMutationGlobalContext & _ReduceContext<NoInfer<TContext>>)\n      ),\n  ) => unknown\n\n  /**\n   * Runs after the mutation is settled, regardless of the result.\n   */\n  onSettled?: (\n    /**\n     * The result of the mutation. `undefined` if the mutation failed.\n     */\n    data: NoInfer<TData> | undefined,\n    /**\n     * The error thrown by the mutation. `undefined` if the mutation was successful.\n     */\n    error: TError | undefined,\n    /**\n     * The variables passed to the mutation.\n     */\n    vars: NoInfer<TVars>,\n    /**\n     * The merged context from `onMutate` and the global context. Properties returned by `onMutate` can be `undefined`\n     * if `onMutate` throws.\n     */\n    context: UseMutationContextCommon<TData, TVars, TError, TContext> &\n      (\n        | (Partial<Record<keyof UseMutationGlobalContext, never>> &\n            Partial<Record<keyof _ReduceContext<NoInfer<TContext>>, never>>)\n        // this is the success case where everything is defined\n        // undefined if global onMutate throws\n        | (UseMutationGlobalContext & _ReduceContext<NoInfer<TContext>>)\n      ),\n  ) => unknown\n}\n\n/**\n * Global default options for `useMutations()`.\n * @internal\n */\nexport type UseMutationOptionsGlobalDefaults = UseMutationOptionsGlobal &\n  typeof USE_MUTATION_DEFAULTS\n\nexport const USE_MUTATION_OPTIONS_KEY: InjectionKey<UseMutationOptionsGlobalDefaults> =\n  process.env.NODE_ENV !== 'production' ? Symbol('useMutationOptions') : Symbol()\n\n/**\n * Injects the global query options.\n *\n * @internal\n */\nexport const useMutationOptions = (): UseMutationOptionsGlobalDefaults =>\n  inject(USE_MUTATION_OPTIONS_KEY, USE_MUTATION_DEFAULTS)\n","import type { AsyncStatus, DataState } from './data-state'\nimport { defineStore, getActivePinia, skipHydrate } from 'pinia'\nimport {\n  customRef,\n  effectScope,\n  getCurrentScope,\n  hasInjectionContext,\n  markRaw,\n  shallowRef,\n} from 'vue'\nimport type { App, EffectScope, ShallowRef } from 'vue'\nimport { find } from './entry-keys'\nimport type { EntryFilter } from './entry-filter'\nimport type { _EmptyObject } from './utils'\nimport { noop, toValueWithArgs, warnOnce } from './utils'\nimport type { _ReduceContext } from './use-mutation'\nimport { useMutationOptions } from './mutation-options'\nimport type {\n  UseMutationContextCommon,\n  UseMutationOptions,\n  UseMutationOptionsWithDefaults,\n} from './mutation-options'\nimport type { EntryKey } from './entry-keys'\nimport type { MutationMeta } from './types-extension'\n\n/**\n * Allows defining extensions to the mutation entry that are returned by `useMutation()`.\n */\nexport interface UseMutationEntryExtensions<\n  // oxlint-disable-next-line no-unused-vars\n  TData,\n  // oxlint-disable-next-line no-unused-vars\n  TVars,\n  // oxlint-disable-next-line no-unused-vars\n  TError,\n  // oxlint-disable-next-line no-unused-vars\n  TContext extends Record<any, any> = _EmptyObject,\n> {}\n\n/**\n * A mutation entry in the cache.\n */\nexport interface UseMutationEntry<\n  TData = unknown,\n  TVars = unknown,\n  TError = unknown,\n  TContext extends Record<any, any> = _EmptyObject,\n> {\n  /**\n   * Unique id of the mutation entry. 0 if the entry is not yet in the cache.\n   */\n  id: number\n\n  /**\n   * The state of the mutation. Contains the data, error and status.\n   */\n  state: ShallowRef<DataState<TData, TError>>\n\n  /**\n   * The async status of the mutation.\n   */\n  asyncStatus: ShallowRef<AsyncStatus>\n\n  /**\n   * When was this data fetched the last time in ms\n   */\n  when: number\n\n  /**\n   * The key associated with this mutation entry.\n   * Can be `undefined` if the entry has no key.\n   */\n  key: EntryKey | undefined\n\n  /**\n   * Resolved meta information for this mutation.\n   */\n  meta: MutationMeta\n\n  /**\n   * The variables used to call the mutation.\n   */\n  vars: TVars | undefined\n\n  /**\n   * Options used to create the mutation.\n   */\n  options: UseMutationOptionsWithDefaults<TData, TVars, TError, TContext>\n\n  /**\n   * Timeout id that scheduled a garbage collection. It is set here to clear it when the entry is used by a different component.\n   */\n  gcTimeout: ReturnType<typeof setTimeout> | undefined\n\n  /**\n   * Extensions to the mutation entry added by plugins. You should only add\n   * properties to the object, not replace it.\n   */\n  readonly ext: UseMutationEntryExtensions<TData, TVars, TError, TContext>\n}\n\n/**\n * Filter to get entries from the mutation cache.\n */\nexport type UseMutationEntryFilter = EntryFilter<UseMutationEntry>\n\n/**\n * The id of the store used for mutations.\n * @internal\n */\nexport const MUTATION_STORE_ID = '_pc_mutation'\n\n/**\n * A mutation entry that is defined with {@link defineMutation}.\n * @internal\n */\ntype DefineMutationEntry = [returnValue: unknown, effect: EffectScope]\n\n/**\n * Composable to get the cache of the mutations. As any other composable, it\n * can be used inside the `setup` function of a component, within another\n * composable, or in injectable contexts like stores and navigation guards.\n */\nexport const useMutationCache = /* @__PURE__ */ defineStore(MUTATION_STORE_ID, ({ action }) => {\n  // We have two versions of the cache, one that track changes and another that doesn't so the actions can be used\n  // inside computed properties\n  // We have two versions of the cache, one that track changes and another that doesn't so the actions can be used\n  // inside computed properties\n  const cachesRaw = new Map<number, UseMutationEntry<unknown, any, unknown, any>>()\n  let triggerCache!: () => void\n  const caches = skipHydrate(\n    customRef(\n      (track, trigger) =>\n        (triggerCache = trigger) && {\n          // eslint-disable-next-line no-sequences\n          get: () => (track(), cachesRaw),\n          set:\n            process.env.NODE_ENV !== 'production'\n              ? () => {\n                  console.error(\n                    `[@pinia/colada]: The mutation cache instance cannot be set directly, it must be modified. This will fail in production.`,\n                  )\n                }\n              : noop,\n        },\n    ),\n  )\n\n  // this allows use to attach reactive effects to the scope later on\n  const scope = getCurrentScope()!\n\n  if (process.env.NODE_ENV !== 'production') {\n    if (!hasInjectionContext()) {\n      warnOnce(\n        `useMutationCache() was called outside of an injection context (component setup, store, navigation guard) You will get a warning about \"inject\" being used incorrectly from Vue. Make sure to use it only in allowed places.\\n` +\n          `See https://vuejs.org/guide/reusability/composables.html#usage-restrictions`,\n      )\n    }\n  }\n\n  const app: App<unknown> =\n    // @ts-expect-error: internal\n    getActivePinia()!._a\n\n  const globalOptions = useMutationOptions()\n  const defineMutationMap = new WeakMap<() => unknown, DefineMutationEntry>()\n\n  let nextMutationId = 1\n\n  /**\n   * Action called when an entry is created for the first time to allow plugins to extend it.\n   *\n   * @param _entry - the entry of the mutation to extend\n   */\n  const extend = action(\n    <\n      TData = unknown,\n      TVars = unknown,\n      TError = unknown,\n      TContext extends Record<any, any> = _EmptyObject,\n    >(\n      _entry: UseMutationEntry<TData, TVars, TError, TContext>,\n    ) => _entry,\n  )\n\n  /**\n   * Creates a mutation entry and its state without adding it to the cache.\n   * This allows for the state to exist in `useMutation()` before the mutation\n   * is actually called. The mutation must be _ensured_ with {@link ensure}\n   * before being called.\n   *\n   * @param options - options to create the mutation\n   */\n  const create = action(\n    <\n      TData = unknown,\n      TVars = unknown,\n      TError = unknown,\n      TContext extends Record<any, any> = _EmptyObject,\n    >(\n      options: UseMutationOptionsWithDefaults<TData, TVars, TError, TContext>,\n      key?: EntryKey | undefined,\n      vars?: TVars,\n    ): UseMutationEntry<TData, TVars, TError, TContext> =>\n      // mutations are not immediately ensured after being created, so we need to\n      // extend them right away to add any extensions that plugins might need.\n      extend(\n        scope.run(() =>\n          markRaw<UseMutationEntry<TData, TVars, TError, TContext>>({\n            // only ids > 0 are real ids\n            id: 0,\n            state: shallowRef<DataState<TData, TError>>({\n              status: 'pending',\n              data: undefined,\n              error: null,\n            }),\n            gcTimeout: undefined,\n            asyncStatus: shallowRef<AsyncStatus>('idle'),\n            when: 0,\n            vars,\n            key,\n            meta: options.meta ?? {},\n            options,\n            // eslint-disable-next-line ts/ban-ts-comment\n            // @ts-ignore: some plugins are adding properties to the entry type\n            ext: {},\n          } satisfies UseMutationEntry<TData, TVars, TError, TContext>),\n        )!,\n      ),\n  )\n\n  /**\n   * Ensures a mutation entry in the cache by assigning it an `id` and a `key` based on `vars`. Usually, a mutation is ensured twice\n   *\n   * @param entry - entry to ensure\n   * @param vars - variables to call the mutation with\n   */\n  function ensure<\n    TData = unknown,\n    TVars = unknown,\n    TError = unknown,\n    TContext extends Record<any, any> = _EmptyObject,\n  >(\n    entry: UseMutationEntry<TData, TVars, TError, TContext>,\n    vars: NoInfer<TVars>,\n  ): UseMutationEntry<TData, TVars, TError, TContext> {\n    const options = entry.options\n    const id = nextMutationId++\n    const key: EntryKey | undefined = options.key && toValueWithArgs(options.key, vars)\n\n    // override the existing entry and untrack it if it was already created\n    entry = entry.id ? (untrack(entry), create(options, key, vars)) : entry\n    entry.id = id\n    entry.key = key\n    entry.vars = vars\n\n    // store the entry with the mutation ID as the map key\n    cachesRaw.set(id, entry as unknown as UseMutationEntry)\n    triggerCache()\n\n    return entry\n  }\n\n  /**\n   * Ensures a mutation created with {@link defineMutation} is present in the cache. If it's not, it creates a new one.\n   * @param fn - function that defines the mutation\n   */\n  const ensureDefinedMutation = action(<T>(fn: () => T) => {\n    let entry = defineMutationMap.get(fn)\n    if (!entry) {\n      entry = scope.run(() => [null, effectScope()])! as DefineMutationEntry\n\n      entry[0] = app.runWithContext(() => entry![1].run(fn)!)\n      defineMutationMap.set(fn, entry)\n    } else {\n      // ensure the scope is active so effects run\n      entry[1].resume()\n    }\n\n    return entry\n  })\n\n  /**\n   * Gets a single mutation entry from the cache based on the ID of the mutation.\n   *\n   * @param id - the ID of the mutation\n   */\n  function get<\n    TData = unknown,\n    TVars = unknown,\n    TError = unknown,\n    TContext extends Record<any, any> = _EmptyObject,\n  >(id: number): UseMutationEntry<TData, TVars, TError, TContext> | undefined {\n    return caches.value.get(id) as UseMutationEntry<TData, TVars, TError, TContext> | undefined\n  }\n\n  /**\n   * Sets the state of a query entry in the cache and updates the\n   * {@link UseQueryEntry['pending']['when'] | `when` property}. This action is\n   * called every time the cache state changes and can be used by plugins to\n   * detect changes.\n   *\n   * @param entry - the entry of the query to set the state\n   * @param state - the new state of the entry\n   */\n  const setEntryState = action(\n    <\n      TData = unknown,\n      TVars = unknown,\n      TError = unknown,\n      TContext extends Record<any, any> = _EmptyObject,\n    >(\n      entry: UseMutationEntry<TData, TVars, TError, TContext>,\n      // NOTE: NoInfer ensures correct inference of TData and TError\n      state: DataState<NoInfer<TData>, NoInfer<TError>>,\n    ) => {\n      entry.state.value = state\n      entry.when = Date.now()\n    },\n  )\n\n  /**\n   * Removes a mutation entry from the cache if it has an id. If it doesn't then it does nothing.\n   *\n   * @param entry - the entry of the mutation to remove\n   */\n  const remove = action(\n    <\n      TData = unknown,\n      TVars = unknown,\n      TError = unknown,\n      TContext extends Record<any, any> = _EmptyObject,\n    >(\n      entry: UseMutationEntry<TData, TVars, TError, TContext>,\n    ) => {\n      cachesRaw.delete(entry.id)\n      triggerCache()\n    },\n  )\n\n  /**\n   * Returns all the entries in the cache that match the filters.\n   * Note that you can have multiple entries with the exact same key if they\n   * were called multiple times.\n   *\n   * @param filters - filters to apply to the entries\n   */\n  const getEntries = action((filters: UseMutationEntryFilter = {}): UseMutationEntry[] => {\n    return [...find(caches.value, filters.key)].filter(\n      (entry) =>\n        (filters.status == null || entry.state.value.status === filters.status) &&\n        (!filters.predicate || filters.predicate(entry)),\n    )\n  })\n\n  /**\n   * Untracks a mutation entry, scheduling garbage collection.\n   *\n   * @param entry - the entry of the mutation to untrack\n   */\n  const untrack = action(\n    <\n      TData = unknown,\n      TVars = unknown,\n      TError = unknown,\n      TContext extends Record<any, any> = _EmptyObject,\n    >(\n      entry: UseMutationEntry<TData, TVars, TError, TContext>,\n    ) => {\n      // schedule a garbage collection if the entry is not active\n      if (entry.gcTimeout) return\n\n      // avoid setting a timeout with false, Infinity or NaN\n      if ((Number.isFinite as (val: unknown) => val is number)(entry.options.gcTime)) {\n        entry.gcTimeout = setTimeout(() => {\n          remove(entry)\n        }, entry.options.gcTime)\n      }\n    },\n  )\n\n  /**\n   * Mutate a previously ensured mutation entry.\n   *\n   * @param entry - the entry to mutate\n   */\n  async function mutate<\n    TData = unknown,\n    TVars = unknown,\n    TError = unknown,\n    TContext extends Record<any, any> = _EmptyObject,\n  >(entry: UseMutationEntry<TData, TVars, TError, TContext>): Promise<TData> {\n    // the vars is set when the entry is ensured, we warn against it below\n    const { vars, options } = entry as typeof entry & { vars: TVars }\n\n    // DEV warnings\n    if (process.env.NODE_ENV !== 'production') {\n      const key = entry.key?.join('/')\n      const keyMessage = key ? `with key \"${key}\"` : 'without a key'\n      if (entry.id === 0) {\n        console.error(\n          `[@pinia/colada] A mutation entry ${keyMessage} was mutated before being ensured. If you are manually calling the \"mutationCache.mutate()\", you should always ensure the entry first If not, this is probably a bug. Please, open an issue on GitHub with a boiled down reproduction.`,\n        )\n      }\n      if (\n        // the entry has already an ongoing request\n        entry.state.value.status !== 'pending' ||\n        entry.asyncStatus.value === 'loading'\n      ) {\n        console.error(\n          `[@pinia/colada] A mutation entry ${keyMessage} was reused. If you are manually calling the \"mutationCache.mutate()\", you should always ensure the entry first: \"mutationCache.mutate(mutationCache.ensure(entry, vars))\". If not this is probably a bug. Please, open an issue on GitHub with a boiled down reproduction.`,\n        )\n      }\n    }\n\n    entry.asyncStatus.value = 'loading'\n\n    // TODO: AbortSignal that is aborted when the mutation is called again so we can throw in pending\n    let currentData: TData | undefined\n    let currentError: TError | undefined\n    type OnMutateContext =\n      /* Parameters<\n      Required<UseMutationOptions<TData, TVars, TError, TContext>>['onMutate']\n    >['1'] */ UseMutationContextCommon<TData, TVars, TError, TContext>\n    type OnSuccessContext = Parameters<\n      Required<UseMutationOptions<TData, TVars, TError, TContext>>['onSuccess']\n    >['2']\n    type OnErrorContext = Parameters<\n      Required<UseMutationOptions<TData, TVars, TError, TContext>>['onError']\n    >['2']\n\n    let context: OnMutateContext | OnErrorContext | OnSuccessContext = { entry }\n\n    try {\n      const globalOnMutateContext = globalOptions.onMutate?.(vars, context as any)\n\n      context = {\n        entry,\n        ...(globalOnMutateContext instanceof Promise\n          ? await globalOnMutateContext\n          : globalOnMutateContext),\n      } as typeof context\n\n      const onMutateContext = (await options.onMutate?.(\n        vars,\n        // contravariance + functions makes this too difficult to generalize without `any`\n        context as any,\n        // NOTE: the cast makes it easier to write without extra code. It's safe because { ...null, ...undefined } works and TContext must be a Record<any, any>\n      )) as _ReduceContext<TContext>\n\n      // we set the context here so it can be used by other hooks\n      context = {\n        ...context,\n        ...onMutateContext,\n        // NOTE: needed for onSuccess cast\n      } satisfies OnSuccessContext\n\n      const newData = (currentData = await options.mutation(vars, context as OnSuccessContext))\n\n      await globalOptions.onSuccess?.(\n        newData,\n        vars,\n        // contravariance + functions makes this too difficult to generalize without `any`\n        context as any,\n      )\n      await options.onSuccess?.(\n        newData,\n        vars,\n        // NOTE: cast is safe because of the satisfies above\n        // using a spread also works\n        context as OnSuccessContext,\n      )\n\n      setEntryState(entry, {\n        status: 'success',\n        data: newData,\n        error: null,\n      })\n    } catch (newError: unknown) {\n      currentError = newError as TError\n      await globalOptions.onError?.(\n        currentError,\n        vars,\n        // contravariance + functions makes this too difficult to generalize without `any`\n        context as any,\n      )\n      await options.onError?.(currentError, vars, context as OnErrorContext)\n      setEntryState(entry, {\n        status: 'error',\n        data: entry.state.value.data,\n        error: currentError,\n      })\n      throw newError\n    } finally {\n      // TODO: should we catch and log it?\n      await globalOptions.onSettled?.(\n        currentData,\n        currentError,\n        vars,\n        // contravariance + functions makes this too difficult to generalize without `any`\n        context as any,\n      )\n      await options.onSettled?.(currentData, currentError, vars, context as OnErrorContext)\n      entry.asyncStatus.value = 'idle'\n    }\n\n    return currentData\n  }\n\n  return {\n    caches,\n\n    create,\n    ensure,\n    ensureDefinedMutation,\n    mutate,\n    remove,\n    extend,\n    get,\n\n    setEntryState,\n    getEntries,\n    untrack,\n\n    /**\n     * Scope to track effects and components that use the mutation cache.\n     * @internal\n     */\n    _s: scope,\n  }\n})\n\n/**\n * The cache of the mutations. It's the store returned by {@link useMutationCache}.\n */\nexport type MutationCache = ReturnType<typeof useMutationCache>\n\n/**\n * Checks if the given object is a mutation cache. Used in SSR to apply custom serialization.\n *\n * @param cache - the object to check\n *\n * @see {@link MutationCache}\n */\nexport function isMutationCache(cache: unknown): cache is MutationCache {\n  return (\n    typeof cache === 'object' &&\n    !!cache &&\n    (cache as Record<string, unknown>).$id === MUTATION_STORE_ID\n  )\n}\n","import type { ComputedRef, ShallowRef } from 'vue'\nimport type { AsyncStatus, DataState, DataStateStatus } from './data-state'\nimport type { EntryKey } from './entry-keys'\nimport type { ErrorDefault } from './types-extension'\nimport {\n  computed,\n  shallowRef,\n  getCurrentInstance,\n  getCurrentScope,\n  isRef,\n  onUnmounted,\n  onScopeDispose,\n  toValue,\n} from 'vue'\nimport { useMutationCache } from './mutation-store'\nimport type { UseMutationEntry, UseMutationEntryExtensions } from './mutation-store'\nimport { noop } from './utils'\nimport type { _EmptyObject } from './utils'\nimport { useMutationOptions, type UseMutationOptions } from './mutation-options'\n\n/**\n * Valid keys for a mutation. Similar to query keys.\n *\n * @see {@link EntryKey}\n *\n * @internal\n */\nexport type _MutationKey<TVars> = EntryKey | ((vars: TVars) => EntryKey)\n\n/**\n * Removes the nullish types from the context type to make `A & TContext` work instead of yield `never`.\n *\n * @internal\n */\nexport type _ReduceContext<TContext> = TContext extends void | null | undefined\n  ? _EmptyObject\n  : Record<any, any> extends TContext\n    ? _EmptyObject\n    : TContext\n\n/**\n * Context object returned by a global `onMutate` function that is merged with the context returned by a local\n * `onMutate`.\n * @example\n * ```ts\n * declare module '@pinia/colada' {\n *   export interface UseMutationGlobalContext {\n *     router: Router // from vue-router\n *   }\n * }\n *\n * // add the `router` to the context\n * app.use(MutationPlugin, {\n *   onMutate() {\n *     return { router }\n *   },\n * })\n * ```\n */\nexport interface UseMutationGlobalContext {}\n\n// export const USE_MUTATIONS_DEFAULTS = {} satisfies Partial<UseMutationsOptions>\n\nexport interface UseMutationReturn<\n  TData,\n  TVars,\n  TError,\n  TContext extends Record<any, any> = _EmptyObject,\n> extends UseMutationEntryExtensions<TData, TVars, TError, TContext> {\n  key?: EntryKey | ((vars: NoInfer<TVars>) => EntryKey)\n\n  /**\n   * The combined state of the mutation. Contains its data, error, and status.\n   * It enables type narrowing based on the {@link UseMutationReturn['status']}.\n   */\n  state: ComputedRef<DataState<TData, TError>>\n\n  /**\n   * The status of the mutation.\n   *\n   * @see {@link DataStateStatus}\n   */\n  status: ShallowRef<DataStateStatus>\n\n  /**\n   * Status of the mutation. Becomes `'loading'` while the mutation is being fetched, is `'idle'` otherwise.\n   */\n  asyncStatus: ShallowRef<AsyncStatus>\n\n  /**\n   * The result of the mutation. `undefined` if the mutation has not been called yet.\n   */\n  data: ShallowRef<TData | undefined>\n\n  /**\n   * The error of the mutation. `null` if the mutation has not been called yet or if it was successful.\n   */\n  error: ShallowRef<TError | null>\n\n  /**\n   * Whether the mutation is currently executing.\n   */\n  isLoading: ComputedRef<boolean>\n\n  /**\n   * The variables passed to the mutation. They are initially `undefined` and change every time the mutation is called.\n   */\n  variables: ShallowRef<TVars | undefined>\n\n  /**\n   * Calls the mutation and returns a promise with the result.\n   *\n   * @param vars - parameters to pass to the mutation\n   */\n  mutateAsync: unknown | void extends TVars ? () => Promise<TData> : (vars: TVars) => Promise<TData>\n\n  /**\n   * Calls the mutation without returning a promise to avoid unhandled promise rejections.\n   *\n   * @param args - parameters to pass to the mutation\n   */\n  mutate: (...args: unknown | void extends TVars ? [] : [vars: TVars]) => void\n\n  /**\n   * Resets the state of the mutation to its initial state.\n   */\n  reset: () => void\n}\n\n/**\n * Setups a mutation.\n *\n * @param options - Options to create the mutation\n *\n * @example\n * ```ts\n * const queryCache = useQueryCache()\n * const { mutate, status, error } = useMutation({\n *   mutation: (id: number) => fetch(`/api/todos/${id}`),\n *   onSuccess() {\n *     queryCache.invalidateQueries('todos')\n *   },\n * })\n * ```\n */\nexport function useMutation<\n  TData,\n  TVars = void,\n  TError = ErrorDefault,\n  TContext extends Record<any, any> = _EmptyObject,\n>(\n  options: UseMutationOptions<TData, TVars, TError, TContext>,\n): UseMutationReturn<TData, TVars, TError, TContext> {\n  const mutationCache = useMutationCache()\n  const hasCurrentInstance = getCurrentInstance()\n  const currentEffect = getCurrentScope()\n  const optionDefaults = useMutationOptions()\n\n  const mergedOptions = {\n    ...optionDefaults,\n    // global hooks are directly handled in the mutation cache\n    onMutate: undefined,\n    onSuccess: undefined,\n    onError: undefined,\n    onSettled: undefined,\n    ...options,\n  }\n\n  // always create an initial entry with no key (cannot be computed without vars)\n  const entry = shallowRef<UseMutationEntry<TData, TVars, TError, TContext>>(\n    mutationCache.create(mergedOptions),\n  )\n\n  // expose entry extensions (added by plugins) on the returned object.\n  // NOTE: the keys are enumerated once (same as `useQuery()`), so plugins\n  // should register all extension properties during the `extend` action.\n  const extensions = {} as Record<string, any>\n  for (const key in entry.value.ext) {\n    extensions[key] = computed<unknown>({\n      get: () =>\n        toValue<unknown>(\n          entry.value.ext[key as keyof UseMutationEntryExtensions<TData, TVars, TError, TContext>],\n        ),\n      set(value) {\n        const target =\n          entry.value.ext[key as keyof UseMutationEntryExtensions<TData, TVars, TError, TContext>]\n        if (isRef(target)) {\n          ;(target as ShallowRef<unknown>).value = value\n        } else {\n          ;(entry.value.ext[\n            key as keyof UseMutationEntryExtensions<TData, TVars, TError, TContext>\n          ] as unknown) = value\n        }\n      },\n    })\n  }\n\n  // Untrack the mutation entry when component or effect scope is disposed\n  if (hasCurrentInstance) {\n    onUnmounted(() => {\n      mutationCache.untrack(entry.value)\n    })\n  }\n  if (currentEffect) {\n    onScopeDispose(() => {\n      mutationCache.untrack(entry.value)\n    })\n  }\n\n  const state = computed(() => entry.value.state.value)\n  const status = computed(() => state.value.status)\n  const data = computed(() => state.value.data)\n  const error = computed(() => state.value.error)\n  const asyncStatus = computed(() => entry.value.asyncStatus.value)\n  const variables = computed(() => entry.value.vars)\n\n  async function mutateAsync(vars: TVars): Promise<TData> {\n    return mutationCache.mutate(\n      // ensures we reuse the initial empty entry and adapt it or create a new one\n      (entry.value = mutationCache.ensure(entry.value, vars)),\n    )\n  }\n\n  function mutate(vars: NoInfer<TVars>) {\n    mutateAsync(vars).catch(noop)\n  }\n\n  function reset() {\n    entry.value = mutationCache.create(mergedOptions)\n  }\n\n  const mutationReturn = {\n    ...(extensions as UseMutationEntryExtensions<TData, TVars, TError, TContext>),\n    state,\n    data,\n    isLoading: computed(() => asyncStatus.value === 'loading'),\n    status,\n    variables,\n    asyncStatus,\n    error,\n    // NOTE: the implementation is always the same but the public types change\n    // based on whether TVars is `void`.\n    mutate: mutate as any,\n    mutateAsync: mutateAsync as any,\n    reset,\n  } as UseMutationReturn<TData, TVars, TError, TContext>\n\n  return mutationReturn\n}\n","import { getCurrentInstance, getCurrentScope, onScopeDispose } from 'vue'\nimport { useMutationCache } from './mutation-store'\nimport type { ErrorDefault } from './types-extension'\nimport { useMutation } from './use-mutation'\nimport type { UseMutationReturn } from './use-mutation'\nimport type { UseMutationOptions } from './mutation-options'\nimport type { _EmptyObject } from './utils'\n\n/**\n * Define a mutation with the given options. Similar to `useMutation(options)` but allows you to reuse the mutation in\n * multiple places.\n *\n * @param options - the options to define the mutation\n * @example\n * ```ts\n * const useCreateTodo = defineMutation({\n *   mutation: (todoText: string) =>\n *     fetch('/api/todos', {\n *       method: 'POST',\n *       body: JSON.stringify({ text: todoText }),\n *     }),\n * })\n * ```\n */\nexport function defineMutation<\n  TData,\n  TVars = void,\n  TError = ErrorDefault,\n  TContext extends Record<any, any> = _EmptyObject,\n>(\n  options: UseMutationOptions<TData, TVars, TError, TContext>,\n): () => UseMutationReturn<TData, TVars, TError, TContext>\n\n/**\n * Define a mutation with a function setup. Allows to return arbitrary values from the mutation function, create\n * contextual refs, rename the returned values, etc.\n *\n * @param setup - a function to setup the mutation\n * @example\n * ```ts\n * const useCreateTodo = defineMutation(() => {\n *   const todoText = ref('')\n *   const { data, mutate, ...rest } = useMutation({\n *     mutation: () =>\n *       fetch('/api/todos', {\n *         method: 'POST',\n *         body: JSON.stringify({ text: todoText.value }),\n *       }),\n *   })\n *   // expose the todoText ref and rename other methods for convenience\n *   return { ...rest, createTodo: mutate, todo: data, todoText }\n * })\n * ```\n */\nexport function defineMutation<T>(setup: () => T): () => T\nexport function defineMutation(\n  optionsOrSetup: UseMutationOptions | (() => unknown),\n): () => unknown {\n  const setupFn =\n    typeof optionsOrSetup === 'function' ? optionsOrSetup : () => useMutation(optionsOrSetup)\n\n  let refCount = 0\n  return () => {\n    const mutationCache = useMutationCache()\n    const currentScope = getCurrentInstance() || getCurrentScope()\n\n    const [ret, scope] = mutationCache.ensureDefinedMutation(setupFn)\n\n    if (currentScope) {\n      refCount++\n      onScopeDispose(() => {\n        if (--refCount < 1) {\n          scope.pause()\n        }\n      })\n    } else if (process.env.NODE_ENV !== 'production') {\n      console.warn(\n        `[@pinia/colada]: defineMutation() composable was called outside of a component or effect scope. The mutation effects will never be cleaned up, which may cause memory leaks. Make sure to call it inside a component setup, an effect scope, or a store.`,\n      )\n    }\n\n    return ret\n  }\n}\n","import type { UseMutationOptions } from './mutation-options'\nimport type { EntryKeyTagged } from './entry-keys'\nimport type { _MutationKey } from './use-mutation'\nimport type { ErrorDefault } from './types-extension'\nimport type { _EmptyObject } from './utils'\n\n/**\n * Tagged version of {@link UseMutationOptions} that includes a key with\n * data type information. Returned by {@link defineMutationOptions}.\n */\nexport interface DefineMutationOptionsTagged<\n  TData = unknown,\n  TVars = void,\n  TError = ErrorDefault,\n  TContext extends Record<any, any> = _EmptyObject,\n> extends UseMutationOptions<TData, TVars, TError, TContext> {\n  key: _MutationKeyTagged<TData, TVars, TError>\n}\n\n/**\n * Same as {@link _MutationKey} but with a data tag that allows inference of the data type.\n * @internal\n */\nexport type _MutationKeyTagged<TData, TVars, TError = ErrorDefault> =\n  | EntryKeyTagged<TData, TError>\n  | ((vars: TVars) => EntryKeyTagged<TData, TError>)\n\n/**\n * Define dynamic mutation options by passing a function that accepts an\n * optional arbitrary parameter and returns the mutation options. Pass to\n * {@link useMutation} directly: `useMutation(setupOptions(params))`.\n *\n * @param setupOptions - A function that returns the mutation options.\n */\nexport function defineMutationOptions<\n  Params,\n  TData,\n  TVars = void,\n  TError = ErrorDefault,\n  TContext extends Record<any, any> = _EmptyObject,\n>(\n  setupOptions: (params?: Params) => UseMutationOptions<TData, TVars, TError, TContext>,\n): (params?: Params) => DefineMutationOptionsTagged<TData, TVars, TError, TContext>\n\n/**\n * Define dynamic mutation options by passing a function that accepts an\n * arbitrary parameter and returns the mutation options. Pass to\n * {@link useMutation} directly: `useMutation(setupOptions(params))`.\n *\n * @param setupOptions - A function that returns the mutation options.\n */\nexport function defineMutationOptions<\n  Params,\n  TData,\n  TVars = void,\n  TError = ErrorDefault,\n  TContext extends Record<any, any> = _EmptyObject,\n>(\n  setupOptions: (params: Params) => UseMutationOptions<TData, TVars, TError, TContext>,\n): (params: Params) => DefineMutationOptionsTagged<TData, TVars, TError, TContext>\n\n/**\n * Define static mutation options that can be passed directly to\n * {@link useMutation}.\n *\n * @param options - The mutation options.\n */\nexport function defineMutationOptions<\n  TData,\n  TVars = void,\n  TError = ErrorDefault,\n  TContext extends Record<any, any> = _EmptyObject,\n>(\n  options: UseMutationOptions<TData, TVars, TError, TContext>,\n): DefineMutationOptionsTagged<TData, TVars, TError, TContext>\n\n/**\n * Define type-safe mutation options. Can be static or dynamic. Define the\n * arguments based on what's needed. Use an object if you need multiple\n * properties.\n *\n * @param setupOrOptions - The mutation options or a function that returns the mutation options.\n *\n * @example\n * ```ts\n * import { defineMutationOptions } from '@pinia/colada'\n *\n * const deleteItemMutation = defineMutationOptions({\n *   mutation: (id: number) => fetch(`/api/items/${id}`, { method: 'DELETE' }),\n * })\n *\n * // use in a component\n * const { mutate } = useMutation(deleteItemMutation)\n * ```\n *\n * @__NO_SIDE_EFFECTS__\n */\nexport function defineMutationOptions<const Options extends UseMutationOptions, Params>(\n  setupOrOptions: Options | ((params: Params) => Options),\n): Options | ((params: Params) => Options) {\n  return setupOrOptions\n}\n","import type { App, Plugin } from 'vue'\nimport type { Pinia } from 'pinia'\nimport type { UseQueryOptionsGlobal } from './query-options'\nimport { USE_QUERY_DEFAULTS, USE_QUERY_OPTIONS_KEY } from './query-options'\nimport { useQueryCache } from './query-store'\nimport type { PiniaColadaPlugin } from './plugins'\nimport { USE_MUTATION_DEFAULTS, USE_MUTATION_OPTIONS_KEY } from './mutation-options'\nimport type { UseMutationOptionsGlobal } from './mutation-options'\n\n/**\n * Options for the Pinia Colada plugin.\n */\nexport interface PiniaColadaOptions {\n  /**\n   * Pinia instance to use. This is only needed if installing before the Pinia plugin.\n   */\n  pinia?: Pinia\n\n  /**\n   * Pinia Colada plugins to install.\n   */\n  plugins?: PiniaColadaPlugin[]\n\n  /**\n   * Global options for queries. These will apply to all `useQuery()`, `defineQuery()`, etc.\n   */\n  queryOptions?: UseQueryOptionsGlobal\n\n  /**\n   * Global options for mutations. These will apply to all `useMutation()`, `defineMutation()`, etc.\n   */\n  mutationOptions?: UseMutationOptionsGlobal\n}\n\n/**\n * Plugin that installs the Query and Mutation plugins alongside some extra plugins.\n *\n * @see {@link QueryPlugin} to only install the Query plugin.\n *\n * @param app - Vue App\n * @param options - Pinia Colada options\n */\nexport const PiniaColada: Plugin<[options?: PiniaColadaOptions]> = (\n  app: App,\n  options: PiniaColadaOptions = {},\n): void => {\n  const {\n    pinia = app.config.globalProperties.$pinia,\n    plugins,\n    queryOptions,\n    mutationOptions,\n  } = options\n\n  app.provide(USE_QUERY_OPTIONS_KEY, {\n    ...USE_QUERY_DEFAULTS,\n    ...queryOptions,\n  })\n\n  app.provide(USE_MUTATION_OPTIONS_KEY, {\n    ...USE_MUTATION_DEFAULTS,\n    ...mutationOptions,\n  })\n\n  if (process.env.NODE_ENV !== 'production' && !pinia) {\n    throw new Error(\n      '[@pinia/colada] root pinia plugin not detected. Make sure you install pinia before installing the \"PiniaColada\" plugin or to manually pass the pinia instance.',\n    )\n  }\n\n  // install plugins\n  const queryCache = useQueryCache(pinia)\n  plugins?.forEach((plugin) =>\n    plugin({\n      scope: queryCache._s,\n      queryCache,\n      pinia,\n    }),\n  )\n}\n","import type { UseQueryEntry } from '../query-store'\nimport type { PiniaColadaPlugin } from '.'\n\n/**\n * Options for {@link PiniaColadaQueryHooksPlugin}.\n */\nexport interface PiniaColadaQueryHooksPluginOptions {\n  /**\n   * Global handler for when a query is successful.\n   *\n   * @param data - data returned by the query\n   */\n  onSuccess?: <TData = unknown>(data: TData, entry: UseQueryEntry<TData, unknown>) => unknown\n\n  /**\n   * Global handler for when a query is settled (either successfully or with an error). Will await for the `onSuccess`\n   * or `onError` handlers to resolve if they return a promise.\n   *\n   * @param data - data returned by the query if any\n   * @param error - error thrown if any\n   */\n  onSettled?: <TData = unknown, TError = unknown>(\n    data: TData | undefined,\n    error: TError | null,\n    entry: UseQueryEntry<TData, TError>,\n  ) => unknown\n\n  /**\n   * Global error handler for all queries.\n   *\n   * @param error - error thrown\n   */\n  onError?: <TError = unknown>(error: TError, entry: UseQueryEntry<unknown, TError>) => unknown\n}\n\n/**\n * Allows to add global hooks to all queries:\n * - `onSuccess`: called when a query is successful\n * - `onError`: called when a query throws an error\n * - `onSettled`: called when a query is settled (either successfully or with an error)\n * @param options - Pinia Colada Query Hooks plugin options\n *\n * @example\n * ```ts\n * import { PiniaColada, PiniaColadaQueryHooksPlugin } from '@pinia/colada'\n *\n * const app = createApp(App)\n * // app setup with other plugins\n * app.use(PiniaColada, {\n *   plugins: [\n *     PiniaColadaQueryHooksPlugin({\n *       onError(error, entry) {\n *         // ...\n *       },\n *     }),\n *   ],\n * })\n * ```\n */\nexport function PiniaColadaQueryHooksPlugin(\n  options: PiniaColadaQueryHooksPluginOptions,\n): PiniaColadaPlugin {\n  return ({ queryCache }) => {\n    queryCache.$onAction(({ name, after, onError, args }) => {\n      if (name === 'fetch') {\n        const [entry] = args\n        after(async ({ data }) => {\n          await options.onSuccess?.(data, entry)\n          options.onSettled?.(data, null, entry)\n        })\n\n        onError(async (error) => {\n          await options.onError?.(error, entry)\n          options.onSettled?.(undefined, error, entry)\n        })\n      }\n    })\n  }\n}\n","import type { PiniaColadaPlugin } from '.'\nimport { useMutationCache } from '../mutation-store'\n\n/**\n * Forces `gcTime: false` on every query and mutation entry, so no garbage\n * collection timers are scheduled. Designed for SSR / SSG / build pipelines\n * where pending `setTimeout` calls keep the Node.js process alive after\n * rendering completes, and where setTimeout closures retain entry memory\n * across requests.\n *\n * Apply conditionally — usually only on the server.\n *\n * @example\n * ```ts\n * import { PiniaColada, PiniaColadaSSRNoGc } from '@pinia/colada'\n *\n * app.use(PiniaColada, {\n *   plugins: import.meta.env.SSR ? [PiniaColadaSSRNoGc()] : [],\n * })\n * ```\n */\nexport function PiniaColadaSSRNoGc(): PiniaColadaPlugin {\n  return ({ queryCache, pinia }) => {\n    queryCache.$onAction(({ name, after }) => {\n      if (name === 'ensure') {\n        after((entry) => {\n          if (entry.options) entry.options.gcTime = false\n        })\n      }\n    })\n\n    const mutationCache = useMutationCache(pinia)\n    mutationCache.$onAction(({ name, after }) => {\n      if (name === 'extend') {\n        after((entry) => {\n          if (entry.options) entry.options.gcTime = false\n        })\n      }\n    })\n  }\n}\n"],"mappings":";;;;;;;;;;AAYA,SAAgB,WAAW,KAA+C;CACxE,OACE,OACA,KAAK,UAAU,MAAM,GAAG,QACtB,CAAC,OAAO,OAAO,QAAQ,YAAY,MAAM,QAAQ,IAAI,GACjD,MACA,OAAO,KAAK,IAAI,CACb,MAAM,CACN,QAAQ,QAAQ,QAAQ;EACvB,OAAO,OAAO,IAAI;EAClB,OAAO;IACN,EAAE,CAAQ,CACpB;;;;;;;;AAUL,SAAgB,WAAW,WAAqB,YAA+B;C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