Index: node_modules/@reduxjs/toolkit/src/actionCreatorInvariantMiddleware.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/actionCreatorInvariantMiddleware.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/actionCreatorInvariantMiddleware.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,34 @@
+import type { Middleware } from 'redux'
+import { isActionCreator as isRTKAction } from './createAction'
+
+export interface ActionCreatorInvariantMiddlewareOptions {
+  /**
+   * The function to identify whether a value is an action creator.
+   * The default checks for a function with a static type property and match method.
+   */
+  isActionCreator?: (action: unknown) => action is Function & { type?: unknown }
+}
+
+export function getMessage(type?: unknown) {
+  const splitType = type ? `${type}`.split('/') : []
+  const actionName = splitType[splitType.length - 1] || 'actionCreator'
+  return `Detected an action creator with type "${
+    type || 'unknown'
+  }" being dispatched. 
+Make sure you're calling the action creator before dispatching, i.e. \`dispatch(${actionName}())\` instead of \`dispatch(${actionName})\`. This is necessary even if the action has no payload.`
+}
+
+export function createActionCreatorInvariantMiddleware(
+  options: ActionCreatorInvariantMiddlewareOptions = {},
+): Middleware {
+  if (process.env.NODE_ENV === 'production') {
+    return () => (next) => (action) => next(action)
+  }
+  const { isActionCreator = isRTKAction } = options
+  return () => (next) => (action) => {
+    if (isActionCreator(action)) {
+      console.warn(getMessage(action.type))
+    }
+    return next(action)
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/autoBatchEnhancer.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/autoBatchEnhancer.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/autoBatchEnhancer.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,128 @@
+import type { StoreEnhancer } from 'redux'
+
+export const SHOULD_AUTOBATCH = 'RTK_autoBatch'
+
+export const prepareAutoBatched =
+  <T>() =>
+  (payload: T): { payload: T; meta: unknown } => ({
+    payload,
+    meta: { [SHOULD_AUTOBATCH]: true },
+  })
+
+const createQueueWithTimer = (timeout: number) => {
+  return (notify: () => void) => {
+    setTimeout(notify, timeout)
+  }
+}
+
+export type AutoBatchOptions =
+  | { type: 'tick' }
+  | { type: 'timer'; timeout: number }
+  | { type: 'raf' }
+  | { type: 'callback'; queueNotification: (notify: () => void) => void }
+
+/**
+ * A Redux store enhancer that watches for "low-priority" actions, and delays
+ * notifying subscribers until either the queued callback executes or the
+ * next "standard-priority" action is dispatched.
+ *
+ * This allows dispatching multiple "low-priority" actions in a row with only
+ * a single subscriber notification to the UI after the sequence of actions
+ * is finished, thus improving UI re-render performance.
+ *
+ * Watches for actions with the `action.meta[SHOULD_AUTOBATCH]` attribute.
+ * This can be added to `action.meta` manually, or by using the
+ * `prepareAutoBatched` helper.
+ *
+ * By default, it will queue a notification for the end of the event loop tick.
+ * However, you can pass several other options to configure the behavior:
+ * - `{type: 'tick'}`: queues using `queueMicrotask`
+ * - `{type: 'timer', timeout: number}`: queues using `setTimeout`
+ * - `{type: 'raf'}`: queues using `requestAnimationFrame` (default)
+ * - `{type: 'callback', queueNotification: (notify: () => void) => void}`: lets you provide your own callback
+ *
+ *
+ */
+export const autoBatchEnhancer =
+  (options: AutoBatchOptions = { type: 'raf' }): StoreEnhancer =>
+  (next) =>
+  (...args) => {
+    const store = next(...args)
+
+    let notifying = true
+    let shouldNotifyAtEndOfTick = false
+    let notificationQueued = false
+
+    const listeners = new Set<() => void>()
+
+    const queueCallback =
+      options.type === 'tick'
+        ? queueMicrotask
+        : options.type === 'raf'
+          ? // requestAnimationFrame won't exist in SSR environments. Fall back to a vague approximation just to keep from erroring.
+            typeof window !== 'undefined' && window.requestAnimationFrame
+            ? window.requestAnimationFrame
+            : createQueueWithTimer(10)
+          : options.type === 'callback'
+            ? options.queueNotification
+            : createQueueWithTimer(options.timeout)
+
+    const notifyListeners = () => {
+      // We're running at the end of the event loop tick.
+      // Run the real listener callbacks to actually update the UI.
+      notificationQueued = false
+      if (shouldNotifyAtEndOfTick) {
+        shouldNotifyAtEndOfTick = false
+        listeners.forEach((l) => l())
+      }
+    }
+
+    return Object.assign({}, store, {
+      // Override the base `store.subscribe` method to keep original listeners
+      // from running if we're delaying notifications
+      subscribe(listener: () => void) {
+        // Each wrapped listener will only call the real listener if
+        // the `notifying` flag is currently active when it's called.
+        // This lets the base store work as normal, while the actual UI
+        // update becomes controlled by this enhancer.
+        const wrappedListener: typeof listener = () => notifying && listener()
+        const unsubscribe = store.subscribe(wrappedListener)
+        listeners.add(listener)
+        return () => {
+          unsubscribe()
+          listeners.delete(listener)
+        }
+      },
+      // Override the base `store.dispatch` method so that we can check actions
+      // for the `shouldAutoBatch` flag and determine if batching is active
+      dispatch(action: any) {
+        try {
+          // If the action does _not_ have the `shouldAutoBatch` flag,
+          // we resume/continue normal notify-after-each-dispatch behavior
+          notifying = !action?.meta?.[SHOULD_AUTOBATCH]
+          // If a `notifyListeners` microtask was queued, you can't cancel it.
+          // Instead, we set a flag so that it's a no-op when it does run
+          shouldNotifyAtEndOfTick = !notifying
+          if (shouldNotifyAtEndOfTick) {
+            // We've seen at least 1 action with `SHOULD_AUTOBATCH`. Try to queue
+            // a microtask to notify listeners at the end of the event loop tick.
+            // Make sure we only enqueue this _once_ per tick.
+            if (!notificationQueued) {
+              notificationQueued = true
+              queueCallback(notifyListeners)
+            }
+          }
+          // Go ahead and process the action as usual, including reducers.
+          // If normal notification behavior is enabled, the store will notify
+          // all of its own listeners, and the wrapper callbacks above will
+          // see `notifying` is true and pass on to the real listener callbacks.
+          // If we're "batching" behavior, then the wrapped callbacks will
+          // bail out, causing the base store notification behavior to be no-ops.
+          return store.dispatch(action)
+        } finally {
+          // Assume we're back to normal behavior after each action
+          notifying = true
+        }
+      },
+    })
+  }
Index: node_modules/@reduxjs/toolkit/src/combineSlices.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/combineSlices.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/combineSlices.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,487 @@
+import type {
+  PreloadedStateShapeFromReducersMapObject,
+  Reducer,
+  StateFromReducersMapObject,
+  UnknownAction,
+} from 'redux'
+import { combineReducers } from 'redux'
+import { nanoid } from './nanoid'
+import type {
+  Id,
+  NonUndefined,
+  Tail,
+  UnionToIntersection,
+  WithOptionalProp,
+} from './tsHelpers'
+import { getOrInsertComputed } from './utils'
+
+type SliceLike<ReducerPath extends string, State, PreloadedState = State> = {
+  reducerPath: ReducerPath
+  reducer: Reducer<State, any, PreloadedState>
+}
+
+type AnySliceLike = SliceLike<string, any>
+
+type SliceLikeReducerPath<A extends AnySliceLike> =
+  A extends SliceLike<infer ReducerPath, any> ? ReducerPath : never
+
+type SliceLikeState<A extends AnySliceLike> =
+  A extends SliceLike<any, infer State, any> ? State : never
+
+type SliceLikePreloadedState<A extends AnySliceLike> =
+  A extends SliceLike<any, any, infer PreloadedState> ? PreloadedState : never
+
+export type WithSlice<A extends AnySliceLike> = {
+  [Path in SliceLikeReducerPath<A>]: SliceLikeState<A>
+}
+
+export type WithSlicePreloadedState<A extends AnySliceLike> = {
+  [Path in SliceLikeReducerPath<A>]: SliceLikePreloadedState<A>
+}
+
+type ReducerMap = Record<string, Reducer>
+
+type ExistingSliceLike<DeclaredState, PreloadedState> = {
+  [ReducerPath in keyof DeclaredState]: SliceLike<
+    ReducerPath & string,
+    NonUndefined<DeclaredState[ReducerPath]>,
+    NonUndefined<PreloadedState[ReducerPath & keyof PreloadedState]>
+  >
+}[keyof DeclaredState]
+
+export type InjectConfig = {
+  /**
+   * Allow replacing reducer with a different reference. Normally, an error will be thrown if a different reducer instance to the one already injected is used.
+   */
+  overrideExisting?: boolean
+}
+
+/**
+ * A reducer that allows for slices/reducers to be injected after initialisation.
+ */
+export interface CombinedSliceReducer<
+  InitialState,
+  DeclaredState extends InitialState = InitialState,
+  PreloadedState extends Partial<
+    Record<keyof PreloadedState, any>
+  > = Partial<DeclaredState>,
+> extends Reducer<DeclaredState, UnknownAction, PreloadedState> {
+  /**
+   * Provide a type for slices that will be injected lazily.
+   *
+   * One way to do this would be with interface merging:
+   * ```ts
+   *
+   * export interface LazyLoadedSlices {}
+   *
+   * export const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
+   *
+   * // elsewhere
+   *
+   * declare module './reducer' {
+   *   export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
+   * }
+   *
+   * const withBoolean = rootReducer.inject(booleanSlice);
+   *
+   * // elsewhere again
+   *
+   * declare module './reducer' {
+   *   export interface LazyLoadedSlices {
+   *     customName: CustomState
+   *   }
+   * }
+   *
+   * const withCustom = rootReducer.inject({ reducerPath: "customName", reducer: customSlice.reducer })
+   * ```
+   */
+  withLazyLoadedSlices<Lazy = {}, LazyPreloaded = Lazy>(): CombinedSliceReducer<
+    InitialState,
+    Id<DeclaredState & Partial<Lazy>>,
+    Id<PreloadedState & Partial<LazyPreloaded>>
+  >
+
+  /**
+   * Inject a slice.
+   *
+   * Accepts an individual slice, RTKQ API instance, or a "slice-like" { reducerPath, reducer } object.
+   *
+   * ```ts
+   * rootReducer.inject(booleanSlice)
+   * rootReducer.inject(baseApi)
+   * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })
+   * ```
+   *
+   */
+  inject<Sl extends Id<ExistingSliceLike<DeclaredState, PreloadedState>>>(
+    slice: Sl,
+    config?: InjectConfig,
+  ): CombinedSliceReducer<
+    InitialState,
+    Id<DeclaredState & WithSlice<Sl>>,
+    Id<PreloadedState & Partial<WithSlicePreloadedState<Sl>>>
+  >
+
+  /**
+   * Inject a slice.
+   *
+   * Accepts an individual slice, RTKQ API instance, or a "slice-like" { reducerPath, reducer } object.
+   *
+   * ```ts
+   * rootReducer.inject(booleanSlice)
+   * rootReducer.inject(baseApi)
+   * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })
+   * ```
+   *
+   */
+  inject<ReducerPath extends string, State, PreloadedState = State>(
+    slice: SliceLike<
+      ReducerPath,
+      State & (ReducerPath extends keyof DeclaredState ? never : State),
+      PreloadedState &
+        (ReducerPath extends keyof PreloadedState ? never : PreloadedState)
+    >,
+    config?: InjectConfig,
+  ): CombinedSliceReducer<
+    InitialState,
+    Id<DeclaredState & WithSlice<SliceLike<ReducerPath, State>>>,
+    Id<
+      PreloadedState &
+        WithSlicePreloadedState<SliceLike<ReducerPath, State, PreloadedState>>
+    >
+  >
+
+  /**
+   * Create a selector that guarantees that the slices injected will have a defined value when selector is run.
+   *
+   * ```ts
+   * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
+   * //                                                                ^? boolean | undefined
+   *
+   * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
+   *   // if action hasn't been dispatched since slice was injected, this would usually be undefined
+   *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
+   *   return state.boolean;
+   *   //           ^? boolean
+   * })
+   * ```
+   *
+   * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.
+   *
+   * ```ts
+   *
+   * export interface LazyLoadedSlices {};
+   *
+   * export const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
+   *
+   * export const rootReducer = combineSlices({ inner: innerReducer });
+   *
+   * export type RootState = ReturnType<typeof rootReducer>;
+   *
+   * // elsewhere
+   *
+   * declare module "./reducer.ts" {
+   *  export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
+   * }
+   *
+   * const withBool = innerReducer.inject(booleanSlice);
+   *
+   * const selectBoolean = withBool.selector(
+   *   (state) => state.boolean,
+   *   (rootState: RootState) => state.inner
+   * );
+   * //    now expects to be passed RootState instead of innerReducer state
+   *
+   * ```
+   *
+   * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
+   *
+   * ```ts
+   * const injectedReducer = rootReducer.inject(booleanSlice);
+   * const selectBoolean = injectedReducer.selector((state) => {
+   *   console.log(injectedReducer.selector.original(state).boolean) // possibly undefined
+   *   return state.boolean
+   * })
+   * ```
+   */
+  selector: {
+    /**
+     * Create a selector that guarantees that the slices injected will have a defined value when selector is run.
+     *
+     * ```ts
+     * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
+     * //                                                                ^? boolean | undefined
+     *
+     * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
+     *   // if action hasn't been dispatched since slice was injected, this would usually be undefined
+     *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
+     *   return state.boolean;
+     *   //           ^? boolean
+     * })
+     * ```
+     *
+     * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
+     *
+     * ```ts
+     * const injectedReducer = rootReducer.inject(booleanSlice);
+     * const selectBoolean = injectedReducer.selector((state) => {
+     *   console.log(injectedReducer.selector.original(state).boolean) // undefined
+     *   return state.boolean
+     * })
+     * ```
+     */
+    <Selector extends (state: DeclaredState, ...args: any[]) => unknown>(
+      selectorFn: Selector,
+    ): (
+      state: WithOptionalProp<
+        Parameters<Selector>[0],
+        Exclude<keyof DeclaredState, keyof InitialState>
+      >,
+      ...args: Tail<Parameters<Selector>>
+    ) => ReturnType<Selector>
+
+    /**
+     * Create a selector that guarantees that the slices injected will have a defined value when selector is run.
+     *
+     * ```ts
+     * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
+     * //                                                                ^? boolean | undefined
+     *
+     * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
+     *   // if action hasn't been dispatched since slice was injected, this would usually be undefined
+     *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
+     *   return state.boolean;
+     *   //           ^? boolean
+     * })
+     * ```
+     *
+     * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.
+     *
+     * ```ts
+     *
+     * interface LazyLoadedSlices {};
+     *
+     * const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
+     *
+     * const rootReducer = combineSlices({ inner: innerReducer });
+     *
+     * type RootState = ReturnType<typeof rootReducer>;
+     *
+     * // elsewhere
+     *
+     * declare module "./reducer.ts" {
+     *  interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
+     * }
+     *
+     * const withBool = innerReducer.inject(booleanSlice);
+     *
+     * const selectBoolean = withBool.selector(
+     *   (state) => state.boolean,
+     *   (rootState: RootState) => state.inner
+     * );
+     * //    now expects to be passed RootState instead of innerReducer state
+     *
+     * ```
+     *
+     * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
+     *
+     * ```ts
+     * const injectedReducer = rootReducer.inject(booleanSlice);
+     * const selectBoolean = injectedReducer.selector((state) => {
+     *   console.log(injectedReducer.selector.original(state).boolean) // possibly undefined
+     *   return state.boolean
+     * })
+     * ```
+     */
+    <
+      Selector extends (state: DeclaredState, ...args: any[]) => unknown,
+      RootState,
+    >(
+      selectorFn: Selector,
+      selectState: (
+        rootState: RootState,
+        ...args: Tail<Parameters<Selector>>
+      ) => WithOptionalProp<
+        Parameters<Selector>[0],
+        Exclude<keyof DeclaredState, keyof InitialState>
+      >,
+    ): (
+      state: RootState,
+      ...args: Tail<Parameters<Selector>>
+    ) => ReturnType<Selector>
+    /**
+     * Returns the unproxied state. Useful for debugging.
+     * @param state state Proxy, that ensures injected reducers have value
+     * @returns original, unproxied state
+     * @throws if value passed is not a state Proxy
+     */
+    original: (state: DeclaredState) => InitialState & Partial<DeclaredState>
+  }
+}
+
+type InitialState<Slices extends Array<AnySliceLike | ReducerMap>> =
+  UnionToIntersection<
+    Slices[number] extends infer Slice
+      ? Slice extends AnySliceLike
+        ? WithSlice<Slice>
+        : StateFromReducersMapObject<Slice>
+      : never
+  >
+
+type InitialPreloadedState<Slices extends Array<AnySliceLike | ReducerMap>> =
+  UnionToIntersection<
+    Slices[number] extends infer Slice
+      ? Slice extends AnySliceLike
+        ? WithSlicePreloadedState<Slice>
+        : PreloadedStateShapeFromReducersMapObject<Slice>
+      : never
+  >
+
+const isSliceLike = (
+  maybeSliceLike: AnySliceLike | ReducerMap,
+): maybeSliceLike is AnySliceLike =>
+  'reducerPath' in maybeSliceLike &&
+  typeof maybeSliceLike.reducerPath === 'string'
+
+const getReducers = (slices: Array<AnySliceLike | ReducerMap>) =>
+  slices.flatMap<[string, Reducer]>((sliceOrMap) =>
+    isSliceLike(sliceOrMap)
+      ? [[sliceOrMap.reducerPath, sliceOrMap.reducer]]
+      : Object.entries(sliceOrMap),
+  )
+
+const ORIGINAL_STATE = Symbol.for('rtk-state-proxy-original')
+
+const isStateProxy = (value: any) => !!value && !!value[ORIGINAL_STATE]
+
+const stateProxyMap = new WeakMap<object, object>()
+
+const createStateProxy = <State extends object>(
+  state: State,
+  reducerMap: Partial<Record<PropertyKey, Reducer>>,
+  initialStateCache: Record<PropertyKey, unknown>,
+) =>
+  getOrInsertComputed(
+    stateProxyMap,
+    state,
+    () =>
+      new Proxy(state, {
+        get: (target, prop, receiver) => {
+          if (prop === ORIGINAL_STATE) return target
+          const result = Reflect.get(target, prop, receiver)
+          if (typeof result === 'undefined') {
+            const cached = initialStateCache[prop]
+            if (typeof cached !== 'undefined') return cached
+            const reducer = reducerMap[prop]
+            if (reducer) {
+              // ensure action type is random, to prevent reducer treating it differently
+              const reducerResult = reducer(undefined, { type: nanoid() })
+              if (typeof reducerResult === 'undefined') {
+                throw new Error(
+                  `The slice reducer for key "${prop.toString()}" returned undefined when called for selector(). ` +
+                    `If the state passed to the reducer is undefined, you must ` +
+                    `explicitly return the initial state. The initial state may ` +
+                    `not be undefined. If you don't want to set a value for this reducer, ` +
+                    `you can use null instead of undefined.`,
+                )
+              }
+              initialStateCache[prop] = reducerResult
+              return reducerResult
+            }
+          }
+          return result
+        },
+      }),
+  ) as State
+
+const original = (state: any) => {
+  if (!isStateProxy(state)) {
+    throw new Error('original must be used on state Proxy')
+  }
+  return state[ORIGINAL_STATE]
+}
+
+const emptyObject = {}
+const noopReducer: Reducer<Record<string, any>> = (state = emptyObject) => state
+
+export function combineSlices<Slices extends Array<AnySliceLike | ReducerMap>>(
+  ...slices: Slices
+): CombinedSliceReducer<
+  Id<InitialState<Slices>>,
+  Id<InitialState<Slices>>,
+  Partial<Id<InitialPreloadedState<Slices>>>
+> {
+  const reducerMap = Object.fromEntries(getReducers(slices))
+
+  const getReducer = () =>
+    Object.keys(reducerMap).length ? combineReducers(reducerMap) : noopReducer
+
+  let reducer = getReducer()
+
+  function combinedReducer(
+    state: Record<string, unknown>,
+    action: UnknownAction,
+  ) {
+    return reducer(state, action)
+  }
+
+  combinedReducer.withLazyLoadedSlices = () => combinedReducer
+
+  const initialStateCache: Record<PropertyKey, unknown> = {}
+
+  const inject = (
+    slice: AnySliceLike,
+    config: InjectConfig = {},
+  ): typeof combinedReducer => {
+    const { reducerPath, reducer: reducerToInject } = slice
+
+    const currentReducer = reducerMap[reducerPath]
+    if (
+      !config.overrideExisting &&
+      currentReducer &&
+      currentReducer !== reducerToInject
+    ) {
+      if (
+        typeof process !== 'undefined' &&
+        process.env.NODE_ENV === 'development'
+      ) {
+        console.error(
+          `called \`inject\` to override already-existing reducer ${reducerPath} without specifying \`overrideExisting: true\``,
+        )
+      }
+
+      return combinedReducer
+    }
+
+    if (config.overrideExisting && currentReducer !== reducerToInject) {
+      delete initialStateCache[reducerPath]
+    }
+
+    reducerMap[reducerPath] = reducerToInject
+
+    reducer = getReducer()
+
+    return combinedReducer
+  }
+
+  const selector = Object.assign(
+    function makeSelector<State extends object, RootState, Args extends any[]>(
+      selectorFn: (state: State, ...args: Args) => any,
+      selectState?: (rootState: RootState, ...args: Args) => State,
+    ) {
+      return function selector(state: State, ...args: Args) {
+        return selectorFn(
+          createStateProxy(
+            selectState ? selectState(state as any, ...args) : state,
+            reducerMap,
+            initialStateCache,
+          ),
+          ...args,
+        )
+      }
+    },
+    { original },
+  )
+
+  return Object.assign(combinedReducer, { inject, selector }) as any
+}
Index: node_modules/@reduxjs/toolkit/src/configureStore.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/configureStore.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/configureStore.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,248 @@
+import type {
+  Reducer,
+  ReducersMapObject,
+  Middleware,
+  Action,
+  StoreEnhancer,
+  Store,
+  UnknownAction,
+} from 'redux'
+import {
+  applyMiddleware,
+  createStore,
+  compose,
+  combineReducers,
+  isPlainObject,
+} from './reduxImports'
+import type { DevToolsEnhancerOptions as DevToolsOptions } from './devtoolsExtension'
+import { composeWithDevTools } from './devtoolsExtension'
+
+import type {
+  ThunkMiddlewareFor,
+  GetDefaultMiddleware,
+} from './getDefaultMiddleware'
+import { buildGetDefaultMiddleware } from './getDefaultMiddleware'
+import type {
+  ExtractDispatchExtensions,
+  ExtractStoreExtensions,
+  ExtractStateExtensions,
+  UnknownIfNonSpecific,
+} from './tsHelpers'
+import type { Tuple } from './utils'
+import type { GetDefaultEnhancers } from './getDefaultEnhancers'
+import { buildGetDefaultEnhancers } from './getDefaultEnhancers'
+
+/**
+ * Options for `configureStore()`.
+ *
+ * @public
+ */
+export interface ConfigureStoreOptions<
+  S = any,
+  A extends Action = UnknownAction,
+  M extends Tuple<Middlewares<S>> = Tuple<Middlewares<S>>,
+  E extends Tuple<Enhancers> = Tuple<Enhancers>,
+  P = S,
+> {
+  /**
+   * A single reducer function that will be used as the root reducer, or an
+   * object of slice reducers that will be passed to `combineReducers()`.
+   */
+  reducer: Reducer<S, A, P> | ReducersMapObject<S, A, P>
+
+  /**
+   * An array of Redux middleware to install, or a callback receiving `getDefaultMiddleware` and returning a Tuple of middleware.
+   * If not supplied, defaults to the set of middleware returned by `getDefaultMiddleware()`.
+   *
+   * @example `middleware: (gDM) => gDM().concat(logger, apiMiddleware, yourCustomMiddleware)`
+   * @see https://redux-toolkit.js.org/api/getDefaultMiddleware#intended-usage
+   */
+  middleware?: (getDefaultMiddleware: GetDefaultMiddleware<S>) => M
+
+  /**
+   * Whether to enable Redux DevTools integration. Defaults to `true`.
+   *
+   * Additional configuration can be done by passing Redux DevTools options
+   */
+  devTools?: boolean | DevToolsOptions
+
+  /**
+   * Whether to check for duplicate middleware instances. Defaults to `true`.
+   */
+  duplicateMiddlewareCheck?: boolean
+
+  /**
+   * The initial state, same as Redux's createStore.
+   * You may optionally specify it to hydrate the state
+   * from the server in universal apps, or to restore a previously serialized
+   * user session. If you use `combineReducers()` to produce the root reducer
+   * function (either directly or indirectly by passing an object as `reducer`),
+   * this must be an object with the same shape as the reducer map keys.
+   */
+  // we infer here, and instead complain if the reducer doesn't match
+  preloadedState?: P
+
+  /**
+   * The store enhancers to apply. See Redux's `createStore()`.
+   * All enhancers will be included before the DevTools Extension enhancer.
+   * If you need to customize the order of enhancers, supply a callback
+   * function that will receive a `getDefaultEnhancers` function that returns a Tuple,
+   * and should return a Tuple of enhancers (such as `getDefaultEnhancers().concat(offline)`).
+   * If you only need to add middleware, you can use the `middleware` parameter instead.
+   */
+  enhancers?: (getDefaultEnhancers: GetDefaultEnhancers<M>) => E
+}
+
+export type Middlewares<S> = ReadonlyArray<Middleware<{}, S>>
+
+type Enhancers = ReadonlyArray<StoreEnhancer>
+
+/**
+ * A Redux store returned by `configureStore()`. Supports dispatching
+ * side-effectful _thunks_ in addition to plain actions.
+ *
+ * @public
+ */
+export type EnhancedStore<
+  S = any,
+  A extends Action = UnknownAction,
+  E extends Enhancers = Enhancers,
+> = ExtractStoreExtensions<E> &
+  Store<S, A, UnknownIfNonSpecific<ExtractStateExtensions<E>>>
+
+/**
+ * A friendly abstraction over the standard Redux `createStore()` function.
+ *
+ * @param options The store configuration.
+ * @returns A configured Redux store.
+ *
+ * @public
+ */
+export function configureStore<
+  S = any,
+  A extends Action = UnknownAction,
+  M extends Tuple<Middlewares<S>> = Tuple<[ThunkMiddlewareFor<S>]>,
+  E extends Tuple<Enhancers> = Tuple<
+    [StoreEnhancer<{ dispatch: ExtractDispatchExtensions<M> }>, StoreEnhancer]
+  >,
+  P = S,
+>(options: ConfigureStoreOptions<S, A, M, E, P>): EnhancedStore<S, A, E> {
+  const getDefaultMiddleware = buildGetDefaultMiddleware<S>()
+
+  const {
+    reducer = undefined,
+    middleware,
+    devTools = true,
+    duplicateMiddlewareCheck = true,
+    preloadedState = undefined,
+    enhancers = undefined,
+  } = options || {}
+
+  let rootReducer: Reducer<S, A, P>
+
+  if (typeof reducer === 'function') {
+    rootReducer = reducer
+  } else if (isPlainObject(reducer)) {
+    rootReducer = combineReducers(reducer) as unknown as Reducer<S, A, P>
+  } else {
+    throw new Error(
+      '`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers',
+    )
+  }
+
+  if (
+    process.env.NODE_ENV !== 'production' &&
+    middleware &&
+    typeof middleware !== 'function'
+  ) {
+    throw new Error('`middleware` field must be a callback')
+  }
+
+  let finalMiddleware: Tuple<Middlewares<S>>
+  if (typeof middleware === 'function') {
+    finalMiddleware = middleware(getDefaultMiddleware)
+
+    if (
+      process.env.NODE_ENV !== 'production' &&
+      !Array.isArray(finalMiddleware)
+    ) {
+      throw new Error(
+        'when using a middleware builder function, an array of middleware must be returned',
+      )
+    }
+  } else {
+    finalMiddleware = getDefaultMiddleware()
+  }
+  if (
+    process.env.NODE_ENV !== 'production' &&
+    finalMiddleware.some((item: any) => typeof item !== 'function')
+  ) {
+    throw new Error(
+      'each middleware provided to configureStore must be a function',
+    )
+  }
+
+  if (process.env.NODE_ENV !== 'production' && duplicateMiddlewareCheck) {
+    let middlewareReferences = new Set<Middleware<any, S>>()
+    finalMiddleware.forEach((middleware) => {
+      if (middlewareReferences.has(middleware)) {
+        throw new Error(
+          'Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.',
+        )
+      }
+      middlewareReferences.add(middleware)
+    })
+  }
+
+  let finalCompose = compose
+
+  if (devTools) {
+    finalCompose = composeWithDevTools({
+      // Enable capture of stack traces for dispatched Redux actions
+      trace: process.env.NODE_ENV !== 'production',
+      ...(typeof devTools === 'object' && devTools),
+    })
+  }
+
+  const middlewareEnhancer = applyMiddleware(...finalMiddleware)
+
+  const getDefaultEnhancers = buildGetDefaultEnhancers<M>(middlewareEnhancer)
+
+  if (
+    process.env.NODE_ENV !== 'production' &&
+    enhancers &&
+    typeof enhancers !== 'function'
+  ) {
+    throw new Error('`enhancers` field must be a callback')
+  }
+
+  let storeEnhancers =
+    typeof enhancers === 'function'
+      ? enhancers(getDefaultEnhancers)
+      : getDefaultEnhancers()
+
+  if (process.env.NODE_ENV !== 'production' && !Array.isArray(storeEnhancers)) {
+    throw new Error('`enhancers` callback must return an array')
+  }
+  if (
+    process.env.NODE_ENV !== 'production' &&
+    storeEnhancers.some((item: any) => typeof item !== 'function')
+  ) {
+    throw new Error(
+      'each enhancer provided to configureStore must be a function',
+    )
+  }
+  if (
+    process.env.NODE_ENV !== 'production' &&
+    finalMiddleware.length &&
+    !storeEnhancers.includes(middlewareEnhancer)
+  ) {
+    console.error(
+      'middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`',
+    )
+  }
+
+  const composedEnhancer: StoreEnhancer<any> = finalCompose(...storeEnhancers)
+
+  return createStore(rootReducer, preloadedState as P, composedEnhancer)
+}
Index: node_modules/@reduxjs/toolkit/src/createAction.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/createAction.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/createAction.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,324 @@
+import { isAction } from './reduxImports'
+import type {
+  IsUnknownOrNonInferrable,
+  IfMaybeUndefined,
+  IfVoid,
+  IsAny,
+} from './tsHelpers'
+import { hasMatchFunction } from './tsHelpers'
+
+/**
+ * An action with a string type and an associated payload. This is the
+ * type of action returned by `createAction()` action creators.
+ *
+ * @template P The type of the action's payload.
+ * @template T the type used for the action type.
+ * @template M The type of the action's meta (optional)
+ * @template E The type of the action's error (optional)
+ *
+ * @public
+ */
+export type PayloadAction<
+  P = void,
+  T extends string = string,
+  M = never,
+  E = never,
+> = {
+  payload: P
+  type: T
+} & ([M] extends [never]
+  ? {}
+  : {
+      meta: M
+    }) &
+  ([E] extends [never]
+    ? {}
+    : {
+        error: E
+      })
+
+/**
+ * A "prepare" method to be used as the second parameter of `createAction`.
+ * Takes any number of arguments and returns a Flux Standard Action without
+ * type (will be added later) that *must* contain a payload (might be undefined).
+ *
+ * @public
+ */
+export type PrepareAction<P> =
+  | ((...args: any[]) => { payload: P })
+  | ((...args: any[]) => { payload: P; meta: any })
+  | ((...args: any[]) => { payload: P; error: any })
+  | ((...args: any[]) => { payload: P; meta: any; error: any })
+
+/**
+ * Internal version of `ActionCreatorWithPreparedPayload`. Not to be used externally.
+ *
+ * @internal
+ */
+export type _ActionCreatorWithPreparedPayload<
+  PA extends PrepareAction<any> | void,
+  T extends string = string,
+> =
+  PA extends PrepareAction<infer P>
+    ? ActionCreatorWithPreparedPayload<
+        Parameters<PA>,
+        P,
+        T,
+        ReturnType<PA> extends {
+          error: infer E
+        }
+          ? E
+          : never,
+        ReturnType<PA> extends {
+          meta: infer M
+        }
+          ? M
+          : never
+      >
+    : void
+
+/**
+ * Basic type for all action creators.
+ *
+ * @inheritdoc {redux#ActionCreator}
+ */
+export type BaseActionCreator<P, T extends string, M = never, E = never> = {
+  type: T
+  match: (action: unknown) => action is PayloadAction<P, T, M, E>
+}
+
+/**
+ * An action creator that takes multiple arguments that are passed
+ * to a `PrepareAction` method to create the final Action.
+ * @typeParam Args arguments for the action creator function
+ * @typeParam P `payload` type
+ * @typeParam T `type` name
+ * @typeParam E optional `error` type
+ * @typeParam M optional `meta` type
+ *
+ * @inheritdoc {redux#ActionCreator}
+ *
+ * @public
+ */
+export interface ActionCreatorWithPreparedPayload<
+  Args extends unknown[],
+  P,
+  T extends string = string,
+  E = never,
+  M = never,
+> extends BaseActionCreator<P, T, M, E> {
+  /**
+   * Calling this {@link redux#ActionCreator} with `Args` will return
+   * an Action with a payload of type `P` and (depending on the `PrepareAction`
+   * method used) a `meta`- and `error` property of types `M` and `E` respectively.
+   */
+  (...args: Args): PayloadAction<P, T, M, E>
+}
+
+/**
+ * An action creator of type `T` that takes an optional payload of type `P`.
+ *
+ * @inheritdoc {redux#ActionCreator}
+ *
+ * @public
+ */
+export interface ActionCreatorWithOptionalPayload<P, T extends string = string>
+  extends BaseActionCreator<P, T> {
+  /**
+   * Calling this {@link redux#ActionCreator} with an argument will
+   * return a {@link PayloadAction} of type `T` with a payload of `P`.
+   * Calling it without an argument will return a PayloadAction with a payload of `undefined`.
+   */
+  (payload?: P): PayloadAction<P, T>
+}
+
+/**
+ * An action creator of type `T` that takes no payload.
+ *
+ * @inheritdoc {redux#ActionCreator}
+ *
+ * @public
+ */
+export interface ActionCreatorWithoutPayload<T extends string = string>
+  extends BaseActionCreator<undefined, T> {
+  /**
+   * Calling this {@link redux#ActionCreator} will
+   * return a {@link PayloadAction} of type `T` with a payload of `undefined`
+   */
+  (noArgument: void): PayloadAction<undefined, T>
+}
+
+/**
+ * An action creator of type `T` that requires a payload of type P.
+ *
+ * @inheritdoc {redux#ActionCreator}
+ *
+ * @public
+ */
+export interface ActionCreatorWithPayload<P, T extends string = string>
+  extends BaseActionCreator<P, T> {
+  /**
+   * Calling this {@link redux#ActionCreator} with an argument will
+   * return a {@link PayloadAction} of type `T` with a payload of `P`
+   */
+  (payload: P): PayloadAction<P, T>
+}
+
+/**
+ * An action creator of type `T` whose `payload` type could not be inferred. Accepts everything as `payload`.
+ *
+ * @inheritdoc {redux#ActionCreator}
+ *
+ * @public
+ */
+export interface ActionCreatorWithNonInferrablePayload<
+  T extends string = string,
+> extends BaseActionCreator<unknown, T> {
+  /**
+   * Calling this {@link redux#ActionCreator} with an argument will
+   * return a {@link PayloadAction} of type `T` with a payload
+   * of exactly the type of the argument.
+   */
+  <PT extends unknown>(payload: PT): PayloadAction<PT, T>
+}
+
+/**
+ * An action creator that produces actions with a `payload` attribute.
+ *
+ * @typeParam P the `payload` type
+ * @typeParam T the `type` of the resulting action
+ * @typeParam PA if the resulting action is preprocessed by a `prepare` method, the signature of said method.
+ *
+ * @public
+ */
+export type PayloadActionCreator<
+  P = void,
+  T extends string = string,
+  PA extends PrepareAction<P> | void = void,
+> = IfPrepareActionMethodProvided<
+  PA,
+  _ActionCreatorWithPreparedPayload<PA, T>,
+  // else
+  IsAny<
+    P,
+    ActionCreatorWithPayload<any, T>,
+    IsUnknownOrNonInferrable<
+      P,
+      ActionCreatorWithNonInferrablePayload<T>,
+      // else
+      IfVoid<
+        P,
+        ActionCreatorWithoutPayload<T>,
+        // else
+        IfMaybeUndefined<
+          P,
+          ActionCreatorWithOptionalPayload<P, T>,
+          // else
+          ActionCreatorWithPayload<P, T>
+        >
+      >
+    >
+  >
+>
+
+/**
+ * A utility function to create an action creator for the given action type
+ * string. The action creator accepts a single argument, which will be included
+ * in the action object as a field called payload. The action creator function
+ * will also have its toString() overridden so that it returns the action type.
+ *
+ * @param type The action type to use for created actions.
+ * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
+ *                If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
+ *
+ * @public
+ */
+export function createAction<P = void, T extends string = string>(
+  type: T,
+): PayloadActionCreator<P, T>
+
+/**
+ * A utility function to create an action creator for the given action type
+ * string. The action creator accepts a single argument, which will be included
+ * in the action object as a field called payload. The action creator function
+ * will also have its toString() overridden so that it returns the action type.
+ *
+ * @param type The action type to use for created actions.
+ * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
+ *                If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
+ *
+ * @public
+ */
+export function createAction<
+  PA extends PrepareAction<any>,
+  T extends string = string,
+>(
+  type: T,
+  prepareAction: PA,
+): PayloadActionCreator<ReturnType<PA>['payload'], T, PA>
+
+export function createAction(type: string, prepareAction?: Function): any {
+  function actionCreator(...args: any[]) {
+    if (prepareAction) {
+      let prepared = prepareAction(...args)
+      if (!prepared) {
+        throw new Error('prepareAction did not return an object')
+      }
+
+      return {
+        type,
+        payload: prepared.payload,
+        ...('meta' in prepared && { meta: prepared.meta }),
+        ...('error' in prepared && { error: prepared.error }),
+      }
+    }
+    return { type, payload: args[0] }
+  }
+
+  actionCreator.toString = () => `${type}`
+
+  actionCreator.type = type
+
+  actionCreator.match = (action: unknown): action is PayloadAction =>
+    isAction(action) && action.type === type
+
+  return actionCreator
+}
+
+/**
+ * Returns true if value is an RTK-like action creator, with a static type property and match method.
+ */
+export function isActionCreator(
+  action: unknown,
+): action is BaseActionCreator<unknown, string> & Function {
+  return (
+    typeof action === 'function' &&
+    'type' in action &&
+    // hasMatchFunction only wants Matchers but I don't see the point in rewriting it
+    hasMatchFunction(action as any)
+  )
+}
+
+/**
+ * Returns true if value is an action with a string type and valid Flux Standard Action keys.
+ */
+export function isFSA(action: unknown): action is {
+  type: string
+  payload?: unknown
+  error?: unknown
+  meta?: unknown
+} {
+  return isAction(action) && Object.keys(action).every(isValidKey)
+}
+
+function isValidKey(key: string) {
+  return ['type', 'payload', 'error', 'meta'].indexOf(key) > -1
+}
+
+// helper types for more readable typings
+
+type IfPrepareActionMethodProvided<
+  PA extends PrepareAction<any> | void,
+  True,
+  False,
+> = PA extends (...args: any[]) => any ? True : False
Index: node_modules/@reduxjs/toolkit/src/createAsyncThunk.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/createAsyncThunk.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/createAsyncThunk.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,791 @@
+import type { Dispatch, UnknownAction } from 'redux'
+import type { ThunkDispatch } from 'redux-thunk'
+import type { ActionCreatorWithPreparedPayload } from './createAction'
+import { createAction } from './createAction'
+import { isAnyOf } from './matchers'
+import { nanoid } from './nanoid'
+import type {
+  FallbackIfUnknown,
+  Id,
+  IsAny,
+  IsUnknown,
+  SafePromise,
+} from './tsHelpers'
+
+export type BaseThunkAPI<
+  S,
+  E,
+  D extends Dispatch = Dispatch,
+  RejectedValue = unknown,
+  RejectedMeta = unknown,
+  FulfilledMeta = unknown,
+> = {
+  dispatch: D
+  getState: () => S
+  extra: E
+  requestId: string
+  signal: AbortSignal
+  abort: (reason?: string) => void
+  rejectWithValue: IsUnknown<
+    RejectedMeta,
+    (value: RejectedValue) => RejectWithValue<RejectedValue, RejectedMeta>,
+    (
+      value: RejectedValue,
+      meta: RejectedMeta,
+    ) => RejectWithValue<RejectedValue, RejectedMeta>
+  >
+  fulfillWithValue: IsUnknown<
+    FulfilledMeta,
+    <FulfilledValue>(value: FulfilledValue) => FulfilledValue,
+    <FulfilledValue>(
+      value: FulfilledValue,
+      meta: FulfilledMeta,
+    ) => FulfillWithMeta<FulfilledValue, FulfilledMeta>
+  >
+}
+
+/**
+ * @public
+ */
+export interface SerializedError {
+  name?: string
+  message?: string
+  stack?: string
+  code?: string
+}
+
+const commonProperties: Array<keyof SerializedError> = [
+  'name',
+  'message',
+  'stack',
+  'code',
+]
+
+class RejectWithValue<Payload, RejectedMeta> {
+  /*
+  type-only property to distinguish between RejectWithValue and FulfillWithMeta
+  does not exist at runtime
+  */
+  private readonly _type!: 'RejectWithValue'
+  constructor(
+    public readonly payload: Payload,
+    public readonly meta: RejectedMeta,
+  ) {}
+}
+
+class FulfillWithMeta<Payload, FulfilledMeta> {
+  /*
+  type-only property to distinguish between RejectWithValue and FulfillWithMeta
+  does not exist at runtime
+  */
+  private readonly _type!: 'FulfillWithMeta'
+  constructor(
+    public readonly payload: Payload,
+    public readonly meta: FulfilledMeta,
+  ) {}
+}
+
+/**
+ * Serializes an error into a plain object.
+ * Reworked from https://github.com/sindresorhus/serialize-error
+ *
+ * @public
+ */
+export const miniSerializeError = (value: any): SerializedError => {
+  if (typeof value === 'object' && value !== null) {
+    const simpleError: SerializedError = {}
+    for (const property of commonProperties) {
+      if (typeof value[property] === 'string') {
+        simpleError[property] = value[property]
+      }
+    }
+
+    return simpleError
+  }
+
+  return { message: String(value) }
+}
+
+export type AsyncThunkConfig = {
+  state?: unknown
+  dispatch?: ThunkDispatch<unknown, unknown, UnknownAction>
+  extra?: unknown
+  rejectValue?: unknown
+  serializedErrorType?: unknown
+  pendingMeta?: unknown
+  fulfilledMeta?: unknown
+  rejectedMeta?: unknown
+}
+
+export type GetState<ThunkApiConfig> = ThunkApiConfig extends {
+  state: infer State
+}
+  ? State
+  : unknown
+
+type GetExtra<ThunkApiConfig> = ThunkApiConfig extends { extra: infer Extra }
+  ? Extra
+  : unknown
+type GetDispatch<ThunkApiConfig> = ThunkApiConfig extends {
+  dispatch: infer Dispatch
+}
+  ? FallbackIfUnknown<
+      Dispatch,
+      ThunkDispatch<
+        GetState<ThunkApiConfig>,
+        GetExtra<ThunkApiConfig>,
+        UnknownAction
+      >
+    >
+  : ThunkDispatch<
+      GetState<ThunkApiConfig>,
+      GetExtra<ThunkApiConfig>,
+      UnknownAction
+    >
+
+export type GetThunkAPI<ThunkApiConfig> = BaseThunkAPI<
+  GetState<ThunkApiConfig>,
+  GetExtra<ThunkApiConfig>,
+  GetDispatch<ThunkApiConfig>,
+  GetRejectValue<ThunkApiConfig>,
+  GetRejectedMeta<ThunkApiConfig>,
+  GetFulfilledMeta<ThunkApiConfig>
+>
+
+type GetRejectValue<ThunkApiConfig> = ThunkApiConfig extends {
+  rejectValue: infer RejectValue
+}
+  ? RejectValue
+  : unknown
+
+type GetPendingMeta<ThunkApiConfig> = ThunkApiConfig extends {
+  pendingMeta: infer PendingMeta
+}
+  ? PendingMeta
+  : unknown
+
+type GetFulfilledMeta<ThunkApiConfig> = ThunkApiConfig extends {
+  fulfilledMeta: infer FulfilledMeta
+}
+  ? FulfilledMeta
+  : unknown
+
+type GetRejectedMeta<ThunkApiConfig> = ThunkApiConfig extends {
+  rejectedMeta: infer RejectedMeta
+}
+  ? RejectedMeta
+  : unknown
+
+type GetSerializedErrorType<ThunkApiConfig> = ThunkApiConfig extends {
+  serializedErrorType: infer GetSerializedErrorType
+}
+  ? GetSerializedErrorType
+  : SerializedError
+
+type MaybePromise<T> = T | Promise<T> | (T extends any ? Promise<T> : never)
+
+/**
+ * A type describing the return value of the `payloadCreator` argument to `createAsyncThunk`.
+ * Might be useful for wrapping `createAsyncThunk` in custom abstractions.
+ *
+ * @public
+ */
+export type AsyncThunkPayloadCreatorReturnValue<
+  Returned,
+  ThunkApiConfig extends AsyncThunkConfig,
+> = MaybePromise<
+  | IsUnknown<
+      GetFulfilledMeta<ThunkApiConfig>,
+      Returned,
+      FulfillWithMeta<Returned, GetFulfilledMeta<ThunkApiConfig>>
+    >
+  | RejectWithValue<
+      GetRejectValue<ThunkApiConfig>,
+      GetRejectedMeta<ThunkApiConfig>
+    >
+>
+/**
+ * A type describing the `payloadCreator` argument to `createAsyncThunk`.
+ * Might be useful for wrapping `createAsyncThunk` in custom abstractions.
+ *
+ * @public
+ */
+export type AsyncThunkPayloadCreator<
+  Returned,
+  ThunkArg = void,
+  ThunkApiConfig extends AsyncThunkConfig = {},
+> = (
+  arg: ThunkArg,
+  thunkAPI: GetThunkAPI<ThunkApiConfig>,
+) => AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig>
+
+/**
+ * A ThunkAction created by `createAsyncThunk`.
+ * Dispatching it returns a Promise for either a
+ * fulfilled or rejected action.
+ * Also, the returned value contains an `abort()` method
+ * that allows the asyncAction to be cancelled from the outside.
+ *
+ * @public
+ */
+export type AsyncThunkAction<
+  Returned,
+  ThunkArg,
+  ThunkApiConfig extends AsyncThunkConfig,
+> = (
+  dispatch: NonNullable<GetDispatch<ThunkApiConfig>>,
+  getState: () => GetState<ThunkApiConfig>,
+  extra: GetExtra<ThunkApiConfig>,
+) => SafePromise<
+  | ReturnType<AsyncThunkFulfilledActionCreator<Returned, ThunkArg>>
+  | ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>>
+> & {
+  abort: (reason?: string) => void
+  requestId: string
+  arg: ThunkArg
+  unwrap: () => Promise<Returned>
+}
+
+/**
+ * Config provided when calling the async thunk action creator.
+ */
+export interface AsyncThunkDispatchConfig {
+  /**
+   * An external `AbortSignal` that will be tracked by the internal `AbortSignal`.
+   */
+  signal?: AbortSignal
+}
+
+type AsyncThunkActionCreator<
+  Returned,
+  ThunkArg,
+  ThunkApiConfig extends AsyncThunkConfig,
+> = IsAny<
+  ThunkArg,
+  // any handling
+  (
+    arg: ThunkArg,
+    config?: AsyncThunkDispatchConfig,
+  ) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,
+  // unknown handling
+  unknown extends ThunkArg
+    ? (
+        arg: ThunkArg,
+        config?: AsyncThunkDispatchConfig,
+      ) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument not specified or specified as void or undefined
+    : [ThunkArg] extends [void] | [undefined]
+      ? (
+          arg?: undefined,
+          config?: AsyncThunkDispatchConfig,
+        ) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains void
+      : [void] extends [ThunkArg] // make optional
+        ? (
+            arg?: ThunkArg,
+            config?: AsyncThunkDispatchConfig,
+          ) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains undefined
+        : [undefined] extends [ThunkArg]
+          ? WithStrictNullChecks<
+              // with strict nullChecks: make optional
+              (
+                arg?: ThunkArg,
+                config?: AsyncThunkDispatchConfig,
+              ) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,
+              // without strict null checks this will match everything, so don't make it optional
+              (
+                arg: ThunkArg,
+                config?: AsyncThunkDispatchConfig,
+              ) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>
+            > // default case: normal argument
+          : (
+              arg: ThunkArg,
+              config?: AsyncThunkDispatchConfig,
+            ) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>
+>
+
+/**
+ * Options object for `createAsyncThunk`.
+ *
+ * @public
+ */
+export type AsyncThunkOptions<
+  ThunkArg = void,
+  ThunkApiConfig extends AsyncThunkConfig = {},
+> = {
+  /**
+   * A method to control whether the asyncThunk should be executed. Has access to the
+   * `arg`, `api.getState()` and `api.extra` arguments.
+   *
+   * @returns `false` if it should be skipped
+   */
+  condition?(
+    arg: ThunkArg,
+    api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>,
+  ): MaybePromise<boolean | undefined>
+  /**
+   * If `condition` returns `false`, the asyncThunk will be skipped.
+   * This option allows you to control whether a `rejected` action with `meta.condition == false`
+   * will be dispatched or not.
+   *
+   * @default `false`
+   */
+  dispatchConditionRejection?: boolean
+
+  serializeError?: (x: unknown) => GetSerializedErrorType<ThunkApiConfig>
+
+  /**
+   * A function to use when generating the `requestId` for the request sequence.
+   *
+   * @default `nanoid`
+   */
+  idGenerator?: (arg: ThunkArg) => string
+} & IsUnknown<
+  GetPendingMeta<ThunkApiConfig>,
+  {
+    /**
+     * A method to generate additional properties to be added to `meta` of the pending action.
+     *
+     * Using this optional overload will not modify the types correctly, this overload is only in place to support JavaScript users.
+     * Please use the `ThunkApiConfig` parameter `pendingMeta` to get access to a correctly typed overload
+     */
+    getPendingMeta?(
+      base: {
+        arg: ThunkArg
+        requestId: string
+      },
+      api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>,
+    ): GetPendingMeta<ThunkApiConfig>
+  },
+  {
+    /**
+     * A method to generate additional properties to be added to `meta` of the pending action.
+     */
+    getPendingMeta(
+      base: {
+        arg: ThunkArg
+        requestId: string
+      },
+      api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>,
+    ): GetPendingMeta<ThunkApiConfig>
+  }
+>
+
+export type AsyncThunkPendingActionCreator<
+  ThunkArg,
+  ThunkApiConfig = {},
+> = ActionCreatorWithPreparedPayload<
+  [string, ThunkArg, GetPendingMeta<ThunkApiConfig>?],
+  undefined,
+  string,
+  never,
+  {
+    arg: ThunkArg
+    requestId: string
+    requestStatus: 'pending'
+  } & GetPendingMeta<ThunkApiConfig>
+>
+
+export type AsyncThunkRejectedActionCreator<
+  ThunkArg,
+  ThunkApiConfig = {},
+> = ActionCreatorWithPreparedPayload<
+  [
+    Error | null,
+    string,
+    ThunkArg,
+    GetRejectValue<ThunkApiConfig>?,
+    GetRejectedMeta<ThunkApiConfig>?,
+  ],
+  GetRejectValue<ThunkApiConfig> | undefined,
+  string,
+  GetSerializedErrorType<ThunkApiConfig>,
+  {
+    arg: ThunkArg
+    requestId: string
+    requestStatus: 'rejected'
+    aborted: boolean
+    condition: boolean
+  } & (
+    | ({ rejectedWithValue: false } & {
+        [K in keyof GetRejectedMeta<ThunkApiConfig>]?: undefined
+      })
+    | ({ rejectedWithValue: true } & GetRejectedMeta<ThunkApiConfig>)
+  )
+>
+
+export type AsyncThunkFulfilledActionCreator<
+  Returned,
+  ThunkArg,
+  ThunkApiConfig = {},
+> = ActionCreatorWithPreparedPayload<
+  [Returned, string, ThunkArg, GetFulfilledMeta<ThunkApiConfig>?],
+  Returned,
+  string,
+  never,
+  {
+    arg: ThunkArg
+    requestId: string
+    requestStatus: 'fulfilled'
+  } & GetFulfilledMeta<ThunkApiConfig>
+>
+
+/**
+ * A type describing the return value of `createAsyncThunk`.
+ * Might be useful for wrapping `createAsyncThunk` in custom abstractions.
+ *
+ * @public
+ */
+export type AsyncThunk<
+  Returned,
+  ThunkArg,
+  ThunkApiConfig extends AsyncThunkConfig,
+> = AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig> & {
+  pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig>
+  rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>
+  fulfilled: AsyncThunkFulfilledActionCreator<
+    Returned,
+    ThunkArg,
+    ThunkApiConfig
+  >
+  // matchSettled?
+  settled: (
+    action: any,
+  ) => action is ReturnType<
+    | AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>
+    | AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>
+  >
+  typePrefix: string
+}
+
+export type OverrideThunkApiConfigs<OldConfig, NewConfig> = Id<
+  NewConfig & Omit<OldConfig, keyof NewConfig>
+>
+
+export type CreateAsyncThunkFunction<
+  CurriedThunkApiConfig extends AsyncThunkConfig,
+> = {
+  /**
+   *
+   * @param typePrefix
+   * @param payloadCreator
+   * @param options
+   *
+   * @public
+   */
+  // separate signature without `AsyncThunkConfig` for better inference
+  <Returned, ThunkArg = void>(
+    typePrefix: string,
+    payloadCreator: AsyncThunkPayloadCreator<
+      Returned,
+      ThunkArg,
+      CurriedThunkApiConfig
+    >,
+    options?: AsyncThunkOptions<ThunkArg, CurriedThunkApiConfig>,
+  ): AsyncThunk<Returned, ThunkArg, CurriedThunkApiConfig>
+
+  /**
+   *
+   * @param typePrefix
+   * @param payloadCreator
+   * @param options
+   *
+   * @public
+   */
+  <Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig>(
+    typePrefix: string,
+    payloadCreator: AsyncThunkPayloadCreator<
+      Returned,
+      ThunkArg,
+      OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
+    >,
+    options?: AsyncThunkOptions<
+      ThunkArg,
+      OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
+    >,
+  ): AsyncThunk<
+    Returned,
+    ThunkArg,
+    OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
+  >
+}
+
+type CreateAsyncThunk<CurriedThunkApiConfig extends AsyncThunkConfig> =
+  CreateAsyncThunkFunction<CurriedThunkApiConfig> & {
+    withTypes<ThunkApiConfig extends AsyncThunkConfig>(): CreateAsyncThunk<
+      OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
+    >
+  }
+
+const externalAbortMessage = 'External signal was aborted'
+
+export const createAsyncThunk = /* @__PURE__ */ (() => {
+  function createAsyncThunk<
+    Returned,
+    ThunkArg,
+    ThunkApiConfig extends AsyncThunkConfig,
+  >(
+    typePrefix: string,
+    payloadCreator: AsyncThunkPayloadCreator<
+      Returned,
+      ThunkArg,
+      ThunkApiConfig
+    >,
+    options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>,
+  ): AsyncThunk<Returned, ThunkArg, ThunkApiConfig> {
+    type RejectedValue = GetRejectValue<ThunkApiConfig>
+    type PendingMeta = GetPendingMeta<ThunkApiConfig>
+    type FulfilledMeta = GetFulfilledMeta<ThunkApiConfig>
+    type RejectedMeta = GetRejectedMeta<ThunkApiConfig>
+
+    const fulfilled: AsyncThunkFulfilledActionCreator<
+      Returned,
+      ThunkArg,
+      ThunkApiConfig
+    > = createAction(
+      typePrefix + '/fulfilled',
+      (
+        payload: Returned,
+        requestId: string,
+        arg: ThunkArg,
+        meta?: FulfilledMeta,
+      ) => ({
+        payload,
+        meta: {
+          ...((meta as any) || {}),
+          arg,
+          requestId,
+          requestStatus: 'fulfilled' as const,
+        },
+      }),
+    )
+
+    const pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig> =
+      createAction(
+        typePrefix + '/pending',
+        (requestId: string, arg: ThunkArg, meta?: PendingMeta) => ({
+          payload: undefined,
+          meta: {
+            ...((meta as any) || {}),
+            arg,
+            requestId,
+            requestStatus: 'pending' as const,
+          },
+        }),
+      )
+
+    const rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig> =
+      createAction(
+        typePrefix + '/rejected',
+        (
+          error: Error | null,
+          requestId: string,
+          arg: ThunkArg,
+          payload?: RejectedValue,
+          meta?: RejectedMeta,
+        ) => ({
+          payload,
+          error: ((options && options.serializeError) || miniSerializeError)(
+            error || 'Rejected',
+          ) as GetSerializedErrorType<ThunkApiConfig>,
+          meta: {
+            ...((meta as any) || {}),
+            arg,
+            requestId,
+            rejectedWithValue: !!payload,
+            requestStatus: 'rejected' as const,
+            aborted: error?.name === 'AbortError',
+            condition: error?.name === 'ConditionError',
+          },
+        }),
+      )
+
+    function actionCreator(
+      arg: ThunkArg,
+      { signal }: AsyncThunkDispatchConfig = {},
+    ): AsyncThunkAction<Returned, ThunkArg, Required<ThunkApiConfig>> {
+      return (dispatch, getState, extra) => {
+        const requestId = options?.idGenerator
+          ? options.idGenerator(arg)
+          : nanoid()
+
+        const abortController = new AbortController()
+        let abortHandler: (() => void) | undefined
+        let abortReason: string | undefined
+
+        function abort(reason?: string) {
+          abortReason = reason
+          abortController.abort()
+        }
+
+        if (signal) {
+          if (signal.aborted) {
+            abort(externalAbortMessage)
+          } else {
+            signal.addEventListener(
+              'abort',
+              () => abort(externalAbortMessage),
+              { once: true },
+            )
+          }
+        }
+
+        const promise = (async function () {
+          let finalAction: ReturnType<typeof fulfilled | typeof rejected>
+          try {
+            let conditionResult = options?.condition?.(arg, { getState, extra })
+            if (isThenable(conditionResult)) {
+              conditionResult = await conditionResult
+            }
+
+            if (conditionResult === false || abortController.signal.aborted) {
+              // eslint-disable-next-line no-throw-literal
+              throw {
+                name: 'ConditionError',
+                message: 'Aborted due to condition callback returning false.',
+              }
+            }
+
+            const abortedPromise = new Promise<never>((_, reject) => {
+              abortHandler = () => {
+                reject({
+                  name: 'AbortError',
+                  message: abortReason || 'Aborted',
+                })
+              }
+              abortController.signal.addEventListener('abort', abortHandler, {
+                once: true,
+              })
+            })
+            dispatch(
+              pending(
+                requestId,
+                arg,
+                options?.getPendingMeta?.(
+                  { requestId, arg },
+                  { getState, extra },
+                ),
+              ) as any,
+            )
+            finalAction = await Promise.race([
+              abortedPromise,
+              Promise.resolve(
+                payloadCreator(arg, {
+                  dispatch,
+                  getState,
+                  extra,
+                  requestId,
+                  signal: abortController.signal,
+                  abort,
+                  rejectWithValue: ((
+                    value: RejectedValue,
+                    meta?: RejectedMeta,
+                  ) => {
+                    return new RejectWithValue(value, meta)
+                  }) as any,
+                  fulfillWithValue: ((value: unknown, meta?: FulfilledMeta) => {
+                    return new FulfillWithMeta(value, meta)
+                  }) as any,
+                }),
+              ).then((result) => {
+                if (result instanceof RejectWithValue) {
+                  throw result
+                }
+                if (result instanceof FulfillWithMeta) {
+                  return fulfilled(result.payload, requestId, arg, result.meta)
+                }
+                return fulfilled(result as any, requestId, arg)
+              }),
+            ])
+          } catch (err) {
+            finalAction =
+              err instanceof RejectWithValue
+                ? rejected(null, requestId, arg, err.payload, err.meta)
+                : rejected(err as any, requestId, arg)
+          } finally {
+            if (abortHandler) {
+              abortController.signal.removeEventListener('abort', abortHandler)
+            }
+          }
+          // We dispatch the result action _after_ the catch, to avoid having any errors
+          // here get swallowed by the try/catch block,
+          // per https://twitter.com/dan_abramov/status/770914221638942720
+          // and https://github.com/reduxjs/redux-toolkit/blob/e85eb17b39a2118d859f7b7746e0f3fee523e089/docs/tutorials/advanced-tutorial.md#async-error-handling-logic-in-thunks
+
+          const skipDispatch =
+            options &&
+            !options.dispatchConditionRejection &&
+            rejected.match(finalAction) &&
+            (finalAction as any).meta.condition
+
+          if (!skipDispatch) {
+            dispatch(finalAction as any)
+          }
+          return finalAction
+        })()
+        return Object.assign(promise as SafePromise<any>, {
+          abort,
+          requestId,
+          arg,
+          unwrap() {
+            return promise.then<any>(unwrapResult)
+          },
+        })
+      }
+    }
+
+    return Object.assign(
+      actionCreator as AsyncThunkActionCreator<
+        Returned,
+        ThunkArg,
+        ThunkApiConfig
+      >,
+      {
+        pending,
+        rejected,
+        fulfilled,
+        settled: isAnyOf(rejected, fulfilled),
+        typePrefix,
+      },
+    )
+  }
+  createAsyncThunk.withTypes = () => createAsyncThunk
+
+  return createAsyncThunk as CreateAsyncThunk<AsyncThunkConfig>
+})()
+
+interface UnwrappableAction {
+  payload: any
+  meta?: any
+  error?: any
+}
+
+type UnwrappedActionPayload<T extends UnwrappableAction> = Exclude<
+  T,
+  { error: any }
+>['payload']
+
+/**
+ * @public
+ */
+export function unwrapResult<R extends UnwrappableAction>(
+  action: R,
+): UnwrappedActionPayload<R> {
+  if (action.meta && action.meta.rejectedWithValue) {
+    throw action.payload
+  }
+  if (action.error) {
+    throw action.error
+  }
+  return action.payload
+}
+
+type WithStrictNullChecks<True, False> = undefined extends boolean
+  ? False
+  : True
+
+function isThenable(value: any): value is PromiseLike<any> {
+  return (
+    value !== null &&
+    typeof value === 'object' &&
+    typeof value.then === 'function'
+  )
+}
Index: node_modules/@reduxjs/toolkit/src/createDraftSafeSelector.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/createDraftSafeSelector.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/createDraftSafeSelector.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,30 @@
+import { current, isDraft } from './immerImports'
+import { createSelectorCreator, weakMapMemoize } from './reselectImports'
+
+export const createDraftSafeSelectorCreator: typeof createSelectorCreator = (
+  ...args: unknown[]
+) => {
+  const createSelector = (createSelectorCreator as any)(...args)
+  const createDraftSafeSelector = Object.assign(
+    (...args: unknown[]) => {
+      const selector = createSelector(...args)
+      const wrappedSelector = (value: unknown, ...rest: unknown[]) =>
+        selector(isDraft(value) ? current(value) : value, ...rest)
+      Object.assign(wrappedSelector, selector)
+      return wrappedSelector as any
+    },
+    { withTypes: () => createDraftSafeSelector },
+  )
+  return createDraftSafeSelector
+}
+
+/**
+ * "Draft-Safe" version of `reselect`'s `createSelector`:
+ * If an `immer`-drafted object is passed into the resulting selector's first argument,
+ * the selector will act on the current draft value, instead of returning a cached value
+ * that might be possibly outdated if the draft has been modified since.
+ * @public
+ */
+export const createDraftSafeSelector =
+  /* @__PURE__ */
+  createDraftSafeSelectorCreator(weakMapMemoize)
Index: node_modules/@reduxjs/toolkit/src/createReducer.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/createReducer.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/createReducer.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,226 @@
+import type { Draft } from 'immer'
+import {
+  createNextState,
+  isDraft,
+  isDraftable,
+  setUseStrictIteration,
+} from './immerImports'
+import type { Action, Reducer, UnknownAction } from 'redux'
+import type { ActionReducerMapBuilder } from './mapBuilders'
+import { executeReducerBuilderCallback } from './mapBuilders'
+import type { NoInfer, TypeGuard } from './tsHelpers'
+import { freezeDraftable } from './utils'
+
+/**
+ * Defines a mapping from action types to corresponding action object shapes.
+ *
+ * @deprecated This should not be used manually - it is only used for internal
+ *             inference purposes and should not have any further value.
+ *             It might be removed in the future.
+ * @public
+ */
+export type Actions<T extends keyof any = string> = Record<T, Action>
+
+export type ActionMatcherDescription<S, A extends Action> = {
+  matcher: TypeGuard<A>
+  reducer: CaseReducer<S, NoInfer<A>>
+}
+
+export type ReadonlyActionMatcherDescriptionCollection<S> = ReadonlyArray<
+  ActionMatcherDescription<S, any>
+>
+
+export type ActionMatcherDescriptionCollection<S> = Array<
+  ActionMatcherDescription<S, any>
+>
+
+/**
+ * A *case reducer* is a reducer function for a specific action type. Case
+ * reducers can be composed to full reducers using `createReducer()`.
+ *
+ * Unlike a normal Redux reducer, a case reducer is never called with an
+ * `undefined` state to determine the initial state. Instead, the initial
+ * state is explicitly specified as an argument to `createReducer()`.
+ *
+ * In addition, a case reducer can choose to mutate the passed-in `state`
+ * value directly instead of returning a new state. This does not actually
+ * cause the store state to be mutated directly; instead, thanks to
+ * [immer](https://github.com/mweststrate/immer), the mutations are
+ * translated to copy operations that result in a new state.
+ *
+ * @public
+ */
+export type CaseReducer<S = any, A extends Action = UnknownAction> = (
+  state: Draft<S>,
+  action: A,
+) => NoInfer<S> | void | Draft<NoInfer<S>>
+
+/**
+ * A mapping from action types to case reducers for `createReducer()`.
+ *
+ * @deprecated This should not be used manually - it is only used
+ *             for internal inference purposes and using it manually
+ *             would lead to type erasure.
+ *             It might be removed in the future.
+ * @public
+ */
+export type CaseReducers<S, AS extends Actions> = {
+  [T in keyof AS]: AS[T] extends Action ? CaseReducer<S, AS[T]> : void
+}
+
+export type NotFunction<T> = T extends Function ? never : T
+
+function isStateFunction<S>(x: unknown): x is () => S {
+  return typeof x === 'function'
+}
+
+export type ReducerWithInitialState<S extends NotFunction<any>> = Reducer<S> & {
+  getInitialState: () => S
+}
+
+/**
+ * A utility function that allows defining a reducer as a mapping from action
+ * type to *case reducer* functions that handle these action types. The
+ * reducer's initial state is passed as the first argument.
+ *
+ * @remarks
+ * The body of every case reducer is implicitly wrapped with a call to
+ * `produce()` from the [immer](https://github.com/mweststrate/immer) library.
+ * This means that rather than returning a new state object, you can also
+ * mutate the passed-in state object directly; these mutations will then be
+ * automatically and efficiently translated into copies, giving you both
+ * convenience and immutability.
+ *
+ * @overloadSummary
+ * This function accepts a callback that receives a `builder` object as its argument.
+ * That builder provides `addCase`, `addMatcher` and `addDefaultCase` functions that may be
+ * called to define what actions this reducer will handle.
+ *
+ * @param initialState - `State | (() => State)`: The initial state that should be used when the reducer is called the first time. This may also be a "lazy initializer" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.
+ * @param builderCallback - `(builder: Builder) => void` A callback that receives a *builder* object to define
+ *   case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.
+ * @example
+```ts
+import {
+  createAction,
+  createReducer,
+  UnknownAction,
+  PayloadAction,
+} from "@reduxjs/toolkit";
+
+const increment = createAction<number>("increment");
+const decrement = createAction<number>("decrement");
+
+function isActionWithNumberPayload(
+  action: UnknownAction
+): action is PayloadAction<number> {
+  return typeof action.payload === "number";
+}
+
+const reducer = createReducer(
+  {
+    counter: 0,
+    sumOfNumberPayloads: 0,
+    unhandledActions: 0,
+  },
+  (builder) => {
+    builder
+      .addCase(increment, (state, action) => {
+        // action is inferred correctly here
+        state.counter += action.payload;
+      })
+      // You can chain calls, or have separate `builder.addCase()` lines each time
+      .addCase(decrement, (state, action) => {
+        state.counter -= action.payload;
+      })
+      // You can apply a "matcher function" to incoming actions
+      .addMatcher(isActionWithNumberPayload, (state, action) => {})
+      // and provide a default case if no other handlers matched
+      .addDefaultCase((state, action) => {});
+  }
+);
+```
+ * @public
+ */
+export function createReducer<S extends NotFunction<any>>(
+  initialState: S | (() => S),
+  mapOrBuilderCallback: (builder: ActionReducerMapBuilder<S>) => void,
+): ReducerWithInitialState<S> {
+  if (process.env.NODE_ENV !== 'production') {
+    if (typeof mapOrBuilderCallback === 'object') {
+      throw new Error(
+        "The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer",
+      )
+    }
+  }
+
+  let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] =
+    executeReducerBuilderCallback(mapOrBuilderCallback)
+
+  // Ensure the initial state gets frozen either way (if draftable)
+  let getInitialState: () => S
+  if (isStateFunction(initialState)) {
+    getInitialState = () => freezeDraftable(initialState())
+  } else {
+    const frozenInitialState = freezeDraftable(initialState)
+    getInitialState = () => frozenInitialState
+  }
+
+  function reducer(state = getInitialState(), action: any): S {
+    let caseReducers = [
+      actionsMap[action.type],
+      ...finalActionMatchers
+        .filter(({ matcher }) => matcher(action))
+        .map(({ reducer }) => reducer),
+    ]
+    if (caseReducers.filter((cr) => !!cr).length === 0) {
+      caseReducers = [finalDefaultCaseReducer]
+    }
+
+    return caseReducers.reduce((previousState, caseReducer): S => {
+      if (caseReducer) {
+        if (isDraft(previousState)) {
+          // If it's already a draft, we must already be inside a `createNextState` call,
+          // likely because this is being wrapped in `createReducer`, `createSlice`, or nested
+          // inside an existing draft. It's safe to just pass the draft to the mutator.
+          const draft = previousState as Draft<S> // We can assume this is already a draft
+          const result = caseReducer(draft, action)
+
+          if (result === undefined) {
+            return previousState
+          }
+
+          return result as S
+        } else if (!isDraftable(previousState)) {
+          // If state is not draftable (ex: a primitive, such as 0), we want to directly
+          // return the caseReducer func and not wrap it with produce.
+          const result = caseReducer(previousState as any, action)
+
+          if (result === undefined) {
+            if (previousState === null) {
+              return previousState
+            }
+            throw Error(
+              'A case reducer on a non-draftable value must not return undefined',
+            )
+          }
+
+          return result as S
+        } else {
+          // @ts-ignore createNextState() produces an Immutable<Draft<S>> rather
+          // than an Immutable<S>, and TypeScript cannot find out how to reconcile
+          // these two types.
+          return createNextState(previousState, (draft: Draft<S>) => {
+            return caseReducer(draft, action)
+          })
+        }
+      }
+
+      return previousState
+    }, state)
+  }
+
+  reducer.getInitialState = getInitialState
+
+  return reducer as ReducerWithInitialState<S>
+}
Index: node_modules/@reduxjs/toolkit/src/createSlice.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/createSlice.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/createSlice.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1073 @@
+import type { Action, Reducer, UnknownAction } from 'redux'
+import type { Selector } from 'reselect'
+import type { InjectConfig } from './combineSlices'
+import type {
+  ActionCreatorWithoutPayload,
+  PayloadAction,
+  PayloadActionCreator,
+  PrepareAction,
+  _ActionCreatorWithPreparedPayload,
+} from './createAction'
+import { createAction } from './createAction'
+import type {
+  AsyncThunk,
+  AsyncThunkConfig,
+  AsyncThunkOptions,
+  AsyncThunkPayloadCreator,
+  OverrideThunkApiConfigs,
+} from './createAsyncThunk'
+import { createAsyncThunk as _createAsyncThunk } from './createAsyncThunk'
+import type {
+  ActionMatcherDescriptionCollection,
+  CaseReducer,
+  ReducerWithInitialState,
+} from './createReducer'
+import { createReducer } from './createReducer'
+import type {
+  ActionReducerMapBuilder,
+  AsyncThunkReducers,
+  TypedActionCreator,
+} from './mapBuilders'
+import { executeReducerBuilderCallback } from './mapBuilders'
+import type { Id, TypeGuard } from './tsHelpers'
+import { getOrInsertComputed } from './utils'
+
+const asyncThunkSymbol = /* @__PURE__ */ Symbol.for(
+  'rtk-slice-createasyncthunk',
+)
+// type is annotated because it's too long to infer
+export const asyncThunkCreator: {
+  [asyncThunkSymbol]: typeof _createAsyncThunk
+} = {
+  [asyncThunkSymbol]: _createAsyncThunk,
+}
+
+type InjectIntoConfig<NewReducerPath extends string> = InjectConfig & {
+  reducerPath?: NewReducerPath
+}
+
+/**
+ * The return value of `createSlice`
+ *
+ * @public
+ */
+export interface Slice<
+  State = any,
+  CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>,
+  Name extends string = string,
+  ReducerPath extends string = Name,
+  Selectors extends SliceSelectors<State> = SliceSelectors<State>,
+> {
+  /**
+   * The slice name.
+   */
+  name: Name
+
+  /**
+   *  The slice reducer path.
+   */
+  reducerPath: ReducerPath
+
+  /**
+   * The slice's reducer.
+   */
+  reducer: Reducer<State>
+
+  /**
+   * Action creators for the types of actions that are handled by the slice
+   * reducer.
+   */
+  actions: CaseReducerActions<CaseReducers, Name>
+
+  /**
+   * The individual case reducer functions that were passed in the `reducers` parameter.
+   * This enables reuse and testing if they were defined inline when calling `createSlice`.
+   */
+  caseReducers: SliceDefinedCaseReducers<CaseReducers>
+
+  /**
+   * Provides access to the initial state value given to the slice.
+   * If a lazy state initializer was provided, it will be called and a fresh value returned.
+   */
+  getInitialState: () => State
+
+  /**
+   * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)
+   */
+  getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State>>
+
+  /**
+   * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)
+   */
+  getSelectors<RootState>(
+    selectState: (rootState: RootState) => State,
+  ): Id<SliceDefinedSelectors<State, Selectors, RootState>>
+
+  /**
+   * Selectors that assume the slice's state is `rootState[slice.reducerPath]` (which is usually the case)
+   *
+   * Equivalent to `slice.getSelectors((state: RootState) => state[slice.reducerPath])`.
+   */
+  get selectors(): Id<
+    SliceDefinedSelectors<State, Selectors, { [K in ReducerPath]: State }>
+  >
+
+  /**
+   * Inject slice into provided reducer (return value from `combineSlices`), and return injected slice.
+   */
+  injectInto<NewReducerPath extends string = ReducerPath>(
+    this: this,
+    injectable: {
+      inject: (
+        slice: { reducerPath: string; reducer: Reducer },
+        config?: InjectConfig,
+      ) => void
+    },
+    config?: InjectIntoConfig<NewReducerPath>,
+  ): InjectedSlice<State, CaseReducers, Name, NewReducerPath, Selectors>
+
+  /**
+   * Select the slice state, using the slice's current reducerPath.
+   *
+   * Will throw an error if slice is not found.
+   */
+  selectSlice(state: { [K in ReducerPath]: State }): State
+}
+
+/**
+ * A slice after being called with `injectInto(reducer)`.
+ *
+ * Selectors can now be called with an `undefined` value, in which case they use the slice's initial state.
+ */
+type InjectedSlice<
+  State = any,
+  CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>,
+  Name extends string = string,
+  ReducerPath extends string = Name,
+  Selectors extends SliceSelectors<State> = SliceSelectors<State>,
+> = Omit<
+  Slice<State, CaseReducers, Name, ReducerPath, Selectors>,
+  'getSelectors' | 'selectors'
+> & {
+  /**
+   * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)
+   */
+  getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State | undefined>>
+
+  /**
+   * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)
+   */
+  getSelectors<RootState>(
+    selectState: (rootState: RootState) => State | undefined,
+  ): Id<SliceDefinedSelectors<State, Selectors, RootState>>
+
+  /**
+   * Selectors that assume the slice's state is `rootState[slice.name]` (which is usually the case)
+   *
+   * Equivalent to `slice.getSelectors((state: RootState) => state[slice.name])`.
+   */
+  get selectors(): Id<
+    SliceDefinedSelectors<
+      State,
+      Selectors,
+      { [K in ReducerPath]?: State | undefined }
+    >
+  >
+
+  /**
+   * Select the slice state, using the slice's current reducerPath.
+   *
+   * Returns initial state if slice is not found.
+   */
+  selectSlice(state: { [K in ReducerPath]?: State | undefined }): State
+}
+
+/**
+ * Options for `createSlice()`.
+ *
+ * @public
+ */
+export interface CreateSliceOptions<
+  State = any,
+  CR extends SliceCaseReducers<State> = SliceCaseReducers<State>,
+  Name extends string = string,
+  ReducerPath extends string = Name,
+  Selectors extends SliceSelectors<State> = SliceSelectors<State>,
+> {
+  /**
+   * The slice's name. Used to namespace the generated action types.
+   */
+  name: Name
+
+  /**
+   * The slice's reducer path. Used when injecting into a combined slice reducer.
+   */
+  reducerPath?: ReducerPath
+
+  /**
+   * The initial state that should be used when the reducer is called the first time. This may also be a "lazy initializer" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.
+   */
+  initialState: State | (() => State)
+
+  /**
+   * A mapping from action types to action-type-specific *case reducer*
+   * functions. For every action type, a matching action creator will be
+   * generated using `createAction()`.
+   */
+  reducers:
+    | ValidateSliceCaseReducers<State, CR>
+    | ((creators: ReducerCreators<State>) => CR)
+
+  /**
+   * A callback that receives a *builder* object to define
+   * case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.
+   *
+   *
+   * @example
+```ts
+import { createAction, createSlice, Action } from '@reduxjs/toolkit'
+const incrementBy = createAction<number>('incrementBy')
+const decrement = createAction('decrement')
+
+interface RejectedAction extends Action {
+  error: Error
+}
+
+function isRejectedAction(action: Action): action is RejectedAction {
+  return action.type.endsWith('rejected')
+}
+
+createSlice({
+  name: 'counter',
+  initialState: 0,
+  reducers: {},
+  extraReducers: builder => {
+    builder
+      .addCase(incrementBy, (state, action) => {
+        // action is inferred correctly here if using TS
+      })
+      // You can chain calls, or have separate `builder.addCase()` lines each time
+      .addCase(decrement, (state, action) => {})
+      // You can match a range of action types
+      .addMatcher(
+        isRejectedAction,
+        // `action` will be inferred as a RejectedAction due to isRejectedAction being defined as a type guard
+        (state, action) => {}
+      )
+      // and provide a default case if no other handlers matched
+      .addDefaultCase((state, action) => {})
+    }
+})
+```
+   */
+  extraReducers?: (builder: ActionReducerMapBuilder<State>) => void
+
+  /**
+   * A map of selectors that receive the slice's state and any additional arguments, and return a result.
+   */
+  selectors?: Selectors
+}
+
+export enum ReducerType {
+  reducer = 'reducer',
+  reducerWithPrepare = 'reducerWithPrepare',
+  asyncThunk = 'asyncThunk',
+}
+
+type ReducerDefinition<T extends ReducerType = ReducerType> = {
+  _reducerDefinitionType: T
+}
+
+export type CaseReducerDefinition<
+  S = any,
+  A extends Action = UnknownAction,
+> = CaseReducer<S, A> & ReducerDefinition<ReducerType.reducer>
+
+/**
+ * A CaseReducer with a `prepare` method.
+ *
+ * @public
+ */
+export type CaseReducerWithPrepare<State, Action extends PayloadAction> = {
+  reducer: CaseReducer<State, Action>
+  prepare: PrepareAction<Action['payload']>
+}
+
+export interface CaseReducerWithPrepareDefinition<
+  State,
+  Action extends PayloadAction,
+> extends CaseReducerWithPrepare<State, Action>,
+    ReducerDefinition<ReducerType.reducerWithPrepare> {}
+
+type AsyncThunkSliceReducerConfig<
+  State,
+  ThunkArg extends any,
+  Returned = unknown,
+  ThunkApiConfig extends AsyncThunkConfig = {},
+> = AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig> & {
+  options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>
+}
+
+type AsyncThunkSliceReducerDefinition<
+  State,
+  ThunkArg extends any,
+  Returned = unknown,
+  ThunkApiConfig extends AsyncThunkConfig = {},
+> = AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig> &
+  ReducerDefinition<ReducerType.asyncThunk> & {
+    payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>
+  }
+
+/**
+ * Providing these as part of the config would cause circular types, so we disallow passing them
+ */
+type PreventCircular<ThunkApiConfig> = {
+  [K in keyof ThunkApiConfig]: K extends 'state' | 'dispatch'
+    ? never
+    : ThunkApiConfig[K]
+}
+
+interface AsyncThunkCreator<
+  State,
+  CurriedThunkApiConfig extends
+    PreventCircular<AsyncThunkConfig> = PreventCircular<AsyncThunkConfig>,
+> {
+  <Returned, ThunkArg = void>(
+    payloadCreator: AsyncThunkPayloadCreator<
+      Returned,
+      ThunkArg,
+      CurriedThunkApiConfig
+    >,
+    config?: AsyncThunkSliceReducerConfig<
+      State,
+      ThunkArg,
+      Returned,
+      CurriedThunkApiConfig
+    >,
+  ): AsyncThunkSliceReducerDefinition<
+    State,
+    ThunkArg,
+    Returned,
+    CurriedThunkApiConfig
+  >
+  <
+    Returned,
+    ThunkArg,
+    ThunkApiConfig extends PreventCircular<AsyncThunkConfig> = {},
+  >(
+    payloadCreator: AsyncThunkPayloadCreator<
+      Returned,
+      ThunkArg,
+      ThunkApiConfig
+    >,
+    config?: AsyncThunkSliceReducerConfig<
+      State,
+      ThunkArg,
+      Returned,
+      ThunkApiConfig
+    >,
+  ): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, ThunkApiConfig>
+  withTypes<
+    ThunkApiConfig extends PreventCircular<AsyncThunkConfig>,
+  >(): AsyncThunkCreator<
+    State,
+    OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
+  >
+}
+
+export interface ReducerCreators<State> {
+  reducer(
+    caseReducer: CaseReducer<State, PayloadAction>,
+  ): CaseReducerDefinition<State, PayloadAction>
+  reducer<Payload>(
+    caseReducer: CaseReducer<State, PayloadAction<Payload>>,
+  ): CaseReducerDefinition<State, PayloadAction<Payload>>
+
+  asyncThunk: AsyncThunkCreator<State>
+
+  preparedReducer<Prepare extends PrepareAction<any>>(
+    prepare: Prepare,
+    reducer: CaseReducer<
+      State,
+      ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>
+    >,
+  ): {
+    _reducerDefinitionType: ReducerType.reducerWithPrepare
+    prepare: Prepare
+    reducer: CaseReducer<
+      State,
+      ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>
+    >
+  }
+}
+
+/**
+ * The type describing a slice's `reducers` option.
+ *
+ * @public
+ */
+export type SliceCaseReducers<State> =
+  | Record<string, ReducerDefinition>
+  | Record<
+      string,
+      | CaseReducer<State, PayloadAction<any>>
+      | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>
+    >
+
+/**
+ * The type describing a slice's `selectors` option.
+ */
+export type SliceSelectors<State> = {
+  [K: string]: (sliceState: State, ...args: any[]) => any
+}
+
+type SliceActionType<
+  SliceName extends string,
+  ActionName extends keyof any,
+> = ActionName extends string | number ? `${SliceName}/${ActionName}` : string
+
+/**
+ * Derives the slice's `actions` property from the `reducers` options
+ *
+ * @public
+ */
+export type CaseReducerActions<
+  CaseReducers extends SliceCaseReducers<any>,
+  SliceName extends string,
+> = {
+  [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition
+    ? Definition extends { prepare: any }
+      ? ActionCreatorForCaseReducerWithPrepare<
+          Definition,
+          SliceActionType<SliceName, Type>
+        >
+      : Definition extends AsyncThunkSliceReducerDefinition<
+            any,
+            infer ThunkArg,
+            infer Returned,
+            infer ThunkApiConfig
+          >
+        ? AsyncThunk<Returned, ThunkArg, ThunkApiConfig>
+        : Definition extends { reducer: any }
+          ? ActionCreatorForCaseReducer<
+              Definition['reducer'],
+              SliceActionType<SliceName, Type>
+            >
+          : ActionCreatorForCaseReducer<
+              Definition,
+              SliceActionType<SliceName, Type>
+            >
+    : never
+}
+
+/**
+ * Get a `PayloadActionCreator` type for a passed `CaseReducerWithPrepare`
+ *
+ * @internal
+ */
+type ActionCreatorForCaseReducerWithPrepare<
+  CR extends { prepare: any },
+  Type extends string,
+> = _ActionCreatorWithPreparedPayload<CR['prepare'], Type>
+
+/**
+ * Get a `PayloadActionCreator` type for a passed `CaseReducer`
+ *
+ * @internal
+ */
+type ActionCreatorForCaseReducer<CR, Type extends string> = CR extends (
+  state: any,
+  action: infer Action,
+) => any
+  ? Action extends { payload: infer P }
+    ? PayloadActionCreator<P, Type>
+    : ActionCreatorWithoutPayload<Type>
+  : ActionCreatorWithoutPayload<Type>
+
+/**
+ * Extracts the CaseReducers out of a `reducers` object, even if they are
+ * tested into a `CaseReducerWithPrepare`.
+ *
+ * @internal
+ */
+type SliceDefinedCaseReducers<CaseReducers extends SliceCaseReducers<any>> = {
+  [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition
+    ? Definition extends AsyncThunkSliceReducerDefinition<any, any, any>
+      ? Id<
+          Pick<
+            Required<Definition>,
+            'fulfilled' | 'rejected' | 'pending' | 'settled'
+          >
+        >
+      : Definition extends {
+            reducer: infer Reducer
+          }
+        ? Reducer
+        : Definition
+    : never
+}
+
+type RemappedSelector<S extends Selector, NewState> =
+  S extends Selector<any, infer R, infer P>
+    ? Selector<NewState, R, P> & { unwrapped: S }
+    : never
+
+/**
+ * Extracts the final selector type from the `selectors` object.
+ *
+ * Removes the `string` index signature from the default value.
+ */
+type SliceDefinedSelectors<
+  State,
+  Selectors extends SliceSelectors<State>,
+  RootState,
+> = {
+  [K in keyof Selectors as string extends K ? never : K]: RemappedSelector<
+    Selectors[K],
+    RootState
+  >
+}
+
+/**
+ * Used on a SliceCaseReducers object.
+ * Ensures that if a CaseReducer is a `CaseReducerWithPrepare`, that
+ * the `reducer` and the `prepare` function use the same type of `payload`.
+ *
+ * Might do additional such checks in the future.
+ *
+ * This type is only ever useful if you want to write your own wrapper around
+ * `createSlice`. Please don't use it otherwise!
+ *
+ * @public
+ */
+export type ValidateSliceCaseReducers<
+  S,
+  ACR extends SliceCaseReducers<S>,
+> = ACR & {
+  [T in keyof ACR]: ACR[T] extends {
+    reducer(s: S, action?: infer A): any
+  }
+    ? {
+        prepare(...a: never[]): Omit<A, 'type'>
+      }
+    : {}
+}
+
+function getType(slice: string, actionKey: string): string {
+  return `${slice}/${actionKey}`
+}
+
+interface BuildCreateSliceConfig {
+  creators?: {
+    asyncThunk?: typeof asyncThunkCreator
+  }
+}
+
+export function buildCreateSlice({ creators }: BuildCreateSliceConfig = {}) {
+  const cAT = creators?.asyncThunk?.[asyncThunkSymbol]
+  return function createSlice<
+    State,
+    CaseReducers extends SliceCaseReducers<State>,
+    Name extends string,
+    Selectors extends SliceSelectors<State>,
+    ReducerPath extends string = Name,
+  >(
+    options: CreateSliceOptions<
+      State,
+      CaseReducers,
+      Name,
+      ReducerPath,
+      Selectors
+    >,
+  ): Slice<State, CaseReducers, Name, ReducerPath, Selectors> {
+    const { name, reducerPath = name as unknown as ReducerPath } = options
+    if (!name) {
+      throw new Error('`name` is a required option for createSlice')
+    }
+
+    if (
+      typeof process !== 'undefined' &&
+      process.env.NODE_ENV === 'development'
+    ) {
+      if (options.initialState === undefined) {
+        console.error(
+          'You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`',
+        )
+      }
+    }
+
+    const reducers =
+      (typeof options.reducers === 'function'
+        ? options.reducers(buildReducerCreators<State>())
+        : options.reducers) || {}
+
+    const reducerNames = Object.keys(reducers)
+
+    const context: ReducerHandlingContext<State> = {
+      sliceCaseReducersByName: {},
+      sliceCaseReducersByType: {},
+      actionCreators: {},
+      sliceMatchers: [],
+    }
+
+    const contextMethods: ReducerHandlingContextMethods<State> = {
+      addCase(
+        typeOrActionCreator: string | TypedActionCreator<any>,
+        reducer: CaseReducer<State>,
+      ) {
+        const type =
+          typeof typeOrActionCreator === 'string'
+            ? typeOrActionCreator
+            : typeOrActionCreator.type
+        if (!type) {
+          throw new Error(
+            '`context.addCase` cannot be called with an empty action type',
+          )
+        }
+        if (type in context.sliceCaseReducersByType) {
+          throw new Error(
+            '`context.addCase` cannot be called with two reducers for the same action type: ' +
+              type,
+          )
+        }
+        context.sliceCaseReducersByType[type] = reducer
+        return contextMethods
+      },
+      addMatcher(matcher, reducer) {
+        context.sliceMatchers.push({ matcher, reducer })
+        return contextMethods
+      },
+      exposeAction(name, actionCreator) {
+        context.actionCreators[name] = actionCreator
+        return contextMethods
+      },
+      exposeCaseReducer(name, reducer) {
+        context.sliceCaseReducersByName[name] = reducer
+        return contextMethods
+      },
+    }
+
+    reducerNames.forEach((reducerName) => {
+      const reducerDefinition = reducers[reducerName]
+      const reducerDetails: ReducerDetails = {
+        reducerName,
+        type: getType(name, reducerName),
+        createNotation: typeof options.reducers === 'function',
+      }
+      if (isAsyncThunkSliceReducerDefinition<State>(reducerDefinition)) {
+        handleThunkCaseReducerDefinition(
+          reducerDetails,
+          reducerDefinition,
+          contextMethods,
+          cAT,
+        )
+      } else {
+        handleNormalReducerDefinition<State>(
+          reducerDetails,
+          reducerDefinition as any,
+          contextMethods,
+        )
+      }
+    })
+
+    function buildReducer() {
+      if (process.env.NODE_ENV !== 'production') {
+        if (typeof options.extraReducers === 'object') {
+          throw new Error(
+            "The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice",
+          )
+        }
+      }
+      const [
+        extraReducers = {},
+        actionMatchers = [],
+        defaultCaseReducer = undefined,
+      ] =
+        typeof options.extraReducers === 'function'
+          ? executeReducerBuilderCallback(options.extraReducers)
+          : [options.extraReducers]
+
+      const finalCaseReducers = {
+        ...extraReducers,
+        ...context.sliceCaseReducersByType,
+      }
+
+      return createReducer(options.initialState, (builder) => {
+        for (let key in finalCaseReducers) {
+          builder.addCase(key, finalCaseReducers[key] as CaseReducer<any>)
+        }
+        for (let sM of context.sliceMatchers) {
+          builder.addMatcher(sM.matcher, sM.reducer)
+        }
+        for (let m of actionMatchers) {
+          builder.addMatcher(m.matcher, m.reducer)
+        }
+        if (defaultCaseReducer) {
+          builder.addDefaultCase(defaultCaseReducer)
+        }
+      })
+    }
+
+    const selectSelf = (state: State) => state
+
+    const injectedSelectorCache = new Map<
+      boolean,
+      WeakMap<
+        (rootState: any) => State | undefined,
+        Record<string, (rootState: any) => any>
+      >
+    >()
+
+    const injectedStateCache = new WeakMap<(rootState: any) => State, State>()
+
+    let _reducer: ReducerWithInitialState<State>
+
+    function reducer(state: State | undefined, action: UnknownAction) {
+      if (!_reducer) _reducer = buildReducer()
+
+      return _reducer(state, action)
+    }
+
+    function getInitialState() {
+      if (!_reducer) _reducer = buildReducer()
+
+      return _reducer.getInitialState()
+    }
+
+    function makeSelectorProps<CurrentReducerPath extends string = ReducerPath>(
+      reducerPath: CurrentReducerPath,
+      injected = false,
+    ): Pick<
+      Slice<State, CaseReducers, Name, CurrentReducerPath, Selectors>,
+      'getSelectors' | 'selectors' | 'selectSlice' | 'reducerPath'
+    > {
+      function selectSlice(state: { [K in CurrentReducerPath]: State }) {
+        let sliceState = state[reducerPath]
+        if (typeof sliceState === 'undefined') {
+          if (injected) {
+            sliceState = getOrInsertComputed(
+              injectedStateCache,
+              selectSlice,
+              getInitialState,
+            )
+          } else if (process.env.NODE_ENV !== 'production') {
+            throw new Error(
+              'selectSlice returned undefined for an uninjected slice reducer',
+            )
+          }
+        }
+        return sliceState
+      }
+
+      function getSelectors(
+        selectState: (rootState: any) => State = selectSelf,
+      ) {
+        const selectorCache = getOrInsertComputed(
+          injectedSelectorCache,
+          injected,
+          () => new WeakMap(),
+        )
+
+        return getOrInsertComputed(selectorCache, selectState, () => {
+          const map: Record<string, Selector<any, any>> = {}
+          for (const [name, selector] of Object.entries(
+            options.selectors ?? {},
+          )) {
+            map[name] = wrapSelector(
+              selector,
+              selectState,
+              () =>
+                getOrInsertComputed(
+                  injectedStateCache,
+                  selectState,
+                  getInitialState,
+                ),
+              injected,
+            )
+          }
+          return map
+        }) as any
+      }
+      return {
+        reducerPath,
+        getSelectors,
+        get selectors() {
+          return getSelectors(selectSlice)
+        },
+        selectSlice,
+      }
+    }
+
+    const slice: Slice<State, CaseReducers, Name, ReducerPath, Selectors> = {
+      name,
+      reducer,
+      actions: context.actionCreators as any,
+      caseReducers: context.sliceCaseReducersByName as any,
+      getInitialState,
+      ...makeSelectorProps(reducerPath),
+      injectInto(injectable, { reducerPath: pathOpt, ...config } = {}) {
+        const newReducerPath = pathOpt ?? reducerPath
+        injectable.inject({ reducerPath: newReducerPath, reducer }, config)
+        return {
+          ...slice,
+          ...makeSelectorProps(newReducerPath, true),
+        } as any
+      },
+    }
+    return slice
+  }
+}
+
+function wrapSelector<State, NewState, S extends Selector<State>>(
+  selector: S,
+  selectState: Selector<NewState, State>,
+  getInitialState: () => State,
+  injected?: boolean,
+) {
+  function wrapper(rootState: NewState, ...args: any[]) {
+    let sliceState = selectState(rootState)
+    if (typeof sliceState === 'undefined') {
+      if (injected) {
+        sliceState = getInitialState()
+      } else if (process.env.NODE_ENV !== 'production') {
+        throw new Error(
+          'selectState returned undefined for an uninjected slice reducer',
+        )
+      }
+    }
+    return selector(sliceState, ...args)
+  }
+  wrapper.unwrapped = selector
+  return wrapper as RemappedSelector<S, NewState>
+}
+
+/**
+ * A function that accepts an initial state, an object full of reducer
+ * functions, and a "slice name", and automatically generates
+ * action creators and action types that correspond to the
+ * reducers and state.
+ *
+ * @public
+ */
+export const createSlice = /* @__PURE__ */ buildCreateSlice()
+
+interface ReducerHandlingContext<State> {
+  sliceCaseReducersByName: Record<
+    string,
+    | CaseReducer<State, any>
+    | Pick<
+        AsyncThunkSliceReducerDefinition<State, any, any, any>,
+        'fulfilled' | 'rejected' | 'pending' | 'settled'
+      >
+  >
+  sliceCaseReducersByType: Record<string, CaseReducer<State, any>>
+  sliceMatchers: ActionMatcherDescriptionCollection<State>
+  actionCreators: Record<string, Function>
+}
+
+interface ReducerHandlingContextMethods<State> {
+  /**
+   * Adds a case reducer to handle a single action type.
+   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
+   * @param reducer - The actual case reducer function.
+   */
+  addCase<ActionCreator extends TypedActionCreator<string>>(
+    actionCreator: ActionCreator,
+    reducer: CaseReducer<State, ReturnType<ActionCreator>>,
+  ): ReducerHandlingContextMethods<State>
+  /**
+   * Adds a case reducer to handle a single action type.
+   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
+   * @param reducer - The actual case reducer function.
+   */
+  addCase<Type extends string, A extends Action<Type>>(
+    type: Type,
+    reducer: CaseReducer<State, A>,
+  ): ReducerHandlingContextMethods<State>
+
+  /**
+   * Allows you to match incoming actions against your own filter function instead of only the `action.type` property.
+   * @remarks
+   * If multiple matcher reducers match, all of them will be executed in the order
+   * they were defined in - even if a case reducer already matched.
+   * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and before any calls to `builder.addDefaultCase`.
+   * @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)
+   *   function
+   * @param reducer - The actual case reducer function.
+   *
+   */
+  addMatcher<A>(
+    matcher: TypeGuard<A>,
+    reducer: CaseReducer<State, A extends Action ? A : A & Action>,
+  ): ReducerHandlingContextMethods<State>
+  /**
+   * Add an action to be exposed under the final `slice.actions` key.
+   * @param name The key to be exposed as.
+   * @param actionCreator The action to expose.
+   * @example
+   * context.exposeAction("addPost", createAction<Post>("addPost"));
+   *
+   * export const { addPost } = slice.actions
+   *
+   * dispatch(addPost(post))
+   */
+  exposeAction(
+    name: string,
+    actionCreator: Function,
+  ): ReducerHandlingContextMethods<State>
+  /**
+   * Add a case reducer to be exposed under the final `slice.caseReducers` key.
+   * @param name The key to be exposed as.
+   * @param reducer The reducer to expose.
+   * @example
+   * context.exposeCaseReducer("addPost", (state, action: PayloadAction<Post>) => {
+   *   state.push(action.payload)
+   * })
+   *
+   * slice.caseReducers.addPost([], addPost(post))
+   */
+  exposeCaseReducer(
+    name: string,
+    reducer:
+      | CaseReducer<State, any>
+      | Pick<
+          AsyncThunkSliceReducerDefinition<State, any, any, any>,
+          'fulfilled' | 'rejected' | 'pending' | 'settled'
+        >,
+  ): ReducerHandlingContextMethods<State>
+}
+
+interface ReducerDetails {
+  /** The key the reducer was defined under */
+  reducerName: string
+  /** The predefined action type, i.e. `${slice.name}/${reducerName}` */
+  type: string
+  /** Whether create. notation was used when defining reducers */
+  createNotation: boolean
+}
+
+function buildReducerCreators<State>(): ReducerCreators<State> {
+  function asyncThunk(
+    payloadCreator: AsyncThunkPayloadCreator<any, any>,
+    config: AsyncThunkSliceReducerConfig<State, any>,
+  ): AsyncThunkSliceReducerDefinition<State, any> {
+    return {
+      _reducerDefinitionType: ReducerType.asyncThunk,
+      payloadCreator,
+      ...config,
+    }
+  }
+  asyncThunk.withTypes = () => asyncThunk
+  return {
+    reducer(caseReducer: CaseReducer<State, any>) {
+      return Object.assign(
+        {
+          // hack so the wrapping function has the same name as the original
+          // we need to create a wrapper so the `reducerDefinitionType` is not assigned to the original
+          [caseReducer.name](...args: Parameters<typeof caseReducer>) {
+            return caseReducer(...args)
+          },
+        }[caseReducer.name],
+        {
+          _reducerDefinitionType: ReducerType.reducer,
+        } as const,
+      )
+    },
+    preparedReducer(prepare, reducer) {
+      return {
+        _reducerDefinitionType: ReducerType.reducerWithPrepare,
+        prepare,
+        reducer,
+      }
+    },
+    asyncThunk: asyncThunk as any,
+  }
+}
+
+function handleNormalReducerDefinition<State>(
+  { type, reducerName, createNotation }: ReducerDetails,
+  maybeReducerWithPrepare:
+    | CaseReducer<State, { payload: any; type: string }>
+    | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>,
+  context: ReducerHandlingContextMethods<State>,
+) {
+  let caseReducer: CaseReducer<State, any>
+  let prepareCallback: PrepareAction<any> | undefined
+  if ('reducer' in maybeReducerWithPrepare) {
+    if (
+      createNotation &&
+      !isCaseReducerWithPrepareDefinition(maybeReducerWithPrepare)
+    ) {
+      throw new Error(
+        'Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.',
+      )
+    }
+    caseReducer = maybeReducerWithPrepare.reducer
+    prepareCallback = maybeReducerWithPrepare.prepare
+  } else {
+    caseReducer = maybeReducerWithPrepare
+  }
+  context
+    .addCase(type, caseReducer)
+    .exposeCaseReducer(reducerName, caseReducer)
+    .exposeAction(
+      reducerName,
+      prepareCallback
+        ? createAction(type, prepareCallback)
+        : createAction(type),
+    )
+}
+
+function isAsyncThunkSliceReducerDefinition<State>(
+  reducerDefinition: any,
+): reducerDefinition is AsyncThunkSliceReducerDefinition<State, any, any, any> {
+  return reducerDefinition._reducerDefinitionType === ReducerType.asyncThunk
+}
+
+function isCaseReducerWithPrepareDefinition<State>(
+  reducerDefinition: any,
+): reducerDefinition is CaseReducerWithPrepareDefinition<State, any> {
+  return (
+    reducerDefinition._reducerDefinitionType === ReducerType.reducerWithPrepare
+  )
+}
+
+function handleThunkCaseReducerDefinition<State>(
+  { type, reducerName }: ReducerDetails,
+  reducerDefinition: AsyncThunkSliceReducerDefinition<State, any, any, any>,
+  context: ReducerHandlingContextMethods<State>,
+  cAT: typeof _createAsyncThunk | undefined,
+) {
+  if (!cAT) {
+    throw new Error(
+      'Cannot use `create.asyncThunk` in the built-in `createSlice`. ' +
+        'Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.',
+    )
+  }
+  const { payloadCreator, fulfilled, pending, rejected, settled, options } =
+    reducerDefinition
+  const thunk = cAT(type, payloadCreator, options as any)
+  context.exposeAction(reducerName, thunk)
+
+  if (fulfilled) {
+    context.addCase(thunk.fulfilled, fulfilled)
+  }
+  if (pending) {
+    context.addCase(thunk.pending, pending)
+  }
+  if (rejected) {
+    context.addCase(thunk.rejected, rejected)
+  }
+  if (settled) {
+    context.addMatcher(thunk.settled, settled)
+  }
+
+  context.exposeCaseReducer(reducerName, {
+    fulfilled: fulfilled || noop,
+    pending: pending || noop,
+    rejected: rejected || noop,
+    settled: settled || noop,
+  })
+}
+
+function noop() {}
Index: node_modules/@reduxjs/toolkit/src/devtoolsExtension.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/devtoolsExtension.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/devtoolsExtension.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,241 @@
+import type { Action, ActionCreator, StoreEnhancer } from 'redux'
+import { compose } from './reduxImports'
+
+/**
+ * @public
+ */
+export interface DevToolsEnhancerOptions {
+  /**
+   * the instance name to be showed on the monitor page. Default value is `document.title`.
+   * If not specified and there's no document title, it will consist of `tabId` and `instanceId`.
+   */
+  name?: string
+  /**
+   * action creators functions to be available in the Dispatcher.
+   */
+  actionCreators?: ActionCreator<any>[] | { [key: string]: ActionCreator<any> }
+  /**
+   * if more than one action is dispatched in the indicated interval, all new actions will be collected and sent at once.
+   * It is the joint between performance and speed. When set to `0`, all actions will be sent instantly.
+   * Set it to a higher value when experiencing perf issues (also `maxAge` to a lower value).
+   *
+   * @default 500 ms.
+   */
+  latency?: number
+  /**
+   * (> 1) - maximum allowed actions to be stored in the history tree. The oldest actions are removed once maxAge is reached. It's critical for performance.
+   *
+   * @default 50
+   */
+  maxAge?: number
+  /**
+   * Customizes how actions and state are serialized and deserialized. Can be a boolean or object. If given a boolean, the behavior is the same as if you
+   * were to pass an object and specify `options` as a boolean. Giving an object allows fine-grained customization using the `replacer` and `reviver`
+   * functions.
+   */
+  serialize?:
+    | boolean
+    | {
+        /**
+         * - `undefined` - will use regular `JSON.stringify` to send data (it's the fast mode).
+         * - `false` - will handle also circular references.
+         * - `true` - will handle also date, regex, undefined, error objects, symbols, maps, sets and functions.
+         * - object, which contains `date`, `regex`, `undefined`, `error`, `symbol`, `map`, `set` and `function` keys.
+         *   For each of them you can indicate if to include (by setting as `true`).
+         *   For `function` key you can also specify a custom function which handles serialization.
+         *   See [`jsan`](https://github.com/kolodny/jsan) for more details.
+         */
+        options?:
+          | undefined
+          | boolean
+          | {
+              date?: true
+              regex?: true
+              undefined?: true
+              error?: true
+              symbol?: true
+              map?: true
+              set?: true
+              function?: true | ((fn: (...args: any[]) => any) => string)
+            }
+        /**
+         * [JSON replacer function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) used for both actions and states stringify.
+         * In addition, you can specify a data type by adding a [`__serializedType__`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/helpers/index.js#L4)
+         * key. So you can deserialize it back while importing or persisting data.
+         * Moreover, it will also [show a nice preview showing the provided custom type](https://cloud.githubusercontent.com/assets/7957859/21814330/a17d556a-d761-11e6-85ef-159dd12f36c5.png):
+         */
+        replacer?: (key: string, value: unknown) => any
+        /**
+         * [JSON `reviver` function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter)
+         * used for parsing the imported actions and states. See [`remotedev-serialize`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/immutable/serialize.js#L8-L41)
+         * as an example on how to serialize special data types and get them back.
+         */
+        reviver?: (key: string, value: unknown) => any
+        /**
+         * Automatically serialize/deserialize immutablejs via [remotedev-serialize](https://github.com/zalmoxisus/remotedev-serialize).
+         * Just pass the Immutable library. It will support all ImmutableJS structures. You can even export them into a file and get them back.
+         * The only exception is `Record` class, for which you should pass this in addition the references to your classes in `refs`.
+         */
+        immutable?: any
+        /**
+         * ImmutableJS `Record` classes used to make possible restore its instances back when importing, persisting...
+         */
+        refs?: any
+      }
+  /**
+   * function which takes `action` object and id number as arguments, and should return `action` object back.
+   */
+  actionSanitizer?: <A extends Action>(action: A, id: number) => A
+  /**
+   * function which takes `state` object and index as arguments, and should return `state` object back.
+   */
+  stateSanitizer?: <S>(state: S, index: number) => S
+  /**
+   * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).
+   * If `actionsAllowlist` specified, `actionsDenylist` is ignored.
+   */
+  actionsDenylist?: string | string[]
+  /**
+   * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).
+   * If `actionsAllowlist` specified, `actionsDenylist` is ignored.
+   */
+  actionsAllowlist?: string | string[]
+  /**
+   * called for every action before sending, takes `state` and `action` object, and returns `true` in case it allows sending the current data to the monitor.
+   * Use it as a more advanced version of `actionsDenylist`/`actionsAllowlist` parameters.
+   */
+  predicate?: <S, A extends Action>(state: S, action: A) => boolean
+  /**
+   * if specified as `false`, it will not record the changes till clicking on `Start recording` button.
+   * Available only for Redux enhancer, for others use `autoPause`.
+   *
+   * @default true
+   */
+  shouldRecordChanges?: boolean
+  /**
+   * if specified, whenever clicking on `Pause recording` button and there are actions in the history log, will add this action type.
+   * If not specified, will commit when paused. Available only for Redux enhancer.
+   *
+   * @default "@@PAUSED""
+   */
+  pauseActionType?: string
+  /**
+   * auto pauses when the extension’s window is not opened, and so has zero impact on your app when not in use.
+   * Not available for Redux enhancer (as it already does it but storing the data to be sent).
+   *
+   * @default false
+   */
+  autoPause?: boolean
+  /**
+   * if specified as `true`, it will not allow any non-monitor actions to be dispatched till clicking on `Unlock changes` button.
+   * Available only for Redux enhancer.
+   *
+   * @default false
+   */
+  shouldStartLocked?: boolean
+  /**
+   * if set to `false`, will not recompute the states on hot reloading (or on replacing the reducers). Available only for Redux enhancer.
+   *
+   * @default true
+   */
+  shouldHotReload?: boolean
+  /**
+   * if specified as `true`, whenever there's an exception in reducers, the monitors will show the error message, and next actions will not be dispatched.
+   *
+   * @default false
+   */
+  shouldCatchErrors?: boolean
+  /**
+   * If you want to restrict the extension, specify the features you allow.
+   * If not specified, all of the features are enabled. When set as an object, only those included as `true` will be allowed.
+   * Note that except `true`/`false`, `import` and `export` can be set as `custom` (which is by default for Redux enhancer), meaning that the importing/exporting occurs on the client side.
+   * Otherwise, you'll get/set the data right from the monitor part.
+   */
+  features?: {
+    /**
+     * start/pause recording of dispatched actions
+     */
+    pause?: boolean
+    /**
+     * lock/unlock dispatching actions and side effects
+     */
+    lock?: boolean
+    /**
+     * persist states on page reloading
+     */
+    persist?: boolean
+    /**
+     * export history of actions in a file
+     */
+    export?: boolean | 'custom'
+    /**
+     * import history of actions from a file
+     */
+    import?: boolean | 'custom'
+    /**
+     * jump back and forth (time travelling)
+     */
+    jump?: boolean
+    /**
+     * skip (cancel) actions
+     */
+    skip?: boolean
+    /**
+     * drag and drop actions in the history list
+     */
+    reorder?: boolean
+    /**
+     * dispatch custom actions or action creators
+     */
+    dispatch?: boolean
+    /**
+     * generate tests for the selected actions
+     */
+    test?: boolean
+  }
+  /**
+   * Set to true or a stacktrace-returning function to record call stack traces for dispatched actions.
+   * Defaults to false.
+   */
+  trace?: boolean | (<A extends Action>(action: A) => string)
+  /**
+   * The maximum number of stack trace entries to record per action. Defaults to 10.
+   */
+  traceLimit?: number
+}
+
+type Compose = typeof compose
+
+interface ComposeWithDevTools {
+  (options: DevToolsEnhancerOptions): Compose
+  <StoreExt extends {}>(
+    ...funcs: StoreEnhancer<StoreExt>[]
+  ): StoreEnhancer<StoreExt>
+}
+
+/**
+ * @public
+ */
+export const composeWithDevTools: ComposeWithDevTools =
+  typeof window !== 'undefined' &&
+  (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
+    ? (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
+    : function () {
+        if (arguments.length === 0) return undefined
+        if (typeof arguments[0] === 'object') return compose
+        return compose.apply(null, arguments as any as Function[])
+      }
+
+/**
+ * @public
+ */
+export const devToolsEnhancer: {
+  (options: DevToolsEnhancerOptions): StoreEnhancer<any>
+} =
+  typeof window !== 'undefined' && (window as any).__REDUX_DEVTOOLS_EXTENSION__
+    ? (window as any).__REDUX_DEVTOOLS_EXTENSION__
+    : function () {
+        return function (noop) {
+          return noop
+        }
+      }
Index: node_modules/@reduxjs/toolkit/src/dynamicMiddleware/index.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/dynamicMiddleware/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/dynamicMiddleware/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,93 @@
+import type { Dispatch, Middleware, UnknownAction } from 'redux'
+import { compose } from '../reduxImports'
+import { createAction } from '../createAction'
+import { isAllOf } from '../matchers'
+import { nanoid } from '../nanoid'
+import { getOrInsertComputed } from '../utils'
+import type {
+  AddMiddleware,
+  DynamicMiddleware,
+  DynamicMiddlewareInstance,
+  MiddlewareEntry,
+  WithMiddleware,
+} from './types'
+export type {
+  DynamicMiddlewareInstance,
+  GetDispatchType as GetDispatch,
+  MiddlewareApiConfig,
+} from './types'
+
+const createMiddlewareEntry = <
+  State = any,
+  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
+>(
+  middleware: Middleware<any, State, DispatchType>,
+): MiddlewareEntry<State, DispatchType> => ({
+  middleware,
+  applied: new Map(),
+})
+
+const matchInstance =
+  (instanceId: string) =>
+  (action: any): action is { meta: { instanceId: string } } =>
+    action?.meta?.instanceId === instanceId
+
+export const createDynamicMiddleware = <
+  State = any,
+  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
+>(): DynamicMiddlewareInstance<State, DispatchType> => {
+  const instanceId = nanoid()
+  const middlewareMap = new Map<
+    Middleware<any, State, DispatchType>,
+    MiddlewareEntry<State, DispatchType>
+  >()
+
+  const withMiddleware = Object.assign(
+    createAction(
+      'dynamicMiddleware/add',
+      (...middlewares: Middleware<any, State, DispatchType>[]) => ({
+        payload: middlewares,
+        meta: {
+          instanceId,
+        },
+      }),
+    ),
+    { withTypes: () => withMiddleware },
+  ) as WithMiddleware<State, DispatchType>
+
+  const addMiddleware = Object.assign(
+    function addMiddleware(
+      ...middlewares: Middleware<any, State, DispatchType>[]
+    ) {
+      middlewares.forEach((middleware) => {
+        getOrInsertComputed(middlewareMap, middleware, createMiddlewareEntry)
+      })
+    },
+    { withTypes: () => addMiddleware },
+  ) as AddMiddleware<State, DispatchType>
+
+  const getFinalMiddleware: Middleware<{}, State, DispatchType> = (api) => {
+    const appliedMiddleware = Array.from(middlewareMap.values()).map((entry) =>
+      getOrInsertComputed(entry.applied, api, entry.middleware),
+    )
+    return compose(...appliedMiddleware)
+  }
+
+  const isWithMiddleware = isAllOf(withMiddleware, matchInstance(instanceId))
+
+  const middleware: DynamicMiddleware<State, DispatchType> =
+    (api) => (next) => (action) => {
+      if (isWithMiddleware(action)) {
+        addMiddleware(...action.payload)
+        return api.dispatch
+      }
+      return getFinalMiddleware(api)(next)(action)
+    }
+
+  return {
+    middleware,
+    addMiddleware,
+    withMiddleware,
+    instanceId,
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/dynamicMiddleware/react/index.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/dynamicMiddleware/react/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/dynamicMiddleware/react/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,101 @@
+import type {
+  DynamicMiddlewareInstance,
+  GetDispatch,
+  GetState,
+  MiddlewareApiConfig,
+  TSHelpersExtractDispatchExtensions,
+} from '@reduxjs/toolkit'
+import { createDynamicMiddleware as cDM } from '@reduxjs/toolkit'
+import type { Context } from 'react'
+import type { ReactReduxContextValue } from 'react-redux'
+import {
+  createDispatchHook,
+  ReactReduxContext,
+  useDispatch as useDefaultDispatch,
+} from 'react-redux'
+import type { Action, Dispatch, Middleware, UnknownAction } from 'redux'
+
+export type UseDispatchWithMiddlewareHook<
+  Middlewares extends Middleware<any, State, DispatchType>[] = [],
+  State = any,
+  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
+> = () => TSHelpersExtractDispatchExtensions<Middlewares> & DispatchType
+
+export type CreateDispatchWithMiddlewareHook<
+  State = any,
+  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
+> = {
+  <
+    Middlewares extends [
+      Middleware<any, State, DispatchType>,
+      ...Middleware<any, State, DispatchType>[],
+    ],
+  >(
+    ...middlewares: Middlewares
+  ): UseDispatchWithMiddlewareHook<Middlewares, State, DispatchType>
+  withTypes<
+    MiddlewareConfig extends MiddlewareApiConfig,
+  >(): CreateDispatchWithMiddlewareHook<
+    GetState<MiddlewareConfig>,
+    GetDispatch<MiddlewareConfig>
+  >
+}
+
+type ActionFromDispatch<DispatchType extends Dispatch<Action>> =
+  DispatchType extends Dispatch<infer Action> ? Action : never
+
+type ReactDynamicMiddlewareInstance<
+  State = any,
+  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
+> = DynamicMiddlewareInstance<State, DispatchType> & {
+  createDispatchWithMiddlewareHookFactory: (
+    context?: Context<ReactReduxContextValue<
+      State,
+      ActionFromDispatch<DispatchType>
+    > | null>,
+  ) => CreateDispatchWithMiddlewareHook<State, DispatchType>
+  createDispatchWithMiddlewareHook: CreateDispatchWithMiddlewareHook<
+    State,
+    DispatchType
+  >
+}
+
+export const createDynamicMiddleware = <
+  State = any,
+  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
+>(): ReactDynamicMiddlewareInstance<State, DispatchType> => {
+  const instance = cDM<State, DispatchType>()
+  const createDispatchWithMiddlewareHookFactory = (
+    // @ts-ignore
+    context: Context<ReactReduxContextValue<
+      State,
+      ActionFromDispatch<DispatchType>
+    > | null> = ReactReduxContext,
+  ) => {
+    const useDispatch =
+      context === ReactReduxContext
+        ? useDefaultDispatch
+        : createDispatchHook(context)
+    function createDispatchWithMiddlewareHook<
+      Middlewares extends Middleware<any, State, DispatchType>[],
+    >(...middlewares: Middlewares) {
+      instance.addMiddleware(...middlewares)
+      return useDispatch
+    }
+    createDispatchWithMiddlewareHook.withTypes = () =>
+      createDispatchWithMiddlewareHook
+    return createDispatchWithMiddlewareHook as CreateDispatchWithMiddlewareHook<
+      State,
+      DispatchType
+    >
+  }
+
+  const createDispatchWithMiddlewareHook =
+    createDispatchWithMiddlewareHookFactory()
+
+  return {
+    ...instance,
+    createDispatchWithMiddlewareHookFactory,
+    createDispatchWithMiddlewareHook,
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/dynamicMiddleware/tests/index.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/dynamicMiddleware/tests/index.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/dynamicMiddleware/tests/index.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,95 @@
+import type { Action, Middleware, UnknownAction } from 'redux'
+import type { ThunkDispatch } from 'redux-thunk'
+import { configureStore } from '../../configureStore'
+import { createDynamicMiddleware } from '../index'
+
+const untypedInstance = createDynamicMiddleware()
+
+interface AppDispatch extends ThunkDispatch<number, undefined, UnknownAction> {
+  (n: 1): 1
+}
+
+const typedInstance = createDynamicMiddleware<number, AppDispatch>()
+
+declare const staticMiddleware: Middleware<(n: 1) => 1>
+
+const store = configureStore({
+  reducer: () => 0,
+  middleware: (gDM) =>
+    gDM().prepend(typedInstance.middleware).concat(staticMiddleware),
+})
+
+declare const compatibleMiddleware: Middleware<{}, number, AppDispatch>
+declare const incompatibleMiddleware: Middleware<{}, string, AppDispatch>
+
+declare const addedMiddleware: Middleware<(n: 2) => 2>
+
+describe('type tests', () => {
+  test('instance typed at creation ensures middleware compatibility with store', () => {
+    const store = configureStore({
+      reducer: () => '',
+      // @ts-expect-error
+      middleware: (gDM) => gDM().prepend(typedInstance.middleware),
+    })
+  })
+
+  test('instance typed at creation enforces correct middleware type', () => {
+    typedInstance.addMiddleware(
+      compatibleMiddleware,
+      // @ts-expect-error
+      incompatibleMiddleware,
+    )
+
+    const dispatch = store.dispatch(
+      typedInstance.withMiddleware(
+        compatibleMiddleware,
+        // @ts-expect-error
+        incompatibleMiddleware,
+      ),
+    )
+  })
+
+  test('withTypes() enforces correct middleware type', () => {
+    const addMiddleware = untypedInstance.addMiddleware.withTypes<{
+      state: number
+      dispatch: AppDispatch
+    }>()
+
+    addMiddleware(
+      compatibleMiddleware,
+      // @ts-expect-error
+      incompatibleMiddleware,
+    )
+
+    const withMiddleware = untypedInstance.withMiddleware.withTypes<{
+      state: number
+      dispatch: AppDispatch
+    }>()
+
+    const dispatch = store.dispatch(
+      withMiddleware(
+        compatibleMiddleware,
+        // @ts-expect-error
+        incompatibleMiddleware,
+      ),
+    )
+  })
+
+  test('withMiddleware returns typed dispatch, with any applicable extensions', () => {
+    const dispatch = store.dispatch(
+      typedInstance.withMiddleware(addedMiddleware),
+    )
+
+    // standard
+    expectTypeOf(dispatch({ type: 'foo' })).toEqualTypeOf<Action<string>>()
+
+    // thunk
+    expectTypeOf(dispatch(() => 'foo')).toBeString()
+
+    // static
+    expectTypeOf(dispatch(1)).toEqualTypeOf<1>()
+
+    // added
+    expectTypeOf(dispatch(2)).toEqualTypeOf<2>()
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/dynamicMiddleware/tests/index.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/dynamicMiddleware/tests/index.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/dynamicMiddleware/tests/index.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,74 @@
+import type { Middleware } from 'redux'
+import { createDynamicMiddleware } from '../index'
+import { configureStore } from '../../configureStore'
+import type { BaseActionCreator, PayloadAction } from '../../createAction'
+import { createAction } from '../../createAction'
+import { isAllOf } from '../../matchers'
+
+const probeType = 'probeableMW/probe'
+
+export interface ProbeMiddleware
+  extends BaseActionCreator<number, typeof probeType> {
+  <Id extends number>(id: Id): PayloadAction<Id, typeof probeType>
+}
+
+export const probeMiddleware = createAction(probeType) as ProbeMiddleware
+
+const matchId =
+  <Id extends number>(id: Id) =>
+  (action: any): action is PayloadAction<Id> =>
+    action.payload === id
+
+export const makeProbeableMiddleware = <Id extends number>(
+  id: Id,
+): Middleware<{
+  (action: PayloadAction<Id, typeof probeType>): Id
+}> => {
+  const isMiddlewareAction = isAllOf(probeMiddleware, matchId(id))
+  return (api) => (next) => (action) => {
+    if (isMiddlewareAction(action)) {
+      return id
+    }
+    return next(action)
+  }
+}
+
+const staticMiddleware = makeProbeableMiddleware(1)
+
+describe('createDynamicMiddleware', () => {
+  it('allows injecting middleware after store instantiation', () => {
+    const dynamicInstance = createDynamicMiddleware()
+    const store = configureStore({
+      reducer: () => 0,
+      middleware: (gDM) =>
+        gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),
+    })
+    // normal, pre-inject
+    expect(store.dispatch(probeMiddleware(2))).toEqual(probeMiddleware(2))
+    // static
+    expect(store.dispatch(probeMiddleware(1))).toBe(1)
+
+    // inject
+    dynamicInstance.addMiddleware(makeProbeableMiddleware(2))
+
+    // injected
+    expect(store.dispatch(probeMiddleware(2))).toBe(2)
+  })
+  it('returns dispatch when withMiddleware is dispatched', () => {
+    const dynamicInstance = createDynamicMiddleware()
+    const store = configureStore({
+      reducer: () => 0,
+      middleware: (gDM) => gDM().prepend(dynamicInstance.middleware),
+    })
+
+    // normal, pre-inject
+    expect(store.dispatch(probeMiddleware(2))).toEqual(probeMiddleware(2))
+
+    const dispatch = store.dispatch(
+      dynamicInstance.withMiddleware(makeProbeableMiddleware(2)),
+    )
+    expect(dispatch).toEqual(expect.any(Function))
+
+    expect(dispatch(probeMiddleware(2))).toBe(2)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/dynamicMiddleware/tests/react.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/dynamicMiddleware/tests/react.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/dynamicMiddleware/tests/react.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,81 @@
+import type { Context } from 'react'
+import type { ReactReduxContextValue } from 'react-redux'
+import type { Action, Middleware, UnknownAction } from 'redux'
+import type { ThunkDispatch } from 'redux-thunk'
+import { createDynamicMiddleware } from '../react'
+
+interface AppDispatch extends ThunkDispatch<number, undefined, UnknownAction> {
+  (n: 1): 1
+}
+
+const untypedInstance = createDynamicMiddleware()
+
+const typedInstance = createDynamicMiddleware<number, AppDispatch>()
+
+declare const compatibleMiddleware: Middleware<{}, number, AppDispatch>
+declare const incompatibleMiddleware: Middleware<{}, string, AppDispatch>
+
+declare const customContext: Context<ReactReduxContextValue | null>
+
+declare const addedMiddleware: Middleware<(n: 2) => 2>
+
+describe('type tests', () => {
+  test('instance typed at creation enforces correct middleware type', () => {
+    const useDispatch = typedInstance.createDispatchWithMiddlewareHook(
+      compatibleMiddleware,
+      // @ts-expect-error
+      incompatibleMiddleware,
+    )
+
+    const createDispatchWithMiddlewareHook =
+      typedInstance.createDispatchWithMiddlewareHookFactory(customContext)
+    const useDispatchWithContext = createDispatchWithMiddlewareHook(
+      compatibleMiddleware,
+      // @ts-expect-error
+      incompatibleMiddleware,
+    )
+  })
+
+  test('withTypes() enforces correct middleware type', () => {
+    const createDispatchWithMiddlewareHook =
+      untypedInstance.createDispatchWithMiddlewareHook.withTypes<{
+        state: number
+        dispatch: AppDispatch
+      }>()
+    const useDispatch = createDispatchWithMiddlewareHook(
+      compatibleMiddleware,
+      // @ts-expect-error
+      incompatibleMiddleware,
+    )
+
+    const createCustomDispatchWithMiddlewareHook = untypedInstance
+      .createDispatchWithMiddlewareHookFactory(customContext)
+      .withTypes<{
+        state: number
+        dispatch: AppDispatch
+      }>()
+    const useCustomDispatch = createCustomDispatchWithMiddlewareHook(
+      compatibleMiddleware,
+      // @ts-expect-error
+      incompatibleMiddleware,
+    )
+  })
+
+  test('useDispatchWithMW returns typed dispatch, with any applicable extensions', () => {
+    const useDispatchWithMW =
+      typedInstance.createDispatchWithMiddlewareHook(addedMiddleware)
+    const dispatch = useDispatchWithMW()
+
+    // standard
+    expectTypeOf(dispatch({ type: 'foo' })).toEqualTypeOf<Action<string>>()
+
+    // thunk
+    expectTypeOf(dispatch(() => 'foo')).toBeString()
+
+    // static
+    expectTypeOf(dispatch(1)).toEqualTypeOf<1>()
+
+    // added
+    expectTypeOf(dispatch(2)).toEqualTypeOf<2>()
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/dynamicMiddleware/tests/react.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/dynamicMiddleware/tests/react.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/dynamicMiddleware/tests/react.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,101 @@
+import * as React from 'react'
+import { createDynamicMiddleware } from '../react'
+import { configureStore } from '../../configureStore'
+import { makeProbeableMiddleware, probeMiddleware } from './index.test'
+import { render } from '@testing-library/react'
+import type { Dispatch } from 'redux'
+import type { ReactReduxContextValue } from 'react-redux'
+import { Provider } from 'react-redux'
+
+const staticMiddleware = makeProbeableMiddleware(1)
+
+describe('createReactDynamicMiddleware', () => {
+  describe('createDispatchWithMiddlewareHook', () => {
+    it('injects middleware upon creation', () => {
+      const dynamicInstance = createDynamicMiddleware()
+      const store = configureStore({
+        reducer: () => 0,
+        middleware: (gDM) =>
+          gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),
+      })
+      // normal, pre-inject
+      expect(store.dispatch(probeMiddleware(2))).toEqual(probeMiddleware(2))
+      // static
+      expect(store.dispatch(probeMiddleware(1))).toBe(1)
+
+      const useDispatch = dynamicInstance.createDispatchWithMiddlewareHook(
+        makeProbeableMiddleware(2),
+      )
+
+      // injected
+      expect(store.dispatch(probeMiddleware(2))).toBe(2)
+    })
+
+    it('returns dispatch', () => {
+      const dynamicInstance = createDynamicMiddleware()
+      const store = configureStore({
+        reducer: () => 0,
+        middleware: (gDM) =>
+          gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),
+      })
+
+      const useDispatch = dynamicInstance.createDispatchWithMiddlewareHook(
+        makeProbeableMiddleware(2),
+      )
+
+      let dispatch: Dispatch | undefined
+      function Component() {
+        dispatch = useDispatch()
+
+        return null
+      }
+      render(<Component />, {
+        wrapper: ({ children }) => (
+          <Provider store={store}>{children}</Provider>
+        ),
+      })
+      expect(dispatch).toBe(store.dispatch)
+    })
+  })
+  describe('createDispatchWithMiddlewareHookFactory', () => {
+    it('returns the correct store dispatch', () => {
+      const dynamicInstance = createDynamicMiddleware()
+      const store = configureStore({
+        reducer: () => 0,
+        middleware: (gDM) =>
+          gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),
+      })
+      const store2 = configureStore({
+        reducer: () => '',
+        middleware: (gDM) =>
+          gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),
+      })
+
+      const context = React.createContext<ReactReduxContextValue | null>(null)
+
+      const createDispatchWithMiddlewareHook =
+        dynamicInstance.createDispatchWithMiddlewareHookFactory(context)
+
+      const useDispatch = createDispatchWithMiddlewareHook(
+        makeProbeableMiddleware(2),
+      )
+
+      let dispatch: Dispatch | undefined
+      function Component() {
+        dispatch = useDispatch()
+
+        return null
+      }
+      render(<Component />, {
+        wrapper: ({ children }) => (
+          <Provider store={store}>
+            <Provider context={context} store={store2}>
+              {children}
+            </Provider>
+          </Provider>
+        ),
+      })
+      expect(dispatch).toBe(store2.dispatch)
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/dynamicMiddleware/types.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/dynamicMiddleware/types.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/dynamicMiddleware/types.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,82 @@
+import type { Dispatch, Middleware, MiddlewareAPI, UnknownAction } from 'redux'
+import type { BaseActionCreator, PayloadAction } from '../createAction'
+import type { GetState } from '../createAsyncThunk'
+import type { ExtractDispatchExtensions, FallbackIfUnknown } from '../tsHelpers'
+
+export type GetMiddlewareApi<MiddlewareApiConfig> = MiddlewareAPI<
+  GetDispatchType<MiddlewareApiConfig>,
+  GetState<MiddlewareApiConfig>
+>
+
+export type MiddlewareApiConfig = {
+  state?: unknown
+  dispatch?: Dispatch
+}
+
+// TODO: consolidate with cAT helpers?
+export type GetDispatchType<MiddlewareApiConfig> = MiddlewareApiConfig extends {
+  dispatch: infer DispatchType
+}
+  ? FallbackIfUnknown<DispatchType, Dispatch>
+  : Dispatch
+
+export type AddMiddleware<
+  State = any,
+  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
+> = {
+  (...middlewares: Middleware<any, State, DispatchType>[]): void
+  withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): AddMiddleware<
+    GetState<MiddlewareConfig>,
+    GetDispatchType<MiddlewareConfig>
+  >
+}
+
+export type WithMiddleware<
+  State = any,
+  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
+> = BaseActionCreator<
+  Middleware<any, State, DispatchType>[],
+  'dynamicMiddleware/add',
+  { instanceId: string }
+> & {
+  <Middlewares extends Middleware<any, State, DispatchType>[]>(
+    ...middlewares: Middlewares
+  ): PayloadAction<Middlewares, 'dynamicMiddleware/add', { instanceId: string }>
+  withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): WithMiddleware<
+    GetState<MiddlewareConfig>,
+    GetDispatchType<MiddlewareConfig>
+  >
+}
+
+export interface DynamicDispatch {
+  // return a version of dispatch that knows about middleware
+  <Middlewares extends Middleware<any>[]>(
+    action: PayloadAction<Middlewares, 'dynamicMiddleware/add'>,
+  ): ExtractDispatchExtensions<Middlewares> & this
+}
+
+export type MiddlewareEntry<
+  State = unknown,
+  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
+> = {
+  middleware: Middleware<any, State, DispatchType>
+  applied: Map<
+    MiddlewareAPI<DispatchType, State>,
+    ReturnType<Middleware<any, State, DispatchType>>
+  >
+}
+
+export type DynamicMiddleware<
+  State = unknown,
+  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
+> = Middleware<DynamicDispatch, State, DispatchType>
+
+export type DynamicMiddlewareInstance<
+  State = unknown,
+  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
+> = {
+  middleware: DynamicMiddleware<State, DispatchType>
+  addMiddleware: AddMiddleware<State, DispatchType>
+  withMiddleware: WithMiddleware<State, DispatchType>
+  instanceId: string
+}
Index: node_modules/@reduxjs/toolkit/src/entities/create_adapter.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/create_adapter.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/create_adapter.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,47 @@
+import type { EntityAdapter, EntityId, EntityAdapterOptions } from './models'
+import { createInitialStateFactory } from './entity_state'
+import { createSelectorsFactory } from './state_selectors'
+import { createSortedStateAdapter } from './sorted_state_adapter'
+import { createUnsortedStateAdapter } from './unsorted_state_adapter'
+import type { WithRequiredProp } from '../tsHelpers'
+
+export function createEntityAdapter<T, Id extends EntityId>(
+  options: WithRequiredProp<EntityAdapterOptions<T, Id>, 'selectId'>,
+): EntityAdapter<T, Id>
+
+export function createEntityAdapter<T extends { id: EntityId }>(
+  options?: Omit<EntityAdapterOptions<T, T['id']>, 'selectId'>,
+): EntityAdapter<T, T['id']>
+
+/**
+ *
+ * @param options
+ *
+ * @public
+ */
+export function createEntityAdapter<T>(
+  options: EntityAdapterOptions<T, EntityId> = {},
+): EntityAdapter<T, EntityId> {
+  const {
+    selectId,
+    sortComparer,
+  }: Required<EntityAdapterOptions<T, EntityId>> = {
+    sortComparer: false,
+    selectId: (instance: any) => instance.id,
+    ...options,
+  }
+
+  const stateAdapter = sortComparer
+    ? createSortedStateAdapter(selectId, sortComparer)
+    : createUnsortedStateAdapter(selectId)
+  const stateFactory = createInitialStateFactory(stateAdapter)
+  const selectorsFactory = createSelectorsFactory<T, EntityId>()
+
+  return {
+    selectId,
+    sortComparer,
+    ...stateFactory,
+    ...selectorsFactory,
+    ...stateAdapter,
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/entities/entity_state.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/entity_state.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/entity_state.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,38 @@
+import type {
+  EntityId,
+  EntityState,
+  EntityStateAdapter,
+  EntityStateFactory,
+} from './models'
+
+export function getInitialEntityState<T, Id extends EntityId>(): EntityState<
+  T,
+  Id
+> {
+  return {
+    ids: [],
+    entities: {} as Record<Id, T>,
+  }
+}
+
+export function createInitialStateFactory<T, Id extends EntityId>(
+  stateAdapter: EntityStateAdapter<T, Id>,
+): EntityStateFactory<T, Id> {
+  function getInitialState(
+    state?: undefined,
+    entities?: readonly T[] | Record<Id, T>,
+  ): EntityState<T, Id>
+  function getInitialState<S extends object>(
+    additionalState: S,
+    entities?: readonly T[] | Record<Id, T>,
+  ): EntityState<T, Id> & S
+  function getInitialState(
+    additionalState: any = {},
+    entities?: readonly T[] | Record<Id, T>,
+  ): any {
+    const state = Object.assign(getInitialEntityState(), additionalState)
+    return entities ? stateAdapter.setAll(state, entities) : state
+  }
+
+  return { getInitialState }
+}
Index: node_modules/@reduxjs/toolkit/src/entities/index.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,8 @@
+export { createEntityAdapter } from './create_adapter'
+export type {
+  EntityState,
+  EntityAdapter,
+  Update,
+  IdSelector,
+  Comparer,
+} from './models'
Index: node_modules/@reduxjs/toolkit/src/entities/models.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/models.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/models.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,198 @@
+import type { Draft } from 'immer'
+import type { PayloadAction } from '../createAction'
+import type { CastAny, Id } from '../tsHelpers'
+import type { UncheckedIndexedAccess } from '../uncheckedindexed.js'
+import type { GetSelectorsOptions } from './state_selectors'
+
+/**
+ * @public
+ */
+export type EntityId = number | string
+
+/**
+ * @public
+ */
+export type Comparer<T> = (a: T, b: T) => number
+
+/**
+ * @public
+ */
+export type IdSelector<T, Id extends EntityId> = (model: T) => Id
+
+/**
+ * @public
+ */
+export type Update<T, Id extends EntityId> = { id: Id; changes: Partial<T> }
+
+/**
+ * @public
+ */
+export interface EntityState<T, Id extends EntityId> {
+  ids: Id[]
+  entities: Record<Id, T>
+}
+
+/**
+ * @public
+ */
+export interface EntityAdapterOptions<T, Id extends EntityId> {
+  selectId?: IdSelector<T, Id>
+  sortComparer?: false | Comparer<T>
+}
+
+export type PreventAny<S, T, Id extends EntityId> = CastAny<
+  S,
+  EntityState<T, Id>
+>
+
+export type DraftableEntityState<T, Id extends EntityId> =
+  | EntityState<T, Id>
+  | Draft<EntityState<T, Id>>
+
+/**
+ * @public
+ */
+export interface EntityStateAdapter<T, Id extends EntityId> {
+  addOne<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    entity: T,
+  ): S
+  addOne<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    action: PayloadAction<T>,
+  ): S
+
+  addMany<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    entities: readonly T[] | Record<Id, T>,
+  ): S
+  addMany<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    entities: PayloadAction<readonly T[] | Record<Id, T>>,
+  ): S
+
+  setOne<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    entity: T,
+  ): S
+  setOne<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    action: PayloadAction<T>,
+  ): S
+  setMany<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    entities: readonly T[] | Record<Id, T>,
+  ): S
+  setMany<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    entities: PayloadAction<readonly T[] | Record<Id, T>>,
+  ): S
+  setAll<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    entities: readonly T[] | Record<Id, T>,
+  ): S
+  setAll<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    entities: PayloadAction<readonly T[] | Record<Id, T>>,
+  ): S
+
+  removeOne<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    key: Id,
+  ): S
+  removeOne<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    key: PayloadAction<Id>,
+  ): S
+
+  removeMany<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    keys: readonly Id[],
+  ): S
+  removeMany<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    keys: PayloadAction<readonly Id[]>,
+  ): S
+
+  removeAll<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+  ): S
+
+  updateOne<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    update: Update<T, Id>,
+  ): S
+  updateOne<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    update: PayloadAction<Update<T, Id>>,
+  ): S
+
+  updateMany<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    updates: ReadonlyArray<Update<T, Id>>,
+  ): S
+  updateMany<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    updates: PayloadAction<ReadonlyArray<Update<T, Id>>>,
+  ): S
+
+  upsertOne<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    entity: T,
+  ): S
+  upsertOne<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    entity: PayloadAction<T>,
+  ): S
+
+  upsertMany<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    entities: readonly T[] | Record<Id, T>,
+  ): S
+  upsertMany<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    entities: PayloadAction<readonly T[] | Record<Id, T>>,
+  ): S
+}
+
+/**
+ * @public
+ */
+export interface EntitySelectors<T, V, IdType extends EntityId> {
+  selectIds: (state: V) => IdType[]
+  selectEntities: (state: V) => Record<IdType, T>
+  selectAll: (state: V) => T[]
+  selectTotal: (state: V) => number
+  selectById: (state: V, id: IdType) => Id<UncheckedIndexedAccess<T>>
+}
+
+/**
+ * @public
+ */
+export interface EntityStateFactory<T, Id extends EntityId> {
+  getInitialState(
+    state?: undefined,
+    entities?: Record<Id, T> | readonly T[],
+  ): EntityState<T, Id>
+  getInitialState<S extends object>(
+    state: S,
+    entities?: Record<Id, T> | readonly T[],
+  ): EntityState<T, Id> & S
+}
+
+/**
+ * @public
+ */
+export interface EntityAdapter<T, Id extends EntityId>
+  extends EntityStateAdapter<T, Id>,
+    EntityStateFactory<T, Id>,
+    Required<EntityAdapterOptions<T, Id>> {
+  getSelectors(
+    selectState?: undefined,
+    options?: GetSelectorsOptions,
+  ): EntitySelectors<T, EntityState<T, Id>, Id>
+  getSelectors<V>(
+    selectState: (state: V) => EntityState<T, Id>,
+    options?: GetSelectorsOptions,
+  ): EntitySelectors<T, V, Id>
+}
Index: node_modules/@reduxjs/toolkit/src/entities/sorted_state_adapter.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/sorted_state_adapter.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/sorted_state_adapter.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,266 @@
+import type {
+  IdSelector,
+  Comparer,
+  EntityStateAdapter,
+  Update,
+  EntityId,
+  DraftableEntityState,
+} from './models'
+import { createStateOperator } from './state_adapter'
+import { createUnsortedStateAdapter } from './unsorted_state_adapter'
+import {
+  selectIdValue,
+  ensureEntitiesArray,
+  splitAddedUpdatedEntities,
+  getCurrent,
+} from './utils'
+
+// Borrowed from Replay
+export function findInsertIndex<T>(
+  sortedItems: T[],
+  item: T,
+  comparisonFunction: Comparer<T>,
+): number {
+  let lowIndex = 0
+  let highIndex = sortedItems.length
+  while (lowIndex < highIndex) {
+    let middleIndex = (lowIndex + highIndex) >>> 1
+    const currentItem = sortedItems[middleIndex]
+    const res = comparisonFunction(item, currentItem)
+    if (res >= 0) {
+      lowIndex = middleIndex + 1
+    } else {
+      highIndex = middleIndex
+    }
+  }
+
+  return lowIndex
+}
+
+export function insert<T>(
+  sortedItems: T[],
+  item: T,
+  comparisonFunction: Comparer<T>,
+): T[] {
+  const insertAtIndex = findInsertIndex(sortedItems, item, comparisonFunction)
+
+  sortedItems.splice(insertAtIndex, 0, item)
+
+  return sortedItems
+}
+
+export function createSortedStateAdapter<T, Id extends EntityId>(
+  selectId: IdSelector<T, Id>,
+  comparer: Comparer<T>,
+): EntityStateAdapter<T, Id> {
+  type R = DraftableEntityState<T, Id>
+
+  const { removeOne, removeMany, removeAll } =
+    createUnsortedStateAdapter(selectId)
+
+  function addOneMutably(entity: T, state: R): void {
+    return addManyMutably([entity], state)
+  }
+
+  function addManyMutably(
+    newEntities: readonly T[] | Record<Id, T>,
+    state: R,
+    existingIds?: Id[],
+  ): void {
+    newEntities = ensureEntitiesArray(newEntities)
+
+    const existingKeys = new Set<Id>(existingIds ?? getCurrent(state.ids))
+    const addedKeys = new Set<Id>();
+    const models = newEntities.filter(
+      (model) => {
+          const modelId = selectIdValue(model, selectId);
+          const notAdded = !addedKeys.has(modelId);
+          if (notAdded) addedKeys.add(modelId);
+          return !existingKeys.has(modelId) && notAdded;
+      }
+    )
+
+    if (models.length !== 0) {
+      mergeFunction(state, models)
+    }
+  }
+
+  function setOneMutably(entity: T, state: R): void {
+    return setManyMutably([entity], state)
+  }
+
+  function setManyMutably(
+    newEntities: readonly T[] | Record<Id, T>,
+    state: R,
+  ): void {
+    let deduplicatedEntities = {} as Record<Id, T>;
+    newEntities = ensureEntitiesArray(newEntities)
+    if (newEntities.length !== 0) {
+      for (const item of newEntities) {
+        const entityId = selectId(item);
+        // For multiple items with the same ID, we should keep the last one.
+        deduplicatedEntities[entityId] = item;
+        delete (state.entities as Record<Id, T>)[entityId]
+      }
+      newEntities = ensureEntitiesArray(deduplicatedEntities);
+      mergeFunction(state, newEntities)
+    }
+  }
+
+  function setAllMutably(
+    newEntities: readonly T[] | Record<Id, T>,
+    state: R,
+  ): void {
+    newEntities = ensureEntitiesArray(newEntities)
+    state.entities = {} as Record<Id, T>
+    state.ids = []
+
+    addManyMutably(newEntities, state, [])
+  }
+
+  function updateOneMutably(update: Update<T, Id>, state: R): void {
+    return updateManyMutably([update], state)
+  }
+
+  function updateManyMutably(
+    updates: ReadonlyArray<Update<T, Id>>,
+    state: R,
+  ): void {
+    let appliedUpdates = false
+    let replacedIds = false
+
+    for (let update of updates) {
+      const entity: T | undefined = (state.entities as Record<Id, T>)[update.id]
+      if (!entity) {
+        continue
+      }
+
+      appliedUpdates = true
+
+      Object.assign(entity, update.changes)
+      const newId = selectId(entity)
+
+      if (update.id !== newId) {
+        // We do support the case where updates can change an item's ID.
+        // This makes things trickier - go ahead and swap the IDs in state now.
+        replacedIds = true
+        delete (state.entities as Record<Id, T>)[update.id]
+        const oldIndex = (state.ids as Id[]).indexOf(update.id)
+        state.ids[oldIndex] = newId
+        ;(state.entities as Record<Id, T>)[newId] = entity
+      }
+    }
+
+    if (appliedUpdates) {
+      mergeFunction(state, [], appliedUpdates, replacedIds)
+    }
+  }
+
+  function upsertOneMutably(entity: T, state: R): void {
+    return upsertManyMutably([entity], state)
+  }
+
+  function upsertManyMutably(
+    newEntities: readonly T[] | Record<Id, T>,
+    state: R,
+  ): void {
+    const [added, updated, existingIdsArray] = splitAddedUpdatedEntities<T, Id>(
+      newEntities,
+      selectId,
+      state,
+    )
+
+    if (added.length) {
+      addManyMutably(added, state, existingIdsArray)
+    }
+    if (updated.length) {
+      updateManyMutably(updated, state)
+    }
+  }
+
+  function areArraysEqual(a: readonly unknown[], b: readonly unknown[]) {
+    if (a.length !== b.length) {
+      return false
+    }
+
+    for (let i = 0; i < a.length; i++) {
+      if (a[i] === b[i]) {
+        continue
+      }
+      return false
+    }
+    return true
+  }
+
+  type MergeFunction = (
+    state: R,
+    addedItems: readonly T[],
+    appliedUpdates?: boolean,
+    replacedIds?: boolean,
+  ) => void
+
+  const mergeFunction: MergeFunction = (
+    state,
+    addedItems,
+    appliedUpdates,
+    replacedIds,
+  ) => {
+    const currentEntities = getCurrent(state.entities)
+    const currentIds = getCurrent(state.ids)
+
+    const stateEntities = state.entities as Record<Id, T>
+
+    let ids: Iterable<Id> = currentIds
+    if (replacedIds) {
+      ids = new Set(currentIds)
+    }
+
+    let sortedEntities: T[] = []
+    for (const id of ids) {
+      const entity = currentEntities[id]
+      if (entity) {
+        sortedEntities.push(entity)
+      }
+    }
+    const wasPreviouslyEmpty = sortedEntities.length === 0
+
+    // Insert/overwrite all new/updated
+    for (const item of addedItems) {
+      stateEntities[selectId(item)] = item
+
+      if (!wasPreviouslyEmpty) {
+        // Binary search insertion generally requires fewer comparisons
+        insert(sortedEntities, item, comparer)
+      }
+    }
+
+    if (wasPreviouslyEmpty) {
+      // All we have is the incoming values, sort them
+      sortedEntities = addedItems.slice().sort(comparer)
+    } else if (appliedUpdates) {
+      // We should have a _mostly_-sorted array already
+      sortedEntities.sort(comparer)
+    }
+
+    const newSortedIds = sortedEntities.map(selectId)
+
+    if (!areArraysEqual(currentIds, newSortedIds)) {
+      state.ids = newSortedIds
+    }
+  }
+
+  return {
+    removeOne,
+    removeMany,
+    removeAll,
+    addOne: createStateOperator(addOneMutably),
+    updateOne: createStateOperator(updateOneMutably),
+    upsertOne: createStateOperator(upsertOneMutably),
+    setOne: createStateOperator(setOneMutably),
+    setMany: createStateOperator(setManyMutably),
+    setAll: createStateOperator(setAllMutably),
+    addMany: createStateOperator(addManyMutably),
+    updateMany: createStateOperator(updateManyMutably),
+    upsertMany: createStateOperator(upsertManyMutably),
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/entities/state_adapter.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/state_adapter.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/state_adapter.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,58 @@
+import { createNextState, isDraft } from '../immerImports'
+import type { Draft } from 'immer'
+import type { EntityId, DraftableEntityState, PreventAny } from './models'
+import type { PayloadAction } from '../createAction'
+import { isFSA } from '../createAction'
+
+export const isDraftTyped = isDraft as <T>(
+  value: T | Draft<T>,
+) => value is Draft<T>
+
+export function createSingleArgumentStateOperator<T, Id extends EntityId>(
+  mutator: (state: DraftableEntityState<T, Id>) => void,
+) {
+  const operator = createStateOperator(
+    (_: undefined, state: DraftableEntityState<T, Id>) => mutator(state),
+  )
+
+  return function operation<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+  ): S {
+    return operator(state as S, undefined)
+  }
+}
+
+export function createStateOperator<T, Id extends EntityId, R>(
+  mutator: (arg: R, state: DraftableEntityState<T, Id>) => void,
+) {
+  return function operation<S extends DraftableEntityState<T, Id>>(
+    state: S,
+    arg: R | PayloadAction<R>,
+  ): S {
+    function isPayloadActionArgument(
+      arg: R | PayloadAction<R>,
+    ): arg is PayloadAction<R> {
+      return isFSA(arg)
+    }
+
+    const runMutator = (draft: DraftableEntityState<T, Id>) => {
+      if (isPayloadActionArgument(arg)) {
+        mutator(arg.payload, draft)
+      } else {
+        mutator(arg, draft)
+      }
+    }
+
+    if (isDraftTyped<DraftableEntityState<T, Id>>(state)) {
+      // we must already be inside a `createNextState` call, likely because
+      // this is being wrapped in `createReducer` or `createSlice`.
+      // It's safe to just pass the draft to the mutator.
+      runMutator(state)
+
+      // since it's a draft, we'll just return it
+      return state
+    }
+
+    return createNextState(state, runMutator)
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/entities/state_selectors.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/state_selectors.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/state_selectors.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,73 @@
+import type { CreateSelectorFunction, Selector } from 'reselect'
+import { createDraftSafeSelector } from '../createDraftSafeSelector'
+import type { EntityId, EntitySelectors, EntityState } from './models'
+
+type AnyCreateSelectorFunction = CreateSelectorFunction<any, any, any>
+
+export type GetSelectorsOptions = {
+  createSelector?: AnyCreateSelectorFunction
+}
+
+export function createSelectorsFactory<T, Id extends EntityId>() {
+  function getSelectors(
+    selectState?: undefined,
+    options?: GetSelectorsOptions,
+  ): EntitySelectors<T, EntityState<T, Id>, Id>
+  function getSelectors<V>(
+    selectState: (state: V) => EntityState<T, Id>,
+    options?: GetSelectorsOptions,
+  ): EntitySelectors<T, V, Id>
+  function getSelectors<V>(
+    selectState?: (state: V) => EntityState<T, Id>,
+    options: GetSelectorsOptions = {},
+  ): EntitySelectors<T, any, Id> {
+    const {
+      createSelector = createDraftSafeSelector as AnyCreateSelectorFunction,
+    } = options
+
+    const selectIds = (state: EntityState<T, Id>) => state.ids
+
+    const selectEntities = (state: EntityState<T, Id>) => state.entities
+
+    const selectAll = createSelector(
+      selectIds,
+      selectEntities,
+      (ids, entities): T[] => ids.map((id) => entities[id]!),
+    )
+
+    const selectId = (_: unknown, id: Id) => id
+
+    const selectById = (entities: Record<Id, T>, id: Id) => entities[id]
+
+    const selectTotal = createSelector(selectIds, (ids) => ids.length)
+
+    if (!selectState) {
+      return {
+        selectIds,
+        selectEntities,
+        selectAll,
+        selectTotal,
+        selectById: createSelector(selectEntities, selectId, selectById),
+      }
+    }
+
+    const selectGlobalizedEntities = createSelector(
+      selectState as Selector<V, EntityState<T, Id>>,
+      selectEntities,
+    )
+
+    return {
+      selectIds: createSelector(selectState, selectIds),
+      selectEntities: selectGlobalizedEntities,
+      selectAll: createSelector(selectState, selectAll),
+      selectTotal: createSelector(selectState, selectTotal),
+      selectById: createSelector(
+        selectGlobalizedEntities,
+        selectId,
+        selectById,
+      ),
+    }
+  }
+
+  return { getSelectors }
+}
Index: node_modules/@reduxjs/toolkit/src/entities/tests/entity_slice_enhancer.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/tests/entity_slice_enhancer.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/tests/entity_slice_enhancer.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,59 @@
+import { createEntityAdapter, createSlice } from '../..'
+import type {
+  PayloadAction,
+  Slice,
+  SliceCaseReducers,
+  UnknownAction,
+} from '../..'
+import type { EntityId, EntityState, IdSelector } from '../models'
+import type { BookModel } from './fixtures/book'
+
+describe('Entity Slice Enhancer', () => {
+  let slice: Slice<EntityState<BookModel, BookModel['id']>>
+
+  beforeEach(() => {
+    const indieSlice = entitySliceEnhancer({
+      name: 'book',
+      selectId: (book: BookModel) => book.id,
+    })
+    slice = indieSlice
+  })
+
+  it('exposes oneAdded', () => {
+    const book = {
+      id: '0',
+      title: 'Der Steppenwolf',
+      author: 'Herman Hesse',
+    }
+    const action = slice.actions.oneAdded(book)
+    const oneAdded = slice.reducer(undefined, action as UnknownAction)
+    expect(oneAdded.entities['0']).toBe(book)
+  })
+})
+
+interface EntitySliceArgs<T, Id extends EntityId> {
+  name: string
+  selectId: IdSelector<T, Id>
+  modelReducer?: SliceCaseReducers<T>
+}
+
+function entitySliceEnhancer<T, Id extends EntityId>({
+  name,
+  selectId,
+  modelReducer,
+}: EntitySliceArgs<T, Id>) {
+  const modelAdapter = createEntityAdapter({
+    selectId,
+  })
+
+  return createSlice({
+    name,
+    initialState: modelAdapter.getInitialState(),
+    reducers: {
+      oneAdded(state, action: PayloadAction<T>) {
+        modelAdapter.addOne(state, action.payload)
+      },
+      ...modelReducer,
+    },
+  })
+}
Index: node_modules/@reduxjs/toolkit/src/entities/tests/entity_state.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/tests/entity_state.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/tests/entity_state.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,104 @@
+import type { EntityAdapter } from '../index'
+import { createEntityAdapter } from '../index'
+import type { PayloadAction } from '../../createAction'
+import { createAction } from '../../createAction'
+import { createSlice } from '../../createSlice'
+import type { BookModel } from './fixtures/book'
+
+describe('Entity State', () => {
+  let adapter: EntityAdapter<BookModel, string>
+
+  beforeEach(() => {
+    adapter = createEntityAdapter({
+      selectId: (book: BookModel) => book.id,
+    })
+  })
+
+  it('should let you get the initial state', () => {
+    const initialState = adapter.getInitialState()
+
+    expect(initialState).toEqual({
+      ids: [],
+      entities: {},
+    })
+  })
+
+  it('should let you provide additional initial state properties', () => {
+    const additionalProperties = { isHydrated: true }
+
+    const initialState = adapter.getInitialState(additionalProperties)
+
+    expect(initialState).toEqual({
+      ...additionalProperties,
+      ids: [],
+      entities: {},
+    })
+  })
+
+  it('should let you provide initial entities', () => {
+    const book1: BookModel = { id: 'a', title: 'First' }
+
+    const initialState = adapter.getInitialState(undefined, [book1])
+
+    expect(initialState).toEqual({
+      ids: [book1.id],
+      entities: { [book1.id]: book1 },
+    })
+
+    const additionalProperties = { isHydrated: true }
+
+    const initialState2 = adapter.getInitialState(additionalProperties, [book1])
+
+    expect(initialState2).toEqual({
+      ...additionalProperties,
+      ids: [book1.id],
+      entities: { [book1.id]: book1 },
+    })
+  })
+
+  it('should allow methods to be passed as reducers', () => {
+    const upsertBook = createAction<BookModel>('otherBooks/upsert')
+
+    const booksSlice = createSlice({
+      name: 'books',
+      initialState: adapter.getInitialState(),
+      reducers: {
+        addOne: adapter.addOne,
+        removeOne(state, action: PayloadAction<string>) {
+          // TODO The nested `produce` calls don't mutate `state` here as I would have expected.
+          // TODO (note that `state` here is actually an Immer Draft<S>, from `createReducer`)
+          // TODO However, this works if we _return_ the new plain result value instead
+          // TODO See https://github.com/immerjs/immer/issues/533
+          const result = adapter.removeOne(state, action)
+          return result
+        },
+      },
+      extraReducers: (builder) => {
+        builder.addCase(upsertBook, (state, action) => {
+          return adapter.upsertOne(state, action)
+        })
+      },
+    })
+
+    const { addOne, removeOne } = booksSlice.actions
+    const { reducer } = booksSlice
+
+    const selectors = adapter.getSelectors()
+
+    const book1: BookModel = { id: 'a', title: 'First' }
+    const book1a: BookModel = { id: 'a', title: 'Second' }
+
+    const afterAddOne = reducer(undefined, addOne(book1))
+    expect(afterAddOne.entities[book1.id]).toBe(book1)
+
+    const afterRemoveOne = reducer(afterAddOne, removeOne(book1.id))
+    expect(afterRemoveOne.entities[book1.id]).toBeUndefined()
+    expect(selectors.selectTotal(afterRemoveOne)).toBe(0)
+
+    const afterUpsertFirst = reducer(afterRemoveOne, upsertBook(book1))
+    const afterUpsertSecond = reducer(afterUpsertFirst, upsertBook(book1a))
+
+    expect(afterUpsertSecond.entities[book1.id]).toEqual(book1a)
+    expect(selectors.selectTotal(afterUpsertSecond)).toBe(1)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/entities/tests/fixtures/book.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/tests/fixtures/book.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/tests/fixtures/book.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,26 @@
+export interface BookModel {
+  id: string
+  title: string
+  author?: string
+}
+
+export const AClockworkOrange: BookModel = Object.freeze({
+  id: 'aco',
+  title: 'A Clockwork Orange',
+})
+
+export const AnimalFarm: BookModel = Object.freeze({
+  id: 'af',
+  title: 'Animal Farm',
+})
+
+export const TheGreatGatsby: BookModel = Object.freeze({
+  id: 'tgg',
+  title: 'The Great Gatsby',
+})
+
+export const TheHobbit: BookModel = Object.freeze({
+  id: 'th',
+  title: 'The Hobbit',
+  author: 'J. R. R. Tolkien',
+})
Index: node_modules/@reduxjs/toolkit/src/entities/tests/sorted_state_adapter.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/tests/sorted_state_adapter.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/tests/sorted_state_adapter.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1181 @@
+import type { PayloadAction } from '@reduxjs/toolkit'
+import {
+  configureStore,
+  createAction,
+  createSlice,
+  nanoid,
+} from '@reduxjs/toolkit'
+import { createNextState } from '../..'
+import { createEntityAdapter } from '../create_adapter'
+import type { EntityAdapter, EntityState } from '../models'
+import type { BookModel } from './fixtures/book'
+import {
+  AClockworkOrange,
+  AnimalFarm,
+  TheGreatGatsby,
+  TheHobbit,
+} from './fixtures/book'
+
+describe('Sorted State Adapter', () => {
+  let adapter: EntityAdapter<BookModel, string>
+  let state: EntityState<BookModel, string>
+
+  beforeAll(() => {
+    //eslint-disable-next-line
+    Object.defineProperty(Array.prototype, 'unwantedField', {
+      enumerable: true,
+      configurable: true,
+      value: 'This should not appear anywhere',
+    })
+  })
+
+  afterAll(() => {
+    delete (Array.prototype as any).unwantedField
+  })
+
+  beforeEach(() => {
+    adapter = createEntityAdapter({
+      selectId: (book: BookModel) => book.id,
+      sortComparer: (a, b) => {
+        return a.title.localeCompare(b.title)
+      },
+    })
+
+    state = { ids: [], entities: {} }
+  })
+
+  it('should let you add one entity to the state', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    expect(withOneEntity).toEqual({
+      ids: [TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+      },
+    })
+  })
+
+  it('should let you add one entity to the state as an FSA', () => {
+    const bookAction = createAction<BookModel>('books/add')
+    const withOneEntity = adapter.addOne(state, bookAction(TheGreatGatsby))
+
+    expect(withOneEntity).toEqual({
+      ids: [TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+      },
+    })
+  })
+
+  it('should not change state if you attempt to re-add an entity', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const readded = adapter.addOne(withOneEntity, TheGreatGatsby)
+
+    expect(readded).toBe(withOneEntity)
+  })
+
+  it('should let you add many entities to the state', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const withManyMore = adapter.addMany(withOneEntity, [
+      AClockworkOrange,
+      AnimalFarm,
+    ])
+
+    expect(withManyMore).toEqual({
+      ids: [AClockworkOrange.id, AnimalFarm.id, TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+        [AClockworkOrange.id]: AClockworkOrange,
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should let you add many entities to the state from a dictionary', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const withManyMore = adapter.addMany(withOneEntity, {
+      [AClockworkOrange.id]: AClockworkOrange,
+      [AnimalFarm.id]: AnimalFarm,
+    })
+
+    expect(withManyMore).toEqual({
+      ids: [AClockworkOrange.id, AnimalFarm.id, TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+        [AClockworkOrange.id]: AClockworkOrange,
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should remove existing and add new ones on setAll', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const withAll = adapter.setAll(withOneEntity, [
+      AClockworkOrange,
+      AnimalFarm,
+    ])
+
+    expect(withAll).toEqual({
+      ids: [AClockworkOrange.id, AnimalFarm.id],
+      entities: {
+        [AClockworkOrange.id]: AClockworkOrange,
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should remove existing and add new ones on setAll when passing in a dictionary', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const withAll = adapter.setAll(withOneEntity, {
+      [AClockworkOrange.id]: AClockworkOrange,
+      [AnimalFarm.id]: AnimalFarm,
+    })
+
+    expect(withAll).toEqual({
+      ids: [AClockworkOrange.id, AnimalFarm.id],
+      entities: {
+        [AClockworkOrange.id]: AClockworkOrange,
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should remove existing and add new ones on addAll (deprecated)', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const withAll = adapter.setAll(withOneEntity, [
+      AClockworkOrange,
+      AnimalFarm,
+    ])
+
+    expect(withAll).toEqual({
+      ids: [AClockworkOrange.id, AnimalFarm.id],
+      entities: {
+        [AClockworkOrange.id]: AClockworkOrange,
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should let you add remove an entity from the state', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const withoutOne = adapter.removeOne(withOneEntity, TheGreatGatsby.id)
+
+    expect(withoutOne).toEqual({
+      ids: [],
+      entities: {},
+    })
+  })
+
+  it('should let you remove many entities by id from the state', () => {
+    const withAll = adapter.setAll(state, [
+      TheGreatGatsby,
+      AClockworkOrange,
+      AnimalFarm,
+    ])
+
+    const withoutMany = adapter.removeMany(withAll, [
+      TheGreatGatsby.id,
+      AClockworkOrange.id,
+    ])
+
+    expect(withoutMany).toEqual({
+      ids: [AnimalFarm.id],
+      entities: {
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should let you remove all entities from the state', () => {
+    const withAll = adapter.setAll(state, [
+      TheGreatGatsby,
+      AClockworkOrange,
+      AnimalFarm,
+    ])
+
+    const withoutAll = adapter.removeAll(withAll)
+
+    expect(withoutAll).toEqual({
+      ids: [],
+      entities: {},
+    })
+  })
+
+  it('should let you update an entity in the state', () => {
+    const withOne = adapter.addOne(state, TheGreatGatsby)
+    const changes = { title: 'A New Hope' }
+
+    const withUpdates = adapter.updateOne(withOne, {
+      id: TheGreatGatsby.id,
+      changes,
+    })
+
+    expect(withUpdates).toEqual({
+      ids: [TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: {
+          ...TheGreatGatsby,
+          ...changes,
+        },
+      },
+    })
+  })
+
+  it('should not change state if you attempt to update an entity that has not been added', () => {
+    const withUpdates = adapter.updateOne(state, {
+      id: TheGreatGatsby.id,
+      changes: { title: 'A New Title' },
+    })
+
+    expect(withUpdates).toBe(state)
+  })
+
+  it('Replaces an existing entity if you change the ID while updating', () => {
+    const a = { id: 'a', title: 'First' }
+    const b = { id: 'b', title: 'Second' }
+    const c = { id: 'c', title: 'Third' }
+    const d = { id: 'd', title: 'Fourth' }
+    const withAdded = adapter.setAll(state, [a, b, c])
+
+    const withUpdated = adapter.updateOne(withAdded, {
+      id: 'b',
+      changes: {
+        id: 'c',
+      },
+    })
+
+    const { ids, entities } = withUpdated
+
+    expect(ids).toEqual(['a', 'c'])
+    expect(entities.a).toBeTruthy()
+    expect(entities.b).not.toBeTruthy()
+    expect(entities.c).toBeTruthy()
+    expect(entities.c!.id).toBe('c')
+    expect(entities.c!.title).toBe('Second')
+  })
+
+  it('should not change ids state if you attempt to update an entity that does not impact sorting', () => {
+    const withAll = adapter.setAll(state, [
+      TheGreatGatsby,
+      AClockworkOrange,
+      AnimalFarm,
+    ])
+    const changes = { title: 'The Great Gatsby II' }
+
+    const withUpdates = adapter.updateOne(withAll, {
+      id: TheGreatGatsby.id,
+      changes,
+    })
+
+    expect(withAll.ids).toBe(withUpdates.ids)
+  })
+
+  it('should let you update the id of entity', () => {
+    const withOne = adapter.addOne(state, TheGreatGatsby)
+    const changes = { id: 'A New Id' }
+
+    const withUpdates = adapter.updateOne(withOne, {
+      id: TheGreatGatsby.id,
+      changes,
+    })
+
+    expect(withUpdates).toEqual({
+      ids: [changes.id],
+      entities: {
+        [changes.id]: {
+          ...TheGreatGatsby,
+          ...changes,
+        },
+      },
+    })
+  })
+
+  it('should resort correctly if same id but sort key update', () => {
+    const withAll = adapter.setAll(state, [
+      TheGreatGatsby,
+      AnimalFarm,
+      AClockworkOrange,
+    ])
+    const changes = { title: 'A New Hope' }
+
+    const withUpdates = adapter.updateOne(withAll, {
+      id: TheGreatGatsby.id,
+      changes,
+    })
+
+    expect(withUpdates).toEqual({
+      ids: [AClockworkOrange.id, TheGreatGatsby.id, AnimalFarm.id],
+      entities: {
+        [AClockworkOrange.id]: AClockworkOrange,
+        [TheGreatGatsby.id]: {
+          ...TheGreatGatsby,
+          ...changes,
+        },
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should resort correctly if the id and sort key update', () => {
+    const withOne = adapter.setAll(state, [
+      TheGreatGatsby,
+      AnimalFarm,
+      AClockworkOrange,
+    ])
+    const changes = { id: 'A New Id', title: 'A New Hope' }
+
+    const withUpdates = adapter.updateOne(withOne, {
+      id: TheGreatGatsby.id,
+      changes,
+    })
+
+    expect(withUpdates).toEqual({
+      ids: [AClockworkOrange.id, changes.id, AnimalFarm.id],
+      entities: {
+        [AClockworkOrange.id]: AClockworkOrange,
+        [changes.id]: {
+          ...TheGreatGatsby,
+          ...changes,
+        },
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should maintain a stable sorting order when updating items', () => {
+    interface OrderedEntity {
+      id: string
+      order: number
+      ts: number
+    }
+    const sortedItemsAdapter = createEntityAdapter<OrderedEntity>({
+      sortComparer: (a, b) => a.order - b.order,
+    })
+    const withInitialItems = sortedItemsAdapter.setAll(
+      sortedItemsAdapter.getInitialState(),
+      [
+        { id: 'C', order: 3, ts: 0 },
+        { id: 'A', order: 1, ts: 0 },
+        { id: 'F', order: 4, ts: 0 },
+        { id: 'B', order: 2, ts: 0 },
+        { id: 'D', order: 3, ts: 0 },
+        { id: 'E', order: 3, ts: 0 },
+      ],
+    )
+
+    expect(withInitialItems.ids).toEqual(['A', 'B', 'C', 'D', 'E', 'F'])
+
+    const updated = sortedItemsAdapter.updateOne(withInitialItems, {
+      id: 'C',
+      changes: { ts: 5 },
+    })
+
+    expect(updated.ids).toEqual(['A', 'B', 'C', 'D', 'E', 'F'])
+
+    const updated2 = sortedItemsAdapter.updateOne(withInitialItems, {
+      id: 'D',
+      changes: { ts: 6 },
+    })
+
+    expect(updated2.ids).toEqual(['A', 'B', 'C', 'D', 'E', 'F'])
+  })
+
+  it('should let you update many entities by id in the state', () => {
+    const firstChange = { title: 'Zack' }
+    const secondChange = { title: 'Aaron' }
+    const withMany = adapter.setAll(state, [TheGreatGatsby, AClockworkOrange])
+
+    const withUpdates = adapter.updateMany(withMany, [
+      { id: TheGreatGatsby.id, changes: firstChange },
+      { id: AClockworkOrange.id, changes: secondChange },
+    ])
+
+    expect(withUpdates).toEqual({
+      ids: [AClockworkOrange.id, TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: {
+          ...TheGreatGatsby,
+          ...firstChange,
+        },
+        [AClockworkOrange.id]: {
+          ...AClockworkOrange,
+          ...secondChange,
+        },
+      },
+    })
+  })
+
+  it('should let you add one entity to the state with upsert()', () => {
+    const withOneEntity = adapter.upsertOne(state, TheGreatGatsby)
+    expect(withOneEntity).toEqual({
+      ids: [TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+      },
+    })
+  })
+
+  it('should let you update an entity in the state with upsert()', () => {
+    const withOne = adapter.addOne(state, TheGreatGatsby)
+    const changes = { title: 'A New Hope' }
+
+    const withUpdates = adapter.upsertOne(withOne, {
+      ...TheGreatGatsby,
+      ...changes,
+    })
+    expect(withUpdates).toEqual({
+      ids: [TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: {
+          ...TheGreatGatsby,
+          ...changes,
+        },
+      },
+    })
+  })
+
+  it('should let you upsert many entities in the state', () => {
+    const firstChange = { title: 'Zack' }
+    const withMany = adapter.setAll(state, [TheGreatGatsby])
+
+    const withUpserts = adapter.upsertMany(withMany, [
+      { ...TheGreatGatsby, ...firstChange },
+      AClockworkOrange,
+    ])
+
+    expect(withUpserts).toEqual({
+      ids: [AClockworkOrange.id, TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: {
+          ...TheGreatGatsby,
+          ...firstChange,
+        },
+        [AClockworkOrange.id]: AClockworkOrange,
+      },
+    })
+  })
+
+  it('should do nothing when upsertMany is given an empty array', () => {
+    const withMany = adapter.setAll(state, [TheGreatGatsby])
+
+    const withUpserts = adapter.upsertMany(withMany, [])
+
+    expect(withUpserts).toEqual({
+      ids: [TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+      },
+    })
+  })
+
+  it('should throw when upsertMany is passed undefined or null', async () => {
+    const withMany = adapter.setAll(state, [TheGreatGatsby])
+
+    const fakeRequest = (response: null | undefined) =>
+      new Promise((resolve) => setTimeout(() => resolve(response), 50))
+
+    const undefinedBooks = (await fakeRequest(undefined)) as BookModel[]
+    expect(() => adapter.upsertMany(withMany, undefinedBooks)).toThrow()
+
+    const nullBooks = (await fakeRequest(null)) as BookModel[]
+    expect(() => adapter.upsertMany(withMany, nullBooks)).toThrow()
+  })
+
+  it('should let you upsert many entities in the state when passing in a dictionary', () => {
+    const firstChange = { title: 'Zack' }
+    const withMany = adapter.setAll(state, [TheGreatGatsby])
+
+    const withUpserts = adapter.upsertMany(withMany, {
+      [TheGreatGatsby.id]: { ...TheGreatGatsby, ...firstChange },
+      [AClockworkOrange.id]: AClockworkOrange,
+    })
+
+    expect(withUpserts).toEqual({
+      ids: [AClockworkOrange.id, TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: {
+          ...TheGreatGatsby,
+          ...firstChange,
+        },
+        [AClockworkOrange.id]: AClockworkOrange,
+      },
+    })
+  })
+
+  it('should let you add a new entity then apply changes to it', () => {
+    const firstChange = { author: TheHobbit.author }
+    const secondChange = { title: 'Zack' }
+    const withMany = adapter.setAll(state, [AClockworkOrange])
+
+    const withUpserts = adapter.upsertMany(withMany, [
+      {...TheGreatGatsby}, { ...TheGreatGatsby, ...firstChange }, {...TheGreatGatsby, ...secondChange}
+    ])
+
+    expect(withUpserts).toEqual({
+      ids: [AClockworkOrange.id, TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: {
+          ...TheGreatGatsby,
+          ...firstChange,
+          ...secondChange,
+        },
+        [AClockworkOrange.id]: AClockworkOrange,
+      },
+    })
+  })
+
+  it('should let you add a new entity in the state with setOne() and keep the sorting', () => {
+    const withMany = adapter.setAll(state, [AnimalFarm, TheHobbit])
+    const withOneMore = adapter.setOne(withMany, TheGreatGatsby)
+    expect(withOneMore).toEqual({
+      ids: [AnimalFarm.id, TheGreatGatsby.id, TheHobbit.id],
+      entities: {
+        [AnimalFarm.id]: AnimalFarm,
+        [TheHobbit.id]: TheHobbit,
+        [TheGreatGatsby.id]: TheGreatGatsby,
+      },
+    })
+  })
+
+  it('should let you replace an entity in the state with setOne()', () => {
+    let withOne = adapter.setOne(state, TheHobbit)
+    const changeWithoutAuthor = { id: TheHobbit.id, title: 'Silmarillion' }
+    withOne = adapter.setOne(withOne, changeWithoutAuthor)
+
+    expect(withOne).toEqual({
+      ids: [TheHobbit.id],
+      entities: {
+        [TheHobbit.id]: changeWithoutAuthor,
+      },
+    })
+  })
+
+  it('should do nothing when setMany is given an empty array', () => {
+    const withMany = adapter.setAll(state, [TheGreatGatsby])
+
+    const withUpserts = adapter.setMany(withMany, [])
+
+    expect(withUpserts).toEqual({
+      ids: [TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+      },
+    })
+  })
+
+  it('should let you set many entities in the state', () => {
+    const firstChange = { id: TheHobbit.id, title: 'Silmarillion' }
+    const withMany = adapter.setAll(state, [TheHobbit])
+
+    const withSetMany = adapter.setMany(withMany, [
+      firstChange,
+      AClockworkOrange,
+    ])
+
+    expect(withSetMany).toEqual({
+      ids: [AClockworkOrange.id, TheHobbit.id],
+      entities: {
+        [TheHobbit.id]: firstChange,
+        [AClockworkOrange.id]: AClockworkOrange,
+      },
+    })
+  })
+
+  it('should work consistent with Unsorted State Adapter adding duplicate ids', () => {
+    const unsortedAdaptor = createEntityAdapter({
+      selectId: (book: BookModel) => book.id
+    });
+
+    const firstEntry = {id: AClockworkOrange.id, author: TheHobbit.author }
+    const secondEntry = {id: AClockworkOrange.id, title: 'Zack' }
+    const withNothingSorted = adapter.setAll(state, []);
+    const withNothingUnsorted = unsortedAdaptor.setAll(state, []);
+    const withOneSorted = adapter.addMany(withNothingSorted, [
+      { ...AClockworkOrange, ...firstEntry }, {...AClockworkOrange, ...secondEntry}
+    ])
+    const withOneUnsorted = adapter.addMany(withNothingUnsorted, [
+      { ...AClockworkOrange, ...firstEntry }, {...AClockworkOrange, ...secondEntry}
+    ])
+
+    expect(withOneSorted).toEqual(withOneUnsorted);
+  })
+
+  it('should work consistent with Unsorted State Adapter adding duplicate ids', () => {
+    const unsortedAdaptor = createEntityAdapter({
+      selectId: (book: BookModel) => book.id
+    });
+
+    const firstEntry = {id: AClockworkOrange.id, author: TheHobbit.author }
+    const secondEntry = {id: AClockworkOrange.id, title: 'Zack' }
+    const withNothingSorted = adapter.setAll(state, [TheHobbit]);
+    const withNothingUnsorted = unsortedAdaptor.setAll(state, [TheHobbit]);
+    const withOneSorted = adapter.setMany(withNothingSorted, [
+      { ...AClockworkOrange, ...firstEntry, id: 'th' }, {...AClockworkOrange, ...secondEntry, id: 'th'}
+    ])
+    const withOneUnsorted = unsortedAdaptor.setMany(withNothingUnsorted, [
+      { ...AClockworkOrange, ...firstEntry, id: 'th' }, {...AClockworkOrange, ...secondEntry, id: 'th'}
+    ])
+
+    expect(withOneSorted).toEqual(withOneUnsorted);
+  })
+
+  it('should let you set many entities in the state when passing in a dictionary', () => {
+    const changeWithoutAuthor = { id: TheHobbit.id, title: 'Silmarillion' }
+    const withMany = adapter.setAll(state, [TheHobbit])
+
+    const withSetMany = adapter.setMany(withMany, {
+      [TheHobbit.id]: changeWithoutAuthor,
+      [AClockworkOrange.id]: AClockworkOrange,
+    })
+
+    expect(withSetMany).toEqual({
+      ids: [AClockworkOrange.id, TheHobbit.id],
+      entities: {
+        [TheHobbit.id]: changeWithoutAuthor,
+        [AClockworkOrange.id]: AClockworkOrange,
+      },
+    })
+  })
+
+  it("only returns one entry for that id in the id's array", () => {
+    const book1: BookModel = { id: 'a', title: 'First' }
+    const book2: BookModel = { id: 'b', title: 'Second' }
+    const initialState = adapter.getInitialState()
+    const withItems = adapter.addMany(initialState, [book1, book2])
+
+    expect(withItems.ids).toEqual(['a', 'b'])
+    const withUpdate = adapter.updateOne(withItems, {
+      id: 'a',
+      changes: { id: 'b' },
+    })
+
+    expect(withUpdate.ids).toEqual(['b'])
+    expect(withUpdate.entities['b']!.title).toBe(book1.title)
+  })
+
+  it('should minimize the amount of sorting work needed', () => {
+    const INITIAL_ITEMS = 10_000
+    const ADDED_ITEMS = 1_000
+
+    type Entity = { id: string; name: string; position: number }
+
+    let numSorts = 0
+
+    const adaptor = createEntityAdapter({
+      selectId: (entity: Entity) => entity.id,
+      sortComparer: (a, b) => {
+        numSorts++
+        if (a.position < b.position) return -1
+        else if (a.position > b.position) return 1
+        return 0
+      },
+    })
+
+    function generateItems(count: number) {
+      const items: readonly Entity[] = new Array(count)
+        .fill(undefined)
+        .map((x, i) => ({
+          name: `${i}`,
+          position: Math.random(),
+          id: nanoid(),
+        }))
+      return items
+    }
+
+    const entitySlice = createSlice({
+      name: 'entity',
+      initialState: adaptor.getInitialState(),
+      reducers: {
+        updateOne: adaptor.updateOne,
+        upsertOne: adaptor.upsertOne,
+        upsertMany: adaptor.upsertMany,
+        addMany: adaptor.addMany,
+      },
+    })
+
+    const store = configureStore({
+      reducer: {
+        entity: entitySlice.reducer,
+      },
+      middleware: (getDefaultMiddleware) => {
+        return getDefaultMiddleware({
+          serializableCheck: false,
+          immutableCheck: false,
+        })
+      },
+    })
+
+    numSorts = 0
+
+    const logComparisons = false
+
+    function measureComparisons(name: string, cb: () => void) {
+      numSorts = 0
+      const start = new Date().getTime()
+      cb()
+      const end = new Date().getTime()
+      const duration = end - start
+
+      if (logComparisons) {
+        console.log(
+          `${name}: sortComparer called ${numSorts.toLocaleString()} times in ${duration.toLocaleString()}ms`,
+        )
+      }
+    }
+
+    const initialItems = generateItems(INITIAL_ITEMS)
+
+    measureComparisons('Original Setup', () => {
+      store.dispatch(entitySlice.actions.upsertMany(initialItems))
+    })
+
+    expect(numSorts).toBeLessThan(INITIAL_ITEMS * 20)
+
+    measureComparisons('Insert One (random)', () => {
+      store.dispatch(
+        entitySlice.actions.upsertOne({
+          id: nanoid(),
+          position: Math.random(),
+          name: 'test',
+        }),
+      )
+    })
+
+    expect(numSorts).toBeLessThan(50)
+
+    measureComparisons('Insert One (middle)', () => {
+      store.dispatch(
+        entitySlice.actions.upsertOne({
+          id: nanoid(),
+          position: 0.5,
+          name: 'test',
+        }),
+      )
+    })
+
+    expect(numSorts).toBeLessThan(50)
+
+    measureComparisons('Insert One (end)', () => {
+      store.dispatch(
+        entitySlice.actions.upsertOne({
+          id: nanoid(),
+          position: 0.9998,
+          name: 'test',
+        }),
+      )
+    })
+
+    expect(numSorts).toBeLessThan(50)
+
+    const addedItems = generateItems(ADDED_ITEMS)
+    measureComparisons('Add Many', () => {
+      store.dispatch(entitySlice.actions.addMany(addedItems))
+    })
+
+    expect(numSorts).toBeLessThan(ADDED_ITEMS * 20)
+
+    // These numbers will vary because of the randomness, but generally
+    // with 10K items the old code had 200K+ sort calls, while the new code
+    // is around 13K sort calls.
+    expect(numSorts).toBeLessThan(20_000)
+
+    const { ids } = store.getState().entity
+    const middleItemId = ids[(ids.length / 2) | 0]
+
+    measureComparisons('Update One (end)', () => {
+      store.dispatch(
+        // Move this middle item near the end
+        entitySlice.actions.updateOne({
+          id: middleItemId,
+          changes: {
+            position: 0.99999,
+          },
+        }),
+      )
+    })
+
+    const SORTING_COUNT_BUFFER = 100
+
+    expect(numSorts).toBeLessThan(
+      INITIAL_ITEMS + ADDED_ITEMS + SORTING_COUNT_BUFFER,
+    )
+
+    measureComparisons('Update One (middle)', () => {
+      store.dispatch(
+        // Move this middle item near the end
+        entitySlice.actions.updateOne({
+          id: middleItemId,
+          changes: {
+            position: 0.42,
+          },
+        }),
+      )
+    })
+
+    expect(numSorts).toBeLessThan(
+      INITIAL_ITEMS + ADDED_ITEMS + SORTING_COUNT_BUFFER,
+    )
+
+    measureComparisons('Update One (replace)', () => {
+      store.dispatch(
+        // Move this middle item near the end
+        entitySlice.actions.updateOne({
+          id: middleItemId,
+          changes: {
+            id: nanoid(),
+            position: 0.98,
+          },
+        }),
+      )
+    })
+
+    expect(numSorts).toBeLessThan(
+      INITIAL_ITEMS + ADDED_ITEMS + SORTING_COUNT_BUFFER,
+    )
+
+    // The old code was around 120K, the new code is around 10K.
+    //expect(numSorts).toBeLessThan(25_000)
+  })
+
+  it('should not throw an Immer `current` error when `state.ids` is a plain array', () => {
+    const book1: BookModel = { id: 'a', title: 'First' }
+    const initialState = adapter.getInitialState()
+    const withItems = adapter.addMany(initialState, [book1])
+    const booksSlice = createSlice({
+      name: 'books',
+      initialState,
+      reducers: {
+        testCurrentBehavior(state, action: PayloadAction<BookModel>) {
+          // Will overwrite `state.ids` with a plain array
+          adapter.removeAll(state)
+
+          // will call `splitAddedUpdatedEntities` and call `current(state.ids)`
+          adapter.upsertMany(state, [book1])
+        },
+      },
+    })
+
+    booksSlice.reducer(
+      initialState,
+      booksSlice.actions.testCurrentBehavior(book1),
+    )
+  })
+
+  it('should not throw an Immer `current` error when the adapter is called twice', () => {
+    const book1: BookModel = { id: 'a', title: 'First' }
+    const book2: BookModel = { id: 'b', title: 'Second' }
+    const initialState = adapter.getInitialState()
+    const booksSlice = createSlice({
+      name: 'books',
+      initialState,
+      reducers: {
+        testCurrentBehavior(state, action: PayloadAction<BookModel>) {
+          // Will overwrite `state.ids` with a plain array
+          adapter.removeAll(state)
+
+          // will call `splitAddedUpdatedEntities` and call `current(state.ids)`
+          adapter.addOne(state, book1)
+          adapter.addOne(state, book2)
+        },
+      },
+    })
+
+    booksSlice.reducer(
+      initialState,
+      booksSlice.actions.testCurrentBehavior(book1),
+    )
+  })
+
+  describe('can be used mutably when wrapped in createNextState', () => {
+    test('removeAll', () => {
+      const withTwo = adapter.addMany(state, [TheGreatGatsby, AnimalFarm])
+      const result = createNextState(withTwo, (draft) => {
+        adapter.removeAll(draft)
+      })
+      expect(result).toEqual({
+        entities: {},
+        ids: [],
+      })
+    })
+
+    test('addOne', () => {
+      const result = createNextState(state, (draft) => {
+        adapter.addOne(draft, TheGreatGatsby)
+      })
+
+      expect(result).toEqual({
+        entities: {
+          tgg: {
+            id: 'tgg',
+            title: 'The Great Gatsby',
+          },
+        },
+        ids: ['tgg'],
+      })
+    })
+
+    test('addMany', () => {
+      const result = createNextState(state, (draft) => {
+        adapter.addMany(draft, [TheGreatGatsby, AnimalFarm])
+      })
+
+      expect(result).toEqual({
+        entities: {
+          af: {
+            id: 'af',
+            title: 'Animal Farm',
+          },
+          tgg: {
+            id: 'tgg',
+            title: 'The Great Gatsby',
+          },
+        },
+        ids: ['af', 'tgg'],
+      })
+    })
+
+    test('setAll', () => {
+      const result = createNextState(state, (draft) => {
+        adapter.setAll(draft, [TheGreatGatsby, AnimalFarm])
+      })
+
+      expect(result).toEqual({
+        entities: {
+          af: {
+            id: 'af',
+            title: 'Animal Farm',
+          },
+          tgg: {
+            id: 'tgg',
+            title: 'The Great Gatsby',
+          },
+        },
+        ids: ['af', 'tgg'],
+      })
+    })
+
+    test('updateOne', () => {
+      const withOne = adapter.addOne(state, TheGreatGatsby)
+      const changes = { title: 'A New Hope' }
+      const result = createNextState(withOne, (draft) => {
+        adapter.updateOne(draft, {
+          id: TheGreatGatsby.id,
+          changes,
+        })
+      })
+
+      expect(result).toEqual({
+        entities: {
+          tgg: {
+            id: 'tgg',
+            title: 'A New Hope',
+          },
+        },
+        ids: ['tgg'],
+      })
+    })
+
+    test('updateMany', () => {
+      const firstChange = { title: 'First Change' }
+      const secondChange = { title: 'Second Change' }
+      const thirdChange = { title: 'Third Change' }
+      const fourthChange = { author: 'Fourth Change' }
+      const withMany = adapter.setAll(state, [
+        TheGreatGatsby,
+        AClockworkOrange,
+        TheHobbit,
+      ])
+
+      const result = createNextState(withMany, (draft) => {
+        adapter.updateMany(draft, [
+          { id: TheHobbit.id, changes: firstChange },
+          { id: TheGreatGatsby.id, changes: secondChange },
+          { id: AClockworkOrange.id, changes: thirdChange },
+          { id: TheHobbit.id, changes: fourthChange },
+        ])
+      })
+
+      expect(result).toEqual({
+        entities: {
+          aco: {
+            id: 'aco',
+            title: 'Third Change',
+          },
+          tgg: {
+            id: 'tgg',
+            title: 'Second Change',
+          },
+          th: {
+            author: 'Fourth Change',
+            id: 'th',
+            title: 'First Change',
+          },
+        },
+        ids: ['th', 'tgg', 'aco'],
+      })
+    })
+
+    test('upsertOne (insert)', () => {
+      const result = createNextState(state, (draft) => {
+        adapter.upsertOne(draft, TheGreatGatsby)
+      })
+      expect(result).toEqual({
+        entities: {
+          tgg: {
+            id: 'tgg',
+            title: 'The Great Gatsby',
+          },
+        },
+        ids: ['tgg'],
+      })
+    })
+
+    test('upsertOne (update)', () => {
+      const withOne = adapter.upsertOne(state, TheGreatGatsby)
+      const result = createNextState(withOne, (draft) => {
+        adapter.upsertOne(draft, {
+          id: TheGreatGatsby.id,
+          title: 'A New Hope',
+        })
+      })
+      expect(result).toEqual({
+        entities: {
+          tgg: {
+            id: 'tgg',
+            title: 'A New Hope',
+          },
+        },
+        ids: ['tgg'],
+      })
+    })
+
+    test('upsertMany', () => {
+      const withOne = adapter.upsertOne(state, TheGreatGatsby)
+      const result = createNextState(withOne, (draft) => {
+        adapter.upsertMany(draft, [
+          {
+            id: TheGreatGatsby.id,
+            title: 'A New Hope',
+          },
+          AnimalFarm,
+        ])
+      })
+      expect(result).toEqual({
+        entities: {
+          af: {
+            id: 'af',
+            title: 'Animal Farm',
+          },
+          tgg: {
+            id: 'tgg',
+            title: 'A New Hope',
+          },
+        },
+        ids: ['tgg', 'af'],
+      })
+    })
+
+    test('setOne (insert)', () => {
+      const result = createNextState(state, (draft) => {
+        adapter.setOne(draft, TheGreatGatsby)
+      })
+      expect(result).toEqual({
+        entities: {
+          tgg: {
+            id: 'tgg',
+            title: 'The Great Gatsby',
+          },
+        },
+        ids: ['tgg'],
+      })
+    })
+
+    test('setOne (update)', () => {
+      const withOne = adapter.setOne(state, TheHobbit)
+      const result = createNextState(withOne, (draft) => {
+        adapter.setOne(draft, {
+          id: TheHobbit.id,
+          title: 'Silmarillion',
+        })
+      })
+      expect(result).toEqual({
+        entities: {
+          th: {
+            id: 'th',
+            title: 'Silmarillion',
+          },
+        },
+        ids: ['th'],
+      })
+    })
+
+    test('setMany', () => {
+      const withOne = adapter.setOne(state, TheHobbit)
+      const result = createNextState(withOne, (draft) => {
+        adapter.setMany(draft, [
+          {
+            id: TheHobbit.id,
+            title: 'Silmarillion',
+          },
+          AnimalFarm,
+        ])
+      })
+      expect(result).toEqual({
+        entities: {
+          af: {
+            id: 'af',
+            title: 'Animal Farm',
+          },
+          th: {
+            id: 'th',
+            title: 'Silmarillion',
+          },
+        },
+        ids: ['af', 'th'],
+      })
+    })
+
+    test('removeOne', () => {
+      const withTwo = adapter.addMany(state, [TheGreatGatsby, AnimalFarm])
+      const result = createNextState(withTwo, (draft) => {
+        adapter.removeOne(draft, TheGreatGatsby.id)
+      })
+      expect(result).toEqual({
+        entities: {
+          af: {
+            id: 'af',
+            title: 'Animal Farm',
+          },
+        },
+        ids: ['af'],
+      })
+    })
+
+    test('removeMany', () => {
+      const withThree = adapter.addMany(state, [
+        TheGreatGatsby,
+        AnimalFarm,
+        AClockworkOrange,
+      ])
+      const result = createNextState(withThree, (draft) => {
+        adapter.removeMany(draft, [TheGreatGatsby.id, AnimalFarm.id])
+      })
+      expect(result).toEqual({
+        entities: {
+          aco: {
+            id: 'aco',
+            title: 'A Clockwork Orange',
+          },
+        },
+        ids: ['aco'],
+      })
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/entities/tests/state_adapter.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/tests/state_adapter.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/tests/state_adapter.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,61 @@
+import type { EntityAdapter } from '../index'
+import { createEntityAdapter } from '../index'
+import type { PayloadAction } from '../../createAction'
+import { configureStore } from '../../configureStore'
+import { createSlice } from '../../createSlice'
+import type { BookModel } from './fixtures/book'
+
+describe('createStateOperator', () => {
+  let adapter: EntityAdapter<BookModel, string>
+
+  beforeEach(() => {
+    adapter = createEntityAdapter({
+      selectId: (book: BookModel) => book.id,
+    })
+  })
+  it('Correctly mutates a draft state when inside `createNextState', () => {
+    const booksSlice = createSlice({
+      name: 'books',
+      initialState: adapter.getInitialState(),
+      reducers: {
+        // We should be able to call an adapter method as a mutating helper in a larger reducer
+        addOne(state, action: PayloadAction<BookModel>) {
+          // Originally, having nested `produce` calls don't mutate `state` here as I would have expected.
+          // (note that `state` here is actually an Immer Draft<S>, from `createReducer`)
+          // One woarkound was to return the new plain result value instead
+          // See https://github.com/immerjs/immer/issues/533
+          // However, after tweaking `createStateOperator` to check if the argument is a draft,
+          // we can just treat the operator as strictly mutating, without returning a result,
+          // and the result should be correct.
+          const result = adapter.addOne(state, action)
+          expect(result.ids.length).toBe(1)
+          //Deliberately _don't_ return result
+        },
+        // We should also be able to pass them individually as case reducers
+        addAnother: adapter.addOne,
+      },
+    })
+
+    const { addOne, addAnother } = booksSlice.actions
+
+    const store = configureStore({
+      reducer: {
+        books: booksSlice.reducer,
+      },
+    })
+
+    const book1: BookModel = { id: 'a', title: 'First' }
+    store.dispatch(addOne(book1))
+
+    const state1 = store.getState()
+    expect(state1.books.ids.length).toBe(1)
+    expect(state1.books.entities['a']).toBe(book1)
+
+    const book2: BookModel = { id: 'b', title: 'Second' }
+    store.dispatch(addAnother(book2))
+
+    const state2 = store.getState()
+    expect(state2.books.ids.length).toBe(2)
+    expect(state2.books.entities['b']).toBe(book2)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/entities/tests/state_selectors.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/tests/state_selectors.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/tests/state_selectors.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,154 @@
+import { createDraftSafeSelectorCreator } from '../../createDraftSafeSelector'
+import type { EntityAdapter, EntityState } from '../index'
+import { createEntityAdapter } from '../index'
+import type { EntitySelectors } from '../models'
+import type { BookModel } from './fixtures/book'
+import { AClockworkOrange, AnimalFarm, TheGreatGatsby } from './fixtures/book'
+import type { Selector } from 'reselect'
+import { createSelector, weakMapMemoize } from 'reselect'
+import { vi } from 'vitest'
+
+describe('Entity State Selectors', () => {
+  describe('Composed Selectors', () => {
+    interface State {
+      books: EntityState<BookModel, string>
+    }
+
+    let adapter: EntityAdapter<BookModel, string>
+    let selectors: EntitySelectors<BookModel, State, string>
+    let state: State
+
+    beforeEach(() => {
+      adapter = createEntityAdapter({
+        selectId: (book: BookModel) => book.id,
+      })
+
+      state = {
+        books: adapter.setAll(adapter.getInitialState(), [
+          AClockworkOrange,
+          AnimalFarm,
+          TheGreatGatsby,
+        ]),
+      }
+
+      selectors = adapter.getSelectors((state: State) => state.books)
+    })
+
+    it('should create a selector for selecting the ids', () => {
+      const ids = selectors.selectIds(state)
+
+      expect(ids).toEqual(state.books.ids)
+    })
+
+    it('should create a selector for selecting the entities', () => {
+      const entities = selectors.selectEntities(state)
+
+      expect(entities).toEqual(state.books.entities)
+    })
+
+    it('should create a selector for selecting the list of models', () => {
+      const models = selectors.selectAll(state)
+
+      expect(models).toEqual([AClockworkOrange, AnimalFarm, TheGreatGatsby])
+    })
+
+    it('should create a selector for selecting the count of models', () => {
+      const total = selectors.selectTotal(state)
+
+      expect(total).toEqual(3)
+    })
+
+    it('should create a selector for selecting a single item by ID', () => {
+      const first = selectors.selectById(state, AClockworkOrange.id)
+      expect(first).toBe(AClockworkOrange)
+      const second = selectors.selectById(state, AnimalFarm.id)
+      expect(second).toBe(AnimalFarm)
+    })
+  })
+
+  describe('Uncomposed Selectors', () => {
+    type State = EntityState<BookModel, string>
+
+    let adapter: EntityAdapter<BookModel, string>
+    let selectors: EntitySelectors<
+      BookModel,
+      EntityState<BookModel, string>,
+      string
+    >
+    let state: State
+
+    beforeEach(() => {
+      adapter = createEntityAdapter({
+        selectId: (book: BookModel) => book.id,
+      })
+
+      state = adapter.setAll(adapter.getInitialState(), [
+        AClockworkOrange,
+        AnimalFarm,
+        TheGreatGatsby,
+      ])
+
+      selectors = adapter.getSelectors()
+    })
+
+    it('should create a selector for selecting the ids', () => {
+      const ids = selectors.selectIds(state)
+
+      expect(ids).toEqual(state.ids)
+    })
+
+    it('should create a selector for selecting the entities', () => {
+      const entities = selectors.selectEntities(state)
+
+      expect(entities).toEqual(state.entities)
+    })
+
+    it('should type single entity from Dictionary as entity type or undefined', () => {
+      expectType<
+        Selector<EntityState<BookModel, string>, BookModel | undefined>
+      >(createSelector(selectors.selectEntities, (entities) => entities[0]))
+    })
+
+    it('should create a selector for selecting the list of models', () => {
+      const models = selectors.selectAll(state)
+
+      expect(models).toEqual([AClockworkOrange, AnimalFarm, TheGreatGatsby])
+    })
+
+    it('should create a selector for selecting the count of models', () => {
+      const total = selectors.selectTotal(state)
+
+      expect(total).toEqual(3)
+    })
+
+    it('should create a selector for selecting a single item by ID', () => {
+      const first = selectors.selectById(state, AClockworkOrange.id)
+      expect(first).toBe(AClockworkOrange)
+      const second = selectors.selectById(state, AnimalFarm.id)
+      expect(second).toBe(AnimalFarm)
+    })
+  })
+  describe('custom createSelector instance', () => {
+    it('should use the custom createSelector function if provided', () => {
+      const memoizeSpy = vi.fn(
+        // test that we're allowed to pass memoizers with different options, as long as they're optional
+        <F extends (...args: any[]) => any>(fn: F, param?: boolean) => fn,
+      )
+      const createCustomSelector = createDraftSafeSelectorCreator(memoizeSpy)
+
+      const adapter = createEntityAdapter({
+        selectId: (book: BookModel) => book.id,
+      })
+
+      adapter.getSelectors(undefined, { createSelector: createCustomSelector })
+
+      expect(memoizeSpy).toHaveBeenCalled()
+
+      memoizeSpy.mockClear()
+    })
+  })
+})
+
+function expectType<T>(t: T) {
+  return t
+}
Index: node_modules/@reduxjs/toolkit/src/entities/tests/unsorted_state_adapter.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/tests/unsorted_state_adapter.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/tests/unsorted_state_adapter.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,759 @@
+import type { EntityAdapter, EntityState } from '../models'
+import { createEntityAdapter } from '../create_adapter'
+import type { BookModel } from './fixtures/book'
+import {
+  TheGreatGatsby,
+  AClockworkOrange,
+  AnimalFarm,
+  TheHobbit,
+} from './fixtures/book'
+import { createNextState } from '../..'
+
+describe('Unsorted State Adapter', () => {
+  let adapter: EntityAdapter<BookModel, string>
+  let state: EntityState<BookModel, string>
+
+  beforeAll(() => {
+    //eslint-disable-next-line
+    Object.defineProperty(Array.prototype, 'unwantedField', {
+      enumerable: true,
+      configurable: true,
+      value: 'This should not appear anywhere',
+    })
+  })
+
+  afterAll(() => {
+    delete (Array.prototype as any).unwantedField
+  })
+
+  beforeEach(() => {
+    adapter = createEntityAdapter({
+      selectId: (book: BookModel) => book.id,
+    })
+
+    state = { ids: [], entities: {} }
+  })
+
+  it('should let you add one entity to the state', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    expect(withOneEntity).toEqual({
+      ids: [TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+      },
+    })
+  })
+
+  it('should not change state if you attempt to re-add an entity', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const readded = adapter.addOne(withOneEntity, TheGreatGatsby)
+
+    expect(readded).toBe(withOneEntity)
+  })
+
+  it('should let you add many entities to the state', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const withManyMore = adapter.addMany(withOneEntity, [
+      AClockworkOrange,
+      AnimalFarm,
+    ])
+
+    expect(withManyMore).toEqual({
+      ids: [TheGreatGatsby.id, AClockworkOrange.id, AnimalFarm.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+        [AClockworkOrange.id]: AClockworkOrange,
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should let you add many entities to the state from a dictionary', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const withManyMore = adapter.addMany(withOneEntity, {
+      [AClockworkOrange.id]: AClockworkOrange,
+      [AnimalFarm.id]: AnimalFarm,
+    })
+
+    expect(withManyMore).toEqual({
+      ids: [TheGreatGatsby.id, AClockworkOrange.id, AnimalFarm.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+        [AClockworkOrange.id]: AClockworkOrange,
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should let you add the only first occurrence for duplicate ids', () => {
+    const firstEntry = {id: AClockworkOrange.id, author: TheHobbit.author }
+    const secondEntry = {id: AClockworkOrange.id, title: 'Zack' }
+    const withOne = adapter.setAll(state, [TheGreatGatsby])
+    const withMany = adapter.addMany(withOne, [
+      { ...AClockworkOrange, ...firstEntry }, {...AClockworkOrange, ...secondEntry}
+    ])
+
+    expect(withMany).toEqual({
+      ids: [TheGreatGatsby.id, AClockworkOrange.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+        [AClockworkOrange.id]: {
+          ...AClockworkOrange,
+          ...firstEntry,
+        },
+      },
+    })
+  })
+
+  it('should remove existing and add new ones on setAll', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const withAll = adapter.setAll(withOneEntity, [
+      AClockworkOrange,
+      AnimalFarm,
+    ])
+
+    expect(withAll).toEqual({
+      ids: [AClockworkOrange.id, AnimalFarm.id],
+      entities: {
+        [AClockworkOrange.id]: AClockworkOrange,
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should remove existing and add new ones on setAll when passing in a dictionary', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const withAll = adapter.setAll(withOneEntity, {
+      [AClockworkOrange.id]: AClockworkOrange,
+      [AnimalFarm.id]: AnimalFarm,
+    })
+
+    expect(withAll).toEqual({
+      ids: [AClockworkOrange.id, AnimalFarm.id],
+      entities: {
+        [AClockworkOrange.id]: AClockworkOrange,
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should let you add remove an entity from the state', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const withoutOne = adapter.removeOne(withOneEntity, TheGreatGatsby.id)
+
+    expect(withoutOne).toEqual({
+      ids: [],
+      entities: {},
+    })
+  })
+
+  it('should let you remove many entities by id from the state', () => {
+    const withAll = adapter.setAll(state, [
+      TheGreatGatsby,
+      AClockworkOrange,
+      AnimalFarm,
+    ])
+
+    const withoutMany = adapter.removeMany(withAll, [
+      TheGreatGatsby.id,
+      AClockworkOrange.id,
+    ])
+
+    expect(withoutMany).toEqual({
+      ids: [AnimalFarm.id],
+      entities: {
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should let you remove all entities from the state', () => {
+    const withAll = adapter.setAll(state, [
+      TheGreatGatsby,
+      AClockworkOrange,
+      AnimalFarm,
+    ])
+
+    const withoutAll = adapter.removeAll(withAll)
+
+    expect(withoutAll).toEqual({
+      ids: [],
+      entities: {},
+    })
+  })
+
+  it('should let you update an entity in the state', () => {
+    const withOne = adapter.addOne(state, TheGreatGatsby)
+    const changes = { title: 'A New Hope' }
+
+    const withUpdates = adapter.updateOne(withOne, {
+      id: TheGreatGatsby.id,
+      changes,
+    })
+
+    expect(withUpdates).toEqual({
+      ids: [TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: {
+          ...TheGreatGatsby,
+          ...changes,
+        },
+      },
+    })
+  })
+
+  it('should not change state if you attempt to update an entity that has not been added', () => {
+    const withUpdates = adapter.updateOne(state, {
+      id: TheGreatGatsby.id,
+      changes: { title: 'A New Title' },
+    })
+
+    expect(withUpdates).toBe(state)
+  })
+
+  it('should not change ids state if you attempt to update an entity that has already been added', () => {
+    const withOne = adapter.addOne(state, TheGreatGatsby)
+    const changes = { title: 'A New Hope' }
+
+    const withUpdates = adapter.updateOne(withOne, {
+      id: TheGreatGatsby.id,
+      changes,
+    })
+
+    expect(withOne.ids).toBe(withUpdates.ids)
+  })
+
+  it('should let you update the id of entity', () => {
+    const withOne = adapter.addOne(state, TheGreatGatsby)
+    const changes = { id: 'A New Id' }
+
+    const withUpdates = adapter.updateOne(withOne, {
+      id: TheGreatGatsby.id,
+      changes,
+    })
+
+    expect(withUpdates).toEqual({
+      ids: [changes.id],
+      entities: {
+        [changes.id]: {
+          ...TheGreatGatsby,
+          ...changes,
+        },
+      },
+    })
+  })
+
+  it('should let you update many entities by id in the state', () => {
+    const firstChange = { title: 'First Change' }
+    const secondChange = { title: 'Second Change' }
+    const withMany = adapter.setAll(state, [TheGreatGatsby, AClockworkOrange])
+
+    const withUpdates = adapter.updateMany(withMany, [
+      { id: TheGreatGatsby.id, changes: firstChange },
+      { id: AClockworkOrange.id, changes: secondChange },
+    ])
+
+    expect(withUpdates).toEqual({
+      ids: [TheGreatGatsby.id, AClockworkOrange.id],
+      entities: {
+        [TheGreatGatsby.id]: {
+          ...TheGreatGatsby,
+          ...firstChange,
+        },
+        [AClockworkOrange.id]: {
+          ...AClockworkOrange,
+          ...secondChange,
+        },
+      },
+    })
+  })
+
+  it("doesn't break when multiple renames of one item occur", () => {
+    const withA = adapter.addOne(state, { id: 'a', title: 'First' })
+
+    const withUpdates = adapter.updateMany(withA, [
+      { id: 'a', changes: { id: 'b' } },
+      { id: 'a', changes: { id: 'c' } },
+    ])
+
+    const { ids, entities } = withUpdates
+
+    /*
+      Original code failed with a mish-mash of values, like:
+      {
+        ids: [ 'c' ],
+        entities: { b: { id: 'b', title: 'First' }, c: { id: 'c' } }
+      }
+      We now expect that only 'c' will be left:
+      { 
+        ids: [ 'c' ], 
+        entities: { c: { id: 'c', title: 'First' } } 
+      }
+    */
+    expect(ids.length).toBe(1)
+    expect(ids).toEqual(['c'])
+    expect(entities.a).toBeFalsy()
+    expect(entities.b).toBeFalsy()
+    expect(entities.c).toBeTruthy()
+  })
+
+  it('should let you add one entity to the state with upsert()', () => {
+    const withOneEntity = adapter.upsertOne(state, TheGreatGatsby)
+    expect(withOneEntity).toEqual({
+      ids: [TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+      },
+    })
+  })
+
+  it('should let you update an entity in the state with upsert()', () => {
+    const withOne = adapter.addOne(state, TheGreatGatsby)
+    const changes = { title: 'A New Hope' }
+
+    const withUpdates = adapter.upsertOne(withOne, {
+      ...TheGreatGatsby,
+      ...changes,
+    })
+    expect(withUpdates).toEqual({
+      ids: [TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: {
+          ...TheGreatGatsby,
+          ...changes,
+        },
+      },
+    })
+  })
+
+  it('should let you upsert many entities in the state', () => {
+    const firstChange = { title: 'First Change' }
+    const withMany = adapter.setAll(state, [TheGreatGatsby])
+
+    const withUpserts = adapter.upsertMany(withMany, [
+      { ...TheGreatGatsby, ...firstChange },
+      AClockworkOrange,
+    ])
+
+    expect(withUpserts).toEqual({
+      ids: [TheGreatGatsby.id, AClockworkOrange.id],
+      entities: {
+        [TheGreatGatsby.id]: {
+          ...TheGreatGatsby,
+          ...firstChange,
+        },
+        [AClockworkOrange.id]: AClockworkOrange,
+      },
+    })
+  })
+
+  it('should let you upsert many entities in the state when passing in a dictionary', () => {
+    const firstChange = { title: 'Zack' }
+    const withMany = adapter.setAll(state, [TheGreatGatsby])
+
+    const withUpserts = adapter.upsertMany(withMany, {
+      [TheGreatGatsby.id]: { ...TheGreatGatsby, ...firstChange },
+      [AClockworkOrange.id]: AClockworkOrange,
+    })
+
+    expect(withUpserts).toEqual({
+      ids: [TheGreatGatsby.id, AClockworkOrange.id],
+      entities: {
+        [TheGreatGatsby.id]: {
+          ...TheGreatGatsby,
+          ...firstChange,
+        },
+        [AClockworkOrange.id]: AClockworkOrange,
+      },
+    })
+  })
+
+  it('should let you add a new entity then apply changes to it', () => {
+    const firstChange = { author: TheHobbit.author }
+    const secondChange = { title: 'Zack' }
+    const withMany = adapter.setAll(state, [TheGreatGatsby])
+
+    const withUpserts = adapter.upsertMany(withMany, [
+      {...AClockworkOrange}, { ...AClockworkOrange, ...firstChange }, {...AClockworkOrange, ...secondChange}
+    ])
+
+    expect(withUpserts).toEqual({
+      ids: [TheGreatGatsby.id, AClockworkOrange.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+        [AClockworkOrange.id]: {
+          ...AClockworkOrange,
+          ...firstChange,
+          ...secondChange,
+        },
+      },
+    })
+  })
+
+  it('should let you add a new entity in the state with setOne()', () => {
+    const withOne = adapter.setOne(state, TheGreatGatsby)
+    expect(withOne).toEqual({
+      ids: [TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+      },
+    })
+  })
+
+  it('should let you replace an entity in the state with setOne()', () => {
+    let withOne = adapter.setOne(state, TheHobbit)
+    const changeWithoutAuthor = { id: TheHobbit.id, title: 'Silmarillion' }
+    withOne = adapter.setOne(withOne, changeWithoutAuthor)
+
+    expect(withOne).toEqual({
+      ids: [TheHobbit.id],
+      entities: {
+        [TheHobbit.id]: changeWithoutAuthor,
+      },
+    })
+  })
+
+  it('should let you set many entities in the state', () => {
+    const changeWithoutAuthor = { id: TheHobbit.id, title: 'Silmarillion' }
+    const withMany = adapter.setAll(state, [TheHobbit])
+
+    const withSetMany = adapter.setMany(withMany, [
+      changeWithoutAuthor,
+      AClockworkOrange,
+    ])
+
+    expect(withSetMany).toEqual({
+      ids: [TheHobbit.id, AClockworkOrange.id],
+      entities: {
+        [TheHobbit.id]: changeWithoutAuthor,
+        [AClockworkOrange.id]: AClockworkOrange,
+      },
+    })
+  })
+
+  it('should let you set many entities in the state when passing in a dictionary', () => {
+    const changeWithoutAuthor = { id: TheHobbit.id, title: 'Silmarillion' }
+    const withMany = adapter.setAll(state, [TheHobbit])
+
+    const withSetMany = adapter.setMany(withMany, {
+      [TheHobbit.id]: changeWithoutAuthor,
+      [AClockworkOrange.id]: AClockworkOrange,
+    })
+
+    expect(withSetMany).toEqual({
+      ids: [TheHobbit.id, AClockworkOrange.id],
+      entities: {
+        [TheHobbit.id]: changeWithoutAuthor,
+        [AClockworkOrange.id]: AClockworkOrange,
+      },
+    })
+  })
+  it("only returns one entry for that id in the id's array", () => {
+    const book1: BookModel = { id: 'a', title: 'First' }
+    const book2: BookModel = { id: 'b', title: 'Second' }
+    const initialState = adapter.getInitialState()
+    const withItems = adapter.addMany(initialState, [book1, book2])
+
+    expect(withItems.ids).toEqual(['a', 'b'])
+    const withUpdate = adapter.updateOne(withItems, {
+      id: 'a',
+      changes: { id: 'b' },
+    })
+
+    expect(withUpdate.ids).toEqual(['b'])
+    expect(withUpdate.entities['b']!.title).toBe(book1.title)
+  })
+
+  describe('can be used mutably when wrapped in createNextState', () => {
+    test('removeAll', () => {
+      const withTwo = adapter.addMany(state, [TheGreatGatsby, AnimalFarm])
+      const result = createNextState(withTwo, (draft) => {
+        adapter.removeAll(draft)
+      })
+      expect(result).toEqual({
+        entities: {},
+        ids: [],
+      })
+    })
+
+    test('addOne', () => {
+      const result = createNextState(state, (draft) => {
+        adapter.addOne(draft, TheGreatGatsby)
+      })
+
+      expect(result).toEqual({
+        entities: {
+          tgg: {
+            id: 'tgg',
+            title: 'The Great Gatsby',
+          },
+        },
+        ids: ['tgg'],
+      })
+    })
+
+    test('addMany', () => {
+      const result = createNextState(state, (draft) => {
+        adapter.addMany(draft, [TheGreatGatsby, AnimalFarm])
+      })
+
+      expect(result).toEqual({
+        entities: {
+          af: {
+            id: 'af',
+            title: 'Animal Farm',
+          },
+          tgg: {
+            id: 'tgg',
+            title: 'The Great Gatsby',
+          },
+        },
+        ids: ['tgg', 'af'],
+      })
+    })
+
+    test('setAll', () => {
+      const result = createNextState(state, (draft) => {
+        adapter.setAll(draft, [TheGreatGatsby, AnimalFarm])
+      })
+
+      expect(result).toEqual({
+        entities: {
+          af: {
+            id: 'af',
+            title: 'Animal Farm',
+          },
+          tgg: {
+            id: 'tgg',
+            title: 'The Great Gatsby',
+          },
+        },
+        ids: ['tgg', 'af'],
+      })
+    })
+
+    test('updateOne', () => {
+      const withOne = adapter.addOne(state, TheGreatGatsby)
+      const changes = { title: 'A New Hope' }
+      const result = createNextState(withOne, (draft) => {
+        adapter.updateOne(draft, {
+          id: TheGreatGatsby.id,
+          changes,
+        })
+      })
+
+      expect(result).toEqual({
+        entities: {
+          tgg: {
+            id: 'tgg',
+            title: 'A New Hope',
+          },
+        },
+        ids: ['tgg'],
+      })
+    })
+
+    test('updateMany', () => {
+      const firstChange = { title: 'First Change' }
+      const secondChange = { title: 'Second Change' }
+      const thirdChange = { title: 'Third Change' }
+      const fourthChange = { author: 'Fourth Change' }
+      const withMany = adapter.setAll(state, [
+        TheGreatGatsby,
+        AClockworkOrange,
+        TheHobbit,
+      ])
+
+      const result = createNextState(withMany, (draft) => {
+        adapter.updateMany(draft, [
+          { id: TheHobbit.id, changes: firstChange },
+          { id: TheGreatGatsby.id, changes: secondChange },
+          { id: AClockworkOrange.id, changes: thirdChange },
+          { id: TheHobbit.id, changes: fourthChange },
+        ])
+      })
+
+      expect(result).toEqual({
+        entities: {
+          aco: {
+            id: 'aco',
+            title: 'Third Change',
+          },
+          tgg: {
+            id: 'tgg',
+            title: 'Second Change',
+          },
+          th: {
+            author: 'Fourth Change',
+            id: 'th',
+            title: 'First Change',
+          },
+        },
+        ids: ['tgg', 'aco', 'th'],
+      })
+    })
+
+    test('upsertOne (insert)', () => {
+      const result = createNextState(state, (draft) => {
+        adapter.upsertOne(draft, TheGreatGatsby)
+      })
+      expect(result).toEqual({
+        entities: {
+          tgg: {
+            id: 'tgg',
+            title: 'The Great Gatsby',
+          },
+        },
+        ids: ['tgg'],
+      })
+    })
+
+    test('upsertOne (update)', () => {
+      const withOne = adapter.upsertOne(state, TheGreatGatsby)
+      const result = createNextState(withOne, (draft) => {
+        adapter.upsertOne(draft, {
+          id: TheGreatGatsby.id,
+          title: 'A New Hope',
+        })
+      })
+      expect(result).toEqual({
+        entities: {
+          tgg: {
+            id: 'tgg',
+            title: 'A New Hope',
+          },
+        },
+        ids: ['tgg'],
+      })
+    })
+
+    test('upsertMany', () => {
+      const withOne = adapter.upsertOne(state, TheGreatGatsby)
+      const result = createNextState(withOne, (draft) => {
+        adapter.upsertMany(draft, [
+          {
+            id: TheGreatGatsby.id,
+            title: 'A New Hope',
+          },
+          AnimalFarm,
+        ])
+      })
+      expect(result).toEqual({
+        entities: {
+          af: {
+            id: 'af',
+            title: 'Animal Farm',
+          },
+          tgg: {
+            id: 'tgg',
+            title: 'A New Hope',
+          },
+        },
+        ids: ['tgg', 'af'],
+      })
+    })
+
+    test('setOne (insert)', () => {
+      const result = createNextState(state, (draft) => {
+        adapter.setOne(draft, TheGreatGatsby)
+      })
+      expect(result).toEqual({
+        entities: {
+          tgg: {
+            id: 'tgg',
+            title: 'The Great Gatsby',
+          },
+        },
+        ids: ['tgg'],
+      })
+    })
+
+    test('setOne (update)', () => {
+      const withOne = adapter.setOne(state, TheHobbit)
+      const result = createNextState(withOne, (draft) => {
+        adapter.setOne(draft, {
+          id: TheHobbit.id,
+          title: 'Silmarillion',
+        })
+      })
+      expect(result).toEqual({
+        entities: {
+          th: {
+            id: 'th',
+            title: 'Silmarillion',
+          },
+        },
+        ids: ['th'],
+      })
+    })
+
+    test('setMany', () => {
+      const withOne = adapter.setOne(state, TheHobbit)
+      const result = createNextState(withOne, (draft) => {
+        adapter.setMany(draft, [
+          {
+            id: TheHobbit.id,
+            title: 'Silmarillion',
+          },
+          AnimalFarm,
+        ])
+      })
+      expect(result).toEqual({
+        entities: {
+          af: {
+            id: 'af',
+            title: 'Animal Farm',
+          },
+          th: {
+            id: 'th',
+            title: 'Silmarillion',
+          },
+        },
+        ids: ['th', 'af'],
+      })
+    })
+
+    test('removeOne', () => {
+      const withTwo = adapter.addMany(state, [TheGreatGatsby, AnimalFarm])
+      const result = createNextState(withTwo, (draft) => {
+        adapter.removeOne(draft, TheGreatGatsby.id)
+      })
+      expect(result).toEqual({
+        entities: {
+          af: {
+            id: 'af',
+            title: 'Animal Farm',
+          },
+        },
+        ids: ['af'],
+      })
+    })
+
+    test('removeMany', () => {
+      const withThree = adapter.addMany(state, [
+        TheGreatGatsby,
+        AnimalFarm,
+        AClockworkOrange,
+      ])
+      const result = createNextState(withThree, (draft) => {
+        adapter.removeMany(draft, [TheGreatGatsby.id, AnimalFarm.id])
+      })
+      expect(result).toEqual({
+        entities: {
+          aco: {
+            id: 'aco',
+            title: 'A Clockwork Orange',
+          },
+        },
+        ids: ['aco'],
+      })
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/entities/tests/utils.spec.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/tests/utils.spec.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/tests/utils.spec.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,71 @@
+import { noop } from '@internal/listenerMiddleware/utils'
+import { AClockworkOrange } from './fixtures/book'
+
+describe('Entity utils', () => {
+  describe(`selectIdValue()`, () => {
+    const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(noop)
+
+    beforeEach(() => {
+      vi.resetModules() // this is important - it clears the cache
+      vi.stubEnv('NODE_ENV', 'development')
+    })
+
+    afterEach(() => {
+      vi.unstubAllEnvs()
+      vi.clearAllMocks()
+    })
+
+    afterAll(() => {
+      vi.restoreAllMocks()
+    })
+
+    it('should not warn when key does exist', async () => {
+      const { selectIdValue } = await import('../utils')
+
+      selectIdValue(AClockworkOrange, (book: any) => book.id)
+      expect(consoleWarnSpy).not.toHaveBeenCalled()
+    })
+
+    it('should warn when key does not exist in dev mode', async () => {
+      const { selectIdValue } = await import('../utils')
+
+      expect(process.env.NODE_ENV).toBe('development')
+
+      selectIdValue(AClockworkOrange, (book: any) => book.foo)
+
+      expect(consoleWarnSpy).toHaveBeenCalledOnce()
+    })
+
+    it('should warn when key is undefined in dev mode', async () => {
+      const { selectIdValue } = await import('../utils')
+
+      expect(process.env.NODE_ENV).toBe('development')
+
+      const undefinedAClockworkOrange = { ...AClockworkOrange, id: undefined }
+      selectIdValue(undefinedAClockworkOrange, (book: any) => book.id)
+
+      expect(consoleWarnSpy).toHaveBeenCalledOnce()
+    })
+
+    it('should not warn when key does not exist in prod mode', async () => {
+      vi.stubEnv('NODE_ENV', 'production')
+
+      const { selectIdValue } = await import('../utils')
+
+      selectIdValue(AClockworkOrange, (book: any) => book.foo)
+
+      expect(consoleWarnSpy).not.toHaveBeenCalled()
+    })
+
+    it('should not warn when key is undefined in prod mode', async () => {
+      vi.stubEnv('NODE_ENV', 'production')
+
+      const { selectIdValue } = await import('../utils')
+
+      const undefinedAClockworkOrange = { ...AClockworkOrange, id: undefined }
+      selectIdValue(undefinedAClockworkOrange, (book: any) => book.id)
+
+      expect(consoleWarnSpy).not.toHaveBeenCalled()
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/entities/unsorted_state_adapter.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/unsorted_state_adapter.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/unsorted_state_adapter.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,204 @@
+import type { Draft } from 'immer'
+import type {
+  EntityStateAdapter,
+  IdSelector,
+  Update,
+  EntityId,
+  DraftableEntityState,
+} from './models'
+import {
+  createStateOperator,
+  createSingleArgumentStateOperator,
+} from './state_adapter'
+import {
+  selectIdValue,
+  ensureEntitiesArray,
+  splitAddedUpdatedEntities,
+} from './utils'
+
+export function createUnsortedStateAdapter<T, Id extends EntityId>(
+  selectId: IdSelector<T, Id>,
+): EntityStateAdapter<T, Id> {
+  type R = DraftableEntityState<T, Id>
+
+  function addOneMutably(entity: T, state: R): void {
+    const key = selectIdValue(entity, selectId)
+
+    if (key in state.entities) {
+      return
+    }
+
+    state.ids.push(key as Id & Draft<Id>)
+    ;(state.entities as Record<Id, T>)[key] = entity
+  }
+
+  function addManyMutably(
+    newEntities: readonly T[] | Record<Id, T>,
+    state: R,
+  ): void {
+    newEntities = ensureEntitiesArray(newEntities)
+
+    for (const entity of newEntities) {
+      addOneMutably(entity, state)
+    }
+  }
+
+  function setOneMutably(entity: T, state: R): void {
+    const key = selectIdValue(entity, selectId)
+    if (!(key in state.entities)) {
+      state.ids.push(key as Id & Draft<Id>)
+    }
+    ;(state.entities as Record<Id, T>)[key] = entity
+  }
+
+  function setManyMutably(
+    newEntities: readonly T[] | Record<Id, T>,
+    state: R,
+  ): void {
+    newEntities = ensureEntitiesArray(newEntities)
+    for (const entity of newEntities) {
+      setOneMutably(entity, state)
+    }
+  }
+
+  function setAllMutably(
+    newEntities: readonly T[] | Record<Id, T>,
+    state: R,
+  ): void {
+    newEntities = ensureEntitiesArray(newEntities)
+
+    state.ids = []
+    state.entities = {} as Record<Id, T>
+
+    addManyMutably(newEntities, state)
+  }
+
+  function removeOneMutably(key: Id, state: R): void {
+    return removeManyMutably([key], state)
+  }
+
+  function removeManyMutably(keys: readonly Id[], state: R): void {
+    let didMutate = false
+
+    keys.forEach((key) => {
+      if (key in state.entities) {
+        delete (state.entities as Record<Id, T>)[key]
+        didMutate = true
+      }
+    })
+
+    if (didMutate) {
+      state.ids = (state.ids as Id[]).filter((id) => id in state.entities) as
+        | Id[]
+        | Draft<Id[]>
+    }
+  }
+
+  function removeAllMutably(state: R): void {
+    Object.assign(state, {
+      ids: [],
+      entities: {},
+    })
+  }
+
+  function takeNewKey(
+    keys: { [id: string]: Id },
+    update: Update<T, Id>,
+    state: R,
+  ): boolean {
+    const original: T | undefined = (state.entities as Record<Id, T>)[update.id]
+    if (original === undefined) {
+      return false
+    }
+    const updated: T = Object.assign({}, original, update.changes)
+    const newKey = selectIdValue(updated, selectId)
+    const hasNewKey = newKey !== update.id
+
+    if (hasNewKey) {
+      keys[update.id] = newKey
+      delete (state.entities as Record<Id, T>)[update.id]
+    }
+
+    ;(state.entities as Record<Id, T>)[newKey] = updated
+
+    return hasNewKey
+  }
+
+  function updateOneMutably(update: Update<T, Id>, state: R): void {
+    return updateManyMutably([update], state)
+  }
+
+  function updateManyMutably(
+    updates: ReadonlyArray<Update<T, Id>>,
+    state: R,
+  ): void {
+    const newKeys: { [id: string]: Id } = {}
+
+    const updatesPerEntity: { [id: string]: Update<T, Id> } = {}
+
+    updates.forEach((update) => {
+      // Only apply updates to entities that currently exist
+      if (update.id in state.entities) {
+        // If there are multiple updates to one entity, merge them together
+        updatesPerEntity[update.id] = {
+          id: update.id,
+          // Spreads ignore falsy values, so this works even if there isn't
+          // an existing update already at this key
+          changes: {
+            ...updatesPerEntity[update.id]?.changes,
+            ...update.changes,
+          },
+        }
+      }
+    })
+
+    updates = Object.values(updatesPerEntity)
+
+    const didMutateEntities = updates.length > 0
+
+    if (didMutateEntities) {
+      const didMutateIds =
+        updates.filter((update) => takeNewKey(newKeys, update, state)).length >
+        0
+
+      if (didMutateIds) {
+        state.ids = Object.values(state.entities).map((e) =>
+          selectIdValue(e as T, selectId),
+        )
+      }
+    }
+  }
+
+  function upsertOneMutably(entity: T, state: R): void {
+    return upsertManyMutably([entity], state)
+  }
+
+  function upsertManyMutably(
+    newEntities: readonly T[] | Record<Id, T>,
+    state: R,
+  ): void {
+    const [added, updated] = splitAddedUpdatedEntities<T, Id>(
+      newEntities,
+      selectId,
+      state,
+    )
+
+    addManyMutably(added, state)
+    updateManyMutably(updated, state)
+  }
+
+  return {
+    removeAll: createSingleArgumentStateOperator(removeAllMutably),
+    addOne: createStateOperator(addOneMutably),
+    addMany: createStateOperator(addManyMutably),
+    setOne: createStateOperator(setOneMutably),
+    setMany: createStateOperator(setManyMutably),
+    setAll: createStateOperator(setAllMutably),
+    updateOne: createStateOperator(updateOneMutably),
+    updateMany: createStateOperator(updateManyMutably),
+    upsertOne: createStateOperator(upsertOneMutably),
+    upsertMany: createStateOperator(upsertManyMutably),
+    removeOne: createStateOperator(removeOneMutably),
+    removeMany: createStateOperator(removeManyMutably),
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/entities/utils.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/utils.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/utils.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,68 @@
+import type { Draft } from 'immer'
+import { current, isDraft } from '../immerImports'
+import type {
+  DraftableEntityState,
+  EntityId,
+  IdSelector,
+  Update,
+} from './models'
+
+export function selectIdValue<T, Id extends EntityId>(
+  entity: T,
+  selectId: IdSelector<T, Id>,
+) {
+  const key = selectId(entity)
+
+  if (process.env.NODE_ENV !== 'production' && key === undefined) {
+    console.warn(
+      'The entity passed to the `selectId` implementation returned undefined.',
+      'You should probably provide your own `selectId` implementation.',
+      'The entity that was passed:',
+      entity,
+      'The `selectId` implementation:',
+      selectId.toString(),
+    )
+  }
+
+  return key
+}
+
+export function ensureEntitiesArray<T, Id extends EntityId>(
+  entities: readonly T[] | Record<Id, T>,
+): readonly T[] {
+  if (!Array.isArray(entities)) {
+    entities = Object.values(entities)
+  }
+
+  return entities
+}
+
+export function getCurrent<T>(value: T | Draft<T>): T {
+  return (isDraft(value) ? current(value) : value) as T
+}
+
+export function splitAddedUpdatedEntities<T, Id extends EntityId>(
+  newEntities: readonly T[] | Record<Id, T>,
+  selectId: IdSelector<T, Id>,
+  state: DraftableEntityState<T, Id>,
+): [T[], Update<T, Id>[], Id[]] {
+  newEntities = ensureEntitiesArray(newEntities)
+
+  const existingIdsArray = getCurrent(state.ids)
+  const existingIds = new Set<Id>(existingIdsArray)
+
+  const added: T[] = []
+  const addedIds = new Set<Id>([])
+  const updated: Update<T, Id>[] = []
+
+  for (const entity of newEntities) {
+    const id = selectIdValue(entity, selectId)
+    if (existingIds.has(id) || addedIds.has(id)) {
+      updated.push({ id, changes: entity })
+    } else {
+      addedIds.add(id)
+      added.push(entity)
+    }
+  }
+  return [added, updated, existingIdsArray]
+}
Index: node_modules/@reduxjs/toolkit/src/formatProdErrorMessage.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/formatProdErrorMessage.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/formatProdErrorMessage.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,13 @@
+/**
+ * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js
+ *
+ * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes
+ * during build.
+ * @param {number} code
+ */
+export function formatProdErrorMessage(code: number) {
+  return (
+    `Minified Redux Toolkit error #${code}; visit https://redux-toolkit.js.org/Errors?code=${code} for the full message or ` +
+    'use the non-minified dev environment for full errors. '
+  )
+}
Index: node_modules/@reduxjs/toolkit/src/getDefaultEnhancers.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/getDefaultEnhancers.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/getDefaultEnhancers.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,31 @@
+import type { StoreEnhancer } from 'redux'
+import type { AutoBatchOptions } from './autoBatchEnhancer'
+import { autoBatchEnhancer } from './autoBatchEnhancer'
+import { Tuple } from './utils'
+import type { Middlewares } from './configureStore'
+import type { ExtractDispatchExtensions } from './tsHelpers'
+
+type GetDefaultEnhancersOptions = {
+  autoBatch?: boolean | AutoBatchOptions
+}
+
+export type GetDefaultEnhancers<M extends Middlewares<any>> = (
+  options?: GetDefaultEnhancersOptions,
+) => Tuple<[StoreEnhancer<{ dispatch: ExtractDispatchExtensions<M> }>]>
+
+export const buildGetDefaultEnhancers = <M extends Middlewares<any>>(
+  middlewareEnhancer: StoreEnhancer<{ dispatch: ExtractDispatchExtensions<M> }>,
+): GetDefaultEnhancers<M> =>
+  function getDefaultEnhancers(options) {
+    const { autoBatch = true } = options ?? {}
+
+    let enhancerArray = new Tuple<StoreEnhancer[]>(middlewareEnhancer)
+    if (autoBatch) {
+      enhancerArray.push(
+        autoBatchEnhancer(
+          typeof autoBatch === 'object' ? autoBatch : undefined,
+        ),
+      )
+    }
+    return enhancerArray as any
+  }
Index: node_modules/@reduxjs/toolkit/src/getDefaultMiddleware.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/getDefaultMiddleware.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/getDefaultMiddleware.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,113 @@
+import type { Middleware, UnknownAction } from 'redux'
+import type { ThunkMiddleware } from 'redux-thunk'
+import { thunk as thunkMiddleware, withExtraArgument } from 'redux-thunk'
+import type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware'
+import { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware'
+import type { ImmutableStateInvariantMiddlewareOptions } from './immutableStateInvariantMiddleware'
+/* PROD_START_REMOVE_UMD */
+import { createImmutableStateInvariantMiddleware } from './immutableStateInvariantMiddleware'
+/* PROD_STOP_REMOVE_UMD */
+
+import type { SerializableStateInvariantMiddlewareOptions } from './serializableStateInvariantMiddleware'
+import { createSerializableStateInvariantMiddleware } from './serializableStateInvariantMiddleware'
+import type { ExcludeFromTuple } from './tsHelpers'
+import { Tuple } from './utils'
+
+function isBoolean(x: any): x is boolean {
+  return typeof x === 'boolean'
+}
+
+interface ThunkOptions<E = any> {
+  extraArgument: E
+}
+
+interface GetDefaultMiddlewareOptions {
+  thunk?: boolean | ThunkOptions
+  immutableCheck?: boolean | ImmutableStateInvariantMiddlewareOptions
+  serializableCheck?: boolean | SerializableStateInvariantMiddlewareOptions
+  actionCreatorCheck?: boolean | ActionCreatorInvariantMiddlewareOptions
+}
+
+export type ThunkMiddlewareFor<
+  S,
+  O extends GetDefaultMiddlewareOptions = {},
+> = O extends {
+  thunk: false
+}
+  ? never
+  : O extends { thunk: { extraArgument: infer E } }
+    ? ThunkMiddleware<S, UnknownAction, E>
+    : ThunkMiddleware<S, UnknownAction>
+
+export type GetDefaultMiddleware<S = any> = <
+  O extends GetDefaultMiddlewareOptions = {
+    thunk: true
+    immutableCheck: true
+    serializableCheck: true
+    actionCreatorCheck: true
+  },
+>(
+  options?: O,
+) => Tuple<ExcludeFromTuple<[ThunkMiddlewareFor<S, O>], never>>
+
+export const buildGetDefaultMiddleware = <S = any>(): GetDefaultMiddleware<S> =>
+  function getDefaultMiddleware(options) {
+    const {
+      thunk = true,
+      immutableCheck = true,
+      serializableCheck = true,
+      actionCreatorCheck = true,
+    } = options ?? {}
+
+    let middlewareArray = new Tuple<Middleware[]>()
+
+    if (thunk) {
+      if (isBoolean(thunk)) {
+        middlewareArray.push(thunkMiddleware)
+      } else {
+        middlewareArray.push(withExtraArgument(thunk.extraArgument))
+      }
+    }
+
+    if (process.env.NODE_ENV !== 'production') {
+      if (immutableCheck) {
+        /* PROD_START_REMOVE_UMD */
+        let immutableOptions: ImmutableStateInvariantMiddlewareOptions = {}
+
+        if (!isBoolean(immutableCheck)) {
+          immutableOptions = immutableCheck
+        }
+
+        middlewareArray.unshift(
+          createImmutableStateInvariantMiddleware(immutableOptions),
+        )
+        /* PROD_STOP_REMOVE_UMD */
+      }
+
+      if (serializableCheck) {
+        let serializableOptions: SerializableStateInvariantMiddlewareOptions =
+          {}
+
+        if (!isBoolean(serializableCheck)) {
+          serializableOptions = serializableCheck
+        }
+
+        middlewareArray.push(
+          createSerializableStateInvariantMiddleware(serializableOptions),
+        )
+      }
+      if (actionCreatorCheck) {
+        let actionCreatorOptions: ActionCreatorInvariantMiddlewareOptions = {}
+
+        if (!isBoolean(actionCreatorCheck)) {
+          actionCreatorOptions = actionCreatorCheck
+        }
+
+        middlewareArray.unshift(
+          createActionCreatorInvariantMiddleware(actionCreatorOptions),
+        )
+      }
+    }
+
+    return middlewareArray as any
+  }
Index: node_modules/@reduxjs/toolkit/src/immerImports.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/immerImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/immerImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,7 @@
+export {
+  current,
+  isDraft,
+  produce as createNextState,
+  isDraftable,
+  setUseStrictIteration,
+} from 'immer'
Index: node_modules/@reduxjs/toolkit/src/immutableStateInvariantMiddleware.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/immutableStateInvariantMiddleware.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/immutableStateInvariantMiddleware.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,274 @@
+import type { Middleware } from 'redux'
+import type { IgnorePaths } from './serializableStateInvariantMiddleware'
+import { getTimeMeasureUtils } from './utils'
+
+type EntryProcessor = (key: string, value: any) => any
+
+/**
+ * The default `isImmutable` function.
+ *
+ * @public
+ */
+export function isImmutableDefault(value: unknown): boolean {
+  return typeof value !== 'object' || value == null || Object.isFrozen(value)
+}
+
+export function trackForMutations(
+  isImmutable: IsImmutableFunc,
+  ignoredPaths: IgnorePaths | undefined,
+  obj: any,
+) {
+  const trackedProperties = trackProperties(isImmutable, ignoredPaths, obj)
+  return {
+    detectMutations() {
+      return detectMutations(isImmutable, ignoredPaths, trackedProperties, obj)
+    },
+  }
+}
+
+interface TrackedProperty {
+  value: any
+  children: Record<string, any>
+}
+
+function trackProperties(
+  isImmutable: IsImmutableFunc,
+  ignoredPaths: IgnorePaths = [],
+  obj: Record<string, any>,
+  path: string = '',
+  checkedObjects: Set<Record<string, any>> = new Set(),
+) {
+  const tracked: Partial<TrackedProperty> = { value: obj }
+
+  if (!isImmutable(obj) && !checkedObjects.has(obj)) {
+    checkedObjects.add(obj)
+    tracked.children = {}
+
+    const hasIgnoredPaths = ignoredPaths.length > 0
+
+    for (const key in obj) {
+      const nestedPath = path ? path + '.' + key : key
+
+      if (hasIgnoredPaths) {
+        const hasMatches = ignoredPaths.some((ignored) => {
+          if (ignored instanceof RegExp) {
+            return ignored.test(nestedPath)
+          }
+          return nestedPath === ignored
+        })
+        if (hasMatches) {
+          continue
+        }
+      }
+
+      tracked.children[key] = trackProperties(
+        isImmutable,
+        ignoredPaths,
+        obj[key],
+        nestedPath,
+      )
+    }
+  }
+  return tracked as TrackedProperty
+}
+
+function detectMutations(
+  isImmutable: IsImmutableFunc,
+  ignoredPaths: IgnorePaths = [],
+  trackedProperty: TrackedProperty,
+  obj: any,
+  sameParentRef: boolean = false,
+  path: string = '',
+): { wasMutated: boolean; path?: string } {
+  const prevObj = trackedProperty ? trackedProperty.value : undefined
+
+  const sameRef = prevObj === obj
+
+  if (sameParentRef && !sameRef && !Number.isNaN(obj)) {
+    return { wasMutated: true, path }
+  }
+
+  if (isImmutable(prevObj) || isImmutable(obj)) {
+    return { wasMutated: false }
+  }
+
+  // Gather all keys from prev (tracked) and after objs
+  const keysToDetect: Record<string, boolean> = {}
+  for (let key in trackedProperty.children) {
+    keysToDetect[key] = true
+  }
+  for (let key in obj) {
+    keysToDetect[key] = true
+  }
+
+  const hasIgnoredPaths = ignoredPaths.length > 0
+
+  for (let key in keysToDetect) {
+    const nestedPath = path ? path + '.' + key : key
+
+    if (hasIgnoredPaths) {
+      const hasMatches = ignoredPaths.some((ignored) => {
+        if (ignored instanceof RegExp) {
+          return ignored.test(nestedPath)
+        }
+        return nestedPath === ignored
+      })
+      if (hasMatches) {
+        continue
+      }
+    }
+
+    const result = detectMutations(
+      isImmutable,
+      ignoredPaths,
+      trackedProperty.children[key],
+      obj[key],
+      sameRef,
+      nestedPath,
+    )
+
+    if (result.wasMutated) {
+      return result
+    }
+  }
+  return { wasMutated: false }
+}
+
+type IsImmutableFunc = (value: any) => boolean
+
+/**
+ * Options for `createImmutableStateInvariantMiddleware()`.
+ *
+ * @public
+ */
+export interface ImmutableStateInvariantMiddlewareOptions {
+  /**
+    Callback function to check if a value is considered to be immutable.
+    This function is applied recursively to every value contained in the state.
+    The default implementation will return true for primitive types
+    (like numbers, strings, booleans, null and undefined).
+   */
+  isImmutable?: IsImmutableFunc
+  /**
+    An array of dot-separated path strings that match named nodes from
+    the root state to ignore when checking for immutability.
+    Defaults to undefined
+   */
+  ignoredPaths?: IgnorePaths
+  /** Print a warning if checks take longer than N ms. Default: 32ms */
+  warnAfter?: number
+}
+
+/**
+ * Creates a middleware that checks whether any state was mutated in between
+ * dispatches or during a dispatch. If any mutations are detected, an error is
+ * thrown.
+ *
+ * @param options Middleware options.
+ *
+ * @public
+ */
+export function createImmutableStateInvariantMiddleware(
+  options: ImmutableStateInvariantMiddlewareOptions = {},
+): Middleware {
+  if (process.env.NODE_ENV === 'production') {
+    return () => (next) => (action) => next(action)
+  } else {
+    function stringify(
+      obj: any,
+      serializer?: EntryProcessor,
+      indent?: string | number,
+      decycler?: EntryProcessor,
+    ): string {
+      return JSON.stringify(obj, getSerialize(serializer, decycler), indent)
+    }
+
+    function getSerialize(
+      serializer?: EntryProcessor,
+      decycler?: EntryProcessor,
+    ): EntryProcessor {
+      let stack: any[] = [],
+        keys: any[] = []
+
+      if (!decycler)
+        decycler = function (_: string, value: any) {
+          if (stack[0] === value) return '[Circular ~]'
+          return (
+            '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']'
+          )
+        }
+
+      return function (this: any, key: string, value: any) {
+        if (stack.length > 0) {
+          var thisPos = stack.indexOf(this)
+          ~thisPos ? stack.splice(thisPos + 1) : stack.push(this)
+          ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key)
+          if (~stack.indexOf(value)) value = decycler!.call(this, key, value)
+        } else stack.push(value)
+
+        return serializer == null ? value : serializer.call(this, key, value)
+      }
+    }
+
+    let {
+      isImmutable = isImmutableDefault,
+      ignoredPaths,
+      warnAfter = 32,
+    } = options
+
+    const track = trackForMutations.bind(null, isImmutable, ignoredPaths)
+
+    return ({ getState }) => {
+      let state = getState()
+      let tracker = track(state)
+
+      let result
+      return (next) => (action) => {
+        const measureUtils = getTimeMeasureUtils(
+          warnAfter,
+          'ImmutableStateInvariantMiddleware',
+        )
+
+        measureUtils.measureTime(() => {
+          state = getState()
+
+          result = tracker.detectMutations()
+          // Track before potentially not meeting the invariant
+          tracker = track(state)
+
+          if (result.wasMutated) {
+            throw new Error(
+              `A state mutation was detected between dispatches, in the path '${
+                result.path || ''
+              }'.  This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`,
+            )
+          }
+        })
+
+        const dispatchedAction = next(action)
+
+        measureUtils.measureTime(() => {
+          state = getState()
+
+          result = tracker.detectMutations()
+          // Track before potentially not meeting the invariant
+          tracker = track(state)
+
+          if (result.wasMutated) {
+            throw new Error(
+              `A state mutation was detected inside a dispatch, in the path: ${
+                result.path || ''
+              }. Take a look at the reducer(s) handling the action ${stringify(
+                action,
+              )}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`,
+            )
+          }
+        })
+
+        measureUtils.warnIfExceeded()
+
+        return dispatchedAction
+      }
+    }
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/index.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,213 @@
+// This must remain here so that the `mangleErrors.cjs` build script
+// does not have to import this into each source file it rewrites.
+import { formatProdErrorMessage } from './formatProdErrorMessage'
+
+export * from 'redux'
+export { freeze, original } from 'immer'
+export { createNextState, current, isDraft } from './immerImports'
+export type { Draft, WritableDraft } from 'immer'
+export { createSelector, lruMemoize } from 'reselect'
+export { createSelectorCreator, weakMapMemoize } from './reselectImports'
+export type { Selector, OutputSelector } from 'reselect'
+export {
+  createDraftSafeSelector,
+  createDraftSafeSelectorCreator,
+} from './createDraftSafeSelector'
+export type { ThunkAction, ThunkDispatch, ThunkMiddleware } from 'redux-thunk'
+
+export {
+  // js
+  configureStore,
+} from './configureStore'
+export type {
+  // types
+  ConfigureStoreOptions,
+  EnhancedStore,
+} from './configureStore'
+export type { DevToolsEnhancerOptions } from './devtoolsExtension'
+export {
+  // js
+  createAction,
+  isActionCreator,
+  isFSA as isFluxStandardAction,
+} from './createAction'
+export type {
+  // types
+  PayloadAction,
+  PayloadActionCreator,
+  ActionCreatorWithNonInferrablePayload,
+  ActionCreatorWithOptionalPayload,
+  ActionCreatorWithPayload,
+  ActionCreatorWithoutPayload,
+  ActionCreatorWithPreparedPayload,
+  PrepareAction,
+} from './createAction'
+export {
+  // js
+  createReducer,
+} from './createReducer'
+export type {
+  // types
+  Actions,
+  CaseReducer,
+  CaseReducers,
+} from './createReducer'
+export {
+  // js
+  createSlice,
+  buildCreateSlice,
+  asyncThunkCreator,
+  ReducerType,
+} from './createSlice'
+
+export type {
+  // types
+  CreateSliceOptions,
+  Slice,
+  CaseReducerActions,
+  SliceCaseReducers,
+  ValidateSliceCaseReducers,
+  CaseReducerWithPrepare,
+  ReducerCreators,
+  SliceSelectors,
+} from './createSlice'
+export type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware'
+export { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware'
+export {
+  // js
+  createImmutableStateInvariantMiddleware,
+  isImmutableDefault,
+} from './immutableStateInvariantMiddleware'
+export type {
+  // types
+  ImmutableStateInvariantMiddlewareOptions,
+} from './immutableStateInvariantMiddleware'
+export {
+  // js
+  createSerializableStateInvariantMiddleware,
+  findNonSerializableValue,
+  isPlain,
+} from './serializableStateInvariantMiddleware'
+export type {
+  // types
+  SerializableStateInvariantMiddlewareOptions,
+} from './serializableStateInvariantMiddleware'
+export type {
+  // types
+  ActionReducerMapBuilder,
+  AsyncThunkReducers,
+} from './mapBuilders'
+export { Tuple } from './utils'
+
+export { createEntityAdapter } from './entities/create_adapter'
+export type {
+  EntityState,
+  EntityAdapter,
+  EntitySelectors,
+  EntityStateAdapter,
+  EntityId,
+  Update,
+  IdSelector,
+  Comparer,
+} from './entities/models'
+
+export {
+  createAsyncThunk,
+  unwrapResult,
+  miniSerializeError,
+} from './createAsyncThunk'
+export type {
+  AsyncThunk,
+  AsyncThunkConfig,
+  AsyncThunkDispatchConfig,
+  AsyncThunkOptions,
+  AsyncThunkAction,
+  AsyncThunkPayloadCreatorReturnValue,
+  AsyncThunkPayloadCreator,
+  GetState,
+  GetThunkAPI,
+  SerializedError,
+  CreateAsyncThunkFunction,
+} from './createAsyncThunk'
+
+export {
+  // js
+  isAllOf,
+  isAnyOf,
+  isPending,
+  isRejected,
+  isFulfilled,
+  isAsyncThunkAction,
+  isRejectedWithValue,
+} from './matchers'
+export type {
+  // types
+  ActionMatchingAllOf,
+  ActionMatchingAnyOf,
+} from './matchers'
+
+export { nanoid } from './nanoid'
+
+export type {
+  ListenerEffect,
+  ListenerMiddleware,
+  ListenerEffectAPI,
+  ListenerMiddlewareInstance,
+  CreateListenerMiddlewareOptions,
+  ListenerErrorHandler,
+  TypedStartListening,
+  TypedAddListener,
+  TypedStopListening,
+  TypedRemoveListener,
+  UnsubscribeListener,
+  UnsubscribeListenerOptions,
+  ForkedTaskExecutor,
+  ForkedTask,
+  ForkedTaskAPI,
+  AsyncTaskExecutor,
+  SyncTaskExecutor,
+  TaskCancelled,
+  TaskRejected,
+  TaskResolved,
+  TaskResult,
+} from './listenerMiddleware/index'
+export type { AnyListenerPredicate } from './listenerMiddleware/types'
+
+export {
+  createListenerMiddleware,
+  addListener,
+  removeListener,
+  clearAllListeners,
+  TaskAbortError,
+} from './listenerMiddleware/index'
+
+export type {
+  AddMiddleware,
+  DynamicDispatch,
+  DynamicMiddlewareInstance,
+  GetDispatchType as GetDispatch,
+  MiddlewareApiConfig,
+} from './dynamicMiddleware/types'
+export { createDynamicMiddleware } from './dynamicMiddleware/index'
+
+export {
+  SHOULD_AUTOBATCH,
+  prepareAutoBatched,
+  autoBatchEnhancer,
+} from './autoBatchEnhancer'
+export type { AutoBatchOptions } from './autoBatchEnhancer'
+
+export { combineSlices } from './combineSlices'
+
+export type {
+  CombinedSliceReducer,
+  WithSlice,
+  WithSlicePreloadedState,
+} from './combineSlices'
+
+export type {
+  ExtractDispatchExtensions as TSHelpersExtractDispatchExtensions,
+  SafePromise,
+} from './tsHelpers'
+
+export { formatProdErrorMessage } from './formatProdErrorMessage'
Index: node_modules/@reduxjs/toolkit/src/listenerMiddleware/exceptions.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/listenerMiddleware/exceptions.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/listenerMiddleware/exceptions.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,20 @@
+import type { SerializedError } from '@reduxjs/toolkit'
+
+const task = 'task'
+const listener = 'listener'
+const completed = 'completed'
+const cancelled = 'cancelled'
+
+/* TaskAbortError error codes  */
+export const taskCancelled = `task-${cancelled}` as const
+export const taskCompleted = `task-${completed}` as const
+export const listenerCancelled = `${listener}-${cancelled}` as const
+export const listenerCompleted = `${listener}-${completed}` as const
+
+export class TaskAbortError implements SerializedError {
+  name = 'TaskAbortError'
+  message: string
+  constructor(public code: string | undefined) {
+    this.message = `${task} ${cancelled} (reason: ${code})`
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/listenerMiddleware/index.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/listenerMiddleware/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/listenerMiddleware/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,562 @@
+import type { Action, Dispatch, MiddlewareAPI, UnknownAction } from 'redux'
+import { isAction } from '../reduxImports'
+import type { ThunkDispatch } from 'redux-thunk'
+import { createAction } from '../createAction'
+import { nanoid } from '../nanoid'
+
+import {
+  TaskAbortError,
+  listenerCancelled,
+  listenerCompleted,
+  taskCancelled,
+  taskCompleted,
+} from './exceptions'
+import {
+  createDelay,
+  createPause,
+  raceWithSignal,
+  runTask,
+  validateActive,
+} from './task'
+import type {
+  AddListenerOverloads,
+  AnyListenerPredicate,
+  CreateListenerMiddlewareOptions,
+  FallbackAddListenerOptions,
+  ForkOptions,
+  ForkedTask,
+  ForkedTaskExecutor,
+  ListenerEntry,
+  ListenerErrorHandler,
+  ListenerErrorInfo,
+  ListenerMiddleware,
+  ListenerMiddlewareInstance,
+  TakePattern,
+  TaskResult,
+  TypedAddListener,
+  TypedCreateListenerEntry,
+  TypedRemoveListener,
+  UnsubscribeListener,
+  UnsubscribeListenerOptions,
+} from './types'
+import {
+  addAbortSignalListener,
+  assertFunction,
+  catchRejection,
+  noop,
+} from './utils'
+export { TaskAbortError } from './exceptions'
+export type {
+  AsyncTaskExecutor,
+  CreateListenerMiddlewareOptions,
+  ForkedTask,
+  ForkedTaskAPI,
+  ForkedTaskExecutor,
+  ListenerEffect,
+  ListenerEffectAPI,
+  ListenerErrorHandler,
+  ListenerMiddleware,
+  ListenerMiddlewareInstance,
+  SyncTaskExecutor,
+  TaskCancelled,
+  TaskRejected,
+  TaskResolved,
+  TaskResult,
+  TypedAddListener,
+  TypedRemoveListener,
+  TypedStartListening,
+  TypedStopListening,
+  UnsubscribeListener,
+  UnsubscribeListenerOptions,
+} from './types'
+
+//Overly-aggressive byte-shaving
+const { assign } = Object
+/**
+ * @internal
+ */
+const INTERNAL_NIL_TOKEN = {} as const
+
+const alm = 'listenerMiddleware' as const
+
+const createFork = (
+  parentAbortSignal: AbortSignal,
+  parentBlockingPromises: Promise<any>[],
+) => {
+  const linkControllers = (controller: AbortController) =>
+    addAbortSignalListener(parentAbortSignal, () =>
+      controller.abort(parentAbortSignal.reason),
+    )
+
+  return <T>(
+    taskExecutor: ForkedTaskExecutor<T>,
+    opts?: ForkOptions,
+  ): ForkedTask<T> => {
+    assertFunction(taskExecutor, 'taskExecutor')
+    const childAbortController = new AbortController()
+
+    linkControllers(childAbortController)
+
+    const result = runTask<T>(
+      async (): Promise<T> => {
+        validateActive(parentAbortSignal)
+        validateActive(childAbortController.signal)
+        const result = (await taskExecutor({
+          pause: createPause(childAbortController.signal),
+          delay: createDelay(childAbortController.signal),
+          signal: childAbortController.signal,
+        })) as T
+        validateActive(childAbortController.signal)
+        return result
+      },
+      () => childAbortController.abort(taskCompleted),
+    )
+
+    if (opts?.autoJoin) {
+      parentBlockingPromises.push(result.catch(noop))
+    }
+
+    return {
+      result: createPause<TaskResult<T>>(parentAbortSignal)(result),
+      cancel() {
+        childAbortController.abort(taskCancelled)
+      },
+    }
+  }
+}
+
+const createTakePattern = <S>(
+  startListening: AddListenerOverloads<UnsubscribeListener, S, Dispatch>,
+  signal: AbortSignal,
+): TakePattern<S> => {
+  /**
+   * A function that takes a ListenerPredicate and an optional timeout,
+   * and resolves when either the predicate returns `true` based on an action
+   * state combination or when the timeout expires.
+   * If the parent listener is canceled while waiting, this will throw a
+   * TaskAbortError.
+   */
+  const take = async <P extends AnyListenerPredicate<S>>(
+    predicate: P,
+    timeout: number | undefined,
+  ) => {
+    validateActive(signal)
+
+    // Placeholder unsubscribe function until the listener is added
+    let unsubscribe: UnsubscribeListener = () => {}
+
+    const tuplePromise = new Promise<[Action, S, S]>((resolve, reject) => {
+      // Inside the Promise, we synchronously add the listener.
+      let stopListening = startListening({
+        predicate: predicate as any,
+        effect: (action, listenerApi): void => {
+          // One-shot listener that cleans up as soon as the predicate passes
+          listenerApi.unsubscribe()
+          // Resolve the promise with the same arguments the predicate saw
+          resolve([
+            action,
+            listenerApi.getState(),
+            listenerApi.getOriginalState(),
+          ])
+        },
+      })
+      unsubscribe = () => {
+        stopListening()
+        reject()
+      }
+    })
+
+    const promises: (Promise<null> | Promise<[Action, S, S]>)[] = [tuplePromise]
+
+    if (timeout != null) {
+      promises.push(
+        new Promise<null>((resolve) => setTimeout(resolve, timeout, null)),
+      )
+    }
+
+    try {
+      const output = await raceWithSignal(signal, Promise.race(promises))
+
+      validateActive(signal)
+      return output
+    } finally {
+      // Always clean up the listener
+      unsubscribe()
+    }
+  }
+
+  return ((predicate: AnyListenerPredicate<S>, timeout: number | undefined) =>
+    catchRejection(take(predicate, timeout))) as TakePattern<S>
+}
+
+const getListenerEntryPropsFrom = (options: FallbackAddListenerOptions) => {
+  let { type, actionCreator, matcher, predicate, effect } = options
+
+  if (type) {
+    predicate = createAction(type).match
+  } else if (actionCreator) {
+    type = actionCreator!.type
+    predicate = actionCreator.match
+  } else if (matcher) {
+    predicate = matcher
+  } else if (predicate) {
+    // pass
+  } else {
+    throw new Error(
+      'Creating or removing a listener requires one of the known fields for matching an action',
+    )
+  }
+
+  assertFunction(effect, 'options.listener')
+
+  return { predicate, type, effect }
+}
+
+/** Accepts the possible options for creating a listener, and returns a formatted listener entry */
+export const createListenerEntry: TypedCreateListenerEntry<unknown> =
+  /* @__PURE__ */ assign(
+    (options: FallbackAddListenerOptions) => {
+      const { type, predicate, effect } = getListenerEntryPropsFrom(options)
+
+      const entry: ListenerEntry<unknown> = {
+        id: nanoid(),
+        effect,
+        type,
+        predicate,
+        pending: new Set<AbortController>(),
+        unsubscribe: () => {
+          throw new Error('Unsubscribe not initialized')
+        },
+      }
+
+      return entry
+    },
+    { withTypes: () => createListenerEntry },
+  ) as unknown as TypedCreateListenerEntry<unknown>
+
+const findListenerEntry = (
+  listenerMap: Map<string, ListenerEntry>,
+  options: FallbackAddListenerOptions,
+) => {
+  const { type, effect, predicate } = getListenerEntryPropsFrom(options)
+
+  return Array.from(listenerMap.values()).find((entry) => {
+    const matchPredicateOrType =
+      typeof type === 'string'
+        ? entry.type === type
+        : entry.predicate === predicate
+
+    return matchPredicateOrType && entry.effect === effect
+  })
+}
+
+const cancelActiveListeners = (
+  entry: ListenerEntry<unknown, Dispatch<UnknownAction>>,
+) => {
+  entry.pending.forEach((controller) => {
+    controller.abort(listenerCancelled)
+  })
+}
+
+const createClearListenerMiddleware = (
+  listenerMap: Map<string, ListenerEntry>,
+  executingListeners: Map<ListenerEntry, number>,
+) => {
+  return () => {
+    for (const listener of executingListeners.keys()) {
+      cancelActiveListeners(listener)
+    }
+    listenerMap.clear()
+  }
+}
+
+/**
+ * Safely reports errors to the `errorHandler` provided.
+ * Errors that occur inside `errorHandler` are notified in a new task.
+ * Inspired by [rxjs reportUnhandledError](https://github.com/ReactiveX/rxjs/blob/6fafcf53dc9e557439b25debaeadfd224b245a66/src/internal/util/reportUnhandledError.ts)
+ * @param errorHandler
+ * @param errorToNotify
+ */
+const safelyNotifyError = (
+  errorHandler: ListenerErrorHandler,
+  errorToNotify: unknown,
+  errorInfo: ListenerErrorInfo,
+): void => {
+  try {
+    errorHandler(errorToNotify, errorInfo)
+  } catch (errorHandlerError) {
+    // We cannot let an error raised here block the listener queue.
+    // The error raised here will be picked up by `window.onerror`, `process.on('error')` etc...
+    setTimeout(() => {
+      throw errorHandlerError
+    }, 0)
+  }
+}
+
+/**
+ * @public
+ */
+export const addListener = /* @__PURE__ */ assign(
+  /* @__PURE__ */ createAction(`${alm}/add`),
+  {
+    withTypes: () => addListener,
+  },
+) as unknown as TypedAddListener<unknown>
+
+/**
+ * @public
+ */
+export const clearAllListeners = /* @__PURE__ */ createAction(
+  `${alm}/removeAll`,
+)
+
+/**
+ * @public
+ */
+export const removeListener = /* @__PURE__ */ assign(
+  /* @__PURE__ */ createAction(`${alm}/remove`),
+  {
+    withTypes: () => removeListener,
+  },
+) as unknown as TypedRemoveListener<unknown>
+
+const defaultErrorHandler: ListenerErrorHandler = (...args: unknown[]) => {
+  console.error(`${alm}/error`, ...args)
+}
+
+/**
+ * @public
+ */
+export const createListenerMiddleware = <
+  StateType = unknown,
+  DispatchType extends Dispatch<Action> = ThunkDispatch<
+    StateType,
+    unknown,
+    UnknownAction
+  >,
+  ExtraArgument = unknown,
+>(
+  middlewareOptions: CreateListenerMiddlewareOptions<ExtraArgument> = {},
+) => {
+  const listenerMap = new Map<string, ListenerEntry>()
+
+  // Track listeners whose effect is currently executing so clearListeners can
+  // abort even listeners that have become unsubscribed while executing.
+  const executingListeners = new Map<ListenerEntry, number>()
+  const trackExecutingListener = (entry: ListenerEntry) => {
+    const count = executingListeners.get(entry) ?? 0
+    executingListeners.set(entry, count + 1)
+  }
+  const untrackExecutingListener = (entry: ListenerEntry) => {
+    const count = executingListeners.get(entry) ?? 1
+    if (count === 1) {
+      executingListeners.delete(entry)
+    } else {
+      executingListeners.set(entry, count - 1)
+    }
+  }
+
+  const { extra, onError = defaultErrorHandler } = middlewareOptions
+
+  assertFunction(onError, 'onError')
+
+  const insertEntry = (entry: ListenerEntry) => {
+    entry.unsubscribe = () => listenerMap.delete(entry.id)
+
+    listenerMap.set(entry.id, entry)
+    return (cancelOptions?: UnsubscribeListenerOptions) => {
+      entry.unsubscribe()
+      if (cancelOptions?.cancelActive) {
+        cancelActiveListeners(entry)
+      }
+    }
+  }
+
+  const startListening = ((options: FallbackAddListenerOptions) => {
+    const entry =
+      findListenerEntry(listenerMap, options) ??
+      createListenerEntry(options as any)
+
+    return insertEntry(entry)
+  }) as AddListenerOverloads<any>
+
+  assign(startListening, {
+    withTypes: () => startListening,
+  })
+
+  const stopListening = (
+    options: FallbackAddListenerOptions & UnsubscribeListenerOptions,
+  ): boolean => {
+    const entry = findListenerEntry(listenerMap, options)
+
+    if (entry) {
+      entry.unsubscribe()
+      if (options.cancelActive) {
+        cancelActiveListeners(entry)
+      }
+    }
+
+    return !!entry
+  }
+
+  assign(stopListening, {
+    withTypes: () => stopListening,
+  })
+
+  const notifyListener = async (
+    entry: ListenerEntry<unknown, Dispatch<UnknownAction>>,
+    action: unknown,
+    api: MiddlewareAPI,
+    getOriginalState: () => StateType,
+  ) => {
+    const internalTaskController = new AbortController()
+    const take = createTakePattern(
+      startListening as AddListenerOverloads<any>,
+      internalTaskController.signal,
+    )
+    const autoJoinPromises: Promise<any>[] = []
+
+    try {
+      entry.pending.add(internalTaskController)
+      trackExecutingListener(entry)
+      await Promise.resolve(
+        entry.effect(
+          action,
+          // Use assign() rather than ... to avoid extra helper functions added to bundle
+          assign({}, api, {
+            getOriginalState,
+            condition: (
+              predicate: AnyListenerPredicate<any>,
+              timeout?: number,
+            ) => take(predicate, timeout).then(Boolean),
+            take,
+            delay: createDelay(internalTaskController.signal),
+            pause: createPause<any>(internalTaskController.signal),
+            extra,
+            signal: internalTaskController.signal,
+            fork: createFork(internalTaskController.signal, autoJoinPromises),
+            unsubscribe: entry.unsubscribe,
+            subscribe: () => {
+              listenerMap.set(entry.id, entry)
+            },
+            cancelActiveListeners: () => {
+              entry.pending.forEach((controller, _, set) => {
+                if (controller !== internalTaskController) {
+                  controller.abort(listenerCancelled)
+                  set.delete(controller)
+                }
+              })
+            },
+            cancel: () => {
+              internalTaskController.abort(listenerCancelled)
+              entry.pending.delete(internalTaskController)
+            },
+            throwIfCancelled: () => {
+              validateActive(internalTaskController.signal)
+            },
+          }),
+        ),
+      )
+    } catch (listenerError) {
+      if (!(listenerError instanceof TaskAbortError)) {
+        safelyNotifyError(onError, listenerError, {
+          raisedBy: 'effect',
+        })
+      }
+    } finally {
+      await Promise.all(autoJoinPromises)
+
+      internalTaskController.abort(listenerCompleted) // Notify that the task has completed
+      untrackExecutingListener(entry)
+      entry.pending.delete(internalTaskController)
+    }
+  }
+
+  const clearListenerMiddleware = createClearListenerMiddleware(
+    listenerMap,
+    executingListeners,
+  )
+
+  const middleware: ListenerMiddleware<
+    StateType,
+    DispatchType,
+    ExtraArgument
+  > = (api) => (next) => (action) => {
+    if (!isAction(action)) {
+      // we only want to notify listeners for action objects
+      return next(action)
+    }
+
+    if (addListener.match(action)) {
+      return startListening(action.payload as any)
+    }
+
+    if (clearAllListeners.match(action)) {
+      clearListenerMiddleware()
+      return
+    }
+
+    if (removeListener.match(action)) {
+      return stopListening(action.payload)
+    }
+
+    // Need to get this state _before_ the reducer processes the action
+    let originalState: StateType | typeof INTERNAL_NIL_TOKEN = api.getState()
+
+    // `getOriginalState` can only be called synchronously.
+    // @see https://github.com/reduxjs/redux-toolkit/discussions/1648#discussioncomment-1932820
+    const getOriginalState = (): StateType => {
+      if (originalState === INTERNAL_NIL_TOKEN) {
+        throw new Error(
+          `${alm}: getOriginalState can only be called synchronously`,
+        )
+      }
+
+      return originalState as StateType
+    }
+
+    let result: unknown
+
+    try {
+      // Actually forward the action to the reducer before we handle listeners
+      result = next(action)
+
+      if (listenerMap.size > 0) {
+        const currentState = api.getState()
+        // Work around ESBuild+TS transpilation issue
+        const listenerEntries = Array.from(listenerMap.values())
+        for (const entry of listenerEntries) {
+          let runListener = false
+
+          try {
+            runListener = entry.predicate(action, currentState, originalState)
+          } catch (predicateError) {
+            runListener = false
+
+            safelyNotifyError(onError, predicateError, {
+              raisedBy: 'predicate',
+            })
+          }
+
+          if (!runListener) {
+            continue
+          }
+
+          notifyListener(entry, action, api, getOriginalState)
+        }
+      }
+    } finally {
+      // Remove `originalState` store from this scope.
+      originalState = INTERNAL_NIL_TOKEN
+    }
+
+    return result
+  }
+
+  return {
+    middleware,
+    startListening,
+    stopListening,
+    clearListeners: clearListenerMiddleware,
+  } as ListenerMiddlewareInstance<StateType, DispatchType, ExtraArgument>
+}
Index: node_modules/@reduxjs/toolkit/src/listenerMiddleware/task.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/listenerMiddleware/task.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/listenerMiddleware/task.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,100 @@
+import { TaskAbortError } from './exceptions'
+import type { TaskResult } from './types'
+import { addAbortSignalListener, catchRejection, noop } from './utils'
+
+/**
+ * Synchronously raises {@link TaskAbortError} if the task tied to the input `signal` has been cancelled.
+ * @param signal
+ * @see {TaskAbortError}
+ * @throws {TaskAbortError} if the task tied to the input `signal` has been cancelled.
+ */
+export const validateActive = (signal: AbortSignal): void => {
+  if (signal.aborted) {
+    throw new TaskAbortError(signal.reason)
+  }
+}
+
+/**
+ * Generates a race between the promise(s) and the AbortSignal
+ * This avoids `Promise.race()`-related memory leaks:
+ * https://github.com/nodejs/node/issues/17469#issuecomment-349794909
+ */
+export function raceWithSignal<T>(
+  signal: AbortSignal,
+  promise: Promise<T>,
+): Promise<T> {
+  let cleanup = noop
+  return new Promise<T>((resolve, reject) => {
+    const notifyRejection = () => reject(new TaskAbortError(signal.reason))
+
+    if (signal.aborted) {
+      notifyRejection()
+      return
+    }
+
+    cleanup = addAbortSignalListener(signal, notifyRejection)
+    promise.finally(() => cleanup()).then(resolve, reject)
+  }).finally(() => {
+    // after this point, replace `cleanup` with a noop, so there is no reference to `signal` any more
+    cleanup = noop
+  })
+}
+
+/**
+ * Runs a task and returns promise that resolves to {@link TaskResult}.
+ * Second argument is an optional `cleanUp` function that always runs after task.
+ *
+ * **Note:** `runTask` runs the executor in the next microtask.
+ * @returns
+ */
+export const runTask = async <T>(
+  task: () => Promise<T>,
+  cleanUp?: () => void,
+): Promise<TaskResult<T>> => {
+  try {
+    await Promise.resolve()
+    const value = await task()
+    return {
+      status: 'ok',
+      value,
+    }
+  } catch (error: any) {
+    return {
+      status: error instanceof TaskAbortError ? 'cancelled' : 'rejected',
+      error,
+    }
+  } finally {
+    cleanUp?.()
+  }
+}
+
+/**
+ * Given an input `AbortSignal` and a promise returns another promise that resolves
+ * as soon the input promise is provided or rejects as soon as
+ * `AbortSignal.abort` is `true`.
+ * @param signal
+ * @returns
+ */
+export const createPause = <T>(signal: AbortSignal) => {
+  return (promise: Promise<T>): Promise<T> => {
+    return catchRejection(
+      raceWithSignal(signal, promise).then((output) => {
+        validateActive(signal)
+        return output
+      }),
+    )
+  }
+}
+
+/**
+ * Given an input `AbortSignal` and `timeoutMs` returns a promise that resolves
+ * after `timeoutMs` or rejects as soon as `AbortSignal.abort` is `true`.
+ * @param signal
+ * @returns
+ */
+export const createDelay = (signal: AbortSignal) => {
+  const pause = createPause<void>(signal)
+  return (timeoutMs: number): Promise<void> => {
+    return pause(new Promise<void>((resolve) => setTimeout(resolve, timeoutMs)))
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/effectScenarios.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/effectScenarios.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/effectScenarios.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,498 @@
+import { noop } from '@internal/listenerMiddleware/utils'
+import type { PayloadAction } from '@reduxjs/toolkit'
+import {
+  configureStore,
+  createAction,
+  createListenerMiddleware,
+  createSlice,
+  isAnyOf,
+  TaskAbortError,
+} from '@reduxjs/toolkit'
+
+describe('Saga-style Effects Scenarios', () => {
+  interface CounterState {
+    value: number
+  }
+
+  const counterSlice = createSlice({
+    name: 'counter',
+    initialState: { value: 0 } as CounterState,
+    reducers: {
+      increment(state) {
+        state.value += 1
+      },
+      decrement(state) {
+        state.value -= 1
+      },
+      // Use the PayloadAction type to declare the contents of `action.payload`
+      incrementByAmount: (state, action: PayloadAction<number>) => {
+        state.value += action.payload
+      },
+    },
+  })
+  const { increment, decrement, incrementByAmount } = counterSlice.actions
+
+  let { reducer } = counterSlice
+  let listenerMiddleware = createListenerMiddleware<CounterState>()
+  let { middleware, startListening, stopListening } = listenerMiddleware
+
+  let store = configureStore({
+    reducer,
+    middleware: (gDM) => gDM().prepend(middleware),
+  })
+
+  const testAction1 = createAction<string>('testAction1')
+  type TestAction1 = ReturnType<typeof testAction1>
+  const testAction2 = createAction<string>('testAction2')
+  type TestAction2 = ReturnType<typeof testAction2>
+  const testAction3 = createAction<string>('testAction3')
+  type TestAction3 = ReturnType<typeof testAction3>
+
+  type RootState = ReturnType<typeof store.getState>
+
+  function delay(ms: number) {
+    return new Promise((resolve) => setTimeout(resolve, ms))
+  }
+
+  const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
+
+  beforeEach(() => {
+    listenerMiddleware = createListenerMiddleware<CounterState>()
+    middleware = listenerMiddleware.middleware
+    startListening = listenerMiddleware.startListening
+    store = configureStore({
+      reducer,
+      middleware: (gDM) => gDM().prepend(middleware),
+    })
+  })
+
+  afterEach(() => {
+    vi.clearAllMocks()
+  })
+
+  afterAll(() => {
+    vi.restoreAllMocks()
+  })
+
+  test('throttle', async () => {
+    // Ignore incoming actions for a given period of time while processing a task.
+    // Ref: https://redux-saga.js.org/docs/api#throttlems-pattern-saga-args
+
+    let listenerCalls = 0
+    let workPerformed = 0
+
+    startListening({
+      actionCreator: increment,
+      effect: (action, listenerApi) => {
+        listenerCalls++
+
+        // Stop listening until further notice
+        listenerApi.unsubscribe()
+
+        // Queue to start listening again after a delay
+        setTimeout(listenerApi.subscribe, 15)
+        workPerformed++
+      },
+    })
+
+    // Dispatch 3 actions. First triggers listener, next two ignored.
+    store.dispatch(increment())
+    store.dispatch(increment())
+    store.dispatch(increment())
+
+    // Wait for resubscription
+    await delay(25)
+
+    // Dispatch 2 more actions, first triggers, second ignored
+    store.dispatch(increment())
+    store.dispatch(increment())
+
+    // Wait for work
+    await delay(5)
+
+    // Both listener calls completed
+    expect(listenerCalls).toBe(2)
+    expect(workPerformed).toBe(2)
+  })
+
+  test('debounce / takeLatest', async () => {
+    // Repeated calls cancel previous ones, no work performed
+    // until the specified delay elapses without another call
+    // NOTE: This is also basically identical to `takeLatest`.
+    // Ref: https://redux-saga.js.org/docs/api#debouncems-pattern-saga-args
+    // Ref: https://redux-saga.js.org/docs/api#takelatestpattern-saga-args
+
+    let listenerCalls = 0
+    let workPerformed = 0
+
+    startListening({
+      actionCreator: increment,
+      effect: async (action, listenerApi) => {
+        listenerCalls++
+
+        // Cancel any in-progress instances of this listener
+        listenerApi.cancelActiveListeners()
+
+        // Delay before starting actual work
+        await listenerApi.delay(15)
+
+        workPerformed++
+      },
+    })
+
+    // First action, listener 1 starts, nothing to cancel
+    store.dispatch(increment())
+    // Second action, listener 2 starts, cancels 1
+    store.dispatch(increment())
+    // Third action, listener 3 starts, cancels 2
+    store.dispatch(increment())
+
+    // 3 listeners started, third is still paused
+    expect(listenerCalls).toBe(3)
+    expect(workPerformed).toBe(0)
+
+    await delay(25)
+
+    // All 3 started
+    expect(listenerCalls).toBe(3)
+    // First two canceled, `delay()` threw JobCanceled and skipped work.
+    // Third actually completed.
+    expect(workPerformed).toBe(1)
+  })
+
+  test('takeEvery', async () => {
+    // Runs the listener on every action match
+    // Ref: https://redux-saga.js.org/docs/api#takeeverypattern-saga-args
+
+    // NOTE: This is already the default behavior - nothing special here!
+
+    let listenerCalls = 0
+    startListening({
+      actionCreator: increment,
+      effect: (action, listenerApi) => {
+        listenerCalls++
+      },
+    })
+
+    store.dispatch(increment())
+    expect(listenerCalls).toBe(1)
+
+    store.dispatch(increment())
+    expect(listenerCalls).toBe(2)
+  })
+
+  test('takeLeading', async () => {
+    // Starts listener on first action, ignores others until task completes
+    // Ref: https://redux-saga.js.org/docs/api#takeleadingpattern-saga-args
+
+    let listenerCalls = 0
+    let workPerformed = 0
+
+    startListening({
+      actionCreator: increment,
+      effect: async (action, listenerApi) => {
+        listenerCalls++
+
+        // Stop listening for this action
+        listenerApi.unsubscribe()
+
+        // Pretend we're doing expensive work
+        await listenerApi.delay(25)
+
+        workPerformed++
+
+        // Re-enable the listener
+        listenerApi.subscribe()
+      },
+    })
+
+    // First action starts the listener, which unsubscribes
+    store.dispatch(increment())
+    // Second action is ignored
+    store.dispatch(increment())
+
+    // One instance in progress, but not complete
+    expect(listenerCalls).toBe(1)
+    expect(workPerformed).toBe(0)
+
+    await delay(5)
+
+    // In-progress listener not done yet
+    store.dispatch(increment())
+
+    // No changes in status
+    expect(listenerCalls).toBe(1)
+    expect(workPerformed).toBe(0)
+
+    await delay(50)
+
+    // Work finished, should have resubscribed
+    expect(workPerformed).toBe(1)
+
+    // Listener is re-subscribed, will trigger again
+    store.dispatch(increment())
+
+    expect(listenerCalls).toBe(2)
+    expect(workPerformed).toBe(1)
+
+    await delay(50)
+
+    expect(workPerformed).toBe(2)
+  })
+
+  test('fork + join', async () => {
+    // fork starts a child job, join waits for the child to complete and return a value
+    // Ref: https://redux-saga.js.org/docs/api#forkfn-args
+    // Ref: https://redux-saga.js.org/docs/api#jointask
+
+    let childResult = 0
+
+    startListening({
+      actionCreator: increment,
+      effect: async (_, listenerApi) => {
+        const childOutput = 42
+        // Spawn a child job and start it immediately
+        const result = await listenerApi.fork(async () => {
+          // Artificially wait a bit inside the child
+          await listenerApi.delay(5)
+          // Complete the child by returning an Outcome-wrapped value
+          return childOutput
+        }).result
+
+        // Unwrap the child result in the listener
+        if (result.status === 'ok') {
+          childResult = result.value
+        }
+      },
+    })
+
+    store.dispatch(increment())
+
+    await delay(10)
+    expect(childResult).toBe(42)
+  })
+
+  test('fork + cancel', async () => {
+    // fork starts a child job, cancel will raise an exception if the
+    // child is paused in the middle of an effect
+    // Ref: https://redux-saga.js.org/docs/api#forkfn-args
+
+    let childResult = 0
+    let listenerCompleted = false
+
+    startListening({
+      actionCreator: increment,
+      effect: async (action, listenerApi) => {
+        // Spawn a child job and start it immediately
+        const forkedTask = listenerApi.fork(async () => {
+          // Artificially wait a bit inside the child
+          await listenerApi.delay(15)
+          // Complete the child by returning an Outcome-wrapped value
+          childResult = 42
+
+          return 0
+        })
+
+        await listenerApi.delay(5)
+        forkedTask.cancel()
+        listenerCompleted = true
+      },
+    })
+
+    // Starts listener, which starts child
+    store.dispatch(increment())
+
+    // Wait for child to have maybe completed
+    await delay(20)
+
+    // Listener finished, but the child was canceled and threw an exception, so it never finished
+    expect(listenerCompleted).toBe(true)
+    expect(childResult).toBe(0)
+  })
+
+  test('canceled', async () => {
+    // canceled allows checking if the current task was canceled
+    // Ref: https://redux-saga.js.org/docs/api#cancelled
+
+    let canceledAndCaught = false
+    let canceledCheck = false
+
+    startListening({
+      matcher: isAnyOf(increment, decrement, incrementByAmount),
+      effect: async (action, listenerApi) => {
+        if (increment.match(action)) {
+          // Have this branch wait around to be canceled by the other
+          try {
+            await listenerApi.delay(10)
+          } catch (err) {
+            // Can check cancelation based on the exception and its reason
+            if (err instanceof TaskAbortError) {
+              canceledAndCaught = true
+            }
+          }
+        } else if (incrementByAmount.match(action)) {
+          // do a non-cancelation-aware wait
+          await delay(15)
+          if (listenerApi.signal.aborted) {
+            canceledCheck = true
+          }
+        } else if (decrement.match(action)) {
+          listenerApi.cancelActiveListeners()
+        }
+      },
+    })
+
+    // Start first branch
+    store.dispatch(increment())
+    // Cancel first listener
+    store.dispatch(decrement())
+
+    // Have to wait for the delay to resolve
+    // TODO Can we make ``Job.delay()` be a race?
+    await delay(15)
+
+    expect(canceledAndCaught).toBe(true)
+
+    // Start second branch
+    store.dispatch(incrementByAmount(42))
+    // Cancel second listener, although it won't know about that until later
+    store.dispatch(decrement())
+
+    expect(canceledCheck).toBe(false)
+
+    await delay(20)
+
+    expect(canceledCheck).toBe(true)
+  })
+
+  test('long-running listener with immediate unsubscribe is cancelable', async () => {
+    let runCount = 0
+    let abortCount = 0
+
+    startListening({
+      actionCreator: increment,
+      effect: async (action, listenerApi) => {
+        runCount++
+
+        // Stop listening for this action
+        listenerApi.unsubscribe()
+
+        try {
+          // Wait indefinitely
+          await listenerApi.condition(() => false)
+        } catch (err) {
+          if (err instanceof TaskAbortError) {
+            abortCount++
+          }
+        }
+      },
+    })
+
+    // First action starts the listener, which unsubscribes
+    store.dispatch(increment())
+    expect(runCount).toBe(1)
+
+    // Verify that the first action unsubscribed the listener
+    store.dispatch(increment())
+    expect(runCount).toBe(1)
+
+    // Now call clearListeners, which should abort the running effect, even
+    // though the listener is no longer subscribed
+    listenerMiddleware.clearListeners()
+    await delay(0)
+
+    expect(abortCount).toBe(1)
+  })
+
+  test('long-running listener with unsubscribe race is cancelable', async () => {
+    let runCount = 0
+    let abortCount = 0
+
+    startListening({
+      actionCreator: increment,
+      effect: async (action, listenerApi) => {
+        runCount++
+
+        if (runCount === 2) {
+          // On the second run, stop listening for this action
+          listenerApi.unsubscribe()
+          return
+        }
+
+        try {
+          // Wait indefinitely
+          await listenerApi.condition(() => false)
+        } catch (err) {
+          if (err instanceof TaskAbortError) {
+            abortCount++
+          }
+        }
+      },
+    })
+
+    // First action starts the hanging effect
+    store.dispatch(increment())
+    expect(runCount).toBe(1)
+
+    // Second action starts the fast effect, which unsubscribes
+    store.dispatch(increment())
+    expect(runCount).toBe(2)
+
+    // Third action should be a noop
+    store.dispatch(increment())
+    expect(runCount).toBe(2)
+
+    // The hanging effect should still be hanging
+    expect(abortCount).toBe(0)
+
+    // Now call clearListeners, which should abort the hanging effect, even
+    // though the listener is no longer subscribed
+    listenerMiddleware.clearListeners()
+    await delay(0)
+
+    expect(abortCount).toBe(1)
+  })
+
+  test('long-running listener with immediate unsubscribe and forked child is cancelable', async () => {
+    let outerAborted = false
+    let innerAborted = false
+
+    startListening({
+      actionCreator: increment,
+      effect: async (action, listenerApi) => {
+        // Stop listening for this action
+        listenerApi.unsubscribe()
+
+        const pollingTask = listenerApi.fork(async (forkApi) => {
+          try {
+            // Cancellation-aware indefinite pause
+            await forkApi.pause(new Promise(() => {}))
+          } catch (err) {
+            if (err instanceof TaskAbortError) {
+              innerAborted = true
+            }
+          }
+        })
+
+        try {
+          // Wait indefinitely
+          await listenerApi.condition(() => false)
+          pollingTask.cancel()
+        } catch (err) {
+          if (err instanceof TaskAbortError) {
+            outerAborted = true
+          }
+        }
+      },
+    })
+
+    store.dispatch(increment())
+    await delay(0)
+
+    listenerMiddleware.clearListeners()
+    await delay(0)
+
+    expect(outerAborted).toBe(true)
+    expect(innerAborted).toBe(true)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/fork.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/fork.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/fork.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,524 @@
+import type { EnhancedStore } from '@reduxjs/toolkit'
+import { configureStore, createSlice, createAction } from '@reduxjs/toolkit'
+
+import type { PayloadAction } from '@reduxjs/toolkit'
+import type { ForkedTaskExecutor, TaskResult } from '../types'
+import { createListenerMiddleware, TaskAbortError } from '../index'
+import {
+  listenerCancelled,
+  listenerCompleted,
+  taskCancelled,
+  taskCompleted,
+} from '../exceptions'
+
+function delay(ms: number) {
+  return new Promise((resolve) => setTimeout(resolve, ms))
+}
+
+// @see https://deno.land/std@0.95.0/async/deferred.ts (MIT)
+export interface Deferred<T> extends Promise<T> {
+  resolve(value?: T | PromiseLike<T>): void
+  reject(reason?: any): void
+}
+
+/** Creates a Promise with the `reject` and `resolve` functions
+ * placed as methods on the promise object itself. It allows you to do:
+ *
+ *     const p = deferred<number>();
+ *     // ...
+ *     p.resolve(42);
+ */
+export function deferred<T>(): Deferred<T> {
+  let methods
+  const promise = new Promise<T>((resolve, reject): void => {
+    methods = { resolve, reject }
+  })
+  return Object.assign(promise, methods) as Deferred<T>
+}
+
+interface CounterSlice {
+  value: number
+}
+
+describe('fork', () => {
+  const counterSlice = createSlice({
+    name: 'counter',
+    initialState: { value: 0 } as CounterSlice,
+    reducers: {
+      increment(state) {
+        state.value += 1
+      },
+      decrement(state) {
+        state.value -= 1
+      },
+      // Use the PayloadAction type to declare the contents of `action.payload`
+      incrementByAmount: (state, action: PayloadAction<number>) => {
+        state.value += action.payload
+      },
+    },
+  })
+  const { increment, decrement, incrementByAmount } = counterSlice.actions
+  let listenerMiddleware = createListenerMiddleware()
+  let { middleware, startListening, stopListening } = listenerMiddleware
+  let store = configureStore({
+    reducer: counterSlice.reducer,
+    middleware: (gDM) => gDM().prepend(middleware),
+  })
+
+  beforeEach(() => {
+    listenerMiddleware = createListenerMiddleware()
+    middleware = listenerMiddleware.middleware
+    startListening = listenerMiddleware.startListening
+    stopListening = listenerMiddleware.stopListening
+    store = configureStore({
+      reducer: counterSlice.reducer,
+      middleware: (gDM) => gDM().prepend(middleware),
+    })
+  })
+
+  it('runs executors in the next microtask', async () => {
+    let hasRunSyncExector = false
+    let hasRunAsyncExecutor = false
+
+    startListening({
+      actionCreator: increment,
+      effect: async (_, listenerApi) => {
+        listenerApi.fork(() => {
+          hasRunSyncExector = true
+        })
+
+        listenerApi.fork(async () => {
+          hasRunAsyncExecutor = true
+        })
+      },
+    })
+
+    store.dispatch(increment())
+
+    expect(hasRunSyncExector).toBe(false)
+    expect(hasRunAsyncExecutor).toBe(false)
+
+    await Promise.resolve()
+
+    expect(hasRunSyncExector).toBe(true)
+    expect(hasRunAsyncExecutor).toBe(true)
+  })
+
+  test('forkedTask.result rejects TaskAbortError if listener is cancelled', async () => {
+    const deferredForkedTaskError = deferred()
+
+    startListening({
+      actionCreator: increment,
+      async effect(_, listenerApi) {
+        listenerApi.cancelActiveListeners()
+        listenerApi
+          .fork(async () => {
+            await delay(10)
+
+            throw new Error('unreachable code')
+          })
+          .result.then(
+            deferredForkedTaskError.resolve,
+            deferredForkedTaskError.resolve,
+          )
+      },
+    })
+
+    store.dispatch(increment())
+    store.dispatch(increment())
+
+    expect(await deferredForkedTaskError).toEqual(
+      new TaskAbortError(listenerCancelled),
+    )
+  })
+
+  it('synchronously throws TypeError error if the provided executor is not a function', () => {
+    const invalidExecutors = [null, {}, undefined, 1]
+
+    startListening({
+      predicate: () => true,
+      effect: async (_, listenerApi) => {
+        invalidExecutors.forEach((invalidExecutor) => {
+          let caughtError
+          try {
+            listenerApi.fork(invalidExecutor as any)
+          } catch (err) {
+            caughtError = err
+          }
+
+          expect(caughtError).toBeInstanceOf(TypeError)
+        })
+      },
+    })
+
+    store.dispatch(increment())
+
+    expect.assertions(invalidExecutors.length)
+  })
+
+  it('does not run an executor if the task is synchronously cancelled', async () => {
+    const storeStateAfter = deferred()
+
+    startListening({
+      actionCreator: increment,
+      effect: async (action, listenerApi) => {
+        const forkedTask = listenerApi.fork(() => {
+          listenerApi.dispatch(decrement())
+          listenerApi.dispatch(decrement())
+          listenerApi.dispatch(decrement())
+        })
+        forkedTask.cancel()
+
+        const result = await forkedTask.result
+        storeStateAfter.resolve(listenerApi.getState())
+      },
+    })
+    store.dispatch(increment())
+
+    await expect(storeStateAfter).resolves.toEqual({ value: 1 })
+  })
+
+  it.each<{
+    desc: string
+    executor: ForkedTaskExecutor<any>
+    cancelAfterMs?: number
+    expected: TaskResult<any>
+  }>([
+    {
+      desc: 'sync exec - success',
+      executor: () => 42,
+      expected: { status: 'ok', value: 42 },
+    },
+    {
+      desc: 'sync exec - error',
+      executor: () => {
+        throw new Error('2020')
+      },
+      expected: { status: 'rejected', error: new Error('2020') },
+    },
+    {
+      desc: 'sync exec - sync cancel',
+      executor: () => 42,
+      cancelAfterMs: -1,
+      expected: {
+        status: 'cancelled',
+        error: new TaskAbortError(taskCancelled),
+      },
+    },
+    {
+      desc: 'sync exec - async cancel',
+      executor: () => 42,
+      cancelAfterMs: 0,
+      expected: { status: 'ok', value: 42 },
+    },
+    {
+      desc: 'async exec - async cancel',
+      executor: async (forkApi) => {
+        await forkApi.delay(100)
+        throw new Error('2020')
+      },
+      cancelAfterMs: 10,
+      expected: {
+        status: 'cancelled',
+        error: new TaskAbortError(taskCancelled),
+      },
+    },
+    {
+      desc: 'async exec - success',
+      executor: async () => {
+        await delay(20)
+        return Promise.resolve(21)
+      },
+      expected: { status: 'ok', value: 21 },
+    },
+    {
+      desc: 'async exec - error',
+      executor: async () => {
+        await Promise.resolve()
+        throw new Error('2020')
+      },
+      expected: { status: 'rejected', error: new Error('2020') },
+    },
+    {
+      desc: 'async exec - success with forkApi.pause',
+      executor: async (forkApi) => {
+        return forkApi.pause(Promise.resolve(2))
+      },
+      expected: { status: 'ok', value: 2 },
+    },
+    {
+      desc: 'async exec - error with forkApi.pause',
+      executor: async (forkApi) => {
+        return forkApi.pause(Promise.reject(22))
+      },
+      expected: { status: 'rejected', error: 22 },
+    },
+    {
+      desc: 'async exec - success with forkApi.delay',
+      executor: async (forkApi) => {
+        await forkApi.delay(10)
+        return 5
+      },
+      expected: { status: 'ok', value: 5 },
+    },
+  ])('$desc', async ({ executor, expected, cancelAfterMs }) => {
+    let deferredResult = deferred()
+    let forkedTask: any = {}
+
+    startListening({
+      predicate: () => true,
+      effect: async (_, listenerApi) => {
+        forkedTask = listenerApi.fork(executor)
+
+        deferredResult.resolve(await forkedTask.result)
+      },
+    })
+
+    store.dispatch({ type: '' })
+
+    if (typeof cancelAfterMs === 'number') {
+      if (cancelAfterMs < 0) {
+        forkedTask.cancel()
+      } else {
+        await delay(cancelAfterMs)
+        forkedTask.cancel()
+      }
+    }
+
+    const result = await deferredResult
+
+    expect(result).toEqual(expected)
+  })
+
+  describe('forkAPI', () => {
+    test('forkApi.delay rejects as soon as the task is cancelled', async () => {
+      let deferredResult = deferred()
+
+      startListening({
+        actionCreator: increment,
+        effect: async (_, listenerApi) => {
+          const forkedTask = listenerApi.fork(async (forkApi) => {
+            await forkApi.delay(100)
+
+            return 4
+          })
+
+          await listenerApi.delay(10)
+          forkedTask.cancel()
+          deferredResult.resolve(await forkedTask.result)
+        },
+      })
+
+      store.dispatch(increment())
+
+      expect(await deferredResult).toEqual({
+        status: 'cancelled',
+        error: new TaskAbortError(taskCancelled),
+      })
+    })
+
+    test('forkApi.delay rejects as soon as the parent listener is cancelled', async () => {
+      let deferredResult = deferred()
+
+      startListening({
+        actionCreator: increment,
+        effect: async (_, listenerApi) => {
+          listenerApi.cancelActiveListeners()
+          await listenerApi.fork(async (forkApi) => {
+            await forkApi
+              .delay(100)
+              .then(deferredResult.resolve, deferredResult.resolve)
+
+            return 4
+          }).result
+
+          deferredResult.resolve(new Error('unreachable'))
+        },
+      })
+
+      store.dispatch(increment())
+
+      await Promise.resolve()
+
+      store.dispatch(increment())
+      expect(await deferredResult).toEqual(
+        new TaskAbortError(listenerCancelled),
+      )
+    })
+
+    it.each([
+      {
+        autoJoin: true,
+        expectedAbortReason: taskCompleted,
+        cancelListener: false,
+      },
+      {
+        autoJoin: false,
+        expectedAbortReason: listenerCompleted,
+        cancelListener: false,
+      },
+      {
+        autoJoin: true,
+        expectedAbortReason: listenerCancelled,
+        cancelListener: true,
+      },
+      {
+        autoJoin: false,
+        expectedAbortReason: listenerCancelled,
+        cancelListener: true,
+      },
+    ])(
+      'signal is $expectedAbortReason when autoJoin: $autoJoin, cancelListener: $cancelListener',
+      async ({ autoJoin, cancelListener, expectedAbortReason }) => {
+        let deferredResult = deferred()
+
+        const unsubscribe = startListening({
+          actionCreator: increment,
+          async effect(_, listenerApi) {
+            listenerApi.fork(
+              async (forkApi) => {
+                forkApi.signal.addEventListener('abort', () => {
+                  deferredResult.resolve(forkApi.signal.reason)
+                })
+
+                await forkApi.delay(10)
+              },
+              { autoJoin },
+            )
+          },
+        })
+
+        store.dispatch(increment())
+
+        // let task start
+        await Promise.resolve()
+
+        if (cancelListener) unsubscribe({ cancelActive: true })
+
+        expect(await deferredResult).toBe(expectedAbortReason)
+      },
+    )
+
+    test('fork.delay does not trigger unhandledRejections for completed or cancelled tasks', async () => {
+      let deferredCompletedEvt = deferred()
+      let deferredCancelledEvt = deferred()
+
+      // Unfortunately we cannot test declaratively unhandleRejections in jest: https://github.com/facebook/jest/issues/5620
+      // This test just fails if an `unhandledRejection` occurs.
+      startListening({
+        actionCreator: increment,
+        effect: async (_, listenerApi) => {
+          const completedTask = listenerApi.fork(async (forkApi) => {
+            forkApi.signal.addEventListener(
+              'abort',
+              deferredCompletedEvt.resolve,
+              { once: true },
+            )
+            forkApi.delay(100) // missing await
+
+            return 4
+          })
+
+          deferredCompletedEvt.resolve(await completedTask.result)
+
+          const godotPauseTrigger = deferred()
+
+          const cancelledTask = listenerApi.fork(async (forkApi) => {
+            forkApi.signal.addEventListener(
+              'abort',
+              deferredCompletedEvt.resolve,
+              { once: true },
+            )
+            forkApi.delay(1_000) // missing await
+            await forkApi.pause(godotPauseTrigger)
+            return 4
+          })
+
+          await Promise.resolve()
+          cancelledTask.cancel()
+          deferredCancelledEvt.resolve(await cancelledTask.result)
+        },
+      })
+
+      store.dispatch(increment())
+      expect(await deferredCompletedEvt).toBeDefined()
+      expect(await deferredCancelledEvt).toBeDefined()
+    })
+  })
+
+  test('forkApi.pause rejects if task is cancelled', async () => {
+    let deferredResult = deferred()
+    startListening({
+      actionCreator: increment,
+      effect: async (_, listenerApi) => {
+        const forkedTask = listenerApi.fork(async (forkApi) => {
+          await forkApi.pause(delay(1_000))
+
+          return 4
+        })
+
+        await Promise.resolve()
+        forkedTask.cancel()
+        deferredResult.resolve(await forkedTask.result)
+      },
+    })
+
+    store.dispatch(increment())
+
+    expect(await deferredResult).toEqual({
+      status: 'cancelled',
+      error: new TaskAbortError(taskCancelled),
+    })
+  })
+
+  test('forkApi.pause rejects as soon as the parent listener is cancelled', async () => {
+    let deferredResult = deferred()
+
+    startListening({
+      actionCreator: increment,
+      effect: async (_, listenerApi) => {
+        listenerApi.cancelActiveListeners()
+        const forkedTask = listenerApi.fork(async (forkApi) => {
+          await forkApi
+            .pause(delay(100))
+            .then(deferredResult.resolve, deferredResult.resolve)
+
+          return 4
+        })
+
+        await forkedTask.result
+        deferredResult.resolve(new Error('unreachable'))
+      },
+    })
+
+    store.dispatch(increment())
+
+    await Promise.resolve()
+
+    store.dispatch(increment())
+    expect(await deferredResult).toEqual(new TaskAbortError(listenerCancelled))
+  })
+
+  test('forkApi.pause rejects if listener is cancelled', async () => {
+    const incrementByInListener = createAction<number>('incrementByInListener')
+
+    startListening({
+      actionCreator: incrementByInListener,
+      async effect({ payload: amountToIncrement }, listenerApi) {
+        listenerApi.cancelActiveListeners()
+        await listenerApi.fork(async (forkApi) => {
+          await forkApi.pause(delay(10))
+          listenerApi.dispatch(incrementByAmount(amountToIncrement))
+        }).result
+        listenerApi.dispatch(incrementByAmount(2 * amountToIncrement))
+      },
+    })
+
+    store.dispatch(incrementByInListener(10))
+    store.dispatch(incrementByInListener(100))
+
+    await delay(50)
+
+    expect(store.getState().value).toEqual(300)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/listenerMiddleware.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/listenerMiddleware.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/listenerMiddleware.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,540 @@
+import { createListenerEntry } from '@internal/listenerMiddleware'
+import type {
+  Action,
+  PayloadAction,
+  TypedAddListener,
+  TypedStartListening,
+  UnknownAction,
+  UnsubscribeListener,
+} from '@reduxjs/toolkit'
+import {
+  addListener,
+  configureStore,
+  createAction,
+  createListenerMiddleware,
+  createSlice,
+  isFluxStandardAction,
+} from '@reduxjs/toolkit'
+
+const listenerMiddleware = createListenerMiddleware()
+const { startListening } = listenerMiddleware
+
+const addTypedListenerAction = addListener as TypedAddListener<CounterState>
+
+interface CounterState {
+  value: number
+}
+
+const testAction1 = createAction<string>('testAction1')
+const testAction2 = createAction<string>('testAction2')
+
+const counterSlice = createSlice({
+  name: 'counter',
+  initialState: { value: 0 } as CounterState,
+  reducers: {
+    increment(state) {
+      state.value += 1
+    },
+    decrement(state) {
+      state.value -= 1
+    },
+    // Use the PayloadAction type to declare the contents of `action.payload`
+    incrementByAmount: (state, action: PayloadAction<number>) => {
+      state.value += action.payload
+    },
+  },
+})
+
+const { increment, decrement, incrementByAmount } = counterSlice.actions
+
+describe('type tests', () => {
+  const store = configureStore({
+    reducer: () => 42,
+    middleware: (gDM) => gDM().prepend(createListenerMiddleware().middleware),
+  })
+
+  test('Allows passing an extra argument on middleware creation', () => {
+    const originalExtra = 42
+    const listenerMiddleware = createListenerMiddleware({
+      extra: originalExtra,
+    })
+    const store = configureStore({
+      reducer: counterSlice.reducer,
+      middleware: (gDM) => gDM().prepend(listenerMiddleware.middleware),
+    })
+
+    let foundExtra: number | null = null
+
+    const typedAddListener =
+      listenerMiddleware.startListening as TypedStartListening<
+        CounterState,
+        typeof store.dispatch,
+        typeof originalExtra
+      >
+
+    typedAddListener({
+      matcher: (action): action is Action => true,
+      effect: (action, listenerApi) => {
+        foundExtra = listenerApi.extra
+
+        expectTypeOf(listenerApi.extra).toMatchTypeOf(originalExtra)
+      },
+    })
+
+    store.dispatch(testAction1('a'))
+    expect(foundExtra).toBe(originalExtra)
+  })
+
+  test('unsubscribing via callback from dispatch', () => {
+    const unsubscribe = store.dispatch(
+      addListener({
+        actionCreator: testAction1,
+        effect: () => {},
+      }),
+    )
+
+    expectTypeOf(unsubscribe).toEqualTypeOf<UnsubscribeListener>()
+
+    store.dispatch(testAction1('a'))
+
+    unsubscribe()
+    store.dispatch(testAction2('b'))
+    store.dispatch(testAction1('c'))
+  })
+
+  test('take resolves to `[A, CurrentState, PreviousState] | null` if a possibly undefined timeout parameter is provided', () => {
+    type ExpectedTakeResultType =
+      | readonly [ReturnType<typeof increment>, CounterState, CounterState]
+      | null
+
+    let timeout: number | undefined = undefined
+    let done = false
+
+    const startAppListening =
+      startListening as TypedStartListening<CounterState>
+    startAppListening({
+      predicate: incrementByAmount.match,
+      effect: async (_, listenerApi) => {
+        let takeResult = await listenerApi.take(increment.match, timeout)
+
+        timeout = 1
+        takeResult = await listenerApi.take(increment.match, timeout)
+        expect(takeResult).toBeNull()
+
+        expectTypeOf(takeResult).toMatchTypeOf<ExpectedTakeResultType>()
+
+        done = true
+      },
+    })
+
+    expect(done).toBe(true)
+  })
+
+  test('State args default to unknown', () => {
+    createListenerEntry({
+      predicate: (
+        action,
+        currentState,
+        previousState,
+      ): action is UnknownAction => {
+        expectTypeOf(currentState).toBeUnknown()
+
+        expectTypeOf(previousState).toBeUnknown()
+
+        return true
+      },
+      effect: (action, listenerApi) => {
+        const listenerState = listenerApi.getState()
+
+        expectTypeOf(listenerState).toBeUnknown()
+
+        listenerApi.dispatch((dispatch, getState) => {
+          const thunkState = getState()
+
+          expectTypeOf(thunkState).toBeUnknown()
+        })
+      },
+    })
+
+    startListening({
+      predicate: (
+        action,
+        currentState,
+        previousState,
+      ): action is UnknownAction => {
+        expectTypeOf(currentState).toBeUnknown()
+
+        expectTypeOf(previousState).toBeUnknown()
+
+        return true
+      },
+      effect: (action, listenerApi) => {},
+    })
+
+    startListening({
+      matcher: increment.match,
+      effect: (action, listenerApi) => {
+        const listenerState = listenerApi.getState()
+
+        expectTypeOf(listenerState).toBeUnknown()
+
+        listenerApi.dispatch((dispatch, getState) => {
+          const thunkState = getState()
+
+          expectTypeOf(thunkState).toBeUnknown()
+        })
+      },
+    })
+
+    store.dispatch(
+      addListener({
+        predicate: (
+          action,
+          currentState,
+          previousState,
+        ): action is UnknownAction => {
+          expectTypeOf(currentState).toBeUnknown()
+
+          expectTypeOf(previousState).toBeUnknown()
+
+          return true
+        },
+        effect: (action, listenerApi) => {
+          const listenerState = listenerApi.getState()
+
+          expectTypeOf(listenerState).toBeUnknown()
+
+          listenerApi.dispatch((dispatch, getState) => {
+            const thunkState = getState()
+
+            expectTypeOf(thunkState).toBeUnknown()
+          })
+        },
+      }),
+    )
+
+    store.dispatch(
+      addListener({
+        matcher: increment.match,
+        effect: (action, listenerApi) => {
+          const listenerState = listenerApi.getState()
+
+          expectTypeOf(listenerState).toBeUnknown()
+
+          listenerApi.dispatch((dispatch, getState) => {
+            const thunkState = getState()
+
+            expectTypeOf(thunkState).toBeUnknown()
+          })
+        },
+      }),
+    )
+  })
+
+  test('Action type is inferred from args', () => {
+    startListening({
+      type: 'abcd',
+      effect: (action, listenerApi) => {
+        expectTypeOf(action).toEqualTypeOf<{ type: 'abcd' }>()
+      },
+    })
+
+    startListening({
+      actionCreator: incrementByAmount,
+      effect: (action, listenerApi) => {
+        expectTypeOf(action).toMatchTypeOf<PayloadAction<number>>()
+      },
+    })
+
+    startListening({
+      matcher: incrementByAmount.match,
+      effect: (action, listenerApi) => {
+        expectTypeOf(action).toMatchTypeOf<PayloadAction<number>>()
+      },
+    })
+
+    startListening({
+      predicate: (
+        action,
+        currentState,
+        previousState,
+      ): action is PayloadAction<number> => {
+        return (
+          isFluxStandardAction(action) && typeof action.payload === 'boolean'
+        )
+      },
+      effect: (action, listenerApi) => {
+        expectTypeOf(action).toEqualTypeOf<PayloadAction<number>>()
+      },
+    })
+
+    startListening({
+      predicate: (action, currentState) => {
+        return (
+          isFluxStandardAction(action) && typeof action.payload === 'number'
+        )
+      },
+      effect: (action, listenerApi) => {
+        expectTypeOf(action).toEqualTypeOf<UnknownAction>()
+      },
+    })
+
+    store.dispatch(
+      addListener({
+        type: 'abcd',
+        effect: (action, listenerApi) => {
+          expectTypeOf(action).toEqualTypeOf<{ type: 'abcd' }>()
+        },
+      }),
+    )
+
+    store.dispatch(
+      addListener({
+        actionCreator: incrementByAmount,
+        effect: (action, listenerApi) => {
+          expectTypeOf(action).toMatchTypeOf<PayloadAction<number>>()
+        },
+      }),
+    )
+
+    store.dispatch(
+      addListener({
+        matcher: incrementByAmount.match,
+        effect: (action, listenerApi) => {
+          expectTypeOf(action).toMatchTypeOf<PayloadAction<number>>()
+        },
+      }),
+    )
+  })
+
+  test('Can create a pre-typed middleware', () => {
+    const typedMiddleware = createListenerMiddleware<CounterState>()
+
+    typedMiddleware.startListening({
+      predicate: (
+        action,
+        currentState,
+        previousState,
+      ): action is UnknownAction => {
+        expectTypeOf(currentState).not.toBeAny()
+
+        expectTypeOf(previousState).not.toBeAny()
+
+        expectTypeOf(currentState).toEqualTypeOf<CounterState>()
+
+        expectTypeOf(previousState).toEqualTypeOf<CounterState>()
+
+        return true
+      },
+      effect: (action, listenerApi) => {
+        const listenerState = listenerApi.getState()
+
+        expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
+
+        listenerApi.dispatch((dispatch, getState) => {
+          const thunkState = listenerApi.getState()
+
+          expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
+        })
+      },
+    })
+
+    // Can pass a predicate function with fewer args
+    typedMiddleware.startListening({
+      predicate: (action, currentState): action is PayloadAction<number> => {
+        expectTypeOf(currentState).not.toBeAny()
+
+        expectTypeOf(currentState).toEqualTypeOf<CounterState>()
+
+        return true
+      },
+      effect: (action, listenerApi) => {
+        expectTypeOf(action).toEqualTypeOf<PayloadAction<number>>()
+
+        const listenerState = listenerApi.getState()
+
+        expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
+
+        listenerApi.dispatch((dispatch, getState) => {
+          const thunkState = listenerApi.getState()
+
+          expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
+        })
+      },
+    })
+
+    typedMiddleware.startListening({
+      actionCreator: incrementByAmount,
+      effect: (action, listenerApi) => {
+        const listenerState = listenerApi.getState()
+
+        expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
+
+        listenerApi.dispatch((dispatch, getState) => {
+          const thunkState = listenerApi.getState()
+
+          expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
+        })
+      },
+    })
+
+    store.dispatch(
+      addTypedListenerAction({
+        predicate: (
+          action,
+          currentState,
+          previousState,
+        ): action is ReturnType<typeof incrementByAmount> => {
+          expectTypeOf(currentState).not.toBeAny()
+
+          expectTypeOf(previousState).not.toBeAny()
+
+          expectTypeOf(currentState).toEqualTypeOf<CounterState>()
+
+          expectTypeOf(previousState).toEqualTypeOf<CounterState>()
+
+          return true
+        },
+        effect: (action, listenerApi) => {
+          const listenerState = listenerApi.getState()
+
+          expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
+
+          listenerApi.dispatch((dispatch, getState) => {
+            const thunkState = listenerApi.getState()
+
+            expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
+          })
+        },
+      }),
+    )
+
+    store.dispatch(
+      addTypedListenerAction({
+        predicate: (
+          action,
+          currentState,
+          previousState,
+        ): action is UnknownAction => {
+          expectTypeOf(currentState).not.toBeAny()
+
+          expectTypeOf(previousState).not.toBeAny()
+
+          expectTypeOf(currentState).toEqualTypeOf<CounterState>()
+
+          expectTypeOf(previousState).toEqualTypeOf<CounterState>()
+
+          return true
+        },
+        effect: (action, listenerApi) => {
+          const listenerState = listenerApi.getState()
+
+          expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
+
+          listenerApi.dispatch((dispatch, getState) => {
+            const thunkState = listenerApi.getState()
+
+            expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
+          })
+        },
+      }),
+    )
+  })
+
+  test('Can create pre-typed versions of startListening and addListener', () => {
+    const typedAddListener = startListening as TypedStartListening<CounterState>
+    const typedAddListenerAction = addListener as TypedAddListener<CounterState>
+
+    typedAddListener({
+      predicate: (
+        action,
+        currentState,
+        previousState,
+      ): action is UnknownAction => {
+        expectTypeOf(currentState).not.toBeAny()
+
+        expectTypeOf(previousState).not.toBeAny()
+
+        expectTypeOf(currentState).toEqualTypeOf<CounterState>()
+
+        expectTypeOf(previousState).toEqualTypeOf<CounterState>()
+
+        return true
+      },
+      effect: (action, listenerApi) => {
+        const listenerState = listenerApi.getState()
+
+        expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
+
+        listenerApi.dispatch((dispatch, getState) => {
+          const thunkState = listenerApi.getState()
+
+          expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
+        })
+      },
+    })
+
+    typedAddListener({
+      matcher: incrementByAmount.match,
+      effect: (action, listenerApi) => {
+        const listenerState = listenerApi.getState()
+
+        expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
+
+        listenerApi.dispatch((dispatch, getState) => {
+          const thunkState = listenerApi.getState()
+
+          expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
+        })
+      },
+    })
+
+    store.dispatch(
+      typedAddListenerAction({
+        predicate: (
+          action,
+          currentState,
+          previousState,
+        ): action is UnknownAction => {
+          expectTypeOf(currentState).not.toBeAny()
+
+          expectTypeOf(previousState).not.toBeAny()
+
+          expectTypeOf(currentState).toEqualTypeOf<CounterState>()
+
+          expectTypeOf(previousState).toEqualTypeOf<CounterState>()
+
+          return true
+        },
+        effect: (action, listenerApi) => {
+          const listenerState = listenerApi.getState()
+
+          expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
+
+          listenerApi.dispatch((dispatch, getState) => {
+            const thunkState = listenerApi.getState()
+
+            expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
+          })
+        },
+      }),
+    )
+
+    store.dispatch(
+      typedAddListenerAction({
+        matcher: incrementByAmount.match,
+        effect: (action, listenerApi) => {
+          const listenerState = listenerApi.getState()
+
+          expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
+
+          listenerApi.dispatch((dispatch, getState) => {
+            const thunkState = listenerApi.getState()
+
+            expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
+          })
+        },
+      }),
+    )
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/listenerMiddleware.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/listenerMiddleware.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/listenerMiddleware.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1371 @@
+import {
+  listenerCancelled,
+  listenerCompleted,
+} from '@internal/listenerMiddleware/exceptions'
+import type { AddListenerOverloads } from '@internal/listenerMiddleware/types'
+import { noop } from '@internal/listenerMiddleware/utils'
+import type {
+  Action,
+  ListenerEffect,
+  ListenerEffectAPI,
+  PayloadAction,
+  TypedRemoveListener,
+  TypedStartListening,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import {
+  TaskAbortError,
+  addListener,
+  clearAllListeners,
+  configureStore,
+  createAction,
+  createListenerMiddleware,
+  createSlice,
+  isAnyOf,
+  removeListener,
+} from '@reduxjs/toolkit'
+import type { Mock } from 'vitest'
+
+const middlewareApi = {
+  getState: expect.any(Function),
+  getOriginalState: expect.any(Function),
+  condition: expect.any(Function),
+  extra: undefined,
+  take: expect.any(Function),
+  signal: expect.any(Object),
+  fork: expect.any(Function),
+  delay: expect.any(Function),
+  pause: expect.any(Function),
+  dispatch: expect.any(Function),
+  unsubscribe: expect.any(Function),
+  subscribe: expect.any(Function),
+  cancelActiveListeners: expect.any(Function),
+  cancel: expect.any(Function),
+  throwIfCancelled: expect.any(Function),
+}
+
+// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
+export interface Deferred<T> extends Promise<T> {
+  resolve(value?: T | PromiseLike<T>): void
+  // deno-lint-ignore no-explicit-any
+  reject(reason?: any): void
+}
+
+/** Creates a Promise with the `reject` and `resolve` functions
+ * placed as methods on the promise object itself. It allows you to do:
+ *
+ *     const p = deferred<number>();
+ *     // ...
+ *     p.resolve(42);
+ */
+export function deferred<T>(): Deferred<T> {
+  let methods
+  const promise = new Promise<T>((resolve, reject): void => {
+    methods = { resolve, reject }
+  })
+  return Object.assign(promise, methods) as Deferred<T>
+}
+
+describe('createListenerMiddleware', () => {
+  let store = configureStore({
+    reducer: () => 42,
+    middleware: (gDM) => gDM().prepend(createListenerMiddleware().middleware),
+  })
+
+  interface CounterState {
+    value: number
+  }
+
+  const counterSlice = createSlice({
+    name: 'counter',
+    initialState: { value: 0 } as CounterState,
+    reducers: {
+      increment(state) {
+        state.value += 1
+      },
+      decrement(state) {
+        state.value -= 1
+      },
+      // Use the PayloadAction type to declare the contents of `action.payload`
+      incrementByAmount: (state, action: PayloadAction<number>) => {
+        state.value += action.payload
+      },
+    },
+  })
+  const { increment, decrement, incrementByAmount } = counterSlice.actions
+
+  function delay(ms: number) {
+    return new Promise((resolve) => setTimeout(resolve, ms))
+  }
+
+  let reducer: Mock
+  let listenerMiddleware = createListenerMiddleware()
+  let { middleware, startListening, stopListening, clearListeners } =
+    listenerMiddleware
+  const removeTypedListenerAction =
+    removeListener as TypedRemoveListener<CounterState>
+
+  const testAction1 = createAction<string>('testAction1')
+  type TestAction1 = ReturnType<typeof testAction1>
+  const testAction2 = createAction<string>('testAction2')
+  type TestAction2 = ReturnType<typeof testAction2>
+  const testAction3 = createAction<string>('testAction3')
+
+  vi.spyOn(console, 'error').mockImplementation(noop)
+
+  beforeEach(() => {
+    listenerMiddleware = createListenerMiddleware()
+    middleware = listenerMiddleware.middleware
+    startListening = listenerMiddleware.startListening
+    stopListening = listenerMiddleware.stopListening
+    clearListeners = listenerMiddleware.clearListeners
+    reducer = vi.fn(() => ({}))
+    store = configureStore({
+      reducer,
+      middleware: (gDM) => gDM().prepend(middleware),
+    })
+  })
+
+  afterEach(() => {
+    vi.clearAllMocks()
+  })
+
+  afterAll(() => {
+    vi.restoreAllMocks()
+  })
+
+  describe('Middleware setup', () => {
+    test('Allows passing an extra argument on middleware creation', () => {
+      const originalExtra = 42
+      const listenerMiddleware = createListenerMiddleware({
+        extra: originalExtra,
+      })
+      const store = configureStore({
+        reducer: counterSlice.reducer,
+        middleware: (gDM) => gDM().prepend(listenerMiddleware.middleware),
+      })
+
+      let foundExtra: number | null = null
+
+      const typedAddListener =
+        listenerMiddleware.startListening as TypedStartListening<
+          CounterState,
+          typeof store.dispatch,
+          typeof originalExtra
+        >
+
+      typedAddListener({
+        matcher: (action): action is Action => true,
+        effect: (action, listenerApi) => {
+          foundExtra = listenerApi.extra
+        },
+      })
+
+      store.dispatch(testAction1('a'))
+      expect(foundExtra).toBe(originalExtra)
+    })
+
+    test('Passes through if there are no listeners', () => {
+      const originalAction = testAction1('a')
+      const resultAction = store.dispatch(originalAction)
+      expect(resultAction).toBe(originalAction)
+    })
+  })
+
+  describe('Subscription and unsubscription', () => {
+    test('directly subscribing', () => {
+      const effect = vi.fn((_: TestAction1) => {})
+
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+
+      store.dispatch(testAction1('a'))
+      store.dispatch(testAction2('b'))
+      store.dispatch(testAction1('c'))
+
+      expect(effect.mock.calls).toEqual([
+        [testAction1('a'), middlewareApi],
+        [testAction1('c'), middlewareApi],
+      ])
+    })
+
+    test('stopListening returns true if an entry has been unsubscribed, false otherwise', () => {
+      const effect = vi.fn((_: TestAction1) => {})
+
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+
+      expect(stopListening({ actionCreator: testAction2, effect })).toBe(false)
+      expect(stopListening({ actionCreator: testAction1, effect })).toBe(true)
+    })
+
+    test('dispatch(removeListener({...})) returns true if an entry has been unsubscribed, false otherwise', () => {
+      const effect = vi.fn((_: TestAction1) => {})
+
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+
+      expect(
+        store.dispatch(
+          removeTypedListenerAction({
+            actionCreator: testAction2,
+            effect,
+          }),
+        ),
+      ).toBe(false)
+      expect(
+        store.dispatch(
+          removeTypedListenerAction({
+            actionCreator: testAction1,
+            effect,
+          }),
+        ),
+      ).toBe(true)
+    })
+
+    test('can subscribe with a string action type', () => {
+      const effect = vi.fn((_: UnknownAction) => {})
+
+      store.dispatch(
+        addListener({
+          type: testAction2.type,
+          effect,
+        }),
+      )
+
+      store.dispatch(testAction2('b'))
+      expect(effect.mock.calls).toEqual([[testAction2('b'), middlewareApi]])
+
+      store.dispatch(removeListener({ type: testAction2.type, effect }))
+
+      store.dispatch(testAction2('b'))
+      expect(effect.mock.calls).toEqual([[testAction2('b'), middlewareApi]])
+    })
+
+    test('can subscribe with a matcher function', () => {
+      const effect = vi.fn((_: UnknownAction) => {})
+
+      const isAction1Or2 = isAnyOf(testAction1, testAction2)
+
+      const unsubscribe = startListening({
+        matcher: isAction1Or2,
+        effect,
+      })
+
+      store.dispatch(testAction1('a'))
+      store.dispatch(testAction2('b'))
+      store.dispatch(testAction3('c'))
+      expect(effect.mock.calls).toEqual([
+        [testAction1('a'), middlewareApi],
+        [testAction2('b'), middlewareApi],
+      ])
+
+      unsubscribe()
+
+      store.dispatch(testAction2('b'))
+      expect(effect.mock.calls).toEqual([
+        [testAction1('a'), middlewareApi],
+        [testAction2('b'), middlewareApi],
+      ])
+    })
+
+    test('Can subscribe with an action predicate function', () => {
+      const store = configureStore({
+        reducer: counterSlice.reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+
+      let listener1Calls = 0
+
+      startListening({
+        predicate: (action, state) => {
+          return (state as CounterState).value > 1
+        },
+        effect: () => {
+          listener1Calls++
+        },
+      })
+
+      let listener2Calls = 0
+
+      startListening({
+        predicate: (action, state, prevState) => {
+          return (
+            (state as CounterState).value > 1 &&
+            (prevState as CounterState).value % 2 === 0
+          )
+        },
+        effect: () => {
+          listener2Calls++
+        },
+      })
+
+      store.dispatch(increment())
+      store.dispatch(increment())
+      store.dispatch(increment())
+      store.dispatch(increment())
+
+      expect(listener1Calls).toBe(3)
+      expect(listener2Calls).toBe(1)
+    })
+
+    test('subscribing with the same listener will not make it trigger twice (like EventTarget.addEventListener())', () => {
+      const effect = vi.fn((_: TestAction1) => {})
+
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+
+      store.dispatch(testAction1('a'))
+      store.dispatch(testAction2('b'))
+      store.dispatch(testAction1('c'))
+
+      expect(effect.mock.calls).toEqual([
+        [testAction1('a'), middlewareApi],
+        [testAction1('c'), middlewareApi],
+      ])
+    })
+
+    test('subscribing with the same effect but different predicate is allowed', () => {
+      const effect = vi.fn((_: TestAction1 | TestAction2) => {})
+
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+      startListening({
+        actionCreator: testAction2,
+        effect,
+      })
+
+      store.dispatch(testAction1('a'))
+      store.dispatch(testAction2('b'))
+
+      expect(effect.mock.calls).toEqual([
+        [testAction1('a'), middlewareApi],
+        [testAction2('b'), middlewareApi],
+      ])
+    })
+
+    test('unsubscribing via callback', () => {
+      const effect = vi.fn((_: TestAction1) => {})
+
+      const unsubscribe = startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+
+      store.dispatch(testAction1('a'))
+      unsubscribe()
+      store.dispatch(testAction2('b'))
+      store.dispatch(testAction1('c'))
+
+      expect(effect.mock.calls).toEqual([[testAction1('a'), middlewareApi]])
+    })
+
+    test('directly unsubscribing', () => {
+      const effect = vi.fn((_: TestAction1) => {})
+
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+
+      store.dispatch(testAction1('a'))
+
+      stopListening({ actionCreator: testAction1, effect })
+      store.dispatch(testAction2('b'))
+      store.dispatch(testAction1('c'))
+
+      expect(effect.mock.calls).toEqual([[testAction1('a'), middlewareApi]])
+    })
+
+    test('unsubscribing without any subscriptions does not trigger an error', () => {
+      stopListening({ matcher: testAction1.match, effect: noop })
+    })
+
+    test('subscribing via action', () => {
+      const effect = vi.fn((_: TestAction1) => {})
+
+      store.dispatch(
+        addListener({
+          actionCreator: testAction1,
+          effect,
+        }),
+      )
+
+      store.dispatch(testAction1('a'))
+      store.dispatch(testAction2('b'))
+      store.dispatch(testAction1('c'))
+
+      expect(effect.mock.calls).toEqual([
+        [testAction1('a'), middlewareApi],
+        [testAction1('c'), middlewareApi],
+      ])
+    })
+
+    test('unsubscribing via callback from dispatch', () => {
+      const effect = vi.fn((_: TestAction1) => {})
+
+      const unsubscribe = store.dispatch(
+        addListener({
+          actionCreator: testAction1,
+          effect,
+        }),
+      )
+
+      store.dispatch(testAction1('a'))
+
+      unsubscribe()
+      store.dispatch(testAction2('b'))
+      store.dispatch(testAction1('c'))
+
+      expect(effect.mock.calls).toEqual([[testAction1('a'), middlewareApi]])
+    })
+
+    test('unsubscribing via action', () => {
+      const effect = vi.fn((_: TestAction1) => {})
+
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+
+      store.dispatch(testAction1('a'))
+
+      store.dispatch(removeListener({ actionCreator: testAction1, effect }))
+      store.dispatch(testAction2('b'))
+      store.dispatch(testAction1('c'))
+
+      expect(effect.mock.calls).toEqual([[testAction1('a'), middlewareApi]])
+    })
+
+    test('can cancel an active listener when unsubscribing directly', async () => {
+      let wasCancelled = false
+      const unsubscribe = startListening({
+        actionCreator: testAction1,
+        effect: async (action, listenerApi) => {
+          try {
+            await listenerApi.condition(testAction2.match)
+          } catch (err) {
+            if (err instanceof TaskAbortError) {
+              wasCancelled = true
+            }
+          }
+        },
+      })
+
+      store.dispatch(testAction1('a'))
+      unsubscribe({ cancelActive: true })
+      expect(wasCancelled).toBe(false)
+      await delay(10)
+      expect(wasCancelled).toBe(true)
+    })
+
+    test('can cancel an active listener when unsubscribing via stopListening', async () => {
+      let wasCancelled = false
+      const effect = async (action: any, listenerApi: any) => {
+        try {
+          await listenerApi.condition(testAction2.match)
+        } catch (err) {
+          if (err instanceof TaskAbortError) {
+            wasCancelled = true
+          }
+        }
+      }
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+
+      store.dispatch(testAction1('a'))
+      stopListening({ actionCreator: testAction1, effect, cancelActive: true })
+      expect(wasCancelled).toBe(false)
+      await delay(10)
+      expect(wasCancelled).toBe(true)
+    })
+
+    test('can cancel an active listener when unsubscribing via removeListener', async () => {
+      let wasCancelled = false
+      const effect = async (action: any, listenerApi: any) => {
+        try {
+          await listenerApi.condition(testAction2.match)
+        } catch (err) {
+          if (err instanceof TaskAbortError) {
+            wasCancelled = true
+          }
+        }
+      }
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+
+      store.dispatch(testAction1('a'))
+      store.dispatch(
+        removeListener({
+          actionCreator: testAction1,
+          effect,
+          cancelActive: true,
+        }),
+      )
+      expect(wasCancelled).toBe(false)
+      await delay(10)
+      expect(wasCancelled).toBe(true)
+    })
+
+    const addListenerOptions: [
+      string,
+      Omit<
+        AddListenerOverloads<
+          () => void,
+          typeof store.getState,
+          typeof store.dispatch
+        >,
+        'effect' | 'withTypes'
+      >,
+    ][] = [
+      ['predicate', { predicate: () => true }],
+      ['actionCreator', { actionCreator: testAction1 }],
+      ['matcher', { matcher: isAnyOf(testAction1, testAction2) }],
+      ['type', { type: testAction1.type }],
+    ]
+
+    test.each(addListenerOptions)(
+      'add and remove listener with "%s" param correctly',
+      (_, params) => {
+        const effect: ListenerEffect<
+          UnknownAction,
+          typeof store.getState,
+          typeof store.dispatch
+        > = vi.fn()
+
+        startListening({ ...params, effect } as any)
+
+        store.dispatch(testAction1('a'))
+        expect(effect).toBeCalledTimes(1)
+
+        stopListening({ ...params, effect } as any)
+
+        store.dispatch(testAction1('b'))
+        expect(effect).toBeCalledTimes(1)
+      },
+    )
+
+    const unforwardedActions: [string, UnknownAction][] = [
+      [
+        'addListener',
+        addListener({ actionCreator: testAction1, effect: noop }),
+      ],
+      [
+        'removeListener',
+        removeListener({ actionCreator: testAction1, effect: noop }),
+      ],
+    ]
+    test.each(unforwardedActions)(
+      '"%s" is not forwarded to the reducer',
+      (_, action) => {
+        reducer.mockClear()
+
+        store.dispatch(testAction1('a'))
+        store.dispatch(action)
+        store.dispatch(testAction2('b'))
+
+        expect(reducer.mock.calls).toEqual([
+          [{}, testAction1('a')],
+          [{}, testAction2('b')],
+        ])
+      },
+    )
+
+    test('listenerApi.signal has correct reason when listener is cancelled or completes', async () => {
+      const notifyDeferred = createAction<Deferred<string>>('notify-deferred')
+
+      startListening({
+        actionCreator: notifyDeferred,
+        async effect({ payload }, { signal, cancelActiveListeners, delay }) {
+          signal.addEventListener(
+            'abort',
+            () => {
+              payload.resolve(signal.reason)
+            },
+            { once: true },
+          )
+
+          cancelActiveListeners()
+          delay(10)
+        },
+      })
+
+      const deferredCancelledSignalReason = store.dispatch(
+        notifyDeferred(deferred<string>()),
+      ).payload
+      const deferredCompletedSignalReason = store.dispatch(
+        notifyDeferred(deferred<string>()),
+      ).payload
+
+      expect(await deferredCancelledSignalReason).toBe(listenerCancelled)
+      expect(await deferredCompletedSignalReason).toBe(listenerCompleted)
+    })
+
+    test('can self-cancel via middleware api', async () => {
+      const notifyDeferred = createAction<Deferred<string>>('notify-deferred')
+
+      startListening({
+        actionCreator: notifyDeferred,
+        effect: async ({ payload }, { signal, cancel, delay }) => {
+          signal.addEventListener(
+            'abort',
+            () => {
+              payload.resolve(signal.reason)
+            },
+            { once: true },
+          )
+
+          cancel()
+        },
+      })
+
+      const deferredCancelledSignalReason = store.dispatch(
+        notifyDeferred(deferred<string>()),
+      ).payload
+
+      expect(await deferredCancelledSignalReason).toBe(listenerCancelled)
+    })
+
+    test('Can easily check if the listener has been cancelled', async () => {
+      const pauseDeferred = deferred<void>()
+
+      let listenerCancelled = false
+      let listenerStarted = false
+      let listenerCompleted = false
+      let cancelListener: () => void = () => {}
+      let error: TaskAbortError | undefined = undefined
+
+      startListening({
+        actionCreator: testAction1,
+        effect: async ({ payload }, { throwIfCancelled, cancel }) => {
+          cancelListener = cancel
+          try {
+            listenerStarted = true
+            throwIfCancelled()
+            await pauseDeferred
+
+            throwIfCancelled()
+            listenerCompleted = true
+          } catch (err) {
+            if (err instanceof TaskAbortError) {
+              listenerCancelled = true
+              error = err
+            }
+          }
+        },
+      })
+
+      store.dispatch(testAction1('a'))
+      expect(listenerStarted).toBe(true)
+      expect(listenerCompleted).toBe(false)
+      expect(listenerCancelled).toBe(false)
+
+      // Cancel it while the listener is paused at a non-cancel-aware promise
+      cancelListener()
+      pauseDeferred.resolve()
+
+      await delay(10)
+      expect(listenerCompleted).toBe(false)
+      expect(listenerCancelled).toBe(true)
+      expect((error as any)?.message).toBe(
+        'task cancelled (reason: listener-cancelled)',
+      )
+    })
+
+    test('can unsubscribe via middleware api', () => {
+      const effect = vi.fn(
+        (action: TestAction1, api: ListenerEffectAPI<any, any>) => {
+          if (action.payload === 'b') {
+            api.unsubscribe()
+          }
+        },
+      )
+
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+
+      store.dispatch(testAction1('a'))
+      store.dispatch(testAction1('b'))
+      store.dispatch(testAction1('c'))
+
+      expect(effect.mock.calls).toEqual([
+        [testAction1('a'), middlewareApi],
+        [testAction1('b'), middlewareApi],
+      ])
+    })
+
+    test('Can re-subscribe via middleware api', async () => {
+      let numListenerRuns = 0
+      startListening({
+        actionCreator: testAction1,
+        effect: async (action, listenerApi) => {
+          numListenerRuns++
+
+          listenerApi.unsubscribe()
+
+          await listenerApi.condition(testAction2.match)
+
+          listenerApi.subscribe()
+        },
+      })
+
+      store.dispatch(testAction1('a'))
+      expect(numListenerRuns).toBe(1)
+
+      store.dispatch(testAction1('a'))
+      expect(numListenerRuns).toBe(1)
+
+      store.dispatch(testAction2('b'))
+      expect(numListenerRuns).toBe(1)
+
+      await delay(5)
+
+      store.dispatch(testAction1('b'))
+      expect(numListenerRuns).toBe(2)
+    })
+  })
+
+  describe('clear listeners', () => {
+    test('dispatch(clearListenerAction()) cancels running listeners and removes all subscriptions', async () => {
+      const listener1Test = deferred()
+      let listener1Calls = 0
+      let listener2Calls = 0
+      let listener3Calls = 0
+
+      startListening({
+        actionCreator: testAction1,
+        async effect(_, listenerApi) {
+          listener1Calls++
+          listenerApi.signal.addEventListener(
+            'abort',
+            () => listener1Test.resolve(listener1Calls),
+            { once: true },
+          )
+          await listenerApi.condition(() => true)
+          listener1Test.reject(new Error('unreachable: listener1Test'))
+        },
+      })
+
+      startListening({
+        actionCreator: clearAllListeners,
+        effect() {
+          listener2Calls++
+        },
+      })
+
+      startListening({
+        predicate: () => true,
+        effect() {
+          listener3Calls++
+        },
+      })
+
+      store.dispatch(testAction1('a'))
+      store.dispatch(clearAllListeners())
+      store.dispatch(testAction1('b'))
+      expect(await listener1Test).toBe(1)
+      expect(listener1Calls).toBe(1)
+      expect(listener3Calls).toBe(1)
+      expect(listener2Calls).toBe(0)
+    })
+
+    test('clear() cancels running listeners and removes all subscriptions', async () => {
+      const listener1Test = deferred()
+
+      let listener1Calls = 0
+      let listener2Calls = 0
+
+      startListening({
+        actionCreator: testAction1,
+        async effect(_, listenerApi) {
+          listener1Calls++
+          listenerApi.signal.addEventListener(
+            'abort',
+            () => listener1Test.resolve(listener1Calls),
+            { once: true },
+          )
+          await listenerApi.condition(() => true)
+          listener1Test.reject(new Error('unreachable: listener1Test'))
+        },
+      })
+
+      startListening({
+        actionCreator: testAction2,
+        effect() {
+          listener2Calls++
+        },
+      })
+
+      store.dispatch(testAction1('a'))
+
+      clearListeners()
+      store.dispatch(testAction1('b'))
+      store.dispatch(testAction2('c'))
+
+      expect(listener2Calls).toBe(0)
+      expect(await listener1Test).toBe(1)
+    })
+
+    test('clear() cancels all running forked tasks', async () => {
+      const store = configureStore({
+        reducer: counterSlice.reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+
+      startListening({
+        actionCreator: testAction1,
+        async effect(_, { fork, dispatch }) {
+          await fork(() => dispatch(incrementByAmount(3))).result
+          dispatch(incrementByAmount(4))
+        },
+      })
+
+      expect(store.getState().value).toBe(0)
+      store.dispatch(testAction1('a'))
+
+      clearListeners()
+
+      await Promise.resolve() // Forked tasks run on the next microtask.
+
+      expect(store.getState().value).toBe(0)
+    })
+  })
+
+  describe('Listener API', () => {
+    test('Passes both getState and getOriginalState in the API', () => {
+      const store = configureStore({
+        reducer: counterSlice.reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+
+      let listener1Calls = 0
+      startListening({
+        actionCreator: increment,
+        effect: (action, listenerApi) => {
+          const stateBefore = listenerApi.getOriginalState() as CounterState
+          const currentState = listenerApi.getOriginalState() as CounterState
+
+          listener1Calls++
+          // In the "before" phase, we pass the same state
+          expect(currentState).toBe(stateBefore)
+        },
+      })
+
+      let listener2Calls = 0
+      startListening({
+        actionCreator: increment,
+        effect: (action, listenerApi) => {
+          // TODO getState functions aren't typed right here
+          const stateBefore = listenerApi.getOriginalState() as CounterState
+          const currentState = listenerApi.getOriginalState() as CounterState
+
+          listener2Calls++
+          // In the "after" phase, we pass the new state for `getState`, and still have original state too
+          expect(currentState.value).toBe(stateBefore.value + 1)
+        },
+      })
+
+      store.dispatch(increment())
+
+      expect(listener1Calls).toBe(1)
+      expect(listener2Calls).toBe(1)
+    })
+
+    test('getOriginalState can only be invoked synchronously', async () => {
+      const onError = vi.fn()
+
+      const listenerMiddleware = createListenerMiddleware<CounterState>({
+        onError,
+      })
+      const { middleware, startListening } = listenerMiddleware
+      const store = configureStore({
+        reducer: counterSlice.reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+
+      startListening({
+        actionCreator: increment,
+        async effect(_, listenerApi) {
+          const runIncrementBy = () => {
+            listenerApi.dispatch(
+              counterSlice.actions.incrementByAmount(
+                listenerApi.getOriginalState().value + 2,
+              ),
+            )
+          }
+
+          runIncrementBy()
+
+          await Promise.resolve()
+
+          runIncrementBy()
+        },
+      })
+
+      expect(store.getState()).toEqual({ value: 0 })
+
+      store.dispatch(increment()) // state.value+=1 && trigger listener
+      expect(onError).not.toHaveBeenCalled()
+      expect(store.getState()).toEqual({ value: 3 })
+
+      await delay(0)
+
+      expect(onError).toBeCalledWith(
+        new Error(
+          'listenerMiddleware: getOriginalState can only be called synchronously',
+        ),
+        { raisedBy: 'effect' },
+      )
+      expect(store.getState()).toEqual({ value: 3 })
+    })
+
+    test('by default, actions are forwarded to the store', () => {
+      reducer.mockClear()
+
+      const effect = vi.fn((_: TestAction1) => {})
+
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+
+      store.dispatch(testAction1('a'))
+
+      expect(reducer.mock.calls).toEqual([[{}, testAction1('a')]])
+    })
+
+    test('listenerApi.delay does not trigger unhandledRejections for completed or cancelled listners', async () => {
+      const deferredCompletedEvt = deferred()
+      const deferredCancelledEvt = deferred()
+      const godotPauseTrigger = deferred()
+
+      // Unfortunately we cannot test declaratively unhandleRejections in jest: https://github.com/facebook/jest/issues/5620
+      // This test just fails if an `unhandledRejection` occurs.
+      startListening({
+        actionCreator: increment,
+        effect: async (_, listenerApi) => {
+          listenerApi.unsubscribe()
+          listenerApi.signal.addEventListener(
+            'abort',
+            deferredCompletedEvt.resolve,
+            { once: true },
+          )
+          listenerApi.delay(100) // missing await
+        },
+      })
+
+      startListening({
+        actionCreator: increment,
+        effect: async (_, listenerApi) => {
+          listenerApi.cancelActiveListeners()
+          listenerApi.signal.addEventListener(
+            'abort',
+            deferredCancelledEvt.resolve,
+            { once: true },
+          )
+          listenerApi.delay(100) // missing await
+          listenerApi.pause(godotPauseTrigger)
+        },
+      })
+
+      store.dispatch(increment())
+      store.dispatch(increment())
+
+      expect(await deferredCompletedEvt).toBeDefined()
+      expect(await deferredCancelledEvt).toBeDefined()
+    })
+  })
+
+  describe('Error handling', () => {
+    test('Continues running other listeners if one of them raises an error', () => {
+      const matcher = (action: any): action is any => true
+
+      startListening({
+        matcher,
+        effect: () => {
+          throw new Error('Panic!')
+        },
+      })
+
+      const effect = vi.fn(() => {})
+      startListening({ matcher, effect })
+
+      store.dispatch(testAction1('a'))
+      expect(effect.mock.calls).toEqual([[testAction1('a'), middlewareApi]])
+    })
+
+    test('Continues running other listeners if a predicate raises an error', () => {
+      const matcher = (action: any): action is any => true
+      const firstListener = vi.fn(() => {})
+      const secondListener = vi.fn(() => {})
+
+      startListening({
+        // @ts-expect-error
+        matcher: (arg: unknown): arg is unknown => {
+          throw new Error('Predicate Panic!')
+        },
+        effect: firstListener,
+      })
+
+      startListening({ matcher, effect: secondListener })
+
+      store.dispatch(testAction1('a'))
+      expect(firstListener).not.toHaveBeenCalled()
+      expect(secondListener.mock.calls).toEqual([
+        [testAction1('a'), middlewareApi],
+      ])
+    })
+
+    test('Notifies sync listener errors to `onError`, if provided', async () => {
+      const onError = vi.fn()
+      const listenerMiddleware = createListenerMiddleware({
+        onError,
+      })
+      const { middleware, startListening } = listenerMiddleware
+      reducer = vi.fn(() => ({}))
+      store = configureStore({
+        reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+
+      const listenerError = new Error('Boom!')
+
+      const matcher = (action: any): action is any => true
+
+      startListening({
+        matcher,
+        effect: () => {
+          throw listenerError
+        },
+      })
+
+      store.dispatch(testAction1('a'))
+      await delay(100)
+
+      expect(onError).toBeCalledWith(listenerError, {
+        raisedBy: 'effect',
+      })
+    })
+
+    test('Notifies async listeners errors to `onError`, if provided', async () => {
+      const onError = vi.fn()
+      const listenerMiddleware = createListenerMiddleware({
+        onError,
+      })
+      const { middleware, startListening } = listenerMiddleware
+      reducer = vi.fn(() => ({}))
+      store = configureStore({
+        reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+
+      const listenerError = new Error('Boom!')
+      const matcher = (action: any): action is any => true
+
+      startListening({
+        matcher,
+        effect: async () => {
+          throw listenerError
+        },
+      })
+
+      store.dispatch(testAction1('a'))
+
+      await delay(100)
+
+      expect(onError).toBeCalledWith(listenerError, {
+        raisedBy: 'effect',
+      })
+    })
+  })
+
+  describe('take and condition methods', () => {
+    test('take resolves to the tuple [A, CurrentState, PreviousState] when the predicate matches the action', async () => {
+      const store = configureStore({
+        reducer: counterSlice.reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+
+      const typedAddListener = startListening as TypedStartListening<
+        CounterState,
+        typeof store.dispatch
+      >
+      let result:
+        | [ReturnType<typeof increment>, CounterState, CounterState]
+        | null = null
+
+      typedAddListener({
+        predicate: incrementByAmount.match,
+        async effect(_: UnknownAction, listenerApi) {
+          result = await listenerApi.take(increment.match)
+        },
+      })
+      store.dispatch(incrementByAmount(1))
+      store.dispatch(increment())
+
+      await delay(10)
+
+      expect(result).toEqual([increment(), { value: 2 }, { value: 1 }])
+    })
+
+    test('take resolves to null if the timeout expires', async () => {
+      const store = configureStore({
+        reducer: counterSlice.reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+
+      let takeResult: any = undefined
+
+      startListening({
+        predicate: incrementByAmount.match,
+        effect: async (_, listenerApi) => {
+          takeResult = await listenerApi.take(increment.match, 15)
+        },
+      })
+      store.dispatch(incrementByAmount(1))
+      await delay(25)
+
+      expect(takeResult).toBe(null)
+    })
+
+    test("take resolves to [A, CurrentState, PreviousState] if the timeout is provided but doesn't expire", async () => {
+      const store = configureStore({
+        reducer: counterSlice.reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+      let takeResult: any = undefined
+      let stateBefore: any = undefined
+      let stateCurrent: any = undefined
+
+      startListening({
+        predicate: incrementByAmount.match,
+        effect: async (_, listenerApi) => {
+          stateBefore = listenerApi.getState()
+          takeResult = await listenerApi.take(increment.match, 50)
+          stateCurrent = listenerApi.getState()
+        },
+      })
+      store.dispatch(incrementByAmount(1))
+      store.dispatch(increment())
+
+      await delay(25)
+      expect(takeResult).toEqual([increment(), stateCurrent, stateBefore])
+    })
+
+    test('take resolves to `[A, CurrentState, PreviousState] | null` if a possibly undefined timeout parameter is provided', async () => {
+      const store = configureStore({
+        reducer: counterSlice.reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+
+      let timeout: number | undefined = undefined
+      let done = false
+
+      const startAppListening =
+        startListening as TypedStartListening<CounterState>
+      startAppListening({
+        predicate: incrementByAmount.match,
+        effect: async (_, listenerApi) => {
+          const stateBefore = listenerApi.getState()
+
+          let takeResult = await listenerApi.take(increment.match, timeout)
+          const stateCurrent = listenerApi.getState()
+          expect(takeResult).toEqual([increment(), stateCurrent, stateBefore])
+
+          timeout = 1
+          takeResult = await listenerApi.take(increment.match, timeout)
+          expect(takeResult).toBeNull()
+
+          done = true
+        },
+      })
+      store.dispatch(incrementByAmount(1))
+      store.dispatch(increment())
+
+      await delay(25)
+      expect(done).toBe(true)
+    })
+
+    test('condition method resolves promise when the predicate succeeds', async () => {
+      const store = configureStore({
+        reducer: counterSlice.reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+
+      let finalCount = 0
+      let listenerStarted = false
+
+      startListening({
+        predicate: (action, _, previousState) => {
+          return (
+            increment.match(action) &&
+            (previousState as CounterState).value === 0
+          )
+        },
+        effect: async (action, listenerApi) => {
+          listenerStarted = true
+          const result = await listenerApi.condition((action, currentState) => {
+            return (currentState as CounterState).value === 3
+          })
+
+          expect(result).toBe(true)
+          const latestState = listenerApi.getState() as CounterState
+          finalCount = latestState.value
+        },
+      })
+
+      store.dispatch(increment())
+
+      expect(listenerStarted).toBe(true)
+      await delay(25)
+      store.dispatch(increment())
+      store.dispatch(increment())
+
+      await delay(25)
+
+      expect(finalCount).toBe(3)
+    })
+
+    test('condition method resolves promise when there is a timeout', async () => {
+      const store = configureStore({
+        reducer: counterSlice.reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+
+      let finalCount = 0
+      let listenerStarted = false
+
+      startListening({
+        predicate: (action, currentState) => {
+          return (
+            increment.match(action) &&
+            (currentState as CounterState).value === 1
+          )
+        },
+        effect: async (action, listenerApi) => {
+          listenerStarted = true
+          const result = await listenerApi.condition((action, currentState) => {
+            return (currentState as CounterState).value === 3
+          }, 25)
+
+          expect(result).toBe(false)
+          const latestState = listenerApi.getState() as CounterState
+          finalCount = latestState.value
+        },
+      })
+
+      store.dispatch(increment())
+      expect(listenerStarted).toBe(true)
+
+      store.dispatch(increment())
+
+      await delay(50)
+      store.dispatch(increment())
+
+      expect(finalCount).toBe(2)
+    })
+
+    test('take does not trigger unhandledRejections for completed or cancelled tasks', async () => {
+      const deferredCompletedEvt = deferred()
+      const deferredCancelledEvt = deferred()
+      const store = configureStore({
+        reducer: counterSlice.reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+      const godotPauseTrigger = deferred()
+
+      startListening({
+        predicate: () => true,
+        effect: async (_, listenerApi) => {
+          listenerApi.unsubscribe() // run once
+          listenerApi.signal.addEventListener(
+            'abort',
+            deferredCompletedEvt.resolve,
+          )
+          listenerApi.take(() => true) // missing await
+        },
+      })
+
+      startListening({
+        predicate: () => true,
+        effect: async (_, listenerApi) => {
+          listenerApi.cancelActiveListeners()
+          listenerApi.signal.addEventListener(
+            'abort',
+            deferredCancelledEvt.resolve,
+          )
+          listenerApi.take(() => true) // missing await
+          await listenerApi.pause(godotPauseTrigger)
+        },
+      })
+
+      store.dispatch({ type: 'type' })
+      store.dispatch({ type: 'type' })
+      expect(await deferredCompletedEvt).toBeDefined()
+    })
+  })
+
+  describe('Job API', () => {
+    test('Allows canceling previous jobs', async () => {
+      let jobsStarted = 0
+      let jobsContinued = 0
+      let jobsCanceled = 0
+
+      startListening({
+        actionCreator: increment,
+        effect: async (action, listenerApi) => {
+          jobsStarted++
+
+          if (jobsStarted < 3) {
+            try {
+              await listenerApi.condition(decrement.match)
+              // Cancelation _should_ cause `condition()` to throw so we never
+              // end up hitting this next line
+              jobsContinued++
+            } catch (err) {
+              if (err instanceof TaskAbortError) {
+                jobsCanceled++
+              }
+            }
+          } else {
+            listenerApi.cancelActiveListeners()
+          }
+        },
+      })
+
+      store.dispatch(increment())
+      store.dispatch(increment())
+      store.dispatch(increment())
+
+      await delay(10)
+      expect(jobsStarted).toBe(3)
+      expect(jobsContinued).toBe(0)
+      expect(jobsCanceled).toBe(2)
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/listenerMiddleware.withTypes.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/listenerMiddleware.withTypes.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/listenerMiddleware.withTypes.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,159 @@
+import type {
+  Action,
+  ThunkAction,
+  TypedAddListener,
+  TypedRemoveListener,
+  TypedStartListening,
+  TypedStopListening,
+} from '@reduxjs/toolkit'
+import {
+  addListener,
+  configureStore,
+  createAsyncThunk,
+  createListenerMiddleware,
+  createSlice,
+  removeListener,
+} from '@reduxjs/toolkit'
+import { describe, expectTypeOf, test } from 'vitest'
+
+export interface CounterState {
+  counter: number
+}
+
+const initialState: CounterState = {
+  counter: 0,
+}
+
+export const counterSlice = createSlice({
+  name: 'counter',
+  initialState,
+  reducers: {
+    increment(state) {
+      state.counter++
+    },
+  },
+})
+
+export function fetchCount(amount = 1) {
+  return new Promise<{ data: number }>((resolve) =>
+    setTimeout(() => resolve({ data: amount }), 500),
+  )
+}
+
+export const incrementAsync = createAsyncThunk(
+  'counter/fetchCount',
+  async (amount: number) => {
+    const response = await fetchCount(amount)
+    // The value we return becomes the `fulfilled` action payload
+    return response.data
+  },
+)
+
+const { increment } = counterSlice.actions
+
+const store = configureStore({
+  reducer: counterSlice.reducer,
+})
+
+type AppStore = typeof store
+type AppDispatch = typeof store.dispatch
+type RootState = ReturnType<typeof store.getState>
+type AppThunk<ThunkReturnType = void> = ThunkAction<
+  ThunkReturnType,
+  RootState,
+  unknown,
+  Action
+>
+type ExtraArgument = { foo: string }
+
+describe('listenerMiddleware.withTypes<RootState, AppDispatch>()', () => {
+  const listenerMiddleware = createListenerMiddleware()
+  let timeout: number | undefined = undefined
+  let done = false
+
+  type ExpectedTakeResultType =
+    | [ReturnType<typeof increment>, RootState, RootState]
+    | null
+
+  test('startListening.withTypes', () => {
+    const startAppListening = listenerMiddleware.startListening.withTypes<
+      RootState,
+      AppDispatch,
+      ExtraArgument
+    >()
+
+    expectTypeOf(startAppListening).toEqualTypeOf<
+      TypedStartListening<RootState, AppDispatch, ExtraArgument>
+    >()
+
+    startAppListening({
+      predicate: increment.match,
+      effect: async (action, listenerApi) => {
+        const stateBefore = listenerApi.getState()
+
+        expectTypeOf(increment).returns.toEqualTypeOf(action)
+
+        expectTypeOf(listenerApi.dispatch).toEqualTypeOf<AppDispatch>()
+
+        expectTypeOf(stateBefore).toEqualTypeOf<RootState>()
+
+        let takeResult = await listenerApi.take(increment.match, timeout)
+        const stateCurrent = listenerApi.getState()
+
+        expectTypeOf(takeResult).toEqualTypeOf<ExpectedTakeResultType>()
+
+        expectTypeOf(stateCurrent).toEqualTypeOf<RootState>()
+
+        expectTypeOf(listenerApi.extra).toEqualTypeOf<ExtraArgument>()
+
+        timeout = 1
+        takeResult = await listenerApi.take(increment.match, timeout)
+
+        done = true
+      },
+    })
+  })
+
+  test('addListener.withTypes', () => {
+    const addAppListener = addListener.withTypes<RootState, AppDispatch, ExtraArgument>()
+
+    expectTypeOf(addAppListener).toEqualTypeOf<
+      TypedAddListener<RootState, AppDispatch, ExtraArgument>
+    >()
+
+    store.dispatch(
+      addAppListener({
+        matcher: increment.match,
+        effect: (action, listenerApi) => {
+          const state = listenerApi.getState()
+
+          expectTypeOf(state).toEqualTypeOf<RootState>()
+
+          expectTypeOf(listenerApi.dispatch).toEqualTypeOf<AppDispatch>()
+
+          expectTypeOf(listenerApi.extra).toEqualTypeOf<ExtraArgument>()
+        },
+      }),
+    )
+  })
+
+  test('removeListener.withTypes', () => {
+    const removeAppListener = removeListener.withTypes<RootState, AppDispatch, ExtraArgument>()
+
+    expectTypeOf(removeAppListener).toEqualTypeOf<
+      TypedRemoveListener<RootState, AppDispatch, ExtraArgument>
+    >()
+  })
+
+  test('stopListening.withTypes', () => {
+    const stopAppListening = listenerMiddleware.stopListening.withTypes<
+      RootState,
+      AppDispatch,
+      ExtraArgument
+    >()
+
+    expectTypeOf(stopAppListening).toEqualTypeOf<
+      TypedStopListening<RootState, AppDispatch, ExtraArgument>
+    >()
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/listenerMiddleware.withTypes.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/listenerMiddleware.withTypes.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/listenerMiddleware.withTypes.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,120 @@
+import type { Action } from 'redux'
+import type { ThunkAction } from 'redux-thunk'
+import { describe, expect, test } from 'vitest'
+import { configureStore } from '../../configureStore'
+import { createAsyncThunk } from '../../createAsyncThunk'
+import { createSlice } from '../../createSlice'
+import { addListener, createListenerMiddleware, removeListener } from '../index'
+
+export interface CounterState {
+  counter: number
+}
+
+const initialState: CounterState = {
+  counter: 0,
+}
+
+export const counterSlice = createSlice({
+  name: 'counter',
+  initialState,
+  reducers: {
+    increment(state) {
+      state.counter++
+    },
+  },
+})
+
+export function fetchCount(amount = 1) {
+  return new Promise<{ data: number }>((resolve) =>
+    setTimeout(() => resolve({ data: amount }), 500),
+  )
+}
+
+export const incrementAsync = createAsyncThunk(
+  'counter/fetchCount',
+  async (amount: number) => {
+    const response = await fetchCount(amount)
+    // The value we return becomes the `fulfilled` action payload
+    return response.data
+  },
+)
+
+const { increment } = counterSlice.actions
+
+const store = configureStore({
+  reducer: counterSlice.reducer,
+})
+
+type AppStore = typeof store
+type AppDispatch = typeof store.dispatch
+type RootState = ReturnType<typeof store.getState>
+type AppThunk<ThunkReturnType = void> = ThunkAction<
+  ThunkReturnType,
+  RootState,
+  unknown,
+  Action
+>
+
+type ExtraArgument = { foo: string }
+
+const listenerMiddleware = createListenerMiddleware()
+
+const startAppListening = listenerMiddleware.startListening.withTypes<
+  RootState,
+  AppDispatch,
+  ExtraArgument
+>()
+
+const stopAppListening = listenerMiddleware.stopListening.withTypes<
+  RootState,
+  AppDispatch,
+  ExtraArgument
+>()
+
+const addAppListener = addListener.withTypes<RootState, AppDispatch, ExtraArgument>()
+
+const removeAppListener = removeListener.withTypes<RootState, AppDispatch, ExtraArgument>()
+
+describe('startAppListening.withTypes', () => {
+  test('should return startListening', () => {
+    expect(startAppListening.withTypes).toEqual(expect.any(Function))
+
+    expect(startAppListening.withTypes().withTypes).toEqual(
+      expect.any(Function),
+    )
+
+    expect(startAppListening).toBe(listenerMiddleware.startListening)
+  })
+})
+
+describe('stopAppListening.withTypes', () => {
+  test('should return stopListening', () => {
+    expect(stopAppListening.withTypes).toEqual(expect.any(Function))
+
+    expect(stopAppListening.withTypes().withTypes).toEqual(expect.any(Function))
+
+    expect(stopAppListening).toBe(listenerMiddleware.stopListening)
+  })
+})
+
+describe('addAppListener.withTypes', () => {
+  test('should return addListener', () => {
+    expect(addAppListener.withTypes).toEqual(expect.any(Function))
+
+    expect(addAppListener.withTypes().withTypes).toEqual(expect.any(Function))
+
+    expect(addAppListener).toBe(addListener)
+  })
+})
+
+describe('removeAppListener.withTypes', () => {
+  test('should return removeListener', () => {
+    expect(removeAppListener.withTypes).toEqual(expect.any(Function))
+
+    expect(removeAppListener.withTypes().withTypes).toEqual(
+      expect.any(Function),
+    )
+
+    expect(removeAppListener).toBe(removeListener)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/useCases.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/useCases.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/useCases.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,175 @@
+import {
+  configureStore,
+  createAction,
+  createSlice,
+  isAnyOf,
+} from '@reduxjs/toolkit'
+
+import type { PayloadAction } from '@reduxjs/toolkit'
+
+import { createListenerMiddleware } from '../index'
+
+import type { TypedAddListener } from '../index'
+import { TaskAbortError } from '../exceptions'
+
+interface CounterState {
+  value: number
+}
+
+const counterSlice = createSlice({
+  name: 'counter',
+  initialState: { value: 0 } as CounterState,
+  reducers: {
+    increment(state) {
+      state.value += 1
+    },
+    decrement(state) {
+      state.value -= 1
+    },
+    // Use the PayloadAction type to declare the contents of `action.payload`
+    incrementByAmount: (state, action: PayloadAction<number>) => {
+      state.value += action.payload
+    },
+  },
+})
+const { increment, decrement, incrementByAmount } = counterSlice.actions
+
+describe('Saga-style Effects Scenarios', () => {
+  let listenerMiddleware = createListenerMiddleware<CounterState>()
+  let { middleware, startListening, stopListening } = listenerMiddleware
+
+  let store = configureStore({
+    reducer: counterSlice.reducer,
+    middleware: (gDM) => gDM().prepend(middleware),
+  })
+
+  const testAction1 = createAction<string>('testAction1')
+  type TestAction1 = ReturnType<typeof testAction1>
+  const testAction2 = createAction<string>('testAction2')
+  type TestAction2 = ReturnType<typeof testAction2>
+  const testAction3 = createAction<string>('testAction3')
+  type TestAction3 = ReturnType<typeof testAction3>
+
+  type RootState = ReturnType<typeof store.getState>
+
+  function delay(ms: number) {
+    return new Promise((resolve) => setTimeout(resolve, ms))
+  }
+
+  beforeEach(() => {
+    listenerMiddleware = createListenerMiddleware<CounterState>()
+    middleware = listenerMiddleware.middleware
+    startListening = listenerMiddleware.startListening
+    store = configureStore({
+      reducer: counterSlice.reducer,
+      middleware: (gDM) => gDM().prepend(middleware),
+    })
+  })
+
+  test('Long polling loop', async () => {
+    // Reimplementation of a saga-based long-polling loop that is controlled
+    // by "start/stop" actions. The infinite loop waits for a message from the
+    // server, processes it somehow, and waits for the next message.
+    // Ref: https://gist.github.com/markerikson/5203e71a69fa9dff203c9e27c3d84154
+    const eventPollingStarted = createAction('serverPolling/started')
+    const eventPollingStopped = createAction('serverPolling/stopped')
+
+    // For this example, we're going to fake up a "server event poll" async
+    // function by wrapping an event emitter so that every call returns a
+    // promise that is resolved the next time an event is emitted.
+    // This is the tiniest event emitter I could find to copy-paste in here.
+    let createNanoEvents = () => ({
+      events: {} as Record<string, any>,
+      emit(event: string, ...args: any[]) {
+        ;(this.events[event] || []).forEach((i: any) => i(...args))
+      },
+      on(event: string, cb: (...args: any[]) => void) {
+        ;(this.events[event] = this.events[event] || []).push(cb)
+        return () =>
+          (this.events[event] = (this.events[event] || []).filter(
+            (l: any) => l !== cb,
+          ))
+      },
+    })
+    const emitter = createNanoEvents()
+
+    // Rig up a dummy "receive a message from the server" API we can trigger manually
+    function pollForEvent() {
+      return new Promise<{ type: string }>((resolve, reject) => {
+        const unsubscribe = emitter.on('serverEvent', (arg1: string) => {
+          unsubscribe()
+          resolve({ type: arg1 })
+        })
+      })
+    }
+
+    // Track how many times each message was processed by the loop
+    const receivedMessages = {
+      a: 0,
+      b: 0,
+      c: 0,
+    }
+
+    let pollingTaskStarted = false
+    let pollingTaskCanceled = false
+
+    startListening({
+      actionCreator: eventPollingStarted,
+      effect: async (action, listenerApi) => {
+        listenerApi.unsubscribe()
+
+        // Start a child job that will infinitely loop receiving messages
+        const pollingTask = listenerApi.fork(async (forkApi) => {
+          pollingTaskStarted = true
+          try {
+            while (true) {
+              // Cancelation-aware pause for a new server message
+              const serverEvent = await forkApi.pause(pollForEvent())
+              // Process the message. In this case, just count the times we've seen this message.
+              if (serverEvent.type in receivedMessages) {
+                receivedMessages[
+                  serverEvent.type as keyof typeof receivedMessages
+                ]++
+              }
+            }
+          } catch (err) {
+            if (err instanceof TaskAbortError) {
+              pollingTaskCanceled = true
+            }
+          }
+          return 0
+        })
+
+        // Wait for the "stop polling" action
+        await listenerApi.condition(eventPollingStopped.match)
+        pollingTask.cancel()
+      },
+    })
+
+    store.dispatch(eventPollingStarted())
+    await delay(5)
+    expect(pollingTaskStarted).toBe(true)
+
+    await delay(5)
+    emitter.emit('serverEvent', 'a')
+    // Promise resolution
+    await delay(1)
+    emitter.emit('serverEvent', 'b')
+    // Promise resolution
+    await delay(1)
+
+    store.dispatch(eventPollingStopped())
+
+    // Have to break out of the event loop to let the cancelation promise
+    // kick in - emitting before this would still resolve pollForEvent()
+    await delay(1)
+    emitter.emit('serverEvent', 'c')
+
+    // A and B were processed earlier. The first C was processed because the
+    // emitter synchronously resolved the `pollForEvents` promise before
+    // the cancelation took effect, but after another pause, the
+    // cancelation kicked in and the second C is ignored.
+    expect(receivedMessages).toEqual({ a: 1, b: 1, c: 0 })
+    expect(pollingTaskCanceled).toBe(true)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/listenerMiddleware/types.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/listenerMiddleware/types.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/listenerMiddleware/types.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,872 @@
+import type {
+  Action,
+  Dispatch,
+  Middleware,
+  MiddlewareAPI,
+  UnknownAction,
+} from 'redux'
+import type { ThunkDispatch } from 'redux-thunk'
+import type { BaseActionCreator, PayloadAction } from '../createAction'
+import type { TypedActionCreator } from '../mapBuilders'
+import type { TaskAbortError } from './exceptions'
+
+/**
+ * Types copied from RTK
+ */
+
+/** @internal */
+type TypedActionCreatorWithMatchFunction<Type extends string> =
+  TypedActionCreator<Type> & {
+    match: MatchFunction<any>
+  }
+
+/** @internal */
+export type AnyListenerPredicate<State> = (
+  action: UnknownAction,
+  currentState: State,
+  originalState: State,
+) => boolean
+
+/** @public */
+export type ListenerPredicate<ActionType extends Action, State> = (
+  action: UnknownAction,
+  currentState: State,
+  originalState: State,
+) => action is ActionType
+
+/** @public */
+export interface ConditionFunction<State> {
+  (predicate: AnyListenerPredicate<State>, timeout?: number): Promise<boolean>
+  (predicate: AnyListenerPredicate<State>, timeout?: number): Promise<boolean>
+  (predicate: () => boolean, timeout?: number): Promise<boolean>
+}
+
+/** @internal */
+export type MatchFunction<T> = (v: any) => v is T
+
+/** @public */
+export interface ForkedTaskAPI {
+  /**
+   * Returns a promise that resolves when `waitFor` resolves or
+   * rejects if the task or the parent listener has been cancelled or is completed.
+   */
+  pause<W>(waitFor: Promise<W>): Promise<W>
+  /**
+   * Returns a promise that resolves after `timeoutMs` or
+   * rejects if the task or the parent listener has been cancelled or is completed.
+   * @param timeoutMs
+   */
+  delay(timeoutMs: number): Promise<void>
+  /**
+   * An abort signal whose `aborted` property is set to `true`
+   * if the task execution is either aborted or completed.
+   * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
+   */
+  signal: AbortSignal
+}
+
+/** @public */
+export interface AsyncTaskExecutor<T> {
+  (forkApi: ForkedTaskAPI): Promise<T>
+}
+
+/** @public */
+export interface SyncTaskExecutor<T> {
+  (forkApi: ForkedTaskAPI): T
+}
+
+/** @public */
+export type ForkedTaskExecutor<T> = AsyncTaskExecutor<T> | SyncTaskExecutor<T>
+
+/** @public */
+export type TaskResolved<T> = {
+  readonly status: 'ok'
+  readonly value: T
+}
+
+/** @public */
+export type TaskRejected = {
+  readonly status: 'rejected'
+  readonly error: unknown
+}
+
+/** @public */
+export type TaskCancelled = {
+  readonly status: 'cancelled'
+  readonly error: TaskAbortError
+}
+
+/** @public */
+export type TaskResult<Value> =
+  | TaskResolved<Value>
+  | TaskRejected
+  | TaskCancelled
+
+/** @public */
+export interface ForkedTask<T> {
+  /**
+   * A promise that resolves when the task is either completed or cancelled or rejects
+   * if parent listener execution is cancelled or completed.
+   *
+   * ### Example
+   * ```ts
+   * const result = await fork(async (forkApi) => Promise.resolve(4)).result
+   *
+   * if(result.status === 'ok') {
+   *   console.log(result.value) // logs 4
+   * }}
+   * ```
+   */
+  result: Promise<TaskResult<T>>
+  /**
+   * Cancel task if it is in progress or not yet started,
+   * it is noop otherwise.
+   */
+  cancel(): void
+}
+
+/** @public */
+export interface ForkOptions {
+  /**
+   * If true, causes the parent task to not be marked as complete until
+   * all autoJoined forks have completed or failed.
+   */
+  autoJoin: boolean
+}
+
+/** @public */
+export interface ListenerEffectAPI<
+  State,
+  DispatchType extends Dispatch,
+  ExtraArgument = unknown,
+> extends MiddlewareAPI<DispatchType, State> {
+  /**
+   * Returns the store state as it existed when the action was originally dispatched, _before_ the reducers ran.
+   *
+   * ### Synchronous invocation
+   *
+   * This function can **only** be invoked **synchronously**, it throws error otherwise.
+   *
+   * @example
+   *
+   * ```ts
+   * middleware.startListening({
+   *  predicate: () => true,
+   *  async effect(_, { getOriginalState }) {
+   *    getOriginalState(); // sync: OK!
+   *
+   *    setTimeout(getOriginalState, 0); // async: throws Error
+   *
+   *    await Promise().resolve();
+   *
+   *    getOriginalState() // async: throws Error
+   *  }
+   * })
+   * ```
+   */
+  getOriginalState: () => State
+  /**
+   * Removes the listener entry from the middleware and prevent future instances of the listener from running.
+   *
+   * It does **not** cancel any active instances.
+   */
+  unsubscribe(): void
+  /**
+   * It will subscribe a listener if it was previously removed, noop otherwise.
+   */
+  subscribe(): void
+  /**
+   * Returns a promise that resolves when the input predicate returns `true` or
+   * rejects if the listener has been cancelled or is completed.
+   *
+   * The return value is `true` if the predicate succeeds or `false` if a timeout is provided and expires first.
+   *
+   * ### Example
+   *
+   * ```ts
+   * const updateBy = createAction<number>('counter/updateBy');
+   *
+   * middleware.startListening({
+   *  actionCreator: updateBy,
+   *  async effect(_, { condition }) {
+   *    // wait at most 3s for `updateBy` actions.
+   *    if(await condition(updateBy.match, 3_000)) {
+   *      // `updateBy` has been dispatched twice in less than 3s.
+   *    }
+   *  }
+   * })
+   * ```
+   */
+  condition: ConditionFunction<State>
+  /**
+   * Returns a promise that resolves when the input predicate returns `true` or
+   * rejects if the listener has been cancelled or is completed.
+   *
+   * The return value is the `[action, currentState, previousState]` combination that the predicate saw as arguments.
+   *
+   * The promise resolves to null if a timeout is provided and expires first,
+   *
+   * ### Example
+   *
+   * ```ts
+   * const updateBy = createAction<number>('counter/updateBy');
+   *
+   * middleware.startListening({
+   *  actionCreator: updateBy,
+   *  async effect(_, { take }) {
+   *    const [{ payload }] =  await take(updateBy.match);
+   *    console.log(payload); // logs 5;
+   *  }
+   * })
+   *
+   * store.dispatch(updateBy(5));
+   * ```
+   */
+  take: TakePattern<State>
+  /**
+   * Cancels all other running instances of this same listener except for the one that made this call.
+   */
+  cancelActiveListeners: () => void
+  /**
+   * Cancels the instance of this listener that made this call.
+   */
+  cancel: () => void
+  /**
+   * Throws a `TaskAbortError` if this listener has been cancelled
+   */
+  throwIfCancelled: () => void
+  /**
+   * An abort signal whose `aborted` property is set to `true`
+   * if the listener execution is either aborted or completed.
+   * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
+   */
+  signal: AbortSignal
+  /**
+   * Returns a promise that resolves after `timeoutMs` or
+   * rejects if the listener has been cancelled or is completed.
+   */
+  delay(timeoutMs: number): Promise<void>
+  /**
+   * Queues in the next microtask the execution of a task.
+   * @param executor
+   * @param options
+   */
+  fork<T>(executor: ForkedTaskExecutor<T>, options?: ForkOptions): ForkedTask<T>
+  /**
+   * Returns a promise that resolves when `waitFor` resolves or
+   * rejects if the listener has been cancelled or is completed.
+   * @param promise
+   */
+  pause<M>(promise: Promise<M>): Promise<M>
+  extra: ExtraArgument
+}
+
+/** @public */
+export type ListenerEffect<
+  ActionType extends Action,
+  State,
+  DispatchType extends Dispatch,
+  ExtraArgument = unknown,
+> = (
+  action: ActionType,
+  api: ListenerEffectAPI<State, DispatchType, ExtraArgument>,
+) => void | Promise<void>
+
+/**
+ * @public
+ * Additional infos regarding the error raised.
+ */
+export interface ListenerErrorInfo {
+  /**
+   * Which function has generated the exception.
+   */
+  raisedBy: 'effect' | 'predicate'
+}
+
+/**
+ * @public
+ * Gets notified with synchronous and asynchronous errors raised by `listeners` or `predicates`.
+ * @param error The thrown error.
+ * @param errorInfo Additional information regarding the thrown error.
+ */
+export interface ListenerErrorHandler {
+  (error: unknown, errorInfo: ListenerErrorInfo): void
+}
+
+/** @public */
+export interface CreateListenerMiddlewareOptions<ExtraArgument = unknown> {
+  extra?: ExtraArgument
+  /**
+   * Receives synchronous errors that are raised by `listener` and `listenerOption.predicate`.
+   */
+  onError?: ListenerErrorHandler
+}
+
+/** @public */
+export type ListenerMiddleware<
+  State = unknown,
+  DispatchType extends ThunkDispatch<State, unknown, Action> = ThunkDispatch<
+    State,
+    unknown,
+    UnknownAction
+  >,
+  ExtraArgument = unknown,
+> = Middleware<
+  {
+    (action: Action<'listenerMiddleware/add'>): UnsubscribeListener
+  },
+  State,
+  DispatchType
+>
+
+/** @public */
+export interface ListenerMiddlewareInstance<
+  StateType = unknown,
+  DispatchType extends ThunkDispatch<
+    StateType,
+    unknown,
+    Action
+  > = ThunkDispatch<StateType, unknown, UnknownAction>,
+  ExtraArgument = unknown,
+> {
+  middleware: ListenerMiddleware<StateType, DispatchType, ExtraArgument>
+
+  startListening: AddListenerOverloads<
+    UnsubscribeListener,
+    StateType,
+    DispatchType,
+    ExtraArgument
+  > &
+    TypedStartListening<StateType, DispatchType, ExtraArgument>
+
+  stopListening: RemoveListenerOverloads<StateType, DispatchType> &
+    TypedStopListening<StateType, DispatchType>
+
+  /**
+   * Unsubscribes all listeners, cancels running listeners and tasks.
+   */
+  clearListeners: () => void
+}
+
+/**
+ * API Function Overloads
+ */
+
+/** @public */
+export type TakePatternOutputWithoutTimeout<
+  State,
+  Predicate extends AnyListenerPredicate<State>,
+> =
+  Predicate extends MatchFunction<infer ActionType>
+    ? Promise<[ActionType, State, State]>
+    : Promise<[UnknownAction, State, State]>
+
+/** @public */
+export type TakePatternOutputWithTimeout<
+  State,
+  Predicate extends AnyListenerPredicate<State>,
+> =
+  Predicate extends MatchFunction<infer ActionType>
+    ? Promise<[ActionType, State, State] | null>
+    : Promise<[UnknownAction, State, State] | null>
+
+/** @public */
+export interface TakePattern<State> {
+  <Predicate extends AnyListenerPredicate<State>>(
+    predicate: Predicate,
+  ): TakePatternOutputWithoutTimeout<State, Predicate>
+  <Predicate extends AnyListenerPredicate<State>>(
+    predicate: Predicate,
+    timeout: number,
+  ): TakePatternOutputWithTimeout<State, Predicate>
+  <Predicate extends AnyListenerPredicate<State>>(
+    predicate: Predicate,
+    timeout?: number | undefined,
+  ): TakePatternOutputWithTimeout<State, Predicate>
+}
+
+/** @public */
+export interface UnsubscribeListenerOptions {
+  cancelActive?: true
+}
+
+/** @public */
+export type UnsubscribeListener = (
+  unsubscribeOptions?: UnsubscribeListenerOptions,
+) => void
+
+/**
+ * @public
+ * The possible overloads and options for defining a listener. The return type of each function is specified as a generic arg, so the overloads can be reused for multiple different functions
+ */
+export type AddListenerOverloads<
+  Return,
+  StateType = unknown,
+  DispatchType extends Dispatch = ThunkDispatch<
+    StateType,
+    unknown,
+    UnknownAction
+  >,
+  ExtraArgument = unknown,
+  AdditionalOptions = unknown,
+> = {
+  /** Accepts a "listener predicate" that is also a TS type predicate for the action*/
+  <
+    MiddlewareActionType extends UnknownAction,
+    ListenerPredicateType extends ListenerPredicate<
+      MiddlewareActionType,
+      StateType
+    >,
+  >(
+    options: {
+      actionCreator?: never
+      type?: never
+      matcher?: never
+      predicate: ListenerPredicateType
+      effect: ListenerEffect<
+        ListenerPredicateGuardedActionType<ListenerPredicateType>,
+        StateType,
+        DispatchType,
+        ExtraArgument
+      >
+    } & AdditionalOptions,
+  ): Return
+
+  /** Accepts an RTK action creator, like `incrementByAmount` */
+  <ActionCreatorType extends TypedActionCreatorWithMatchFunction<any>>(
+    options: {
+      actionCreator: ActionCreatorType
+      type?: never
+      matcher?: never
+      predicate?: never
+      effect: ListenerEffect<
+        ReturnType<ActionCreatorType>,
+        StateType,
+        DispatchType,
+        ExtraArgument
+      >
+    } & AdditionalOptions,
+  ): Return
+
+  /** Accepts a specific action type string */
+  <T extends string>(
+    options: {
+      actionCreator?: never
+      type: T
+      matcher?: never
+      predicate?: never
+      effect: ListenerEffect<Action<T>, StateType, DispatchType, ExtraArgument>
+    } & AdditionalOptions,
+  ): Return
+
+  /** Accepts an RTK matcher function, such as `incrementByAmount.match` */
+  <MatchFunctionType extends MatchFunction<UnknownAction>>(
+    options: {
+      actionCreator?: never
+      type?: never
+      matcher: MatchFunctionType
+      predicate?: never
+      effect: ListenerEffect<
+        GuardedType<MatchFunctionType>,
+        StateType,
+        DispatchType,
+        ExtraArgument
+      >
+    } & AdditionalOptions,
+  ): Return
+
+  /** Accepts a "listener predicate" that just returns a boolean, no type assertion */
+  <ListenerPredicateType extends AnyListenerPredicate<StateType>>(
+    options: {
+      actionCreator?: never
+      type?: never
+      matcher?: never
+      predicate: ListenerPredicateType
+      effect: ListenerEffect<
+        UnknownAction,
+        StateType,
+        DispatchType,
+        ExtraArgument
+      >
+    } & AdditionalOptions,
+  ): Return
+}
+
+/** @public */
+export type RemoveListenerOverloads<
+  StateType = unknown,
+  DispatchType extends Dispatch = ThunkDispatch<
+    StateType,
+    unknown,
+    UnknownAction
+  >,
+  ExtraArgument = unknown,
+> = AddListenerOverloads<
+  boolean,
+  StateType,
+  DispatchType,
+  ExtraArgument,
+  UnsubscribeListenerOptions
+>
+
+/** @public */
+export interface RemoveListenerAction<
+  ActionType extends UnknownAction,
+  State,
+  DispatchType extends Dispatch,
+> {
+  type: 'listenerMiddleware/remove'
+  payload: {
+    type: string
+    listener: ListenerEffect<ActionType, State, DispatchType>
+  }
+}
+
+/**
+ * A "pre-typed" version of `addListenerAction`, so the listener args are well-typed
+ *
+ * @public
+ */
+export type TypedAddListener<
+  StateType,
+  DispatchType extends Dispatch = ThunkDispatch<
+    StateType,
+    unknown,
+    UnknownAction
+  >,
+  ExtraArgument = unknown,
+  Payload = ListenerEntry<StateType, DispatchType>,
+  T extends string = 'listenerMiddleware/add',
+> = BaseActionCreator<Payload, T> &
+  AddListenerOverloads<
+    PayloadAction<Payload, T>,
+    StateType,
+    DispatchType,
+    ExtraArgument
+  > & {
+    /**
+     * Creates a "pre-typed" version of `addListener`
+     * where the `state`, `dispatch` and `extra` types are predefined.
+     *
+     * This allows you to set the `state`, `dispatch` and `extra` types once,
+     * eliminating the need to specify them with every `addListener` call.
+     *
+     * @returns A pre-typed `addListener` with the state, dispatch and extra types already defined.
+     *
+     * @example
+     * ```ts
+     * import { addListener } from '@reduxjs/toolkit'
+     *
+     * export const addAppListener = addListener.withTypes<RootState, AppDispatch, ExtraArguments>()
+     * ```
+     *
+     * @template OverrideStateType - The specific type of state the middleware listener operates on.
+     * @template OverrideDispatchType - The specific type of the dispatch function.
+     * @template OverrideExtraArgument - The specific type of the extra object.
+     *
+     * @since 2.1.0
+     */
+    withTypes: <
+      OverrideStateType extends StateType,
+      OverrideDispatchType extends Dispatch = ThunkDispatch<
+        OverrideStateType,
+        unknown,
+        UnknownAction
+      >,
+      OverrideExtraArgument = unknown,
+    >() => TypedAddListener<
+      OverrideStateType,
+      OverrideDispatchType,
+      OverrideExtraArgument
+    >
+  }
+
+/**
+ * A "pre-typed" version of `removeListenerAction`, so the listener args are well-typed
+ *
+ * @public
+ */
+export type TypedRemoveListener<
+  StateType,
+  DispatchType extends Dispatch = ThunkDispatch<
+    StateType,
+    unknown,
+    UnknownAction
+  >,
+  ExtraArgument = unknown,
+  Payload = ListenerEntry<StateType, DispatchType>,
+  T extends string = 'listenerMiddleware/remove',
+> = BaseActionCreator<Payload, T> &
+  AddListenerOverloads<
+    PayloadAction<Payload, T>,
+    StateType,
+    DispatchType,
+    ExtraArgument,
+    UnsubscribeListenerOptions
+  > & {
+    /**
+     * Creates a "pre-typed" version of `removeListener`
+     * where the `state`, `dispatch` and `extra` types are predefined.
+     *
+     * This allows you to set the `state`, `dispatch` and `extra` types once,
+     * eliminating the need to specify them with every `removeListener` call.
+     *
+     * @returns A pre-typed `removeListener` with the state, dispatch and extra
+     * types already defined.
+     *
+     * @example
+     * ```ts
+     * import { removeListener } from '@reduxjs/toolkit'
+     *
+     * export const removeAppListener = removeListener.withTypes<
+     *   RootState,
+     *   AppDispatch,
+     *   ExtraArguments
+     * >()
+     * ```
+     *
+     * @template OverrideStateType - The specific type of state the middleware listener operates on.
+     * @template OverrideDispatchType - The specific type of the dispatch function.
+     * @template OverrideExtraArgument - The specific type of the extra object.
+     *
+     * @since 2.1.0
+     */
+    withTypes: <
+      OverrideStateType extends StateType,
+      OverrideDispatchType extends Dispatch = ThunkDispatch<
+        OverrideStateType,
+        unknown,
+        UnknownAction
+      >,
+      OverrideExtraArgument = unknown,
+    >() => TypedRemoveListener<
+      OverrideStateType,
+      OverrideDispatchType,
+      OverrideExtraArgument
+    >
+  }
+
+/**
+ * A "pre-typed" version of `middleware.startListening`, so the listener args are well-typed
+ *
+ * @public
+ */
+export type TypedStartListening<
+  StateType,
+  DispatchType extends Dispatch = ThunkDispatch<
+    StateType,
+    unknown,
+    UnknownAction
+  >,
+  ExtraArgument = unknown,
+> = AddListenerOverloads<
+  UnsubscribeListener,
+  StateType,
+  DispatchType,
+  ExtraArgument
+> & {
+  /**
+   * Creates a "pre-typed" version of
+   * {@linkcode ListenerMiddlewareInstance.startListening startListening}
+   * where the `state`, `dispatch` and `extra` types are predefined.
+   *
+   * This allows you to set the `state`, `dispatch` and `extra` types once,
+   * eliminating the need to specify them with every
+   * {@linkcode ListenerMiddlewareInstance.startListening startListening} call.
+   *
+   * @returns A pre-typed `startListening` with the state, dispatch and extra types already defined.
+   *
+   * @example
+   * ```ts
+   * import { createListenerMiddleware } from '@reduxjs/toolkit'
+   *
+   * const listenerMiddleware = createListenerMiddleware()
+   *
+   * export const startAppListening = listenerMiddleware.startListening.withTypes<
+   *   RootState,
+   *   AppDispatch,
+   *   ExtraArguments
+   * >()
+   * ```
+   *
+   * @template OverrideStateType - The specific type of state the middleware listener operates on.
+   * @template OverrideDispatchType - The specific type of the dispatch function.
+   * @template OverrideExtraArgument - The specific type of the extra object.
+   *
+   * @since 2.1.0
+   */
+  withTypes: <
+    OverrideStateType extends StateType,
+    OverrideDispatchType extends Dispatch = ThunkDispatch<
+      OverrideStateType,
+      unknown,
+      UnknownAction
+    >,
+    OverrideExtraArgument = unknown,
+  >() => TypedStartListening<
+    OverrideStateType,
+    OverrideDispatchType,
+    OverrideExtraArgument
+  >
+}
+
+/**
+ * A "pre-typed" version of `middleware.stopListening`, so the listener args are well-typed
+ *
+ * @public
+ */
+export type TypedStopListening<
+  StateType,
+  DispatchType extends Dispatch = ThunkDispatch<
+    StateType,
+    unknown,
+    UnknownAction
+  >,
+  ExtraArgument = unknown,
+> = RemoveListenerOverloads<StateType, DispatchType, ExtraArgument> & {
+  /**
+   * Creates a "pre-typed" version of
+   * {@linkcode ListenerMiddlewareInstance.stopListening stopListening}
+   * where the `state`, `dispatch` and `extra` types are predefined.
+   *
+   * This allows you to set the `state`, `dispatch` and `extra` types once,
+   * eliminating the need to specify them with every
+   * {@linkcode ListenerMiddlewareInstance.stopListening stopListening} call.
+   *
+   * @returns A pre-typed `stopListening` with the state, dispatch and extra types already defined.
+   *
+   * @example
+   * ```ts
+   * import { createListenerMiddleware } from '@reduxjs/toolkit'
+   *
+   * const listenerMiddleware = createListenerMiddleware()
+   *
+   * export const stopAppListening = listenerMiddleware.stopListening.withTypes<
+   *   RootState,
+   *   AppDispatch,
+   *   ExtraArguments
+   * >()
+   * ```
+   *
+   * @template OverrideStateType - The specific type of state the middleware listener operates on.
+   * @template OverrideDispatchType - The specific type of the dispatch function.
+   * @template OverrideExtraArgument - The specific type of the extra object.
+   *
+   * @since 2.1.0
+   */
+  withTypes: <
+    OverrideStateType extends StateType,
+    OverrideDispatchType extends Dispatch = ThunkDispatch<
+      OverrideStateType,
+      unknown,
+      UnknownAction
+    >,
+    OverrideExtraArgument = unknown,
+  >() => TypedStopListening<
+    OverrideStateType,
+    OverrideDispatchType,
+    OverrideExtraArgument
+  >
+}
+
+/**
+ * A "pre-typed" version of `createListenerEntry`, so the listener args are well-typed
+ *
+ * @public
+ */
+export type TypedCreateListenerEntry<
+  StateType,
+  DispatchType extends Dispatch = ThunkDispatch<
+    StateType,
+    unknown,
+    UnknownAction
+  >,
+  ExtraArgument = unknown,
+> = AddListenerOverloads<
+  ListenerEntry<StateType, DispatchType>,
+  StateType,
+  DispatchType,
+  ExtraArgument
+> & {
+  /**
+   * Creates a "pre-typed" version of `createListenerEntry`
+   * where the `state`, `dispatch` and `extra` types are predefined.
+   *
+   * This allows you to set the `state`, `dispatch` and `extra` types once, eliminating
+   * the need to specify them with every `createListenerEntry` call.
+   *
+   * @returns A pre-typed `createListenerEntry` with the state, dispatch and extra
+   * types already defined.
+   *
+   * @example
+   * ```ts
+   * import { createListenerEntry } from '@reduxjs/toolkit'
+   *
+   * export const createAppListenerEntry = createListenerEntry.withTypes<
+   *   RootState,
+   *   AppDispatch,
+   *   ExtraArguments
+   * >()
+   * ```
+   *
+   * @template OverrideStateType - The specific type of state the middleware listener operates on.
+   * @template OverrideDispatchType - The specific type of the dispatch function.
+   * @template OverrideExtraArgument - The specific type of the extra object.
+   *
+   * @since 2.1.0
+   */
+  withTypes: <
+    OverrideStateType extends StateType,
+    OverrideDispatchType extends Dispatch = ThunkDispatch<
+      OverrideStateType,
+      unknown,
+      UnknownAction
+    >,
+    OverrideExtraArgument = unknown,
+  >() => TypedStopListening<
+    OverrideStateType,
+    OverrideDispatchType,
+    OverrideExtraArgument
+  >
+}
+
+/**
+ * Internal Types
+ */
+
+/** @internal An single listener entry */
+export type ListenerEntry<
+  State = unknown,
+  DispatchType extends Dispatch = Dispatch,
+> = {
+  id: string
+  effect: ListenerEffect<any, State, DispatchType>
+  unsubscribe: () => void
+  pending: Set<AbortController>
+  type?: string
+  predicate: ListenerPredicate<UnknownAction, State>
+}
+
+/**
+ * @internal
+ * A shorthand form of the accepted args, solely so that `createListenerEntry` has validly-typed conditional logic when checking the options contents
+ */
+export type FallbackAddListenerOptions = {
+  actionCreator?: TypedActionCreatorWithMatchFunction<string>
+  type?: string
+  matcher?: MatchFunction<any>
+  predicate?: ListenerPredicate<any, any>
+} & { effect: ListenerEffect<any, any, any> }
+
+/**
+ * Utility Types
+ */
+
+/** @public */
+export type GuardedType<T> = T extends (x: any, ...args: any[]) => x is infer T
+  ? T
+  : never
+
+/** @public */
+export type ListenerPredicateGuardedActionType<T> =
+  T extends ListenerPredicate<infer ActionType, any> ? ActionType : never
Index: node_modules/@reduxjs/toolkit/src/listenerMiddleware/utils.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/listenerMiddleware/utils.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/listenerMiddleware/utils.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,30 @@
+export const assertFunction: (
+  func: unknown,
+  expected: string,
+) => asserts func is (...args: unknown[]) => unknown = (
+  func: unknown,
+  expected: string,
+) => {
+  if (typeof func !== 'function') {
+    throw new TypeError(`${expected} is not a function`)
+  }
+}
+
+export const noop = () => {}
+
+export const catchRejection = <T>(
+  promise: Promise<T>,
+  onError = noop,
+): Promise<T> => {
+  promise.catch(onError)
+
+  return promise
+}
+
+export const addAbortSignalListener = (
+  abortSignal: AbortSignal,
+  callback: (evt: Event) => void,
+) => {
+  abortSignal.addEventListener('abort', callback, { once: true })
+  return () => abortSignal.removeEventListener('abort', callback)
+}
Index: node_modules/@reduxjs/toolkit/src/mapBuilders.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/mapBuilders.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/mapBuilders.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,299 @@
+import type { Action } from 'redux'
+import type {
+  CaseReducer,
+  CaseReducers,
+  ActionMatcherDescriptionCollection,
+} from './createReducer'
+import type { TypeGuard } from './tsHelpers'
+import type { AsyncThunk, AsyncThunkConfig } from './createAsyncThunk'
+
+export type AsyncThunkReducers<
+  State,
+  ThunkArg extends any,
+  Returned = unknown,
+  ThunkApiConfig extends AsyncThunkConfig = {},
+> = {
+  pending?: CaseReducer<
+    State,
+    ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['pending']>
+  >
+  rejected?: CaseReducer<
+    State,
+    ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected']>
+  >
+  fulfilled?: CaseReducer<
+    State,
+    ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['fulfilled']>
+  >
+  settled?: CaseReducer<
+    State,
+    ReturnType<
+      AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected' | 'fulfilled']
+    >
+  >
+}
+
+export type TypedActionCreator<Type extends string> = {
+  (...args: any[]): Action<Type>
+  type: Type
+}
+
+/**
+ * A builder for an action <-> reducer map.
+ *
+ * @public
+ */
+export interface ActionReducerMapBuilder<State> {
+  /**
+   * Adds a case reducer to handle a single exact action type.
+   * @remarks
+   * All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.
+   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
+   * @param reducer - The actual case reducer function.
+   */
+  addCase<ActionCreator extends TypedActionCreator<string>>(
+    actionCreator: ActionCreator,
+    reducer: CaseReducer<State, ReturnType<ActionCreator>>,
+  ): ActionReducerMapBuilder<State>
+  /**
+   * Adds a case reducer to handle a single exact action type.
+   * @remarks
+   * All calls to `builder.addCase` must come before any calls to `builder.addAsyncThunk`, `builder.addMatcher` or `builder.addDefaultCase`.
+   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
+   * @param reducer - The actual case reducer function.
+   */
+  addCase<Type extends string, A extends Action<Type>>(
+    type: Type,
+    reducer: CaseReducer<State, A>,
+  ): ActionReducerMapBuilder<State>
+
+  /**
+   * Adds case reducers to handle actions based on a `AsyncThunk` action creator.
+   * @remarks
+   * All calls to `builder.addAsyncThunk` must come before after any calls to `builder.addCase` and before any calls to `builder.addMatcher` or `builder.addDefaultCase`.
+   * @param asyncThunk - The async thunk action creator itself.
+   * @param reducers - A mapping from each of the `AsyncThunk` action types to the case reducer that should handle those actions.
+   * @example
+```ts no-transpile
+import { createAsyncThunk, createReducer } from '@reduxjs/toolkit'
+
+const fetchUserById = createAsyncThunk('users/fetchUser', async (id) => {
+  const response = await fetch(`https://reqres.in/api/users/${id}`)
+  return (await response.json()).data
+})
+
+const reducer = createReducer(initialState, (builder) => {
+  builder.addAsyncThunk(fetchUserById, {
+    pending: (state, action) => {
+      state.fetchUserById.loading = 'pending'
+    },
+    fulfilled: (state, action) => {
+      state.fetchUserById.data = action.payload
+    },
+    rejected: (state, action) => {
+      state.fetchUserById.error = action.error
+    },
+    settled: (state, action) => {
+      state.fetchUserById.loading = action.meta.requestStatus
+    },
+  })
+})
+   */
+  addAsyncThunk<
+    Returned,
+    ThunkArg,
+    ThunkApiConfig extends AsyncThunkConfig = {},
+  >(
+    asyncThunk: AsyncThunk<Returned, ThunkArg, ThunkApiConfig>,
+    reducers: AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig>,
+  ): Omit<ActionReducerMapBuilder<State>, 'addCase'>
+
+  /**
+   * Allows you to match your incoming actions against your own filter function instead of only the `action.type` property.
+   * @remarks
+   * If multiple matcher reducers match, all of them will be executed in the order
+   * they were defined in - even if a case reducer already matched.
+   * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and `builder.addAsyncThunk` and before any calls to `builder.addDefaultCase`.
+   * @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)
+   *   function
+   * @param reducer - The actual case reducer function.
+   *
+   * @example
+```ts
+import {
+  createAction,
+  createReducer,
+  AsyncThunk,
+  UnknownAction,
+} from "@reduxjs/toolkit";
+
+type GenericAsyncThunk = AsyncThunk<unknown, unknown, any>;
+
+type PendingAction = ReturnType<GenericAsyncThunk["pending"]>;
+type RejectedAction = ReturnType<GenericAsyncThunk["rejected"]>;
+type FulfilledAction = ReturnType<GenericAsyncThunk["fulfilled"]>;
+
+const initialState: Record<string, string> = {};
+const resetAction = createAction("reset-tracked-loading-state");
+
+function isPendingAction(action: UnknownAction): action is PendingAction {
+  return typeof action.type === "string" && action.type.endsWith("/pending");
+}
+
+const reducer = createReducer(initialState, (builder) => {
+  builder
+    .addCase(resetAction, () => initialState)
+    // matcher can be defined outside as a type predicate function
+    .addMatcher(isPendingAction, (state, action) => {
+      state[action.meta.requestId] = "pending";
+    })
+    .addMatcher(
+      // matcher can be defined inline as a type predicate function
+      (action): action is RejectedAction => action.type.endsWith("/rejected"),
+      (state, action) => {
+        state[action.meta.requestId] = "rejected";
+      }
+    )
+    // matcher can just return boolean and the matcher can receive a generic argument
+    .addMatcher<FulfilledAction>(
+      (action) => action.type.endsWith("/fulfilled"),
+      (state, action) => {
+        state[action.meta.requestId] = "fulfilled";
+      }
+    );
+});
+```
+   */
+  addMatcher<A>(
+    matcher: TypeGuard<A> | ((action: any) => boolean),
+    reducer: CaseReducer<State, A extends Action ? A : A & Action>,
+  ): Omit<ActionReducerMapBuilder<State>, 'addCase' | 'addAsyncThunk'>
+
+  /**
+   * Adds a "default case" reducer that is executed if no case reducer and no matcher
+   * reducer was executed for this action.
+   * @param reducer - The fallback "default case" reducer function.
+   *
+   * @example
+```ts
+import { createReducer } from '@reduxjs/toolkit'
+const initialState = { otherActions: 0 }
+const reducer = createReducer(initialState, builder => {
+  builder
+    // .addCase(...)
+    // .addMatcher(...)
+    .addDefaultCase((state, action) => {
+      state.otherActions++
+    })
+})
+```
+   */
+  addDefaultCase(reducer: CaseReducer<State, Action>): {}
+}
+
+export function executeReducerBuilderCallback<S>(
+  builderCallback: (builder: ActionReducerMapBuilder<S>) => void,
+): [
+  CaseReducers<S, any>,
+  ActionMatcherDescriptionCollection<S>,
+  CaseReducer<S, Action> | undefined,
+] {
+  const actionsMap: CaseReducers<S, any> = {}
+  const actionMatchers: ActionMatcherDescriptionCollection<S> = []
+  let defaultCaseReducer: CaseReducer<S, Action> | undefined
+  const builder = {
+    addCase(
+      typeOrActionCreator: string | TypedActionCreator<any>,
+      reducer: CaseReducer<S>,
+    ) {
+      if (process.env.NODE_ENV !== 'production') {
+        /*
+         to keep the definition by the user in line with actual behavior,
+         we enforce `addCase` to always be called before calling `addMatcher`
+         as matching cases take precedence over matchers
+         */
+        if (actionMatchers.length > 0) {
+          throw new Error(
+            '`builder.addCase` should only be called before calling `builder.addMatcher`',
+          )
+        }
+        if (defaultCaseReducer) {
+          throw new Error(
+            '`builder.addCase` should only be called before calling `builder.addDefaultCase`',
+          )
+        }
+      }
+      const type =
+        typeof typeOrActionCreator === 'string'
+          ? typeOrActionCreator
+          : typeOrActionCreator.type
+      if (!type) {
+        throw new Error(
+          '`builder.addCase` cannot be called with an empty action type',
+        )
+      }
+      if (type in actionsMap) {
+        throw new Error(
+          '`builder.addCase` cannot be called with two reducers for the same action type ' +
+            `'${type}'`,
+        )
+      }
+      actionsMap[type] = reducer
+      return builder
+    },
+    addAsyncThunk<
+      Returned,
+      ThunkArg,
+      ThunkApiConfig extends AsyncThunkConfig = {},
+    >(
+      asyncThunk: AsyncThunk<Returned, ThunkArg, ThunkApiConfig>,
+      reducers: AsyncThunkReducers<S, ThunkArg, Returned, ThunkApiConfig>,
+    ) {
+      if (process.env.NODE_ENV !== 'production') {
+        // since this uses both action cases and matchers, we can't enforce the order in runtime other than checking for default case
+        if (defaultCaseReducer) {
+          throw new Error(
+            '`builder.addAsyncThunk` should only be called before calling `builder.addDefaultCase`',
+          )
+        }
+      }
+      if (reducers.pending)
+        actionsMap[asyncThunk.pending.type] = reducers.pending
+      if (reducers.rejected)
+        actionsMap[asyncThunk.rejected.type] = reducers.rejected
+      if (reducers.fulfilled)
+        actionsMap[asyncThunk.fulfilled.type] = reducers.fulfilled
+      if (reducers.settled)
+        actionMatchers.push({
+          matcher: asyncThunk.settled,
+          reducer: reducers.settled,
+        })
+      return builder
+    },
+    addMatcher<A>(
+      matcher: TypeGuard<A>,
+      reducer: CaseReducer<S, A extends Action ? A : A & Action>,
+    ) {
+      if (process.env.NODE_ENV !== 'production') {
+        if (defaultCaseReducer) {
+          throw new Error(
+            '`builder.addMatcher` should only be called before calling `builder.addDefaultCase`',
+          )
+        }
+      }
+      actionMatchers.push({ matcher, reducer })
+      return builder
+    },
+    addDefaultCase(reducer: CaseReducer<S, Action>) {
+      if (process.env.NODE_ENV !== 'production') {
+        if (defaultCaseReducer) {
+          throw new Error('`builder.addDefaultCase` can only be called once')
+        }
+      }
+      defaultCaseReducer = reducer
+      return builder
+    },
+  }
+  builderCallback(builder)
+  return [actionsMap, actionMatchers, defaultCaseReducer]
+}
Index: node_modules/@reduxjs/toolkit/src/matchers.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/matchers.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/matchers.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,365 @@
+import type {
+  ActionFromMatcher,
+  Matcher,
+  UnionToIntersection,
+} from './tsHelpers'
+import { hasMatchFunction } from './tsHelpers'
+import type {
+  AsyncThunk,
+  AsyncThunkFulfilledActionCreator,
+  AsyncThunkPendingActionCreator,
+  AsyncThunkRejectedActionCreator,
+} from './createAsyncThunk'
+
+/** @public */
+export type ActionMatchingAnyOf<Matchers extends Matcher<any>[]> =
+  ActionFromMatcher<Matchers[number]>
+
+/** @public */
+export type ActionMatchingAllOf<Matchers extends Matcher<any>[]> =
+  UnionToIntersection<ActionMatchingAnyOf<Matchers>>
+
+const matches = (matcher: Matcher<any>, action: any) => {
+  if (hasMatchFunction(matcher)) {
+    return matcher.match(action)
+  } else {
+    return matcher(action)
+  }
+}
+
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action matches any one of the supplied type guards or action
+ * creators.
+ *
+ * @param matchers The type guards or action creators to match against.
+ *
+ * @public
+ */
+export function isAnyOf<Matchers extends Matcher<any>[]>(
+  ...matchers: Matchers
+) {
+  return (action: any): action is ActionMatchingAnyOf<Matchers> => {
+    return matchers.some((matcher) => matches(matcher, action))
+  }
+}
+
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action matches all of the supplied type guards or action
+ * creators.
+ *
+ * @param matchers The type guards or action creators to match against.
+ *
+ * @public
+ */
+export function isAllOf<Matchers extends Matcher<any>[]>(
+  ...matchers: Matchers
+) {
+  return (action: any): action is ActionMatchingAllOf<Matchers> => {
+    return matchers.every((matcher) => matches(matcher, action))
+  }
+}
+
+/**
+ * @param action A redux action
+ * @param validStatus An array of valid meta.requestStatus values
+ *
+ * @internal
+ */
+export function hasExpectedRequestMetadata(
+  action: any,
+  validStatus: readonly string[],
+) {
+  if (!action || !action.meta) return false
+
+  const hasValidRequestId = typeof action.meta.requestId === 'string'
+  const hasValidRequestStatus =
+    validStatus.indexOf(action.meta.requestStatus) > -1
+
+  return hasValidRequestId && hasValidRequestStatus
+}
+
+function isAsyncThunkArray(a: [any] | AnyAsyncThunk[]): a is AnyAsyncThunk[] {
+  return (
+    typeof a[0] === 'function' &&
+    'pending' in a[0] &&
+    'fulfilled' in a[0] &&
+    'rejected' in a[0]
+  )
+}
+
+export type UnknownAsyncThunkPendingAction = ReturnType<
+  AsyncThunkPendingActionCreator<unknown>
+>
+
+export type PendingActionFromAsyncThunk<T extends AnyAsyncThunk> =
+  ActionFromMatcher<T['pending']>
+
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action was created by an async thunk action creator, and that
+ * the action is pending.
+ *
+ * @public
+ */
+export function isPending(): (
+  action: any,
+) => action is UnknownAsyncThunkPendingAction
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action belongs to one of the provided async thunk action creators,
+ * and that the action is pending.
+ *
+ * @param asyncThunks (optional) The async thunk action creators to match against.
+ *
+ * @public
+ */
+export function isPending<
+  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
+>(
+  ...asyncThunks: AsyncThunks
+): (action: any) => action is PendingActionFromAsyncThunk<AsyncThunks[number]>
+/**
+ * Tests if `action` is a pending thunk action
+ * @public
+ */
+export function isPending(action: any): action is UnknownAsyncThunkPendingAction
+export function isPending<
+  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
+>(...asyncThunks: AsyncThunks | [any]) {
+  if (asyncThunks.length === 0) {
+    return (action: any) => hasExpectedRequestMetadata(action, ['pending'])
+  }
+
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isPending()(asyncThunks[0])
+  }
+
+  return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.pending))
+}
+
+export type UnknownAsyncThunkRejectedAction = ReturnType<
+  AsyncThunkRejectedActionCreator<unknown, unknown>
+>
+
+export type RejectedActionFromAsyncThunk<T extends AnyAsyncThunk> =
+  ActionFromMatcher<T['rejected']>
+
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action was created by an async thunk action creator, and that
+ * the action is rejected.
+ *
+ * @public
+ */
+export function isRejected(): (
+  action: any,
+) => action is UnknownAsyncThunkRejectedAction
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action belongs to one of the provided async thunk action creators,
+ * and that the action is rejected.
+ *
+ * @param asyncThunks (optional) The async thunk action creators to match against.
+ *
+ * @public
+ */
+export function isRejected<
+  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
+>(
+  ...asyncThunks: AsyncThunks
+): (action: any) => action is RejectedActionFromAsyncThunk<AsyncThunks[number]>
+/**
+ * Tests if `action` is a rejected thunk action
+ * @public
+ */
+export function isRejected(
+  action: any,
+): action is UnknownAsyncThunkRejectedAction
+export function isRejected<
+  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
+>(...asyncThunks: AsyncThunks | [any]) {
+  if (asyncThunks.length === 0) {
+    return (action: any) => hasExpectedRequestMetadata(action, ['rejected'])
+  }
+
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isRejected()(asyncThunks[0])
+  }
+
+  return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.rejected))
+}
+
+export type UnknownAsyncThunkRejectedWithValueAction = ReturnType<
+  AsyncThunkRejectedActionCreator<unknown, unknown>
+>
+
+export type RejectedWithValueActionFromAsyncThunk<T extends AnyAsyncThunk> =
+  ActionFromMatcher<T['rejected']> &
+    (T extends AsyncThunk<any, any, { rejectValue: infer RejectedValue }>
+      ? { payload: RejectedValue }
+      : unknown)
+
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action was created by an async thunk action creator, and that
+ * the action is rejected with value.
+ *
+ * @public
+ */
+export function isRejectedWithValue(): (
+  action: any,
+) => action is UnknownAsyncThunkRejectedAction
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action belongs to one of the provided async thunk action creators,
+ * and that the action is rejected with value.
+ *
+ * @param asyncThunks (optional) The async thunk action creators to match against.
+ *
+ * @public
+ */
+export function isRejectedWithValue<
+  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
+>(
+  ...asyncThunks: AsyncThunks
+): (
+  action: any,
+) => action is RejectedWithValueActionFromAsyncThunk<AsyncThunks[number]>
+/**
+ * Tests if `action` is a rejected thunk action with value
+ * @public
+ */
+export function isRejectedWithValue(
+  action: any,
+): action is UnknownAsyncThunkRejectedAction
+export function isRejectedWithValue<
+  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
+>(...asyncThunks: AsyncThunks | [any]) {
+  const hasFlag = (action: any): action is any => {
+    return action && action.meta && action.meta.rejectedWithValue
+  }
+
+  if (asyncThunks.length === 0) {
+    return isAllOf(isRejected(...asyncThunks), hasFlag)
+  }
+
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isRejectedWithValue()(asyncThunks[0])
+  }
+
+  return isAllOf(isRejected(...asyncThunks), hasFlag)
+}
+
+export type UnknownAsyncThunkFulfilledAction = ReturnType<
+  AsyncThunkFulfilledActionCreator<unknown, unknown>
+>
+
+export type FulfilledActionFromAsyncThunk<T extends AnyAsyncThunk> =
+  ActionFromMatcher<T['fulfilled']>
+
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action was created by an async thunk action creator, and that
+ * the action is fulfilled.
+ *
+ * @public
+ */
+export function isFulfilled(): (
+  action: any,
+) => action is UnknownAsyncThunkFulfilledAction
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action belongs to one of the provided async thunk action creators,
+ * and that the action is fulfilled.
+ *
+ * @param asyncThunks (optional) The async thunk action creators to match against.
+ *
+ * @public
+ */
+export function isFulfilled<
+  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
+>(
+  ...asyncThunks: AsyncThunks
+): (action: any) => action is FulfilledActionFromAsyncThunk<AsyncThunks[number]>
+/**
+ * Tests if `action` is a fulfilled thunk action
+ * @public
+ */
+export function isFulfilled(
+  action: any,
+): action is UnknownAsyncThunkFulfilledAction
+export function isFulfilled<
+  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
+>(...asyncThunks: AsyncThunks | [any]) {
+  if (asyncThunks.length === 0) {
+    return (action: any) => hasExpectedRequestMetadata(action, ['fulfilled'])
+  }
+
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isFulfilled()(asyncThunks[0])
+  }
+
+  return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.fulfilled))
+}
+
+export type UnknownAsyncThunkAction =
+  | UnknownAsyncThunkPendingAction
+  | UnknownAsyncThunkRejectedAction
+  | UnknownAsyncThunkFulfilledAction
+
+export type AnyAsyncThunk = {
+  pending: { match: (action: any) => action is any }
+  fulfilled: { match: (action: any) => action is any }
+  rejected: { match: (action: any) => action is any }
+}
+
+export type ActionsFromAsyncThunk<T extends AnyAsyncThunk> =
+  | ActionFromMatcher<T['pending']>
+  | ActionFromMatcher<T['fulfilled']>
+  | ActionFromMatcher<T['rejected']>
+
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action was created by an async thunk action creator.
+ *
+ * @public
+ */
+export function isAsyncThunkAction(): (
+  action: any,
+) => action is UnknownAsyncThunkAction
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action belongs to one of the provided async thunk action creators.
+ *
+ * @param asyncThunks (optional) The async thunk action creators to match against.
+ *
+ * @public
+ */
+export function isAsyncThunkAction<
+  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
+>(
+  ...asyncThunks: AsyncThunks
+): (action: any) => action is ActionsFromAsyncThunk<AsyncThunks[number]>
+/**
+ * Tests if `action` is a thunk action
+ * @public
+ */
+export function isAsyncThunkAction(
+  action: any,
+): action is UnknownAsyncThunkAction
+export function isAsyncThunkAction<
+  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
+>(...asyncThunks: AsyncThunks | [any]) {
+  if (asyncThunks.length === 0) {
+    return (action: any) =>
+      hasExpectedRequestMetadata(action, ['pending', 'fulfilled', 'rejected'])
+  }
+
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isAsyncThunkAction()(asyncThunks[0])
+  }
+
+  return isAnyOf(...asyncThunks.flatMap(asyncThunk => [asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled]))
+}
Index: node_modules/@reduxjs/toolkit/src/nanoid.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/nanoid.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/nanoid.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,20 @@
+// Borrowed from https://github.com/ai/nanoid/blob/3.0.2/non-secure/index.js
+// This alphabet uses `A-Za-z0-9_-` symbols. A genetic algorithm helped
+// optimize the gzip compression for this alphabet.
+let urlAlphabet =
+  'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW'
+
+/**
+ *
+ * @public
+ */
+export let nanoid = (size = 21) => {
+  let id = ''
+  // A compact alternative for `for (var i = 0; i < step; i++)`.
+  let i = size
+  while (i--) {
+    // `| 0` is more compact and faster than `Math.floor()`.
+    id += urlAlphabet[(Math.random() * 64) | 0]
+  }
+  return id
+}
Index: node_modules/@reduxjs/toolkit/src/query/HandledError.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/HandledError.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/HandledError.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,6 @@
+export class HandledError {
+  constructor(
+    public readonly value: any,
+    public readonly meta: any = undefined,
+  ) {}
+}
Index: node_modules/@reduxjs/toolkit/src/query/apiTypes.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/apiTypes.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/apiTypes.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,124 @@
+import type { UnknownAction } from '@reduxjs/toolkit'
+import type { BaseQueryFn } from './baseQueryTypes'
+import type { CombinedState, CoreModule, QueryKeys } from './core'
+import type { ApiModules } from './core/module'
+import type { CreateApiOptions } from './createApi'
+import type {
+  EndpointBuilder,
+  EndpointDefinition,
+  EndpointDefinitions,
+  UpdateDefinitions,
+} from './endpointDefinitions'
+import type {
+  NoInfer,
+  UnionToIntersection,
+  WithRequiredProp,
+} from './tsHelpers'
+
+export type ModuleName = keyof ApiModules<any, any, any, any>
+
+export type Module<Name extends ModuleName> = {
+  name: Name
+  init<
+    BaseQuery extends BaseQueryFn,
+    Definitions extends EndpointDefinitions,
+    ReducerPath extends string,
+    TagTypes extends string,
+  >(
+    api: Api<BaseQuery, EndpointDefinitions, ReducerPath, TagTypes, ModuleName>,
+    options: WithRequiredProp<
+      CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>,
+      | 'reducerPath'
+      | 'serializeQueryArgs'
+      | 'keepUnusedDataFor'
+      | 'refetchOnMountOrArgChange'
+      | 'refetchOnFocus'
+      | 'refetchOnReconnect'
+      | 'invalidationBehavior'
+      | 'tagTypes'
+    >,
+    context: ApiContext<Definitions>,
+  ): {
+    injectEndpoint(
+      endpointName: string,
+      definition: EndpointDefinition<any, any, any, any>,
+    ): void
+  }
+}
+
+export interface ApiContext<Definitions extends EndpointDefinitions> {
+  apiUid: string
+  endpointDefinitions: Definitions
+  batch(cb: () => void): void
+  extractRehydrationInfo: (
+    action: UnknownAction,
+  ) => CombinedState<any, any, any> | undefined
+  hasRehydrationInfo: (action: UnknownAction) => boolean
+}
+
+export const getEndpointDefinition = <
+  Definitions extends EndpointDefinitions,
+  EndpointName extends keyof Definitions,
+>(
+  context: ApiContext<Definitions>,
+  endpointName: EndpointName,
+) => context.endpointDefinitions[endpointName]
+
+export type Api<
+  BaseQuery extends BaseQueryFn,
+  Definitions extends EndpointDefinitions,
+  ReducerPath extends string,
+  TagTypes extends string,
+  Enhancers extends ModuleName = CoreModule,
+> = UnionToIntersection<
+  ApiModules<BaseQuery, Definitions, ReducerPath, TagTypes>[Enhancers]
+> & {
+  /**
+   * A function to inject the endpoints into the original API, but also give you that same API with correct types for these endpoints back. Useful with code-splitting.
+   */
+  injectEndpoints<NewDefinitions extends EndpointDefinitions>(_: {
+    endpoints: (
+      build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>,
+    ) => NewDefinitions
+    /**
+     * Optionally allows endpoints to be overridden if defined by multiple `injectEndpoints` calls.
+     *
+     * If set to `true`, will override existing endpoints with the new definition.
+     * If set to `'throw'`, will throw an error if an endpoint is redefined with a different definition.
+     * If set to `false` (or unset), will not override existing endpoints with the new definition, and log a warning in development.
+     */
+    overrideExisting?: boolean | 'throw'
+  }): Api<
+    BaseQuery,
+    Definitions & NewDefinitions,
+    ReducerPath,
+    TagTypes,
+    Enhancers
+  >
+  /**
+   *A function to enhance a generated API with additional information. Useful with code-generation.
+   */
+  enhanceEndpoints<
+    NewTagTypes extends string = never,
+    NewDefinitions extends EndpointDefinitions = never,
+  >(_: {
+    addTagTypes?: readonly NewTagTypes[]
+    endpoints?: UpdateDefinitions<
+      Definitions,
+      TagTypes | NoInfer<NewTagTypes>,
+      NewDefinitions
+    > extends infer NewDefinitions
+      ? {
+          [K in keyof NewDefinitions]?:
+            | Partial<NewDefinitions[K]>
+            | ((definition: NewDefinitions[K]) => void)
+        }
+      : never
+  }): Api<
+    BaseQuery,
+    UpdateDefinitions<Definitions, TagTypes | NewTagTypes, NewDefinitions>,
+    ReducerPath,
+    TagTypes | NewTagTypes,
+    Enhancers
+  >
+}
Index: node_modules/@reduxjs/toolkit/src/query/baseQueryTypes.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/baseQueryTypes.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/baseQueryTypes.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,101 @@
+import type { ThunkDispatch } from '@reduxjs/toolkit'
+import type { MaybePromise, UnwrapPromise } from './tsHelpers'
+
+export interface BaseQueryApi {
+  signal: AbortSignal
+  abort: (reason?: string) => void
+  dispatch: ThunkDispatch<any, any, any>
+  getState: () => unknown
+  extra: unknown
+  endpoint: string
+  type: 'query' | 'mutation'
+  /**
+   * Only available for queries: indicates if a query has been forced,
+   * i.e. it would have been fetched even if there would already be a cache entry
+   * (this does not mean that there is already a cache entry though!)
+   *
+   * This can be used to for example add a `Cache-Control: no-cache` header for
+   * invalidated queries.
+   */
+  forced?: boolean
+  /**
+   * Only available for queries: the cache key that was used to store the query result
+   */
+  queryCacheKey?: string
+}
+
+export type QueryReturnValue<T = unknown, E = unknown, M = unknown> =
+  | {
+      error: E
+      data?: undefined
+      meta?: M
+    }
+  | {
+      error?: undefined
+      data: T
+      meta?: M
+    }
+
+export type BaseQueryFn<
+  Args = any,
+  Result = unknown,
+  Error = unknown,
+  DefinitionExtraOptions = {},
+  Meta = {},
+> = (
+  args: Args,
+  api: BaseQueryApi,
+  extraOptions: DefinitionExtraOptions,
+) => MaybePromise<QueryReturnValue<Result, Error, Meta>>
+
+export type BaseQueryEnhancer<
+  AdditionalArgs = unknown,
+  AdditionalDefinitionExtraOptions = unknown,
+  Config = void,
+> = <BaseQuery extends BaseQueryFn>(
+  baseQuery: BaseQuery,
+  config: Config,
+) => BaseQueryFn<
+  BaseQueryArg<BaseQuery> & AdditionalArgs,
+  BaseQueryResult<BaseQuery>,
+  BaseQueryError<BaseQuery>,
+  BaseQueryExtraOptions<BaseQuery> & AdditionalDefinitionExtraOptions,
+  NonNullable<BaseQueryMeta<BaseQuery>>
+>
+
+/**
+ * @public
+ */
+export type BaseQueryResult<BaseQuery extends BaseQueryFn> =
+  UnwrapPromise<ReturnType<BaseQuery>> extends infer Unwrapped
+    ? Unwrapped extends { data: any }
+      ? Unwrapped['data']
+      : never
+    : never
+
+/**
+ * @public
+ */
+export type BaseQueryMeta<BaseQuery extends BaseQueryFn> = UnwrapPromise<
+  ReturnType<BaseQuery>
+>['meta']
+
+/**
+ * @public
+ */
+export type BaseQueryError<BaseQuery extends BaseQueryFn> = Exclude<
+  UnwrapPromise<ReturnType<BaseQuery>>,
+  { error?: undefined }
+>['error']
+
+/**
+ * @public
+ */
+export type BaseQueryArg<T extends (arg: any, ...args: any[]) => any> =
+  T extends (arg: infer A, ...args: any[]) => any ? A : any
+
+/**
+ * @public
+ */
+export type BaseQueryExtraOptions<BaseQuery extends BaseQueryFn> =
+  Parameters<BaseQuery>[2]
Index: node_modules/@reduxjs/toolkit/src/query/core/apiState.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/apiState.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/apiState.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,377 @@
+import type { SerializedError } from '@reduxjs/toolkit'
+import type { BaseQueryError } from '../baseQueryTypes'
+import type {
+  BaseEndpointDefinition,
+  EndpointDefinitions,
+  FullTagDescription,
+  InfiniteQueryDefinition,
+  MutationDefinition,
+  PageParamFrom,
+  QueryArgFromAnyQuery,
+  QueryDefinition,
+  ResultTypeFrom,
+} from '../endpointDefinitions'
+import type { Id, WithRequiredProp } from '../tsHelpers'
+
+export type QueryCacheKey = string & { _type: 'queryCacheKey' }
+export type QuerySubstateIdentifier = { queryCacheKey: QueryCacheKey }
+export type MutationSubstateIdentifier =
+  | { requestId: string; fixedCacheKey?: string }
+  | { requestId?: string; fixedCacheKey: string }
+
+export type RefetchConfigOptions = {
+  refetchOnMountOrArgChange: boolean | number
+  refetchOnReconnect: boolean
+  refetchOnFocus: boolean
+}
+
+export type InfiniteQueryConfigOptions<DataType, PageParam, QueryArg> = {
+  /**
+   * The initial page parameter to use for the first page fetch.
+   */
+  initialPageParam: PageParam
+  /**
+   * This function is required to automatically get the next cursor for infinite queries.
+   * The result will also be used to determine the value of `hasNextPage`.
+   */
+  getNextPageParam: (
+    lastPage: DataType,
+    allPages: Array<DataType>,
+    lastPageParam: PageParam,
+    allPageParams: Array<PageParam>,
+    queryArg: QueryArg,
+  ) => PageParam | undefined | null
+  /**
+   * This function can be set to automatically get the previous cursor for infinite queries.
+   * The result will also be used to determine the value of `hasPreviousPage`.
+   */
+  getPreviousPageParam?: (
+    firstPage: DataType,
+    allPages: Array<DataType>,
+    firstPageParam: PageParam,
+    allPageParams: Array<PageParam>,
+    queryArg: QueryArg,
+  ) => PageParam | undefined | null
+  /**
+   * If specified, only keep this many pages in cache at once.
+   * If additional pages are fetched, older pages in the other
+   * direction will be dropped from the cache.
+   */
+  maxPages?: number
+  /**
+   * Defaults to `true`. When this is `true` and an infinite query endpoint is refetched
+   * (due to tag invalidation, polling, arg change configuration, or manual refetching),
+   * RTK Query will try to sequentially refetch all pages currently in the cache.
+   * When `false` only the first page will be refetched.
+   */
+  refetchCachedPages?: boolean
+}
+
+export type InfiniteData<DataType, PageParam> = {
+  pages: Array<DataType>
+  pageParams: Array<PageParam>
+}
+
+// NOTE: DO NOT import and use this for runtime comparisons internally,
+// except in the RTKQ React package. Use the string versions just below this.
+// ESBuild auto-inlines TS enums, which bloats our bundle with many repeated
+// constants like "initialized":
+// https://github.com/evanw/esbuild/releases/tag/v0.14.7
+// We still have to use this in the React package since we don't publicly export
+// the string constants below.
+/**
+ * Strings describing the query state at any given time.
+ */
+export enum QueryStatus {
+  uninitialized = 'uninitialized',
+  pending = 'pending',
+  fulfilled = 'fulfilled',
+  rejected = 'rejected',
+}
+
+// Use these string constants for runtime comparisons internally
+export const STATUS_UNINITIALIZED = QueryStatus.uninitialized
+export const STATUS_PENDING = QueryStatus.pending
+export const STATUS_FULFILLED = QueryStatus.fulfilled
+export const STATUS_REJECTED = QueryStatus.rejected
+
+export type RequestStatusFlags =
+  | {
+      status: QueryStatus.uninitialized
+      isUninitialized: true
+      isLoading: false
+      isSuccess: false
+      isError: false
+    }
+  | {
+      status: QueryStatus.pending
+      isUninitialized: false
+      isLoading: true
+      isSuccess: false
+      isError: false
+    }
+  | {
+      status: QueryStatus.fulfilled
+      isUninitialized: false
+      isLoading: false
+      isSuccess: true
+      isError: false
+    }
+  | {
+      status: QueryStatus.rejected
+      isUninitialized: false
+      isLoading: false
+      isSuccess: false
+      isError: true
+    }
+
+export function getRequestStatusFlags(status: QueryStatus): RequestStatusFlags {
+  return {
+    status,
+    isUninitialized: status === STATUS_UNINITIALIZED,
+    isLoading: status === STATUS_PENDING,
+    isSuccess: status === STATUS_FULFILLED,
+    isError: status === STATUS_REJECTED,
+  } as any
+}
+
+/**
+ * @public
+ */
+export type SubscriptionOptions = {
+  /**
+   * How frequently to automatically re-fetch data (in milliseconds). Defaults to `0` (off).
+   */
+  pollingInterval?: number
+  /**
+   *  Defaults to 'false'. This setting allows you to control whether RTK Query will continue polling if the window is not focused.
+   *
+   *  If pollingInterval is not set or set to 0, this **will not be evaluated** until pollingInterval is greater than 0.
+   *
+   *  Note: requires [`setupListeners`](./setupListeners) to have been called.
+   */
+  skipPollingIfUnfocused?: boolean
+  /**
+   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.
+   *
+   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
+   *
+   * Note: requires [`setupListeners`](./setupListeners) to have been called.
+   */
+  refetchOnReconnect?: boolean
+  /**
+   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.
+   *
+   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
+   *
+   * Note: requires [`setupListeners`](./setupListeners) to have been called.
+   */
+  refetchOnFocus?: boolean
+}
+export type SubscribersInternal = Map<string, SubscriptionOptions>
+export type Subscribers = { [requestId: string]: SubscriptionOptions }
+export type QueryKeys<Definitions extends EndpointDefinitions> = {
+  [K in keyof Definitions]: Definitions[K] extends QueryDefinition<
+    any,
+    any,
+    any,
+    any
+  >
+    ? K
+    : never
+}[keyof Definitions]
+
+export type InfiniteQueryKeys<Definitions extends EndpointDefinitions> = {
+  [K in keyof Definitions]: Definitions[K] extends InfiniteQueryDefinition<
+    any,
+    any,
+    any,
+    any,
+    any
+  >
+    ? K
+    : never
+}[keyof Definitions]
+
+export type MutationKeys<Definitions extends EndpointDefinitions> = {
+  [K in keyof Definitions]: Definitions[K] extends MutationDefinition<
+    any,
+    any,
+    any,
+    any
+  >
+    ? K
+    : never
+}[keyof Definitions]
+
+type BaseQuerySubState<
+  D extends BaseEndpointDefinition<any, any, any, any>,
+  DataType = ResultTypeFrom<D>,
+> = {
+  /**
+   * The argument originally passed into the hook or `initiate` action call
+   */
+  originalArgs: QueryArgFromAnyQuery<D>
+  /**
+   * A unique ID associated with the request
+   */
+  requestId: string
+  /**
+   * The received data from the query
+   */
+  data?: DataType
+  /**
+   * The received error if applicable
+   */
+  error?:
+    | SerializedError
+    | (D extends QueryDefinition<any, infer BaseQuery, any, any>
+        ? BaseQueryError<BaseQuery>
+        : never)
+  /**
+   * The name of the endpoint associated with the query
+   */
+  endpointName: string
+  /**
+   * Time that the latest query started
+   */
+  startedTimeStamp: number
+  /**
+   * Time that the latest query was fulfilled
+   */
+  fulfilledTimeStamp?: number
+}
+
+export type QuerySubState<
+  D extends BaseEndpointDefinition<any, any, any, any>,
+  DataType = ResultTypeFrom<D>,
+> = Id<
+  | ({ status: QueryStatus.fulfilled } & WithRequiredProp<
+      BaseQuerySubState<D, DataType>,
+      'data' | 'fulfilledTimeStamp'
+    > & { error: undefined })
+  | ({ status: QueryStatus.pending } & BaseQuerySubState<D, DataType>)
+  | ({ status: QueryStatus.rejected } & WithRequiredProp<
+      BaseQuerySubState<D, DataType>,
+      'error'
+    >)
+  | {
+      status: QueryStatus.uninitialized
+      originalArgs?: undefined
+      data?: undefined
+      error?: undefined
+      requestId?: undefined
+      endpointName?: string
+      startedTimeStamp?: undefined
+      fulfilledTimeStamp?: undefined
+    }
+>
+
+export type InfiniteQueryDirection = 'forward' | 'backward'
+
+export type InfiniteQuerySubState<
+  D extends BaseEndpointDefinition<any, any, any, any>,
+> =
+  D extends InfiniteQueryDefinition<any, any, any, any, any>
+    ? QuerySubState<D, InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>> & {
+        direction?: InfiniteQueryDirection
+      }
+    : never
+
+type BaseMutationSubState<
+  D extends BaseEndpointDefinition<any, any, any, any>,
+> = {
+  requestId: string
+  data?: ResultTypeFrom<D>
+  error?:
+    | SerializedError
+    | (D extends MutationDefinition<any, infer BaseQuery, any, any>
+        ? BaseQueryError<BaseQuery>
+        : never)
+  endpointName: string
+  startedTimeStamp: number
+  fulfilledTimeStamp?: number
+}
+
+export type MutationSubState<
+  D extends BaseEndpointDefinition<any, any, any, any>,
+> =
+  | (({
+      status: QueryStatus.fulfilled
+    } & WithRequiredProp<
+      BaseMutationSubState<D>,
+      'data' | 'fulfilledTimeStamp'
+    >) & { error: undefined })
+  | (({ status: QueryStatus.pending } & BaseMutationSubState<D>) & {
+      data?: undefined
+    })
+  | ({ status: QueryStatus.rejected } & WithRequiredProp<
+      BaseMutationSubState<D>,
+      'error'
+    >)
+  | {
+      requestId?: undefined
+      status: QueryStatus.uninitialized
+      data?: undefined
+      error?: undefined
+      endpointName?: string
+      startedTimeStamp?: undefined
+      fulfilledTimeStamp?: undefined
+    }
+
+export type CombinedState<
+  D extends EndpointDefinitions,
+  E extends string,
+  ReducerPath extends string,
+> = {
+  queries: QueryState<D>
+  mutations: MutationState<D>
+  provided: InvalidationState<E>
+  subscriptions: SubscriptionState
+  config: ConfigState<ReducerPath>
+}
+
+export type InvalidationState<TagTypes extends string> = {
+  tags: {
+    [_ in TagTypes]: {
+      [id: string]: Array<QueryCacheKey>
+      [id: number]: Array<QueryCacheKey>
+    }
+  }
+  keys: Record<QueryCacheKey, Array<FullTagDescription<any>>>
+}
+
+export type QueryState<D extends EndpointDefinitions> = {
+  [queryCacheKey: string]:
+    | QuerySubState<D[string]>
+    | InfiniteQuerySubState<D[string]>
+    | undefined
+}
+
+export type SubscriptionInternalState = Map<string, SubscribersInternal>
+
+export type SubscriptionState = {
+  [queryCacheKey: string]: Subscribers | undefined
+}
+
+export type ConfigState<ReducerPath> = RefetchConfigOptions & {
+  reducerPath: ReducerPath
+  online: boolean
+  focused: boolean
+  middlewareRegistered: boolean | 'conflict'
+} & ModifiableConfigState
+
+export type ModifiableConfigState = {
+  keepUnusedDataFor: number
+  invalidationBehavior: 'delayed' | 'immediately'
+} & RefetchConfigOptions
+
+export type MutationState<D extends EndpointDefinitions> = {
+  [requestId: string]: MutationSubState<D[string]> | undefined
+}
+
+export type RootState<
+  Definitions extends EndpointDefinitions,
+  TagTypes extends string,
+  ReducerPath extends string,
+> = { [P in ReducerPath]: CombinedState<Definitions, TagTypes, P> }
Index: node_modules/@reduxjs/toolkit/src/query/core/buildInitiate.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildInitiate.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildInitiate.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,596 @@
+import type {
+  AsyncThunkAction,
+  SafePromise,
+  SerializedError,
+  ThunkAction,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import type { Dispatch } from 'redux'
+import { asSafePromise } from '../../tsHelpers'
+import { getEndpointDefinition, type Api, type ApiContext } from '../apiTypes'
+import type { BaseQueryError, QueryReturnValue } from '../baseQueryTypes'
+import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'
+import {
+  ENDPOINT_QUERY,
+  isQueryDefinition,
+  type EndpointDefinition,
+  type EndpointDefinitions,
+  type InfiniteQueryArgFrom,
+  type InfiniteQueryDefinition,
+  type MutationDefinition,
+  type PageParamFrom,
+  type QueryArgFrom,
+  type QueryDefinition,
+  type ResultTypeFrom,
+} from '../endpointDefinitions'
+import { filterNullishValues } from '../utils'
+import type {
+  InfiniteData,
+  InfiniteQueryConfigOptions,
+  InfiniteQueryDirection,
+  SubscriptionOptions,
+} from './apiState'
+import type {
+  InfiniteQueryResultSelectorResult,
+  QueryResultSelectorResult,
+} from './buildSelectors'
+import type {
+  InfiniteQueryThunk,
+  InfiniteQueryThunkArg,
+  MutationThunk,
+  QueryThunk,
+  QueryThunkArg,
+  ThunkApiMetaConfig,
+} from './buildThunks'
+import type { ApiEndpointQuery } from './module'
+import type { InternalMiddlewareState } from './buildMiddleware/types'
+
+export type BuildInitiateApiEndpointQuery<
+  Definition extends QueryDefinition<any, any, any, any, any>,
+> = {
+  initiate: StartQueryActionCreator<Definition>
+}
+
+export type BuildInitiateApiEndpointInfiniteQuery<
+  Definition extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = {
+  initiate: StartInfiniteQueryActionCreator<Definition>
+}
+
+export type BuildInitiateApiEndpointMutation<
+  Definition extends MutationDefinition<any, any, any, any, any>,
+> = {
+  initiate: StartMutationActionCreator<Definition>
+}
+
+export const forceQueryFnSymbol = Symbol('forceQueryFn')
+export const isUpsertQuery = (arg: QueryThunkArg) =>
+  typeof arg[forceQueryFnSymbol] === 'function'
+
+export type StartQueryActionCreatorOptions = {
+  subscribe?: boolean
+  forceRefetch?: boolean | number
+  subscriptionOptions?: SubscriptionOptions
+  [forceQueryFnSymbol]?: () => QueryReturnValue
+}
+
+type RefetchOptions = {
+  refetchCachedPages?: boolean
+}
+
+export type StartInfiniteQueryActionCreatorOptions<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = StartQueryActionCreatorOptions & {
+  direction?: InfiniteQueryDirection
+  param?: unknown
+} & Partial<
+    Pick<
+      Partial<
+        InfiniteQueryConfigOptions<
+          ResultTypeFrom<D>,
+          PageParamFrom<D>,
+          InfiniteQueryArgFrom<D>
+        >
+      >,
+      'initialPageParam' | 'refetchCachedPages'
+    >
+  >
+
+type AnyQueryActionCreator<D extends EndpointDefinition<any, any, any, any>> = (
+  arg: any,
+  options?: StartQueryActionCreatorOptions,
+) => ThunkAction<AnyActionCreatorResult, any, any, UnknownAction>
+
+type StartQueryActionCreator<
+  D extends QueryDefinition<any, any, any, any, any>,
+> = (
+  arg: QueryArgFrom<D>,
+  options?: StartQueryActionCreatorOptions,
+) => ThunkAction<QueryActionCreatorResult<D>, any, any, UnknownAction>
+
+export type StartInfiniteQueryActionCreator<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = (
+  arg: InfiniteQueryArgFrom<D>,
+  options?: StartInfiniteQueryActionCreatorOptions<D>,
+) => ThunkAction<InfiniteQueryActionCreatorResult<D>, any, any, UnknownAction>
+
+type QueryActionCreatorFields = {
+  requestId: string
+  subscriptionOptions: SubscriptionOptions | undefined
+  abort(): void
+  unsubscribe(): void
+  updateSubscriptionOptions(options: SubscriptionOptions): void
+  queryCacheKey: string
+}
+
+type AnyActionCreatorResult = SafePromise<any> &
+  QueryActionCreatorFields & {
+    arg: any
+    unwrap(): Promise<any>
+    refetch(options?: RefetchOptions): AnyActionCreatorResult
+  }
+
+export type QueryActionCreatorResult<
+  D extends QueryDefinition<any, any, any, any>,
+> = SafePromise<QueryResultSelectorResult<D>> &
+  QueryActionCreatorFields & {
+    arg: QueryArgFrom<D>
+    unwrap(): Promise<ResultTypeFrom<D>>
+    refetch(): QueryActionCreatorResult<D>
+  }
+
+export type InfiniteQueryActionCreatorResult<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = SafePromise<InfiniteQueryResultSelectorResult<D>> &
+  QueryActionCreatorFields & {
+    arg: InfiniteQueryArgFrom<D>
+    unwrap(): Promise<InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>>
+    refetch(
+      options?: Pick<
+        StartInfiniteQueryActionCreatorOptions<D>,
+        'refetchCachedPages'
+      >,
+    ): InfiniteQueryActionCreatorResult<D>
+  }
+
+type StartMutationActionCreator<
+  D extends MutationDefinition<any, any, any, any>,
+> = (
+  arg: QueryArgFrom<D>,
+  options?: {
+    /**
+     * If this mutation should be tracked in the store.
+     * If you just want to manually trigger this mutation using `dispatch` and don't care about the
+     * result, state & potential errors being held in store, you can set this to false.
+     * (defaults to `true`)
+     */
+    track?: boolean
+    fixedCacheKey?: string
+  },
+) => ThunkAction<MutationActionCreatorResult<D>, any, any, UnknownAction>
+
+export type MutationActionCreatorResult<
+  D extends MutationDefinition<any, any, any, any>,
+> = SafePromise<
+  | {
+      data: ResultTypeFrom<D>
+      error?: undefined
+    }
+  | {
+      data?: undefined
+      error:
+        | Exclude<
+            BaseQueryError<
+              D extends MutationDefinition<any, infer BaseQuery, any, any>
+                ? BaseQuery
+                : never
+            >,
+            undefined
+          >
+        | SerializedError
+    }
+> & {
+  /** @internal */
+  arg: {
+    /**
+     * The name of the given endpoint for the mutation
+     */
+    endpointName: string
+    /**
+     * The original arguments supplied to the mutation call
+     */
+    originalArgs: QueryArgFrom<D>
+    /**
+     * Whether the mutation is being tracked in the store.
+     */
+    track?: boolean
+    fixedCacheKey?: string
+  }
+  /**
+   * A unique string generated for the request sequence
+   */
+  requestId: string
+
+  /**
+   * A method to cancel the mutation promise. Note that this is not intended to prevent the mutation
+   * that was fired off from reaching the server, but only to assist in handling the response.
+   *
+   * Calling `abort()` prior to the promise resolving will force it to reach the error state with
+   * the serialized error:
+   * `{ name: 'AbortError', message: 'Aborted' }`
+   *
+   * @example
+   * ```ts
+   * const [updateUser] = useUpdateUserMutation();
+   *
+   * useEffect(() => {
+   *   const promise = updateUser(id);
+   *   promise
+   *     .unwrap()
+   *     .catch((err) => {
+   *       if (err.name === 'AbortError') return;
+   *       // else handle the unexpected error
+   *     })
+   *
+   *   return () => {
+   *     promise.abort();
+   *   }
+   * }, [id, updateUser])
+   * ```
+   */
+  abort(): void
+  /**
+   * Unwraps a mutation call to provide the raw response/error.
+   *
+   * @remarks
+   * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta title="Using .unwrap"
+   * addPost({ id: 1, name: 'Example' })
+   *   .unwrap()
+   *   .then((payload) => console.log('fulfilled', payload))
+   *   .catch((error) => console.error('rejected', error));
+   * ```
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta title="Using .unwrap with async await"
+   * try {
+   *   const payload = await addPost({ id: 1, name: 'Example' }).unwrap();
+   *   console.log('fulfilled', payload)
+   * } catch (error) {
+   *   console.error('rejected', error);
+   * }
+   * ```
+   */
+  unwrap(): Promise<ResultTypeFrom<D>>
+  /**
+   * A method to manually unsubscribe from the mutation call, meaning it will be removed from cache after the usual caching grace period.
+   The value returned by the hook will reset to `isUninitialized` afterwards.
+   */
+  reset(): void
+}
+
+export function buildInitiate({
+  serializeQueryArgs,
+  queryThunk,
+  infiniteQueryThunk,
+  mutationThunk,
+  api,
+  context,
+  getInternalState,
+}: {
+  serializeQueryArgs: InternalSerializeQueryArgs
+  queryThunk: QueryThunk
+  infiniteQueryThunk: InfiniteQueryThunk<any>
+  mutationThunk: MutationThunk
+  api: Api<any, EndpointDefinitions, any, any>
+  context: ApiContext<EndpointDefinitions>
+  getInternalState: (dispatch: Dispatch) => InternalMiddlewareState
+}) {
+  const getRunningQueries = (dispatch: Dispatch) =>
+    getInternalState(dispatch)?.runningQueries
+  const getRunningMutations = (dispatch: Dispatch) =>
+    getInternalState(dispatch)?.runningMutations
+
+  const {
+    unsubscribeQueryResult,
+    removeMutationResult,
+    updateSubscriptionOptions,
+  } = api.internalActions
+  return {
+    buildInitiateQuery,
+    buildInitiateInfiniteQuery,
+    buildInitiateMutation,
+    getRunningQueryThunk,
+    getRunningMutationThunk,
+    getRunningQueriesThunk,
+    getRunningMutationsThunk,
+  }
+
+  function getRunningQueryThunk(endpointName: string, queryArgs: any) {
+    return (dispatch: Dispatch) => {
+      const endpointDefinition = getEndpointDefinition(context, endpointName)
+      const queryCacheKey = serializeQueryArgs({
+        queryArgs,
+        endpointDefinition,
+        endpointName,
+      })
+      return getRunningQueries(dispatch)?.get(queryCacheKey) as
+        | QueryActionCreatorResult<never>
+        | InfiniteQueryActionCreatorResult<never>
+        | undefined
+    }
+  }
+
+  function getRunningMutationThunk(
+    /**
+     * this is only here to allow TS to infer the result type by input value
+     * we could use it to validate the result, but it's probably not necessary
+     */
+    _endpointName: string,
+    fixedCacheKeyOrRequestId: string,
+  ) {
+    return (dispatch: Dispatch) => {
+      return getRunningMutations(dispatch)?.get(fixedCacheKeyOrRequestId) as
+        | MutationActionCreatorResult<never>
+        | undefined
+    }
+  }
+
+  function getRunningQueriesThunk() {
+    return (dispatch: Dispatch) =>
+      filterNullishValues(getRunningQueries(dispatch))
+  }
+
+  function getRunningMutationsThunk() {
+    return (dispatch: Dispatch) =>
+      filterNullishValues(getRunningMutations(dispatch))
+  }
+
+  function middlewareWarning(dispatch: Dispatch) {
+    if (process.env.NODE_ENV !== 'production') {
+      if ((middlewareWarning as any).triggered) return
+      const returnedValue = dispatch(
+        api.internalActions.internal_getRTKQSubscriptions(),
+      )
+
+      ;(middlewareWarning as any).triggered = true
+
+      // The RTKQ middleware should return the internal state object,
+      // but it should _not_ be the action object.
+      if (
+        typeof returnedValue !== 'object' ||
+        typeof returnedValue?.type === 'string'
+      ) {
+        // Otherwise, must not have been added
+        throw new Error(
+          `Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
+You must add the middleware for RTK-Query to function correctly!`,
+        )
+      }
+    }
+  }
+
+  function buildInitiateAnyQuery<T extends 'query' | 'infiniteQuery'>(
+    endpointName: string,
+    endpointDefinition:
+      | QueryDefinition<any, any, any, any>
+      | InfiniteQueryDefinition<any, any, any, any, any>,
+  ) {
+    const queryAction: AnyQueryActionCreator<any> =
+      (
+        arg,
+        {
+          subscribe = true,
+          forceRefetch,
+          subscriptionOptions,
+          [forceQueryFnSymbol]: forceQueryFn,
+          ...rest
+        } = {},
+      ) =>
+      (dispatch, getState) => {
+        const queryCacheKey = serializeQueryArgs({
+          queryArgs: arg,
+          endpointDefinition,
+          endpointName,
+        })
+
+        let thunk: AsyncThunkAction<unknown, QueryThunkArg, ThunkApiMetaConfig>
+
+        const commonThunkArgs = {
+          ...rest,
+          type: ENDPOINT_QUERY as 'query',
+          subscribe,
+          forceRefetch: forceRefetch,
+          subscriptionOptions,
+          endpointName,
+          originalArgs: arg,
+          queryCacheKey,
+          [forceQueryFnSymbol]: forceQueryFn,
+        }
+
+        if (isQueryDefinition(endpointDefinition)) {
+          thunk = queryThunk(commonThunkArgs)
+        } else {
+          const { direction, initialPageParam, refetchCachedPages } =
+            rest as Pick<
+              InfiniteQueryThunkArg<any>,
+              'direction' | 'initialPageParam' | 'refetchCachedPages'
+            >
+          thunk = infiniteQueryThunk({
+            ...(commonThunkArgs as InfiniteQueryThunkArg<any>),
+            // Supply these even if undefined. This helps with a field existence
+            // check over in `buildSlice.ts`
+            direction,
+            initialPageParam,
+            refetchCachedPages,
+          })
+        }
+
+        const selector = (
+          api.endpoints[endpointName] as ApiEndpointQuery<any, any>
+        ).select(arg)
+
+        const thunkResult = dispatch(thunk)
+        const stateAfter = selector(getState())
+
+        middlewareWarning(dispatch)
+
+        const { requestId, abort } = thunkResult
+
+        const skippedSynchronously = stateAfter.requestId !== requestId
+
+        const runningQuery = getRunningQueries(dispatch)?.get(queryCacheKey)
+        const selectFromState = () => selector(getState())
+
+        const statePromise: AnyActionCreatorResult = Object.assign(
+          (forceQueryFn
+            ? // a query has been forced (upsertQueryData)
+              // -> we want to resolve it once data has been written with the data that will be written
+              thunkResult.then(selectFromState)
+            : skippedSynchronously && !runningQuery
+              ? // a query has been skipped due to a condition and we do not have any currently running query
+                // -> we want to resolve it immediately with the current data
+                Promise.resolve(stateAfter)
+              : // query just started or one is already in flight
+                // -> wait for the running query, then resolve with data from after that
+                Promise.all([runningQuery, thunkResult]).then(
+                  selectFromState,
+                )) as SafePromise<any>,
+          {
+            arg,
+            requestId,
+            subscriptionOptions,
+            queryCacheKey,
+            abort,
+            async unwrap() {
+              const result = await statePromise
+
+              if (result.isError) {
+                throw result.error
+              }
+
+              return result.data
+            },
+            refetch: (options?: RefetchOptions) =>
+              dispatch(
+                queryAction(arg, {
+                  subscribe: false,
+                  forceRefetch: true,
+                  ...options,
+                }),
+              ),
+            unsubscribe() {
+              if (subscribe)
+                dispatch(
+                  unsubscribeQueryResult({
+                    queryCacheKey,
+                    requestId,
+                  }),
+                )
+            },
+            updateSubscriptionOptions(options: SubscriptionOptions) {
+              statePromise.subscriptionOptions = options
+              dispatch(
+                updateSubscriptionOptions({
+                  endpointName,
+                  requestId,
+                  queryCacheKey,
+                  options,
+                }),
+              )
+            },
+          },
+        )
+
+        if (!runningQuery && !skippedSynchronously && !forceQueryFn) {
+          const runningQueries = getRunningQueries(dispatch)!
+          runningQueries.set(queryCacheKey, statePromise)
+
+          statePromise.then(() => {
+            runningQueries.delete(queryCacheKey)
+          })
+        }
+
+        return statePromise
+      }
+    return queryAction
+  }
+
+  function buildInitiateQuery(
+    endpointName: string,
+    endpointDefinition: QueryDefinition<any, any, any, any>,
+  ) {
+    const queryAction: StartQueryActionCreator<any> = buildInitiateAnyQuery(
+      endpointName,
+      endpointDefinition,
+    )
+
+    return queryAction
+  }
+
+  function buildInitiateInfiniteQuery(
+    endpointName: string,
+    endpointDefinition: InfiniteQueryDefinition<any, any, any, any, any>,
+  ) {
+    const infiniteQueryAction: StartInfiniteQueryActionCreator<any> =
+      buildInitiateAnyQuery(endpointName, endpointDefinition)
+
+    return infiniteQueryAction
+  }
+
+  function buildInitiateMutation(
+    endpointName: string,
+  ): StartMutationActionCreator<any> {
+    return (arg, { track = true, fixedCacheKey } = {}) =>
+      (dispatch, getState) => {
+        const thunk = mutationThunk({
+          type: 'mutation',
+          endpointName,
+          originalArgs: arg,
+          track,
+          fixedCacheKey,
+        })
+        const thunkResult = dispatch(thunk)
+        middlewareWarning(dispatch)
+        const { requestId, abort, unwrap } = thunkResult
+        const returnValuePromise = asSafePromise(
+          thunkResult.unwrap().then((data) => ({ data })),
+          (error) => ({ error }),
+        )
+
+        const reset = () => {
+          dispatch(removeMutationResult({ requestId, fixedCacheKey }))
+        }
+
+        const ret = Object.assign(returnValuePromise, {
+          arg: thunkResult.arg,
+          requestId,
+          abort,
+          unwrap,
+          reset,
+        })
+
+        const runningMutations = getRunningMutations(dispatch)!
+
+        runningMutations.set(requestId, ret)
+        ret.then(() => {
+          runningMutations.delete(requestId)
+        })
+        if (fixedCacheKey) {
+          runningMutations.set(fixedCacheKey, ret)
+          ret.then(() => {
+            if (runningMutations.get(fixedCacheKey) === ret) {
+              runningMutations.delete(fixedCacheKey)
+            }
+          })
+        }
+
+        return ret
+      }
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/batchActions.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/batchActions.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/batchActions.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,207 @@
+import type { InternalHandlerBuilder, SubscriptionSelectors } from './types'
+import type { SubscriptionInternalState, SubscriptionState } from '../apiState'
+import { produceWithPatches } from '../../utils/immerImports'
+import type { Action } from '@reduxjs/toolkit'
+import { getOrInsertComputed, createNewMap } from '../../utils/getOrInsert'
+
+export const buildBatchedActionsHandler: InternalHandlerBuilder<
+  [actionShouldContinue: boolean, returnValue: SubscriptionSelectors | boolean]
+> = ({ api, queryThunk, internalState, mwApi }) => {
+  const subscriptionsPrefix = `${api.reducerPath}/subscriptions`
+
+  let previousSubscriptions: SubscriptionState =
+    null as unknown as SubscriptionState
+
+  let updateSyncTimer: ReturnType<typeof window.setTimeout> | null = null
+
+  const { updateSubscriptionOptions, unsubscribeQueryResult } =
+    api.internalActions
+
+  // Actually intentionally mutate the subscriptions state used in the middleware
+  // This is done to speed up perf when loading many components
+  const actuallyMutateSubscriptions = (
+    currentSubscriptions: SubscriptionInternalState,
+    action: Action,
+  ) => {
+    if (updateSubscriptionOptions.match(action)) {
+      const { queryCacheKey, requestId, options } = action.payload
+
+      const sub = currentSubscriptions.get(queryCacheKey)
+      if (sub?.has(requestId)) {
+        sub.set(requestId, options)
+      }
+      return true
+    }
+    if (unsubscribeQueryResult.match(action)) {
+      const { queryCacheKey, requestId } = action.payload
+      const sub = currentSubscriptions.get(queryCacheKey)
+      if (sub) {
+        sub.delete(requestId)
+      }
+      return true
+    }
+    if (api.internalActions.removeQueryResult.match(action)) {
+      currentSubscriptions.delete(action.payload.queryCacheKey)
+      return true
+    }
+    if (queryThunk.pending.match(action)) {
+      const {
+        meta: { arg, requestId },
+      } = action
+      const substate = getOrInsertComputed(
+        currentSubscriptions,
+        arg.queryCacheKey,
+        createNewMap,
+      )
+      if (arg.subscribe) {
+        substate.set(
+          requestId,
+          arg.subscriptionOptions ?? substate.get(requestId) ?? {},
+        )
+      }
+      return true
+    }
+    let mutated = false
+
+    if (queryThunk.rejected.match(action)) {
+      const {
+        meta: { condition, arg, requestId },
+      } = action
+      if (condition && arg.subscribe) {
+        const substate = getOrInsertComputed(
+          currentSubscriptions,
+          arg.queryCacheKey,
+          createNewMap,
+        )
+        substate.set(
+          requestId,
+          arg.subscriptionOptions ?? substate.get(requestId) ?? {},
+        )
+
+        mutated = true
+      }
+    }
+
+    return mutated
+  }
+
+  const getSubscriptions = () => internalState.currentSubscriptions
+  const getSubscriptionCount = (queryCacheKey: string) => {
+    const subscriptions = getSubscriptions()
+    const subscriptionsForQueryArg = subscriptions.get(queryCacheKey)
+    return subscriptionsForQueryArg?.size ?? 0
+  }
+  const isRequestSubscribed = (queryCacheKey: string, requestId: string) => {
+    const subscriptions = getSubscriptions()
+    return !!subscriptions?.get(queryCacheKey)?.get(requestId)
+  }
+
+  const subscriptionSelectors: SubscriptionSelectors = {
+    getSubscriptions,
+    getSubscriptionCount,
+    isRequestSubscribed,
+  }
+
+  function serializeSubscriptions(
+    currentSubscriptions: SubscriptionInternalState,
+  ): SubscriptionState {
+    // We now use nested Maps for subscriptions, instead of
+    // plain Records. Stringify this accordingly so we can
+    // convert it to the shape we need for the store.
+    return JSON.parse(
+      JSON.stringify(
+        Object.fromEntries(
+          [...currentSubscriptions].map(([k, v]) => [k, Object.fromEntries(v)]),
+        ),
+      ),
+    )
+  }
+
+  return (
+    action,
+    mwApi,
+  ): [
+    actionShouldContinue: boolean,
+    result: SubscriptionSelectors | boolean,
+  ] => {
+    if (!previousSubscriptions) {
+      // Initialize it the first time this handler runs
+      previousSubscriptions = serializeSubscriptions(
+        internalState.currentSubscriptions,
+      )
+    }
+
+    if (api.util.resetApiState.match(action)) {
+      previousSubscriptions = {}
+      internalState.currentSubscriptions.clear()
+      updateSyncTimer = null
+      return [true, false]
+    }
+
+    // Intercept requests by hooks to see if they're subscribed
+    // We return the internal state reference so that hooks
+    // can do their own checks to see if they're still active.
+    // It's stupid and hacky, but it does cut down on some dispatch calls.
+    if (api.internalActions.internal_getRTKQSubscriptions.match(action)) {
+      return [false, subscriptionSelectors]
+    }
+
+    // Update subscription data based on this action
+    const didMutate = actuallyMutateSubscriptions(
+      internalState.currentSubscriptions,
+      action,
+    )
+
+    let actionShouldContinue = true
+
+    // HACK Sneak the test-only polling state back out
+    if (
+      process.env.NODE_ENV === 'test' &&
+      typeof action.type === 'string' &&
+      action.type === `${api.reducerPath}/getPolling`
+    ) {
+      return [false, internalState.currentPolls] as any
+    }
+
+    if (didMutate) {
+      if (!updateSyncTimer) {
+        // We only use the subscription state for the Redux DevTools at this point,
+        // as the real data is kept here in the middleware.
+        // Given that, we can throttle synchronizing this state significantly to
+        // save on overall perf.
+        // In 1.9, it was updated in a microtask, but now we do it at most every 500ms.
+        updateSyncTimer = setTimeout(() => {
+          // Deep clone the current subscription data
+          const newSubscriptions: SubscriptionState = serializeSubscriptions(
+            internalState.currentSubscriptions,
+          )
+          // Figure out a smaller diff between original and current
+          const [, patches] = produceWithPatches(
+            previousSubscriptions,
+            () => newSubscriptions,
+          )
+
+          // Sync the store state for visibility
+          mwApi.next(api.internalActions.subscriptionsUpdated(patches))
+          // Save the cloned state for later reference
+          previousSubscriptions = newSubscriptions
+          updateSyncTimer = null
+        }, 500)
+      }
+
+      const isSubscriptionSliceAction =
+        typeof action.type == 'string' &&
+        !!action.type.startsWith(subscriptionsPrefix)
+
+      const isAdditionalSubscriptionAction =
+        queryThunk.rejected.match(action) &&
+        action.meta.condition &&
+        !!action.meta.arg.subscribe
+
+      actionShouldContinue =
+        !isSubscriptionSliceAction && !isAdditionalSubscriptionAction
+    }
+
+    return [actionShouldContinue, false]
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/cacheCollection.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/cacheCollection.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/cacheCollection.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,204 @@
+import { getEndpointDefinition } from '@internal/query/apiTypes'
+import type { QueryDefinition } from '../../endpointDefinitions'
+import type { ConfigState, QueryCacheKey, QuerySubState } from '../apiState'
+import { isAnyOf } from '../rtkImports'
+import type {
+  ApiMiddlewareInternalHandler,
+  InternalHandlerBuilder,
+  QueryStateMeta,
+  SubMiddlewareApi,
+  TimeoutId,
+} from './types'
+
+export type ReferenceCacheCollection = never
+
+/**
+ * @example
+ * ```ts
+ * // codeblock-meta title="keepUnusedDataFor example"
+ * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+ * interface Post {
+ *   id: number
+ *   name: string
+ * }
+ * type PostsResponse = Post[]
+ *
+ * const api = createApi({
+ *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+ *   endpoints: (build) => ({
+ *     getPosts: build.query<PostsResponse, void>({
+ *       query: () => 'posts',
+ *       // highlight-start
+ *       keepUnusedDataFor: 5
+ *       // highlight-end
+ *     })
+ *   })
+ * })
+ * ```
+ */
+export type CacheCollectionQueryExtraOptions = {
+  /**
+   * Overrides the api-wide definition of `keepUnusedDataFor` for this endpoint only. _(This value is in seconds.)_
+   *
+   * This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.
+   */
+  keepUnusedDataFor?: number
+}
+
+// Per https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value , browsers store
+// `setTimeout()` timer values in a 32-bit int. If we pass a value in that's larger than that,
+// it wraps and ends up executing immediately.
+// Our `keepUnusedDataFor` values are in seconds, so adjust the numbers here accordingly.
+export const THIRTY_TWO_BIT_MAX_INT = 2_147_483_647
+export const THIRTY_TWO_BIT_MAX_TIMER_SECONDS = 2_147_483_647 / 1_000 - 1
+
+export const buildCacheCollectionHandler: InternalHandlerBuilder = ({
+  reducerPath,
+  api,
+  queryThunk,
+  context,
+  internalState,
+  selectors: { selectQueryEntry, selectConfig },
+  getRunningQueryThunk,
+  mwApi,
+}) => {
+  const { removeQueryResult, unsubscribeQueryResult, cacheEntriesUpserted } =
+    api.internalActions
+
+  const canTriggerUnsubscribe = isAnyOf(
+    unsubscribeQueryResult.match,
+    queryThunk.fulfilled,
+    queryThunk.rejected,
+    cacheEntriesUpserted.match,
+  )
+
+  function anySubscriptionsRemainingForKey(queryCacheKey: string) {
+    const subscriptions = internalState.currentSubscriptions.get(queryCacheKey)
+    if (!subscriptions) {
+      return false
+    }
+
+    const hasSubscriptions = subscriptions.size > 0
+    return hasSubscriptions
+  }
+
+  const currentRemovalTimeouts: QueryStateMeta<TimeoutId> = {}
+
+  function abortAllPromises<T extends { abort?: () => void }>(
+    promiseMap: Map<string, T | undefined>,
+  ): void {
+    for (const promise of promiseMap.values()) {
+      promise?.abort?.()
+    }
+  }
+
+  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {
+    const state = mwApi.getState()
+    const config = selectConfig(state)
+
+    if (canTriggerUnsubscribe(action)) {
+      let queryCacheKeys: QueryCacheKey[]
+
+      if (cacheEntriesUpserted.match(action)) {
+        queryCacheKeys = action.payload.map(
+          (entry) => entry.queryDescription.queryCacheKey,
+        )
+      } else {
+        const { queryCacheKey } = unsubscribeQueryResult.match(action)
+          ? action.payload
+          : action.meta.arg
+        queryCacheKeys = [queryCacheKey]
+      }
+
+      handleUnsubscribeMany(queryCacheKeys, mwApi, config)
+    }
+
+    if (api.util.resetApiState.match(action)) {
+      for (const [key, timeout] of Object.entries(currentRemovalTimeouts)) {
+        if (timeout) clearTimeout(timeout)
+        delete currentRemovalTimeouts[key]
+      }
+
+      abortAllPromises(internalState.runningQueries)
+      abortAllPromises(internalState.runningMutations)
+    }
+
+    if (context.hasRehydrationInfo(action)) {
+      const { queries } = context.extractRehydrationInfo(action)!
+      // Gotcha:
+      // If rehydrating before the endpoint has been injected,the global `keepUnusedDataFor`
+      // will be used instead of the endpoint-specific one.
+      handleUnsubscribeMany(
+        Object.keys(queries) as QueryCacheKey[],
+        mwApi,
+        config,
+      )
+    }
+  }
+
+  function handleUnsubscribeMany(
+    cacheKeys: QueryCacheKey[],
+    api: SubMiddlewareApi,
+    config: ConfigState<string>,
+  ) {
+    const state = api.getState()
+    for (const queryCacheKey of cacheKeys) {
+      const entry = selectQueryEntry(state, queryCacheKey)
+      if (entry?.endpointName) {
+        handleUnsubscribe(queryCacheKey, entry.endpointName, api, config)
+      }
+    }
+  }
+
+  function handleUnsubscribe(
+    queryCacheKey: QueryCacheKey,
+    endpointName: string,
+    api: SubMiddlewareApi,
+    config: ConfigState<string>,
+  ) {
+    const endpointDefinition = getEndpointDefinition(
+      context,
+      endpointName,
+    ) as QueryDefinition<any, any, any, any>
+    const keepUnusedDataFor =
+      endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor
+
+    if (keepUnusedDataFor === Infinity) {
+      // Hey, user said keep this forever!
+      return
+    }
+    // Prevent `setTimeout` timers from overflowing a 32-bit internal int, by
+    // clamping the max value to be at most 1000ms less than the 32-bit max.
+    // Look, a 24.8-day keepalive ought to be enough for anybody, right? :)
+    // Also avoid negative values too.
+    const finalKeepUnusedDataFor = Math.max(
+      0,
+      Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS),
+    )
+
+    if (!anySubscriptionsRemainingForKey(queryCacheKey)) {
+      const currentTimeout = currentRemovalTimeouts[queryCacheKey]
+      if (currentTimeout) {
+        clearTimeout(currentTimeout)
+      }
+
+      currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {
+        if (!anySubscriptionsRemainingForKey(queryCacheKey)) {
+          // Try to abort any running query for this cache key
+          const entry = selectQueryEntry(api.getState(), queryCacheKey)
+
+          if (entry?.endpointName) {
+            const runningQuery = api.dispatch(
+              getRunningQueryThunk(entry.endpointName, entry.originalArgs),
+            )
+            runningQuery?.abort()
+          }
+          api.dispatch(removeQueryResult({ queryCacheKey }))
+        }
+        delete currentRemovalTimeouts![queryCacheKey]
+      }, finalKeepUnusedDataFor * 1000)
+    }
+  }
+
+  return handler
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/cacheLifecycle.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/cacheLifecycle.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/cacheLifecycle.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,379 @@
+import type { ThunkDispatch, UnknownAction } from '@reduxjs/toolkit'
+import type {
+  BaseQueryFn,
+  BaseQueryMeta,
+  BaseQueryResult,
+} from '../../baseQueryTypes'
+import type {
+  BaseEndpointDefinition,
+  DefinitionType,
+} from '../../endpointDefinitions'
+import { isAnyQueryDefinition } from '../../endpointDefinitions'
+import type { QueryCacheKey, RootState } from '../apiState'
+import type {
+  MutationResultSelectorResult,
+  QueryResultSelectorResult,
+} from '../buildSelectors'
+import { getMutationCacheKey } from '../buildSlice'
+import type { PatchCollection, Recipe } from '../buildThunks'
+import { isAsyncThunkAction, isFulfilled } from '../rtkImports'
+import type {
+  ApiMiddlewareInternalHandler,
+  InternalHandlerBuilder,
+  PromiseWithKnownReason,
+  SubMiddlewareApi,
+} from './types'
+import { getEndpointDefinition } from '@internal/query/apiTypes'
+
+export type ReferenceCacheLifecycle = never
+
+export interface QueryBaseLifecycleApi<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ResultType,
+  ReducerPath extends string = string,
+> extends LifecycleApi<ReducerPath> {
+  /**
+   * Gets the current value of this cache entry.
+   */
+  getCacheEntry(): QueryResultSelectorResult<
+    { type: DefinitionType.query } & BaseEndpointDefinition<
+      QueryArg,
+      BaseQuery,
+      ResultType,
+      BaseQueryResult<BaseQuery>
+    >
+  >
+  /**
+   * Updates the current cache entry value.
+   * For documentation see `api.util.updateQueryData`.
+   */
+  updateCachedData(updateRecipe: Recipe<ResultType>): PatchCollection
+}
+
+export type MutationBaseLifecycleApi<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ResultType,
+  ReducerPath extends string = string,
+> = LifecycleApi<ReducerPath> & {
+  /**
+   * Gets the current value of this cache entry.
+   */
+  getCacheEntry(): MutationResultSelectorResult<
+    { type: DefinitionType.mutation } & BaseEndpointDefinition<
+      QueryArg,
+      BaseQuery,
+      ResultType,
+      BaseQueryResult<BaseQuery>
+    >
+  >
+}
+
+type LifecycleApi<ReducerPath extends string = string> = {
+  /**
+   * The dispatch method for the store
+   */
+  dispatch: ThunkDispatch<any, any, UnknownAction>
+  /**
+   * A method to get the current state
+   */
+  getState(): RootState<any, any, ReducerPath>
+  /**
+   * `extra` as provided as `thunk.extraArgument` to the `configureStore` `getDefaultMiddleware` option.
+   */
+  extra: unknown
+  /**
+   * A unique ID generated for the mutation
+   */
+  requestId: string
+}
+
+type CacheLifecyclePromises<ResultType = unknown, MetaType = unknown> = {
+  /**
+   * Promise that will resolve with the first value for this cache key.
+   * This allows you to `await` until an actual value is in cache.
+   *
+   * If the cache entry is removed from the cache before any value has ever
+   * been resolved, this Promise will reject with
+   * `new Error('Promise never resolved before cacheEntryRemoved.')`
+   * to prevent memory leaks.
+   * You can just re-throw that error (or not handle it at all) -
+   * it will be caught outside of `cacheEntryAdded`.
+   *
+   * If you don't interact with this promise, it will not throw.
+   */
+  cacheDataLoaded: PromiseWithKnownReason<
+    {
+      /**
+       * The (transformed) query result.
+       */
+      data: ResultType
+      /**
+       * The `meta` returned by the `baseQuery`
+       */
+      meta: MetaType
+    },
+    typeof neverResolvedError
+  >
+  /**
+   * Promise that allows you to wait for the point in time when the cache entry
+   * has been removed from the cache, by not being used/subscribed to any more
+   * in the application for too long or by dispatching `api.util.resetApiState`.
+   */
+  cacheEntryRemoved: Promise<void>
+}
+
+export interface QueryCacheLifecycleApi<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ResultType,
+  ReducerPath extends string = string,
+> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>,
+    CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>> {}
+
+export type MutationCacheLifecycleApi<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ResultType,
+  ReducerPath extends string = string,
+> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> &
+  CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>>
+
+export type CacheLifecycleQueryExtraOptions<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ReducerPath extends string = string,
+> = {
+  onCacheEntryAdded?(
+    arg: QueryArg,
+    api: QueryCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>,
+  ): Promise<void> | void
+}
+
+export type CacheLifecycleInfiniteQueryExtraOptions<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ReducerPath extends string = string,
+> = CacheLifecycleQueryExtraOptions<
+  ResultType,
+  QueryArg,
+  BaseQuery,
+  ReducerPath
+>
+
+export type CacheLifecycleMutationExtraOptions<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ReducerPath extends string = string,
+> = {
+  onCacheEntryAdded?(
+    arg: QueryArg,
+    api: MutationCacheLifecycleApi<
+      QueryArg,
+      BaseQuery,
+      ResultType,
+      ReducerPath
+    >,
+  ): Promise<void> | void
+}
+
+const neverResolvedError = new Error(
+  'Promise never resolved before cacheEntryRemoved.',
+) as Error & {
+  message: 'Promise never resolved before cacheEntryRemoved.'
+}
+
+export const buildCacheLifecycleHandler: InternalHandlerBuilder = ({
+  api,
+  reducerPath,
+  context,
+  queryThunk,
+  mutationThunk,
+  internalState,
+  selectors: { selectQueryEntry, selectApiState },
+}) => {
+  const isQueryThunk = isAsyncThunkAction(queryThunk)
+  const isMutationThunk = isAsyncThunkAction(mutationThunk)
+  const isFulfilledThunk = isFulfilled(queryThunk, mutationThunk)
+
+  type CacheLifecycle = {
+    valueResolved?(value: { data: unknown; meta: unknown }): unknown
+    cacheEntryRemoved(): void
+  }
+  const lifecycleMap: Record<string, CacheLifecycle> = {}
+
+  const { removeQueryResult, removeMutationResult, cacheEntriesUpserted } =
+    api.internalActions
+
+  function resolveLifecycleEntry(
+    cacheKey: string,
+    data: unknown,
+    meta: unknown,
+  ) {
+    const lifecycle = lifecycleMap[cacheKey]
+
+    if (lifecycle?.valueResolved) {
+      lifecycle.valueResolved({
+        data,
+        meta,
+      })
+      delete lifecycle.valueResolved
+    }
+  }
+
+  function removeLifecycleEntry(cacheKey: string) {
+    const lifecycle = lifecycleMap[cacheKey]
+    if (lifecycle) {
+      delete lifecycleMap[cacheKey]
+      lifecycle.cacheEntryRemoved()
+    }
+  }
+
+  function getActionMetaFields(
+    action:
+      | ReturnType<typeof queryThunk.pending>
+      | ReturnType<typeof mutationThunk.pending>,
+  ) {
+    const { arg, requestId } = action.meta
+    const { endpointName, originalArgs } = arg
+    return [endpointName, originalArgs, requestId] as const
+  }
+
+  const handler: ApiMiddlewareInternalHandler = (
+    action,
+    mwApi,
+    stateBefore,
+  ) => {
+    const cacheKey = getCacheKey(action) as QueryCacheKey
+
+    function checkForNewCacheKey(
+      endpointName: string,
+      cacheKey: QueryCacheKey,
+      requestId: string,
+      originalArgs: unknown,
+    ) {
+      const oldEntry = selectQueryEntry(stateBefore, cacheKey)
+      const newEntry = selectQueryEntry(mwApi.getState(), cacheKey)
+      if (!oldEntry && newEntry) {
+        handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId)
+      }
+    }
+
+    if (queryThunk.pending.match(action)) {
+      const [endpointName, originalArgs, requestId] =
+        getActionMetaFields(action)
+      checkForNewCacheKey(endpointName, cacheKey, requestId, originalArgs)
+    } else if (cacheEntriesUpserted.match(action)) {
+      for (const { queryDescription, value } of action.payload) {
+        const { endpointName, originalArgs, queryCacheKey } = queryDescription
+        checkForNewCacheKey(
+          endpointName,
+          queryCacheKey,
+          action.meta.requestId,
+          originalArgs,
+        )
+
+        resolveLifecycleEntry(queryCacheKey, value, {})
+      }
+    } else if (mutationThunk.pending.match(action)) {
+      const state = mwApi.getState()[reducerPath].mutations[cacheKey]
+      if (state) {
+        const [endpointName, originalArgs, requestId] =
+          getActionMetaFields(action)
+        handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId)
+      }
+    } else if (isFulfilledThunk(action)) {
+      resolveLifecycleEntry(cacheKey, action.payload, action.meta.baseQueryMeta)
+    } else if (
+      removeQueryResult.match(action) ||
+      removeMutationResult.match(action)
+    ) {
+      removeLifecycleEntry(cacheKey)
+    } else if (api.util.resetApiState.match(action)) {
+      for (const cacheKey of Object.keys(lifecycleMap)) {
+        removeLifecycleEntry(cacheKey)
+      }
+    }
+  }
+
+  function getCacheKey(action: any) {
+    if (isQueryThunk(action)) return action.meta.arg.queryCacheKey
+    if (isMutationThunk(action)) {
+      return action.meta.arg.fixedCacheKey ?? action.meta.requestId
+    }
+    if (removeQueryResult.match(action)) return action.payload.queryCacheKey
+    if (removeMutationResult.match(action))
+      return getMutationCacheKey(action.payload)
+    return ''
+  }
+
+  function handleNewKey(
+    endpointName: string,
+    originalArgs: any,
+    queryCacheKey: string,
+    mwApi: SubMiddlewareApi,
+    requestId: string,
+  ) {
+    const endpointDefinition = getEndpointDefinition(context, endpointName)
+    const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded
+    if (!onCacheEntryAdded) return
+
+    const lifecycle = {} as CacheLifecycle
+
+    const cacheEntryRemoved = new Promise<void>((resolve) => {
+      lifecycle.cacheEntryRemoved = resolve
+    })
+    const cacheDataLoaded: PromiseWithKnownReason<
+      { data: unknown; meta: unknown },
+      typeof neverResolvedError
+    > = Promise.race([
+      new Promise<{ data: unknown; meta: unknown }>((resolve) => {
+        lifecycle.valueResolved = resolve
+      }),
+      cacheEntryRemoved.then(() => {
+        throw neverResolvedError
+      }),
+    ])
+    // prevent uncaught promise rejections from happening.
+    // if the original promise is used in any way, that will create a new promise that will throw again
+    cacheDataLoaded.catch(() => {})
+    lifecycleMap[queryCacheKey] = lifecycle
+    const selector = (api.endpoints[endpointName] as any).select(
+      isAnyQueryDefinition(endpointDefinition) ? originalArgs : queryCacheKey,
+    )
+
+    const extra = mwApi.dispatch((_, __, extra) => extra)
+    const lifecycleApi = {
+      ...mwApi,
+      getCacheEntry: () => selector(mwApi.getState()),
+      requestId,
+      extra,
+      updateCachedData: (isAnyQueryDefinition(endpointDefinition)
+        ? (updateRecipe: Recipe<any>) =>
+            mwApi.dispatch(
+              api.util.updateQueryData(
+                endpointName as never,
+                originalArgs as never,
+                updateRecipe,
+              ),
+            )
+        : undefined) as any,
+
+      cacheDataLoaded,
+      cacheEntryRemoved,
+    }
+
+    const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi as any)
+    // if a `neverResolvedError` was thrown, but not handled in the running handler, do not let it leak out further
+    Promise.resolve(runningHandler).catch((e) => {
+      if (e === neverResolvedError) return
+      throw e
+    })
+  }
+
+  return handler
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/devMiddleware.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/devMiddleware.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/devMiddleware.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,34 @@
+import type { InternalHandlerBuilder } from './types'
+
+export const buildDevCheckHandler: InternalHandlerBuilder = ({
+  api,
+  context: { apiUid },
+  reducerPath,
+}) => {
+  return (action, mwApi) => {
+    if (api.util.resetApiState.match(action)) {
+      // dispatch after api reset
+      mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid))
+    }
+
+    if (
+      typeof process !== 'undefined' &&
+      process.env.NODE_ENV === 'development'
+    ) {
+      if (
+        api.internalActions.middlewareRegistered.match(action) &&
+        action.payload === apiUid &&
+        mwApi.getState()[reducerPath]?.config?.middlewareRegistered ===
+          'conflict'
+      ) {
+        console.warn(`There is a mismatch between slice and middleware for the reducerPath "${reducerPath}".
+You can only have one api per reducer path, this will lead to crashes in various situations!${
+          reducerPath === 'api'
+            ? `
+If you have multiple apis, you *have* to specify the reducerPath option when using createApi!`
+            : ''
+        }`)
+      }
+    }
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/index.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,162 @@
+import type {
+  Action,
+  Middleware,
+  ThunkDispatch,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import type {
+  EndpointDefinitions,
+  FullTagDescription,
+} from '../../endpointDefinitions'
+import type { QueryStatus, QuerySubState, RootState } from '../apiState'
+import type { QueryThunkArg } from '../buildThunks'
+import { createAction, isAction } from '../rtkImports'
+import { buildBatchedActionsHandler } from './batchActions'
+import { buildCacheCollectionHandler } from './cacheCollection'
+import { buildCacheLifecycleHandler } from './cacheLifecycle'
+import { buildDevCheckHandler } from './devMiddleware'
+import { buildInvalidationByTagsHandler } from './invalidationByTags'
+import { buildPollingHandler } from './polling'
+import { buildQueryLifecycleHandler } from './queryLifecycle'
+import type {
+  BuildMiddlewareInput,
+  InternalHandlerBuilder,
+  InternalMiddlewareState,
+} from './types'
+import { buildWindowEventHandler } from './windowEventHandling'
+import type { ApiEndpointQuery } from '../module'
+export type { ReferenceCacheCollection } from './cacheCollection'
+export type {
+  MutationCacheLifecycleApi,
+  QueryCacheLifecycleApi,
+  ReferenceCacheLifecycle,
+} from './cacheLifecycle'
+export type {
+  MutationLifecycleApi,
+  QueryLifecycleApi,
+  ReferenceQueryLifecycle,
+  TypedMutationOnQueryStarted,
+  TypedQueryOnQueryStarted,
+} from './queryLifecycle'
+export type { SubscriptionSelectors } from './types'
+
+export function buildMiddleware<
+  Definitions extends EndpointDefinitions,
+  ReducerPath extends string,
+  TagTypes extends string,
+>(input: BuildMiddlewareInput<Definitions, ReducerPath, TagTypes>) {
+  const { reducerPath, queryThunk, api, context, getInternalState } = input
+  const { apiUid } = context
+
+  const actions = {
+    invalidateTags: createAction<
+      Array<TagTypes | FullTagDescription<TagTypes> | null | undefined>
+    >(`${reducerPath}/invalidateTags`),
+  }
+
+  const isThisApiSliceAction = (action: Action) =>
+    action.type.startsWith(`${reducerPath}/`)
+
+  const handlerBuilders: InternalHandlerBuilder[] = [
+    buildDevCheckHandler,
+    buildCacheCollectionHandler,
+    buildInvalidationByTagsHandler,
+    buildPollingHandler,
+    buildCacheLifecycleHandler,
+    buildQueryLifecycleHandler,
+  ]
+
+  const middleware: Middleware<
+    {},
+    RootState<Definitions, string, ReducerPath>,
+    ThunkDispatch<any, any, UnknownAction>
+  > = (mwApi) => {
+    let initialized = false
+
+    const internalState = getInternalState(mwApi.dispatch)
+
+    const builderArgs = {
+      ...(input as any as BuildMiddlewareInput<
+        EndpointDefinitions,
+        string,
+        string
+      >),
+      internalState,
+      refetchQuery,
+      isThisApiSliceAction,
+      mwApi,
+    }
+
+    const handlers = handlerBuilders.map((build) => build(builderArgs))
+
+    const batchedActionsHandler = buildBatchedActionsHandler(builderArgs)
+    const windowEventsHandler = buildWindowEventHandler(builderArgs)
+
+    return (next) => {
+      return (action) => {
+        if (!isAction(action)) {
+          return next(action)
+        }
+        if (!initialized) {
+          initialized = true
+          // dispatch before any other action
+          mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid))
+        }
+
+        const mwApiWithNext = { ...mwApi, next }
+
+        const stateBefore = mwApi.getState()
+
+        const [actionShouldContinue, internalProbeResult] =
+          batchedActionsHandler(action, mwApiWithNext, stateBefore)
+
+        let res: any
+
+        if (actionShouldContinue) {
+          res = next(action)
+        } else {
+          res = internalProbeResult
+        }
+
+        if (!!mwApi.getState()[reducerPath]) {
+          // Only run these checks if the middleware is registered okay
+
+          // This looks for actions that aren't specific to the API slice
+          windowEventsHandler(action, mwApiWithNext, stateBefore)
+
+          if (
+            isThisApiSliceAction(action) ||
+            context.hasRehydrationInfo(action)
+          ) {
+            // Only run these additional checks if the actions are part of the API slice,
+            // or the action has hydration-related data
+            for (const handler of handlers) {
+              handler(action, mwApiWithNext, stateBefore)
+            }
+          }
+        }
+
+        return res
+      }
+    }
+  }
+
+  return { middleware, actions }
+
+  function refetchQuery(
+    querySubState: Exclude<
+      QuerySubState<any>,
+      { status: QueryStatus.uninitialized }
+    >,
+  ) {
+    return (
+      input.api.endpoints[querySubState.endpointName] as ApiEndpointQuery<
+        any,
+        any
+      >
+    ).initiate(querySubState.originalArgs as any, {
+      subscribe: false,
+      forceRefetch: true,
+    })
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/invalidationByTags.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/invalidationByTags.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/invalidationByTags.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,139 @@
+import {
+  isAnyOf,
+  isFulfilled,
+  isRejected,
+  isRejectedWithValue,
+} from '../rtkImports'
+
+import type {
+  EndpointDefinitions,
+  FullTagDescription,
+} from '../../endpointDefinitions'
+import { calculateProvidedBy } from '../../endpointDefinitions'
+import type { CombinedState, QueryCacheKey } from '../apiState'
+import { QueryStatus, STATUS_UNINITIALIZED } from '../apiState'
+import { calculateProvidedByThunk } from '../buildThunks'
+import type {
+  SubMiddlewareApi,
+  InternalHandlerBuilder,
+  ApiMiddlewareInternalHandler,
+} from './types'
+import { getOrInsertComputed, createNewMap } from '../../utils/getOrInsert'
+
+export const buildInvalidationByTagsHandler: InternalHandlerBuilder = ({
+  reducerPath,
+  context,
+  context: { endpointDefinitions },
+  mutationThunk,
+  queryThunk,
+  api,
+  assertTagType,
+  refetchQuery,
+  internalState,
+}) => {
+  const { removeQueryResult } = api.internalActions
+  const isThunkActionWithTags = isAnyOf(
+    isFulfilled(mutationThunk),
+    isRejectedWithValue(mutationThunk),
+  )
+
+  const isQueryEnd = isAnyOf(
+    isFulfilled(queryThunk, mutationThunk),
+    isRejected(queryThunk, mutationThunk),
+  )
+  let pendingTagInvalidations: FullTagDescription<string>[] = []
+  // Track via counter so we can avoid iterating over state every time
+  let pendingRequestCount = 0
+
+  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {
+    if (
+      queryThunk.pending.match(action) ||
+      mutationThunk.pending.match(action)
+    ) {
+      pendingRequestCount++
+    }
+
+    if (isQueryEnd(action)) {
+      pendingRequestCount = Math.max(0, pendingRequestCount - 1)
+    }
+
+    if (isThunkActionWithTags(action)) {
+      invalidateTags(
+        calculateProvidedByThunk(
+          action,
+          'invalidatesTags',
+          endpointDefinitions,
+          assertTagType,
+        ),
+        mwApi,
+      )
+    } else if (isQueryEnd(action)) {
+      invalidateTags([], mwApi)
+    } else if (api.util.invalidateTags.match(action)) {
+      invalidateTags(
+        calculateProvidedBy(
+          action.payload,
+          undefined,
+          undefined,
+          undefined,
+          undefined,
+          assertTagType,
+        ),
+        mwApi,
+      )
+    }
+  }
+
+  function hasPendingRequests() {
+    return pendingRequestCount > 0
+  }
+
+  function invalidateTags(
+    newTags: readonly FullTagDescription<string>[],
+    mwApi: SubMiddlewareApi,
+  ) {
+    const rootState = mwApi.getState()
+    const state = rootState[reducerPath]
+
+    pendingTagInvalidations.push(...newTags)
+
+    if (
+      state.config.invalidationBehavior === 'delayed' &&
+      hasPendingRequests()
+    ) {
+      return
+    }
+
+    const tags = pendingTagInvalidations
+    pendingTagInvalidations = []
+    if (tags.length === 0) return
+
+    const toInvalidate = api.util.selectInvalidatedBy(rootState, tags)
+
+    context.batch(() => {
+      const valuesArray = Array.from(toInvalidate.values())
+      for (const { queryCacheKey } of valuesArray) {
+        const querySubState = state.queries[queryCacheKey]
+        const subscriptionSubState = getOrInsertComputed(
+          internalState.currentSubscriptions,
+          queryCacheKey,
+          createNewMap,
+        )
+
+        if (querySubState) {
+          if (subscriptionSubState.size === 0) {
+            mwApi.dispatch(
+              removeQueryResult({
+                queryCacheKey: queryCacheKey as QueryCacheKey,
+              }),
+            )
+          } else if (querySubState.status !== STATUS_UNINITIALIZED) {
+            mwApi.dispatch(refetchQuery(querySubState))
+          }
+        }
+      }
+    })
+  }
+
+  return handler
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/polling.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/polling.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/polling.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,187 @@
+import type {
+  QueryCacheKey,
+  QuerySubstateIdentifier,
+  Subscribers,
+  SubscribersInternal,
+} from '../apiState'
+import { QueryStatus, STATUS_UNINITIALIZED } from '../apiState'
+import type {
+  QueryStateMeta,
+  SubMiddlewareApi,
+  TimeoutId,
+  InternalHandlerBuilder,
+  ApiMiddlewareInternalHandler,
+  InternalMiddlewareState,
+} from './types'
+
+export const buildPollingHandler: InternalHandlerBuilder = ({
+  reducerPath,
+  queryThunk,
+  api,
+  refetchQuery,
+  internalState,
+}) => {
+  const { currentPolls, currentSubscriptions } = internalState
+
+  // Batching state for polling updates
+  const pendingPollingUpdates = new Set<string>()
+  let pollingUpdateTimer: ReturnType<typeof setTimeout> | null = null
+
+  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {
+    if (
+      api.internalActions.updateSubscriptionOptions.match(action) ||
+      api.internalActions.unsubscribeQueryResult.match(action)
+    ) {
+      schedulePollingUpdate(action.payload.queryCacheKey, mwApi)
+    }
+
+    if (
+      queryThunk.pending.match(action) ||
+      (queryThunk.rejected.match(action) && action.meta.condition)
+    ) {
+      schedulePollingUpdate(action.meta.arg.queryCacheKey, mwApi)
+    }
+
+    if (
+      queryThunk.fulfilled.match(action) ||
+      (queryThunk.rejected.match(action) && !action.meta.condition)
+    ) {
+      startNextPoll(action.meta.arg, mwApi)
+    }
+
+    if (api.util.resetApiState.match(action)) {
+      clearPolls()
+      // Clear any pending updates
+      if (pollingUpdateTimer) {
+        clearTimeout(pollingUpdateTimer)
+        pollingUpdateTimer = null
+      }
+      pendingPollingUpdates.clear()
+    }
+  }
+
+  function schedulePollingUpdate(queryCacheKey: string, api: SubMiddlewareApi) {
+    pendingPollingUpdates.add(queryCacheKey)
+
+    if (!pollingUpdateTimer) {
+      pollingUpdateTimer = setTimeout(() => {
+        // Process all pending updates in a single batch
+        for (const key of pendingPollingUpdates) {
+          updatePollingInterval({ queryCacheKey: key as any }, api)
+        }
+        pendingPollingUpdates.clear()
+        pollingUpdateTimer = null
+      }, 0)
+    }
+  }
+
+  function startNextPoll(
+    { queryCacheKey }: QuerySubstateIdentifier,
+    api: SubMiddlewareApi,
+  ) {
+    const state = api.getState()[reducerPath]
+    const querySubState = state.queries[queryCacheKey]
+    const subscriptions = currentSubscriptions.get(queryCacheKey)
+
+    if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) return
+
+    const { lowestPollingInterval, skipPollingIfUnfocused } =
+      findLowestPollingInterval(subscriptions)
+    if (!Number.isFinite(lowestPollingInterval)) return
+
+    const currentPoll = currentPolls.get(queryCacheKey)
+
+    if (currentPoll?.timeout) {
+      clearTimeout(currentPoll.timeout)
+      currentPoll.timeout = undefined
+    }
+
+    const nextPollTimestamp = Date.now() + lowestPollingInterval
+
+    currentPolls.set(queryCacheKey, {
+      nextPollTimestamp,
+      pollingInterval: lowestPollingInterval,
+      timeout: setTimeout(() => {
+        if (state.config.focused || !skipPollingIfUnfocused) {
+          api.dispatch(refetchQuery(querySubState))
+        }
+        startNextPoll({ queryCacheKey }, api)
+      }, lowestPollingInterval),
+    })
+  }
+
+  function updatePollingInterval(
+    { queryCacheKey }: QuerySubstateIdentifier,
+    api: SubMiddlewareApi,
+  ) {
+    const state = api.getState()[reducerPath]
+    const querySubState = state.queries[queryCacheKey]
+    const subscriptions = currentSubscriptions.get(queryCacheKey)
+
+    if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) {
+      return
+    }
+
+    const { lowestPollingInterval } = findLowestPollingInterval(subscriptions)
+
+    // HACK add extra data to track how many times this has been called in tests
+    // yes we're mutating a nonexistent field on a Map here
+    if (process.env.NODE_ENV === 'test') {
+      const updateCounters = ((currentPolls as any).pollUpdateCounters ??= {})
+      updateCounters[queryCacheKey] ??= 0
+      updateCounters[queryCacheKey]++
+    }
+
+    if (!Number.isFinite(lowestPollingInterval)) {
+      cleanupPollForKey(queryCacheKey)
+      return
+    }
+
+    const currentPoll = currentPolls.get(queryCacheKey)
+
+    const nextPollTimestamp = Date.now() + lowestPollingInterval
+
+    if (!currentPoll || nextPollTimestamp < currentPoll.nextPollTimestamp) {
+      startNextPoll({ queryCacheKey }, api)
+    }
+  }
+
+  function cleanupPollForKey(key: string) {
+    const existingPoll = currentPolls.get(key)
+    if (existingPoll?.timeout) {
+      clearTimeout(existingPoll.timeout)
+    }
+    currentPolls.delete(key)
+  }
+
+  function clearPolls() {
+    for (const key of currentPolls.keys()) {
+      cleanupPollForKey(key)
+    }
+  }
+
+  function findLowestPollingInterval(
+    subscribers: SubscribersInternal = new Map(),
+  ) {
+    let skipPollingIfUnfocused: boolean | undefined = false
+    let lowestPollingInterval = Number.POSITIVE_INFINITY
+
+    for (const entry of subscribers.values()) {
+      if (!!entry.pollingInterval) {
+        lowestPollingInterval = Math.min(
+          entry.pollingInterval!,
+          lowestPollingInterval,
+        )
+        skipPollingIfUnfocused =
+          entry.skipPollingIfUnfocused || skipPollingIfUnfocused
+      }
+    }
+
+    return {
+      lowestPollingInterval,
+      skipPollingIfUnfocused,
+    }
+  }
+
+  return handler
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/queryLifecycle.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/queryLifecycle.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/queryLifecycle.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,505 @@
+import { getEndpointDefinition } from '@internal/query/apiTypes'
+import type {
+  BaseQueryError,
+  BaseQueryFn,
+  BaseQueryMeta,
+} from '../../baseQueryTypes'
+import { isAnyQueryDefinition } from '../../endpointDefinitions'
+import type { Recipe } from '../buildThunks'
+import { isFulfilled, isPending, isRejected } from '../rtkImports'
+import type {
+  MutationBaseLifecycleApi,
+  QueryBaseLifecycleApi,
+} from './cacheLifecycle'
+import type {
+  ApiMiddlewareInternalHandler,
+  InternalHandlerBuilder,
+  PromiseConstructorWithKnownReason,
+  PromiseWithKnownReason,
+} from './types'
+
+export type ReferenceQueryLifecycle = never
+
+type QueryLifecyclePromises<ResultType, BaseQuery extends BaseQueryFn> = {
+  /**
+   * Promise that will resolve with the (transformed) query result.
+   *
+   * If the query fails, this promise will reject with the error.
+   *
+   * This allows you to `await` for the query to finish.
+   *
+   * If you don't interact with this promise, it will not throw.
+   */
+  queryFulfilled: PromiseWithKnownReason<
+    {
+      /**
+       * The (transformed) query result.
+       */
+      data: ResultType
+      /**
+       * The `meta` returned by the `baseQuery`
+       */
+      meta: BaseQueryMeta<BaseQuery>
+    },
+    QueryFulfilledRejectionReason<BaseQuery>
+  >
+}
+
+type QueryFulfilledRejectionReason<BaseQuery extends BaseQueryFn> =
+  | {
+      error: BaseQueryError<BaseQuery>
+      /**
+       * If this is `false`, that means this error was returned from the `baseQuery` or `queryFn` in a controlled manner.
+       */
+      isUnhandledError: false
+      /**
+       * The `meta` returned by the `baseQuery`
+       */
+      meta: BaseQueryMeta<BaseQuery>
+    }
+  | {
+      error: unknown
+      meta?: undefined
+      /**
+       * If this is `true`, that means that this error is the result of `baseQueryFn`, `queryFn`, `transformResponse` or `transformErrorResponse` throwing an error instead of handling it properly.
+       * There can not be made any assumption about the shape of `error`.
+       */
+      isUnhandledError: true
+    }
+
+export type QueryLifecycleQueryExtraOptions<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ReducerPath extends string = string,
+> = {
+  /**
+   * A function that is called when the individual query is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).
+   *
+   * Can be used to perform side-effects throughout the lifecycle of the query.
+   *
+   * @example
+   * ```ts
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+   * import { messageCreated } from './notificationsSlice
+   * export interface Post {
+   *   id: number
+   *   name: string
+   * }
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({
+   *     baseUrl: '/',
+   *   }),
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, number>({
+   *       query: (id) => `post/${id}`,
+   *       async onQueryStarted(id, { dispatch, queryFulfilled }) {
+   *         // `onStart` side-effect
+   *         dispatch(messageCreated('Fetching posts...'))
+   *         try {
+   *           const { data } = await queryFulfilled
+   *           // `onSuccess` side-effect
+   *           dispatch(messageCreated('Posts received!'))
+   *         } catch (err) {
+   *           // `onError` side-effect
+   *           dispatch(messageCreated('Error fetching posts!'))
+   *         }
+   *       }
+   *     }),
+   *   }),
+   * })
+   * ```
+   */
+  onQueryStarted?(
+    queryArgument: QueryArg,
+    queryLifeCycleApi: QueryLifecycleApi<
+      QueryArg,
+      BaseQuery,
+      ResultType,
+      ReducerPath
+    >,
+  ): Promise<void> | void
+}
+
+export type QueryLifecycleInfiniteQueryExtraOptions<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ReducerPath extends string = string,
+> = QueryLifecycleQueryExtraOptions<
+  ResultType,
+  QueryArg,
+  BaseQuery,
+  ReducerPath
+>
+
+export type QueryLifecycleMutationExtraOptions<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ReducerPath extends string = string,
+> = {
+  /**
+   * A function that is called when the individual mutation is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).
+   *
+   * Can be used for `optimistic updates`.
+   *
+   * @example
+   *
+   * ```ts
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+   * export interface Post {
+   *   id: number
+   *   name: string
+   * }
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({
+   *     baseUrl: '/',
+   *   }),
+   *   tagTypes: ['Post'],
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, number>({
+   *       query: (id) => `post/${id}`,
+   *       providesTags: ['Post'],
+   *     }),
+   *     updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({
+   *       query: ({ id, ...patch }) => ({
+   *         url: `post/${id}`,
+   *         method: 'PATCH',
+   *         body: patch,
+   *       }),
+   *       invalidatesTags: ['Post'],
+   *       async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
+   *         const patchResult = dispatch(
+   *           api.util.updateQueryData('getPost', id, (draft) => {
+   *             Object.assign(draft, patch)
+   *           })
+   *         )
+   *         try {
+   *           await queryFulfilled
+   *         } catch {
+   *           patchResult.undo()
+   *         }
+   *       },
+   *     }),
+   *   }),
+   * })
+   * ```
+   */
+  onQueryStarted?(
+    queryArgument: QueryArg,
+    mutationLifeCycleApi: MutationLifecycleApi<
+      QueryArg,
+      BaseQuery,
+      ResultType,
+      ReducerPath
+    >,
+  ): Promise<void> | void
+}
+
+export interface QueryLifecycleApi<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ResultType,
+  ReducerPath extends string = string,
+> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>,
+    QueryLifecyclePromises<ResultType, BaseQuery> {}
+
+export type MutationLifecycleApi<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ResultType,
+  ReducerPath extends string = string,
+> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> &
+  QueryLifecyclePromises<ResultType, BaseQuery>
+
+/**
+ * Provides a way to define a strongly-typed version of
+ * {@linkcode QueryLifecycleQueryExtraOptions.onQueryStarted | onQueryStarted}
+ * for a specific query.
+ *
+ * @example
+ * <caption>#### __Create and reuse a strongly-typed `onQueryStarted` function__</caption>
+ *
+ * ```ts
+ * import type { TypedQueryOnQueryStarted } from '@reduxjs/toolkit/query'
+ * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+ *
+ * type Post = {
+ *   id: number
+ *   title: string
+ *   userId: number
+ * }
+ *
+ * type PostsApiResponse = {
+ *   posts: Post[]
+ *   total: number
+ *   skip: number
+ *   limit: number
+ * }
+ *
+ * type QueryArgument = number | undefined
+ *
+ * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>
+ *
+ * const baseApiSlice = createApi({
+ *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),
+ *   reducerPath: 'postsApi',
+ *   tagTypes: ['Posts'],
+ *   endpoints: (build) => ({
+ *     getPosts: build.query<PostsApiResponse, void>({
+ *       query: () => `/posts`,
+ *     }),
+ *
+ *     getPostById: build.query<Post, QueryArgument>({
+ *       query: (postId) => `/posts/${postId}`,
+ *     }),
+ *   }),
+ * })
+ *
+ * const updatePostOnFulfilled: TypedQueryOnQueryStarted<
+ *   PostsApiResponse,
+ *   QueryArgument,
+ *   BaseQueryFunction,
+ *   'postsApi'
+ * > = async (queryArgument, { dispatch, queryFulfilled }) => {
+ *   const result = await queryFulfilled
+ *
+ *   const { posts } = result.data
+ *
+ *   // Pre-fill the individual post entries with the results
+ *   // from the list endpoint query
+ *   dispatch(
+ *     baseApiSlice.util.upsertQueryEntries(
+ *       posts.map((post) => ({
+ *         endpointName: 'getPostById',
+ *         arg: post.id,
+ *         value: post,
+ *       })),
+ *     ),
+ *   )
+ * }
+ *
+ * export const extendedApiSlice = baseApiSlice.injectEndpoints({
+ *   endpoints: (build) => ({
+ *     getPostsByUserId: build.query<PostsApiResponse, QueryArgument>({
+ *       query: (userId) => `/posts/user/${userId}`,
+ *
+ *       onQueryStarted: updatePostOnFulfilled,
+ *     }),
+ *   }),
+ * })
+ * ```
+ *
+ * @template ResultType - The type of the result `data` returned by the query.
+ * @template QueryArgumentType - The type of the argument passed into the query.
+ * @template BaseQueryFunctionType - The type of the base query function being used.
+ * @template ReducerPath - The type representing the `reducerPath` for the API slice.
+ *
+ * @since 2.4.0
+ * @public
+ */
+export type TypedQueryOnQueryStarted<
+  ResultType,
+  QueryArgumentType,
+  BaseQueryFunctionType extends BaseQueryFn,
+  ReducerPath extends string = string,
+> = QueryLifecycleQueryExtraOptions<
+  ResultType,
+  QueryArgumentType,
+  BaseQueryFunctionType,
+  ReducerPath
+>['onQueryStarted']
+
+/**
+ * Provides a way to define a strongly-typed version of
+ * {@linkcode QueryLifecycleMutationExtraOptions.onQueryStarted | onQueryStarted}
+ * for a specific mutation.
+ *
+ * @example
+ * <caption>#### __Create and reuse a strongly-typed `onQueryStarted` function__</caption>
+ *
+ * ```ts
+ * import type { TypedMutationOnQueryStarted } from '@reduxjs/toolkit/query'
+ * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+ *
+ * type Post = {
+ *   id: number
+ *   title: string
+ *   userId: number
+ * }
+ *
+ * type PostsApiResponse = {
+ *   posts: Post[]
+ *   total: number
+ *   skip: number
+ *   limit: number
+ * }
+ *
+ * type QueryArgument = Pick<Post, 'id'> & Partial<Post>
+ *
+ * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>
+ *
+ * const baseApiSlice = createApi({
+ *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),
+ *   reducerPath: 'postsApi',
+ *   tagTypes: ['Posts'],
+ *   endpoints: (build) => ({
+ *     getPosts: build.query<PostsApiResponse, void>({
+ *       query: () => `/posts`,
+ *     }),
+ *
+ *     getPostById: build.query<Post, number>({
+ *       query: (postId) => `/posts/${postId}`,
+ *     }),
+ *   }),
+ * })
+ *
+ * const updatePostOnFulfilled: TypedMutationOnQueryStarted<
+ *   Post,
+ *   QueryArgument,
+ *   BaseQueryFunction,
+ *   'postsApi'
+ * > = async ({ id, ...patch }, { dispatch, queryFulfilled }) => {
+ *   const patchCollection = dispatch(
+ *     baseApiSlice.util.updateQueryData('getPostById', id, (draftPost) => {
+ *       Object.assign(draftPost, patch)
+ *     }),
+ *   )
+ *
+ *   try {
+ *     await queryFulfilled
+ *   } catch {
+ *     patchCollection.undo()
+ *   }
+ * }
+ *
+ * export const extendedApiSlice = baseApiSlice.injectEndpoints({
+ *   endpoints: (build) => ({
+ *     addPost: build.mutation<Post, Omit<QueryArgument, 'id'>>({
+ *       query: (body) => ({
+ *         url: `posts/add`,
+ *         method: 'POST',
+ *         body,
+ *       }),
+ *
+ *       onQueryStarted: updatePostOnFulfilled,
+ *     }),
+ *
+ *     updatePost: build.mutation<Post, QueryArgument>({
+ *       query: ({ id, ...patch }) => ({
+ *         url: `post/${id}`,
+ *         method: 'PATCH',
+ *         body: patch,
+ *       }),
+ *
+ *       onQueryStarted: updatePostOnFulfilled,
+ *     }),
+ *   }),
+ * })
+ * ```
+ *
+ * @template ResultType - The type of the result `data` returned by the query.
+ * @template QueryArgumentType - The type of the argument passed into the query.
+ * @template BaseQueryFunctionType - The type of the base query function being used.
+ * @template ReducerPath - The type representing the `reducerPath` for the API slice.
+ *
+ * @since 2.4.0
+ * @public
+ */
+export type TypedMutationOnQueryStarted<
+  ResultType,
+  QueryArgumentType,
+  BaseQueryFunctionType extends BaseQueryFn,
+  ReducerPath extends string = string,
+> = QueryLifecycleMutationExtraOptions<
+  ResultType,
+  QueryArgumentType,
+  BaseQueryFunctionType,
+  ReducerPath
+>['onQueryStarted']
+
+export const buildQueryLifecycleHandler: InternalHandlerBuilder = ({
+  api,
+  context,
+  queryThunk,
+  mutationThunk,
+}) => {
+  const isPendingThunk = isPending(queryThunk, mutationThunk)
+  const isRejectedThunk = isRejected(queryThunk, mutationThunk)
+  const isFullfilledThunk = isFulfilled(queryThunk, mutationThunk)
+
+  type CacheLifecycle = {
+    resolve(value: { data: unknown; meta: unknown }): unknown
+    reject(value: QueryFulfilledRejectionReason<any>): unknown
+  }
+  const lifecycleMap: Record<string, CacheLifecycle> = {}
+
+  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {
+    if (isPendingThunk(action)) {
+      const {
+        requestId,
+        arg: { endpointName, originalArgs },
+      } = action.meta
+      const endpointDefinition = getEndpointDefinition(context, endpointName)
+      const onQueryStarted = endpointDefinition?.onQueryStarted
+      if (onQueryStarted) {
+        const lifecycle = {} as CacheLifecycle
+        const queryFulfilled =
+          new (Promise as PromiseConstructorWithKnownReason)<
+            { data: unknown; meta: unknown },
+            QueryFulfilledRejectionReason<any>
+          >((resolve, reject) => {
+            lifecycle.resolve = resolve
+            lifecycle.reject = reject
+          })
+        // prevent uncaught promise rejections from happening.
+        // if the original promise is used in any way, that will create a new promise that will throw again
+        queryFulfilled.catch(() => {})
+        lifecycleMap[requestId] = lifecycle
+        const selector = (api.endpoints[endpointName] as any).select(
+          isAnyQueryDefinition(endpointDefinition) ? originalArgs : requestId,
+        )
+
+        const extra = mwApi.dispatch((_, __, extra) => extra)
+        const lifecycleApi = {
+          ...mwApi,
+          getCacheEntry: () => selector(mwApi.getState()),
+          requestId,
+          extra,
+          updateCachedData: (isAnyQueryDefinition(endpointDefinition)
+            ? (updateRecipe: Recipe<any>) =>
+                mwApi.dispatch(
+                  api.util.updateQueryData(
+                    endpointName as never,
+                    originalArgs as never,
+                    updateRecipe,
+                  ),
+                )
+            : undefined) as any,
+          queryFulfilled,
+        }
+        onQueryStarted(originalArgs, lifecycleApi as any)
+      }
+    } else if (isFullfilledThunk(action)) {
+      const { requestId, baseQueryMeta } = action.meta
+      lifecycleMap[requestId]?.resolve({
+        data: action.payload,
+        meta: baseQueryMeta,
+      })
+      delete lifecycleMap[requestId]
+    } else if (isRejectedThunk(action)) {
+      const { requestId, rejectedWithValue, baseQueryMeta } = action.meta
+      lifecycleMap[requestId]?.reject({
+        error: action.payload ?? action.error,
+        isUnhandledError: !rejectedWithValue,
+        meta: baseQueryMeta as any,
+      })
+      delete lifecycleMap[requestId]
+    }
+  }
+
+  return handler
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/types.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/types.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/types.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,173 @@
+import type {
+  Action,
+  AsyncThunkAction,
+  Dispatch,
+  Middleware,
+  MiddlewareAPI,
+  ThunkAction,
+  ThunkDispatch,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import type { Api, ApiContext } from '../../apiTypes'
+import type {
+  AssertTagTypes,
+  EndpointDefinitions,
+} from '../../endpointDefinitions'
+import type {
+  QueryStatus,
+  QuerySubState,
+  RootState,
+  SubscriptionInternalState,
+  SubscriptionState,
+} from '../apiState'
+import type {
+  InfiniteQueryThunk,
+  MutationThunk,
+  QueryThunk,
+  QueryThunkArg,
+  ThunkResult,
+} from '../buildThunks'
+import type {
+  InfiniteQueryActionCreatorResult,
+  MutationActionCreatorResult,
+  QueryActionCreatorResult,
+} from '../buildInitiate'
+import type { AllSelectors } from '../buildSelectors'
+
+export type QueryStateMeta<T> = Record<string, undefined | T>
+export type TimeoutId = ReturnType<typeof setTimeout>
+
+type QueryPollState = {
+  nextPollTimestamp: number
+  timeout?: TimeoutId
+  pollingInterval: number
+}
+
+export interface InternalMiddlewareState {
+  currentSubscriptions: SubscriptionInternalState
+  currentPolls: Map<string, QueryPollState>
+  runningQueries: Map<
+    string,
+    | QueryActionCreatorResult<any>
+    | InfiniteQueryActionCreatorResult<any>
+    | undefined
+  >
+  runningMutations: Map<string, MutationActionCreatorResult<any> | undefined>
+}
+
+export interface SubscriptionSelectors {
+  getSubscriptions: () => SubscriptionInternalState
+  getSubscriptionCount: (queryCacheKey: string) => number
+  isRequestSubscribed: (queryCacheKey: string, requestId: string) => boolean
+}
+
+export interface BuildMiddlewareInput<
+  Definitions extends EndpointDefinitions,
+  ReducerPath extends string,
+  TagTypes extends string,
+> {
+  reducerPath: ReducerPath
+  context: ApiContext<Definitions>
+  queryThunk: QueryThunk
+  mutationThunk: MutationThunk
+  infiniteQueryThunk: InfiniteQueryThunk<any>
+  api: Api<any, Definitions, ReducerPath, TagTypes>
+  assertTagType: AssertTagTypes
+  selectors: AllSelectors
+  getRunningQueryThunk: (
+    endpointName: string,
+    queryArgs: any,
+  ) => (dispatch: Dispatch) => QueryActionCreatorResult<any> | undefined
+  getInternalState: (dispatch: Dispatch) => InternalMiddlewareState
+}
+
+export type SubMiddlewareApi = MiddlewareAPI<
+  ThunkDispatch<any, any, UnknownAction>,
+  RootState<EndpointDefinitions, string, string>
+>
+
+export interface BuildSubMiddlewareInput
+  extends BuildMiddlewareInput<EndpointDefinitions, string, string> {
+  internalState: InternalMiddlewareState
+  refetchQuery(
+    querySubState: Exclude<
+      QuerySubState<any>,
+      { status: QueryStatus.uninitialized }
+    >,
+  ): ThunkAction<QueryActionCreatorResult<any>, any, any, UnknownAction>
+  isThisApiSliceAction: (action: Action) => boolean
+  selectors: AllSelectors
+  mwApi: MiddlewareAPI<
+    ThunkDispatch<any, any, UnknownAction>,
+    RootState<EndpointDefinitions, string, string>
+  >
+}
+
+export type SubMiddlewareBuilder = (
+  input: BuildSubMiddlewareInput,
+) => Middleware<
+  {},
+  RootState<EndpointDefinitions, string, string>,
+  ThunkDispatch<any, any, UnknownAction>
+>
+
+type MwNext = Parameters<ReturnType<Middleware>>[0]
+
+export type ApiMiddlewareInternalHandler<Return = void> = (
+  action: Action,
+  mwApi: SubMiddlewareApi & { next: MwNext },
+  prevState: RootState<EndpointDefinitions, string, string>,
+) => Return
+
+export type InternalHandlerBuilder<ReturnType = void> = (
+  input: BuildSubMiddlewareInput,
+) => ApiMiddlewareInternalHandler<ReturnType>
+
+export interface PromiseConstructorWithKnownReason {
+  /**
+   * Creates a new Promise with a known rejection reason.
+   * @param executor A callback used to initialize the promise. This callback is passed two arguments:
+   * a resolve callback used to resolve the promise with a value or the result of another promise,
+   * and a reject callback used to reject the promise with a provided reason or error.
+   */
+  new <T, R>(
+    executor: (
+      resolve: (value: T | PromiseLike<T>) => void,
+      reject: (reason?: R) => void,
+    ) => void,
+  ): PromiseWithKnownReason<T, R>
+}
+
+export type PromiseWithKnownReason<T, R> = Omit<
+  Promise<T>,
+  'then' | 'catch'
+> & {
+  /**
+   * Attaches callbacks for the resolution and/or rejection of the Promise.
+   * @param onfulfilled The callback to execute when the Promise is resolved.
+   * @param onrejected The callback to execute when the Promise is rejected.
+   * @returns A Promise for the completion of which ever callback is executed.
+   */
+  then<TResult1 = T, TResult2 = never>(
+    onfulfilled?:
+      | ((value: T) => TResult1 | PromiseLike<TResult1>)
+      | undefined
+      | null,
+    onrejected?:
+      | ((reason: R) => TResult2 | PromiseLike<TResult2>)
+      | undefined
+      | null,
+  ): Promise<TResult1 | TResult2>
+
+  /**
+   * Attaches a callback for only the rejection of the Promise.
+   * @param onrejected The callback to execute when the Promise is rejected.
+   * @returns A Promise for the completion of the callback.
+   */
+  catch<TResult = never>(
+    onrejected?:
+      | ((reason: R) => TResult | PromiseLike<TResult>)
+      | undefined
+      | null,
+  ): Promise<T | TResult>
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/windowEventHandling.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/windowEventHandling.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/windowEventHandling.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,64 @@
+import { QueryStatus, STATUS_UNINITIALIZED } from '../apiState'
+import type { QueryCacheKey } from '../apiState'
+import { onFocus, onOnline } from '../setupListeners'
+import type {
+  ApiMiddlewareInternalHandler,
+  InternalHandlerBuilder,
+  SubMiddlewareApi,
+} from './types'
+
+export const buildWindowEventHandler: InternalHandlerBuilder = ({
+  reducerPath,
+  context,
+  api,
+  refetchQuery,
+  internalState,
+}) => {
+  const { removeQueryResult } = api.internalActions
+
+  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {
+    if (onFocus.match(action)) {
+      refetchValidQueries(mwApi, 'refetchOnFocus')
+    }
+    if (onOnline.match(action)) {
+      refetchValidQueries(mwApi, 'refetchOnReconnect')
+    }
+  }
+
+  function refetchValidQueries(
+    api: SubMiddlewareApi,
+    type: 'refetchOnFocus' | 'refetchOnReconnect',
+  ) {
+    const state = api.getState()[reducerPath]
+    const queries = state.queries
+    const subscriptions = internalState.currentSubscriptions
+
+    context.batch(() => {
+      for (const queryCacheKey of subscriptions.keys()) {
+        const querySubState = queries[queryCacheKey]
+        const subscriptionSubState = subscriptions.get(queryCacheKey)
+
+        if (!subscriptionSubState || !querySubState) continue
+
+        const values = [...subscriptionSubState.values()]
+        const shouldRefetch =
+          values.some((sub) => sub[type] === true) ||
+          (values.every((sub) => sub[type] === undefined) && state.config[type])
+
+        if (shouldRefetch) {
+          if (subscriptionSubState.size === 0) {
+            api.dispatch(
+              removeQueryResult({
+                queryCacheKey: queryCacheKey as QueryCacheKey,
+              }),
+            )
+          } else if (querySubState.status !== STATUS_UNINITIALIZED) {
+            api.dispatch(refetchQuery(querySubState))
+          }
+        }
+      }
+    })
+  }
+
+  return handler
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/buildSelectors.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildSelectors.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildSelectors.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,413 @@
+import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'
+import type {
+  EndpointDefinition,
+  EndpointDefinitions,
+  InfiniteQueryArgFrom,
+  InfiniteQueryDefinition,
+  MutationDefinition,
+  QueryArgFrom,
+  QueryArgFromAnyQuery,
+  QueryDefinition,
+  ReducerPathFrom,
+  TagDescription,
+  TagTypesFrom,
+} from '../endpointDefinitions'
+import { expandTagDescription } from '../endpointDefinitions'
+import { filterMap, isNotNullish } from '../utils'
+import type {
+  InfiniteData,
+  InfiniteQueryConfigOptions,
+  InfiniteQuerySubState,
+  MutationSubState,
+  QueryCacheKey,
+  QueryState,
+  QuerySubState,
+  RequestStatusFlags,
+  RootState as _RootState,
+  QueryStatus,
+} from './apiState'
+import { STATUS_UNINITIALIZED, getRequestStatusFlags } from './apiState'
+import { getMutationCacheKey } from './buildSlice'
+import type { createSelector as _createSelector } from './rtkImports'
+import { createNextState } from './rtkImports'
+import {
+  type AllQueryKeys,
+  getNextPageParam,
+  getPreviousPageParam,
+} from './buildThunks'
+
+export type SkipToken = typeof skipToken
+/**
+ * Can be passed into `useQuery`, `useQueryState` or `useQuerySubscription`
+ * instead of the query argument to get the same effect as if setting
+ * `skip: true` in the query options.
+ *
+ * Useful for scenarios where a query should be skipped when `arg` is `undefined`
+ * and TypeScript complains about it because `arg` is not allowed to be passed
+ * in as `undefined`, such as
+ *
+ * ```ts
+ * // codeblock-meta title="will error if the query argument is not allowed to be undefined" no-transpile
+ * useSomeQuery(arg, { skip: !!arg })
+ * ```
+ *
+ * ```ts
+ * // codeblock-meta title="using skipToken instead" no-transpile
+ * useSomeQuery(arg ?? skipToken)
+ * ```
+ *
+ * If passed directly into a query or mutation selector, that selector will always
+ * return an uninitialized state.
+ */
+export const skipToken = /* @__PURE__ */ Symbol.for('RTKQ/skipToken')
+
+export type BuildSelectorsApiEndpointQuery<
+  Definition extends QueryDefinition<any, any, any, any, any>,
+  Definitions extends EndpointDefinitions,
+> = {
+  select: QueryResultSelectorFactory<
+    Definition,
+    _RootState<
+      Definitions,
+      TagTypesFrom<Definition>,
+      ReducerPathFrom<Definition>
+    >
+  >
+}
+
+export type BuildSelectorsApiEndpointInfiniteQuery<
+  Definition extends InfiniteQueryDefinition<any, any, any, any, any>,
+  Definitions extends EndpointDefinitions,
+> = {
+  select: InfiniteQueryResultSelectorFactory<
+    Definition,
+    _RootState<
+      Definitions,
+      TagTypesFrom<Definition>,
+      ReducerPathFrom<Definition>
+    >
+  >
+}
+
+export type BuildSelectorsApiEndpointMutation<
+  Definition extends MutationDefinition<any, any, any, any, any>,
+  Definitions extends EndpointDefinitions,
+> = {
+  select: MutationResultSelectorFactory<
+    Definition,
+    _RootState<
+      Definitions,
+      TagTypesFrom<Definition>,
+      ReducerPathFrom<Definition>
+    >
+  >
+}
+
+type QueryResultSelectorFactory<
+  Definition extends QueryDefinition<any, any, any, any>,
+  RootState,
+> = (
+  queryArg: QueryArgFrom<Definition> | SkipToken,
+) => (state: RootState) => QueryResultSelectorResult<Definition>
+
+export type QueryResultSelectorResult<
+  Definition extends QueryDefinition<any, any, any, any>,
+> = QuerySubState<Definition> & RequestStatusFlags
+
+type InfiniteQueryResultSelectorFactory<
+  Definition extends InfiniteQueryDefinition<any, any, any, any, any>,
+  RootState,
+> = (
+  queryArg: InfiniteQueryArgFrom<Definition> | SkipToken,
+) => (state: RootState) => InfiniteQueryResultSelectorResult<Definition>
+
+export type InfiniteQueryResultFlags = {
+  hasNextPage: boolean
+  hasPreviousPage: boolean
+  isFetchingNextPage: boolean
+  isFetchingPreviousPage: boolean
+  isFetchNextPageError: boolean
+  isFetchPreviousPageError: boolean
+}
+
+export type InfiniteQueryResultSelectorResult<
+  Definition extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = InfiniteQuerySubState<Definition> &
+  RequestStatusFlags &
+  InfiniteQueryResultFlags
+
+type MutationResultSelectorFactory<
+  Definition extends MutationDefinition<any, any, any, any>,
+  RootState,
+> = (
+  requestId:
+    | string
+    | { requestId: string | undefined; fixedCacheKey: string | undefined }
+    | SkipToken,
+) => (state: RootState) => MutationResultSelectorResult<Definition>
+
+export type MutationResultSelectorResult<
+  Definition extends MutationDefinition<any, any, any, any>,
+> = MutationSubState<Definition> & RequestStatusFlags
+
+const initialSubState: QuerySubState<any> = {
+  status: STATUS_UNINITIALIZED,
+}
+
+// abuse immer to freeze default states
+const defaultQuerySubState = /* @__PURE__ */ createNextState(
+  initialSubState,
+  () => {},
+)
+const defaultMutationSubState = /* @__PURE__ */ createNextState(
+  initialSubState as MutationSubState<any>,
+  () => {},
+)
+
+export type AllSelectors = ReturnType<typeof buildSelectors>
+
+export function buildSelectors<
+  Definitions extends EndpointDefinitions,
+  ReducerPath extends string,
+>({
+  serializeQueryArgs,
+  reducerPath,
+  createSelector,
+}: {
+  serializeQueryArgs: InternalSerializeQueryArgs
+  reducerPath: ReducerPath
+  createSelector: typeof _createSelector
+}) {
+  type RootState = _RootState<Definitions, string, string>
+
+  const selectSkippedQuery = (state: RootState) => defaultQuerySubState
+  const selectSkippedMutation = (state: RootState) => defaultMutationSubState
+
+  return {
+    buildQuerySelector,
+    buildInfiniteQuerySelector,
+    buildMutationSelector,
+    selectInvalidatedBy,
+    selectCachedArgsForQuery,
+    selectApiState,
+    selectQueries,
+    selectMutations,
+    selectQueryEntry,
+    selectConfig,
+  }
+
+  function withRequestFlags<T extends { status: QueryStatus }>(
+    substate: T,
+  ): T & RequestStatusFlags {
+    return { ...substate, ...getRequestStatusFlags(substate.status) }
+  }
+
+  function selectApiState(rootState: RootState) {
+    const state = rootState[reducerPath]
+    if (process.env.NODE_ENV !== 'production') {
+      if (!state) {
+        if ((selectApiState as any).triggered) return state
+        ;(selectApiState as any).triggered = true
+        console.error(
+          `Error: No data found at \`state.${reducerPath}\`. Did you forget to add the reducer to the store?`,
+        )
+      }
+    }
+    return state
+  }
+
+  function selectQueries(rootState: RootState) {
+    return selectApiState(rootState)?.queries
+  }
+
+  function selectQueryEntry(rootState: RootState, cacheKey: QueryCacheKey) {
+    return selectQueries(rootState)?.[cacheKey]
+  }
+
+  function selectMutations(rootState: RootState) {
+    return selectApiState(rootState)?.mutations
+  }
+
+  function selectConfig(rootState: RootState) {
+    return selectApiState(rootState)?.config
+  }
+
+  function buildAnyQuerySelector(
+    endpointName: string,
+    endpointDefinition: EndpointDefinition<any, any, any, any>,
+    combiner: <T extends { status: QueryStatus }>(
+      substate: T,
+    ) => T & RequestStatusFlags,
+  ) {
+    return (queryArgs: any) => {
+      // Avoid calling serializeQueryArgs if the arg is skipToken
+      if (queryArgs === skipToken) {
+        return createSelector(selectSkippedQuery, combiner)
+      }
+
+      const serializedArgs = serializeQueryArgs({
+        queryArgs,
+        endpointDefinition,
+        endpointName,
+      })
+      const selectQuerySubstate = (state: RootState) =>
+        selectQueryEntry(state, serializedArgs) ?? defaultQuerySubState
+
+      return createSelector(selectQuerySubstate, combiner)
+    }
+  }
+
+  function buildQuerySelector(
+    endpointName: string,
+    endpointDefinition: QueryDefinition<any, any, any, any>,
+  ) {
+    return buildAnyQuerySelector(
+      endpointName,
+      endpointDefinition,
+      withRequestFlags,
+    ) as QueryResultSelectorFactory<any, RootState>
+  }
+
+  function buildInfiniteQuerySelector(
+    endpointName: string,
+    endpointDefinition: InfiniteQueryDefinition<any, any, any, any, any>,
+  ) {
+    const { infiniteQueryOptions } = endpointDefinition
+
+    function withInfiniteQueryResultFlags<T extends { status: QueryStatus }>(
+      substate: T,
+    ): T & RequestStatusFlags & InfiniteQueryResultFlags {
+      const stateWithRequestFlags = {
+        ...(substate as InfiniteQuerySubState<any>),
+        ...getRequestStatusFlags(substate.status),
+      }
+
+      const { isLoading, isError, direction } = stateWithRequestFlags
+      const isForward = direction === 'forward'
+      const isBackward = direction === 'backward'
+
+      return {
+        ...stateWithRequestFlags,
+        hasNextPage: getHasNextPage(
+          infiniteQueryOptions,
+          stateWithRequestFlags.data,
+          stateWithRequestFlags.originalArgs,
+        ),
+        hasPreviousPage: getHasPreviousPage(
+          infiniteQueryOptions,
+          stateWithRequestFlags.data,
+          stateWithRequestFlags.originalArgs,
+        ),
+        isFetchingNextPage: isLoading && isForward,
+        isFetchingPreviousPage: isLoading && isBackward,
+        isFetchNextPageError: isError && isForward,
+        isFetchPreviousPageError: isError && isBackward,
+      }
+    }
+
+    return buildAnyQuerySelector(
+      endpointName,
+      endpointDefinition,
+      withInfiniteQueryResultFlags,
+    ) as unknown as InfiniteQueryResultSelectorFactory<any, RootState>
+  }
+
+  function buildMutationSelector() {
+    return ((id) => {
+      let mutationId: string | typeof skipToken
+      if (typeof id === 'object') {
+        mutationId = getMutationCacheKey(id) ?? skipToken
+      } else {
+        mutationId = id
+      }
+      const selectMutationSubstate = (state: RootState) =>
+        selectApiState(state)?.mutations?.[mutationId as string] ??
+        defaultMutationSubState
+      const finalSelectMutationSubstate =
+        mutationId === skipToken
+          ? selectSkippedMutation
+          : selectMutationSubstate
+
+      return createSelector(finalSelectMutationSubstate, withRequestFlags)
+    }) as MutationResultSelectorFactory<any, RootState>
+  }
+
+  function selectInvalidatedBy(
+    state: RootState,
+    tags: ReadonlyArray<TagDescription<string> | null | undefined>,
+  ): Array<{
+    endpointName: string
+    originalArgs: any
+    queryCacheKey: QueryCacheKey
+  }> {
+    const apiState = state[reducerPath]
+    const toInvalidate = new Set<QueryCacheKey>()
+    const finalTags = filterMap(tags, isNotNullish, expandTagDescription)
+    for (const tag of finalTags) {
+      const provided = apiState.provided.tags[tag.type]
+      if (!provided) {
+        continue
+      }
+
+      let invalidateSubscriptions =
+        (tag.id !== undefined
+          ? // id given: invalidate all queries that provide this type & id
+            provided[tag.id]
+          : // no id: invalidate all queries that provide this type
+            Object.values(provided).flat()) ?? []
+
+      for (const invalidate of invalidateSubscriptions) {
+        toInvalidate.add(invalidate)
+      }
+    }
+
+    return Array.from(toInvalidate.values()).flatMap((queryCacheKey) => {
+      const querySubState = apiState.queries[queryCacheKey]
+      return querySubState
+        ? {
+            queryCacheKey,
+            endpointName: querySubState.endpointName!,
+            originalArgs: querySubState.originalArgs,
+          }
+        : []
+    })
+  }
+
+  function selectCachedArgsForQuery<
+    QueryName extends AllQueryKeys<Definitions>,
+  >(
+    state: RootState,
+    queryName: QueryName,
+  ): Array<QueryArgFromAnyQuery<Definitions[QueryName]>> {
+    return filterMap(
+      Object.values(selectQueries(state) as QueryState<any>),
+      (
+        entry,
+      ): entry is Exclude<
+        QuerySubState<Definitions[QueryName]>,
+        { status: QueryStatus.uninitialized }
+      > =>
+        entry?.endpointName === queryName &&
+        entry.status !== STATUS_UNINITIALIZED,
+      (entry) => entry.originalArgs,
+    )
+  }
+
+  function getHasNextPage(
+    options: InfiniteQueryConfigOptions<any, any, any>,
+    data?: InfiniteData<unknown, unknown>,
+    queryArg?: unknown,
+  ): boolean {
+    if (!data) return false
+    return getNextPageParam(options, data, queryArg) != null
+  }
+
+  function getHasPreviousPage(
+    options: InfiniteQueryConfigOptions<any, any, any>,
+    data?: InfiniteData<unknown, unknown>,
+    queryArg?: unknown,
+  ): boolean {
+    if (!data || !options.getPreviousPageParam) return false
+    return getPreviousPageParam(options, data, queryArg) != null
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/buildSlice.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildSlice.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildSlice.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,735 @@
+import type { PayloadAction } from '@reduxjs/toolkit'
+import {
+  combineReducers,
+  createAction,
+  createSlice,
+  isAnyOf,
+  isFulfilled,
+  isRejectedWithValue,
+  createNextState,
+  prepareAutoBatched,
+  SHOULD_AUTOBATCH,
+  nanoid,
+} from './rtkImports'
+import type {
+  QuerySubstateIdentifier,
+  QuerySubState,
+  MutationSubstateIdentifier,
+  MutationSubState,
+  MutationState,
+  QueryState,
+  InvalidationState,
+  Subscribers,
+  QueryCacheKey,
+  SubscriptionState,
+  ConfigState,
+  InfiniteQuerySubState,
+  InfiniteQueryDirection,
+} from './apiState'
+import {
+  STATUS_FULFILLED,
+  STATUS_PENDING,
+  QueryStatus,
+  STATUS_REJECTED,
+  STATUS_UNINITIALIZED,
+} from './apiState'
+import type {
+  AllQueryKeys,
+  QueryArgFromAnyQueryDefinition,
+  DataFromAnyQueryDefinition,
+  InfiniteQueryThunk,
+  MutationThunk,
+  QueryThunk,
+  QueryThunkArg,
+} from './buildThunks'
+import { calculateProvidedByThunk } from './buildThunks'
+import {
+  ENDPOINT_QUERY,
+  isInfiniteQueryDefinition,
+  type AssertTagTypes,
+  type EndpointDefinitions,
+  type FullTagDescription,
+  type QueryDefinition,
+} from '../endpointDefinitions'
+import type { Patch } from 'immer'
+import { applyPatches, original, isDraft } from '../utils/immerImports'
+import { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners'
+import {
+  isDocumentVisible,
+  isOnline,
+  copyWithStructuralSharing,
+} from '../utils'
+import type { ApiContext } from '../apiTypes'
+import { isUpsertQuery } from './buildInitiate'
+import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'
+import type { UnwrapPromise } from '../tsHelpers'
+import { getCurrent } from '../utils/getCurrent'
+
+/**
+ * A typesafe single entry to be upserted into the cache
+ */
+export type NormalizedQueryUpsertEntry<
+  Definitions extends EndpointDefinitions,
+  EndpointName extends AllQueryKeys<Definitions>,
+> = {
+  endpointName: EndpointName
+  arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>
+  value: DataFromAnyQueryDefinition<Definitions, EndpointName>
+}
+
+/**
+ * The internal version that is not typesafe since we can't carry the generics through `createSlice`
+ */
+type NormalizedQueryUpsertEntryPayload = {
+  endpointName: string
+  arg: unknown
+  value: unknown
+}
+
+export type ProcessedQueryUpsertEntry = {
+  queryDescription: QueryThunkArg
+  value: unknown
+}
+
+/**
+ * A typesafe representation of a util action creator that accepts cache entry descriptions to upsert
+ */
+export type UpsertEntries<Definitions extends EndpointDefinitions> = (<
+  EndpointNames extends Array<AllQueryKeys<Definitions>>,
+>(
+  entries: [
+    ...{
+      [I in keyof EndpointNames]: NormalizedQueryUpsertEntry<
+        Definitions,
+        EndpointNames[I]
+      >
+    },
+  ],
+) => PayloadAction<NormalizedQueryUpsertEntryPayload[]>) & {
+  match: (
+    action: unknown,
+  ) => action is PayloadAction<NormalizedQueryUpsertEntryPayload[]>
+}
+
+function updateQuerySubstateIfExists(
+  state: QueryState<any>,
+  queryCacheKey: QueryCacheKey,
+  update: (substate: QuerySubState<any> | InfiniteQuerySubState<any>) => void,
+) {
+  const substate = state[queryCacheKey]
+  if (substate) {
+    update(substate)
+  }
+}
+
+export function getMutationCacheKey(
+  id:
+    | MutationSubstateIdentifier
+    | { requestId: string; arg: { fixedCacheKey?: string | undefined } },
+): string
+export function getMutationCacheKey(id: {
+  fixedCacheKey?: string
+  requestId?: string
+}): string | undefined
+
+export function getMutationCacheKey(
+  id:
+    | { fixedCacheKey?: string; requestId?: string }
+    | MutationSubstateIdentifier
+    | { requestId: string; arg: { fixedCacheKey?: string | undefined } },
+): string | undefined {
+  return ('arg' in id ? id.arg.fixedCacheKey : id.fixedCacheKey) ?? id.requestId
+}
+
+function updateMutationSubstateIfExists(
+  state: MutationState<any>,
+  id:
+    | MutationSubstateIdentifier
+    | { requestId: string; arg: { fixedCacheKey?: string | undefined } },
+  update: (substate: MutationSubState<any>) => void,
+) {
+  const substate = state[getMutationCacheKey(id)]
+  if (substate) {
+    update(substate)
+  }
+}
+
+const initialState = {} as any
+
+export function buildSlice({
+  reducerPath,
+  queryThunk,
+  mutationThunk,
+  serializeQueryArgs,
+  context: {
+    endpointDefinitions: definitions,
+    apiUid,
+    extractRehydrationInfo,
+    hasRehydrationInfo,
+  },
+  assertTagType,
+  config,
+}: {
+  reducerPath: string
+  queryThunk: QueryThunk
+  infiniteQueryThunk: InfiniteQueryThunk<any>
+  mutationThunk: MutationThunk
+  serializeQueryArgs: InternalSerializeQueryArgs
+  context: ApiContext<EndpointDefinitions>
+  assertTagType: AssertTagTypes
+  config: Omit<
+    ConfigState<string>,
+    'online' | 'focused' | 'middlewareRegistered'
+  >
+}) {
+  const resetApiState = createAction(`${reducerPath}/resetApiState`)
+
+  function writePendingCacheEntry(
+    draft: QueryState<any>,
+    arg: QueryThunkArg,
+    upserting: boolean,
+    meta: {
+      arg: QueryThunkArg
+      requestId: string
+      // requestStatus: 'pending'
+    } & { startedTimeStamp: number },
+  ) {
+    draft[arg.queryCacheKey] ??= {
+      status: STATUS_UNINITIALIZED,
+      endpointName: arg.endpointName,
+    }
+
+    updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {
+      substate.status = STATUS_PENDING
+
+      substate.requestId =
+        upserting && substate.requestId
+          ? // for `upsertQuery` **updates**, keep the current `requestId`
+            substate.requestId
+          : // for normal queries or `upsertQuery` **inserts** always update the `requestId`
+            meta.requestId
+      if (arg.originalArgs !== undefined) {
+        substate.originalArgs = arg.originalArgs
+      }
+      substate.startedTimeStamp = meta.startedTimeStamp
+
+      const endpointDefinition = definitions[meta.arg.endpointName]
+
+      if (isInfiniteQueryDefinition(endpointDefinition) && 'direction' in arg) {
+        ;(substate as InfiniteQuerySubState<any>).direction =
+          arg.direction as InfiniteQueryDirection
+      }
+    })
+  }
+
+  function writeFulfilledCacheEntry(
+    draft: QueryState<any>,
+    meta: { arg: QueryThunkArg; requestId: string } & {
+      fulfilledTimeStamp: number
+      baseQueryMeta: unknown
+    },
+    payload: unknown,
+    upserting: boolean,
+  ) {
+    updateQuerySubstateIfExists(draft, meta.arg.queryCacheKey, (substate) => {
+      if (substate.requestId !== meta.requestId && !upserting) return
+      const { merge } = definitions[meta.arg.endpointName] as QueryDefinition<
+        any,
+        any,
+        any,
+        any
+      >
+      substate.status = STATUS_FULFILLED
+
+      if (merge) {
+        if (substate.data !== undefined) {
+          const { fulfilledTimeStamp, arg, baseQueryMeta, requestId } = meta
+          // There's existing cache data. Let the user merge it in themselves.
+          // We're already inside an Immer-powered reducer, and the user could just mutate `substate.data`
+          // themselves inside of `merge()`. But, they might also want to return a new value.
+          // Try to let Immer figure that part out, save the result, and assign it to `substate.data`.
+          let newData = createNextState(substate.data, (draftSubstateData) => {
+            // As usual with Immer, you can mutate _or_ return inside here, but not both
+            return merge(draftSubstateData, payload, {
+              arg: arg.originalArgs,
+              baseQueryMeta,
+              fulfilledTimeStamp,
+              requestId,
+            })
+          })
+          substate.data = newData
+        } else {
+          // Presumably a fresh request. Just cache the response data.
+          substate.data = payload
+        }
+      } else {
+        // Assign or safely update the cache data.
+        substate.data =
+          (definitions[meta.arg.endpointName].structuralSharing ?? true)
+            ? copyWithStructuralSharing(
+                isDraft(substate.data)
+                  ? original(substate.data)
+                  : substate.data,
+                payload,
+              )
+            : payload
+      }
+
+      delete substate.error
+      substate.fulfilledTimeStamp = meta.fulfilledTimeStamp
+    })
+  }
+
+  const querySlice = createSlice({
+    name: `${reducerPath}/queries`,
+    initialState: initialState as QueryState<any>,
+    reducers: {
+      removeQueryResult: {
+        reducer(
+          draft,
+          {
+            payload: { queryCacheKey },
+          }: PayloadAction<QuerySubstateIdentifier>,
+        ) {
+          delete draft[queryCacheKey]
+        },
+        prepare: prepareAutoBatched<QuerySubstateIdentifier>(),
+      },
+      cacheEntriesUpserted: {
+        reducer(
+          draft,
+          action: PayloadAction<
+            ProcessedQueryUpsertEntry[],
+            string,
+            { RTK_autoBatch: boolean; requestId: string; timestamp: number }
+          >,
+        ) {
+          for (const entry of action.payload) {
+            const { queryDescription: arg, value } = entry
+            writePendingCacheEntry(draft, arg, true, {
+              arg,
+              requestId: action.meta.requestId,
+              startedTimeStamp: action.meta.timestamp,
+            })
+
+            writeFulfilledCacheEntry(
+              draft,
+              {
+                arg,
+                requestId: action.meta.requestId,
+                fulfilledTimeStamp: action.meta.timestamp,
+                baseQueryMeta: {},
+              },
+              value,
+              // We know we're upserting here
+              true,
+            )
+          }
+        },
+        prepare: (payload: NormalizedQueryUpsertEntryPayload[]) => {
+          const queryDescriptions: ProcessedQueryUpsertEntry[] = payload.map(
+            (entry) => {
+              const { endpointName, arg, value } = entry
+              const endpointDefinition = definitions[endpointName]
+              const queryDescription: QueryThunkArg = {
+                type: ENDPOINT_QUERY as 'query',
+                endpointName,
+                originalArgs: entry.arg,
+                queryCacheKey: serializeQueryArgs({
+                  queryArgs: arg,
+                  endpointDefinition,
+                  endpointName,
+                }),
+              }
+              return { queryDescription, value }
+            },
+          )
+
+          const result = {
+            payload: queryDescriptions,
+            meta: {
+              [SHOULD_AUTOBATCH]: true,
+              requestId: nanoid(),
+              timestamp: Date.now(),
+            },
+          }
+          return result
+        },
+      },
+      queryResultPatched: {
+        reducer(
+          draft,
+          {
+            payload: { queryCacheKey, patches },
+          }: PayloadAction<
+            QuerySubstateIdentifier & { patches: readonly Patch[] }
+          >,
+        ) {
+          updateQuerySubstateIfExists(draft, queryCacheKey, (substate) => {
+            substate.data = applyPatches(substate.data as any, patches.concat())
+          })
+        },
+        prepare: prepareAutoBatched<
+          QuerySubstateIdentifier & { patches: readonly Patch[] }
+        >(),
+      },
+    },
+    extraReducers(builder) {
+      builder
+        .addCase(queryThunk.pending, (draft, { meta, meta: { arg } }) => {
+          const upserting = isUpsertQuery(arg)
+          writePendingCacheEntry(draft, arg, upserting, meta)
+        })
+        .addCase(queryThunk.fulfilled, (draft, { meta, payload }) => {
+          const upserting = isUpsertQuery(meta.arg)
+          writeFulfilledCacheEntry(draft, meta, payload, upserting)
+        })
+        .addCase(
+          queryThunk.rejected,
+          (draft, { meta: { condition, arg, requestId }, error, payload }) => {
+            updateQuerySubstateIfExists(
+              draft,
+              arg.queryCacheKey,
+              (substate) => {
+                if (condition) {
+                  // request was aborted due to condition (another query already running)
+                } else {
+                  // request failed
+                  if (substate.requestId !== requestId) return
+                  substate.status = STATUS_REJECTED
+                  substate.error = (payload ?? error) as any
+                }
+              },
+            )
+          },
+        )
+        .addMatcher(hasRehydrationInfo, (draft, action) => {
+          const { queries } = extractRehydrationInfo(action)!
+          for (const [key, entry] of Object.entries(queries)) {
+            if (
+              // do not rehydrate entries that were currently in flight.
+              entry?.status === STATUS_FULFILLED ||
+              entry?.status === STATUS_REJECTED
+            ) {
+              draft[key] = entry
+            }
+          }
+        })
+    },
+  })
+  const mutationSlice = createSlice({
+    name: `${reducerPath}/mutations`,
+    initialState: initialState as MutationState<any>,
+    reducers: {
+      removeMutationResult: {
+        reducer(draft, { payload }: PayloadAction<MutationSubstateIdentifier>) {
+          const cacheKey = getMutationCacheKey(payload)
+          if (cacheKey in draft) {
+            delete draft[cacheKey]
+          }
+        },
+        prepare: prepareAutoBatched<MutationSubstateIdentifier>(),
+      },
+    },
+    extraReducers(builder) {
+      builder
+        .addCase(
+          mutationThunk.pending,
+          (draft, { meta, meta: { requestId, arg, startedTimeStamp } }) => {
+            if (!arg.track) return
+
+            draft[getMutationCacheKey(meta)] = {
+              requestId,
+              status: STATUS_PENDING,
+              endpointName: arg.endpointName,
+              startedTimeStamp,
+            }
+          },
+        )
+        .addCase(mutationThunk.fulfilled, (draft, { payload, meta }) => {
+          if (!meta.arg.track) return
+
+          updateMutationSubstateIfExists(draft, meta, (substate) => {
+            if (substate.requestId !== meta.requestId) return
+            substate.status = STATUS_FULFILLED
+            substate.data = payload
+            substate.fulfilledTimeStamp = meta.fulfilledTimeStamp
+          })
+        })
+        .addCase(mutationThunk.rejected, (draft, { payload, error, meta }) => {
+          if (!meta.arg.track) return
+
+          updateMutationSubstateIfExists(draft, meta, (substate) => {
+            if (substate.requestId !== meta.requestId) return
+
+            substate.status = STATUS_REJECTED
+            substate.error = (payload ?? error) as any
+          })
+        })
+        .addMatcher(hasRehydrationInfo, (draft, action) => {
+          const { mutations } = extractRehydrationInfo(action)!
+          for (const [key, entry] of Object.entries(mutations)) {
+            if (
+              // do not rehydrate entries that were currently in flight.
+              (entry?.status === STATUS_FULFILLED ||
+                entry?.status === STATUS_REJECTED) &&
+              // only rehydrate endpoints that were persisted using a `fixedCacheKey`
+              key !== entry?.requestId
+            ) {
+              draft[key] = entry
+            }
+          }
+        })
+    },
+  })
+
+  type CalculateProvidedByAction = UnwrapPromise<
+    | ReturnType<ReturnType<QueryThunk>>
+    | ReturnType<ReturnType<InfiniteQueryThunk<any>>>
+  >
+
+  const initialInvalidationState: InvalidationState<string> = {
+    tags: {},
+    keys: {},
+  }
+
+  const invalidationSlice = createSlice({
+    name: `${reducerPath}/invalidation`,
+    initialState: initialInvalidationState,
+    reducers: {
+      updateProvidedBy: {
+        reducer(
+          draft,
+          action: PayloadAction<
+            Array<{
+              queryCacheKey: QueryCacheKey
+              providedTags: readonly FullTagDescription<string>[]
+            }>
+          >,
+        ) {
+          for (const { queryCacheKey, providedTags } of action.payload) {
+            removeCacheKeyFromTags(draft, queryCacheKey)
+
+            for (const { type, id } of providedTags) {
+              const subscribedQueries = ((draft.tags[type] ??= {})[
+                id || '__internal_without_id'
+              ] ??= [])
+              const alreadySubscribed =
+                subscribedQueries.includes(queryCacheKey)
+              if (!alreadySubscribed) {
+                subscribedQueries.push(queryCacheKey)
+              }
+            }
+
+            // Remove readonly from the providedTags array
+            draft.keys[queryCacheKey] =
+              providedTags as FullTagDescription<string>[]
+          }
+        },
+        prepare: prepareAutoBatched<
+          Array<{
+            queryCacheKey: QueryCacheKey
+            providedTags: readonly FullTagDescription<string>[]
+          }>
+        >(),
+      },
+    },
+    extraReducers(builder) {
+      builder
+        .addCase(
+          querySlice.actions.removeQueryResult,
+          (draft, { payload: { queryCacheKey } }) => {
+            removeCacheKeyFromTags(draft, queryCacheKey)
+          },
+        )
+        .addMatcher(hasRehydrationInfo, (draft, action) => {
+          const { provided } = extractRehydrationInfo(action)!
+          for (const [type, incomingTags] of Object.entries(
+            provided.tags ?? {},
+          )) {
+            for (const [id, cacheKeys] of Object.entries(incomingTags)) {
+              const subscribedQueries = ((draft.tags[type] ??= {})[
+                id || '__internal_without_id'
+              ] ??= [])
+              for (const queryCacheKey of cacheKeys) {
+                const alreadySubscribed =
+                  subscribedQueries.includes(queryCacheKey)
+                if (!alreadySubscribed) {
+                  subscribedQueries.push(queryCacheKey)
+                }
+                draft.keys[queryCacheKey] = provided.keys[queryCacheKey]
+              }
+            }
+          }
+        })
+        .addMatcher(
+          isAnyOf(isFulfilled(queryThunk), isRejectedWithValue(queryThunk)),
+          (draft, action) => {
+            writeProvidedTagsForQueries(draft, [action])
+          },
+        )
+        .addMatcher(
+          querySlice.actions.cacheEntriesUpserted.match,
+          (draft, action) => {
+            const mockActions: CalculateProvidedByAction[] = action.payload.map(
+              ({ queryDescription, value }) => {
+                return {
+                  type: 'UNKNOWN',
+                  payload: value,
+                  meta: {
+                    requestStatus: 'fulfilled',
+                    requestId: 'UNKNOWN',
+                    arg: queryDescription,
+                  },
+                }
+              },
+            )
+            writeProvidedTagsForQueries(draft, mockActions)
+          },
+        )
+    },
+  })
+
+  function removeCacheKeyFromTags(
+    draft: InvalidationState<any>,
+    queryCacheKey: QueryCacheKey,
+  ) {
+    const existingTags = getCurrent(draft.keys[queryCacheKey] ?? [])
+
+    // Delete this cache key from any existing tags that may have provided it
+    for (const tag of existingTags) {
+      const tagType = tag.type
+      const tagId = tag.id ?? '__internal_without_id'
+      const tagSubscriptions = draft.tags[tagType]?.[tagId]
+
+      if (tagSubscriptions) {
+        draft.tags[tagType][tagId] = getCurrent(tagSubscriptions).filter(
+          (qc) => qc !== queryCacheKey,
+        )
+      }
+    }
+
+    delete draft.keys[queryCacheKey]
+  }
+
+  function writeProvidedTagsForQueries(
+    draft: InvalidationState<string>,
+    actions: CalculateProvidedByAction[],
+  ) {
+    const providedByEntries = actions.map((action) => {
+      const providedTags = calculateProvidedByThunk(
+        action,
+        'providesTags',
+        definitions,
+        assertTagType,
+      )
+      const { queryCacheKey } = action.meta.arg
+      return { queryCacheKey, providedTags }
+    })
+
+    invalidationSlice.caseReducers.updateProvidedBy(
+      draft,
+      invalidationSlice.actions.updateProvidedBy(providedByEntries),
+    )
+  }
+
+  // Dummy slice to generate actions
+  const subscriptionSlice = createSlice({
+    name: `${reducerPath}/subscriptions`,
+    initialState: initialState as SubscriptionState,
+    reducers: {
+      updateSubscriptionOptions(
+        d,
+        a: PayloadAction<
+          {
+            endpointName: string
+            requestId: string
+            options: Subscribers[number]
+          } & QuerySubstateIdentifier
+        >,
+      ) {
+        // Dummy
+      },
+      unsubscribeQueryResult(
+        d,
+        a: PayloadAction<{ requestId: string } & QuerySubstateIdentifier>,
+      ) {
+        // Dummy
+      },
+      internal_getRTKQSubscriptions() {},
+    },
+  })
+
+  const internalSubscriptionsSlice = createSlice({
+    name: `${reducerPath}/internalSubscriptions`,
+    initialState: initialState as SubscriptionState,
+    reducers: {
+      subscriptionsUpdated: {
+        reducer(state, action: PayloadAction<Patch[]>) {
+          return applyPatches(state, action.payload)
+        },
+        prepare: prepareAutoBatched<Patch[]>(),
+      },
+    },
+  })
+
+  const configSlice = createSlice({
+    name: `${reducerPath}/config`,
+    initialState: {
+      online: isOnline(),
+      focused: isDocumentVisible(),
+      middlewareRegistered: false,
+      ...config,
+    } as ConfigState<string>,
+    reducers: {
+      middlewareRegistered(state, { payload }: PayloadAction<string>) {
+        state.middlewareRegistered =
+          state.middlewareRegistered === 'conflict' || apiUid !== payload
+            ? 'conflict'
+            : true
+      },
+    },
+    extraReducers: (builder) => {
+      builder
+        .addCase(onOnline, (state) => {
+          state.online = true
+        })
+        .addCase(onOffline, (state) => {
+          state.online = false
+        })
+        .addCase(onFocus, (state) => {
+          state.focused = true
+        })
+        .addCase(onFocusLost, (state) => {
+          state.focused = false
+        })
+        // update the state to be a new object to be picked up as a "state change"
+        // by redux-persist's `autoMergeLevel2`
+        .addMatcher(hasRehydrationInfo, (draft) => ({ ...draft }))
+    },
+  })
+
+  const combinedReducer = combineReducers({
+    queries: querySlice.reducer,
+    mutations: mutationSlice.reducer,
+    provided: invalidationSlice.reducer,
+    subscriptions: internalSubscriptionsSlice.reducer,
+    config: configSlice.reducer,
+  })
+
+  const reducer: typeof combinedReducer = (state, action) =>
+    combinedReducer(resetApiState.match(action) ? undefined : state, action)
+
+  const actions = {
+    ...configSlice.actions,
+    ...querySlice.actions,
+    ...subscriptionSlice.actions,
+    ...internalSubscriptionsSlice.actions,
+    ...mutationSlice.actions,
+    ...invalidationSlice.actions,
+    resetApiState,
+  }
+
+  return { reducer, actions }
+}
+export type SliceActions = ReturnType<typeof buildSlice>['actions']
Index: node_modules/@reduxjs/toolkit/src/query/core/buildThunks.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildThunks.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildThunks.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1124 @@
+import type {
+  AsyncThunk,
+  AsyncThunkPayloadCreator,
+  Draft,
+  ThunkAction,
+  ThunkDispatch,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import type { Patch } from 'immer'
+import { isDraftable, produceWithPatches } from '../utils/immerImports'
+import type { Api, ApiContext } from '../apiTypes'
+import type {
+  BaseQueryError,
+  BaseQueryFn,
+  QueryReturnValue,
+} from '../baseQueryTypes'
+import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'
+import type {
+  AssertTagTypes,
+  EndpointDefinition,
+  EndpointDefinitions,
+  InfiniteQueryArgFrom,
+  InfiniteQueryCombinedArg,
+  InfiniteQueryDefinition,
+  MutationDefinition,
+  PageParamFrom,
+  QueryArgFrom,
+  QueryDefinition,
+  ResultDescription,
+  ResultTypeFrom,
+  SchemaFailureConverter,
+  SchemaFailureHandler,
+  SchemaFailureInfo,
+  SchemaType,
+} from '../endpointDefinitions'
+import {
+  calculateProvidedBy,
+  ENDPOINT_QUERY,
+  isInfiniteQueryDefinition,
+  isQueryDefinition,
+} from '../endpointDefinitions'
+import { HandledError } from '../HandledError'
+import type { UnwrapPromise } from '../tsHelpers'
+import type {
+  RootState,
+  QueryKeys,
+  QuerySubstateIdentifier,
+  InfiniteData,
+  InfiniteQueryConfigOptions,
+  QueryCacheKey,
+  InfiniteQueryDirection,
+  InfiniteQueryKeys,
+} from './apiState'
+import { QueryStatus, STATUS_UNINITIALIZED } from './apiState'
+import type {
+  InfiniteQueryActionCreatorResult,
+  QueryActionCreatorResult,
+  StartInfiniteQueryActionCreatorOptions,
+  StartQueryActionCreatorOptions,
+} from './buildInitiate'
+import { forceQueryFnSymbol, isUpsertQuery } from './buildInitiate'
+import type { AllSelectors } from './buildSelectors'
+import type { ApiEndpointQuery, PrefetchOptions } from './module'
+import {
+  createAsyncThunk,
+  isAllOf,
+  isFulfilled,
+  isPending,
+  isRejected,
+  isRejectedWithValue,
+  SHOULD_AUTOBATCH,
+} from './rtkImports'
+import {
+  parseWithSchema,
+  NamedSchemaError,
+  shouldSkip,
+} from '../standardSchema'
+
+export type BuildThunksApiEndpointQuery<
+  Definition extends QueryDefinition<any, any, any, any, any>,
+> = Matchers<QueryThunk, Definition>
+
+export type BuildThunksApiEndpointInfiniteQuery<
+  Definition extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = Matchers<InfiniteQueryThunk<any>, Definition>
+
+export type BuildThunksApiEndpointMutation<
+  Definition extends MutationDefinition<any, any, any, any, any>,
+> = Matchers<MutationThunk, Definition>
+
+type EndpointThunk<
+  Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>,
+  Definition extends EndpointDefinition<any, any, any, any>,
+> =
+  Definition extends EndpointDefinition<
+    infer QueryArg,
+    infer BaseQueryFn,
+    any,
+    infer ResultType
+  >
+    ? Thunk extends AsyncThunk<unknown, infer ATArg, infer ATConfig>
+      ? AsyncThunk<
+          ResultType,
+          ATArg & { originalArgs: QueryArg },
+          ATConfig & { rejectValue: BaseQueryError<BaseQueryFn> }
+        >
+      : never
+    : Definition extends InfiniteQueryDefinition<
+          infer QueryArg,
+          infer PageParam,
+          infer BaseQueryFn,
+          any,
+          infer ResultType
+        >
+      ? Thunk extends AsyncThunk<unknown, infer ATArg, infer ATConfig>
+        ? AsyncThunk<
+            InfiniteData<ResultType, PageParam>,
+            ATArg & { originalArgs: QueryArg },
+            ATConfig & { rejectValue: BaseQueryError<BaseQueryFn> }
+          >
+        : never
+      : never
+
+export type PendingAction<
+  Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>,
+  Definition extends EndpointDefinition<any, any, any, any>,
+> = ReturnType<EndpointThunk<Thunk, Definition>['pending']>
+
+export type FulfilledAction<
+  Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>,
+  Definition extends EndpointDefinition<any, any, any, any>,
+> = ReturnType<EndpointThunk<Thunk, Definition>['fulfilled']>
+
+export type RejectedAction<
+  Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>,
+  Definition extends EndpointDefinition<any, any, any, any>,
+> = ReturnType<EndpointThunk<Thunk, Definition>['rejected']>
+
+export type Matcher<M> = (value: any) => value is M
+
+export interface Matchers<
+  Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>,
+  Definition extends EndpointDefinition<any, any, any, any>,
+> {
+  matchPending: Matcher<PendingAction<Thunk, Definition>>
+  matchFulfilled: Matcher<FulfilledAction<Thunk, Definition>>
+  matchRejected: Matcher<RejectedAction<Thunk, Definition>>
+}
+
+export type QueryThunkArg = QuerySubstateIdentifier &
+  StartQueryActionCreatorOptions & {
+    type: 'query'
+    originalArgs: unknown
+    endpointName: string
+  }
+
+export type InfiniteQueryThunkArg<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = QuerySubstateIdentifier &
+  StartInfiniteQueryActionCreatorOptions<D> & {
+    type: `query`
+    originalArgs: unknown
+    endpointName: string
+    param: unknown
+    direction?: InfiniteQueryDirection
+    refetchCachedPages?: boolean
+  }
+
+type MutationThunkArg = {
+  type: 'mutation'
+  originalArgs: unknown
+  endpointName: string
+  track?: boolean
+  fixedCacheKey?: string
+}
+
+export type ThunkResult = unknown
+
+export type ThunkApiMetaConfig = {
+  pendingMeta: { startedTimeStamp: number; [SHOULD_AUTOBATCH]: true }
+  fulfilledMeta: {
+    fulfilledTimeStamp: number
+    baseQueryMeta: unknown
+    [SHOULD_AUTOBATCH]: true
+  }
+  rejectedMeta: { baseQueryMeta: unknown; [SHOULD_AUTOBATCH]: true }
+}
+export type QueryThunk = AsyncThunk<
+  ThunkResult,
+  QueryThunkArg,
+  ThunkApiMetaConfig
+>
+export type InfiniteQueryThunk<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = AsyncThunk<ThunkResult, InfiniteQueryThunkArg<D>, ThunkApiMetaConfig>
+export type MutationThunk = AsyncThunk<
+  ThunkResult,
+  MutationThunkArg,
+  ThunkApiMetaConfig
+>
+
+function defaultTransformResponse(baseQueryReturnValue: unknown) {
+  return baseQueryReturnValue
+}
+
+export type MaybeDrafted<T> = T | Draft<T>
+export type Recipe<T> = (data: MaybeDrafted<T>) => void | MaybeDrafted<T>
+export type UpsertRecipe<T> = (
+  data: MaybeDrafted<T> | undefined,
+) => void | MaybeDrafted<T>
+
+export type PatchQueryDataThunk<
+  Definitions extends EndpointDefinitions,
+  PartialState,
+> = <EndpointName extends QueryKeys<Definitions>>(
+  endpointName: EndpointName,
+  arg: QueryArgFrom<Definitions[EndpointName]>,
+  patches: readonly Patch[],
+  updateProvided?: boolean,
+) => ThunkAction<void, PartialState, any, UnknownAction>
+
+export type AllQueryKeys<Definitions extends EndpointDefinitions> =
+  | QueryKeys<Definitions>
+  | InfiniteQueryKeys<Definitions>
+
+export type QueryArgFromAnyQueryDefinition<
+  Definitions extends EndpointDefinitions,
+  EndpointName extends AllQueryKeys<Definitions>,
+> =
+  Definitions[EndpointName] extends InfiniteQueryDefinition<
+    any,
+    any,
+    any,
+    any,
+    any
+  >
+    ? InfiniteQueryArgFrom<Definitions[EndpointName]>
+    : Definitions[EndpointName] extends QueryDefinition<any, any, any, any>
+      ? QueryArgFrom<Definitions[EndpointName]>
+      : never
+
+export type DataFromAnyQueryDefinition<
+  Definitions extends EndpointDefinitions,
+  EndpointName extends AllQueryKeys<Definitions>,
+> =
+  Definitions[EndpointName] extends InfiniteQueryDefinition<
+    any,
+    any,
+    any,
+    any,
+    any
+  >
+    ? InfiniteData<
+        ResultTypeFrom<Definitions[EndpointName]>,
+        PageParamFrom<Definitions[EndpointName]>
+      >
+    : Definitions[EndpointName] extends QueryDefinition<any, any, any, any>
+      ? ResultTypeFrom<Definitions[EndpointName]>
+      : unknown
+
+export type UpsertThunkResult<
+  Definitions extends EndpointDefinitions,
+  EndpointName extends AllQueryKeys<Definitions>,
+> =
+  Definitions[EndpointName] extends InfiniteQueryDefinition<
+    any,
+    any,
+    any,
+    any,
+    any
+  >
+    ? InfiniteQueryActionCreatorResult<Definitions[EndpointName]>
+    : Definitions[EndpointName] extends QueryDefinition<any, any, any, any>
+      ? QueryActionCreatorResult<Definitions[EndpointName]>
+      : QueryActionCreatorResult<never>
+
+export type UpdateQueryDataThunk<
+  Definitions extends EndpointDefinitions,
+  PartialState,
+> = <EndpointName extends AllQueryKeys<Definitions>>(
+  endpointName: EndpointName,
+  arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>,
+  updateRecipe: Recipe<DataFromAnyQueryDefinition<Definitions, EndpointName>>,
+  updateProvided?: boolean,
+) => ThunkAction<PatchCollection, PartialState, any, UnknownAction>
+
+export type UpsertQueryDataThunk<
+  Definitions extends EndpointDefinitions,
+  PartialState,
+> = <EndpointName extends AllQueryKeys<Definitions>>(
+  endpointName: EndpointName,
+  arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>,
+  value: DataFromAnyQueryDefinition<Definitions, EndpointName>,
+) => ThunkAction<
+  UpsertThunkResult<Definitions, EndpointName>,
+  PartialState,
+  any,
+  UnknownAction
+>
+
+/**
+ * An object returned from dispatching a `api.util.updateQueryData` call.
+ */
+export type PatchCollection = {
+  /**
+   * An `immer` Patch describing the cache update.
+   */
+  patches: Patch[]
+  /**
+   * An `immer` Patch to revert the cache update.
+   */
+  inversePatches: Patch[]
+  /**
+   * A function that will undo the cache update.
+   */
+  undo: () => void
+}
+
+type TransformCallback = (
+  baseQueryReturnValue: unknown,
+  meta: unknown,
+  arg: unknown,
+) => any
+
+export const addShouldAutoBatch = <T extends Record<string, any>>(
+  arg: T = {} as T,
+): T & { [SHOULD_AUTOBATCH]: true } => {
+  return { ...arg, [SHOULD_AUTOBATCH]: true }
+}
+
+export function buildThunks<
+  BaseQuery extends BaseQueryFn,
+  ReducerPath extends string,
+  Definitions extends EndpointDefinitions,
+>({
+  reducerPath,
+  baseQuery,
+  context: { endpointDefinitions },
+  serializeQueryArgs,
+  api,
+  assertTagType,
+  selectors,
+  onSchemaFailure,
+  catchSchemaFailure: globalCatchSchemaFailure,
+  skipSchemaValidation: globalSkipSchemaValidation,
+}: {
+  baseQuery: BaseQuery
+  reducerPath: ReducerPath
+  context: ApiContext<Definitions>
+  serializeQueryArgs: InternalSerializeQueryArgs
+  api: Api<BaseQuery, Definitions, ReducerPath, any>
+  assertTagType: AssertTagTypes
+  selectors: AllSelectors
+  onSchemaFailure: SchemaFailureHandler | undefined
+  catchSchemaFailure: SchemaFailureConverter<BaseQuery> | undefined
+  skipSchemaValidation: boolean | SchemaType[] | undefined
+}) {
+  type State = RootState<any, string, ReducerPath>
+
+  const patchQueryData: PatchQueryDataThunk<EndpointDefinitions, State> =
+    (endpointName, arg, patches, updateProvided) => (dispatch, getState) => {
+      const endpointDefinition = endpointDefinitions[endpointName]
+
+      const queryCacheKey = serializeQueryArgs({
+        queryArgs: arg,
+        endpointDefinition,
+        endpointName,
+      })
+
+      dispatch(
+        api.internalActions.queryResultPatched({ queryCacheKey, patches }),
+      )
+
+      if (!updateProvided) {
+        return
+      }
+
+      const newValue = api.endpoints[endpointName].select(arg)(
+        // Work around TS 4.1 mismatch
+        getState() as RootState<any, any, any>,
+      )
+
+      const providedTags = calculateProvidedBy(
+        endpointDefinition.providesTags,
+        newValue.data,
+        undefined,
+        arg,
+        {},
+        assertTagType,
+      )
+
+      dispatch(
+        api.internalActions.updateProvidedBy([{ queryCacheKey, providedTags }]),
+      )
+    }
+
+  function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {
+    const newItems = [item, ...items]
+    return max && newItems.length > max ? newItems.slice(0, -1) : newItems
+  }
+
+  function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {
+    const newItems = [...items, item]
+    return max && newItems.length > max ? newItems.slice(1) : newItems
+  }
+
+  const updateQueryData: UpdateQueryDataThunk<EndpointDefinitions, State> =
+    (endpointName, arg, updateRecipe, updateProvided = true) =>
+    (dispatch, getState) => {
+      const endpointDefinition = api.endpoints[endpointName]
+
+      const currentState = endpointDefinition.select(arg)(
+        // Work around TS 4.1 mismatch
+        getState() as RootState<any, any, any>,
+      )
+
+      const ret: PatchCollection = {
+        patches: [],
+        inversePatches: [],
+        undo: () =>
+          dispatch(
+            api.util.patchQueryData(
+              endpointName,
+              arg,
+              ret.inversePatches,
+              updateProvided,
+            ),
+          ),
+      }
+      if (currentState.status === STATUS_UNINITIALIZED) {
+        return ret
+      }
+      let newValue
+      if ('data' in currentState) {
+        if (isDraftable(currentState.data)) {
+          const [value, patches, inversePatches] = produceWithPatches(
+            currentState.data,
+            updateRecipe,
+          )
+          ret.patches.push(...patches)
+          ret.inversePatches.push(...inversePatches)
+          newValue = value
+        } else {
+          newValue = updateRecipe(currentState.data)
+          ret.patches.push({ op: 'replace', path: [], value: newValue })
+          ret.inversePatches.push({
+            op: 'replace',
+            path: [],
+            value: currentState.data,
+          })
+        }
+      }
+
+      if (ret.patches.length === 0) {
+        return ret
+      }
+
+      dispatch(
+        api.util.patchQueryData(endpointName, arg, ret.patches, updateProvided),
+      )
+
+      return ret
+    }
+
+  const upsertQueryData: UpsertQueryDataThunk<Definitions, State> =
+    (endpointName, arg, value) => (dispatch) => {
+      type EndpointName = typeof endpointName
+      const res = dispatch(
+        (
+          api.endpoints[endpointName] as ApiEndpointQuery<
+            QueryDefinition<any, any, any, any, any>,
+            Definitions
+          >
+        ).initiate(arg, {
+          subscribe: false,
+          forceRefetch: true,
+          [forceQueryFnSymbol]: () => ({ data: value }),
+        }),
+      ) as UpsertThunkResult<Definitions, EndpointName>
+
+      return res
+    }
+
+  const getTransformCallbackForEndpoint = (
+    endpointDefinition: EndpointDefinition<any, any, any, any>,
+    transformFieldName: 'transformResponse' | 'transformErrorResponse',
+  ): TransformCallback => {
+    return endpointDefinition.query && endpointDefinition[transformFieldName]
+      ? (endpointDefinition[transformFieldName]! as TransformCallback)
+      : defaultTransformResponse
+  }
+
+  // The generic async payload function for all of our thunks
+  const executeEndpoint: AsyncThunkPayloadCreator<
+    ThunkResult,
+    QueryThunkArg | MutationThunkArg | InfiniteQueryThunkArg<any>,
+    ThunkApiMetaConfig & { state: RootState<any, string, ReducerPath> }
+  > = async (
+    arg,
+    {
+      signal,
+      abort,
+      rejectWithValue,
+      fulfillWithValue,
+      dispatch,
+      getState,
+      extra,
+    },
+  ) => {
+    const endpointDefinition = endpointDefinitions[arg.endpointName]
+    const { metaSchema, skipSchemaValidation = globalSkipSchemaValidation } =
+      endpointDefinition
+
+    const isQuery = arg.type === ENDPOINT_QUERY
+
+    try {
+      let transformResponse: TransformCallback = defaultTransformResponse
+
+      const baseQueryApi = {
+        signal,
+        abort,
+        dispatch,
+        getState,
+        extra,
+        endpoint: arg.endpointName,
+        type: arg.type,
+        forced: isQuery ? isForcedQuery(arg, getState()) : undefined,
+        queryCacheKey: isQuery ? arg.queryCacheKey : undefined,
+      }
+
+      const forceQueryFn = isQuery ? arg[forceQueryFnSymbol] : undefined
+
+      let finalQueryReturnValue: QueryReturnValue
+
+      // Infinite query wrapper, which executes the request and returns
+      // the InfiniteData `{pages, pageParams}` structure
+      const fetchPage = async (
+        data: InfiniteData<unknown, unknown>,
+        param: unknown,
+        maxPages: number,
+        previous?: boolean,
+      ): Promise<QueryReturnValue> => {
+        // This should handle cases where there is no `getPrevPageParam`,
+        // or `getPPP` returned nullish
+        if (param == null && data.pages.length) {
+          return Promise.resolve({ data })
+        }
+
+        const finalQueryArg: InfiniteQueryCombinedArg<any, any> = {
+          queryArg: arg.originalArgs,
+          pageParam: param,
+        }
+
+        const pageResponse = await executeRequest(finalQueryArg)
+
+        const addTo = previous ? addToStart : addToEnd
+
+        return {
+          data: {
+            pages: addTo(data.pages, pageResponse.data, maxPages),
+            pageParams: addTo(data.pageParams, param, maxPages),
+          },
+          meta: pageResponse.meta,
+        }
+      }
+
+      // Wrapper for executing either `query` or `queryFn`,
+      // and handling any errors
+      async function executeRequest(
+        finalQueryArg: unknown,
+      ): Promise<QueryReturnValue> {
+        let result: QueryReturnValue
+        const { extraOptions, argSchema, rawResponseSchema, responseSchema } =
+          endpointDefinition
+
+        if (argSchema && !shouldSkip(skipSchemaValidation, 'arg')) {
+          finalQueryArg = await parseWithSchema(
+            argSchema,
+            finalQueryArg,
+            'argSchema',
+            {}, // we don't have a meta yet, so we can't pass it
+          )
+        }
+
+        if (forceQueryFn) {
+          // upsertQueryData relies on this to pass in the user-provided value
+          result = forceQueryFn()
+        } else if (endpointDefinition.query) {
+          // We should only run `transformResponse` when the endpoint has a `query` method,
+          // and we're not doing an `upsertQueryData`.
+          transformResponse = getTransformCallbackForEndpoint(
+            endpointDefinition,
+            'transformResponse',
+          )
+
+          result = await baseQuery(
+            endpointDefinition.query(finalQueryArg as any),
+            baseQueryApi,
+            extraOptions as any,
+          )
+        } else {
+          result = await endpointDefinition.queryFn(
+            finalQueryArg as any,
+            baseQueryApi,
+            extraOptions as any,
+            (arg) => baseQuery(arg, baseQueryApi, extraOptions as any),
+          )
+        }
+
+        if (
+          typeof process !== 'undefined' &&
+          process.env.NODE_ENV === 'development'
+        ) {
+          const what = endpointDefinition.query ? '`baseQuery`' : '`queryFn`'
+          let err: undefined | string
+          if (!result) {
+            err = `${what} did not return anything.`
+          } else if (typeof result !== 'object') {
+            err = `${what} did not return an object.`
+          } else if (result.error && result.data) {
+            err = `${what} returned an object containing both \`error\` and \`result\`.`
+          } else if (result.error === undefined && result.data === undefined) {
+            err = `${what} returned an object containing neither a valid \`error\` and \`result\`. At least one of them should not be \`undefined\``
+          } else {
+            for (const key of Object.keys(result)) {
+              if (key !== 'error' && key !== 'data' && key !== 'meta') {
+                err = `The object returned by ${what} has the unknown property ${key}.`
+                break
+              }
+            }
+          }
+          if (err) {
+            console.error(
+              `Error encountered handling the endpoint ${arg.endpointName}.
+                  ${err}
+                  It needs to return an object with either the shape \`{ data: <value> }\` or \`{ error: <value> }\` that may contain an optional \`meta\` property.
+                  Object returned was:`,
+              result,
+            )
+          }
+        }
+
+        if (result.error) throw new HandledError(result.error, result.meta)
+
+        let { data } = result
+
+        if (
+          rawResponseSchema &&
+          !shouldSkip(skipSchemaValidation, 'rawResponse')
+        ) {
+          data = await parseWithSchema(
+            rawResponseSchema,
+            result.data,
+            'rawResponseSchema',
+            result.meta,
+          )
+        }
+
+        let transformedResponse = await transformResponse(
+          data,
+          result.meta,
+          finalQueryArg,
+        )
+
+        if (responseSchema && !shouldSkip(skipSchemaValidation, 'response')) {
+          transformedResponse = await parseWithSchema(
+            responseSchema,
+            transformedResponse,
+            'responseSchema',
+            result.meta,
+          )
+        }
+
+        return {
+          ...result,
+          data: transformedResponse,
+        }
+      }
+
+      if (isQuery && 'infiniteQueryOptions' in endpointDefinition) {
+        // This is an infinite query endpoint
+        const { infiniteQueryOptions } = endpointDefinition
+
+        // Runtime checks should guarantee this is a positive number if provided
+        const { maxPages = Infinity } = infiniteQueryOptions
+
+        // Priority: per-call override > endpoint config > default (true)
+        const refetchCachedPages =
+          (arg as InfiniteQueryThunkArg<any>).refetchCachedPages ??
+          infiniteQueryOptions.refetchCachedPages ??
+          true
+
+        let result: QueryReturnValue
+
+        // Start by looking up the existing InfiniteData value from state,
+        // falling back to an empty value if it doesn't exist yet
+        const blankData = { pages: [], pageParams: [] }
+        const cachedData = selectors.selectQueryEntry(
+          getState(),
+          arg.queryCacheKey,
+        )?.data as InfiniteData<unknown, unknown> | undefined
+
+        // When the arg changes or the user forces a refetch,
+        // we don't include the `direction` flag. This lets us distinguish
+        // between actually refetching with a forced query, vs just fetching
+        // the next page.
+        const isForcedQueryNeedingRefetch = // arg.forceRefetch
+          isForcedQuery(arg, getState()) &&
+          !(arg as InfiniteQueryThunkArg<any>).direction
+        const existingData = (
+          isForcedQueryNeedingRefetch || !cachedData ? blankData : cachedData
+        ) as InfiniteData<unknown, unknown>
+
+        // If the thunk specified a direction and we do have at least one page,
+        // fetch the next or previous page
+        if ('direction' in arg && arg.direction && existingData.pages.length) {
+          const previous = arg.direction === 'backward'
+          const pageParamFn = previous ? getPreviousPageParam : getNextPageParam
+          const param = pageParamFn(
+            infiniteQueryOptions,
+            existingData,
+            arg.originalArgs,
+          )
+
+          result = await fetchPage(existingData, param, maxPages, previous)
+        } else {
+          // Otherwise, fetch the first page and then any remaining pages
+
+          const { initialPageParam = infiniteQueryOptions.initialPageParam } =
+            arg as InfiniteQueryThunkArg<any>
+
+          // If we're doing a refetch, we should start from
+          // the first page we have cached.
+          // Otherwise, we should start from the initialPageParam
+          const cachedPageParams = cachedData?.pageParams ?? []
+          const firstPageParam = cachedPageParams[0] ?? initialPageParam
+          const totalPages = cachedPageParams.length
+
+          // Fetch first page
+          result = await fetchPage(existingData, firstPageParam, maxPages)
+
+          if (forceQueryFn) {
+            // HACK `upsertQueryData` expects the user to pass in the `{pages, pageParams}` structure,
+            // but `fetchPage` treats that as `pages[0]`. We have to manually un-nest it.
+            result = {
+              data: (result.data as InfiniteData<unknown, unknown>).pages[0],
+            } as QueryReturnValue
+          }
+
+          if (refetchCachedPages) {
+            // Fetch remaining pages
+            for (let i = 1; i < totalPages; i++) {
+              const param = getNextPageParam(
+                infiniteQueryOptions,
+                result.data as InfiniteData<unknown, unknown>,
+                arg.originalArgs,
+              )
+              result = await fetchPage(
+                result.data as InfiniteData<unknown, unknown>,
+                param,
+                maxPages,
+              )
+            }
+          }
+        }
+
+        finalQueryReturnValue = result
+      } else {
+        // Non-infinite endpoint. Just run the one request.
+        finalQueryReturnValue = await executeRequest(arg.originalArgs)
+      }
+
+      if (
+        metaSchema &&
+        !shouldSkip(skipSchemaValidation, 'meta') &&
+        finalQueryReturnValue.meta
+      ) {
+        finalQueryReturnValue.meta = await parseWithSchema(
+          metaSchema,
+          finalQueryReturnValue.meta,
+          'metaSchema',
+          finalQueryReturnValue.meta,
+        )
+      }
+
+      // console.log('Final result: ', transformedData)
+      return fulfillWithValue(
+        finalQueryReturnValue.data,
+        addShouldAutoBatch({
+          fulfilledTimeStamp: Date.now(),
+          baseQueryMeta: finalQueryReturnValue.meta,
+        }),
+      )
+    } catch (error) {
+      let caughtError = error
+      if (caughtError instanceof HandledError) {
+        let transformErrorResponse = getTransformCallbackForEndpoint(
+          endpointDefinition,
+          'transformErrorResponse',
+        )
+        const { rawErrorResponseSchema, errorResponseSchema } =
+          endpointDefinition
+
+        let { value, meta } = caughtError
+
+        try {
+          if (
+            rawErrorResponseSchema &&
+            !shouldSkip(skipSchemaValidation, 'rawErrorResponse')
+          ) {
+            value = await parseWithSchema(
+              rawErrorResponseSchema,
+              value,
+              'rawErrorResponseSchema',
+              meta,
+            )
+          }
+
+          if (metaSchema && !shouldSkip(skipSchemaValidation, 'meta')) {
+            meta = await parseWithSchema(metaSchema, meta, 'metaSchema', meta)
+          }
+          let transformedErrorResponse = await transformErrorResponse(
+            value,
+            meta,
+            arg.originalArgs,
+          )
+          if (
+            errorResponseSchema &&
+            !shouldSkip(skipSchemaValidation, 'errorResponse')
+          ) {
+            transformedErrorResponse = await parseWithSchema(
+              errorResponseSchema,
+              transformedErrorResponse,
+              'errorResponseSchema',
+              meta,
+            )
+          }
+
+          return rejectWithValue(
+            transformedErrorResponse,
+            addShouldAutoBatch({ baseQueryMeta: meta }),
+          )
+        } catch (e) {
+          caughtError = e
+        }
+      }
+      try {
+        if (caughtError instanceof NamedSchemaError) {
+          const info: SchemaFailureInfo = {
+            endpoint: arg.endpointName,
+            arg: arg.originalArgs,
+            type: arg.type,
+            queryCacheKey: isQuery ? arg.queryCacheKey : undefined,
+          }
+          endpointDefinition.onSchemaFailure?.(caughtError, info)
+          onSchemaFailure?.(caughtError, info)
+          const { catchSchemaFailure = globalCatchSchemaFailure } =
+            endpointDefinition
+          if (catchSchemaFailure) {
+            return rejectWithValue(
+              catchSchemaFailure(caughtError, info),
+              addShouldAutoBatch({ baseQueryMeta: caughtError._bqMeta }),
+            )
+          }
+        }
+      } catch (e) {
+        caughtError = e
+      }
+      if (
+        typeof process !== 'undefined' &&
+        process.env.NODE_ENV !== 'production'
+      ) {
+        console.error(
+          `An unhandled error occurred processing a request for the endpoint "${arg.endpointName}".
+In the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+          caughtError,
+        )
+      } else {
+        console.error(caughtError)
+      }
+      throw caughtError
+    }
+  }
+
+  function isForcedQuery(
+    arg: QueryThunkArg,
+    state: RootState<any, string, ReducerPath>,
+  ) {
+    const requestState = selectors.selectQueryEntry(state, arg.queryCacheKey)
+    const baseFetchOnMountOrArgChange =
+      selectors.selectConfig(state).refetchOnMountOrArgChange
+
+    const fulfilledVal = requestState?.fulfilledTimeStamp
+    const refetchVal =
+      arg.forceRefetch ?? (arg.subscribe && baseFetchOnMountOrArgChange)
+
+    if (refetchVal) {
+      // Return if it's true or compare the dates because it must be a number
+      return (
+        refetchVal === true ||
+        (Number(new Date()) - Number(fulfilledVal)) / 1000 >= refetchVal
+      )
+    }
+    return false
+  }
+
+  const createQueryThunk = <
+    ThunkArgType extends QueryThunkArg | InfiniteQueryThunkArg<any>,
+  >() => {
+    const generatedQueryThunk = createAsyncThunk<
+      ThunkResult,
+      ThunkArgType,
+      ThunkApiMetaConfig & { state: RootState<any, string, ReducerPath> }
+    >(`${reducerPath}/executeQuery`, executeEndpoint, {
+      getPendingMeta({ arg }) {
+        const endpointDefinition = endpointDefinitions[arg.endpointName]
+        return addShouldAutoBatch({
+          startedTimeStamp: Date.now(),
+          ...(isInfiniteQueryDefinition(endpointDefinition)
+            ? { direction: (arg as InfiniteQueryThunkArg<any>).direction }
+            : {}),
+        })
+      },
+      condition(queryThunkArg, { getState }) {
+        const state = getState()
+
+        const requestState = selectors.selectQueryEntry(
+          state,
+          queryThunkArg.queryCacheKey,
+        )
+        const fulfilledVal = requestState?.fulfilledTimeStamp
+        const currentArg = queryThunkArg.originalArgs
+        const previousArg = requestState?.originalArgs
+        const endpointDefinition =
+          endpointDefinitions[queryThunkArg.endpointName]
+        const direction = (queryThunkArg as InfiniteQueryThunkArg<any>)
+          .direction
+
+        // Order of these checks matters.
+        // In order for `upsertQueryData` to successfully run while an existing request is in flight,
+        /// we have to check for that first, otherwise `queryThunk` will bail out and not run at all.
+        if (isUpsertQuery(queryThunkArg)) {
+          return true
+        }
+
+        // Don't retry a request that's currently in-flight
+        if (requestState?.status === 'pending') {
+          return false
+        }
+
+        // if this is forced, continue
+        if (isForcedQuery(queryThunkArg, state)) {
+          return true
+        }
+
+        if (
+          isQueryDefinition(endpointDefinition) &&
+          endpointDefinition?.forceRefetch?.({
+            currentArg,
+            previousArg,
+            endpointState: requestState,
+            state,
+          })
+        ) {
+          return true
+        }
+
+        // Pull from the cache unless we explicitly force refetch or qualify based on time
+        if (fulfilledVal && !direction) {
+          // Value is cached and we didn't specify to refresh, skip it.
+          return false
+        }
+
+        return true
+      },
+      dispatchConditionRejection: true,
+    })
+    return generatedQueryThunk
+  }
+
+  const queryThunk = createQueryThunk<QueryThunkArg>()
+  const infiniteQueryThunk = createQueryThunk<InfiniteQueryThunkArg<any>>()
+
+  const mutationThunk = createAsyncThunk<
+    ThunkResult,
+    MutationThunkArg,
+    ThunkApiMetaConfig & { state: RootState<any, string, ReducerPath> }
+  >(`${reducerPath}/executeMutation`, executeEndpoint, {
+    getPendingMeta() {
+      return addShouldAutoBatch({ startedTimeStamp: Date.now() })
+    },
+  })
+
+  const hasTheForce = (options: any): options is { force: boolean } =>
+    'force' in options
+  const hasMaxAge = (
+    options: any,
+  ): options is { ifOlderThan: false | number } => 'ifOlderThan' in options
+
+  const prefetch =
+    <EndpointName extends QueryKeys<Definitions>>(
+      endpointName: EndpointName,
+      arg: any,
+      options: PrefetchOptions = {},
+    ): ThunkAction<void, any, any, UnknownAction> =>
+    (dispatch: ThunkDispatch<any, any, any>, getState: () => any) => {
+      const force = hasTheForce(options) && options.force
+      const maxAge = hasMaxAge(options) && options.ifOlderThan
+
+      const queryAction = (force: boolean = true) => {
+        const options: StartQueryActionCreatorOptions = {
+          forceRefetch: force,
+          subscribe: false,
+        }
+        return (
+          api.endpoints[endpointName] as ApiEndpointQuery<any, any>
+        ).initiate(arg, options)
+      }
+      const latestStateValue = (
+        api.endpoints[endpointName] as ApiEndpointQuery<any, any>
+      ).select(arg)(getState())
+
+      if (force) {
+        dispatch(queryAction())
+      } else if (maxAge) {
+        const lastFulfilledTs = latestStateValue?.fulfilledTimeStamp
+        if (!lastFulfilledTs) {
+          dispatch(queryAction())
+          return
+        }
+        const shouldRetrigger =
+          (Number(new Date()) - Number(new Date(lastFulfilledTs))) / 1000 >=
+          maxAge
+        if (shouldRetrigger) {
+          dispatch(queryAction())
+        }
+      } else {
+        // If prefetching with no options, just let it try
+        dispatch(queryAction(false))
+      }
+    }
+
+  function matchesEndpoint(endpointName: string) {
+    return (action: any): action is UnknownAction =>
+      action?.meta?.arg?.endpointName === endpointName
+  }
+
+  function buildMatchThunkActions<
+    Thunk extends
+      | AsyncThunk<any, QueryThunkArg, ThunkApiMetaConfig>
+      | AsyncThunk<any, MutationThunkArg, ThunkApiMetaConfig>,
+  >(thunk: Thunk, endpointName: string) {
+    return {
+      matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)),
+      matchFulfilled: isAllOf(
+        isFulfilled(thunk),
+        matchesEndpoint(endpointName),
+      ),
+      matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpointName)),
+    } as Matchers<Thunk, any>
+  }
+
+  return {
+    queryThunk,
+    mutationThunk,
+    infiniteQueryThunk,
+    prefetch,
+    updateQueryData,
+    upsertQueryData,
+    patchQueryData,
+    buildMatchThunkActions,
+  }
+}
+
+export function getNextPageParam(
+  options: InfiniteQueryConfigOptions<unknown, unknown, unknown>,
+  { pages, pageParams }: InfiniteData<unknown, unknown>,
+  queryArg: unknown,
+): unknown | undefined {
+  const lastIndex = pages.length - 1
+  return options.getNextPageParam(
+    pages[lastIndex],
+    pages,
+    pageParams[lastIndex],
+    pageParams,
+    queryArg,
+  )
+}
+
+export function getPreviousPageParam(
+  options: InfiniteQueryConfigOptions<unknown, unknown, unknown>,
+  { pages, pageParams }: InfiniteData<unknown, unknown>,
+  queryArg: unknown,
+): unknown | undefined {
+  return options.getPreviousPageParam?.(
+    pages[0],
+    pages,
+    pageParams[0],
+    pageParams,
+    queryArg,
+  )
+}
+
+export function calculateProvidedByThunk(
+  action: UnwrapPromise<
+    | ReturnType<ReturnType<QueryThunk>>
+    | ReturnType<ReturnType<MutationThunk>>
+    | ReturnType<ReturnType<InfiniteQueryThunk<any>>>
+  >,
+  type: 'providesTags' | 'invalidatesTags',
+  endpointDefinitions: EndpointDefinitions,
+  assertTagType: AssertTagTypes,
+) {
+  return calculateProvidedBy(
+    endpointDefinitions[action.meta.arg.endpointName][
+      type
+    ] as ResultDescription<any, any, any, any, any>,
+    isFulfilled(action) ? action.payload : undefined,
+    isRejectedWithValue(action) ? action.payload : undefined,
+    action.meta.arg.originalArgs,
+    'baseQueryMeta' in action.meta ? action.meta.baseQueryMeta : undefined,
+    assertTagType,
+  )
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/index.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,58 @@
+import { buildCreateApi } from '../createApi'
+import { coreModule } from './module'
+
+export const createApi = /* @__PURE__ */ buildCreateApi(coreModule())
+
+export { QueryStatus } from './apiState'
+export type {
+  CombinedState,
+  InfiniteData,
+  InfiniteQueryConfigOptions,
+  InfiniteQuerySubState,
+  MutationKeys,
+  QueryCacheKey,
+  QueryKeys,
+  QuerySubState,
+  RootState,
+  SubscriptionOptions,
+} from './apiState'
+export type {
+  InfiniteQueryActionCreatorResult,
+  MutationActionCreatorResult,
+  QueryActionCreatorResult,
+  StartQueryActionCreatorOptions,
+} from './buildInitiate'
+export type {
+  MutationCacheLifecycleApi,
+  MutationLifecycleApi,
+  QueryCacheLifecycleApi,
+  QueryLifecycleApi,
+  SubscriptionSelectors,
+  TypedMutationOnQueryStarted,
+  TypedQueryOnQueryStarted,
+} from './buildMiddleware/index'
+export { skipToken } from './buildSelectors'
+export type {
+  InfiniteQueryResultSelectorResult,
+  MutationResultSelectorResult,
+  QueryResultSelectorResult,
+  SkipToken,
+} from './buildSelectors'
+export type { SliceActions } from './buildSlice'
+export type {
+  PatchQueryDataThunk,
+  UpdateQueryDataThunk,
+  UpsertQueryDataThunk,
+} from './buildThunks'
+export { coreModuleName } from './module'
+export type {
+  ApiEndpointInfiniteQuery,
+  ApiEndpointMutation,
+  ApiEndpointQuery,
+  CoreModule,
+  InternalActions,
+  PrefetchOptions,
+  ThunkWithReturnValue,
+} from './module'
+export { setupListeners } from './setupListeners'
+export { buildCreateApi, coreModule }
Index: node_modules/@reduxjs/toolkit/src/query/core/module.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/module.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/module.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,727 @@
+/**
+ * Note: this file should import all other files for type discovery and declaration merging
+ */
+import type {
+  ActionCreatorWithPayload,
+  Dispatch,
+  Middleware,
+  Reducer,
+  ThunkAction,
+  ThunkDispatch,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import { enablePatches } from '../utils/immerImports'
+import type { Api, Module } from '../apiTypes'
+import type { BaseQueryFn } from '../baseQueryTypes'
+import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'
+import type {
+  AssertTagTypes,
+  EndpointDefinitions,
+  InfiniteQueryDefinition,
+  MutationDefinition,
+  QueryArgFrom,
+  QueryArgFromAnyQuery,
+  QueryDefinition,
+  TagDescription,
+} from '../endpointDefinitions'
+import {
+  isInfiniteQueryDefinition,
+  isMutationDefinition,
+  isQueryDefinition,
+} from '../endpointDefinitions'
+import { assertCast, safeAssign } from '../tsHelpers'
+import type {
+  CombinedState,
+  MutationKeys,
+  QueryKeys,
+  RootState,
+} from './apiState'
+import type {
+  BuildInitiateApiEndpointMutation,
+  BuildInitiateApiEndpointQuery,
+  MutationActionCreatorResult,
+  QueryActionCreatorResult,
+  InfiniteQueryActionCreatorResult,
+  BuildInitiateApiEndpointInfiniteQuery,
+} from './buildInitiate'
+import { buildInitiate } from './buildInitiate'
+import type {
+  ReferenceCacheCollection,
+  ReferenceCacheLifecycle,
+  ReferenceQueryLifecycle,
+} from './buildMiddleware'
+import { buildMiddleware } from './buildMiddleware'
+import type {
+  BuildSelectorsApiEndpointInfiniteQuery,
+  BuildSelectorsApiEndpointMutation,
+  BuildSelectorsApiEndpointQuery,
+} from './buildSelectors'
+import { buildSelectors } from './buildSelectors'
+import type { SliceActions, UpsertEntries } from './buildSlice'
+import { buildSlice } from './buildSlice'
+import type {
+  AllQueryKeys,
+  BuildThunksApiEndpointInfiniteQuery,
+  BuildThunksApiEndpointMutation,
+  BuildThunksApiEndpointQuery,
+  PatchQueryDataThunk,
+  QueryArgFromAnyQueryDefinition,
+  UpdateQueryDataThunk,
+  UpsertQueryDataThunk,
+} from './buildThunks'
+import { buildThunks } from './buildThunks'
+import { createSelector as _createSelector } from './rtkImports'
+import { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners'
+import type { InternalMiddlewareState } from './buildMiddleware/types'
+import { getOrInsertComputed } from '../utils'
+import type { CreateSelectorFunction } from 'reselect'
+
+/**
+ * `ifOlderThan` - (default: `false` | `number`) - _number is value in seconds_
+ * - If specified, it will only run the query if the difference between `new Date()` and the last `fulfilledTimeStamp` is greater than the given value
+ *
+ * @overloadSummary
+ * `force`
+ * - If `force: true`, it will ignore the `ifOlderThan` value if it is set and the query will be run even if it exists in the cache.
+ */
+export type PrefetchOptions =
+  | {
+      ifOlderThan?: false | number
+    }
+  | { force?: boolean }
+
+export const coreModuleName = /* @__PURE__ */ Symbol()
+export type CoreModule =
+  | typeof coreModuleName
+  | ReferenceCacheLifecycle
+  | ReferenceQueryLifecycle
+  | ReferenceCacheCollection
+
+export type ThunkWithReturnValue<T> = ThunkAction<T, any, any, UnknownAction>
+
+export interface ApiModules<
+  // eslint-disable-next-line @typescript-eslint/no-unused-vars
+  BaseQuery extends BaseQueryFn,
+  Definitions extends EndpointDefinitions,
+  ReducerPath extends string,
+  TagTypes extends string,
+> {
+  [coreModuleName]: {
+    /**
+     * This api's reducer should be mounted at `store[api.reducerPath]`.
+     *
+     * @example
+     * ```ts
+     * configureStore({
+     *   reducer: {
+     *     [api.reducerPath]: api.reducer,
+     *   },
+     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
+     * })
+     * ```
+     */
+    reducerPath: ReducerPath
+    /**
+     * Internal actions not part of the public API. Note: These are subject to change at any given time.
+     */
+    internalActions: InternalActions
+    /**
+     *  A standard redux reducer that enables core functionality. Make sure it's included in your store.
+     *
+     * @example
+     * ```ts
+     * configureStore({
+     *   reducer: {
+     *     [api.reducerPath]: api.reducer,
+     *   },
+     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
+     * })
+     * ```
+     */
+    reducer: Reducer<
+      CombinedState<Definitions, TagTypes, ReducerPath>,
+      UnknownAction
+    >
+    /**
+     * This is a standard redux middleware and is responsible for things like polling, garbage collection and a handful of other things. Make sure it's included in your store.
+     *
+     * @example
+     * ```ts
+     * configureStore({
+     *   reducer: {
+     *     [api.reducerPath]: api.reducer,
+     *   },
+     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
+     * })
+     * ```
+     */
+    middleware: Middleware<
+      {},
+      RootState<Definitions, string, ReducerPath>,
+      ThunkDispatch<any, any, UnknownAction>
+    >
+    /**
+     * A collection of utility thunks for various situations.
+     */
+    util: {
+      /**
+       * A thunk that (if dispatched) will return a specific running query, identified
+       * by `endpointName` and `arg`.
+       * If that query is not running, dispatching the thunk will result in `undefined`.
+       *
+       * Can be used to await a specific query triggered in any way,
+       * including via hook calls or manually dispatching `initiate` actions.
+       *
+       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
+       */
+      getRunningQueryThunk<EndpointName extends AllQueryKeys<Definitions>>(
+        endpointName: EndpointName,
+        arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>,
+      ): ThunkWithReturnValue<
+        | QueryActionCreatorResult<
+            Definitions[EndpointName] & { type: 'query' }
+          >
+        | InfiniteQueryActionCreatorResult<
+            Definitions[EndpointName] & { type: 'infinitequery' }
+          >
+        | undefined
+      >
+
+      /**
+       * A thunk that (if dispatched) will return a specific running mutation, identified
+       * by `endpointName` and `fixedCacheKey` or `requestId`.
+       * If that mutation is not running, dispatching the thunk will result in `undefined`.
+       *
+       * Can be used to await a specific mutation triggered in any way,
+       * including via hook trigger functions or manually dispatching `initiate` actions.
+       *
+       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
+       */
+      getRunningMutationThunk<EndpointName extends MutationKeys<Definitions>>(
+        endpointName: EndpointName,
+        fixedCacheKeyOrRequestId: string,
+      ): ThunkWithReturnValue<
+        | MutationActionCreatorResult<
+            Definitions[EndpointName] & { type: 'mutation' }
+          >
+        | undefined
+      >
+
+      /**
+       * A thunk that (if dispatched) will return all running queries.
+       *
+       * Useful for SSR scenarios to await all running queries triggered in any way,
+       * including via hook calls or manually dispatching `initiate` actions.
+       *
+       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
+       */
+      getRunningQueriesThunk(): ThunkWithReturnValue<
+        Array<
+          QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>
+        >
+      >
+
+      /**
+       * A thunk that (if dispatched) will return all running mutations.
+       *
+       * Useful for SSR scenarios to await all running mutations triggered in any way,
+       * including via hook calls or manually dispatching `initiate` actions.
+       *
+       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
+       */
+      getRunningMutationsThunk(): ThunkWithReturnValue<
+        Array<MutationActionCreatorResult<any>>
+      >
+
+      /**
+       * A Redux thunk that can be used to manually trigger pre-fetching of data.
+       *
+       * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a set of options used to determine if the data actually should be re-fetched based on cache staleness.
+       *
+       * React Hooks users will most likely never need to use this directly, as the `usePrefetch` hook will dispatch this thunk internally as needed when you call the prefetching function supplied by the hook.
+       *
+       * @example
+       *
+       * ```ts no-transpile
+       * dispatch(api.util.prefetch('getPosts', undefined, { force: true }))
+       * ```
+       */
+      prefetch<EndpointName extends QueryKeys<Definitions>>(
+        endpointName: EndpointName,
+        arg: QueryArgFrom<Definitions[EndpointName]>,
+        options?: PrefetchOptions,
+      ): ThunkAction<void, any, any, UnknownAction>
+      /**
+       * A Redux thunk action creator that, when dispatched, creates and applies a set of JSON diff/patch objects to the current state. This immediately updates the Redux state with those changes.
+       *
+       * The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and an `updateRecipe` callback function. The callback receives an Immer-wrapped `draft` of the current state, and may modify the draft to match the expected results after the mutation completes successfully.
+       *
+       * The thunk executes _synchronously_, and returns an object containing `{patches: Patch[], inversePatches: Patch[], undo: () => void}`. The `patches` and `inversePatches` are generated using Immer's [`produceWithPatches` method](https://immerjs.github.io/immer/patches).
+       *
+       * This is typically used as the first step in implementing optimistic updates. The generated `inversePatches` can be used to revert the updates by calling `dispatch(patchQueryData(endpointName, arg, inversePatches))`. Alternatively, the `undo` method can be called directly to achieve the same effect.
+       *
+       * Note that the first two arguments (`endpointName` and `arg`) are used to determine which existing cache entry to update. If no existing cache entry is found, the `updateRecipe` callback will not run.
+       *
+       * @example
+       *
+       * ```ts
+       * const patchCollection = dispatch(
+       *   api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
+       *     draftPosts.push({ id: 1, name: 'Teddy' })
+       *   })
+       * )
+       * ```
+       */
+      updateQueryData: UpdateQueryDataThunk<
+        Definitions,
+        RootState<Definitions, string, ReducerPath>
+      >
+
+      /**
+       * A Redux thunk action creator that, when dispatched, acts as an artificial API request to upsert a value into the cache.
+       *
+       * The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and the data to upsert.
+       *
+       * If no cache entry for that cache key exists, a cache entry will be created and the data added. If a cache entry already exists, this will _overwrite_ the existing cache entry data.
+       *
+       * The thunk executes _asynchronously_, and returns a promise that resolves when the store has been updated.
+       *
+       * If dispatched while an actual request is in progress, both the upsert and request will be handled as soon as they resolve, resulting in a "last result wins" update behavior.
+       *
+       * @example
+       *
+       * ```ts
+       * await dispatch(
+       *   api.util.upsertQueryData('getPost', {id: 1}, {id: 1, text: "Hello!"})
+       * )
+       * ```
+       */
+      upsertQueryData: UpsertQueryDataThunk<
+        Definitions,
+        RootState<Definitions, string, ReducerPath>
+      >
+      /**
+       * A Redux thunk that applies a JSON diff/patch array to the cached data for a given query result. This immediately updates the Redux state with those changes.
+       *
+       * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a JSON diff/patch array as produced by Immer's `produceWithPatches`.
+       *
+       * This is typically used as the second step in implementing optimistic updates. If a request fails, the optimistically-applied changes can be reverted by dispatching `patchQueryData` with the `inversePatches` that were generated by `updateQueryData` earlier.
+       *
+       * In cases where it is desired to simply revert the previous changes, it may be preferable to call the `undo` method returned from dispatching `updateQueryData` instead.
+       *
+       * @example
+       * ```ts
+       * const patchCollection = dispatch(
+       *   api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
+       *     draftPosts.push({ id: 1, name: 'Teddy' })
+       *   })
+       * )
+       *
+       * // later
+       * dispatch(
+       *   api.util.patchQueryData('getPosts', undefined, patchCollection.inversePatches)
+       * )
+       *
+       * // or
+       * patchCollection.undo()
+       * ```
+       */
+      patchQueryData: PatchQueryDataThunk<
+        Definitions,
+        RootState<Definitions, string, ReducerPath>
+      >
+
+      /**
+       * A Redux action creator that can be dispatched to manually reset the api state completely. This will immediately remove all existing cache entries, and all queries will be considered 'uninitialized'.
+       *
+       * @example
+       *
+       * ```ts
+       * dispatch(api.util.resetApiState())
+       * ```
+       */
+      resetApiState: SliceActions['resetApiState']
+
+      upsertQueryEntries: UpsertEntries<Definitions>
+
+      /**
+       * A Redux action creator that can be used to manually invalidate cache tags for [automated re-fetching](../../usage/automated-refetching.mdx).
+       *
+       * The action creator accepts one argument: the cache tags to be invalidated. It returns an action with those tags as a payload, and the corresponding `invalidateTags` action type for the api.
+       *
+       * Dispatching the result of this action creator will [invalidate](../../usage/automated-refetching.mdx#invalidating-cache-data) the given tags, causing queries to automatically re-fetch if they are subscribed to cache data that [provides](../../usage/automated-refetching.mdx#providing-cache-data) the corresponding tags.
+       *
+       * The array of tags provided to the action creator should be in one of the following formats, where `TagType` is equal to a string provided to the [`tagTypes`](../createApi.mdx#tagtypes) property of the api:
+       *
+       * - `[TagType]`
+       * - `[{ type: TagType }]`
+       * - `[{ type: TagType, id: number | string }]`
+       *
+       * @example
+       *
+       * ```ts
+       * dispatch(api.util.invalidateTags(['Post']))
+       * dispatch(api.util.invalidateTags([{ type: 'Post', id: 1 }]))
+       * dispatch(
+       *   api.util.invalidateTags([
+       *     { type: 'Post', id: 1 },
+       *     { type: 'Post', id: 'LIST' },
+       *   ])
+       * )
+       * ```
+       */
+      invalidateTags: ActionCreatorWithPayload<
+        Array<TagDescription<TagTypes> | null | undefined>,
+        string
+      >
+
+      /**
+       * A function to select all `{ endpointName, originalArgs, queryCacheKey }` combinations that would be invalidated by a specific set of tags.
+       *
+       * Can be used for mutations that want to do optimistic updates instead of invalidating a set of tags, but don't know exactly what they need to update.
+       */
+      selectInvalidatedBy: (
+        state: RootState<Definitions, string, ReducerPath>,
+        tags: ReadonlyArray<TagDescription<TagTypes> | null | undefined>,
+      ) => Array<{
+        endpointName: string
+        originalArgs: any
+        queryCacheKey: string
+      }>
+
+      /**
+       * A function to select all arguments currently cached for a given endpoint.
+       *
+       * Can be used for mutations that want to do optimistic updates instead of invalidating a set of tags, but don't know exactly what they need to update.
+       */
+      selectCachedArgsForQuery: <QueryName extends AllQueryKeys<Definitions>>(
+        state: RootState<Definitions, string, ReducerPath>,
+        queryName: QueryName,
+      ) => Array<QueryArgFromAnyQuery<Definitions[QueryName]>>
+    }
+    /**
+     * Endpoints based on the input endpoints provided to `createApi`, containing `select` and `action matchers`.
+     */
+    endpoints: {
+      [K in keyof Definitions]: Definitions[K] extends QueryDefinition<
+        any,
+        any,
+        any,
+        any,
+        any
+      >
+        ? ApiEndpointQuery<Definitions[K], Definitions>
+        : Definitions[K] extends MutationDefinition<any, any, any, any, any>
+          ? ApiEndpointMutation<Definitions[K], Definitions>
+          : Definitions[K] extends InfiniteQueryDefinition<
+                any,
+                any,
+                any,
+                any,
+                any
+              >
+            ? ApiEndpointInfiniteQuery<Definitions[K], Definitions>
+            : never
+    }
+  }
+}
+
+export interface ApiEndpointQuery<
+  // eslint-disable-next-line @typescript-eslint/no-unused-vars
+  Definition extends QueryDefinition<any, any, any, any, any>,
+  // eslint-disable-next-line @typescript-eslint/no-unused-vars
+  Definitions extends EndpointDefinitions,
+> extends BuildThunksApiEndpointQuery<Definition>,
+    BuildInitiateApiEndpointQuery<Definition>,
+    BuildSelectorsApiEndpointQuery<Definition, Definitions> {
+  name: string
+  /**
+   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
+   */
+  Types: NonNullable<Definition['Types']>
+}
+
+export interface ApiEndpointInfiniteQuery<
+  // eslint-disable-next-line @typescript-eslint/no-unused-vars
+  Definition extends InfiniteQueryDefinition<any, any, any, any, any>,
+  // eslint-disable-next-line @typescript-eslint/no-unused-vars
+  Definitions extends EndpointDefinitions,
+> extends BuildThunksApiEndpointInfiniteQuery<Definition>,
+    BuildInitiateApiEndpointInfiniteQuery<Definition>,
+    BuildSelectorsApiEndpointInfiniteQuery<Definition, Definitions> {
+  name: string
+  /**
+   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
+   */
+  Types: NonNullable<Definition['Types']>
+}
+
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+export interface ApiEndpointMutation<
+  // eslint-disable-next-line @typescript-eslint/no-unused-vars
+  Definition extends MutationDefinition<any, any, any, any, any>,
+  // eslint-disable-next-line @typescript-eslint/no-unused-vars
+  Definitions extends EndpointDefinitions,
+> extends BuildThunksApiEndpointMutation<Definition>,
+    BuildInitiateApiEndpointMutation<Definition>,
+    BuildSelectorsApiEndpointMutation<Definition, Definitions> {
+  name: string
+  /**
+   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
+   */
+  Types: NonNullable<Definition['Types']>
+}
+
+export type ListenerActions = {
+  /**
+   * Will cause the RTK Query middleware to trigger any refetchOnReconnect-related behavior
+   * @link https://redux-toolkit.js.org/rtk-query/api/setupListeners
+   */
+  onOnline: typeof onOnline
+  onOffline: typeof onOffline
+  /**
+   * Will cause the RTK Query middleware to trigger any refetchOnFocus-related behavior
+   * @link https://redux-toolkit.js.org/rtk-query/api/setupListeners
+   */
+  onFocus: typeof onFocus
+  onFocusLost: typeof onFocusLost
+}
+
+export type InternalActions = SliceActions & ListenerActions
+
+export interface CoreModuleOptions {
+  /**
+   * A selector creator (usually from `reselect`, or matching the same signature)
+   */
+  createSelector?: CreateSelectorFunction<any, any, any>
+}
+
+/**
+ * Creates a module containing the basic redux logic for use with `buildCreateApi`.
+ *
+ * @example
+ * ```ts
+ * const createBaseApi = buildCreateApi(coreModule());
+ * ```
+ */
+export const coreModule = ({
+  createSelector = _createSelector,
+}: CoreModuleOptions = {}): Module<CoreModule> => ({
+  name: coreModuleName,
+  init(
+    api,
+    {
+      baseQuery,
+      tagTypes,
+      reducerPath,
+      serializeQueryArgs,
+      keepUnusedDataFor,
+      refetchOnMountOrArgChange,
+      refetchOnFocus,
+      refetchOnReconnect,
+      invalidationBehavior,
+      onSchemaFailure,
+      catchSchemaFailure,
+      skipSchemaValidation,
+    },
+    context,
+  ) {
+    enablePatches()
+
+    assertCast<InternalSerializeQueryArgs>(serializeQueryArgs)
+
+    const assertTagType: AssertTagTypes = (tag) => {
+      if (
+        typeof process !== 'undefined' &&
+        process.env.NODE_ENV === 'development'
+      ) {
+        if (!tagTypes.includes(tag.type as any)) {
+          console.error(
+            `Tag type '${tag.type}' was used, but not specified in \`tagTypes\`!`,
+          )
+        }
+      }
+      return tag
+    }
+
+    Object.assign(api, {
+      reducerPath,
+      endpoints: {},
+      internalActions: {
+        onOnline,
+        onOffline,
+        onFocus,
+        onFocusLost,
+      },
+      util: {},
+    })
+
+    const selectors = buildSelectors({
+      serializeQueryArgs: serializeQueryArgs as any,
+      reducerPath,
+      createSelector,
+    })
+
+    const {
+      selectInvalidatedBy,
+      selectCachedArgsForQuery,
+      buildQuerySelector,
+      buildInfiniteQuerySelector,
+      buildMutationSelector,
+    } = selectors
+
+    safeAssign(api.util, { selectInvalidatedBy, selectCachedArgsForQuery })
+
+    const {
+      queryThunk,
+      infiniteQueryThunk,
+      mutationThunk,
+      patchQueryData,
+      updateQueryData,
+      upsertQueryData,
+      prefetch,
+      buildMatchThunkActions,
+    } = buildThunks({
+      baseQuery,
+      reducerPath,
+      context,
+      api,
+      serializeQueryArgs,
+      assertTagType,
+      selectors,
+      onSchemaFailure,
+      catchSchemaFailure,
+      skipSchemaValidation,
+    })
+
+    const { reducer, actions: sliceActions } = buildSlice({
+      context,
+      queryThunk,
+      infiniteQueryThunk,
+      mutationThunk,
+      serializeQueryArgs,
+      reducerPath,
+      assertTagType,
+      config: {
+        refetchOnFocus,
+        refetchOnReconnect,
+        refetchOnMountOrArgChange,
+        keepUnusedDataFor,
+        reducerPath,
+        invalidationBehavior,
+      },
+    })
+
+    safeAssign(api.util, {
+      patchQueryData,
+      updateQueryData,
+      upsertQueryData,
+      prefetch,
+      resetApiState: sliceActions.resetApiState,
+      upsertQueryEntries: sliceActions.cacheEntriesUpserted as any,
+    })
+    safeAssign(api.internalActions, sliceActions)
+
+    const internalStateMap = new WeakMap<Dispatch, InternalMiddlewareState>()
+
+    const getInternalState = (dispatch: Dispatch) => {
+      const state = getOrInsertComputed(internalStateMap, dispatch, () => ({
+        currentSubscriptions: new Map(),
+        currentPolls: new Map(),
+        runningQueries: new Map(),
+        runningMutations: new Map(),
+      }))
+
+      return state
+    }
+
+    const {
+      buildInitiateQuery,
+      buildInitiateInfiniteQuery,
+      buildInitiateMutation,
+      getRunningMutationThunk,
+      getRunningMutationsThunk,
+      getRunningQueriesThunk,
+      getRunningQueryThunk,
+    } = buildInitiate({
+      queryThunk,
+      mutationThunk,
+      infiniteQueryThunk,
+      api,
+      serializeQueryArgs: serializeQueryArgs as any,
+      context,
+      getInternalState,
+    })
+
+    safeAssign(api.util, {
+      getRunningMutationThunk,
+      getRunningMutationsThunk,
+      getRunningQueryThunk,
+      getRunningQueriesThunk,
+    })
+
+    const { middleware, actions: middlewareActions } = buildMiddleware({
+      reducerPath,
+      context,
+      queryThunk,
+      mutationThunk,
+      infiniteQueryThunk,
+      api,
+      assertTagType,
+      selectors,
+      getRunningQueryThunk,
+      getInternalState,
+    })
+    safeAssign(api.util, middlewareActions)
+
+    safeAssign(api, { reducer: reducer as any, middleware })
+
+    return {
+      name: coreModuleName,
+      injectEndpoint(endpointName, definition) {
+        const anyApi = api as any as Api<
+          any,
+          Record<string, any>,
+          string,
+          string,
+          CoreModule
+        >
+        const endpoint = (anyApi.endpoints[endpointName] ??= {} as any)
+
+        if (isQueryDefinition(definition)) {
+          safeAssign(
+            endpoint,
+            {
+              name: endpointName,
+              select: buildQuerySelector(endpointName, definition),
+              initiate: buildInitiateQuery(endpointName, definition),
+            },
+            buildMatchThunkActions(queryThunk, endpointName),
+          )
+        }
+        if (isMutationDefinition(definition)) {
+          safeAssign(
+            endpoint,
+            {
+              name: endpointName,
+              select: buildMutationSelector(),
+              initiate: buildInitiateMutation(endpointName),
+            },
+            buildMatchThunkActions(mutationThunk, endpointName),
+          )
+        }
+        if (isInfiniteQueryDefinition(definition)) {
+          safeAssign(
+            endpoint,
+            {
+              name: endpointName,
+              select: buildInfiniteQuerySelector(endpointName, definition),
+              initiate: buildInitiateInfiniteQuery(endpointName, definition),
+            },
+            buildMatchThunkActions(queryThunk, endpointName),
+          )
+        }
+      },
+    }
+  },
+})
Index: node_modules/@reduxjs/toolkit/src/query/core/rtkImports.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/rtkImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/rtkImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,24 @@
+// This file exists to consolidate all of the imports from the `@reduxjs/toolkit` package.
+// ESBuild does not de-duplicate imports, so this file is used to ensure that each method
+// imported is only listed once, and there's only one mention of the `@reduxjs/toolkit` package.
+
+export {
+  createAction,
+  createSlice,
+  createSelector,
+  createAsyncThunk,
+  combineReducers,
+  createNextState,
+  isAnyOf,
+  isAllOf,
+  isAction,
+  isPending,
+  isRejected,
+  isFulfilled,
+  isRejectedWithValue,
+  isAsyncThunkAction,
+  prepareAutoBatched,
+  SHOULD_AUTOBATCH,
+  isPlainObject,
+  nanoid,
+} from '@reduxjs/toolkit'
Index: node_modules/@reduxjs/toolkit/src/query/core/setupListeners.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/setupListeners.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/setupListeners.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,118 @@
+import type {
+  ThunkDispatch,
+  ActionCreatorWithoutPayload, // Workaround for API-Extractor
+} from '@reduxjs/toolkit'
+import { createAction } from './rtkImports'
+
+export const INTERNAL_PREFIX = '__rtkq/'
+
+const ONLINE = 'online'
+const OFFLINE = 'offline'
+const FOCUS = 'focus'
+const FOCUSED = 'focused'
+const VISIBILITYCHANGE = 'visibilitychange'
+
+export const onFocus = /* @__PURE__ */ createAction(
+  `${INTERNAL_PREFIX}${FOCUSED}`,
+)
+export const onFocusLost = /* @__PURE__ */ createAction(
+  `${INTERNAL_PREFIX}un${FOCUSED}`,
+)
+export const onOnline = /* @__PURE__ */ createAction(
+  `${INTERNAL_PREFIX}${ONLINE}`,
+)
+export const onOffline = /* @__PURE__ */ createAction(
+  `${INTERNAL_PREFIX}${OFFLINE}`,
+)
+
+const actions = {
+  onFocus,
+  onFocusLost,
+  onOnline,
+  onOffline,
+}
+
+let initialized = false
+
+/**
+ * A utility used to enable `refetchOnMount` and `refetchOnReconnect` behaviors.
+ * It requires the dispatch method from your store.
+ * Calling `setupListeners(store.dispatch)` will configure listeners with the recommended defaults,
+ * but you have the option of providing a callback for more granular control.
+ *
+ * @example
+ * ```ts
+ * setupListeners(store.dispatch)
+ * ```
+ *
+ * @param dispatch - The dispatch method from your store
+ * @param customHandler - An optional callback for more granular control over listener behavior
+ * @returns Return value of the handler.
+ * The default handler returns an `unsubscribe` method that can be called to remove the listeners.
+ */
+export function setupListeners(
+  dispatch: ThunkDispatch<any, any, any>,
+  customHandler?: (
+    dispatch: ThunkDispatch<any, any, any>,
+    actions: {
+      onFocus: typeof onFocus
+      onFocusLost: typeof onFocusLost
+      onOnline: typeof onOnline
+      onOffline: typeof onOffline
+    },
+  ) => () => void,
+) {
+  function defaultHandler() {
+    const [handleFocus, handleFocusLost, handleOnline, handleOffline] = [
+      onFocus,
+      onFocusLost,
+      onOnline,
+      onOffline,
+    ].map((action) => () => dispatch(action()))
+
+    const handleVisibilityChange = () => {
+      if (window.document.visibilityState === 'visible') {
+        handleFocus()
+      } else {
+        handleFocusLost()
+      }
+    }
+
+    let unsubscribe = () => {
+      initialized = false
+    }
+
+    if (!initialized) {
+      if (typeof window !== 'undefined' && window.addEventListener) {
+        const handlers = {
+          [FOCUS]: handleFocus,
+          [VISIBILITYCHANGE]: handleVisibilityChange,
+          [ONLINE]: handleOnline,
+          [OFFLINE]: handleOffline,
+        }
+
+        function updateListeners(add: boolean) {
+          Object.entries(handlers).forEach(([event, handler]) => {
+            if (add) {
+              window.addEventListener(event, handler, false)
+            } else {
+              window.removeEventListener(event, handler)
+            }
+          })
+        }
+        // Handle focus events
+        updateListeners(true)
+        initialized = true
+
+        unsubscribe = () => {
+          updateListeners(false)
+          initialized = false
+        }
+      }
+    }
+
+    return unsubscribe
+  }
+
+  return customHandler ? customHandler(dispatch, actions) : defaultHandler()
+}
Index: node_modules/@reduxjs/toolkit/src/query/createApi.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/createApi.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/createApi.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,514 @@
+import {
+  getEndpointDefinition,
+  type Api,
+  type ApiContext,
+  type Module,
+  type ModuleName,
+} from './apiTypes'
+import type { CombinedState } from './core/apiState'
+import type { BaseQueryArg, BaseQueryFn } from './baseQueryTypes'
+import type { SerializeQueryArgs } from './defaultSerializeQueryArgs'
+import { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs'
+import type {
+  EndpointBuilder,
+  EndpointDefinitions,
+  SchemaFailureConverter,
+  SchemaFailureHandler,
+  SchemaType,
+} from './endpointDefinitions'
+import {
+  DefinitionType,
+  ENDPOINT_INFINITEQUERY,
+  ENDPOINT_MUTATION,
+  ENDPOINT_QUERY,
+  isInfiniteQueryDefinition,
+  isQueryDefinition,
+} from './endpointDefinitions'
+import { nanoid } from './core/rtkImports'
+import type { UnknownAction } from '@reduxjs/toolkit'
+import type { NoInfer } from './tsHelpers'
+import { weakMapMemoize } from 'reselect'
+
+export interface CreateApiOptions<
+  BaseQuery extends BaseQueryFn,
+  Definitions extends EndpointDefinitions,
+  ReducerPath extends string = 'api',
+  TagTypes extends string = never,
+> {
+  /**
+   * The base query used by each endpoint if no `queryFn` option is specified. RTK Query exports a utility called [fetchBaseQuery](./fetchBaseQuery) as a lightweight wrapper around `fetch` for common use-cases. See [Customizing Queries](../../rtk-query/usage/customizing-queries) if `fetchBaseQuery` does not handle your requirements.
+   *
+   * @example
+   *
+   * ```ts
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+   *
+   * const api = createApi({
+   *   // highlight-start
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   // highlight-end
+   *   endpoints: (build) => ({
+   *     // ...endpoints
+   *   }),
+   * })
+   * ```
+   */
+  baseQuery: BaseQuery
+  /**
+   * An array of string tag type names. Specifying tag types is optional, but you should define them so that they can be used for caching and invalidation. When defining a tag type, you will be able to [provide](../../rtk-query/usage/automated-refetching#providing-tags) them with `providesTags` and [invalidate](../../rtk-query/usage/automated-refetching#invalidating-tags) them with `invalidatesTags` when configuring [endpoints](#endpoints).
+   *
+   * @example
+   *
+   * ```ts
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   // highlight-start
+   *   tagTypes: ['Post', 'User'],
+   *   // highlight-end
+   *   endpoints: (build) => ({
+   *     // ...endpoints
+   *   }),
+   * })
+   * ```
+   */
+  tagTypes?: readonly TagTypes[]
+  /**
+   * The `reducerPath` is a _unique_ key that your service will be mounted to in your store. If you call `createApi` more than once in your application, you will need to provide a unique value each time. Defaults to `'api'`.
+   *
+   * @example
+   *
+   * ```ts
+   * // codeblock-meta title="apis.js"
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query';
+   *
+   * const apiOne = createApi({
+   *   // highlight-start
+   *   reducerPath: 'apiOne',
+   *   // highlight-end
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   endpoints: (builder) => ({
+   *     // ...endpoints
+   *   }),
+   * });
+   *
+   * const apiTwo = createApi({
+   *   // highlight-start
+   *   reducerPath: 'apiTwo',
+   *   // highlight-end
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   endpoints: (builder) => ({
+   *     // ...endpoints
+   *   }),
+   * });
+   * ```
+   */
+  reducerPath?: ReducerPath
+  /**
+   * Accepts a custom function if you have a need to change the creation of cache keys for any reason.
+   */
+  serializeQueryArgs?: SerializeQueryArgs<unknown>
+  /**
+   * Endpoints are a set of operations that you want to perform against your server. You define them as an object using the builder syntax. There are three endpoint types: [`query`](../../rtk-query/usage/queries), [`infiniteQuery`](../../rtk-query/usage/infinite-queries) and [`mutation`](../../rtk-query/usage/mutations).
+   */
+  endpoints(
+    build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>,
+  ): Definitions
+  /**
+   * Defaults to `60` _(this value is in seconds)_. This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta title="keepUnusedDataFor example"
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+   * interface Post {
+   *   id: number
+   *   name: string
+   * }
+   * type PostsResponse = Post[]
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   endpoints: (build) => ({
+   *     getPosts: build.query<PostsResponse, void>({
+   *       query: () => 'posts'
+   *     })
+   *   }),
+   *   // highlight-start
+   *   keepUnusedDataFor: 5
+   *   // highlight-end
+   * })
+   * ```
+   */
+  keepUnusedDataFor?: number
+  /**
+   * Defaults to `false`. This setting allows you to control whether if a cached result is already available RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.
+   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
+   * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.
+   * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.
+   *
+   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
+   */
+  refetchOnMountOrArgChange?: boolean | number
+  /**
+   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.
+   *
+   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
+   *
+   * Note: requires [`setupListeners`](./setupListeners) to have been called.
+   */
+  refetchOnFocus?: boolean
+  /**
+   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.
+   *
+   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
+   *
+   * Note: requires [`setupListeners`](./setupListeners) to have been called.
+   */
+  refetchOnReconnect?: boolean
+  /**
+   * Defaults to `'delayed'`. This setting allows you to control when tags are invalidated after a mutation.
+   *
+   * - `'immediately'`: Queries are invalidated instantly after the mutation finished, even if they are running.
+   *   If the query provides tags that were invalidated while it ran, it won't be re-fetched.
+   * - `'delayed'`: Invalidation only happens after all queries and mutations are settled.
+   *   This ensures that queries are always invalidated correctly and automatically "batches" invalidations of concurrent mutations.
+   *   Note that if you constantly have some queries (or mutations) running, this can delay tag invalidations indefinitely.
+   */
+  invalidationBehavior?: 'delayed' | 'immediately'
+  /**
+   * A function that is passed every dispatched action. If this returns something other than `undefined`,
+   * that return value will be used to rehydrate fulfilled & errored queries.
+   *
+   * @example
+   *
+   * ```ts
+   * // codeblock-meta title="next-redux-wrapper rehydration example"
+   * import type { Action, PayloadAction } from '@reduxjs/toolkit'
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+   * import { HYDRATE } from 'next-redux-wrapper'
+   *
+   * type RootState = any; // normally inferred from state
+   *
+   * function isHydrateAction(action: Action): action is PayloadAction<RootState> {
+   *   return action.type === HYDRATE
+   * }
+   *
+   * export const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   // highlight-start
+   *   extractRehydrationInfo(action, { reducerPath }): any {
+   *     if (isHydrateAction(action)) {
+   *       return action.payload[reducerPath]
+   *     }
+   *   },
+   *   // highlight-end
+   *   endpoints: (build) => ({
+   *     // omitted
+   *   }),
+   * })
+   * ```
+   */
+  extractRehydrationInfo?: (
+    action: UnknownAction,
+    {
+      reducerPath,
+    }: {
+      reducerPath: ReducerPath
+    },
+  ) =>
+    | undefined
+    | CombinedState<
+        NoInfer<Definitions>,
+        NoInfer<TagTypes>,
+        NoInfer<ReducerPath>
+      >
+
+  /**
+   * A function that is called when a schema validation fails.
+   *
+   * Gets called with a `NamedSchemaError` and an object containing the endpoint name, the type of the endpoint, the argument passed to the endpoint, and the query cache key (if applicable).
+   *
+   * `NamedSchemaError` has the following properties:
+   * - `issues`: an array of issues that caused the validation to fail
+   * - `value`: the value that was passed to the schema
+   * - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta no-transpile
+   * import { createApi } from '@reduxjs/toolkit/query/react'
+   * import * as v from "valibot"
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, { id: number }>({
+   *       query: ({ id }) => `/post/${id}`,
+   *     }),
+   *   }),
+   *   onSchemaFailure: (error, info) => {
+   *     console.error(error, info)
+   *   },
+   * })
+   * ```
+   */
+  onSchemaFailure?: SchemaFailureHandler
+
+  /**
+   * Convert a schema validation failure into an error shape matching base query errors.
+   *
+   * When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta no-transpile
+   * import { createApi } from '@reduxjs/toolkit/query/react'
+   * import * as v from "valibot"
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, { id: number }>({
+   *       query: ({ id }) => `/post/${id}`,
+   *       responseSchema: v.object({ id: v.number(), name: v.string() }),
+   *     }),
+   *   }),
+   *   catchSchemaFailure: (error, info) => ({
+   *     status: "CUSTOM_ERROR",
+   *     error: error.schemaName + " failed validation",
+   *     data: error.issues,
+   *   }),
+   * })
+   * ```
+   */
+  catchSchemaFailure?: SchemaFailureConverter<BaseQuery>
+
+  /**
+   * Defaults to `false`.
+   *
+   * If set to `true`, will skip schema validation for all endpoints, unless overridden by the endpoint.
+   *
+   * Can be overridden for specific schemas by passing an array of schema types to skip.
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta no-transpile
+   * import { createApi } from '@reduxjs/toolkit/query/react'
+   * import * as v from "valibot"
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   skipSchemaValidation: process.env.NODE_ENV === "test" ? ["response"] : false, // skip schema validation for response in tests, since we'll be mocking the response
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, { id: number }>({
+   *       query: ({ id }) => `/post/${id}`,
+   *       responseSchema: v.object({ id: v.number(), name: v.string() }),
+   *     }),
+   *   })
+   * })
+   * ```
+   */
+  skipSchemaValidation?: boolean | SchemaType[]
+}
+
+export type CreateApi<Modules extends ModuleName> = {
+  /**
+   * Creates a service to use in your application. Contains only the basic redux logic (the core module).
+   *
+   * @link https://redux-toolkit.js.org/rtk-query/api/createApi
+   */
+  <
+    BaseQuery extends BaseQueryFn,
+    Definitions extends EndpointDefinitions,
+    ReducerPath extends string = 'api',
+    TagTypes extends string = never,
+  >(
+    options: CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>,
+  ): Api<BaseQuery, Definitions, ReducerPath, TagTypes, Modules>
+}
+
+/**
+ * Builds a `createApi` method based on the provided `modules`.
+ *
+ * @link https://redux-toolkit.js.org/rtk-query/usage/customizing-create-api
+ *
+ * @example
+ * ```ts
+ * const MyContext = React.createContext<ReactReduxContextValue | null>(null);
+ * const customCreateApi = buildCreateApi(
+ *   coreModule(),
+ *   reactHooksModule({
+ *     hooks: {
+ *       useDispatch: createDispatchHook(MyContext),
+ *       useSelector: createSelectorHook(MyContext),
+ *       useStore: createStoreHook(MyContext)
+ *     }
+ *   })
+ * );
+ * ```
+ *
+ * @param modules - A variable number of modules that customize how the `createApi` method handles endpoints
+ * @returns A `createApi` method using the provided `modules`.
+ */
+export function buildCreateApi<Modules extends [Module<any>, ...Module<any>[]]>(
+  ...modules: Modules
+): CreateApi<Modules[number]['name']> {
+  return function baseCreateApi(options) {
+    const extractRehydrationInfo = weakMapMemoize((action: UnknownAction) =>
+      options.extractRehydrationInfo?.(action, {
+        reducerPath: (options.reducerPath ?? 'api') as any,
+      }),
+    )
+
+    const optionsWithDefaults: CreateApiOptions<any, any, any, any> = {
+      reducerPath: 'api',
+      keepUnusedDataFor: 60,
+      refetchOnMountOrArgChange: false,
+      refetchOnFocus: false,
+      refetchOnReconnect: false,
+      invalidationBehavior: 'delayed',
+      ...options,
+      extractRehydrationInfo,
+      serializeQueryArgs(queryArgsApi) {
+        let finalSerializeQueryArgs = defaultSerializeQueryArgs
+        if ('serializeQueryArgs' in queryArgsApi.endpointDefinition) {
+          const endpointSQA =
+            queryArgsApi.endpointDefinition.serializeQueryArgs!
+          finalSerializeQueryArgs = (queryArgsApi) => {
+            const initialResult = endpointSQA(queryArgsApi)
+            if (typeof initialResult === 'string') {
+              // If the user function returned a string, use it as-is
+              return initialResult
+            } else {
+              // Assume they returned an object (such as a subset of the original
+              // query args) or a primitive, and serialize it ourselves
+              return defaultSerializeQueryArgs({
+                ...queryArgsApi,
+                queryArgs: initialResult,
+              })
+            }
+          }
+        } else if (options.serializeQueryArgs) {
+          finalSerializeQueryArgs = options.serializeQueryArgs
+        }
+
+        return finalSerializeQueryArgs(queryArgsApi)
+      },
+      tagTypes: [...(options.tagTypes || [])],
+    }
+
+    const context: ApiContext<EndpointDefinitions> = {
+      endpointDefinitions: {},
+      batch(fn) {
+        // placeholder "batch" method to be overridden by plugins, for example with React.unstable_batchedUpdate
+        fn()
+      },
+      apiUid: nanoid(),
+      extractRehydrationInfo,
+      hasRehydrationInfo: weakMapMemoize(
+        (action) => extractRehydrationInfo(action) != null,
+      ),
+    }
+
+    const api = {
+      injectEndpoints,
+      enhanceEndpoints({ addTagTypes, endpoints }) {
+        if (addTagTypes) {
+          for (const eT of addTagTypes) {
+            if (!optionsWithDefaults.tagTypes!.includes(eT as any)) {
+              ;(optionsWithDefaults.tagTypes as any[]).push(eT)
+            }
+          }
+        }
+        if (endpoints) {
+          for (const [endpointName, partialDefinition] of Object.entries(
+            endpoints,
+          )) {
+            if (typeof partialDefinition === 'function') {
+              partialDefinition(getEndpointDefinition(context, endpointName))
+            } else {
+              Object.assign(
+                getEndpointDefinition(context, endpointName) || {},
+                partialDefinition,
+              )
+            }
+          }
+        }
+        return api
+      },
+    } as Api<BaseQueryFn, {}, string, string, Modules[number]['name']>
+
+    const initializedModules = modules.map((m) =>
+      m.init(api as any, optionsWithDefaults as any, context),
+    )
+
+    function injectEndpoints(
+      inject: Parameters<typeof api.injectEndpoints>[0],
+    ) {
+      const evaluatedEndpoints = inject.endpoints({
+        query: (x) => ({ ...x, type: ENDPOINT_QUERY }) as any,
+        mutation: (x) => ({ ...x, type: ENDPOINT_MUTATION }) as any,
+        infiniteQuery: (x) => ({ ...x, type: ENDPOINT_INFINITEQUERY }) as any,
+      })
+
+      for (const [endpointName, definition] of Object.entries(
+        evaluatedEndpoints,
+      )) {
+        if (
+          inject.overrideExisting !== true &&
+          endpointName in context.endpointDefinitions
+        ) {
+          if (inject.overrideExisting === 'throw') {
+            throw new Error(
+              `called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``,
+            )
+          } else if (
+            typeof process !== 'undefined' &&
+            process.env.NODE_ENV === 'development'
+          ) {
+            console.error(
+              `called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``,
+            )
+          }
+
+          continue
+        }
+
+        if (
+          typeof process !== 'undefined' &&
+          process.env.NODE_ENV === 'development'
+        ) {
+          if (isInfiniteQueryDefinition(definition)) {
+            const { infiniteQueryOptions } = definition
+            const { maxPages, getPreviousPageParam } = infiniteQueryOptions
+
+            if (typeof maxPages === 'number') {
+              if (maxPages < 1) {
+                throw new Error(
+                  `maxPages for endpoint '${endpointName}' must be a number greater than 0`,
+                )
+              }
+
+              if (typeof getPreviousPageParam !== 'function') {
+                throw new Error(
+                  `getPreviousPageParam for endpoint '${endpointName}' must be a function if maxPages is used`,
+                )
+              }
+            }
+          }
+        }
+
+        context.endpointDefinitions[endpointName] = definition
+        for (const m of initializedModules) {
+          m.injectEndpoint(endpointName, definition)
+        }
+      }
+
+      return api as any
+    }
+
+    return api.injectEndpoints({ endpoints: options.endpoints as any })
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/query/defaultSerializeQueryArgs.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/defaultSerializeQueryArgs.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/defaultSerializeQueryArgs.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,52 @@
+import type { QueryCacheKey } from './core/apiState'
+import type { EndpointDefinition } from './endpointDefinitions'
+import { isPlainObject } from './core/rtkImports'
+
+const cache: WeakMap<any, string> | undefined = WeakMap
+  ? new WeakMap()
+  : undefined
+
+export const defaultSerializeQueryArgs: SerializeQueryArgs<any> = ({
+  endpointName,
+  queryArgs,
+}) => {
+  let serialized = ''
+
+  const cached = cache?.get(queryArgs)
+
+  if (typeof cached === 'string') {
+    serialized = cached
+  } else {
+    const stringified = JSON.stringify(queryArgs, (key, value) => {
+      // Handle bigints
+      value = typeof value === 'bigint' ? { $bigint: value.toString() } : value
+      // Sort the object keys before stringifying, to prevent useQuery({ a: 1, b: 2 }) having a different cache key than useQuery({ b: 2, a: 1 })
+      value = isPlainObject(value)
+        ? Object.keys(value)
+            .sort()
+            .reduce<any>((acc, key) => {
+              acc[key] = (value as any)[key]
+              return acc
+            }, {})
+        : value
+      return value
+    })
+    if (isPlainObject(queryArgs)) {
+      cache?.set(queryArgs, stringified)
+    }
+    serialized = stringified
+  }
+  return `${endpointName}(${serialized})`
+}
+
+export type SerializeQueryArgs<QueryArgs, ReturnType = string> = (_: {
+  queryArgs: QueryArgs
+  endpointDefinition: EndpointDefinition<any, any, any, any>
+  endpointName: string
+}) => ReturnType
+
+export type InternalSerializeQueryArgs = (_: {
+  queryArgs: any
+  endpointDefinition: EndpointDefinition<any, any, any, any>
+  endpointName: string
+}) => QueryCacheKey
Index: node_modules/@reduxjs/toolkit/src/query/endpointDefinitions.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/endpointDefinitions.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/endpointDefinitions.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1605 @@
+import type { Api } from '@reduxjs/toolkit/query'
+import type { StandardSchemaV1 } from '@standard-schema/spec'
+import type {
+  BaseQueryApi,
+  BaseQueryArg,
+  BaseQueryError,
+  BaseQueryExtraOptions,
+  BaseQueryFn,
+  BaseQueryMeta,
+  BaseQueryResult,
+  QueryReturnValue,
+} from './baseQueryTypes'
+import type { CacheCollectionQueryExtraOptions } from './core/buildMiddleware/cacheCollection'
+import type {
+  CacheLifecycleInfiniteQueryExtraOptions,
+  CacheLifecycleMutationExtraOptions,
+  CacheLifecycleQueryExtraOptions,
+} from './core/buildMiddleware/cacheLifecycle'
+import type {
+  QueryLifecycleInfiniteQueryExtraOptions,
+  QueryLifecycleMutationExtraOptions,
+  QueryLifecycleQueryExtraOptions,
+} from './core/buildMiddleware/queryLifecycle'
+import type {
+  InfiniteData,
+  InfiniteQueryConfigOptions,
+  QuerySubState,
+  RootState,
+} from './core/index'
+import type { SerializeQueryArgs } from './defaultSerializeQueryArgs'
+import type { NEVER } from './fakeBaseQuery'
+import type {
+  CastAny,
+  HasRequiredProps,
+  MaybePromise,
+  NonUndefined,
+  OmitFromUnion,
+  UnwrapPromise,
+} from './tsHelpers'
+import { isNotNullish } from './utils'
+import type { NamedSchemaError } from './standardSchema'
+import { filterMap } from './utils/filterMap'
+
+const rawResultType = /* @__PURE__ */ Symbol()
+const resultType = /* @__PURE__ */ Symbol()
+const baseQuery = /* @__PURE__ */ Symbol()
+
+export interface SchemaFailureInfo {
+  endpoint: string
+  arg: any
+  type: 'query' | 'mutation'
+  queryCacheKey?: string
+}
+
+export type SchemaFailureHandler = (
+  error: NamedSchemaError,
+  info: SchemaFailureInfo,
+) => void
+
+export type SchemaFailureConverter<BaseQuery extends BaseQueryFn> = (
+  error: NamedSchemaError,
+  info: SchemaFailureInfo,
+) => BaseQueryError<BaseQuery>
+
+export type EndpointDefinitionWithQuery<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ResultType,
+  RawResultType extends BaseQueryResult<BaseQuery>,
+> = {
+  /**
+   * `query` can be a function that returns either a `string` or an `object` which is passed to your `baseQuery`. If you are using [fetchBaseQuery](./fetchBaseQuery), this can return either a `string` or an `object` of properties in `FetchArgs`. If you use your own custom [`baseQuery`](../../rtk-query/usage/customizing-queries), you can customize this behavior to your liking.
+   *
+   * @example
+   *
+   * ```ts
+   * // codeblock-meta title="query example"
+   *
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+   * interface Post {
+   *   id: number
+   *   name: string
+   * }
+   * type PostsResponse = Post[]
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   tagTypes: ['Post'],
+   *   endpoints: (build) => ({
+   *     getPosts: build.query<PostsResponse, void>({
+   *       // highlight-start
+   *       query: () => 'posts',
+   *       // highlight-end
+   *     }),
+   *     addPost: build.mutation<Post, Partial<Post>>({
+   *      // highlight-start
+   *      query: (body) => ({
+   *        url: `posts`,
+   *        method: 'POST',
+   *        body,
+   *      }),
+   *      // highlight-end
+   *      invalidatesTags: [{ type: 'Post', id: 'LIST' }],
+   *    }),
+   *   })
+   * })
+   * ```
+   */
+  query(arg: QueryArg): BaseQueryArg<BaseQuery>
+  queryFn?: never
+  /**
+   * A function to manipulate the data returned by a query or mutation.
+   */
+  transformResponse?(
+    baseQueryReturnValue: RawResultType,
+    meta: BaseQueryMeta<BaseQuery>,
+    arg: QueryArg,
+  ): ResultType | Promise<ResultType>
+  /**
+   * A function to manipulate the data returned by a failed query or mutation.
+   */
+  transformErrorResponse?(
+    baseQueryReturnValue: BaseQueryError<BaseQuery>,
+    meta: BaseQueryMeta<BaseQuery>,
+    arg: QueryArg,
+  ): unknown
+
+  /**
+   * A schema for the result *before* it's passed to `transformResponse`.
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta no-transpile
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+   * import * as v from "valibot"
+   *
+   * const postSchema = v.object({ id: v.number(), name: v.string() })
+   * type Post = v.InferOutput<typeof postSchema>
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   endpoints: (build) => ({
+   *     getPostName: build.query<Post, { id: number }>({
+   *       query: ({ id }) => `/post/${id}`,
+   *       rawResponseSchema: postSchema,
+   *       transformResponse: (post) => post.name,
+   *     }),
+   *   })
+   * })
+   * ```
+   */
+  rawResponseSchema?: StandardSchemaV1<RawResultType>
+
+  /**
+   * A schema for the error object returned by the `query` or `queryFn`, *before* it's passed to `transformErrorResponse`.
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta no-transpile
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+   * import * as v from "valibot"
+   * import {customBaseQuery, baseQueryErrorSchema} from "./customBaseQuery"
+   *
+   * const api = createApi({
+   *   baseQuery: customBaseQuery,
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, { id: number }>({
+   *       query: ({ id }) => `/post/${id}`,
+   *       rawErrorResponseSchema: baseQueryErrorSchema,
+   *       transformErrorResponse: (error) => error.data,
+   *     }),
+   *   })
+   * })
+   * ```
+   */
+  rawErrorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>
+}
+
+export type EndpointDefinitionWithQueryFn<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ResultType,
+> = {
+  /**
+   * Can be used in place of `query` as an inline function that bypasses `baseQuery` completely for the endpoint.
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta title="Basic queryFn example"
+   *
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+   * interface Post {
+   *   id: number
+   *   name: string
+   * }
+   * type PostsResponse = Post[]
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   endpoints: (build) => ({
+   *     getPosts: build.query<PostsResponse, void>({
+   *       query: () => 'posts',
+   *     }),
+   *     flipCoin: build.query<'heads' | 'tails', void>({
+   *       // highlight-start
+   *       queryFn(arg, queryApi, extraOptions, baseQuery) {
+   *         const randomVal = Math.random()
+   *         if (randomVal < 0.45) {
+   *           return { data: 'heads' }
+   *         }
+   *         if (randomVal < 0.9) {
+   *           return { data: 'tails' }
+   *         }
+   *         return { error: { status: 500, statusText: 'Internal Server Error', data: "Coin landed on its edge!" } }
+   *       }
+   *       // highlight-end
+   *     })
+   *   })
+   * })
+   * ```
+   */
+  queryFn(
+    arg: QueryArg,
+    api: BaseQueryApi,
+    extraOptions: BaseQueryExtraOptions<BaseQuery>,
+    baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>,
+  ): MaybePromise<
+    QueryReturnValue<
+      ResultType,
+      BaseQueryError<BaseQuery>,
+      BaseQueryMeta<BaseQuery>
+    >
+  >
+  query?: never
+  transformResponse?: never
+  transformErrorResponse?: never
+  rawResponseSchema?: never
+  rawErrorResponseSchema?: never
+}
+
+type BaseEndpointTypes<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ResultType,
+  RawResultType,
+> = {
+  QueryArg: QueryArg
+  BaseQuery: BaseQuery
+  ResultType: ResultType
+  RawResultType: RawResultType
+}
+
+export type SchemaType =
+  | 'arg'
+  | 'rawResponse'
+  | 'response'
+  | 'rawErrorResponse'
+  | 'errorResponse'
+  | 'meta'
+
+interface CommonEndpointDefinition<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ResultType,
+> {
+  /**
+   * A schema for the arguments to be passed to the `query` or `queryFn`.
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta no-transpile
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+   * import * as v from "valibot"
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, { id: number }>({
+   *       query: ({ id }) => `/post/${id}`,
+   *       argSchema: v.object({ id: v.number() }),
+   *     }),
+   *   })
+   * })
+   * ```
+   */
+  argSchema?: StandardSchemaV1<QueryArg>
+
+  /**
+   * A schema for the result (including `transformResponse` if provided).
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta no-transpile
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+   * import * as v from "valibot"
+   *
+   * const postSchema = v.object({ id: v.number(), name: v.string() })
+   * type Post = v.InferOutput<typeof postSchema>
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, { id: number }>({
+   *       query: ({ id }) => `/post/${id}`,
+   *       responseSchema: postSchema,
+   *     }),
+   *   })
+   * })
+   * ```
+   */
+  responseSchema?: StandardSchemaV1<ResultType>
+
+  /**
+   * A schema for the error object returned by the `query` or `queryFn` (including `transformErrorResponse` if provided).
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta no-transpile
+   * import { createApi } from '@reduxjs/toolkit/query/react'
+   * import * as v from "valibot"
+   * import { customBaseQuery, baseQueryErrorSchema } from "./customBaseQuery"
+   *
+   * const api = createApi({
+   *   baseQuery: customBaseQuery,
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, { id: number }>({
+   *       query: ({ id }) => `/post/${id}`,
+   *       errorResponseSchema: baseQueryErrorSchema,
+   *     }),
+   *   })
+   * })
+   * ```
+   */
+  errorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>
+
+  /**
+   * A schema for the `meta` property returned by the `query` or `queryFn`.
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta no-transpile
+   * import { createApi } from '@reduxjs/toolkit/query/react'
+   * import * as v from "valibot"
+   * import { customBaseQuery, baseQueryMetaSchema } from "./customBaseQuery"
+   *
+   * const api = createApi({
+   *   baseQuery: customBaseQuery,
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, { id: number }>({
+   *       query: ({ id }) => `/post/${id}`,
+   *       metaSchema: baseQueryMetaSchema,
+   *     }),
+   *   })
+   * })
+   * ```
+   */
+  metaSchema?: StandardSchemaV1<BaseQueryMeta<BaseQuery>>
+
+  /**
+   * Defaults to `true`.
+   *
+   * Most apps should leave this setting on. The only time it can be a performance issue
+   * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and
+   * you're unable to paginate it.
+   *
+   * For details of how this works, please see the below. When it is set to `false`,
+   * every request will cause subscribed components to rerender, even when the data has not changed.
+   *
+   * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing
+   */
+  structuralSharing?: boolean
+
+  /**
+   * A function that is called when a schema validation fails.
+   *
+   * Gets called with a `NamedSchemaError` and an object containing the endpoint name, the type of the endpoint, the argument passed to the endpoint, and the query cache key (if applicable).
+   *
+   * `NamedSchemaError` has the following properties:
+   * - `issues`: an array of issues that caused the validation to fail
+   * - `value`: the value that was passed to the schema
+   * - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta no-transpile
+   * import { createApi } from '@reduxjs/toolkit/query/react'
+   * import * as v from "valibot"
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, { id: number }>({
+   *       query: ({ id }) => `/post/${id}`,
+   *       onSchemaFailure: (error, info) => {
+   *         console.error(error, info)
+   *       },
+   *     }),
+   *   })
+   * })
+   * ```
+   */
+  onSchemaFailure?: SchemaFailureHandler
+
+  /**
+   * Convert a schema validation failure into an error shape matching base query errors.
+   *
+   * When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta no-transpile
+   * import { createApi } from '@reduxjs/toolkit/query/react'
+   * import * as v from "valibot"
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, { id: number }>({
+   *       query: ({ id }) => `/post/${id}`,
+   *       responseSchema: v.object({ id: v.number(), name: v.string() }),
+   *       catchSchemaFailure: (error, info) => ({
+   *         status: "CUSTOM_ERROR",
+   *         error: error.schemaName + " failed validation",
+   *         data: error.issues,
+   *       }),
+   *     }),
+   *   }),
+   * })
+   * ```
+   */
+  catchSchemaFailure?: SchemaFailureConverter<BaseQuery>
+
+  /**
+   * Defaults to `false`.
+   *
+   * If set to `true`, will skip schema validation for this endpoint.
+   * Overrides the global setting.
+   *
+   * Can be overridden for specific schemas by passing an array of schema types to skip.
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta no-transpile
+   * import { createApi } from '@reduxjs/toolkit/query/react'
+   * import * as v from "valibot"
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, { id: number }>({
+   *       query: ({ id }) => `/post/${id}`,
+   *       responseSchema: v.object({ id: v.number(), name: v.string() }),
+   *       skipSchemaValidation: process.env.NODE_ENV === "test" ? ["response"] : false, // skip schema validation for response in tests, since we'll be mocking the response
+   *     }),
+   *   })
+   * })
+   * ```
+   */
+  skipSchemaValidation?: boolean | SchemaType[]
+}
+
+export type BaseEndpointDefinition<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ResultType,
+  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+> = (
+  | ([CastAny<BaseQueryResult<BaseQuery>, {}>] extends [NEVER]
+      ? never
+      : EndpointDefinitionWithQuery<
+          QueryArg,
+          BaseQuery,
+          ResultType,
+          RawResultType
+        >)
+  | EndpointDefinitionWithQueryFn<QueryArg, BaseQuery, ResultType>
+) &
+  CommonEndpointDefinition<QueryArg, BaseQuery, ResultType> & {
+    /* phantom type */
+    [rawResultType]?: RawResultType
+    /* phantom type */
+    [resultType]?: ResultType
+    /* phantom type */
+    [baseQuery]?: BaseQuery
+  } & HasRequiredProps<
+    BaseQueryExtraOptions<BaseQuery>,
+    { extraOptions: BaseQueryExtraOptions<BaseQuery> },
+    { extraOptions?: BaseQueryExtraOptions<BaseQuery> }
+  >
+
+// NOTE As with QueryStatus in `apiState.ts`, don't use this for real comparisons
+// at runtime, use the string constants defined below.
+export enum DefinitionType {
+  query = 'query',
+  mutation = 'mutation',
+  infinitequery = 'infinitequery',
+}
+
+export const ENDPOINT_QUERY = DefinitionType.query
+export const ENDPOINT_MUTATION = DefinitionType.mutation
+export const ENDPOINT_INFINITEQUERY = DefinitionType.infinitequery
+
+type TagDescriptionArray<TagTypes extends string> = ReadonlyArray<
+  TagDescription<TagTypes> | undefined | null
+>
+
+export type GetResultDescriptionFn<
+  TagTypes extends string,
+  ResultType,
+  QueryArg,
+  ErrorType,
+  MetaType,
+> = (
+  result: ResultType | undefined,
+  error: ErrorType | undefined,
+  arg: QueryArg,
+  meta: MetaType,
+) => TagDescriptionArray<TagTypes>
+
+export type FullTagDescription<TagType> = {
+  type: TagType
+  id?: number | string
+}
+export type TagDescription<TagType> = TagType | FullTagDescription<TagType>
+
+/**
+ * @public
+ */
+export type ResultDescription<
+  TagTypes extends string,
+  ResultType,
+  QueryArg,
+  ErrorType,
+  MetaType,
+> =
+  | TagDescriptionArray<TagTypes>
+  | GetResultDescriptionFn<TagTypes, ResultType, QueryArg, ErrorType, MetaType>
+
+type QueryTypes<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  TagTypes extends string,
+  ResultType,
+  ReducerPath extends string = string,
+  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {
+  /**
+   * The endpoint definition type. To be used with some internal generic types.
+   * @example
+   * ```ts
+   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...
+   * ```
+   */
+  QueryDefinition: QueryDefinition<
+    QueryArg,
+    BaseQuery,
+    TagTypes,
+    ResultType,
+    ReducerPath
+  >
+  TagTypes: TagTypes
+  ReducerPath: ReducerPath
+}
+
+/**
+ * @public
+ */
+export interface QueryExtraOptions<
+  TagTypes extends string,
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ReducerPath extends string = string,
+  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+> extends CacheLifecycleQueryExtraOptions<
+      ResultType,
+      QueryArg,
+      BaseQuery,
+      ReducerPath
+    >,
+    QueryLifecycleQueryExtraOptions<
+      ResultType,
+      QueryArg,
+      BaseQuery,
+      ReducerPath
+    >,
+    CacheCollectionQueryExtraOptions {
+  type: DefinitionType.query
+
+  /**
+   * Used by `query` endpoints. Determines which 'tag' is attached to the cached data returned by the query.
+   * Expects an array of tag type strings, an array of objects of tag types with ids, or a function that returns such an array.
+   * 1.  `['Post']` - equivalent to `2`
+   * 2.  `[{ type: 'Post' }]` - equivalent to `1`
+   * 3.  `[{ type: 'Post', id: 1 }]`
+   * 4.  `(result, error, arg) => ['Post']` - equivalent to `5`
+   * 5.  `(result, error, arg) => [{ type: 'Post' }]` - equivalent to `4`
+   * 6.  `(result, error, arg) => [{ type: 'Post', id: 1 }]`
+   *
+   * @example
+   *
+   * ```ts
+   * // codeblock-meta title="providesTags example"
+   *
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+   * interface Post {
+   *   id: number
+   *   name: string
+   * }
+   * type PostsResponse = Post[]
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   tagTypes: ['Posts'],
+   *   endpoints: (build) => ({
+   *     getPosts: build.query<PostsResponse, void>({
+   *       query: () => 'posts',
+   *       // highlight-start
+   *       providesTags: (result) =>
+   *         result
+   *           ? [
+   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),
+   *               { type: 'Posts', id: 'LIST' },
+   *             ]
+   *           : [{ type: 'Posts', id: 'LIST' }],
+   *       // highlight-end
+   *     })
+   *   })
+   * })
+   * ```
+   */
+  providesTags?: ResultDescription<
+    TagTypes,
+    ResultType,
+    QueryArg,
+    BaseQueryError<BaseQuery>,
+    BaseQueryMeta<BaseQuery>
+  >
+  /**
+   * Not to be used. A query should not invalidate tags in the cache.
+   */
+  invalidatesTags?: never
+
+  /**
+   * Can be provided to return a custom cache key value based on the query arguments.
+   *
+   * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key.  It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.
+   *
+   * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean.  If it returns a string, that value will be used as the cache key directly.  If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`.  This simplifies the use case of stripping out args you don't want included in the cache key.
+   *
+   *
+   * @example
+   *
+   * ```ts
+   * // codeblock-meta title="serializeQueryArgs : exclude value"
+   *
+   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
+   * interface Post {
+   *   id: number
+   *   name: string
+   * }
+   *
+   * interface MyApiClient {
+   *   fetchPost: (id: string) => Promise<Post>
+   * }
+   *
+   * createApi({
+   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *  endpoints: (build) => ({
+   *    // Example: an endpoint with an API client passed in as an argument,
+   *    // but only the item ID should be used as the cache key
+   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({
+   *      queryFn: async ({ id, client }) => {
+   *        const post = await client.fetchPost(id)
+   *        return { data: post }
+   *      },
+   *      // highlight-start
+   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {
+   *        const { id } = queryArgs
+   *        // This can return a string, an object, a number, or a boolean.
+   *        // If it returns an object, number or boolean, that value
+   *        // will be serialized automatically via `defaultSerializeQueryArgs`
+   *        return { id } // omit `client` from the cache key
+   *
+   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:
+   *        // return defaultSerializeQueryArgs({
+   *        //   endpointName,
+   *        //   queryArgs: { id },
+   *        //   endpointDefinition
+   *        // })
+   *        // Or  create and return a string yourself:
+   *        // return `getPost(${id})`
+   *      },
+   *      // highlight-end
+   *    }),
+   *  }),
+   *})
+   * ```
+   */
+  serializeQueryArgs?: SerializeQueryArgs<
+    QueryArg,
+    string | number | boolean | Record<any, any>
+  >
+
+  /**
+   * Can be provided to merge an incoming response value into the current cache data.
+   * If supplied, no automatic structural sharing will be applied - it's up to
+   * you to update the cache appropriately.
+   *
+   * Since RTKQ normally replaces cache entries with the new response, you will usually
+   * need to use this with the `serializeQueryArgs` or `forceRefetch` options to keep
+   * an existing cache entry so that it can be updated.
+   *
+   * Since this is wrapped with Immer, you may either mutate the `currentCacheValue` directly,
+   * or return a new value, but _not_ both at once.
+   *
+   * Will only be called if the existing `currentCacheData` is _not_ `undefined` - on first response,
+   * the cache entry will just save the response data directly.
+   *
+   * Useful if you don't want a new request to completely override the current cache value,
+   * maybe because you have manually updated it from another source and don't want those
+   * updates to get lost.
+   *
+   *
+   * @example
+   *
+   * ```ts
+   * // codeblock-meta title="merge: pagination"
+   *
+   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
+   * interface Post {
+   *   id: number
+   *   name: string
+   * }
+   *
+   * createApi({
+   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *  endpoints: (build) => ({
+   *    listItems: build.query<string[], number>({
+   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,
+   *     // Only have one cache entry because the arg always maps to one string
+   *     serializeQueryArgs: ({ endpointName }) => {
+   *       return endpointName
+   *      },
+   *      // Always merge incoming data to the cache entry
+   *      merge: (currentCache, newItems) => {
+   *        currentCache.push(...newItems)
+   *      },
+   *      // Refetch when the page arg changes
+   *      forceRefetch({ currentArg, previousArg }) {
+   *        return currentArg !== previousArg
+   *      },
+   *    }),
+   *  }),
+   *})
+   * ```
+   */
+  merge?(
+    currentCacheData: ResultType,
+    responseData: ResultType,
+    otherArgs: {
+      arg: QueryArg
+      baseQueryMeta: BaseQueryMeta<BaseQuery>
+      requestId: string
+      fulfilledTimeStamp: number
+    },
+  ): ResultType | void
+
+  /**
+   * Check to see if the endpoint should force a refetch in cases where it normally wouldn't.
+   * This is primarily useful for "infinite scroll" / pagination use cases where
+   * RTKQ is keeping a single cache entry that is added to over time, in combination
+   * with `serializeQueryArgs` returning a fixed cache key and a `merge` callback
+   * set to add incoming data to the cache entry each time.
+   *
+   * @example
+   *
+   * ```ts
+   * // codeblock-meta title="forceRefresh: pagination"
+   *
+   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
+   * interface Post {
+   *   id: number
+   *   name: string
+   * }
+   *
+   * createApi({
+   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *  endpoints: (build) => ({
+   *    listItems: build.query<string[], number>({
+   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,
+   *     // Only have one cache entry because the arg always maps to one string
+   *     serializeQueryArgs: ({ endpointName }) => {
+   *       return endpointName
+   *      },
+   *      // Always merge incoming data to the cache entry
+   *      merge: (currentCache, newItems) => {
+   *        currentCache.push(...newItems)
+   *      },
+   *      // Refetch when the page arg changes
+   *      forceRefetch({ currentArg, previousArg }) {
+   *        return currentArg !== previousArg
+   *      },
+   *    }),
+   *  }),
+   *})
+   * ```
+   */
+  forceRefetch?(params: {
+    currentArg: QueryArg | undefined
+    previousArg: QueryArg | undefined
+    state: RootState<any, any, string>
+    endpointState?: QuerySubState<any>
+  }): boolean
+
+  /**
+   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
+   */
+  Types?: QueryTypes<
+    QueryArg,
+    BaseQuery,
+    TagTypes,
+    ResultType,
+    ReducerPath,
+    RawResultType
+  >
+}
+
+export type QueryDefinition<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  TagTypes extends string,
+  ResultType,
+  ReducerPath extends string = string,
+  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+> = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType, RawResultType> &
+  QueryExtraOptions<
+    TagTypes,
+    ResultType,
+    QueryArg,
+    BaseQuery,
+    ReducerPath,
+    RawResultType
+  >
+
+export type InfiniteQueryTypes<
+  QueryArg,
+  PageParam,
+  BaseQuery extends BaseQueryFn,
+  TagTypes extends string,
+  ResultType,
+  ReducerPath extends string = string,
+  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {
+  /**
+   * The endpoint definition type. To be used with some internal generic types.
+   * @example
+   * ```ts
+   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...
+   * ```
+   */
+  InfiniteQueryDefinition: InfiniteQueryDefinition<
+    QueryArg,
+    PageParam,
+    BaseQuery,
+    TagTypes,
+    ResultType,
+    ReducerPath
+  >
+  TagTypes: TagTypes
+  ReducerPath: ReducerPath
+}
+
+export interface InfiniteQueryExtraOptions<
+  TagTypes extends string,
+  ResultType,
+  QueryArg,
+  PageParam,
+  BaseQuery extends BaseQueryFn,
+  ReducerPath extends string = string,
+  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+> extends CacheLifecycleInfiniteQueryExtraOptions<
+      InfiniteData<ResultType, PageParam>,
+      QueryArg,
+      BaseQuery,
+      ReducerPath
+    >,
+    QueryLifecycleInfiniteQueryExtraOptions<
+      InfiniteData<ResultType, PageParam>,
+      QueryArg,
+      BaseQuery,
+      ReducerPath
+    >,
+    CacheCollectionQueryExtraOptions {
+  type: DefinitionType.infinitequery
+
+  providesTags?: ResultDescription<
+    TagTypes,
+    InfiniteData<ResultType, PageParam>,
+    QueryArg,
+    BaseQueryError<BaseQuery>,
+    BaseQueryMeta<BaseQuery>
+  >
+  /**
+   * Not to be used. A query should not invalidate tags in the cache.
+   */
+  invalidatesTags?: never
+
+  /**
+   * Required options to configure the infinite query behavior.
+   * `initialPageParam` and `getNextPageParam` are required, to
+   * ensure the infinite query can properly fetch the next page of data.
+   * `initialPageParam` may be specified when using the
+   * endpoint, to override the default value.
+   * `maxPages` and `getPreviousPageParam` are both optional.
+   * 
+   * @example
+   * 
+   * ```ts
+   * // codeblock-meta title="infiniteQueryOptions example"
+   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
+   * 
+   * type Pokemon = {
+   *   id: string
+   *   name: string
+   * }
+   * 
+   * const pokemonApi = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
+   *   endpoints: (build) => ({
+   *     getInfinitePokemonWithMax: build.infiniteQuery<Pokemon[], string, number>({
+   *       infiniteQueryOptions: {
+   *         initialPageParam: 0,
+   *         maxPages: 3,
+   *         getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) =>
+   *           lastPageParam + 1,
+   *         getPreviousPageParam: (
+   *           firstPage,
+   *           allPages,
+   *           firstPageParam,
+   *           allPageParams,
+   *         ) => {
+   *           return firstPageParam > 0 ? firstPageParam - 1 : undefined
+   *         },
+   *       },
+   *       query({pageParam}) {
+   *         return `https://example.com/listItems?page=${pageParam}`
+   *       },
+   *     }),
+   *   }),
+   * })
+   
+   * ```
+   */
+  infiniteQueryOptions: InfiniteQueryConfigOptions<
+    ResultType,
+    PageParam,
+    QueryArg
+  >
+
+  /**
+   * Can be provided to return a custom cache key value based on the query arguments.
+   *
+   * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key.  It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.
+   *
+   * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean.  If it returns a string, that value will be used as the cache key directly.  If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`.  This simplifies the use case of stripping out args you don't want included in the cache key.
+   *
+   *
+   * @example
+   *
+   * ```ts
+   * // codeblock-meta title="serializeQueryArgs : exclude value"
+   *
+   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
+   * interface Post {
+   *   id: number
+   *   name: string
+   * }
+   *
+   * interface MyApiClient {
+   *   fetchPost: (id: string) => Promise<Post>
+   * }
+   *
+   * createApi({
+   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *  endpoints: (build) => ({
+   *    // Example: an endpoint with an API client passed in as an argument,
+   *    // but only the item ID should be used as the cache key
+   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({
+   *      queryFn: async ({ id, client }) => {
+   *        const post = await client.fetchPost(id)
+   *        return { data: post }
+   *      },
+   *      // highlight-start
+   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {
+   *        const { id } = queryArgs
+   *        // This can return a string, an object, a number, or a boolean.
+   *        // If it returns an object, number or boolean, that value
+   *        // will be serialized automatically via `defaultSerializeQueryArgs`
+   *        return { id } // omit `client` from the cache key
+   *
+   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:
+   *        // return defaultSerializeQueryArgs({
+   *        //   endpointName,
+   *        //   queryArgs: { id },
+   *        //   endpointDefinition
+   *        // })
+   *        // Or  create and return a string yourself:
+   *        // return `getPost(${id})`
+   *      },
+   *      // highlight-end
+   *    }),
+   *  }),
+   *})
+   * ```
+   */
+  serializeQueryArgs?: SerializeQueryArgs<
+    QueryArg,
+    string | number | boolean | Record<any, any>
+  >
+
+  /**
+   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
+   */
+  Types?: InfiniteQueryTypes<
+    QueryArg,
+    PageParam,
+    BaseQuery,
+    TagTypes,
+    ResultType,
+    ReducerPath,
+    RawResultType
+  >
+}
+
+export type InfiniteQueryDefinition<
+  QueryArg,
+  PageParam,
+  BaseQuery extends BaseQueryFn,
+  TagTypes extends string,
+  ResultType,
+  ReducerPath extends string = string,
+  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+> =
+  // Infinite query endpoints receive `{queryArg, pageParam}`
+  BaseEndpointDefinition<
+    InfiniteQueryCombinedArg<QueryArg, PageParam>,
+    BaseQuery,
+    ResultType,
+    RawResultType
+  > &
+    InfiniteQueryExtraOptions<
+      TagTypes,
+      ResultType,
+      QueryArg,
+      PageParam,
+      BaseQuery,
+      ReducerPath,
+      RawResultType
+    >
+
+type MutationTypes<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  TagTypes extends string,
+  ResultType,
+  ReducerPath extends string = string,
+  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {
+  /**
+   * The endpoint definition type. To be used with some internal generic types.
+   * @example
+   * ```ts
+   * const useMyWrappedHook: UseMutation<typeof api.endpoints.query.Types.MutationDefinition> = ...
+   * ```
+   */
+  MutationDefinition: MutationDefinition<
+    QueryArg,
+    BaseQuery,
+    TagTypes,
+    ResultType,
+    ReducerPath
+  >
+  TagTypes: TagTypes
+  ReducerPath: ReducerPath
+}
+
+/**
+ * @public
+ */
+export interface MutationExtraOptions<
+  TagTypes extends string,
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ReducerPath extends string = string,
+  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+> extends CacheLifecycleMutationExtraOptions<
+      ResultType,
+      QueryArg,
+      BaseQuery,
+      ReducerPath
+    >,
+    QueryLifecycleMutationExtraOptions<
+      ResultType,
+      QueryArg,
+      BaseQuery,
+      ReducerPath
+    > {
+  type: DefinitionType.mutation
+
+  /**
+   * Used by `mutation` endpoints. Determines which cached data should be either re-fetched or removed from the cache.
+   * Expects the same shapes as `providesTags`.
+   *
+   * @example
+   *
+   * ```ts
+   * // codeblock-meta title="invalidatesTags example"
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+   * interface Post {
+   *   id: number
+   *   name: string
+   * }
+   * type PostsResponse = Post[]
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   tagTypes: ['Posts'],
+   *   endpoints: (build) => ({
+   *     getPosts: build.query<PostsResponse, void>({
+   *       query: () => 'posts',
+   *       providesTags: (result) =>
+   *         result
+   *           ? [
+   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),
+   *               { type: 'Posts', id: 'LIST' },
+   *             ]
+   *           : [{ type: 'Posts', id: 'LIST' }],
+   *     }),
+   *     addPost: build.mutation<Post, Partial<Post>>({
+   *       query(body) {
+   *         return {
+   *           url: `posts`,
+   *           method: 'POST',
+   *           body,
+   *         }
+   *       },
+   *       // highlight-start
+   *       invalidatesTags: [{ type: 'Posts', id: 'LIST' }],
+   *       // highlight-end
+   *     }),
+   *   })
+   * })
+   * ```
+   */
+  invalidatesTags?: ResultDescription<
+    TagTypes,
+    ResultType,
+    QueryArg,
+    BaseQueryError<BaseQuery>,
+    BaseQueryMeta<BaseQuery>
+  >
+  /**
+   * Not to be used. A mutation should not provide tags to the cache.
+   */
+  providesTags?: never
+
+  /**
+   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
+   */
+  Types?: MutationTypes<
+    QueryArg,
+    BaseQuery,
+    TagTypes,
+    ResultType,
+    ReducerPath,
+    RawResultType
+  >
+}
+
+export type MutationDefinition<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  TagTypes extends string,
+  ResultType,
+  ReducerPath extends string = string,
+  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+> = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType, RawResultType> &
+  MutationExtraOptions<
+    TagTypes,
+    ResultType,
+    QueryArg,
+    BaseQuery,
+    ReducerPath,
+    RawResultType
+  >
+
+export type EndpointDefinition<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  TagTypes extends string,
+  ResultType,
+  ReducerPath extends string = string,
+  PageParam = any,
+  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+> =
+  | QueryDefinition<
+      QueryArg,
+      BaseQuery,
+      TagTypes,
+      ResultType,
+      ReducerPath,
+      RawResultType
+    >
+  | MutationDefinition<
+      QueryArg,
+      BaseQuery,
+      TagTypes,
+      ResultType,
+      ReducerPath,
+      RawResultType
+    >
+  | InfiniteQueryDefinition<
+      QueryArg,
+      PageParam,
+      BaseQuery,
+      TagTypes,
+      ResultType,
+      ReducerPath,
+      RawResultType
+    >
+
+export type EndpointDefinitions = Record<
+  string,
+  EndpointDefinition<any, any, any, any, any, any, any>
+>
+
+export function isQueryDefinition(
+  e: EndpointDefinition<any, any, any, any, any, any, any>,
+): e is QueryDefinition<any, any, any, any, any, any> {
+  return e.type === ENDPOINT_QUERY
+}
+
+export function isMutationDefinition(
+  e: EndpointDefinition<any, any, any, any, any, any, any>,
+): e is MutationDefinition<any, any, any, any, any, any> {
+  return e.type === ENDPOINT_MUTATION
+}
+
+export function isInfiniteQueryDefinition(
+  e: EndpointDefinition<any, any, any, any, any, any, any>,
+): e is InfiniteQueryDefinition<any, any, any, any, any, any, any> {
+  return e.type === ENDPOINT_INFINITEQUERY
+}
+
+export function isAnyQueryDefinition(
+  e: EndpointDefinition<any, any, any, any>,
+): e is
+  | QueryDefinition<any, any, any, any>
+  | InfiniteQueryDefinition<any, any, any, any, any> {
+  return isQueryDefinition(e) || isInfiniteQueryDefinition(e)
+}
+
+export type EndpointBuilder<
+  BaseQuery extends BaseQueryFn,
+  TagTypes extends string,
+  ReducerPath extends string,
+> = {
+  /**
+   * An endpoint definition that retrieves data, and may provide tags to the cache.
+   *
+   * @example
+   * ```js
+   * // codeblock-meta title="Example of all query endpoint options"
+   * const api = createApi({
+   *  baseQuery,
+   *  endpoints: (build) => ({
+   *    getPost: build.query({
+   *      query: (id) => ({ url: `post/${id}` }),
+   *      // Pick out data and prevent nested properties in a hook or selector
+   *      transformResponse: (response) => response.data,
+   *      // Pick out error and prevent nested properties in a hook or selector
+   *      transformErrorResponse: (response) => response.error,
+   *      // `result` is the server response
+   *      providesTags: (result, error, id) => [{ type: 'Post', id }],
+   *      // trigger side effects or optimistic updates
+   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry, updateCachedData }) {},
+   *      // handle subscriptions etc
+   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry, updateCachedData }) {},
+   *    }),
+   *  }),
+   *});
+   *```
+   */
+  query<
+    ResultType,
+    QueryArg,
+    RawResultType extends
+      BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+  >(
+    definition: OmitFromUnion<
+      QueryDefinition<
+        QueryArg,
+        BaseQuery,
+        TagTypes,
+        ResultType,
+        ReducerPath,
+        RawResultType
+      >,
+      'type'
+    >,
+  ): QueryDefinition<
+    QueryArg,
+    BaseQuery,
+    TagTypes,
+    ResultType,
+    ReducerPath,
+    RawResultType
+  >
+
+  /**
+   * An endpoint definition that alters data on the server or will possibly invalidate the cache.
+   *
+   * @example
+   * ```js
+   * // codeblock-meta title="Example of all mutation endpoint options"
+   * const api = createApi({
+   *   baseQuery,
+   *   endpoints: (build) => ({
+   *     updatePost: build.mutation({
+   *       query: ({ id, ...patch }) => ({ url: `post/${id}`, method: 'PATCH', body: patch }),
+   *       // Pick out data and prevent nested properties in a hook or selector
+   *       transformResponse: (response) => response.data,
+   *       // Pick out error and prevent nested properties in a hook or selector
+   *       transformErrorResponse: (response) => response.error,
+   *       // `result` is the server response
+   *       invalidatesTags: (result, error, id) => [{ type: 'Post', id }],
+   *      // trigger side effects or optimistic updates
+   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry }) {},
+   *      // handle subscriptions etc
+   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry }) {},
+   *     }),
+   *   }),
+   * });
+   * ```
+   */
+  mutation<
+    ResultType,
+    QueryArg,
+    RawResultType extends
+      BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+  >(
+    definition: OmitFromUnion<
+      MutationDefinition<
+        QueryArg,
+        BaseQuery,
+        TagTypes,
+        ResultType,
+        ReducerPath,
+        RawResultType
+      >,
+      'type'
+    >,
+  ): MutationDefinition<
+    QueryArg,
+    BaseQuery,
+    TagTypes,
+    ResultType,
+    ReducerPath,
+    RawResultType
+  >
+
+  infiniteQuery<
+    ResultType,
+    QueryArg,
+    PageParam,
+    RawResultType extends
+      BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+  >(
+    definition: OmitFromUnion<
+      InfiniteQueryDefinition<
+        QueryArg,
+        PageParam,
+        BaseQuery,
+        TagTypes,
+        ResultType,
+        ReducerPath,
+        RawResultType
+      >,
+      'type'
+    >,
+  ): InfiniteQueryDefinition<
+    QueryArg,
+    PageParam,
+    BaseQuery,
+    TagTypes,
+    ResultType,
+    ReducerPath,
+    RawResultType
+  >
+}
+
+export type AssertTagTypes = <T extends FullTagDescription<string>>(t: T) => T
+
+export function calculateProvidedBy<ResultType, QueryArg, ErrorType, MetaType>(
+  description:
+    | ResultDescription<string, ResultType, QueryArg, ErrorType, MetaType>
+    | undefined,
+  result: ResultType | undefined,
+  error: ErrorType | undefined,
+  queryArg: QueryArg,
+  meta: MetaType | undefined,
+  assertTagTypes: AssertTagTypes,
+): readonly FullTagDescription<string>[] {
+  const finalDescription = isFunction(description)
+    ? description(
+        result as ResultType,
+        error as undefined,
+        queryArg,
+        meta as MetaType,
+      )
+    : description
+
+  if (finalDescription) {
+    return filterMap(finalDescription, isNotNullish, (tag) =>
+      assertTagTypes(expandTagDescription(tag)),
+    )
+  }
+
+  return []
+}
+
+function isFunction<T>(t: T): t is Extract<T, Function> {
+  return typeof t === 'function'
+}
+
+export function expandTagDescription(
+  description: TagDescription<string>,
+): FullTagDescription<string> {
+  return typeof description === 'string' ? { type: description } : description
+}
+
+export type QueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> =
+  D extends BaseEndpointDefinition<infer QA, any, any, any> ? QA : never
+
+// Just extracting `QueryArg` from `BaseEndpointDefinition`
+// doesn't sufficiently match here.
+// We need to explicitly match against `InfiniteQueryDefinition`
+export type InfiniteQueryArgFrom<
+  D extends BaseEndpointDefinition<any, any, any, any>,
+> =
+  D extends InfiniteQueryDefinition<infer QA, any, any, any, any, any, any>
+    ? QA
+    : never
+
+export type QueryArgFromAnyQuery<
+  D extends BaseEndpointDefinition<any, any, any, any>,
+> =
+  D extends InfiniteQueryDefinition<any, any, any, any, any, any, any>
+    ? InfiniteQueryArgFrom<D>
+    : D extends QueryDefinition<any, any, any, any, any, any>
+      ? QueryArgFrom<D>
+      : never
+
+export type ResultTypeFrom<
+  D extends BaseEndpointDefinition<any, any, any, any>,
+> = D extends BaseEndpointDefinition<any, any, infer RT, any> ? RT : unknown
+
+export type ReducerPathFrom<
+  D extends EndpointDefinition<any, any, any, any, any, any, any>,
+> =
+  D extends EndpointDefinition<any, any, any, any, infer RP, any, any>
+    ? RP
+    : unknown
+
+export type TagTypesFrom<
+  D extends EndpointDefinition<any, any, any, any, any, any, any>,
+> =
+  D extends EndpointDefinition<any, any, infer TT, any, any, any, any>
+    ? TT
+    : unknown
+
+export type PageParamFrom<
+  D extends InfiniteQueryDefinition<any, any, any, any, any, any, any>,
+> =
+  D extends InfiniteQueryDefinition<any, infer PP, any, any, any, any, any>
+    ? PP
+    : unknown
+
+export type InfiniteQueryCombinedArg<QueryArg, PageParam> = {
+  queryArg: QueryArg
+  pageParam: PageParam
+}
+
+export type TagTypesFromApi<T> =
+  T extends Api<any, any, any, infer TagTypes> ? TagTypes : never
+
+export type DefinitionsFromApi<T> =
+  T extends Api<any, infer Definitions, any, any> ? Definitions : never
+
+export type TransformedResponse<
+  NewDefinitions extends EndpointDefinitions,
+  K,
+  ResultType,
+> = K extends keyof NewDefinitions
+  ? NewDefinitions[K]['transformResponse'] extends undefined
+    ? ResultType
+    : UnwrapPromise<
+        ReturnType<NonUndefined<NewDefinitions[K]['transformResponse']>>
+      >
+  : ResultType
+
+export type OverrideResultType<Definition, NewResultType> =
+  Definition extends QueryDefinition<
+    infer QueryArg,
+    infer BaseQuery,
+    infer TagTypes,
+    any,
+    infer ReducerPath
+  >
+    ? QueryDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath>
+    : Definition extends MutationDefinition<
+          infer QueryArg,
+          infer BaseQuery,
+          infer TagTypes,
+          any,
+          infer ReducerPath
+        >
+      ? MutationDefinition<
+          QueryArg,
+          BaseQuery,
+          TagTypes,
+          NewResultType,
+          ReducerPath
+        >
+      : Definition extends InfiniteQueryDefinition<
+            infer QueryArg,
+            infer PageParam,
+            infer BaseQuery,
+            infer TagTypes,
+            any,
+            infer ReducerPath
+          >
+        ? InfiniteQueryDefinition<
+            QueryArg,
+            PageParam,
+            BaseQuery,
+            TagTypes,
+            NewResultType,
+            ReducerPath
+          >
+        : never
+
+export type UpdateDefinitions<
+  Definitions extends EndpointDefinitions,
+  NewTagTypes extends string,
+  NewDefinitions extends EndpointDefinitions,
+> = {
+  [K in keyof Definitions]: Definitions[K] extends QueryDefinition<
+    infer QueryArg,
+    infer BaseQuery,
+    any,
+    infer ResultType,
+    infer ReducerPath
+  >
+    ? QueryDefinition<
+        QueryArg,
+        BaseQuery,
+        NewTagTypes,
+        TransformedResponse<NewDefinitions, K, ResultType>,
+        ReducerPath
+      >
+    : Definitions[K] extends MutationDefinition<
+          infer QueryArg,
+          infer BaseQuery,
+          any,
+          infer ResultType,
+          infer ReducerPath
+        >
+      ? MutationDefinition<
+          QueryArg,
+          BaseQuery,
+          NewTagTypes,
+          TransformedResponse<NewDefinitions, K, ResultType>,
+          ReducerPath
+        >
+      : Definitions[K] extends InfiniteQueryDefinition<
+            infer QueryArg,
+            infer PageParam,
+            infer BaseQuery,
+            any,
+            infer ResultType,
+            infer ReducerPath
+          >
+        ? InfiniteQueryDefinition<
+            QueryArg,
+            PageParam,
+            BaseQuery,
+            NewTagTypes,
+            TransformedResponse<NewDefinitions, K, ResultType>,
+            ReducerPath
+          >
+        : never
+}
Index: node_modules/@reduxjs/toolkit/src/query/fakeBaseQuery.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/fakeBaseQuery.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/fakeBaseQuery.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,21 @@
+import type { BaseQueryFn } from './baseQueryTypes'
+
+export const _NEVER = /* @__PURE__ */ Symbol()
+export type NEVER = typeof _NEVER
+
+/**
+ * Creates a "fake" baseQuery to be used if your api *only* uses the `queryFn` definition syntax.
+ * This also allows you to specify a specific error type to be shared by all your `queryFn` definitions.
+ */
+export function fakeBaseQuery<ErrorType>(): BaseQueryFn<
+  void,
+  NEVER,
+  ErrorType,
+  {}
+> {
+  return function () {
+    throw new Error(
+      'When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.',
+    )
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/query/fetchBaseQuery.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/fetchBaseQuery.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/fetchBaseQuery.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,385 @@
+import { joinUrls } from './utils'
+import { isPlainObject } from './core/rtkImports'
+import type { BaseQueryApi, BaseQueryFn } from './baseQueryTypes'
+import type { MaybePromise, Override } from './tsHelpers'
+import { anySignal, timeoutSignal } from './utils/signals'
+
+export type ResponseHandler =
+  | 'content-type'
+  | 'json'
+  | 'text'
+  | ((response: Response) => Promise<any>)
+
+type CustomRequestInit = Override<
+  RequestInit,
+  {
+    headers?:
+      | Headers
+      | string[][]
+      | Record<string, string | undefined>
+      | undefined
+  }
+>
+
+export interface FetchArgs extends CustomRequestInit {
+  url: string
+  params?: Record<string, any>
+  body?: any
+  responseHandler?: ResponseHandler
+  validateStatus?: (response: Response, body: any) => boolean
+  /**
+   * A number in milliseconds that represents that maximum time a request can take before timing out.
+   */
+  timeout?: number
+}
+
+/**
+ * A mini-wrapper that passes arguments straight through to
+ * {@link [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)}.
+ * Avoids storing `fetch` in a closure, in order to permit mocking/monkey-patching.
+ */
+const defaultFetchFn: typeof fetch = (...args) => fetch(...args)
+
+const defaultValidateStatus = (response: Response) =>
+  response.status >= 200 && response.status <= 299
+
+const defaultIsJsonContentType = (headers: Headers) =>
+  /*applicat*/ /ion\/(vnd\.api\+)?json/.test(headers.get('content-type') || '')
+
+export type FetchBaseQueryError =
+  | {
+      /**
+       * * `number`:
+       *   HTTP status code
+       */
+      status: number
+      data: unknown
+    }
+  | {
+      /**
+       * * `"FETCH_ERROR"`:
+       *   An error that occurred during execution of `fetch` or the `fetchFn` callback option
+       **/
+      status: 'FETCH_ERROR'
+      data?: undefined
+      error: string
+    }
+  | {
+      /**
+       * * `"PARSING_ERROR"`:
+       *   An error happened during parsing.
+       *   Most likely a non-JSON-response was returned with the default `responseHandler` "JSON",
+       *   or an error occurred while executing a custom `responseHandler`.
+       **/
+      status: 'PARSING_ERROR'
+      originalStatus: number
+      data: string
+      error: string
+    }
+  | {
+      /**
+       * * `"TIMEOUT_ERROR"`:
+       *   Request timed out
+       **/
+      status: 'TIMEOUT_ERROR'
+      data?: undefined
+      error: string
+    }
+  | {
+      /**
+       * * `"CUSTOM_ERROR"`:
+       *   A custom error type that you can return from your `queryFn` where another error might not make sense.
+       **/
+      status: 'CUSTOM_ERROR'
+      data?: unknown
+      error: string
+    }
+
+function stripUndefined(obj: any) {
+  if (!isPlainObject(obj)) {
+    return obj
+  }
+  const copy: Record<string, any> = { ...obj }
+  for (const [k, v] of Object.entries(copy)) {
+    if (v === undefined) delete copy[k]
+  }
+  return copy
+}
+
+// Only set the content-type to json if appropriate. Will not be true for FormData, ArrayBuffer, Blob, etc.
+const isJsonifiable = (body: any) =>
+  typeof body === 'object' &&
+  (isPlainObject(body) ||
+    Array.isArray(body) ||
+    typeof body.toJSON === 'function')
+
+export type FetchBaseQueryArgs = {
+  baseUrl?: string
+  prepareHeaders?: (
+    headers: Headers,
+    api: Pick<
+      BaseQueryApi,
+      'getState' | 'extra' | 'endpoint' | 'type' | 'forced'
+    > & { arg: string | FetchArgs; extraOptions: unknown },
+  ) => MaybePromise<Headers | void>
+  fetchFn?: (
+    input: RequestInfo,
+    init?: RequestInit | undefined,
+  ) => Promise<Response>
+  paramsSerializer?: (params: Record<string, any>) => string
+  /**
+   * By default, we only check for 'application/json' and 'application/vnd.api+json' as the content-types for json. If you need to support another format, you can pass
+   * in a predicate function for your given api to get the same automatic stringifying behavior
+   * @example
+   * ```ts
+   * const isJsonContentType = (headers: Headers) => ["application/vnd.api+json", "application/json", "application/vnd.hal+json"].includes(headers.get("content-type")?.trim());
+   * ```
+   */
+  isJsonContentType?: (headers: Headers) => boolean
+  /**
+   * Defaults to `application/json`;
+   */
+  jsonContentType?: string
+
+  /**
+   * Custom replacer function used when calling `JSON.stringify()`;
+   */
+  jsonReplacer?: (this: any, key: string, value: any) => any
+} & RequestInit &
+  Pick<FetchArgs, 'responseHandler' | 'validateStatus' | 'timeout'>
+
+export type FetchBaseQueryMeta = { request: Request; response?: Response }
+
+/**
+ * This is a very small wrapper around fetch that aims to simplify requests.
+ *
+ * @example
+ * ```ts
+ * const baseQuery = fetchBaseQuery({
+ *   baseUrl: 'https://api.your-really-great-app.com/v1/',
+ *   prepareHeaders: (headers, { getState }) => {
+ *     const token = (getState() as RootState).auth.token;
+ *     // If we have a token set in state, let's assume that we should be passing it.
+ *     if (token) {
+ *       headers.set('authorization', `Bearer ${token}`);
+ *     }
+ *     return headers;
+ *   },
+ * })
+ * ```
+ *
+ * @param {string} baseUrl
+ * The base URL for an API service.
+ * Typically in the format of https://example.com/
+ *
+ * @param {(headers: Headers, api: { getState: () => unknown; arg: string | FetchArgs; extra: unknown; endpoint: string; type: 'query' | 'mutation'; forced: boolean; }) => Headers} prepareHeaders
+ * An optional function that can be used to inject headers on requests.
+ * Provides a Headers object, most of the `BaseQueryApi` (`dispatch` is not available), and the arg passed into the query function.
+ * Useful for setting authentication or headers that need to be set conditionally.
+ *
+ * @link https://developer.mozilla.org/en-US/docs/Web/API/Headers
+ *
+ * @param {(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>} fetchFn
+ * Accepts a custom `fetch` function if you do not want to use the default on the window.
+ * Useful in SSR environments if you need to use a library such as `isomorphic-fetch` or `cross-fetch`
+ *
+ * @param {(params: Record<string, unknown>) => string} paramsSerializer
+ * An optional function that can be used to stringify querystring parameters.
+ *
+ * @param {(headers: Headers) => boolean} isJsonContentType
+ * An optional predicate function to determine if `JSON.stringify()` should be called on the `body` arg of `FetchArgs`
+ *
+ * @param {string} jsonContentType Used when automatically setting the content-type header for a request with a jsonifiable body that does not have an explicit content-type header. Defaults to `application/json`.
+ *
+ * @param {(this: any, key: string, value: any) => any} jsonReplacer Custom replacer function used when calling `JSON.stringify()`.
+ *
+ * @param {number} timeout
+ * A number in milliseconds that represents the maximum time a request can take before timing out.
+ */
+
+export function fetchBaseQuery({
+  baseUrl,
+  prepareHeaders = (x) => x,
+  fetchFn = defaultFetchFn,
+  paramsSerializer,
+  isJsonContentType = defaultIsJsonContentType,
+  jsonContentType = 'application/json',
+  jsonReplacer,
+  timeout: defaultTimeout,
+  responseHandler: globalResponseHandler,
+  validateStatus: globalValidateStatus,
+  ...baseFetchOptions
+}: FetchBaseQueryArgs = {}): BaseQueryFn<
+  string | FetchArgs,
+  unknown,
+  FetchBaseQueryError,
+  {},
+  FetchBaseQueryMeta
+> {
+  if (typeof fetch === 'undefined' && fetchFn === defaultFetchFn) {
+    console.warn(
+      'Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.',
+    )
+  }
+  return async (arg, api, extraOptions) => {
+    const { getState, extra, endpoint, forced, type } = api
+    let meta: FetchBaseQueryMeta | undefined
+    let {
+      url,
+      headers = new Headers(baseFetchOptions.headers),
+      params = undefined,
+      responseHandler = globalResponseHandler ?? ('json' as const),
+      validateStatus = globalValidateStatus ?? defaultValidateStatus,
+      timeout = defaultTimeout,
+      ...rest
+    } = typeof arg == 'string' ? { url: arg } : arg
+
+    let config: RequestInit = {
+      ...baseFetchOptions,
+      signal: timeout
+        ? anySignal(api.signal, timeoutSignal(timeout))
+        : api.signal,
+      ...rest,
+    }
+
+    headers = new Headers(stripUndefined(headers))
+    config.headers =
+      (await prepareHeaders(headers, {
+        getState,
+        arg,
+        extra,
+        endpoint,
+        forced,
+        type,
+        extraOptions,
+      })) || headers
+
+    const bodyIsJsonifiable = isJsonifiable(config.body)
+
+    // Remove content-type for non-jsonifiable bodies to let the browser set it automatically
+    // Exception: keep content-type for string bodies as they might be intentional (text/plain, text/html, etc.)
+    if (
+      config.body != null &&
+      !bodyIsJsonifiable &&
+      typeof config.body !== 'string'
+    ) {
+      config.headers.delete('content-type')
+    }
+
+    if (!config.headers.has('content-type') && bodyIsJsonifiable) {
+      config.headers.set('content-type', jsonContentType)
+    }
+
+    if (bodyIsJsonifiable && isJsonContentType(config.headers)) {
+      config.body = JSON.stringify(config.body, jsonReplacer)
+    }
+
+    // Set Accept header based on responseHandler if not already set
+    if (!config.headers.has('accept')) {
+      if (responseHandler === 'json') {
+        config.headers.set('accept', 'application/json')
+      } else if (responseHandler === 'text') {
+        config.headers.set('accept', 'text/plain, text/html, */*')
+      }
+      // For 'content-type' responseHandler, don't set Accept (let server decide)
+    }
+
+    if (params) {
+      const divider = ~url.indexOf('?') ? '&' : '?'
+      const query = paramsSerializer
+        ? paramsSerializer(params)
+        : new URLSearchParams(stripUndefined(params))
+      url += divider + query
+    }
+
+    url = joinUrls(baseUrl, url)
+
+    const request = new Request(url, config)
+    const requestClone = new Request(url, config)
+    meta = { request: requestClone }
+
+    let response
+    try {
+      response = await fetchFn(request)
+    } catch (e) {
+      return {
+        error: {
+          status:
+            (e instanceof Error ||
+              (typeof DOMException !== 'undefined' &&
+                e instanceof DOMException)) &&
+            e.name === 'TimeoutError'
+              ? 'TIMEOUT_ERROR'
+              : 'FETCH_ERROR',
+          error: String(e),
+        },
+        meta,
+      }
+    }
+    const responseClone = response.clone()
+
+    meta.response = responseClone
+
+    let resultData: any
+    let responseText: string = ''
+    try {
+      let handleResponseError
+      await Promise.all([
+        handleResponse(response, responseHandler).then(
+          (r) => (resultData = r),
+          (e) => (handleResponseError = e),
+        ),
+        // see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182
+        // we *have* to "use up" both streams at the same time or they will stop running in node-fetch scenarios
+        responseClone.text().then(
+          (r) => (responseText = r),
+          () => {},
+        ),
+      ])
+      if (handleResponseError) throw handleResponseError
+    } catch (e) {
+      return {
+        error: {
+          status: 'PARSING_ERROR',
+          originalStatus: response.status,
+          data: responseText,
+          error: String(e),
+        },
+        meta,
+      }
+    }
+
+    return validateStatus(response, resultData)
+      ? {
+          data: resultData,
+          meta,
+        }
+      : {
+          error: {
+            status: response.status,
+            data: resultData,
+          },
+          meta,
+        }
+  }
+
+  async function handleResponse(
+    response: Response,
+    responseHandler: ResponseHandler,
+  ) {
+    if (typeof responseHandler === 'function') {
+      return responseHandler(response)
+    }
+
+    if (responseHandler === 'content-type') {
+      responseHandler = isJsonContentType(response.headers) ? 'json' : 'text'
+    }
+
+    if (responseHandler === 'json') {
+      const text = await response.text()
+      return text.length ? JSON.parse(text) : null
+    }
+
+    return response.text()
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/query/index.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,106 @@
+// This must remain here so that the `mangleErrors.cjs` build script
+// does not have to import this into each source file it rewrites.
+import { formatProdErrorMessage } from '@reduxjs/toolkit'
+
+export type {
+  CombinedState,
+  QueryCacheKey,
+  QueryKeys,
+  QuerySubState,
+  RootState,
+  SubscriptionOptions,
+} from './core/apiState'
+export { QueryStatus } from './core/apiState'
+export type { Api, ApiContext, Module } from './apiTypes'
+
+export type {
+  BaseQueryApi,
+  BaseQueryArg,
+  BaseQueryEnhancer,
+  BaseQueryError,
+  BaseQueryExtraOptions,
+  BaseQueryFn,
+  BaseQueryMeta,
+  BaseQueryResult,
+  QueryReturnValue,
+} from './baseQueryTypes'
+export type {
+  BaseEndpointDefinition,
+  EndpointDefinitions,
+  EndpointDefinition,
+  EndpointBuilder,
+  QueryDefinition,
+  MutationDefinition,
+  MutationExtraOptions,
+  InfiniteQueryArgFrom,
+  InfiniteQueryDefinition,
+  InfiniteQueryExtraOptions,
+  PageParamFrom,
+  TagDescription,
+  QueryArgFrom,
+  QueryExtraOptions,
+  ResultTypeFrom,
+  DefinitionType,
+  DefinitionsFromApi,
+  OverrideResultType,
+  ResultDescription,
+  TagTypesFromApi,
+  UpdateDefinitions,
+  SchemaFailureHandler,
+  SchemaFailureConverter,
+  SchemaFailureInfo,
+  SchemaType,
+} from './endpointDefinitions'
+export { fetchBaseQuery } from './fetchBaseQuery'
+export type {
+  FetchBaseQueryArgs,
+  FetchBaseQueryError,
+  FetchBaseQueryMeta,
+  FetchArgs,
+} from './fetchBaseQuery'
+export { retry } from './retry'
+export type { RetryOptions } from './retry'
+export { setupListeners } from './core/setupListeners'
+export { skipToken } from './core/buildSelectors'
+export type {
+  QueryResultSelectorResult,
+  MutationResultSelectorResult,
+  SkipToken,
+} from './core/buildSelectors'
+export type {
+  QueryActionCreatorResult,
+  MutationActionCreatorResult,
+  StartQueryActionCreatorOptions,
+} from './core/buildInitiate'
+export type { CreateApi, CreateApiOptions } from './createApi'
+export { buildCreateApi } from './createApi'
+export { _NEVER, fakeBaseQuery } from './fakeBaseQuery'
+export { copyWithStructuralSharing } from './utils/copyWithStructuralSharing'
+export { createApi, coreModule, coreModuleName } from './core/index'
+export type {
+  InfiniteData,
+  InfiniteQueryActionCreatorResult,
+  InfiniteQueryConfigOptions,
+  InfiniteQueryResultSelectorResult,
+  InfiniteQuerySubState,
+  TypedMutationOnQueryStarted,
+  TypedQueryOnQueryStarted,
+} from './core/index'
+export type {
+  ApiEndpointMutation,
+  ApiEndpointQuery,
+  ApiEndpointInfiniteQuery,
+  ApiModules,
+  CoreModule,
+  PrefetchOptions,
+} from './core/module'
+export { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs'
+export type { SerializeQueryArgs } from './defaultSerializeQueryArgs'
+
+export type {
+  Id as TSHelpersId,
+  NoInfer as TSHelpersNoInfer,
+  Override as TSHelpersOverride,
+} from './tsHelpers'
+
+export { NamedSchemaError } from './standardSchema'
Index: node_modules/@reduxjs/toolkit/src/query/react/ApiProvider.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/react/ApiProvider.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/react/ApiProvider.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,69 @@
+import { configureStore } from '@reduxjs/toolkit'
+import type { Context } from 'react'
+import { useContext, useEffect } from './reactImports'
+import * as React from 'react'
+import type { ReactReduxContextValue } from 'react-redux'
+import { Provider, ReactReduxContext } from './reactReduxImports'
+import { setupListeners } from './rtkqImports'
+import type { Api } from '@reduxjs/toolkit/query'
+
+/**
+ * Can be used as a `Provider` if you **do not already have a Redux store**.
+ *
+ * @example
+ * ```tsx
+ * // codeblock-meta no-transpile title="Basic usage - wrap your App with ApiProvider"
+ * import * as React from 'react';
+ * import { ApiProvider } from '@reduxjs/toolkit/query/react';
+ * import { Pokemon } from './features/Pokemon';
+ *
+ * function App() {
+ *   return (
+ *     <ApiProvider api={api}>
+ *       <Pokemon />
+ *     </ApiProvider>
+ *   );
+ * }
+ * ```
+ *
+ * @remarks
+ * Using this together with an existing redux store, both will
+ * conflict with each other - please use the traditional redux setup
+ * in that case.
+ */
+export function ApiProvider(props: {
+  children: any
+  api: Api<any, {}, any, any>
+  setupListeners?: Parameters<typeof setupListeners>[1] | false
+  context?: Context<ReactReduxContextValue | null>
+}) {
+  const context = props.context || ReactReduxContext
+  const existingContext = useContext(context)
+  if (existingContext) {
+    throw new Error(
+      'Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.',
+    )
+  }
+  const [store] = React.useState(() =>
+    configureStore({
+      reducer: {
+        [props.api.reducerPath]: props.api.reducer,
+      },
+      middleware: (gDM) => gDM().concat(props.api.middleware),
+    }),
+  )
+  // Adds the event listeners for online/offline/focus/etc
+  useEffect(
+    (): undefined | (() => void) =>
+      props.setupListeners === false
+        ? undefined
+        : setupListeners(store.dispatch, props.setupListeners),
+    [props.setupListeners, store.dispatch],
+  )
+
+  return (
+    <Provider store={store} context={context}>
+      {props.children}
+    </Provider>
+  )
+}
Index: node_modules/@reduxjs/toolkit/src/query/react/buildHooks.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/react/buildHooks.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/react/buildHooks.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,2258 @@
+import type {
+  Selector,
+  ThunkAction,
+  ThunkDispatch,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import type {
+  Api,
+  ApiContext,
+  ApiEndpointInfiniteQuery,
+  ApiEndpointMutation,
+  ApiEndpointQuery,
+  BaseQueryFn,
+  CoreModule,
+  EndpointDefinitions,
+  InfiniteQueryActionCreatorResult,
+  InfiniteQueryArgFrom,
+  InfiniteQueryDefinition,
+  InfiniteQueryResultSelectorResult,
+  InfiniteQuerySubState,
+  MutationActionCreatorResult,
+  MutationDefinition,
+  MutationResultSelectorResult,
+  PageParamFrom,
+  PrefetchOptions,
+  QueryActionCreatorResult,
+  QueryArgFrom,
+  QueryCacheKey,
+  QueryDefinition,
+  QueryKeys,
+  QueryResultSelectorResult,
+  QuerySubState,
+  ResultTypeFrom,
+  RootState,
+  SerializeQueryArgs,
+  SkipToken,
+  SubscriptionOptions,
+  TSHelpersId,
+  TSHelpersNoInfer,
+  TSHelpersOverride,
+} from '@reduxjs/toolkit/query'
+import { QueryStatus, skipToken } from './rtkqImports'
+import type { DependencyList } from 'react'
+import {
+  useCallback,
+  useDebugValue,
+  useEffect,
+  useLayoutEffect,
+  useMemo,
+  useRef,
+  useState,
+} from './reactImports'
+import { shallowEqual } from './reactReduxImports'
+
+import type { SubscriptionSelectors } from '../core/buildMiddleware/index'
+import type { InfiniteData, InfiniteQueryConfigOptions } from '../core/index'
+import type { UninitializedValue } from './constants'
+import { UNINITIALIZED_VALUE } from './constants'
+import type { ReactHooksModuleOptions } from './module'
+import { useStableQueryArgs } from './useSerializedStableValue'
+import { useShallowStableValue } from './useShallowStableValue'
+import type { InfiniteQueryDirection } from '../core/apiState'
+import { isInfiniteQueryDefinition } from '../endpointDefinitions'
+import type { StartInfiniteQueryActionCreator } from '../core/buildInitiate'
+
+// Copy-pasted from React-Redux
+const canUseDOM = () =>
+  !!(
+    typeof window !== 'undefined' &&
+    typeof window.document !== 'undefined' &&
+    typeof window.document.createElement !== 'undefined'
+  )
+
+const isDOM = /* @__PURE__ */ canUseDOM()
+
+// Under React Native, we know that we always want to use useLayoutEffect
+
+const isRunningInReactNative = () =>
+  typeof navigator !== 'undefined' && navigator.product === 'ReactNative'
+
+const isReactNative = /* @__PURE__ */ isRunningInReactNative()
+
+const getUseIsomorphicLayoutEffect = () =>
+  isDOM || isReactNative ? useLayoutEffect : useEffect
+
+export const useIsomorphicLayoutEffect =
+  /* @__PURE__ */ getUseIsomorphicLayoutEffect()
+
+export type QueryHooks<
+  Definition extends QueryDefinition<any, any, any, any, any>,
+> = {
+  useQuery: UseQuery<Definition>
+  useLazyQuery: UseLazyQuery<Definition>
+  useQuerySubscription: UseQuerySubscription<Definition>
+  useLazyQuerySubscription: UseLazyQuerySubscription<Definition>
+  useQueryState: UseQueryState<Definition>
+}
+
+export type InfiniteQueryHooks<
+  Definition extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = {
+  useInfiniteQuery: UseInfiniteQuery<Definition>
+  useInfiniteQuerySubscription: UseInfiniteQuerySubscription<Definition>
+  useInfiniteQueryState: UseInfiniteQueryState<Definition>
+}
+
+export type MutationHooks<
+  Definition extends MutationDefinition<any, any, any, any, any>,
+> = {
+  useMutation: UseMutation<Definition>
+}
+
+/**
+ * A React hook that automatically triggers fetches of data from an endpoint, 'subscribes' the component to the cached data, and reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.
+ *
+ * The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already, and the hook will return the data for that query arg once it's available.
+ *
+ * This hook combines the functionality of both [`useQueryState`](#usequerystate) and [`useQuerySubscription`](#usequerysubscription) together, and is intended to be used in the majority of situations.
+ *
+ * #### Features
+ *
+ * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
+ * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
+ * - Returns the latest request status and cached data from the Redux store
+ * - Re-renders as the request status changes and data becomes available
+ */
+export type UseQuery<D extends QueryDefinition<any, any, any, any>> = <
+  R extends Record<string, any> = UseQueryStateDefaultResult<D>,
+>(
+  arg: QueryArgFrom<D> | SkipToken,
+  options?: UseQuerySubscriptionOptions & UseQueryStateOptions<D, R>,
+) => UseQueryHookResult<D, R>
+
+export type TypedUseQuery<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+> = UseQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>
+
+export type UseQueryHookResult<
+  D extends QueryDefinition<any, any, any, any>,
+  R = UseQueryStateDefaultResult<D>,
+> = UseQueryStateResult<D, R> & UseQuerySubscriptionResult<D>
+
+/**
+ * Helper type to manually type the result
+ * of the `useQuery` hook in userland code.
+ */
+export type TypedUseQueryHookResult<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  R = UseQueryStateDefaultResult<
+    QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
+  >,
+> = TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery, R> &
+  TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery>
+
+export type UseQuerySubscriptionOptions = SubscriptionOptions & {
+  /**
+   * Prevents a query from automatically running.
+   *
+   * @remarks
+   * When `skip` is true (or `skipToken` is passed in as `arg`):
+   *
+   * - **If the query has cached data:**
+   *   * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed
+   *   * The query will have a status of `uninitialized`
+   *   * If `skip: false` is set after the initial load, the cached result will be used
+   * - **If the query does not have cached data:**
+   *   * The query will have a status of `uninitialized`
+   *   * The query will not exist in the state when viewed with the dev tools
+   *   * The query will not automatically fetch on mount
+   *   * The query will not automatically run when additional components with the same query are added that do run
+   *
+   * @example
+   * ```tsx
+   * // codeblock-meta no-transpile title="Skip example"
+   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
+   *   const { data, error, status } = useGetPokemonByNameQuery(name, {
+   *     skip,
+   *   });
+   *
+   *   return (
+   *     <div>
+   *       {name} - {status}
+   *     </div>
+   *   );
+   * };
+   * ```
+   */
+  skip?: boolean
+  /**
+   * Defaults to `false`. This setting allows you to control whether if a cached result is already available, RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.
+   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
+   * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.
+   * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.
+   *
+   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
+   */
+  refetchOnMountOrArgChange?: boolean | number
+}
+
+/**
+ * A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data.
+ *
+ * The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already.
+ *
+ * Note that this hook does not return a request status or cached data. For that use-case, see [`useQuery`](#usequery) or [`useQueryState`](#usequerystate).
+ *
+ * #### Features
+ *
+ * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
+ * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
+ */
+export type UseQuerySubscription<
+  D extends QueryDefinition<any, any, any, any>,
+> = (
+  arg: QueryArgFrom<D> | SkipToken,
+  options?: UseQuerySubscriptionOptions,
+) => UseQuerySubscriptionResult<D>
+
+export type TypedUseQuerySubscription<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+> = UseQuerySubscription<
+  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
+>
+
+export type UseQuerySubscriptionResult<
+  D extends QueryDefinition<any, any, any, any>,
+> = Pick<QueryActionCreatorResult<D>, 'refetch'>
+
+/**
+ * Helper type to manually type the result
+ * of the `useQuerySubscription` hook in userland code.
+ */
+export type TypedUseQuerySubscriptionResult<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+> = UseQuerySubscriptionResult<
+  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
+>
+
+export type UseLazyQueryLastPromiseInfo<
+  D extends QueryDefinition<any, any, any, any>,
+> = {
+  lastArg: QueryArgFrom<D>
+}
+
+/**
+ * A React hook similar to [`useQuery`](#usequery), but with manual control over when the data fetching occurs.
+ *
+ * This hook includes the functionality of [`useLazyQuerySubscription`](#uselazyquerysubscription).
+ *
+ * #### Features
+ *
+ * - Manual control over firing a request to retrieve data
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
+ * - Returns the latest request status and cached data from the Redux store
+ * - Re-renders as the request status changes and data becomes available
+ * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met and the fetch has been manually called at least once
+ *
+ * #### Note
+ *
+ * When the trigger function returned from a LazyQuery is called, it always initiates a new request to the server even if there is cached data. Set `preferCacheValue`(the second argument to the function) as `true` if you want it to immediately return a cached value if one exists.
+ */
+export type UseLazyQuery<D extends QueryDefinition<any, any, any, any>> = <
+  R extends Record<string, any> = UseQueryStateDefaultResult<D>,
+>(
+  options?: SubscriptionOptions & Omit<UseQueryStateOptions<D, R>, 'skip'>,
+) => [
+  LazyQueryTrigger<D>,
+  UseLazyQueryStateResult<D, R>,
+  UseLazyQueryLastPromiseInfo<D>,
+]
+
+export type TypedUseLazyQuery<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+> = UseLazyQuery<
+  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
+>
+
+export type UseLazyQueryStateResult<
+  D extends QueryDefinition<any, any, any, any>,
+  R = UseQueryStateDefaultResult<D>,
+> = UseQueryStateResult<D, R> & {
+  /**
+   * Resets the hook state to its initial `uninitialized` state.
+   * This will also remove the last result from the cache.
+   */
+  reset: () => void
+}
+
+/**
+ * Helper type to manually type the result
+ * of the `useLazyQuery` hook in userland code.
+ */
+export type TypedUseLazyQueryStateResult<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  R = UseQueryStateDefaultResult<
+    QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
+  >,
+> = UseLazyQueryStateResult<
+  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>,
+  R
+>
+
+export type LazyQueryTrigger<D extends QueryDefinition<any, any, any, any>> = {
+  /**
+   * Triggers a lazy query.
+   *
+   * By default, this will start a new request even if there is already a value in the cache.
+   * If you want to use the cache value and only start a request if there is no cache value, set the second argument to `true`.
+   *
+   * @remarks
+   * If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta title="Using .unwrap with async await"
+   * try {
+   *   const payload = await getUserById(1).unwrap();
+   *   console.log('fulfilled', payload)
+   * } catch (error) {
+   *   console.error('rejected', error);
+   * }
+   * ```
+   */
+  (
+    arg: QueryArgFrom<D>,
+    preferCacheValue?: boolean,
+  ): QueryActionCreatorResult<D>
+}
+
+export type TypedLazyQueryTrigger<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+> = LazyQueryTrigger<
+  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
+>
+
+/**
+ * A React hook similar to [`useQuerySubscription`](#usequerysubscription), but with manual control over when the data fetching occurs.
+ *
+ * Note that this hook does not return a request status or cached data. For that use-case, see [`useLazyQuery`](#uselazyquery).
+ *
+ * #### Features
+ *
+ * - Manual control over firing a request to retrieve data
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
+ * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met and the fetch has been manually called at least once
+ */
+export type UseLazyQuerySubscription<
+  D extends QueryDefinition<any, any, any, any>,
+> = (
+  options?: SubscriptionOptions,
+) => readonly [
+  LazyQueryTrigger<D>,
+  QueryArgFrom<D> | UninitializedValue,
+  { reset: () => void },
+]
+
+export type TypedUseLazyQuerySubscription<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+> = UseLazyQuerySubscription<
+  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
+>
+
+/**
+ * @internal
+ */
+export type QueryStateSelector<
+  R extends Record<string, any>,
+  D extends QueryDefinition<any, any, any, any>,
+> = (state: UseQueryStateDefaultResult<D>) => R
+
+/**
+ * Provides a way to define a strongly-typed version of
+ * {@linkcode QueryStateSelector} for use with a specific query.
+ * This is useful for scenarios where you want to create a "pre-typed"
+ * {@linkcode UseQueryStateOptions.selectFromResult | selectFromResult}
+ * function.
+ *
+ * @example
+ * <caption>#### __Create a strongly-typed `selectFromResult` selector function__</caption>
+ *
+ * ```tsx
+ * import type { TypedQueryStateSelector } from '@reduxjs/toolkit/query/react'
+ * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+ *
+ * type Post = {
+ *   id: number
+ *   title: string
+ * }
+ *
+ * type PostsApiResponse = {
+ *   posts: Post[]
+ *   total: number
+ *   skip: number
+ *   limit: number
+ * }
+ *
+ * type QueryArgument = number | undefined
+ *
+ * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>
+ *
+ * type SelectedResult = Pick<PostsApiResponse, 'posts'>
+ *
+ * const postsApiSlice = createApi({
+ *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com/posts' }),
+ *   reducerPath: 'postsApi',
+ *   tagTypes: ['Posts'],
+ *   endpoints: (build) => ({
+ *     getPosts: build.query<PostsApiResponse, QueryArgument>({
+ *       query: (limit = 5) => `?limit=${limit}&select=title`,
+ *     }),
+ *   }),
+ * })
+ *
+ * const { useGetPostsQuery } = postsApiSlice
+ *
+ * function PostById({ id }: { id: number }) {
+ *   const { post } = useGetPostsQuery(undefined, {
+ *     selectFromResult: (state) => ({
+ *       post: state.data?.posts.find((post) => post.id === id),
+ *     }),
+ *   })
+ *
+ *   return <li>{post?.title}</li>
+ * }
+ *
+ * const EMPTY_ARRAY: Post[] = []
+ *
+ * const typedSelectFromResult: TypedQueryStateSelector<
+ *   PostsApiResponse,
+ *   QueryArgument,
+ *   BaseQueryFunction,
+ *   SelectedResult
+ * > = (state) => ({ posts: state.data?.posts ?? EMPTY_ARRAY })
+ *
+ * function PostsList() {
+ *   const { posts } = useGetPostsQuery(undefined, {
+ *     selectFromResult: typedSelectFromResult,
+ *   })
+ *
+ *   return (
+ *     <div>
+ *       <ul>
+ *         {posts.map((post) => (
+ *           <PostById key={post.id} id={post.id} />
+ *         ))}
+ *       </ul>
+ *     </div>
+ *   )
+ * }
+ * ```
+ *
+ * @template ResultType - The type of the result `data` returned by the query.
+ * @template QueryArgumentType - The type of the argument passed into the query.
+ * @template BaseQueryFunctionType - The type of the base query function being used.
+ * @template SelectedResultType - The type of the selected result returned by the __`selectFromResult`__ function.
+ *
+ * @since 2.3.0
+ * @public
+ */
+export type TypedQueryStateSelector<
+  ResultType,
+  QueryArgumentType,
+  BaseQueryFunctionType extends BaseQueryFn,
+  SelectedResultType extends Record<string, any> = UseQueryStateDefaultResult<
+    QueryDefinition<
+      QueryArgumentType,
+      BaseQueryFunctionType,
+      string,
+      ResultType,
+      string
+    >
+  >,
+> = QueryStateSelector<
+  SelectedResultType,
+  QueryDefinition<
+    QueryArgumentType,
+    BaseQueryFunctionType,
+    string,
+    ResultType,
+    string
+  >
+>
+
+/**
+ * A React hook that reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.
+ *
+ * Note that this hook does not trigger fetching new data. For that use-case, see [`useQuery`](#usequery) or [`useQuerySubscription`](#usequerysubscription).
+ *
+ * #### Features
+ *
+ * - Returns the latest request status and cached data from the Redux store
+ * - Re-renders as the request status changes and data becomes available
+ */
+export type UseQueryState<D extends QueryDefinition<any, any, any, any>> = <
+  R extends Record<string, any> = UseQueryStateDefaultResult<D>,
+>(
+  arg: QueryArgFrom<D> | SkipToken,
+  options?: UseQueryStateOptions<D, R>,
+) => UseQueryStateResult<D, R>
+
+export type TypedUseQueryState<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+> = UseQueryState<
+  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
+>
+
+/**
+ * @internal
+ */
+export type UseQueryStateOptions<
+  D extends QueryDefinition<any, any, any, any>,
+  R extends Record<string, any>,
+> = {
+  /**
+   * Prevents a query from automatically running.
+   *
+   * @remarks
+   * When skip is true:
+   *
+   * - **If the query has cached data:**
+   *   * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed
+   *   * The query will have a status of `uninitialized`
+   *   * If `skip: false` is set after skipping the initial load, the cached result will be used
+   * - **If the query does not have cached data:**
+   *   * The query will have a status of `uninitialized`
+   *   * The query will not exist in the state when viewed with the dev tools
+   *   * The query will not automatically fetch on mount
+   *   * The query will not automatically run when additional components with the same query are added that do run
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta title="Skip example"
+   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
+   *   const { data, error, status } = useGetPokemonByNameQuery(name, {
+   *     skip,
+   *   });
+   *
+   *   return (
+   *     <div>
+   *       {name} - {status}
+   *     </div>
+   *   );
+   * };
+   * ```
+   */
+  skip?: boolean
+  /**
+   * `selectFromResult` allows you to get a specific segment from a query result in a performant manner.
+   * When using this feature, the component will not rerender unless the underlying data of the selected item has changed.
+   * If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta title="Using selectFromResult to extract a single result"
+   * function PostsList() {
+   *   const { data: posts } = api.useGetPostsQuery();
+   *
+   *   return (
+   *     <ul>
+   *       {posts?.data?.map((post) => (
+   *         <PostById key={post.id} id={post.id} />
+   *       ))}
+   *     </ul>
+   *   );
+   * }
+   *
+   * function PostById({ id }: { id: number }) {
+   *   // Will select the post with the given id, and will only rerender if the given posts data changes
+   *   const { post } = api.useGetPostsQuery(undefined, {
+   *     selectFromResult: ({ data }) => ({ post: data?.find((post) => post.id === id) }),
+   *   });
+   *
+   *   return <li>{post?.name}</li>;
+   * }
+   * ```
+   */
+  selectFromResult?: QueryStateSelector<R, D>
+}
+
+/**
+ * Provides a way to define a "pre-typed" version of
+ * {@linkcode UseQueryStateOptions} with specific options for a given query.
+ * This is particularly useful for setting default query behaviors such as
+ * refetching strategies, which can be overridden as needed.
+ *
+ * @example
+ * <caption>#### __Create a `useQuery` hook with default options__</caption>
+ *
+ * ```ts
+ * import type {
+ *   SubscriptionOptions,
+ *   TypedUseQueryStateOptions,
+ * } from '@reduxjs/toolkit/query/react'
+ * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+ *
+ * type Post = {
+ *   id: number
+ *   name: string
+ * }
+ *
+ * const api = createApi({
+ *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+ *   tagTypes: ['Post'],
+ *   endpoints: (build) => ({
+ *     getPosts: build.query<Post[], void>({
+ *       query: () => 'posts',
+ *     }),
+ *   }),
+ * })
+ *
+ * const { useGetPostsQuery } = api
+ *
+ * export const useGetPostsQueryWithDefaults = <
+ *   SelectedResult extends Record<string, any>,
+ * >(
+ *   overrideOptions: TypedUseQueryStateOptions<
+ *     Post[],
+ *     void,
+ *     ReturnType<typeof fetchBaseQuery>,
+ *     SelectedResult
+ *   > &
+ *     SubscriptionOptions,
+ * ) =>
+ *   useGetPostsQuery(undefined, {
+ *     // Insert default options here
+ *
+ *     refetchOnMountOrArgChange: true,
+ *     refetchOnFocus: true,
+ *     ...overrideOptions,
+ *   })
+ * ```
+ *
+ * @template ResultType - The type of the result `data` returned by the query.
+ * @template QueryArg - The type of the argument passed into the query.
+ * @template BaseQuery - The type of the base query function being used.
+ * @template SelectedResult - The type of the selected result returned by the __`selectFromResult`__ function.
+ *
+ * @since 2.2.8
+ * @public
+ */
+export type TypedUseQueryStateOptions<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  SelectedResult extends Record<string, any> = UseQueryStateDefaultResult<
+    QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
+  >,
+> = UseQueryStateOptions<
+  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>,
+  SelectedResult
+>
+
+export type UseQueryStateResult<
+  _ extends QueryDefinition<any, any, any, any>,
+  R,
+> = TSHelpersNoInfer<R>
+
+/**
+ * Helper type to manually type the result
+ * of the `useQueryState` hook in userland code.
+ */
+export type TypedUseQueryStateResult<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  R = UseQueryStateDefaultResult<
+    QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
+  >,
+> = TSHelpersNoInfer<R>
+
+type UseQueryStateBaseResult<D extends QueryDefinition<any, any, any, any>> =
+  QuerySubState<D> & {
+    /**
+     * Where `data` tries to hold data as much as possible, also re-using
+     * data from the last arguments passed into the hook, this property
+     * will always contain the received data from the query, for the current query arguments.
+     */
+    currentData?: ResultTypeFrom<D>
+    /**
+     * Query has not started yet.
+     */
+    isUninitialized: false
+    /**
+     * Query is currently loading for the first time. No data yet.
+     */
+    isLoading: false
+    /**
+     * Query is currently fetching, but might have data from an earlier request.
+     */
+    isFetching: false
+    /**
+     * Query has data from a successful load.
+     */
+    isSuccess: false
+    /**
+     * Query is currently in "error" state.
+     */
+    isError: false
+  }
+
+type UseQueryStateUninitialized<D extends QueryDefinition<any, any, any, any>> =
+  TSHelpersOverride<
+    Extract<UseQueryStateBaseResult<D>, { status: QueryStatus.uninitialized }>,
+    { isUninitialized: true }
+  >
+
+type UseQueryStateLoading<D extends QueryDefinition<any, any, any, any>> =
+  TSHelpersOverride<
+    UseQueryStateBaseResult<D>,
+    { isLoading: true; isFetching: boolean; data: undefined }
+  >
+
+type UseQueryStateSuccessFetching<
+  D extends QueryDefinition<any, any, any, any>,
+> = TSHelpersOverride<
+  UseQueryStateBaseResult<D>,
+  {
+    isSuccess: true
+    isFetching: true
+    error: undefined
+  } & {
+    data: ResultTypeFrom<D>
+  } & Required<Pick<UseQueryStateBaseResult<D>, 'fulfilledTimeStamp'>>
+>
+
+type UseQueryStateSuccessNotFetching<
+  D extends QueryDefinition<any, any, any, any>,
+> = TSHelpersOverride<
+  UseQueryStateBaseResult<D>,
+  {
+    isSuccess: true
+    isFetching: false
+    error: undefined
+  } & {
+    data: ResultTypeFrom<D>
+    currentData: ResultTypeFrom<D>
+  } & Required<Pick<UseQueryStateBaseResult<D>, 'fulfilledTimeStamp'>>
+>
+
+type UseQueryStateError<D extends QueryDefinition<any, any, any, any>> =
+  TSHelpersOverride<
+    UseQueryStateBaseResult<D>,
+    { isError: true } & Required<Pick<UseQueryStateBaseResult<D>, 'error'>>
+  >
+
+type UseQueryStateDefaultResult<D extends QueryDefinition<any, any, any, any>> =
+  TSHelpersId<
+    | UseQueryStateUninitialized<D>
+    | UseQueryStateLoading<D>
+    | UseQueryStateSuccessFetching<D>
+    | UseQueryStateSuccessNotFetching<D>
+    | UseQueryStateError<D>
+  > & {
+    /**
+     * @deprecated Included for completeness, but discouraged.
+     * Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`
+     * and `isUninitialized` flags instead
+     */
+    status: QueryStatus
+  }
+
+export type LazyInfiniteQueryTrigger<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = {
+  /**
+   * Triggers a lazy query.
+   *
+   * By default, this will start a new request even if there is already a value in the cache.
+   * If you want to use the cache value and only start a request if there is no cache value, set the second argument to `true`.
+   *
+   * @remarks
+   * If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta title="Using .unwrap with async await"
+   * try {
+   *   const payload = await getUserById(1).unwrap();
+   *   console.log('fulfilled', payload)
+   * } catch (error) {
+   *   console.error('rejected', error);
+   * }
+   * ```
+   */
+  (
+    arg: QueryArgFrom<D>,
+    direction: InfiniteQueryDirection,
+  ): InfiniteQueryActionCreatorResult<D>
+}
+
+export type TypedLazyInfiniteQueryTrigger<
+  ResultType,
+  QueryArg,
+  PageParam,
+  BaseQuery extends BaseQueryFn,
+> = LazyInfiniteQueryTrigger<
+  InfiniteQueryDefinition<
+    QueryArg,
+    PageParam,
+    BaseQuery,
+    string,
+    ResultType,
+    string
+  >
+>
+
+export type UseInfiniteQuerySubscriptionOptions<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = SubscriptionOptions & {
+  /**
+   * Prevents a query from automatically running.
+   *
+   * @remarks
+   * When `skip` is true (or `skipToken` is passed in as `arg`):
+   *
+   * - **If the query has cached data:**
+   *   * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed
+   *   * The query will have a status of `uninitialized`
+   *   * If `skip: false` is set after the initial load, the cached result will be used
+   * - **If the query does not have cached data:**
+   *   * The query will have a status of `uninitialized`
+   *   * The query will not exist in the state when viewed with the dev tools
+   *   * The query will not automatically fetch on mount
+   *   * The query will not automatically run when additional components with the same query are added that do run
+   *
+   * @example
+   * ```tsx
+   * // codeblock-meta no-transpile title="Skip example"
+   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
+   *   const { data, error, status } = useGetPokemonByNameQuery(name, {
+   *     skip,
+   *   });
+   *
+   *   return (
+   *     <div>
+   *       {name} - {status}
+   *     </div>
+   *   );
+   * };
+   * ```
+   */
+  skip?: boolean
+  /**
+   * Defaults to `false`. This setting allows you to control whether if a cached result is already available, RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.
+   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
+   * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.
+   * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.
+   *
+   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
+   */
+  refetchOnMountOrArgChange?: boolean | number
+  initialPageParam?: PageParamFrom<D>
+  /**
+   * Defaults to `true`. When this is `true` and an infinite query endpoint is refetched
+   * (due to tag invalidation, polling, arg change configuration, or manual refetching),
+   * RTK Query will try to sequentially refetch all pages currently in the cache.
+   * When `false` only the first page will be refetched.
+   *
+   * This option applies to all automatic refetches for this subscription (polling, tag invalidation, etc.).
+   * It can be overridden on a per-call basis using the `refetch()` method.
+   */
+  refetchCachedPages?: boolean
+}
+
+export type TypedUseInfiniteQuerySubscription<
+  ResultType,
+  QueryArg,
+  PageParam,
+  BaseQuery extends BaseQueryFn,
+> = UseInfiniteQuerySubscription<
+  InfiniteQueryDefinition<
+    QueryArg,
+    PageParam,
+    BaseQuery,
+    string,
+    ResultType,
+    string
+  >
+>
+
+export type UseInfiniteQuerySubscriptionResult<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = {
+  refetch: (
+    options?: Pick<
+      UseInfiniteQuerySubscriptionOptions<D>,
+      'refetchCachedPages'
+    >,
+  ) => InfiniteQueryActionCreatorResult<D>
+  trigger: LazyInfiniteQueryTrigger<D>
+  fetchNextPage: () => InfiniteQueryActionCreatorResult<D>
+  fetchPreviousPage: () => InfiniteQueryActionCreatorResult<D>
+}
+
+/**
+ * Helper type to manually type the result
+ * of the `useQuerySubscription` hook in userland code.
+ */
+export type TypedUseInfiniteQuerySubscriptionResult<
+  ResultType,
+  QueryArg,
+  PageParam,
+  BaseQuery extends BaseQueryFn,
+> = UseInfiniteQuerySubscriptionResult<
+  InfiniteQueryDefinition<
+    QueryArg,
+    PageParam,
+    BaseQuery,
+    string,
+    ResultType,
+    string
+  >
+>
+
+export type InfiniteQueryStateSelector<
+  R extends Record<string, any>,
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = (state: UseInfiniteQueryStateDefaultResult<D>) => R
+
+export type TypedInfiniteQueryStateSelector<
+  ResultType,
+  QueryArg,
+  PageParam,
+  BaseQuery extends BaseQueryFn,
+  SelectedResult extends Record<
+    string,
+    any
+  > = UseInfiniteQueryStateDefaultResult<
+    InfiniteQueryDefinition<
+      QueryArg,
+      PageParam,
+      BaseQuery,
+      string,
+      ResultType,
+      string
+    >
+  >,
+> = InfiniteQueryStateSelector<
+  SelectedResult,
+  InfiniteQueryDefinition<
+    QueryArg,
+    PageParam,
+    BaseQuery,
+    string,
+    ResultType,
+    string
+  >
+>
+
+/**
+ * A React hook that automatically triggers fetches of data from an endpoint, 'subscribes' the component to the cached data, and reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.  Additionally, it will cache multiple "pages" worth of responses within a single cache entry, and allows fetching more pages forwards and backwards from the current cached pages.
+ *
+ * The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already, and the hook will return the data for that query arg once it's available.
+ *
+ *  The `data` field will be a `{pages: Data[], pageParams: PageParam[]}` structure containing all fetched page responses and the corresponding page param values for each page. You may use this to render individual pages, combine all pages into a single infinite list, or other display logic as needed.
+ *
+ * This hook combines the functionality of both [`useInfiniteQueryState`](#useinfinitequerystate) and [`useInfiniteQuerySubscription`](#useinfinitequerysubscription) together, and is intended to be used in the majority of situations.
+ *
+ * As with normal query hooks, `skipToken` is a valid argument that will skip the query from executing.
+ *
+ * By default, the initial request will use the `initialPageParam` value that was defined on the infinite query endpoint. If you want to start from a different value, you can pass `initialPageParam` as part of the hook options to override that initial request value.
+ *
+ * Use the returned `fetchNextPage` and `fetchPreviousPage` methods on the hook result object to trigger fetches forwards and backwards. These will always calculate the next or previous page param based on the current cached pages and the provided `getNext/PreviousPageParam` callbacks defined in the endpoint.
+ *
+ *
+ * #### Features
+ *
+ * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
+ * - Caches multiple pages worth of responses, and provides methods to trigger more page fetches forwards and backwards
+ * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
+ * - Returns the latest request status and cached data from the Redux store
+ * - Re-renders as the request status changes and data becomes available
+ */
+export type UseInfiniteQuery<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = <R extends Record<string, any> = UseInfiniteQueryStateDefaultResult<D>>(
+  arg: InfiniteQueryArgFrom<D> | SkipToken,
+  options?: UseInfiniteQuerySubscriptionOptions<D> &
+    UseInfiniteQueryStateOptions<D, R>,
+) => UseInfiniteQueryHookResult<D, R> &
+  Pick<
+    UseInfiniteQuerySubscriptionResult<D>,
+    'fetchNextPage' | 'fetchPreviousPage'
+  >
+
+export type TypedUseInfiniteQuery<
+  ResultType,
+  QueryArg,
+  PageParam,
+  BaseQuery extends BaseQueryFn,
+> = UseInfiniteQuery<
+  InfiniteQueryDefinition<
+    QueryArg,
+    PageParam,
+    BaseQuery,
+    string,
+    ResultType,
+    string
+  >
+>
+
+/**
+ * A React hook that reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.
+ *
+ * Note that this hook does not trigger fetching new data. For that use-case, see [`useInfiniteQuery`](#useinfinitequery) or [`useInfiniteQuerySubscription`](#useinfinitequerysubscription).
+ *
+ * #### Features
+ *
+ * - Returns the latest request status and cached data from the Redux store
+ * - Re-renders as the request status changes and data becomes available
+ */
+export type UseInfiniteQueryState<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = <R extends Record<string, any> = UseInfiniteQueryStateDefaultResult<D>>(
+  arg: InfiniteQueryArgFrom<D> | SkipToken,
+  options?: UseInfiniteQueryStateOptions<D, R>,
+) => UseInfiniteQueryStateResult<D, R>
+
+export type TypedUseInfiniteQueryState<
+  ResultType,
+  QueryArg,
+  PageParam,
+  BaseQuery extends BaseQueryFn,
+> = UseInfiniteQueryState<
+  InfiniteQueryDefinition<
+    QueryArg,
+    PageParam,
+    BaseQuery,
+    string,
+    ResultType,
+    string
+  >
+>
+
+/**
+ * A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data. Additionally, it will cache multiple "pages" worth of responses within a single cache entry, and allows fetching more pages forwards and backwards from the current cached pages.
+ *
+ * The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already.
+ *
+ * Note that this hook does not return a request status or cached data. For that use-case, see [`useInfiniteQuery`](#useinfinitequery) or [`useInfiniteQueryState`](#useinfinitequerystate).
+ *
+ * #### Features
+ *
+ * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
+ * - Caches multiple pages worth of responses, and provides methods to trigger more page fetches forwards and backwards
+ * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
+ */
+export type UseInfiniteQuerySubscription<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = (
+  arg: InfiniteQueryArgFrom<D> | SkipToken,
+  options?: UseInfiniteQuerySubscriptionOptions<D>,
+) => UseInfiniteQuerySubscriptionResult<D>
+
+export type UseInfiniteQueryHookResult<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+  R = UseInfiniteQueryStateDefaultResult<D>,
+> = UseInfiniteQueryStateResult<D, R> &
+  Pick<
+    UseInfiniteQuerySubscriptionResult<D>,
+    'refetch' | 'fetchNextPage' | 'fetchPreviousPage'
+  >
+
+export type TypedUseInfiniteQueryHookResult<
+  ResultType,
+  QueryArg,
+  PageParam,
+  BaseQuery extends BaseQueryFn,
+  R extends Record<string, any> = UseInfiniteQueryStateDefaultResult<
+    InfiniteQueryDefinition<
+      QueryArg,
+      PageParam,
+      BaseQuery,
+      string,
+      ResultType,
+      string
+    >
+  >,
+> = UseInfiniteQueryHookResult<
+  InfiniteQueryDefinition<
+    QueryArg,
+    PageParam,
+    BaseQuery,
+    string,
+    ResultType,
+    string
+  >,
+  R
+>
+
+export type UseInfiniteQueryStateOptions<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+  R extends Record<string, any>,
+> = {
+  /**
+   * Prevents a query from automatically running.
+   *
+   * @remarks
+   * When skip is true:
+   *
+   * - **If the query has cached data:**
+   *   * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed
+   *   * The query will have a status of `uninitialized`
+   *   * If `skip: false` is set after skipping the initial load, the cached result will be used
+   * - **If the query does not have cached data:**
+   *   * The query will have a status of `uninitialized`
+   *   * The query will not exist in the state when viewed with the dev tools
+   *   * The query will not automatically fetch on mount
+   *   * The query will not automatically run when additional components with the same query are added that do run
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta title="Skip example"
+   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
+   *   const { data, error, status } = useGetPokemonByNameQuery(name, {
+   *     skip,
+   *   });
+   *
+   *   return (
+   *     <div>
+   *       {name} - {status}
+   *     </div>
+   *   );
+   * };
+   * ```
+   */
+  skip?: boolean
+  /**
+   * `selectFromResult` allows you to get a specific segment from a query result in a performant manner.
+   * When using this feature, the component will not rerender unless the underlying data of the selected item has changed.
+   * If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.
+   * Note that this should always return an object (not a primitive), as RTKQ adds fields to the return value.
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta title="Using selectFromResult to extract a single result"
+   * function PostsList() {
+   *   const { data: posts } = api.useGetPostsQuery();
+   *
+   *   return (
+   *     <ul>
+   *       {posts?.data?.map((post) => (
+   *         <PostById key={post.id} id={post.id} />
+   *       ))}
+   *     </ul>
+   *   );
+   * }
+   *
+   * function PostById({ id }: { id: number }) {
+   *   // Will select the post with the given id, and will only rerender if the given posts data changes
+   *   const { post } = api.useGetPostsQuery(undefined, {
+   *     selectFromResult: ({ data }) => ({ post: data?.find((post) => post.id === id) }),
+   *   });
+   *
+   *   return <li>{post?.name}</li>;
+   * }
+   * ```
+   */
+  selectFromResult?: InfiniteQueryStateSelector<R, D>
+}
+
+export type TypedUseInfiniteQueryStateOptions<
+  ResultType,
+  QueryArg,
+  PageParam,
+  BaseQuery extends BaseQueryFn,
+  SelectedResult extends Record<
+    string,
+    any
+  > = UseInfiniteQueryStateDefaultResult<
+    InfiniteQueryDefinition<
+      QueryArg,
+      PageParam,
+      BaseQuery,
+      string,
+      ResultType,
+      string
+    >
+  >,
+> = UseInfiniteQueryStateOptions<
+  InfiniteQueryDefinition<
+    QueryArg,
+    PageParam,
+    BaseQuery,
+    string,
+    ResultType,
+    string
+  >,
+  SelectedResult
+>
+
+export type UseInfiniteQueryStateResult<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+  R = UseInfiniteQueryStateDefaultResult<D>,
+> = TSHelpersNoInfer<R>
+
+export type TypedUseInfiniteQueryStateResult<
+  ResultType,
+  QueryArg,
+  PageParam,
+  BaseQuery extends BaseQueryFn,
+  R = UseInfiniteQueryStateDefaultResult<
+    InfiniteQueryDefinition<
+      QueryArg,
+      PageParam,
+      BaseQuery,
+      string,
+      ResultType,
+      string
+    >
+  >,
+> = UseInfiniteQueryStateResult<
+  InfiniteQueryDefinition<
+    QueryArg,
+    PageParam,
+    BaseQuery,
+    string,
+    ResultType,
+    string
+  >,
+  R
+>
+
+type UseInfiniteQueryStateBaseResult<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = InfiniteQuerySubState<D> & {
+  /**
+   * Where `data` tries to hold data as much as possible, also re-using
+   * data from the last arguments passed into the hook, this property
+   * will always contain the received data from the query, for the current query arguments.
+   */
+  currentData?: InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>
+  /**
+   * Query has not started yet.
+   */
+  isUninitialized: false
+  /**
+   * Query is currently loading for the first time. No data yet.
+   */
+  isLoading: false
+  /**
+   * Query is currently fetching, but might have data from an earlier request.
+   */
+  isFetching: false
+  /**
+   * Query has data from a successful load.
+   */
+  isSuccess: false
+  /**
+   * Query is currently in "error" state.
+   */
+  isError: false
+  hasNextPage: boolean
+  hasPreviousPage: boolean
+  isFetchingNextPage: boolean
+  isFetchingPreviousPage: boolean
+}
+
+type UseInfiniteQueryStateDefaultResult<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = TSHelpersId<
+  | TSHelpersOverride<
+      Extract<
+        UseInfiniteQueryStateBaseResult<D>,
+        { status: QueryStatus.uninitialized }
+      >,
+      { isUninitialized: true }
+    >
+  | TSHelpersOverride<
+      UseInfiniteQueryStateBaseResult<D>,
+      | { isLoading: true; isFetching: boolean; data: undefined }
+      | ({
+          isSuccess: true
+          isFetching: true
+          error: undefined
+        } & Required<
+          Pick<
+            UseInfiniteQueryStateBaseResult<D>,
+            'data' | 'fulfilledTimeStamp'
+          >
+        >)
+      | ({
+          isSuccess: true
+          isFetching: false
+          error: undefined
+        } & Required<
+          Pick<
+            UseInfiniteQueryStateBaseResult<D>,
+            'data' | 'fulfilledTimeStamp' | 'currentData'
+          >
+        >)
+      | ({ isError: true } & Required<
+          Pick<UseInfiniteQueryStateBaseResult<D>, 'error'>
+        >)
+    >
+> & {
+  /**
+   * @deprecated Included for completeness, but discouraged.
+   * Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`
+   * and `isUninitialized` flags instead
+   */
+  status: QueryStatus
+}
+
+export type MutationStateSelector<
+  R extends Record<string, any>,
+  D extends MutationDefinition<any, any, any, any>,
+> = (state: MutationResultSelectorResult<D>) => R
+
+export type UseMutationStateOptions<
+  D extends MutationDefinition<any, any, any, any>,
+  R extends Record<string, any>,
+> = {
+  selectFromResult?: MutationStateSelector<R, D>
+  fixedCacheKey?: string
+}
+
+export type UseMutationStateResult<
+  D extends MutationDefinition<any, any, any, any>,
+  R,
+> = TSHelpersNoInfer<R> & {
+  originalArgs?: QueryArgFrom<D>
+  /**
+   * Resets the hook state to its initial `uninitialized` state.
+   * This will also remove the last result from the cache.
+   */
+  reset: () => void
+}
+
+/**
+ * Helper type to manually type the result
+ * of the `useMutation` hook in userland code.
+ */
+export type TypedUseMutationResult<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  R = MutationResultSelectorResult<
+    MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>
+  >,
+> = UseMutationStateResult<
+  MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>,
+  R
+>
+
+/**
+ * A React hook that lets you trigger an update request for a given endpoint, and subscribes the component to read the request status from the Redux store. The component will re-render as the loading status changes.
+ *
+ * #### Features
+ *
+ * - Manual control over firing a request to alter data on the server or possibly invalidate the cache
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
+ * - Returns the latest request status and cached data from the Redux store
+ * - Re-renders as the request status changes and data becomes available
+ */
+export type UseMutation<D extends MutationDefinition<any, any, any, any>> = <
+  R extends Record<string, any> = MutationResultSelectorResult<D>,
+>(
+  options?: UseMutationStateOptions<D, R>,
+) => readonly [MutationTrigger<D>, UseMutationStateResult<D, R>]
+
+export type TypedUseMutation<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+> = UseMutation<
+  MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>
+>
+
+export type MutationTrigger<D extends MutationDefinition<any, any, any, any>> =
+  {
+    /**
+     * Triggers the mutation and returns a Promise.
+     * @remarks
+     * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().
+     *
+     * @example
+     * ```ts
+     * // codeblock-meta title="Using .unwrap with async await"
+     * try {
+     *   const payload = await addPost({ id: 1, name: 'Example' }).unwrap();
+     *   console.log('fulfilled', payload)
+     * } catch (error) {
+     *   console.error('rejected', error);
+     * }
+     * ```
+     */
+    (arg: QueryArgFrom<D>): MutationActionCreatorResult<D>
+  }
+
+export type TypedMutationTrigger<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+> = MutationTrigger<
+  MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>
+>
+
+/**
+ * Wrapper around `defaultQueryStateSelector` to be used in `useQuery`.
+ * We want the initial render to already come back with
+ * `{ isUninitialized: false, isFetching: true, isLoading: true }`
+ * to prevent that the library user has to do an additional check for `isUninitialized`/
+ */
+const noPendingQueryStateSelector: QueryStateSelector<any, any> = (
+  selected,
+) => {
+  if (selected.isUninitialized) {
+    return {
+      ...selected,
+      isUninitialized: false,
+      isFetching: true,
+      isLoading: selected.data !== undefined ? false : true,
+      // This is the one place where we still have to use `QueryStatus` as an enum,
+      // since it's the only reference in the React package and not in the core.
+      status: QueryStatus.pending,
+    } as any
+  }
+  return selected
+}
+
+function pick<T, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K> {
+  const ret: any = {}
+  keys.forEach((key) => {
+    ret[key] = obj[key]
+  })
+  return ret
+}
+
+const COMMON_HOOK_DEBUG_FIELDS = [
+  'data',
+  'status',
+  'isLoading',
+  'isSuccess',
+  'isError',
+  'error',
+] as const
+
+type GenericPrefetchThunk = (
+  endpointName: any,
+  arg: any,
+  options: PrefetchOptions,
+) => ThunkAction<void, any, any, UnknownAction>
+
+/**
+ *
+ * @param opts.api - An API with defined endpoints to create hooks for
+ * @param opts.moduleOptions.batch - The version of the `batchedUpdates` function to be used
+ * @param opts.moduleOptions.useDispatch - The version of the `useDispatch` hook to be used
+ * @param opts.moduleOptions.useSelector - The version of the `useSelector` hook to be used
+ * @returns An object containing functions to generate hooks based on an endpoint
+ */
+export function buildHooks<Definitions extends EndpointDefinitions>({
+  api,
+  moduleOptions: {
+    batch,
+    hooks: { useDispatch, useSelector, useStore },
+    unstable__sideEffectsInRender,
+    createSelector,
+  },
+  serializeQueryArgs,
+  context,
+}: {
+  api: Api<any, Definitions, any, any, CoreModule>
+  moduleOptions: Required<ReactHooksModuleOptions>
+  serializeQueryArgs: SerializeQueryArgs<any>
+  context: ApiContext<Definitions>
+}) {
+  const usePossiblyImmediateEffect: (
+    effect: () => void | undefined,
+    deps?: DependencyList,
+  ) => void = unstable__sideEffectsInRender ? (cb) => cb() : useEffect
+
+  type UnsubscribePromiseRef = React.RefObject<
+    { unsubscribe?: () => void } | undefined
+  >
+
+  const unsubscribePromiseRef = (ref: UnsubscribePromiseRef) =>
+    ref.current?.unsubscribe?.()
+
+  const endpointDefinitions = context.endpointDefinitions
+
+  return {
+    buildQueryHooks,
+    buildInfiniteQueryHooks,
+    buildMutationHook,
+    usePrefetch,
+  }
+
+  function queryStatePreSelector(
+    currentState: QueryResultSelectorResult<any>,
+    lastResult: UseQueryStateDefaultResult<any> | undefined,
+    queryArgs: any,
+  ): UseQueryStateDefaultResult<any> {
+    // if we had a last result and the current result is uninitialized,
+    // we might have called `api.util.resetApiState`
+    // in this case, reset the hook
+    if (lastResult?.endpointName && currentState.isUninitialized) {
+      const { endpointName } = lastResult
+      const endpointDefinition = endpointDefinitions[endpointName]
+      if (
+        queryArgs !== skipToken &&
+        serializeQueryArgs({
+          queryArgs: lastResult.originalArgs,
+          endpointDefinition,
+          endpointName,
+        }) ===
+          serializeQueryArgs({
+            queryArgs,
+            endpointDefinition,
+            endpointName,
+          })
+      )
+        lastResult = undefined
+    }
+
+    // data is the last known good request result we have tracked - or if none has been tracked yet the last good result for the current args
+    let data = currentState.isSuccess ? currentState.data : lastResult?.data
+    if (data === undefined) data = currentState.data
+
+    const hasData = data !== undefined
+
+    // isFetching = true any time a request is in flight
+    const isFetching = currentState.isLoading
+
+    // isLoading = true only when loading while no data is present yet (initial load with no data in the cache)
+    const isLoading =
+      (!lastResult || lastResult.isLoading || lastResult.isUninitialized) &&
+      !hasData &&
+      isFetching
+
+    // isSuccess = true when data is present and we're not refetching after an error.
+    // That includes cases where the _current_ item is either actively
+    // fetching or about to fetch due to an uninitialized entry.
+    const isSuccess =
+      currentState.isSuccess ||
+      (hasData &&
+        ((isFetching && !lastResult?.isError) || currentState.isUninitialized))
+
+    return {
+      ...currentState,
+      data,
+      currentData: currentState.data,
+      isFetching,
+      isLoading,
+      isSuccess,
+    } as UseQueryStateDefaultResult<any>
+  }
+
+  function infiniteQueryStatePreSelector(
+    currentState: InfiniteQueryResultSelectorResult<any>,
+    lastResult: UseInfiniteQueryStateDefaultResult<any> | undefined,
+    queryArgs: any,
+  ): UseInfiniteQueryStateDefaultResult<any> {
+    // if we had a last result and the current result is uninitialized,
+    // we might have called `api.util.resetApiState`
+    // in this case, reset the hook
+    if (lastResult?.endpointName && currentState.isUninitialized) {
+      const { endpointName } = lastResult
+      const endpointDefinition = endpointDefinitions[endpointName]
+      if (
+        queryArgs !== skipToken &&
+        serializeQueryArgs({
+          queryArgs: lastResult.originalArgs,
+          endpointDefinition,
+          endpointName,
+        }) ===
+          serializeQueryArgs({
+            queryArgs,
+            endpointDefinition,
+            endpointName,
+          })
+      )
+        lastResult = undefined
+    }
+
+    // data is the last known good request result we have tracked - or if none has been tracked yet the last good result for the current args
+    let data = currentState.isSuccess ? currentState.data : lastResult?.data
+    if (data === undefined) data = currentState.data
+
+    const hasData = data !== undefined
+
+    // isFetching = true any time a request is in flight
+    const isFetching = currentState.isLoading
+    // isLoading = true only when loading while no data is present yet (initial load with no data in the cache)
+    const isLoading =
+      (!lastResult || lastResult.isLoading || lastResult.isUninitialized) &&
+      !hasData &&
+      isFetching
+    // isSuccess = true when data is present
+    const isSuccess = currentState.isSuccess || (isFetching && hasData)
+
+    return {
+      ...currentState,
+      data,
+      currentData: currentState.data,
+      isFetching,
+      isLoading,
+      isSuccess,
+    } as UseInfiniteQueryStateDefaultResult<any>
+  }
+
+  function usePrefetch<EndpointName extends QueryKeys<Definitions>>(
+    endpointName: EndpointName,
+    defaultOptions?: PrefetchOptions,
+  ) {
+    const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>()
+    const stableDefaultOptions = useShallowStableValue(defaultOptions)
+
+    return useCallback(
+      (arg: any, options?: PrefetchOptions) =>
+        dispatch(
+          (api.util.prefetch as GenericPrefetchThunk)(endpointName, arg, {
+            ...stableDefaultOptions,
+            ...options,
+          }),
+        ),
+      [endpointName, dispatch, stableDefaultOptions],
+    )
+  }
+
+  function useQuerySubscriptionCommonImpl<
+    T extends
+      | QueryActionCreatorResult<any>
+      | InfiniteQueryActionCreatorResult<any>,
+  >(
+    endpointName: string,
+    arg: unknown | SkipToken,
+    {
+      refetchOnReconnect,
+      refetchOnFocus,
+      refetchOnMountOrArgChange,
+      skip = false,
+      pollingInterval = 0,
+      skipPollingIfUnfocused = false,
+      ...rest
+    }: UseQuerySubscriptionOptions = {},
+  ) {
+    const { initiate } = api.endpoints[endpointName] as ApiEndpointQuery<
+      QueryDefinition<any, any, any, any, any>,
+      Definitions
+    >
+    const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>()
+
+    // TODO: Change this to `useRef<SubscriptionSelectors>(undefined)` after upgrading to React 19.
+    const subscriptionSelectorsRef = useRef<SubscriptionSelectors | undefined>(
+      undefined,
+    )
+
+    if (!subscriptionSelectorsRef.current) {
+      const returnedValue = dispatch(
+        api.internalActions.internal_getRTKQSubscriptions(),
+      )
+
+      if (process.env.NODE_ENV !== 'production') {
+        if (
+          typeof returnedValue !== 'object' ||
+          typeof returnedValue?.type === 'string'
+        ) {
+          throw new Error(
+            `Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
+    You must add the middleware for RTK-Query to function correctly!`,
+          )
+        }
+      }
+
+      subscriptionSelectorsRef.current =
+        returnedValue as unknown as SubscriptionSelectors
+    }
+    const stableArg = useStableQueryArgs(skip ? skipToken : arg)
+    const stableSubscriptionOptions = useShallowStableValue({
+      refetchOnReconnect,
+      refetchOnFocus,
+      pollingInterval,
+      skipPollingIfUnfocused,
+    })
+
+    const initialPageParam = (rest as UseInfiniteQuerySubscriptionOptions<any>)
+      .initialPageParam
+    const stableInitialPageParam = useShallowStableValue(initialPageParam)
+
+    const refetchCachedPages = (
+      rest as UseInfiniteQuerySubscriptionOptions<any>
+    ).refetchCachedPages
+    const stableRefetchCachedPages = useShallowStableValue(refetchCachedPages)
+
+    /**
+     * @todo Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.
+     */
+    const promiseRef = useRef<T | undefined>(undefined)
+
+    let { queryCacheKey, requestId } = promiseRef.current || {}
+
+    // HACK We've saved the middleware subscription lookup callbacks into a ref,
+    // so we can directly check here if the subscription exists for this query.
+    let currentRenderHasSubscription = false
+    if (queryCacheKey && requestId) {
+      currentRenderHasSubscription =
+        subscriptionSelectorsRef.current.isRequestSubscribed(
+          queryCacheKey,
+          requestId,
+        )
+    }
+
+    const subscriptionRemoved =
+      !currentRenderHasSubscription && promiseRef.current !== undefined
+
+    usePossiblyImmediateEffect((): void | undefined => {
+      if (subscriptionRemoved) {
+        promiseRef.current = undefined
+      }
+    }, [subscriptionRemoved])
+
+    usePossiblyImmediateEffect((): void | undefined => {
+      const lastPromise = promiseRef.current
+      if (
+        typeof process !== 'undefined' &&
+        process.env.NODE_ENV === 'removeMeOnCompilation'
+      ) {
+        // this is only present to enforce the rule of hooks to keep `isSubscribed` in the dependency array
+        console.log(subscriptionRemoved)
+      }
+
+      if (stableArg === skipToken) {
+        lastPromise?.unsubscribe()
+        promiseRef.current = undefined
+        return
+      }
+
+      const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions
+
+      if (!lastPromise || lastPromise.arg !== stableArg) {
+        lastPromise?.unsubscribe()
+        const promise = dispatch(
+          initiate(stableArg, {
+            subscriptionOptions: stableSubscriptionOptions,
+            forceRefetch: refetchOnMountOrArgChange,
+            ...(isInfiniteQueryDefinition(endpointDefinitions[endpointName])
+              ? {
+                  initialPageParam: stableInitialPageParam,
+                  refetchCachedPages: stableRefetchCachedPages,
+                }
+              : {}),
+          }),
+        )
+
+        promiseRef.current = promise as T
+      } else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
+        lastPromise.updateSubscriptionOptions(stableSubscriptionOptions)
+      }
+    }, [
+      dispatch,
+      initiate,
+      refetchOnMountOrArgChange,
+      stableArg,
+      stableSubscriptionOptions,
+      subscriptionRemoved,
+      stableInitialPageParam,
+      stableRefetchCachedPages,
+      endpointName,
+    ])
+
+    return [promiseRef, dispatch, initiate, stableSubscriptionOptions] as const
+  }
+
+  function buildUseQueryState(
+    endpointName: string,
+    preSelector:
+      | typeof queryStatePreSelector
+      | typeof infiniteQueryStatePreSelector,
+  ) {
+    const useQueryState = (
+      arg: any,
+      {
+        skip = false,
+        selectFromResult,
+      }:
+        | UseQueryStateOptions<any, any>
+        | UseInfiniteQueryStateOptions<any, any> = {},
+    ) => {
+      const { select } = api.endpoints[endpointName] as ApiEndpointQuery<
+        QueryDefinition<any, any, any, any, any>,
+        Definitions
+      >
+      const stableArg = useStableQueryArgs(skip ? skipToken : arg)
+
+      type ApiRootState = Parameters<ReturnType<typeof select>>[0]
+
+      const lastValue = useRef<any>(undefined)
+
+      const selectDefaultResult: Selector<ApiRootState, any, [any]> = useMemo(
+        () =>
+          // Normally ts-ignores are bad and should be avoided, but we're
+          // already casting this selector to be `Selector<any>` anyway,
+          // so the inconsistencies don't matter here
+          // @ts-ignore
+          createSelector(
+            [
+              // @ts-ignore
+              select(stableArg),
+              (_: ApiRootState, lastResult: any) => lastResult,
+              (_: ApiRootState) => stableArg,
+            ],
+            preSelector,
+            {
+              memoizeOptions: {
+                resultEqualityCheck: shallowEqual,
+              },
+            },
+          ),
+        [select, stableArg],
+      )
+
+      const querySelector: Selector<ApiRootState, any, [any]> = useMemo(
+        () =>
+          selectFromResult
+            ? createSelector([selectDefaultResult], selectFromResult, {
+                devModeChecks: { identityFunctionCheck: 'never' },
+              })
+            : selectDefaultResult,
+        [selectDefaultResult, selectFromResult],
+      )
+
+      const currentState = useSelector(
+        (state: RootState<Definitions, any, any>) =>
+          querySelector(state, lastValue.current),
+        shallowEqual,
+      )
+
+      const store = useStore<RootState<Definitions, any, any>>()
+      const newLastValue = selectDefaultResult(
+        store.getState(),
+        lastValue.current,
+      )
+      useIsomorphicLayoutEffect(() => {
+        lastValue.current = newLastValue
+      }, [newLastValue])
+
+      return currentState
+    }
+
+    return useQueryState
+  }
+
+  function usePromiseRefUnsubscribeOnUnmount(
+    promiseRef: UnsubscribePromiseRef,
+  ) {
+    useEffect(() => {
+      return () => {
+        unsubscribePromiseRef(promiseRef)
+        // eslint-disable-next-line react-hooks/exhaustive-deps
+        ;(promiseRef.current as any) = undefined
+      }
+    }, [promiseRef])
+  }
+
+  function refetchOrErrorIfUnmounted<
+    T extends
+      | QueryActionCreatorResult<any>
+      | InfiniteQueryActionCreatorResult<any>,
+  >(promiseRef: React.RefObject<T | undefined>): T {
+    if (!promiseRef.current)
+      throw new Error('Cannot refetch a query that has not been started yet.')
+    return promiseRef.current.refetch() as T
+  }
+
+  function buildQueryHooks(endpointName: string): QueryHooks<any> {
+    const useQuerySubscription: UseQuerySubscription<any> = (
+      arg: any,
+      options = {},
+    ) => {
+      const [promiseRef] = useQuerySubscriptionCommonImpl<
+        QueryActionCreatorResult<any>
+      >(endpointName, arg, options)
+
+      usePromiseRefUnsubscribeOnUnmount(promiseRef)
+
+      return useMemo(
+        () => ({
+          /**
+           * A method to manually refetch data for the query
+           */
+          refetch: () => refetchOrErrorIfUnmounted(promiseRef),
+        }),
+        [promiseRef],
+      )
+    }
+
+    const useLazyQuerySubscription: UseLazyQuerySubscription<any> = ({
+      refetchOnReconnect,
+      refetchOnFocus,
+      pollingInterval = 0,
+      skipPollingIfUnfocused = false,
+    } = {}) => {
+      const { initiate } = api.endpoints[endpointName] as ApiEndpointQuery<
+        QueryDefinition<any, any, any, any, any>,
+        Definitions
+      >
+      const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>()
+
+      const [arg, setArg] = useState<any>(UNINITIALIZED_VALUE)
+
+      // TODO: Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.
+      /**
+       * @todo Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.
+       */
+      const promiseRef = useRef<QueryActionCreatorResult<any> | undefined>(
+        undefined,
+      )
+
+      const stableSubscriptionOptions = useShallowStableValue({
+        refetchOnReconnect,
+        refetchOnFocus,
+        pollingInterval,
+        skipPollingIfUnfocused,
+      })
+
+      usePossiblyImmediateEffect(() => {
+        const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions
+
+        if (stableSubscriptionOptions !== lastSubscriptionOptions) {
+          promiseRef.current?.updateSubscriptionOptions(
+            stableSubscriptionOptions,
+          )
+        }
+      }, [stableSubscriptionOptions])
+
+      const subscriptionOptionsRef = useRef(stableSubscriptionOptions)
+      usePossiblyImmediateEffect(() => {
+        subscriptionOptionsRef.current = stableSubscriptionOptions
+      }, [stableSubscriptionOptions])
+
+      const trigger = useCallback(
+        function (arg: any, preferCacheValue = false) {
+          let promise: QueryActionCreatorResult<any>
+
+          batch(() => {
+            unsubscribePromiseRef(promiseRef)
+
+            promiseRef.current = promise = dispatch(
+              initiate(arg, {
+                subscriptionOptions: subscriptionOptionsRef.current,
+                forceRefetch: !preferCacheValue,
+              }),
+            )
+
+            setArg(arg)
+          })
+
+          return promise!
+        },
+        [dispatch, initiate],
+      )
+
+      const reset = useCallback(() => {
+        if (promiseRef.current?.queryCacheKey) {
+          dispatch(
+            api.internalActions.removeQueryResult({
+              queryCacheKey: promiseRef.current?.queryCacheKey as QueryCacheKey,
+            }),
+          )
+        }
+      }, [dispatch])
+
+      /* cleanup on unmount */
+      useEffect(() => {
+        return () => {
+          unsubscribePromiseRef(promiseRef)
+        }
+      }, [])
+
+      /* if "cleanup on unmount" was triggered from a fast refresh, we want to reinstate the query */
+      useEffect(() => {
+        if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
+          trigger(arg, true)
+        }
+      }, [arg, trigger])
+
+      return useMemo(
+        () => [trigger, arg, { reset }] as const,
+        [trigger, arg, reset],
+      )
+    }
+
+    const useQueryState: UseQueryState<any> = buildUseQueryState(
+      endpointName,
+      queryStatePreSelector,
+    )
+
+    return {
+      useQueryState,
+      useQuerySubscription,
+      useLazyQuerySubscription,
+      useLazyQuery(options) {
+        const [trigger, arg, { reset }] = useLazyQuerySubscription(options)
+        const queryStateResults = useQueryState(arg, {
+          ...options,
+          skip: arg === UNINITIALIZED_VALUE,
+        })
+
+        const info = useMemo(() => ({ lastArg: arg }), [arg])
+        return useMemo(
+          () => [trigger, { ...queryStateResults, reset }, info],
+          [trigger, queryStateResults, reset, info],
+        )
+      },
+      useQuery(arg, options) {
+        const querySubscriptionResults = useQuerySubscription(arg, options)
+        const queryStateResults = useQueryState(arg, {
+          selectFromResult:
+            arg === skipToken || options?.skip
+              ? undefined
+              : noPendingQueryStateSelector,
+          ...options,
+        })
+
+        const debugValue = pick(queryStateResults, ...COMMON_HOOK_DEBUG_FIELDS)
+        useDebugValue(debugValue)
+
+        return useMemo(
+          () => ({ ...queryStateResults, ...querySubscriptionResults }),
+          [queryStateResults, querySubscriptionResults],
+        )
+      },
+    }
+  }
+
+  function buildInfiniteQueryHooks(
+    endpointName: string,
+  ): InfiniteQueryHooks<any> {
+    const useInfiniteQuerySubscription: UseInfiniteQuerySubscription<any> = (
+      arg: any,
+      options = {},
+    ) => {
+      const [promiseRef, dispatch, initiate, stableSubscriptionOptions] =
+        useQuerySubscriptionCommonImpl<InfiniteQueryActionCreatorResult<any>>(
+          endpointName,
+          arg,
+          options,
+        )
+
+      const subscriptionOptionsRef = useRef(stableSubscriptionOptions)
+      usePossiblyImmediateEffect(() => {
+        subscriptionOptionsRef.current = stableSubscriptionOptions
+      }, [stableSubscriptionOptions])
+
+      // Extract and stabilize the hook-level refetchCachedPages option
+      const hookRefetchCachedPages = (
+        options as UseInfiniteQuerySubscriptionOptions<any>
+      ).refetchCachedPages
+      const stableHookRefetchCachedPages = useShallowStableValue(
+        hookRefetchCachedPages,
+      )
+
+      const trigger: LazyInfiniteQueryTrigger<any> = useCallback(
+        function (arg: unknown, direction: 'forward' | 'backward') {
+          let promise: InfiniteQueryActionCreatorResult<any>
+
+          batch(() => {
+            unsubscribePromiseRef(promiseRef)
+
+            promiseRef.current = promise = dispatch(
+              (initiate as StartInfiniteQueryActionCreator<any>)(arg, {
+                subscriptionOptions: subscriptionOptionsRef.current,
+                direction,
+              }),
+            )
+          })
+
+          return promise!
+        },
+        [promiseRef, dispatch, initiate],
+      )
+
+      usePromiseRefUnsubscribeOnUnmount(promiseRef)
+
+      const stableArg = useStableQueryArgs(options.skip ? skipToken : arg)
+
+      const refetch = useCallback(
+        (
+          options?: Pick<
+            UseInfiniteQuerySubscriptionOptions<any>,
+            'refetchCachedPages'
+          >,
+        ) => {
+          if (!promiseRef.current)
+            throw new Error(
+              'Cannot refetch a query that has not been started yet.',
+            )
+          // Merge per-call options with hook-level default
+          const mergedOptions = {
+            refetchCachedPages:
+              options?.refetchCachedPages ?? stableHookRefetchCachedPages,
+          }
+          return promiseRef.current.refetch(mergedOptions)
+        },
+        [promiseRef, stableHookRefetchCachedPages],
+      )
+
+      return useMemo(() => {
+        const fetchNextPage = () => {
+          return trigger(stableArg, 'forward')
+        }
+
+        const fetchPreviousPage = () => {
+          return trigger(stableArg, 'backward')
+        }
+
+        return {
+          trigger,
+          /**
+           * A method to manually refetch data for the query
+           */
+          refetch,
+          fetchNextPage,
+          fetchPreviousPage,
+        }
+      }, [refetch, trigger, stableArg])
+    }
+
+    const useInfiniteQueryState: UseInfiniteQueryState<any> =
+      buildUseQueryState(endpointName, infiniteQueryStatePreSelector)
+
+    return {
+      useInfiniteQueryState,
+      useInfiniteQuerySubscription,
+      useInfiniteQuery(arg, options) {
+        const { refetch, fetchNextPage, fetchPreviousPage } =
+          useInfiniteQuerySubscription(arg, options)
+        const queryStateResults = useInfiniteQueryState(arg, {
+          selectFromResult:
+            arg === skipToken || options?.skip
+              ? undefined
+              : noPendingQueryStateSelector,
+          ...options,
+        })
+
+        const debugValue = pick(
+          queryStateResults,
+          ...COMMON_HOOK_DEBUG_FIELDS,
+          'hasNextPage',
+          'hasPreviousPage',
+        )
+        useDebugValue(debugValue)
+
+        return useMemo(
+          () => ({
+            ...queryStateResults,
+            fetchNextPage,
+            fetchPreviousPage,
+            refetch,
+          }),
+          [queryStateResults, fetchNextPage, fetchPreviousPage, refetch],
+        )
+      },
+    }
+  }
+
+  function buildMutationHook(name: string): UseMutation<any> {
+    return ({ selectFromResult, fixedCacheKey } = {}) => {
+      const { select, initiate } = api.endpoints[name] as ApiEndpointMutation<
+        MutationDefinition<any, any, any, any, any>,
+        Definitions
+      >
+      const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>()
+      const [promise, setPromise] = useState<MutationActionCreatorResult<any>>()
+
+      useEffect(
+        () => () => {
+          if (!promise?.arg.fixedCacheKey) {
+            promise?.reset()
+          }
+        },
+        [promise],
+      )
+
+      const triggerMutation = useCallback(
+        function (arg: Parameters<typeof initiate>['0']) {
+          const promise = dispatch(initiate(arg, { fixedCacheKey }))
+          setPromise(promise)
+          return promise
+        },
+        [dispatch, initiate, fixedCacheKey],
+      )
+
+      const { requestId } = promise || {}
+      const selectDefaultResult = useMemo(
+        () => select({ fixedCacheKey, requestId: promise?.requestId }),
+        [fixedCacheKey, promise, select],
+      )
+      const mutationSelector = useMemo(
+        (): Selector<RootState<Definitions, any, any>, any> =>
+          selectFromResult
+            ? createSelector([selectDefaultResult], selectFromResult)
+            : selectDefaultResult,
+        [selectFromResult, selectDefaultResult],
+      )
+
+      const currentState = useSelector(mutationSelector, shallowEqual)
+      const originalArgs =
+        fixedCacheKey == null ? promise?.arg.originalArgs : undefined
+      const reset = useCallback(() => {
+        batch(() => {
+          if (promise) {
+            setPromise(undefined)
+          }
+          if (fixedCacheKey) {
+            dispatch(
+              api.internalActions.removeMutationResult({
+                requestId,
+                fixedCacheKey,
+              }),
+            )
+          }
+        })
+      }, [dispatch, fixedCacheKey, promise, requestId])
+
+      const debugValue = pick(
+        currentState,
+        ...COMMON_HOOK_DEBUG_FIELDS,
+        'endpointName',
+      )
+      useDebugValue(debugValue)
+
+      const finalState = useMemo(
+        () => ({ ...currentState, originalArgs, reset }),
+        [currentState, originalArgs, reset],
+      )
+
+      return useMemo(
+        () => [triggerMutation, finalState] as const,
+        [triggerMutation, finalState],
+      )
+    }
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/query/react/constants.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/react/constants.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/react/constants.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,2 @@
+export const UNINITIALIZED_VALUE = Symbol()
+export type UninitializedValue = typeof UNINITIALIZED_VALUE
Index: node_modules/@reduxjs/toolkit/src/query/react/index.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/react/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/react/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,43 @@
+// This must remain here so that the `mangleErrors.cjs` build script
+// does not have to import this into each source file it rewrites.
+import { formatProdErrorMessage } from '@reduxjs/toolkit'
+
+import { buildCreateApi, coreModule } from './rtkqImports'
+import { reactHooksModule, reactHooksModuleName } from './module'
+
+export * from '@reduxjs/toolkit/query'
+export { ApiProvider } from './ApiProvider'
+
+const createApi = /* @__PURE__ */ buildCreateApi(
+  coreModule(),
+  reactHooksModule(),
+)
+
+export type {
+  TypedUseMutationResult,
+  TypedUseQueryHookResult,
+  TypedUseQueryStateResult,
+  TypedUseQuerySubscriptionResult,
+  TypedLazyQueryTrigger,
+  TypedUseLazyQuery,
+  TypedUseMutation,
+  TypedMutationTrigger,
+  TypedQueryStateSelector,
+  TypedUseQueryState,
+  TypedUseQuery,
+  TypedUseQuerySubscription,
+  TypedUseLazyQuerySubscription,
+  TypedUseQueryStateOptions,
+  TypedUseLazyQueryStateResult,
+  TypedUseInfiniteQuery,
+  TypedUseInfiniteQueryHookResult,
+  TypedUseInfiniteQueryStateResult,
+  TypedUseInfiniteQuerySubscriptionResult,
+  TypedUseInfiniteQueryStateOptions,
+  TypedInfiniteQueryStateSelector,
+  TypedUseInfiniteQuerySubscription,
+  TypedUseInfiniteQueryState,
+  TypedLazyInfiniteQueryTrigger,
+} from './buildHooks'
+export { UNINITIALIZED_VALUE } from './constants'
+export { createApi, reactHooksModule, reactHooksModuleName }
Index: node_modules/@reduxjs/toolkit/src/query/react/module.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/react/module.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/react/module.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,275 @@
+import type {
+  Api,
+  BaseQueryFn,
+  EndpointDefinitions,
+  InfiniteQueryDefinition,
+  Module,
+  MutationDefinition,
+  PrefetchOptions,
+  QueryArgFrom,
+  QueryDefinition,
+  QueryKeys,
+} from '@reduxjs/toolkit/query'
+import {
+  batch as rrBatch,
+  useDispatch as rrUseDispatch,
+  useSelector as rrUseSelector,
+  useStore as rrUseStore,
+} from 'react-redux'
+import type { CreateSelectorFunction } from 'reselect'
+import { createSelector as _createSelector } from 'reselect'
+import {
+  isInfiniteQueryDefinition,
+  isMutationDefinition,
+  isQueryDefinition,
+} from '../endpointDefinitions'
+import { safeAssign } from '../tsHelpers'
+import { capitalize, countObjectKeys } from '../utils'
+import type {
+  InfiniteQueryHooks,
+  MutationHooks,
+  QueryHooks,
+} from './buildHooks'
+import { buildHooks } from './buildHooks'
+import type { HooksWithUniqueNames } from './namedHooks'
+
+export const reactHooksModuleName = /* @__PURE__ */ Symbol()
+export type ReactHooksModule = typeof reactHooksModuleName
+
+declare module '@reduxjs/toolkit/query' {
+  export interface ApiModules<
+    // eslint-disable-next-line @typescript-eslint/no-unused-vars
+    BaseQuery extends BaseQueryFn,
+    Definitions extends EndpointDefinitions,
+    // eslint-disable-next-line @typescript-eslint/no-unused-vars
+    ReducerPath extends string,
+    // eslint-disable-next-line @typescript-eslint/no-unused-vars
+    TagTypes extends string,
+  > {
+    [reactHooksModuleName]: {
+      /**
+       *  Endpoints based on the input endpoints provided to `createApi`, containing `select`, `hooks` and `action matchers`.
+       */
+      endpoints: {
+        [K in keyof Definitions]: Definitions[K] extends QueryDefinition<
+          any,
+          any,
+          any,
+          any,
+          any
+        >
+          ? QueryHooks<Definitions[K]>
+          : Definitions[K] extends MutationDefinition<any, any, any, any, any>
+            ? MutationHooks<Definitions[K]>
+            : Definitions[K] extends InfiniteQueryDefinition<
+                  any,
+                  any,
+                  any,
+                  any,
+                  any
+                >
+              ? InfiniteQueryHooks<Definitions[K]>
+              : never
+      }
+      /**
+       * A hook that accepts a string endpoint name, and provides a callback that when called, pre-fetches the data for that endpoint.
+       */
+      usePrefetch<EndpointName extends QueryKeys<Definitions>>(
+        endpointName: EndpointName,
+        options?: PrefetchOptions,
+      ): (
+        arg: QueryArgFrom<Definitions[EndpointName]>,
+        options?: PrefetchOptions,
+      ) => void
+    } & HooksWithUniqueNames<Definitions>
+  }
+}
+
+type RR = typeof import('react-redux')
+
+export interface ReactHooksModuleOptions {
+  /**
+   * The hooks from React Redux to be used
+   */
+  hooks?: {
+    /**
+     * The version of the `useDispatch` hook to be used
+     */
+    useDispatch: RR['useDispatch']
+    /**
+     * The version of the `useSelector` hook to be used
+     */
+    useSelector: RR['useSelector']
+    /**
+     * The version of the `useStore` hook to be used
+     */
+    useStore: RR['useStore']
+  }
+  /**
+   * The version of the `batchedUpdates` function to be used
+   */
+  batch?: RR['batch']
+  /**
+   * Enables performing asynchronous tasks immediately within a render.
+   *
+   * @example
+   *
+   * ```ts
+   * import {
+   *   buildCreateApi,
+   *   coreModule,
+   *   reactHooksModule
+   * } from '@reduxjs/toolkit/query/react'
+   *
+   * const createApi = buildCreateApi(
+   *   coreModule(),
+   *   reactHooksModule({ unstable__sideEffectsInRender: true })
+   * )
+   * ```
+   */
+  unstable__sideEffectsInRender?: boolean
+  /**
+   * A selector creator (usually from `reselect`, or matching the same signature)
+   */
+  createSelector?: CreateSelectorFunction<any, any, any>
+}
+
+/**
+ * Creates a module that generates react hooks from endpoints, for use with `buildCreateApi`.
+ *
+ *  @example
+ * ```ts
+ * const MyContext = React.createContext<ReactReduxContextValue | null>(null);
+ * const customCreateApi = buildCreateApi(
+ *   coreModule(),
+ *   reactHooksModule({
+ *     hooks: {
+ *       useDispatch: createDispatchHook(MyContext),
+ *       useSelector: createSelectorHook(MyContext),
+ *       useStore: createStoreHook(MyContext)
+ *     }
+ *   })
+ * );
+ * ```
+ *
+ * @returns A module for use with `buildCreateApi`
+ */
+export const reactHooksModule = ({
+  batch = rrBatch,
+  hooks = {
+    useDispatch: rrUseDispatch,
+    useSelector: rrUseSelector,
+    useStore: rrUseStore,
+  },
+  createSelector = _createSelector,
+  unstable__sideEffectsInRender = false,
+  ...rest
+}: ReactHooksModuleOptions = {}): Module<ReactHooksModule> => {
+  if (process.env.NODE_ENV !== 'production') {
+    const hookNames = ['useDispatch', 'useSelector', 'useStore'] as const
+    let warned = false
+    for (const hookName of hookNames) {
+      // warn for old hook options
+      if (countObjectKeys(rest) > 0) {
+        if ((rest as Partial<typeof hooks>)[hookName]) {
+          if (!warned) {
+            console.warn(
+              'As of RTK 2.0, the hooks now need to be specified as one object, provided under a `hooks` key:' +
+                '\n`reactHooksModule({ hooks: { useDispatch, useSelector, useStore } })`',
+            )
+            warned = true
+          }
+        }
+        // migrate
+        // @ts-ignore
+        hooks[hookName] = rest[hookName]
+      }
+      // then make sure we have them all
+      if (typeof hooks[hookName] !== 'function') {
+        throw new Error(
+          `When using custom hooks for context, all ${
+            hookNames.length
+          } hooks need to be provided: ${hookNames.join(
+            ', ',
+          )}.\nHook ${hookName} was either not provided or not a function.`,
+        )
+      }
+    }
+  }
+
+  return {
+    name: reactHooksModuleName,
+    init(api, { serializeQueryArgs }, context) {
+      const anyApi = api as any as Api<
+        any,
+        Record<string, any>,
+        any,
+        any,
+        ReactHooksModule
+      >
+      const {
+        buildQueryHooks,
+        buildInfiniteQueryHooks,
+        buildMutationHook,
+        usePrefetch,
+      } = buildHooks({
+        api,
+        moduleOptions: {
+          batch,
+          hooks,
+          unstable__sideEffectsInRender,
+          createSelector,
+        },
+        serializeQueryArgs,
+        context,
+      })
+      safeAssign(anyApi, { usePrefetch })
+      safeAssign(context, { batch })
+
+      return {
+        injectEndpoint(endpointName, definition) {
+          if (isQueryDefinition(definition)) {
+            const {
+              useQuery,
+              useLazyQuery,
+              useLazyQuerySubscription,
+              useQueryState,
+              useQuerySubscription,
+            } = buildQueryHooks(endpointName)
+            safeAssign(anyApi.endpoints[endpointName], {
+              useQuery,
+              useLazyQuery,
+              useLazyQuerySubscription,
+              useQueryState,
+              useQuerySubscription,
+            })
+            ;(api as any)[`use${capitalize(endpointName)}Query`] = useQuery
+            ;(api as any)[`useLazy${capitalize(endpointName)}Query`] =
+              useLazyQuery
+          }
+          if (isMutationDefinition(definition)) {
+            const useMutation = buildMutationHook(endpointName)
+            safeAssign(anyApi.endpoints[endpointName], {
+              useMutation,
+            })
+            ;(api as any)[`use${capitalize(endpointName)}Mutation`] =
+              useMutation
+          } else if (isInfiniteQueryDefinition(definition)) {
+            const {
+              useInfiniteQuery,
+              useInfiniteQuerySubscription,
+              useInfiniteQueryState,
+            } = buildInfiniteQueryHooks(endpointName)
+            safeAssign(anyApi.endpoints[endpointName], {
+              useInfiniteQuery,
+              useInfiniteQuerySubscription,
+              useInfiniteQueryState,
+            })
+            ;(api as any)[`use${capitalize(endpointName)}InfiniteQuery`] =
+              useInfiniteQuery
+          }
+        },
+      }
+    },
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/query/react/namedHooks.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/react/namedHooks.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/react/namedHooks.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,59 @@
+import type {
+  DefinitionType,
+  EndpointDefinitions,
+  MutationDefinition,
+  QueryDefinition,
+  InfiniteQueryDefinition,
+} from '@reduxjs/toolkit/query'
+import type {
+  UseInfiniteQuery,
+  UseLazyQuery,
+  UseMutation,
+  UseQuery,
+} from './buildHooks'
+
+type QueryHookNames<Definitions extends EndpointDefinitions> = {
+  [K in keyof Definitions as Definitions[K] extends {
+    type: DefinitionType.query
+  }
+    ? `use${Capitalize<K & string>}Query`
+    : never]: UseQuery<
+    Extract<Definitions[K], QueryDefinition<any, any, any, any>>
+  >
+}
+
+type LazyQueryHookNames<Definitions extends EndpointDefinitions> = {
+  [K in keyof Definitions as Definitions[K] extends {
+    type: DefinitionType.query
+  }
+    ? `useLazy${Capitalize<K & string>}Query`
+    : never]: UseLazyQuery<
+    Extract<Definitions[K], QueryDefinition<any, any, any, any>>
+  >
+}
+
+type InfiniteQueryHookNames<Definitions extends EndpointDefinitions> = {
+  [K in keyof Definitions as Definitions[K] extends {
+    type: DefinitionType.infinitequery
+  }
+    ? `use${Capitalize<K & string>}InfiniteQuery`
+    : never]: UseInfiniteQuery<
+    Extract<Definitions[K], InfiniteQueryDefinition<any, any, any, any, any>>
+  >
+}
+
+type MutationHookNames<Definitions extends EndpointDefinitions> = {
+  [K in keyof Definitions as Definitions[K] extends {
+    type: DefinitionType.mutation
+  }
+    ? `use${Capitalize<K & string>}Mutation`
+    : never]: UseMutation<
+    Extract<Definitions[K], MutationDefinition<any, any, any, any>>
+  >
+}
+
+export type HooksWithUniqueNames<Definitions extends EndpointDefinitions> =
+  QueryHookNames<Definitions> &
+    LazyQueryHookNames<Definitions> &
+    InfiniteQueryHookNames<Definitions> &
+    MutationHookNames<Definitions>
Index: node_modules/@reduxjs/toolkit/src/query/react/reactImports.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/react/reactImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/react/reactImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,10 @@
+export {
+  useEffect,
+  useRef,
+  useMemo,
+  useContext,
+  useCallback,
+  useDebugValue,
+  useLayoutEffect,
+  useState,
+} from 'react'
Index: node_modules/@reduxjs/toolkit/src/query/react/reactReduxImports.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/react/reactReduxImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/react/reactReduxImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+export { shallowEqual, Provider, ReactReduxContext } from 'react-redux'
Index: node_modules/@reduxjs/toolkit/src/query/react/rtkqImports.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/react/rtkqImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/react/rtkqImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,8 @@
+export {
+  buildCreateApi,
+  coreModule,
+  copyWithStructuralSharing,
+  setupListeners,
+  QueryStatus,
+  skipToken,
+} from '@reduxjs/toolkit/query'
Index: node_modules/@reduxjs/toolkit/src/query/react/useSerializedStableValue.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/react/useSerializedStableValue.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/react/useSerializedStableValue.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,17 @@
+import { useEffect, useRef, useMemo } from './reactImports'
+import { copyWithStructuralSharing } from './rtkqImports'
+
+export function useStableQueryArgs<T>(queryArgs: T) {
+  const cache = useRef(queryArgs)
+  const copy = useMemo(
+    () => copyWithStructuralSharing(cache.current, queryArgs),
+    [queryArgs],
+  )
+  useEffect(() => {
+    if (cache.current !== copy) {
+      cache.current = copy
+    }
+  }, [copy])
+
+  return copy
+}
Index: node_modules/@reduxjs/toolkit/src/query/react/useShallowStableValue.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/react/useShallowStableValue.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/react/useShallowStableValue.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,13 @@
+import { useEffect, useRef } from './reactImports'
+import { shallowEqual } from './reactReduxImports'
+
+export function useShallowStableValue<T>(value: T) {
+  const cache = useRef(value)
+  useEffect(() => {
+    if (!shallowEqual(cache.current, value)) {
+      cache.current = value
+    }
+  }, [value])
+
+  return shallowEqual(cache.current, value) ? cache.current : value
+}
Index: node_modules/@reduxjs/toolkit/src/query/retry.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/retry.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/retry.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,233 @@
+import type {
+  BaseQueryApi,
+  BaseQueryArg,
+  BaseQueryEnhancer,
+  BaseQueryError,
+  BaseQueryExtraOptions,
+  BaseQueryFn,
+  BaseQueryMeta,
+} from './baseQueryTypes'
+import type { FetchBaseQueryError } from './fetchBaseQuery'
+import { HandledError } from './HandledError'
+
+/**
+ * Exponential backoff based on the attempt number.
+ *
+ * @remarks
+ * 1. 600ms * random(0.4, 1.4)
+ * 2. 1200ms * random(0.4, 1.4)
+ * 3. 2400ms * random(0.4, 1.4)
+ * 4. 4800ms * random(0.4, 1.4)
+ * 5. 9600ms * random(0.4, 1.4)
+ *
+ * @param attempt - Current attempt
+ * @param maxRetries - Maximum number of retries
+ */
+async function defaultBackoff(
+  attempt: number = 0,
+  maxRetries: number = 5,
+  signal?: AbortSignal,
+) {
+  const attempts = Math.min(attempt, maxRetries)
+
+  const timeout = ~~((Math.random() + 0.4) * (300 << attempts)) // Force a positive int in the case we make this an option
+
+  await new Promise<void>((resolve, reject) => {
+    const timeoutId = setTimeout(() => resolve(), timeout)
+
+    // If signal is provided and gets aborted, clear timeout and reject
+    if (signal) {
+      const abortHandler = () => {
+        clearTimeout(timeoutId)
+        reject(new Error('Aborted'))
+      }
+
+      // Check if already aborted
+      if (signal.aborted) {
+        clearTimeout(timeoutId)
+        reject(new Error('Aborted'))
+      } else {
+        signal.addEventListener('abort', abortHandler, { once: true })
+      }
+    }
+  })
+}
+
+type RetryConditionFunction = (
+  error: BaseQueryError<BaseQueryFn>,
+  args: BaseQueryArg<BaseQueryFn>,
+  extraArgs: {
+    attempt: number
+    baseQueryApi: BaseQueryApi
+    extraOptions: BaseQueryExtraOptions<BaseQueryFn> & RetryOptions
+  },
+) => boolean
+
+export type RetryOptions = {
+  /**
+   * Function used to determine delay between retries
+   */
+  backoff?: (
+    attempt: number,
+    maxRetries: number,
+    signal?: AbortSignal,
+  ) => Promise<void>
+} & (
+  | {
+      /**
+       * How many times the query will be retried (default: 5)
+       */
+      maxRetries?: number
+      retryCondition?: undefined
+    }
+  | {
+      /**
+       * Callback to determine if a retry should be attempted.
+       * Return `true` for another retry and `false` to quit trying prematurely.
+       */
+      retryCondition?: RetryConditionFunction
+      maxRetries?: undefined
+    }
+)
+
+function fail<BaseQuery extends BaseQueryFn = BaseQueryFn>(
+  error: BaseQueryError<BaseQuery>,
+  meta?: BaseQueryMeta<BaseQuery>,
+): never {
+  throw Object.assign(new HandledError({ error, meta }), {
+    throwImmediately: true,
+  })
+}
+
+/**
+ * Checks if the abort signal is aborted and fails immediately if so.
+ * Used to exit retry loops cleanly when a request is aborted.
+ */
+function failIfAborted(signal: AbortSignal): void {
+  if (signal.aborted) {
+    fail({ status: 'CUSTOM_ERROR', error: 'Aborted' })
+  }
+}
+
+const EMPTY_OPTIONS = {}
+
+const retryWithBackoff: BaseQueryEnhancer<
+  unknown,
+  RetryOptions,
+  RetryOptions | void
+> = (baseQuery, defaultOptions) => async (args, api, extraOptions) => {
+  // We need to figure out `maxRetries` before we define `defaultRetryCondition.
+  // This is probably goofy, but ought to work.
+  // Put our defaults in one array, filter out undefineds, grab the last value.
+  const possibleMaxRetries: number[] = [
+    5,
+    ((defaultOptions as any) || EMPTY_OPTIONS).maxRetries,
+    ((extraOptions as any) || EMPTY_OPTIONS).maxRetries,
+  ].filter((x) => x !== undefined)
+  const [maxRetries] = possibleMaxRetries.slice(-1)
+
+  const defaultRetryCondition: RetryConditionFunction = (_, __, { attempt }) =>
+    attempt <= maxRetries
+
+  const options: {
+    maxRetries: number
+    backoff: typeof defaultBackoff
+    retryCondition: typeof defaultRetryCondition
+  } = {
+    maxRetries,
+    backoff: defaultBackoff,
+    retryCondition: defaultRetryCondition,
+    ...defaultOptions,
+    ...extraOptions,
+  }
+  let retry = 0
+
+  while (true) {
+    // Check if aborted before each attempt
+    failIfAborted(api.signal)
+
+    try {
+      const result = await baseQuery(args, api, extraOptions)
+      // baseQueries _should_ return an error property, so we should check for that and throw it to continue retrying
+      if (result.error) {
+        throw new HandledError(result)
+      }
+      return result
+    } catch (e: any) {
+      retry++
+
+      if (e.throwImmediately) {
+        if (e instanceof HandledError) {
+          return e.value
+        }
+
+        // We don't know what this is, so we have to rethrow it
+        throw e
+      }
+
+      if (e instanceof HandledError) {
+        if (
+          !options.retryCondition(e.value.error as FetchBaseQueryError, args, {
+            attempt: retry,
+            baseQueryApi: api,
+            extraOptions,
+          })
+        ) {
+          return e.value // Max retries for expected error
+        }
+      } else {
+        // For unexpected errors, respect maxRetries
+        if (retry > options.maxRetries) {
+          // Return the error as a proper error response instead of throwing
+          return { error: e }
+        }
+      }
+
+      // Check if aborted before backoff
+      failIfAborted(api.signal)
+
+      try {
+        await options.backoff(retry, options.maxRetries, api.signal)
+      } catch (backoffError) {
+        // If backoff was aborted, exit the retry loop
+        failIfAborted(api.signal)
+        // Otherwise, rethrow the backoff error
+        throw backoffError
+      }
+    }
+  }
+}
+
+/**
+ * A utility that can wrap `baseQuery` in the API definition to provide retries with a basic exponential backoff.
+ *
+ * @example
+ *
+ * ```ts
+ * // codeblock-meta title="Retry every request 5 times by default"
+ * import { createApi, fetchBaseQuery, retry } from '@reduxjs/toolkit/query/react'
+ * interface Post {
+ *   id: number
+ *   name: string
+ * }
+ * type PostsResponse = Post[]
+ *
+ * // maxRetries: 5 is the default, and can be omitted. Shown for documentation purposes.
+ * const staggeredBaseQuery = retry(fetchBaseQuery({ baseUrl: '/' }), { maxRetries: 5 });
+ * export const api = createApi({
+ *   baseQuery: staggeredBaseQuery,
+ *   endpoints: (build) => ({
+ *     getPosts: build.query<PostsResponse, void>({
+ *       query: () => ({ url: 'posts' }),
+ *     }),
+ *     getPost: build.query<PostsResponse, string>({
+ *       query: (id) => ({ url: `post/${id}` }),
+ *       extraOptions: { maxRetries: 8 }, // You can override the retry behavior on each endpoint
+ *     }),
+ *   }),
+ * });
+ *
+ * export const { useGetPostsQuery, useGetPostQuery } = api;
+ * ```
+ */
+export const retry = /* @__PURE__ */ Object.assign(retryWithBackoff, { fail })
Index: node_modules/@reduxjs/toolkit/src/query/standardSchema.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/standardSchema.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/standardSchema.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,35 @@
+import type { StandardSchemaV1 } from '@standard-schema/spec'
+import { SchemaError } from '@standard-schema/utils'
+import type { SchemaType } from './endpointDefinitions'
+
+export class NamedSchemaError extends SchemaError {
+  constructor(
+    issues: readonly StandardSchemaV1.Issue[],
+    public readonly value: any,
+    public readonly schemaName: `${SchemaType}Schema`,
+    public readonly _bqMeta: any,
+  ) {
+    super(issues)
+  }
+}
+
+export const shouldSkip = (
+  skipSchemaValidation: boolean | SchemaType[] | undefined,
+  schemaName: SchemaType,
+) =>
+  Array.isArray(skipSchemaValidation)
+    ? skipSchemaValidation.includes(schemaName)
+    : !!skipSchemaValidation
+
+export async function parseWithSchema<Schema extends StandardSchemaV1>(
+  schema: Schema,
+  data: unknown,
+  schemaName: `${SchemaType}Schema`,
+  bqMeta: any,
+): Promise<StandardSchemaV1.InferOutput<Schema>> {
+  const result = await schema['~standard'].validate(data)
+  if (result.issues) {
+    throw new NamedSchemaError(result.issues, data, schemaName, bqMeta)
+  }
+  return result.value
+}
Index: node_modules/@reduxjs/toolkit/src/query/tests/apiProvider.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/apiProvider.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/apiProvider.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,170 @@
+import { configureStore } from '@reduxjs/toolkit'
+import {
+  ApiProvider,
+  buildCreateApi,
+  coreModule,
+  createApi,
+  reactHooksModule,
+} from '@reduxjs/toolkit/query/react'
+import { fireEvent, render, waitFor } from '@testing-library/react'
+import { delay } from 'msw'
+import * as React from 'react'
+import type { ReactReduxContextValue } from 'react-redux'
+import {
+  Provider,
+  createDispatchHook,
+  createSelectorHook,
+  createStoreHook,
+} from 'react-redux'
+
+const api = createApi({
+  baseQuery: async (arg: any) => {
+    await delay(150)
+    return { data: arg?.body ? arg.body : null }
+  },
+  endpoints: (build) => ({
+    getUser: build.query<any, number>({
+      query: (arg) => arg,
+    }),
+    updateUser: build.mutation<any, { name: string }>({
+      query: (update) => ({ body: update }),
+    }),
+  }),
+})
+
+afterEach(() => {
+  vi.resetAllMocks()
+})
+
+describe('ApiProvider', () => {
+  test('ApiProvider allows a user to make queries without a traditional Redux setup', async () => {
+    function User() {
+      const [value, setValue] = React.useState(0)
+
+      const { isFetching } = api.endpoints.getUser.useQuery(1, {
+        skip: value < 1,
+      })
+
+      return (
+        <div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <button onClick={() => setValue((val) => val + 1)}>
+            Increment value
+          </button>
+        </div>
+      )
+    }
+
+    const { getByText, getByTestId } = render(
+      <ApiProvider api={api}>
+        <User />
+      </ApiProvider>,
+    )
+
+    await waitFor(() =>
+      expect(getByTestId('isFetching').textContent).toBe('false'),
+    )
+    fireEvent.click(getByText('Increment value'))
+    await waitFor(() =>
+      expect(getByTestId('isFetching').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(getByTestId('isFetching').textContent).toBe('false'),
+    )
+    fireEvent.click(getByText('Increment value'))
+    // Being that nothing has changed in the args, this should never fire.
+    expect(getByTestId('isFetching').textContent).toBe('false')
+  })
+  test('ApiProvider throws if nested inside a Redux context', () => {
+    // Intentionally swallow the "unhandled error" message
+    vi.spyOn(console, 'error').mockImplementation(() => {})
+    expect(() =>
+      render(
+        <Provider store={configureStore({ reducer: () => null })}>
+          <ApiProvider api={api}>child</ApiProvider>
+        </Provider>,
+      ),
+    ).toThrowErrorMatchingInlineSnapshot(
+      `[Error: Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.]`,
+    )
+  })
+  test('ApiProvider allows a custom context', async () => {
+    const customContext = React.createContext<ReactReduxContextValue | null>(
+      null,
+    )
+
+    const createApiWithCustomContext = buildCreateApi(
+      coreModule(),
+      reactHooksModule({
+        hooks: {
+          useStore: createStoreHook(customContext),
+          useSelector: createSelectorHook(customContext),
+          useDispatch: createDispatchHook(customContext),
+        },
+      }),
+    )
+
+    const customApi = createApiWithCustomContext({
+      baseQuery: async (arg: any) => {
+        await delay(150)
+        return { data: arg?.body ? arg.body : null }
+      },
+      endpoints: (build) => ({
+        getUser: build.query<any, number>({
+          query: (arg) => arg,
+        }),
+        updateUser: build.mutation<any, { name: string }>({
+          query: (update) => ({ body: update }),
+        }),
+      }),
+    })
+
+    function User() {
+      const [value, setValue] = React.useState(0)
+
+      const { isFetching } = customApi.endpoints.getUser.useQuery(1, {
+        skip: value < 1,
+      })
+
+      return (
+        <div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <button onClick={() => setValue((val) => val + 1)}>
+            Increment value
+          </button>
+        </div>
+      )
+    }
+
+    const { getByText, getByTestId } = render(
+      <ApiProvider api={customApi} context={customContext}>
+        <User />
+      </ApiProvider>,
+    )
+
+    await waitFor(() =>
+      expect(getByTestId('isFetching').textContent).toBe('false'),
+    )
+    fireEvent.click(getByText('Increment value'))
+    await waitFor(() =>
+      expect(getByTestId('isFetching').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(getByTestId('isFetching').textContent).toBe('false'),
+    )
+    fireEvent.click(getByText('Increment value'))
+    // Being that nothing has changed in the args, this should never fire.
+    expect(getByTestId('isFetching').textContent).toBe('false')
+
+    // won't throw if nested, because context is different
+    expect(() =>
+      render(
+        <Provider store={configureStore({ reducer: () => null })}>
+          <ApiProvider api={customApi} context={customContext}>
+            child
+          </ApiProvider>
+        </Provider>,
+      ),
+    ).not.toThrow()
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/baseQueryTypes.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/baseQueryTypes.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/baseQueryTypes.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,32 @@
+import { createApi, fetchBaseQuery, retry } from '@reduxjs/toolkit/query'
+
+describe('type tests', () => {
+  test('BaseQuery meta types propagate to endpoint callbacks', () => {
+    createApi({
+      baseQuery: fetchBaseQuery(),
+      endpoints: (build) => ({
+        getDummy: build.query<null, undefined>({
+          query: () => 'dummy',
+          onCacheEntryAdded: async (arg, { cacheDataLoaded }) => {
+            const { meta } = await cacheDataLoaded
+            const { request, response } = meta! // Expect request and response to be there
+          },
+        }),
+      }),
+    })
+
+    const baseQuery = retry(fetchBaseQuery()) // Even when wrapped with retry
+    createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        getDummy: build.query<null, undefined>({
+          query: () => 'dummy',
+          onCacheEntryAdded: async (arg, { cacheDataLoaded }) => {
+            const { meta } = await cacheDataLoaded
+            const { request, response } = meta! // Expect request and response to be there
+          },
+        }),
+      }),
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/buildCreateApi.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/buildCreateApi.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/buildCreateApi.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,168 @@
+import { createSelectorCreator, lruMemoize } from '@reduxjs/toolkit'
+import {
+  buildCreateApi,
+  coreModule,
+  reactHooksModule,
+} from '@reduxjs/toolkit/query/react'
+import { render, screen, waitFor } from '@testing-library/react'
+import { delay } from 'msw'
+import * as React from 'react'
+import type { ReactReduxContextValue } from 'react-redux'
+import {
+  Provider,
+  createDispatchHook,
+  createSelectorHook,
+  createStoreHook,
+} from 'react-redux'
+import { setupApiStore, useRenderCounter } from '../../tests/utils/helpers'
+
+const MyContext = React.createContext<ReactReduxContextValue | null>(null)
+
+describe('buildCreateApi', () => {
+  test('Works with all hooks provided', async () => {
+    const customCreateApi = buildCreateApi(
+      coreModule(),
+      reactHooksModule({
+        hooks: {
+          useDispatch: createDispatchHook(MyContext),
+          useSelector: createSelectorHook(MyContext),
+          useStore: createStoreHook(MyContext),
+        },
+      }),
+    )
+
+    const api = customCreateApi({
+      baseQuery: async (arg: any) => {
+        await delay(150)
+
+        return {
+          data: arg?.body ? { ...arg.body } : {},
+        }
+      },
+      endpoints: (build) => ({
+        getUser: build.query<{ name: string }, number>({
+          query: () => ({
+            body: { name: 'Timmy' },
+          }),
+        }),
+      }),
+    })
+
+    let getRenderCount: () => number = () => 0
+
+    const storeRef = setupApiStore(api, {}, { withoutTestLifecycles: true })
+
+    // Copy of 'useQuery hook basic render count assumptions' from `buildHooks.test.tsx`
+    function User() {
+      const { isFetching } = api.endpoints.getUser.useQuery(1)
+      getRenderCount = useRenderCounter()
+
+      return (
+        <div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+        </div>
+      )
+    }
+
+    function Wrapper({ children }: any) {
+      return (
+        <Provider store={storeRef.store} context={MyContext}>
+          {children}
+        </Provider>
+      )
+    }
+
+    render(<User />, { wrapper: Wrapper })
+    // By the time this runs, the initial render will happen, and the query
+    //  will start immediately running by the time we can expect this
+    expect(getRenderCount()).toBe(2)
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+    )
+    expect(getRenderCount()).toBe(3)
+  })
+
+  test("Throws an error if you don't provide all hooks", async () => {
+    const callBuildCreateApi = () => {
+      const customCreateApi = buildCreateApi(
+        coreModule(),
+        reactHooksModule({
+          // @ts-ignore
+          hooks: {
+            useDispatch: createDispatchHook(MyContext),
+            useSelector: createSelectorHook(MyContext),
+          },
+        }),
+      )
+    }
+
+    expect(callBuildCreateApi).toThrowErrorMatchingInlineSnapshot(
+      `
+      [Error: When using custom hooks for context, all 3 hooks need to be provided: useDispatch, useSelector, useStore.
+      Hook useStore was either not provided or not a function.]
+    `,
+    )
+  })
+  test('allows passing createSelector instance', async () => {
+    const memoize = vi.fn(lruMemoize)
+    const createSelector = createSelectorCreator(memoize)
+    const createApi = buildCreateApi(
+      coreModule({ createSelector }),
+      reactHooksModule({ createSelector }),
+    )
+    const api = createApi({
+      baseQuery: async (arg: any) => {
+        await delay(150)
+
+        return {
+          data: arg?.body ? { ...arg.body } : {},
+        }
+      },
+      endpoints: (build) => ({
+        getUser: build.query<{ name: string }, number>({
+          query: () => ({
+            body: { name: 'Timmy' },
+          }),
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, {}, { withoutTestLifecycles: true })
+
+    await storeRef.store.dispatch(api.endpoints.getUser.initiate(1))
+
+    const selectUser = api.endpoints.getUser.select(1)
+
+    expect(selectUser(storeRef.store.getState()).data).toEqual({
+      name: 'Timmy',
+    })
+
+    expect(memoize).toHaveBeenCalledTimes(4)
+
+    memoize.mockClear()
+
+    function User() {
+      const { isFetching } = api.endpoints.getUser.useQuery(1)
+
+      return (
+        <div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+        </div>
+      )
+    }
+
+    function Wrapper({ children }: any) {
+      return <Provider store={storeRef.store}>{children}</Provider>
+    }
+
+    render(<User />, { wrapper: Wrapper })
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+    )
+
+    // select() + selectFromResult
+    expect(memoize).toHaveBeenCalledTimes(8)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/buildHooks.test-d.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/buildHooks.test-d.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/buildHooks.test-d.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,343 @@
+import type {
+  QueryStateSelector,
+  UseMutation,
+  UseQuery,
+} from '@internal/query/react/buildHooks'
+import { ANY } from '@internal/tests/utils/helpers'
+import type { SerializedError } from '@reduxjs/toolkit'
+import type {
+  QueryDefinition,
+  SubscriptionOptions,
+  TypedQueryStateSelector,
+} from '@reduxjs/toolkit/query/react'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+import { useState } from 'react'
+
+let amount = 0
+let nextItemId = 0
+
+interface Item {
+  id: number
+}
+
+const api = createApi({
+  baseQuery: (arg: any) => {
+    if (arg?.body && 'amount' in arg.body) {
+      amount += 1
+    }
+
+    if (arg?.body && 'forceError' in arg.body) {
+      return {
+        error: {
+          status: 500,
+          data: null,
+        },
+      }
+    }
+
+    if (arg?.body && 'listItems' in arg.body) {
+      const items: Item[] = []
+      for (let i = 0; i < 3; i++) {
+        const item = { id: nextItemId++ }
+        items.push(item)
+      }
+      return { data: items }
+    }
+
+    return {
+      data: arg?.body ? { ...arg.body, ...(amount ? { amount } : {}) } : {},
+    }
+  },
+  endpoints: (build) => ({
+    getUser: build.query<{ name: string }, number>({
+      query: () => ({
+        body: { name: 'Timmy' },
+      }),
+    }),
+    getUserAndForceError: build.query<{ name: string }, number>({
+      query: () => ({
+        body: {
+          forceError: true,
+        },
+      }),
+    }),
+    getIncrementedAmount: build.query<{ amount: number }, void>({
+      query: () => ({
+        url: '',
+        body: {
+          amount,
+        },
+      }),
+    }),
+    updateUser: build.mutation<{ name: string }, { name: string }>({
+      query: (update) => ({ body: update }),
+    }),
+    getError: build.query({
+      query: () => '/error',
+    }),
+    listItems: build.query<Item[], { pageNumber: number }>({
+      serializeQueryArgs: ({ endpointName }) => {
+        return endpointName
+      },
+      query: ({ pageNumber }) => ({
+        url: `items?limit=1&offset=${pageNumber}`,
+        body: {
+          listItems: true,
+        },
+      }),
+      merge: (currentCache, newItems) => {
+        currentCache.push(...newItems)
+      },
+      forceRefetch: () => {
+        return true
+      },
+    }),
+  }),
+})
+
+describe('type tests', () => {
+  test('useLazyQuery hook callback returns various properties to handle the result', () => {
+    function User() {
+      const [getUser] = api.endpoints.getUser.useLazyQuery()
+      const [{ successMsg, errMsg, isAborted }, setValues] = useState({
+        successMsg: '',
+        errMsg: '',
+        isAborted: false,
+      })
+
+      const handleClick = (abort: boolean) => async () => {
+        const res = getUser(1)
+
+        // no-op simply for clearer type assertions
+        res.then((result) => {
+          if (result.isSuccess) {
+            expectTypeOf(result).toMatchTypeOf<{
+              data: {
+                name: string
+              }
+            }>()
+          }
+
+          if (result.isError) {
+            expectTypeOf(result).toMatchTypeOf<{
+              error: { status: number; data: unknown } | SerializedError
+            }>()
+          }
+        })
+
+        expectTypeOf(res.arg).toBeNumber()
+
+        expectTypeOf(res.requestId).toBeString()
+
+        expectTypeOf(res.abort).toEqualTypeOf<() => void>()
+
+        expectTypeOf(res.unsubscribe).toEqualTypeOf<() => void>()
+
+        expectTypeOf(res.updateSubscriptionOptions).toEqualTypeOf<
+          (options: SubscriptionOptions) => void
+        >()
+
+        expectTypeOf(res.refetch).toMatchTypeOf<() => void>()
+
+        expectTypeOf(res.unwrap()).resolves.toEqualTypeOf<{ name: string }>()
+      }
+
+      return (
+        <div>
+          <button onClick={handleClick(false)}>Fetch User successfully</button>
+          <button onClick={handleClick(true)}>Fetch User and abort</button>
+          <div>{successMsg}</div>
+          <div>{errMsg}</div>
+          <div>{isAborted ? 'Request was aborted' : ''}</div>
+        </div>
+      )
+    }
+  })
+
+  test('useMutation hook callback returns various properties to handle the result', async () => {
+    function User() {
+      const [updateUser] = api.endpoints.updateUser.useMutation()
+      const [successMsg, setSuccessMsg] = useState('')
+      const [errMsg, setErrMsg] = useState('')
+      const [isAborted, setIsAborted] = useState(false)
+
+      const handleClick = async () => {
+        const res = updateUser({ name: 'Banana' })
+
+        expectTypeOf(res).resolves.toMatchTypeOf<
+          | {
+              error: { status: number; data: unknown } | SerializedError
+            }
+          | {
+              data: {
+                name: string
+              }
+            }
+        >()
+
+        expectTypeOf(res.arg).toMatchTypeOf<{
+          endpointName: string
+          originalArgs: { name: string }
+          track?: boolean
+        }>()
+
+        expectTypeOf(res.requestId).toBeString()
+
+        expectTypeOf(res.abort).toEqualTypeOf<() => void>()
+
+        expectTypeOf(res.unwrap()).resolves.toEqualTypeOf<{ name: string }>()
+
+        expectTypeOf(res.reset).toEqualTypeOf<() => void>()
+      }
+
+      return (
+        <div>
+          <button onClick={handleClick}>Update User and abort</button>
+          <div>{successMsg}</div>
+          <div>{errMsg}</div>
+          <div>{isAborted ? 'Request was aborted' : ''}</div>
+        </div>
+      )
+    }
+  })
+
+  test('top level named hooks', () => {
+    interface Post {
+      id: number
+      name: string
+      fetched_at: string
+    }
+
+    type PostsResponse = Post[]
+
+    const api = createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com/' }),
+      tagTypes: ['Posts'],
+      endpoints: (build) => ({
+        getPosts: build.query<PostsResponse, void>({
+          query: () => ({ url: 'posts' }),
+          providesTags: (result) =>
+            result ? result.map(({ id }) => ({ type: 'Posts', id })) : [],
+        }),
+        updatePost: build.mutation<Post, Partial<Post>>({
+          query: ({ id, ...body }) => ({
+            url: `post/${id}`,
+            method: 'PUT',
+            body,
+          }),
+          invalidatesTags: (result, error, { id }) => [{ type: 'Posts', id }],
+        }),
+        addPost: build.mutation<Post, Partial<Post>>({
+          query: (body) => ({
+            url: `post`,
+            method: 'POST',
+            body,
+          }),
+          invalidatesTags: ['Posts'],
+        }),
+      }),
+    })
+
+    expectTypeOf(api.useGetPostsQuery).toEqualTypeOf(
+      api.endpoints.getPosts.useQuery,
+    )
+
+    expectTypeOf(api.useUpdatePostMutation).toEqualTypeOf(
+      api.endpoints.updatePost.useMutation,
+    )
+
+    expectTypeOf(api.useAddPostMutation).toEqualTypeOf(
+      api.endpoints.addPost.useMutation,
+    )
+  })
+
+  test('UseQuery type can be used to recreate the hook type', () => {
+    const fakeQuery = ANY as UseQuery<
+      typeof api.endpoints.getUser.Types.QueryDefinition
+    >
+
+    expectTypeOf(fakeQuery).toEqualTypeOf(api.endpoints.getUser.useQuery)
+  })
+
+  test('UseMutation type can be used to recreate the hook type', () => {
+    const fakeMutation = ANY as UseMutation<
+      typeof api.endpoints.updateUser.Types.MutationDefinition
+    >
+
+    expectTypeOf(fakeMutation).toEqualTypeOf(
+      api.endpoints.updateUser.useMutation,
+    )
+  })
+
+  test('TypedQueryStateSelector creates a pre-typed version of QueryStateSelector', () => {
+    type Post = {
+      id: number
+      title: string
+    }
+
+    type PostsApiResponse = {
+      posts: Post[]
+      total: number
+      skip: number
+      limit: number
+    }
+
+    type QueryArgument = number | undefined
+
+    type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>
+
+    type SelectedResult = Pick<PostsApiResponse, 'posts'>
+
+    const postsApiSlice = createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com/posts' }),
+      reducerPath: 'postsApi',
+      tagTypes: ['Posts'],
+      endpoints: (build) => ({
+        getPosts: build.query<PostsApiResponse, QueryArgument>({
+          query: (limit = 5) => `?limit=${limit}&select=title`,
+        }),
+      }),
+    })
+
+    const { useGetPostsQuery } = postsApiSlice
+
+    function PostById({ id }: { id: number }) {
+      const { post } = useGetPostsQuery(undefined, {
+        selectFromResult: (state) => ({
+          post: state.data?.posts.find((post) => post.id === id),
+        }),
+      })
+
+      expectTypeOf(post).toEqualTypeOf<Post | undefined>()
+
+      return <li>{post?.title}</li>
+    }
+
+    const EMPTY_ARRAY: Post[] = []
+
+    const typedSelectFromResult: TypedQueryStateSelector<
+      PostsApiResponse,
+      QueryArgument,
+      BaseQueryFunction,
+      SelectedResult
+    > = (state) => ({ posts: state.data?.posts ?? EMPTY_ARRAY })
+
+    function PostsList() {
+      const { posts } = useGetPostsQuery(undefined, {
+        selectFromResult: typedSelectFromResult,
+      })
+
+      expectTypeOf(posts).toEqualTypeOf<Post[]>()
+
+      return (
+        <div>
+          <ul>
+            {posts.map((post) => (
+              <PostById key={post.id} id={post.id} />
+            ))}
+          </ul>
+        </div>
+      )
+    }
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/buildHooks.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/buildHooks.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/buildHooks.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,4142 @@
+import { noop } from '@internal/listenerMiddleware/utils'
+import type { SubscriptionOptions } from '@internal/query/core/apiState'
+import type { SubscriptionSelectors } from '@internal/query/core/buildMiddleware/types'
+import { server } from '@internal/query/tests/mocks/server'
+import { countObjectKeys } from '@internal/query/utils/countObjectKeys'
+import {
+  actionsReducer,
+  setupApiStore,
+  useRenderCounter,
+  waitForFakeTimer,
+  waitMs,
+  withProvider,
+} from '@internal/tests/utils/helpers'
+import type { UnknownAction } from '@reduxjs/toolkit'
+import {
+  configureStore,
+  createListenerMiddleware,
+  createSlice,
+} from '@reduxjs/toolkit'
+import {
+  QueryStatus,
+  createApi,
+  fetchBaseQuery,
+  skipToken,
+} from '@reduxjs/toolkit/query/react'
+import {
+  act,
+  fireEvent,
+  render,
+  renderHook,
+  screen,
+  waitFor,
+} from '@testing-library/react'
+import { userEvent } from '@testing-library/user-event'
+import type { SyncScreen } from '@testing-library/react-render-stream/pure'
+import { createRenderStream } from '@testing-library/react-render-stream/pure'
+import { HttpResponse, http, delay } from 'msw'
+import { useEffect, useMemo, useRef, useState } from 'react'
+import type { InfiniteQueryResultFlags } from '../core/buildSelectors'
+
+// Just setup a temporary in-memory counter for tests that `getIncrementedAmount`.
+// This can be used to test how many renders happen due to data changes or
+// the refetching behavior of components.
+let amount = 0
+let nextItemId = 0
+let refetchCount = 0
+
+interface Item {
+  id: number
+}
+
+const api = createApi({
+  baseQuery: async (arg: any) => {
+    await waitForFakeTimer(150)
+    if (arg?.body && 'amount' in arg.body) {
+      amount += 1
+    }
+
+    if (arg?.body && 'forceError' in arg.body) {
+      return {
+        error: {
+          status: 500,
+          data: null,
+        },
+      }
+    }
+
+    if (arg?.body && 'listItems' in arg.body) {
+      const items: Item[] = []
+      for (let i = 0; i < 3; i++) {
+        const item = { id: nextItemId++ }
+        items.push(item)
+      }
+      return { data: items }
+    }
+
+    return {
+      data: arg?.body ? { ...arg.body, ...(amount ? { amount } : {}) } : {},
+    }
+  },
+  tagTypes: ['IncrementedAmount'],
+  endpoints: (build) => ({
+    getUser: build.query<{ name: string }, number>({
+      query: () => ({
+        body: { name: 'Timmy' },
+      }),
+    }),
+    getUserAndForceError: build.query<{ name: string }, number>({
+      query: () => ({
+        body: {
+          forceError: true,
+        },
+      }),
+    }),
+    getUserWithRefetchError: build.query<{ name: string }, number>({
+      queryFn: async (id) => {
+        refetchCount += 1
+
+        if (refetchCount > 1) {
+          return { error: true } as any
+        }
+
+        return { data: { name: 'Timmy' } }
+      },
+    }),
+    getIncrementedAmount: build.query<{ amount: number }, void>({
+      query: () => ({
+        url: '',
+        body: {
+          amount,
+        },
+      }),
+      providesTags: ['IncrementedAmount'],
+    }),
+    triggerUpdatedAmount: build.mutation<void, void>({
+      queryFn: async () => {
+        return { data: undefined }
+      },
+      invalidatesTags: ['IncrementedAmount'],
+    }),
+    updateUser: build.mutation<{ name: string }, { name: string }>({
+      query: (update) => ({ body: update }),
+    }),
+    getError: build.query({
+      query: () => '/error',
+    }),
+    listItems: build.query<Item[], { pageNumber: number | bigint }>({
+      serializeQueryArgs: ({ endpointName }) => {
+        return endpointName
+      },
+      query: ({ pageNumber }) => ({
+        url: `items?limit=1&offset=${pageNumber}`,
+        body: {
+          listItems: true,
+        },
+      }),
+      merge: (currentCache, newItems) => {
+        currentCache.push(...newItems)
+      },
+      forceRefetch: () => {
+        return true
+      },
+    }),
+    queryWithDeepArg: build.query<string, { param: { nested: string } }>({
+      query: ({ param: { nested } }) => nested,
+      serializeQueryArgs: ({ queryArgs }) => {
+        return queryArgs.param.nested
+      },
+    }),
+  }),
+})
+
+const listenerMiddleware = createListenerMiddleware()
+
+let actions: UnknownAction[] = []
+
+const storeRef = setupApiStore(
+  api,
+  {},
+  {
+    middleware: {
+      prepend: [listenerMiddleware.middleware],
+    },
+  },
+)
+
+let getSubscriptions: SubscriptionSelectors['getSubscriptions']
+let getSubscriptionCount: SubscriptionSelectors['getSubscriptionCount']
+
+beforeEach(() => {
+  actions = []
+  listenerMiddleware.startListening({
+    predicate: () => true,
+    effect: (action) => {
+      actions.push(action)
+    },
+  })
+  ;({ getSubscriptions, getSubscriptionCount } = storeRef.store.dispatch(
+    api.internalActions.internal_getRTKQSubscriptions(),
+  ) as unknown as SubscriptionSelectors)
+})
+
+afterEach(() => {
+  nextItemId = 0
+  amount = 0
+  listenerMiddleware.clearListeners()
+
+  server.resetHandlers()
+})
+
+let getRenderCount: () => number = () => 0
+
+describe('hooks tests', () => {
+  describe('useQuery', () => {
+    test('useQuery hook basic render count assumptions', async () => {
+      function User() {
+        const { isFetching } = api.endpoints.getUser.useQuery(1)
+        getRenderCount = useRenderCounter()
+
+        return (
+          <div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+      // By the time this runs, the initial render will happen, and the query
+      //  will start immediately running by the time we can expect this
+      expect(getRenderCount()).toBe(2)
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+      expect(getRenderCount()).toBe(3)
+    })
+
+    test('useQuery hook sets isFetching=true whenever a request is in flight', async () => {
+      function User() {
+        const [value, setValue] = useState(0)
+
+        const { isFetching } = api.endpoints.getUser.useQuery(1, {
+          skip: value < 1,
+        })
+        getRenderCount = useRenderCounter()
+
+        return (
+          <div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <button onClick={() => setValue((val) => val + 1)}>
+              Increment value
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+      expect(getRenderCount()).toBe(1)
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+      fireEvent.click(screen.getByText('Increment value')) // setState = 1, perform request = 2
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+      expect(getRenderCount()).toBe(4)
+
+      fireEvent.click(screen.getByText('Increment value'))
+      // Being that nothing has changed in the args, this should never fire.
+      expect(screen.getByTestId('isFetching').textContent).toBe('false')
+      expect(getRenderCount()).toBe(5) // even though there was no request, the button click updates the state so this is an expected render
+    })
+
+    test('useQuery hook sets isLoading=true only on initial request', async () => {
+      let refetch: any, isLoading: boolean, isFetching: boolean
+      function User() {
+        const [value, setValue] = useState(0)
+
+        ;({ isLoading, isFetching, refetch } = api.endpoints.getUser.useQuery(
+          2,
+          {
+            skip: value < 1,
+          },
+        ))
+        return (
+          <div>
+            <div data-testid="isLoading">{String(isLoading)}</div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <button onClick={() => setValue((val) => val + 1)}>
+              Increment value
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      // Being that we skipped the initial request on mount, this should be false
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+      )
+      fireEvent.click(screen.getByText('Increment value'))
+      // Condition is met, should load
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+      ) // Make sure the original loading has completed.
+      fireEvent.click(screen.getByText('Increment value'))
+      // Being that we already have data, isLoading should be false
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+      )
+      // We call a refetch, should still be `false`
+      act(() => void refetch())
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+      expect(screen.getByTestId('isLoading').textContent).toBe('false')
+    })
+
+    test('useQuery hook sets isLoading and isFetching to the correct states', async () => {
+      let refetchMe: () => void = () => {}
+      function User() {
+        const [value, setValue] = useState(0)
+        getRenderCount = useRenderCounter()
+
+        const { isLoading, isFetching, refetch } =
+          api.endpoints.getUser.useQuery(22, { skip: value < 1 })
+        refetchMe = refetch
+        return (
+          <div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <div data-testid="isLoading">{String(isLoading)}</div>
+            <button onClick={() => setValue((val) => val + 1)}>
+              Increment value
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+      expect(getRenderCount()).toBe(1)
+
+      expect(screen.getByTestId('isLoading').textContent).toBe('false')
+      expect(screen.getByTestId('isFetching').textContent).toBe('false')
+
+      fireEvent.click(screen.getByText('Increment value')) // renders: set state = 1, perform request = 2
+      // Condition is met, should load
+      await waitFor(() => {
+        expect(screen.getByTestId('isLoading').textContent).toBe('true')
+        expect(screen.getByTestId('isFetching').textContent).toBe('true')
+      })
+
+      // Make sure the request is done for sure.
+      await waitFor(() => {
+        expect(screen.getByTestId('isLoading').textContent).toBe('false')
+        expect(screen.getByTestId('isFetching').textContent).toBe('false')
+      })
+      expect(getRenderCount()).toBe(4)
+
+      fireEvent.click(screen.getByText('Increment value'))
+      // Being that we already have data and changing the value doesn't trigger a new request, only the button click should impact the render
+      await waitFor(() => {
+        expect(screen.getByTestId('isLoading').textContent).toBe('false')
+        expect(screen.getByTestId('isFetching').textContent).toBe('false')
+      })
+      expect(getRenderCount()).toBe(5)
+
+      // We call a refetch, should set `isFetching` to true, then false when complete/errored
+      act(() => void refetchMe())
+      await waitFor(() => {
+        expect(screen.getByTestId('isLoading').textContent).toBe('false')
+        expect(screen.getByTestId('isFetching').textContent).toBe('true')
+      })
+      await waitFor(() => {
+        expect(screen.getByTestId('isLoading').textContent).toBe('false')
+        expect(screen.getByTestId('isFetching').textContent).toBe('false')
+      })
+      expect(getRenderCount()).toBe(7)
+    })
+
+    test('`isLoading` does not jump back to true, while `isFetching` does', async () => {
+      const loadingHist: boolean[] = [],
+        fetchingHist: boolean[] = []
+
+      function User({ id }: { id: number }) {
+        const { isLoading, isFetching, status } =
+          api.endpoints.getUser.useQuery(id)
+
+        useEffect(() => {
+          loadingHist.push(isLoading)
+        }, [isLoading])
+        useEffect(() => {
+          fetchingHist.push(isFetching)
+        }, [isFetching])
+        return (
+          <div data-testid="status">
+            {status === QueryStatus.fulfilled && id}
+          </div>
+        )
+      }
+
+      let { rerender } = render(<User id={1} />, { wrapper: storeRef.wrapper })
+
+      await waitFor(() =>
+        expect(screen.getByTestId('status').textContent).toBe('1'),
+      )
+      rerender(<User id={2} />)
+
+      await waitFor(() =>
+        expect(screen.getByTestId('status').textContent).toBe('2'),
+      )
+
+      expect(loadingHist).toEqual([true, false])
+      expect(fetchingHist).toEqual([true, false, true, false])
+    })
+
+    test('`isSuccess` does not jump back false on subsequent queries', async () => {
+      type LoadingState = {
+        id: number
+        isFetching: boolean
+        isSuccess: boolean
+      }
+      const loadingHistory: LoadingState[] = []
+
+      function User({ id }: { id: number }) {
+        const queryRes = api.endpoints.getUser.useQuery(id)
+
+        useEffect(() => {
+          const { isFetching, isSuccess } = queryRes
+          loadingHistory.push({ id, isFetching, isSuccess })
+        }, [id, queryRes])
+        return (
+          <div data-testid="status">
+            {queryRes.status === QueryStatus.fulfilled && id}
+          </div>
+        )
+      }
+
+      let { rerender } = render(<User id={1} />, { wrapper: storeRef.wrapper })
+
+      await waitFor(() =>
+        expect(screen.getByTestId('status').textContent).toBe('1'),
+      )
+      rerender(<User id={2} />)
+
+      await waitFor(() =>
+        expect(screen.getByTestId('status').textContent).toBe('2'),
+      )
+
+      expect(loadingHistory).toEqual([
+        // Initial render(s)
+        { id: 1, isFetching: true, isSuccess: false },
+        { id: 1, isFetching: true, isSuccess: false },
+        // Data returned
+        { id: 1, isFetching: false, isSuccess: true },
+        // ID changed, there's an uninitialized cache entry.
+        // IMPORTANT: `isSuccess` should not be false here.
+        // We have valid data already for the old item.
+        { id: 2, isFetching: true, isSuccess: true },
+        { id: 2, isFetching: true, isSuccess: true },
+        { id: 2, isFetching: false, isSuccess: true },
+      ])
+    })
+
+    test('isSuccess stays consistent if there is an error while refetching', async () => {
+      type LoadingState = {
+        id: number
+        isFetching: boolean
+        isSuccess: boolean
+        isError: boolean
+      }
+      const loadingHistory: LoadingState[] = []
+
+      function Component({ id = 1 }) {
+        const queryRes = api.endpoints.getUserWithRefetchError.useQuery(id)
+        const { refetch, data, status } = queryRes
+
+        useEffect(() => {
+          const { isFetching, isSuccess, isError } = queryRes
+          loadingHistory.push({ id, isFetching, isSuccess, isError })
+        }, [id, queryRes])
+
+        return (
+          <div>
+            <button
+              onClick={() => {
+                refetch()
+              }}
+            >
+              refetch
+            </button>
+            <div data-testid="name">{data?.name}</div>
+            <div data-testid="status">{status}</div>
+          </div>
+        )
+      }
+
+      render(<Component />, { wrapper: storeRef.wrapper })
+
+      await waitFor(() =>
+        expect(screen.getByTestId('name').textContent).toBe('Timmy'),
+      )
+
+      fireEvent.click(screen.getByText('refetch'))
+
+      await waitFor(() =>
+        expect(screen.getByTestId('status').textContent).toBe('pending'),
+      )
+
+      await waitFor(() =>
+        expect(screen.getByTestId('status').textContent).toBe('rejected'),
+      )
+
+      fireEvent.click(screen.getByText('refetch'))
+
+      await waitFor(() =>
+        expect(screen.getByTestId('status').textContent).toBe('pending'),
+      )
+
+      await waitFor(() =>
+        expect(screen.getByTestId('status').textContent).toBe('rejected'),
+      )
+
+      expect(loadingHistory).toEqual([
+        // Initial renders
+        { id: 1, isFetching: true, isSuccess: false, isError: false },
+        { id: 1, isFetching: true, isSuccess: false, isError: false },
+        // Data is returned
+        { id: 1, isFetching: false, isSuccess: true, isError: false },
+        // Started first refetch
+        { id: 1, isFetching: true, isSuccess: true, isError: false },
+        // First refetch errored
+        { id: 1, isFetching: false, isSuccess: false, isError: true },
+        // Started second refetch
+        // IMPORTANT We expect `isSuccess` to still be false,
+        // despite having started the refetch again.
+        { id: 1, isFetching: true, isSuccess: false, isError: false },
+        // Second refetch errored
+        { id: 1, isFetching: false, isSuccess: false, isError: true },
+      ])
+    })
+
+    test('useQuery hook respects refetchOnMountOrArgChange: true', async () => {
+      let data, isLoading, isFetching
+      function User() {
+        ;({ data, isLoading, isFetching } =
+          api.endpoints.getIncrementedAmount.useQuery(undefined, {
+            refetchOnMountOrArgChange: true,
+          }))
+        return (
+          <div>
+            <div data-testid="isLoading">{String(isLoading)}</div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <div data-testid="amount">{String(data?.amount)}</div>
+          </div>
+        )
+      }
+
+      const { unmount } = render(<User />, { wrapper: storeRef.wrapper })
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+      )
+
+      await waitFor(() =>
+        expect(screen.getByTestId('amount').textContent).toBe('1'),
+      )
+
+      unmount()
+
+      render(<User />, { wrapper: storeRef.wrapper })
+      // Let's make sure we actually fetch, and we increment
+      expect(screen.getByTestId('isLoading').textContent).toBe('false')
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+
+      await waitFor(() =>
+        expect(screen.getByTestId('amount').textContent).toBe('2'),
+      )
+    })
+
+    test('useQuery does not refetch when refetchOnMountOrArgChange: NUMBER condition is not met', async () => {
+      let data, isLoading, isFetching
+      function User() {
+        ;({ data, isLoading, isFetching } =
+          api.endpoints.getIncrementedAmount.useQuery(undefined, {
+            refetchOnMountOrArgChange: 10,
+          }))
+        return (
+          <div>
+            <div data-testid="isLoading">{String(isLoading)}</div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <div data-testid="amount">{String(data?.amount)}</div>
+          </div>
+        )
+      }
+
+      const { unmount } = render(<User />, { wrapper: storeRef.wrapper })
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+      )
+
+      await waitFor(() =>
+        expect(screen.getByTestId('amount').textContent).toBe('1'),
+      )
+
+      unmount()
+
+      render(<User />, { wrapper: storeRef.wrapper })
+      // Let's make sure we actually fetch, and we increment. Should be false because we do this immediately
+      // and the condition is set to 10 seconds
+      expect(screen.getByTestId('isFetching').textContent).toBe('false')
+      await waitFor(() =>
+        expect(screen.getByTestId('amount').textContent).toBe('1'),
+      )
+    })
+
+    test('useQuery refetches when refetchOnMountOrArgChange: NUMBER condition is met', async () => {
+      let data, isLoading, isFetching
+      function User() {
+        ;({ data, isLoading, isFetching } =
+          api.endpoints.getIncrementedAmount.useQuery(undefined, {
+            refetchOnMountOrArgChange: 0.5,
+          }))
+        return (
+          <div>
+            <div data-testid="isLoading">{String(isLoading)}</div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <div data-testid="amount">{String(data?.amount)}</div>
+          </div>
+        )
+      }
+
+      const { unmount } = render(<User />, { wrapper: storeRef.wrapper })
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+      )
+
+      await waitFor(() =>
+        expect(screen.getByTestId('amount').textContent).toBe('1'),
+      )
+
+      unmount()
+
+      // Wait to make sure we've passed the `refetchOnMountOrArgChange` value
+      await waitMs(510)
+
+      render(<User />, { wrapper: storeRef.wrapper })
+      // Let's make sure we actually fetch, and we increment
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+
+      await waitFor(() =>
+        expect(screen.getByTestId('amount').textContent).toBe('2'),
+      )
+    })
+
+    test('refetchOnMountOrArgChange works as expected when changing skip from false->true', async () => {
+      let data, isLoading, isFetching
+      function User() {
+        const [skip, setSkip] = useState(true)
+        ;({ data, isLoading, isFetching } =
+          api.endpoints.getIncrementedAmount.useQuery(undefined, {
+            refetchOnMountOrArgChange: 0.5,
+            skip,
+          }))
+
+        return (
+          <div>
+            <div data-testid="isLoading">{String(isLoading)}</div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <div data-testid="amount">{String(data?.amount)}</div>
+            <button onClick={() => setSkip((prev) => !prev)}>
+              change skip
+            </button>
+            ;
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      expect(screen.getByTestId('isLoading').textContent).toBe('false')
+      expect(screen.getByTestId('amount').textContent).toBe('undefined')
+
+      fireEvent.click(screen.getByText('change skip'))
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+
+      await waitFor(() =>
+        expect(screen.getByTestId('amount').textContent).toBe('1'),
+      )
+    })
+
+    test('refetchOnMountOrArgChange works as expected when changing skip from false->true with a cached query', async () => {
+      // 1. we need to mount a skipped query, then toggle skip to generate a cached result
+      // 2. we need to mount a skipped component after that, then toggle skip as well. should pull from the cache.
+      // 3. we need to mount another skipped component, then toggle skip after the specified duration and expect the time condition to be satisfied
+
+      let data, isLoading, isFetching
+      function User() {
+        const [skip, setSkip] = useState(true)
+        ;({ data, isLoading, isFetching } =
+          api.endpoints.getIncrementedAmount.useQuery(undefined, {
+            skip,
+            refetchOnMountOrArgChange: 0.5,
+          }))
+
+        return (
+          <div>
+            <div data-testid="isLoading">{String(isLoading)}</div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <div data-testid="amount">{String(data?.amount)}</div>
+            <button onClick={() => setSkip((prev) => !prev)}>
+              change skip
+            </button>
+            ;
+          </div>
+        )
+      }
+
+      let { unmount } = render(<User />, { wrapper: storeRef.wrapper })
+
+      expect(screen.getByTestId('isFetching').textContent).toBe('false')
+
+      // skipped queries do nothing by default, so we need to toggle that to get a cached result
+      fireEvent.click(screen.getByText('change skip'))
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+
+      await waitFor(() => {
+        expect(screen.getByTestId('amount').textContent).toBe('1')
+        expect(screen.getByTestId('isFetching').textContent).toBe('false')
+      })
+
+      unmount()
+
+      await waitMs(100)
+
+      // This will pull from the cache as the time criteria is not met.
+      ;({ unmount } = render(<User />, {
+        wrapper: storeRef.wrapper,
+      }))
+
+      // skipped queries return nothing
+      expect(screen.getByTestId('isFetching').textContent).toBe('false')
+      expect(screen.getByTestId('amount').textContent).toBe('undefined')
+
+      // toggle skip -> true... won't refetch as the time critera is not met, and just loads the cached values
+      fireEvent.click(screen.getByText('change skip'))
+      expect(screen.getByTestId('isFetching').textContent).toBe('false')
+      expect(screen.getByTestId('amount').textContent).toBe('1')
+
+      unmount()
+
+      await waitMs(500)
+      ;({ unmount } = render(<User />, {
+        wrapper: storeRef.wrapper,
+      }))
+
+      // toggle skip -> true... will cause a refetch as the time criteria is now satisfied
+      fireEvent.click(screen.getByText('change skip'))
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+
+      await waitFor(() =>
+        expect(screen.getByTestId('amount').textContent).toBe('2'),
+      )
+    })
+
+    test(`useQuery refetches when query args object changes even if serialized args don't change`, async () => {
+      const user = userEvent.setup()
+
+      function ItemList() {
+        const [pageNumber, setPageNumber] = useState(0)
+        const { data = [] } = api.useListItemsQuery({
+          pageNumber,
+        })
+
+        const renderedItems = data.map((item) => (
+          <li key={item.id}>ID: {item.id}</li>
+        ))
+        return (
+          <div>
+            <button onClick={() => setPageNumber(pageNumber + 1)}>
+              Next Page
+            </button>
+            <ul>{renderedItems}</ul>
+          </div>
+        )
+      }
+
+      render(<ItemList />, { wrapper: storeRef.wrapper })
+
+      await screen.findByText('ID: 0')
+
+      await user.click(screen.getByText('Next Page'))
+
+      await screen.findByText('ID: 3')
+    })
+
+    test(`useQuery shouldn't call args serialization if request skipped`, async () => {
+      expect(() =>
+        renderHook(() => api.endpoints.queryWithDeepArg.useQuery(skipToken), {
+          wrapper: storeRef.wrapper,
+        }),
+      ).not.toThrow()
+    })
+
+    test(`useQuery gracefully handles bigint types`, async () => {
+      const user = userEvent.setup()
+
+      function ItemList() {
+        const [pageNumber, setPageNumber] = useState(0)
+        const { data = [] } = api.useListItemsQuery({
+          pageNumber: BigInt(pageNumber),
+        })
+
+        const renderedItems = data.map((item) => (
+          <li key={item.id}>ID: {item.id}</li>
+        ))
+        return (
+          <div>
+            <button onClick={() => setPageNumber(pageNumber + 1)}>
+              Next Page
+            </button>
+            <ul>{renderedItems}</ul>
+          </div>
+        )
+      }
+
+      render(<ItemList />, { wrapper: storeRef.wrapper })
+
+      await screen.findByText('ID: 0')
+
+      await user.click(screen.getByText('Next Page'))
+
+      await screen.findByText('ID: 3')
+    })
+
+    describe('api.util.resetApiState resets hook', () => {
+      test('without `selectFromResult`', async () => {
+        const { result } = renderHook(() => api.endpoints.getUser.useQuery(5), {
+          wrapper: storeRef.wrapper,
+        })
+
+        await waitFor(() => expect(result.current.isSuccess).toBe(true))
+
+        act(() => void storeRef.store.dispatch(api.util.resetApiState()))
+
+        expect(result.current).toEqual(
+          expect.objectContaining({
+            isError: false,
+            isFetching: true,
+            isLoading: true,
+            isSuccess: false,
+            isUninitialized: false,
+            refetch: expect.any(Function),
+            status: 'pending',
+          }),
+        )
+      })
+      test('with `selectFromResult`', async () => {
+        const selectFromResult = vi.fn((x) => x)
+        const { result } = renderHook(
+          () => api.endpoints.getUser.useQuery(5, { selectFromResult }),
+          {
+            wrapper: storeRef.wrapper,
+          },
+        )
+
+        await waitFor(() => expect(result.current.isSuccess).toBe(true))
+        selectFromResult.mockClear()
+        act(() => {
+          storeRef.store.dispatch(api.util.resetApiState())
+        })
+
+        expect(selectFromResult).toHaveBeenNthCalledWith(1, {
+          isError: false,
+          isFetching: false,
+          isLoading: false,
+          isSuccess: false,
+          isUninitialized: true,
+          status: 'uninitialized',
+        })
+      })
+
+      test('hook should not be stuck loading post resetApiState after re-render', async () => {
+        const user = userEvent.setup()
+
+        function QueryComponent() {
+          const { isLoading, data } = api.endpoints.getUser.useQuery(1)
+
+          if (isLoading) {
+            return <p>Loading...</p>
+          }
+
+          return <p>{data?.name}</p>
+        }
+
+        function Wrapper() {
+          const [open, setOpen] = useState(true)
+
+          const handleRerender = () => {
+            setOpen(false)
+            setTimeout(() => {
+              setOpen(true)
+            }, 250)
+          }
+
+          const handleReset = () => {
+            storeRef.store.dispatch(api.util.resetApiState())
+          }
+
+          return (
+            <>
+              <button onClick={handleRerender} aria-label="Rerender component">
+                Rerender
+              </button>
+              {open ? (
+                <div>
+                  <button onClick={handleReset} aria-label="Reset API state">
+                    Reset
+                  </button>
+
+                  <QueryComponent />
+                </div>
+              ) : null}
+            </>
+          )
+        }
+
+        render(<Wrapper />, { wrapper: storeRef.wrapper })
+
+        await user.click(
+          screen.getByRole('button', { name: /Rerender component/i }),
+        )
+        await waitFor(() => {
+          expect(screen.getByText('Timmy')).toBeTruthy()
+        })
+
+        await user.click(
+          screen.getByRole('button', { name: /reset api state/i }),
+        )
+        await waitFor(() => {
+          expect(screen.queryByText('Loading...')).toBeNull()
+        })
+        await waitFor(() => {
+          expect(screen.getByText('Timmy')).toBeTruthy()
+        })
+      })
+    })
+
+    test('useQuery refetch method returns a promise that resolves with the result', async () => {
+      const { result } = renderHook(
+        () => api.endpoints.getIncrementedAmount.useQuery(),
+        {
+          wrapper: storeRef.wrapper,
+        },
+      )
+
+      await waitFor(() => expect(result.current.isSuccess).toBe(true))
+      const originalAmount = result.current.data!.amount
+
+      const { refetch } = result.current
+
+      let resPromise: ReturnType<typeof refetch> = null as any
+      await act(async () => {
+        resPromise = refetch()
+      })
+      expect(resPromise).toBeInstanceOf(Promise)
+      const res = await act(() => resPromise)
+      expect(res.data!.amount).toBeGreaterThan(originalAmount)
+    })
+
+    // See https://github.com/reduxjs/redux-toolkit/issues/4267 - Memory leak in useQuery rapid query arg changes
+    test('Hook subscriptions are properly cleaned up when query is fulfilled/rejected', async () => {
+      // This is imported already, but it seems to be causing issues with the test on certain matrixes
+
+      const pokemonApi = createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
+        endpoints: (builder) => ({
+          getTest: builder.query<string, number>({
+            async queryFn() {
+              await new Promise((resolve) => setTimeout(resolve, 1000))
+              return { data: 'data!' }
+            },
+            keepUnusedDataFor: 0,
+          }),
+        }),
+      })
+
+      const storeRef = setupApiStore(pokemonApi, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      const checkNumQueries = (count: number) => {
+        const cacheEntries = Object.keys(storeRef.store.getState().api.queries)
+        const queries = cacheEntries.length
+
+        expect(queries).toBe(count)
+      }
+
+      let i = 0
+
+      function User() {
+        const [fetchTest, { isFetching, isUninitialized }] =
+          pokemonApi.endpoints.getTest.useLazyQuery()
+
+        return (
+          <div>
+            <div data-testid="isUninitialized">{String(isUninitialized)}</div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <button data-testid="fetchButton" onClick={() => fetchTest(i++)}>
+              fetchUser
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+      fireEvent.click(screen.getByTestId('fetchButton'))
+      fireEvent.click(screen.getByTestId('fetchButton'))
+      fireEvent.click(screen.getByTestId('fetchButton'))
+      checkNumQueries(3)
+
+      await act(async () => {
+        await delay(1500)
+      })
+
+      // There should only be one stored query once they have had time to resolve
+      checkNumQueries(1)
+    })
+
+    // See https://github.com/reduxjs/redux-toolkit/issues/3182
+    test('Hook subscriptions are properly cleaned up when changing skip back and forth', async () => {
+      const pokemonApi = createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
+        endpoints: (builder) => ({
+          getPokemonByName: builder.query({
+            queryFn: (name: string) => ({ data: null }),
+            keepUnusedDataFor: 1,
+          }),
+        }),
+      })
+
+      const storeRef = setupApiStore(pokemonApi, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      const checkNumSubscriptions = (arg: string, count: number) => {
+        const subscriptions = getSubscriptions()
+        const cacheKeyEntry = subscriptions.get(arg)
+
+        if (cacheKeyEntry) {
+          const subscriptionCount = Object.keys(cacheKeyEntry) //getSubscriptionCount(arg)
+          expect(subscriptionCount).toBe(count)
+        }
+      }
+
+      // 1) Initial state: an active subscription
+      const { rerender, unmount } = renderHook(
+        ([arg, options]: Parameters<
+          typeof pokemonApi.useGetPokemonByNameQuery
+        >) => pokemonApi.useGetPokemonByNameQuery(arg, options),
+        {
+          wrapper: storeRef.wrapper,
+          initialProps: ['a'],
+        },
+      )
+
+      await act(async () => {
+        await waitMs(1)
+      })
+
+      // 2) Set the current subscription to `{skip: true}
+      rerender(['a', { skip: true }])
+
+      // 3) Change _both_ the cache key _and_ `{skip: false}` at the same time.
+      // This causes the `subscriptionRemoved` check to be `true`.
+      rerender(['b'])
+
+      // There should only be one active subscription after changing the arg
+      checkNumSubscriptions('b', 1)
+
+      // 4) Re-render with the same arg.
+      // This causes the `subscriptionRemoved` check to be `false`.
+      // Correct behavior is this does _not_ clear the promise ref,
+      // so
+      rerender(['b'])
+
+      // There should only be one active subscription after changing the arg
+      checkNumSubscriptions('b', 1)
+
+      await act(async () => {
+        await waitMs(1)
+      })
+
+      unmount()
+
+      await act(async () => {
+        await waitMs(1)
+      })
+
+      // There should be no subscription entries left over after changing
+      // cache key args and swapping `skip` on and off
+      checkNumSubscriptions('b', 0)
+
+      const finalSubscriptions = getSubscriptions()
+
+      for (const cacheKeyEntry of Object.values(finalSubscriptions)) {
+        expect(Object.values(cacheKeyEntry!).length).toBe(0)
+      }
+    })
+
+    test('Hook subscription failures do not reset isLoading state', async () => {
+      const states: boolean[] = []
+
+      function Parent() {
+        const { isLoading } = api.endpoints.getUserAndForceError.useQuery(1)
+
+        // Collect loading states to verify that it does not revert back to true.
+        states.push(isLoading)
+
+        // Parent conditionally renders child when loading.
+        if (isLoading) return null
+
+        return <Child />
+      }
+
+      function Child() {
+        // Using the same args as the parent
+        api.endpoints.getUserAndForceError.useQuery(1)
+
+        return null
+      }
+
+      render(<Parent />, { wrapper: storeRef.wrapper })
+
+      expect(states).toHaveLength(2)
+
+      // Allow at least three state effects to hit.
+      // Trying to see if any [true, false, true] occurs.
+      await act(async () => {
+        await waitForFakeTimer(150)
+      })
+
+      expect(states).toHaveLength(4)
+
+      await act(async () => {
+        await waitForFakeTimer(150)
+      })
+
+      expect(states).toHaveLength(5)
+
+      await act(async () => {
+        await waitForFakeTimer(150)
+      })
+
+      expect(states).toHaveLength(5)
+
+      // Find if at any time the isLoading state has reverted
+      // E.G.: `[..., true, false, ..., true]`
+      //              ^^^^  ^^^^^       ^^^^
+      const firstTrue = states.indexOf(true)
+      const firstFalse = states.slice(firstTrue).indexOf(false)
+      const revertedState = states.slice(firstFalse).indexOf(true)
+
+      expect(
+        revertedState,
+        `Expected isLoading state to never revert back to true but did after ${revertedState} renders...`,
+      ).toBe(-1)
+    })
+
+    test('query thunk should be aborted when component unmounts and cache entry is removed', async () => {
+      let abortSignalFromQueryFn: AbortSignal | undefined
+
+      const pokemonApi = createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
+        endpoints: (builder) => ({
+          getTest: builder.query<string, number>({
+            async queryFn(arg, { signal }) {
+              abortSignalFromQueryFn = signal
+
+              // Simulate a long-running request that should be aborted
+              await new Promise((resolve, reject) => {
+                const timeout = setTimeout(resolve, 5000)
+
+                signal.addEventListener('abort', () => {
+                  clearTimeout(timeout)
+                  reject(new Error('Aborted'))
+                })
+              })
+
+              return { data: 'data!' }
+            },
+            keepUnusedDataFor: 0.01, // Very short timeout (10ms)
+          }),
+        }),
+      })
+
+      const storeRef = setupApiStore(pokemonApi, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      function TestComponent() {
+        const { data, isFetching } = pokemonApi.endpoints.getTest.useQuery(1)
+
+        return (
+          <div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <div data-testid="data">{data || 'no data'}</div>
+          </div>
+        )
+      }
+
+      function App() {
+        const [showComponent, setShowComponent] = useState(true)
+
+        return (
+          <div>
+            {showComponent && <TestComponent />}
+            <button
+              data-testid="unmount"
+              onClick={() => setShowComponent(false)}
+            >
+              Unmount Component
+            </button>
+          </div>
+        )
+      }
+
+      render(<App />, { wrapper: storeRef.wrapper })
+
+      // Wait for the query to start
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+
+      // Verify we have an abort signal
+      expect(abortSignalFromQueryFn).toBeDefined()
+      expect(abortSignalFromQueryFn!.aborted).toBe(false)
+
+      // Unmount the component
+      fireEvent.click(screen.getByTestId('unmount'))
+
+      // Wait for the cache entry to be removed (keepUnusedDataFor: 0.01s = 10ms)
+      await act(async () => {
+        await delay(100)
+      })
+
+      // The abort signal should now be aborted
+      expect(abortSignalFromQueryFn!.aborted).toBe(true)
+    })
+
+    describe('Hook middleware requirements', () => {
+      const consoleErrorSpy = vi
+        .spyOn(console, 'error')
+        .mockImplementation(noop)
+
+      afterEach(() => {
+        consoleErrorSpy.mockClear()
+      })
+
+      afterAll(() => {
+        consoleErrorSpy.mockRestore()
+      })
+
+      test('Throws error if middleware is not added to the store', async () => {
+        const store = configureStore({
+          reducer: {
+            [api.reducerPath]: api.reducer,
+          },
+        })
+
+        const doRender = () => {
+          renderHook(() => api.endpoints.getIncrementedAmount.useQuery(), {
+            wrapper: withProvider(store),
+          })
+        }
+
+        expect(doRender).toThrowError(
+          /Warning: Middleware for RTK-Query API at reducerPath "api" has not been added to the store/,
+        )
+      })
+    })
+  })
+
+  describe('useLazyQuery', () => {
+    let data: any
+
+    afterEach(() => {
+      data = undefined
+    })
+
+    let getRenderCount: () => number = () => 0
+    test('useLazyQuery does not automatically fetch when mounted and has undefined data', async () => {
+      function User() {
+        const [fetchUser, { data: hookData, isFetching, isUninitialized }] =
+          api.endpoints.getUser.useLazyQuery()
+        getRenderCount = useRenderCounter()
+
+        data = hookData
+
+        return (
+          <div>
+            <div data-testid="isUninitialized">{String(isUninitialized)}</div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <button data-testid="fetchButton" onClick={() => fetchUser(1)}>
+              fetchUser
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+      expect(getRenderCount()).toBe(1)
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isUninitialized').textContent).toBe('true'),
+      )
+      await waitFor(() => expect(data).toBeUndefined())
+
+      fireEvent.click(screen.getByTestId('fetchButton'))
+      expect(getRenderCount()).toBe(2)
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isUninitialized').textContent).toBe('false'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+      expect(getRenderCount()).toBe(3)
+
+      fireEvent.click(screen.getByTestId('fetchButton'))
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+      expect(getRenderCount()).toBe(5)
+    })
+
+    test('useLazyQuery accepts updated subscription options and only dispatches updateSubscriptionOptions when values are updated', async () => {
+      let interval = 1000
+      function User() {
+        const [options, setOptions] = useState<SubscriptionOptions>()
+        const [fetchUser, { data: hookData, isFetching, isUninitialized }] =
+          api.endpoints.getUser.useLazyQuery(options)
+        getRenderCount = useRenderCounter()
+
+        data = hookData
+
+        return (
+          <div>
+            <div data-testid="isUninitialized">{String(isUninitialized)}</div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+
+            <button data-testid="fetchButton" onClick={() => fetchUser(1)}>
+              fetchUser
+            </button>
+            <button
+              data-testid="updateOptions"
+              onClick={() =>
+                setOptions({
+                  pollingInterval: interval,
+                })
+              }
+            >
+              updateOptions
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+      expect(getRenderCount()).toBe(1) // hook mount
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isUninitialized').textContent).toBe('true'),
+      )
+      await waitFor(() => expect(data).toBeUndefined())
+
+      fireEvent.click(screen.getByTestId('fetchButton'))
+      expect(getRenderCount()).toBe(2)
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+      expect(getRenderCount()).toBe(3)
+
+      fireEvent.click(screen.getByTestId('updateOptions')) // setState = 1
+      expect(getRenderCount()).toBe(4)
+
+      fireEvent.click(screen.getByTestId('fetchButton')) // perform new request = 2
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+      expect(getRenderCount()).toBe(6)
+
+      interval = 1000
+
+      fireEvent.click(screen.getByTestId('updateOptions')) // setState = 1
+      expect(getRenderCount()).toBe(7)
+
+      fireEvent.click(screen.getByTestId('fetchButton'))
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+      expect(getRenderCount()).toBe(9)
+
+      expect(
+        actions.filter(api.internalActions.updateSubscriptionOptions.match),
+      ).toHaveLength(1)
+    })
+
+    test('useLazyQuery accepts updated args and unsubscribes the original query', async () => {
+      function User() {
+        const [fetchUser, { data: hookData, isFetching, isUninitialized }] =
+          api.endpoints.getUser.useLazyQuery()
+
+        data = hookData
+
+        return (
+          <div>
+            <div data-testid="isUninitialized">{String(isUninitialized)}</div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+
+            <button data-testid="fetchUser1" onClick={() => fetchUser(1)}>
+              fetchUser1
+            </button>
+            <button data-testid="fetchUser2" onClick={() => fetchUser(2)}>
+              fetchUser2
+            </button>
+          </div>
+        )
+      }
+
+      const { unmount } = render(<User />, { wrapper: storeRef.wrapper })
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isUninitialized').textContent).toBe('true'),
+      )
+      await waitFor(() => expect(data).toBeUndefined())
+
+      fireEvent.click(screen.getByTestId('fetchUser1'))
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+
+      // Being that there is only the initial query, no unsubscribe should be dispatched
+      expect(
+        actions.filter(api.internalActions.unsubscribeQueryResult.match),
+      ).toHaveLength(0)
+
+      fireEvent.click(screen.getByTestId('fetchUser2'))
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+
+      expect(
+        actions.filter(api.internalActions.unsubscribeQueryResult.match),
+      ).toHaveLength(1)
+
+      fireEvent.click(screen.getByTestId('fetchUser1'))
+
+      expect(
+        actions.filter(api.internalActions.unsubscribeQueryResult.match),
+      ).toHaveLength(2)
+
+      // we always unsubscribe the original promise and create a new one
+      fireEvent.click(screen.getByTestId('fetchUser1'))
+      expect(
+        actions.filter(api.internalActions.unsubscribeQueryResult.match),
+      ).toHaveLength(3)
+
+      unmount()
+
+      // We unsubscribe after the component unmounts
+      expect(
+        actions.filter(api.internalActions.unsubscribeQueryResult.match),
+      ).toHaveLength(4)
+    })
+
+    test('useLazyQuery hook callback returns various properties to handle the result', async () => {
+      const user = userEvent.setup()
+
+      function User() {
+        const [getUser] = api.endpoints.getUser.useLazyQuery()
+        const [{ successMsg, errMsg, isAborted }, setValues] = useState({
+          successMsg: '',
+          errMsg: '',
+          isAborted: false,
+        })
+
+        const handleClick = (abort: boolean) => async () => {
+          const res = getUser(1)
+
+          // abort the query immediately to force an error
+          if (abort) res.abort()
+          res
+            .unwrap()
+            .then((result) => {
+              setValues({
+                successMsg: `Successfully fetched user ${result.name}`,
+                errMsg: '',
+                isAborted: false,
+              })
+            })
+            .catch((err) => {
+              setValues({
+                successMsg: '',
+                errMsg: `An error has occurred fetching userId: ${res.arg}`,
+                isAborted: err.name === 'AbortError',
+              })
+            })
+        }
+
+        return (
+          <div>
+            <button onClick={handleClick(false)}>
+              Fetch User successfully
+            </button>
+            <button onClick={handleClick(true)}>Fetch User and abort</button>
+            <div>{successMsg}</div>
+            <div>{errMsg}</div>
+            <div>{isAborted ? 'Request was aborted' : ''}</div>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+      expect(screen.queryByText(/An error has occurred/i)).toBeNull()
+      expect(screen.queryByText(/Successfully fetched user/i)).toBeNull()
+      expect(screen.queryByText('Request was aborted')).toBeNull()
+
+      fireEvent.click(
+        screen.getByRole('button', { name: 'Fetch User and abort' }),
+      )
+      await screen.findByText('An error has occurred fetching userId: 1')
+      expect(screen.queryByText(/Successfully fetched user/i)).toBeNull()
+      screen.getByText('Request was aborted')
+
+      await user.click(
+        screen.getByRole('button', { name: 'Fetch User successfully' }),
+      )
+
+      await screen.findByText('Successfully fetched user Timmy')
+      expect(screen.queryByText(/An error has occurred/i)).toBeNull()
+      expect(screen.queryByText('Request was aborted')).toBeNull()
+    })
+
+    // Based on issue #5079, which I couldn't reproduce but we might as well capture
+    test('useLazyQuery calling abort() multiple times does not throw an error', async () => {
+      const user = userEvent.setup()
+
+      // Create a fresh API instance with fetchBaseQuery and timeout, matching the user's example
+      const timeoutApi = createApi({
+        baseQuery: fetchBaseQuery({
+          baseUrl: 'https://example.com',
+          timeout: 5000,
+        }),
+        endpoints: (builder) => ({
+          getData: builder.query<string, void>({
+            query: () => ({ url: '/data/' }),
+          }),
+        }),
+      })
+
+      const timeoutStoreRef = setupApiStore(timeoutApi, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      // Set up a mock handler for the endpoint
+      server.use(
+        http.get('https://example.com/data/', async () => {
+          await delay(100)
+          return HttpResponse.json('test data')
+        }),
+      )
+
+      function Component() {
+        const [trigger] = timeoutApi.endpoints.getData.useLazyQuery()
+        const abortRef = useRef<(() => void) | undefined>(undefined)
+        const [errorMsg, setErrorMsg] = useState('')
+
+        const handleChange = () => {
+          // Abort any previous request
+          abortRef.current?.()
+
+          // Trigger new request
+          const result = trigger()
+
+          // Store abort function for next call
+          abortRef.current = () => {
+            try {
+              result.abort()
+            } catch (err: any) {
+              setErrorMsg(err.message)
+            }
+          }
+        }
+
+        return (
+          <div>
+            <input data-testid="input" onChange={handleChange} />
+            <div data-testid="error">{errorMsg}</div>
+          </div>
+        )
+      }
+
+      render(<Component />, { wrapper: timeoutStoreRef.wrapper })
+
+      const input = screen.getByTestId('input')
+
+      // Trigger multiple rapid changes that will call abort() multiple times
+      await user.type(input, 'abc')
+
+      // Wait a bit to ensure any errors would have been caught
+      await waitMs(200)
+
+      // Should not have any error messages
+      expect(screen.getByTestId('error').textContent).toBe('')
+    })
+
+    test('unwrapping the useLazyQuery trigger result does not throw on ConditionError and instead returns the aggregate error', async () => {
+      function User() {
+        const [getUser, { data, error }] =
+          api.endpoints.getUserAndForceError.useLazyQuery()
+
+        const [unwrappedError, setUnwrappedError] = useState<any>()
+
+        const handleClick = async () => {
+          const res = getUser(1)
+
+          try {
+            await res.unwrap()
+          } catch (error) {
+            setUnwrappedError(error)
+          }
+        }
+
+        return (
+          <div>
+            <button onClick={handleClick}>Fetch User</button>
+            <div data-testid="result">{JSON.stringify(data)}</div>
+            <div data-testid="error">{JSON.stringify(error)}</div>
+            <div data-testid="unwrappedError">
+              {JSON.stringify(unwrappedError)}
+            </div>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      const fetchButton = screen.getByRole('button', { name: 'Fetch User' })
+      fireEvent.click(fetchButton)
+      fireEvent.click(fetchButton) // This technically dispatches a ConditionError, but we don't want to see that here. We want the real error to resolve.
+
+      await waitFor(() => {
+        const errorResult = screen.getByTestId('error')?.textContent
+        const unwrappedErrorResult =
+          screen.getByTestId('unwrappedError')?.textContent
+
+        if (errorResult && unwrappedErrorResult) {
+          expect(JSON.parse(errorResult)).toMatchObject({
+            status: 500,
+            data: null,
+          })
+          expect(JSON.parse(unwrappedErrorResult)).toMatchObject(
+            JSON.parse(errorResult),
+          )
+        }
+      })
+
+      expect(screen.getByTestId('result').textContent).toBe('')
+    })
+
+    test('useLazyQuery does not throw on ConditionError and instead returns the aggregate result', async () => {
+      function User() {
+        const [getUser, { data, error }] = api.endpoints.getUser.useLazyQuery()
+
+        const [unwrappedResult, setUnwrappedResult] = useState<
+          undefined | { name: string }
+        >()
+
+        const handleClick = async () => {
+          const res = getUser(1)
+
+          const result = await res.unwrap()
+          setUnwrappedResult(result)
+        }
+
+        return (
+          <div>
+            <button onClick={handleClick}>Fetch User</button>
+            <div data-testid="result">{JSON.stringify(data)}</div>
+            <div data-testid="error">{JSON.stringify(error)}</div>
+            <div data-testid="unwrappedResult">
+              {JSON.stringify(unwrappedResult)}
+            </div>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      const fetchButton = screen.getByRole('button', { name: 'Fetch User' })
+      fireEvent.click(fetchButton)
+      fireEvent.click(fetchButton) // This technically dispatches a ConditionError, but we don't want to see that here. We want the real result to resolve and ignore the error.
+
+      await waitFor(() => {
+        const dataResult = screen.getByTestId('error')?.textContent
+        const unwrappedDataResult =
+          screen.getByTestId('unwrappedResult')?.textContent
+
+        if (dataResult && unwrappedDataResult) {
+          expect(JSON.parse(dataResult)).toMatchObject({
+            name: 'Timmy',
+          })
+          expect(JSON.parse(unwrappedDataResult)).toMatchObject(
+            JSON.parse(dataResult),
+          )
+        }
+      })
+
+      expect(screen.getByTestId('error').textContent).toBe('')
+    })
+
+    test('useLazyQuery trigger promise returns the correctly updated data', async () => {
+      const user = userEvent.setup()
+
+      const LazyUnwrapUseEffect = () => {
+        const [triggerGetIncrementedAmount, { isFetching, isSuccess, data }] =
+          api.endpoints.getIncrementedAmount.useLazyQuery()
+
+        type AmountData = { amount: number } | undefined
+
+        const [triggerUpdate] = api.endpoints.triggerUpdatedAmount.useMutation()
+
+        const [dataFromQuery, setDataFromQuery] =
+          useState<AmountData>(undefined)
+        const [dataFromTrigger, setDataFromTrigger] =
+          useState<AmountData>(undefined)
+
+        const handleLoad = async () => {
+          try {
+            const res = await triggerGetIncrementedAmount().unwrap()
+
+            setDataFromTrigger(res) // adding client side state here will cause stale data
+          } catch (error) {
+            console.error('Error handling increment trigger', error)
+          }
+        }
+
+        const handleMutate = async () => {
+          try {
+            await triggerUpdate()
+            // Force the lazy trigger to refetch
+            await handleLoad()
+          } catch (error) {
+            console.error('Error handling mutate trigger', error)
+          }
+        }
+
+        useEffect(() => {
+          // Intentionally copy to local state for comparison purposes
+          setDataFromQuery(data)
+        }, [data])
+
+        let content: React.ReactNode | null = null
+
+        if (isFetching) {
+          content = <div className="loading">Loading</div>
+        } else if (isSuccess) {
+          content = (
+            <div className="wrapper">
+              <div>
+                useEffect data: {dataFromQuery?.amount ?? 'No query amount'}
+              </div>
+              <div>
+                Unwrap data: {dataFromTrigger?.amount ?? 'No trigger amount'}
+              </div>
+            </div>
+          )
+        }
+
+        return (
+          <div className="outer">
+            <button onClick={() => handleLoad()}>Load Data</button>
+            <button onClick={() => handleMutate()}>Update Data</button>
+            {content}
+          </div>
+        )
+      }
+
+      render(<LazyUnwrapUseEffect />, { wrapper: storeRef.wrapper })
+
+      // Kick off the initial fetch via lazy query trigger
+      await user.click(screen.getByText('Load Data'))
+
+      // We get back initial data, which should get copied into local state,
+      // and also should come back as valid via the lazy trigger promise
+      await waitFor(() => {
+        expect(screen.getByText('useEffect data: 1')).toBeTruthy()
+        expect(screen.getByText('Unwrap data: 1')).toBeTruthy()
+      })
+
+      // If we mutate and then re-run the lazy trigger afterwards...
+      await user.click(screen.getByText('Update Data'))
+
+      // We should see both sets of data agree (ie, the lazy trigger promise
+      // should not return stale data or be out of sync with the hook).
+      // Prior to PR #4651, this would fail because the trigger never updated properly.
+      await waitFor(() => {
+        expect(screen.getByText('useEffect data: 2')).toBeTruthy()
+        expect(screen.getByText('Unwrap data: 2')).toBeTruthy()
+      })
+    })
+
+    test('`reset` sets state back to original state', async () => {
+      const user = userEvent.setup()
+
+      function User() {
+        const [getUser, { isSuccess, isUninitialized, reset }, _lastInfo] =
+          api.endpoints.getUser.useLazyQuery()
+
+        const handleFetchClick = async () => {
+          await getUser(1).unwrap()
+        }
+
+        return (
+          <div>
+            <span>
+              {isUninitialized
+                ? 'isUninitialized'
+                : isSuccess
+                  ? 'isSuccess'
+                  : 'other'}
+            </span>
+            <button onClick={handleFetchClick}>Fetch User</button>
+            <button onClick={reset}>Reset</button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      await screen.findByText(/isUninitialized/i)
+      expect(countObjectKeys(storeRef.store.getState().api.queries)).toBe(0)
+
+      await user.click(screen.getByRole('button', { name: 'Fetch User' }))
+
+      await screen.findByText(/isSuccess/i)
+      expect(countObjectKeys(storeRef.store.getState().api.queries)).toBe(1)
+
+      await user.click(
+        screen.getByRole('button', {
+          name: 'Reset',
+        }),
+      )
+
+      await screen.findByText(/isUninitialized/i)
+      expect(countObjectKeys(storeRef.store.getState().api.queries)).toBe(0)
+    })
+  })
+
+  describe('useInfiniteQuery', () => {
+    type Pokemon = {
+      id: string
+      name: string
+    }
+
+    const pokemonApi = createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
+      endpoints: (builder) => ({
+        getInfinitePokemon: builder.infiniteQuery<Pokemon, string, number>({
+          infiniteQueryOptions: {
+            initialPageParam: 0,
+            getNextPageParam: (
+              lastPage,
+              allPages,
+              lastPageParam,
+              allPageParams,
+            ) => lastPageParam + 1,
+            getPreviousPageParam: (
+              firstPage,
+              allPages,
+              firstPageParam,
+              allPageParams,
+            ) => {
+              return firstPageParam > 0 ? firstPageParam - 1 : undefined
+            },
+          },
+          query({ pageParam }) {
+            return `https://example.com/listItems?page=${pageParam}`
+          },
+        }),
+      }),
+    })
+
+    const pokemonApiWithRefetch = createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
+      endpoints: (builder) => ({
+        getInfinitePokemon: builder.infiniteQuery<Pokemon, string, number>({
+          infiniteQueryOptions: {
+            initialPageParam: 0,
+            getNextPageParam: (
+              lastPage,
+              allPages,
+              lastPageParam,
+              allPageParams,
+            ) => lastPageParam + 1,
+            getPreviousPageParam: (
+              firstPage,
+              allPages,
+              firstPageParam,
+              allPageParams,
+            ) => {
+              return firstPageParam > 0 ? firstPageParam - 1 : undefined
+            },
+          },
+          query({ pageParam }) {
+            return `https://example.com/listItems?page=${pageParam}`
+          },
+        }),
+      }),
+      refetchOnMountOrArgChange: true,
+    })
+
+    function PokemonList({
+      api,
+      arg = 'fire',
+      initialPageParam = 0,
+    }: {
+      api: typeof pokemonApi
+      arg?: string
+      initialPageParam?: number
+    }) {
+      const {
+        data,
+        isFetching,
+        isUninitialized,
+        fetchNextPage,
+        fetchPreviousPage,
+        refetch,
+      } = api.useGetInfinitePokemonInfiniteQuery(arg, {
+        initialPageParam,
+      })
+
+      const handlePreviousPage = async () => {
+        const res = await fetchPreviousPage()
+      }
+
+      const handleNextPage = async () => {
+        const res = await fetchNextPage()
+      }
+
+      const handleRefetch = async () => {
+        const res = await refetch()
+      }
+
+      return (
+        <div>
+          <div data-testid="isUninitialized">{String(isUninitialized)}</div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <div>Type: {arg}</div>
+          <div data-testid="data">
+            {data?.pages.map((page, i: number | null | undefined) => (
+              <div key={i}>{page.name}</div>
+            ))}
+          </div>
+          <button data-testid="prevPage" onClick={() => handlePreviousPage()}>
+            previousPage
+          </button>
+          <button data-testid="nextPage" onClick={() => handleNextPage()}>
+            nextPage
+          </button>
+          <button data-testid="refetch" onClick={() => handleRefetch()}>
+            refetch
+          </button>
+        </div>
+      )
+    }
+
+    beforeEach(() => {
+      server.use(
+        http.get('https://example.com/listItems', ({ request }) => {
+          const url = new URL(request.url)
+          const pageString = url.searchParams.get('page')
+          const pageNum = parseInt(pageString || '0')
+
+          const results: Pokemon = {
+            id: `${pageNum}`,
+            name: `Pokemon ${pageNum}`,
+          }
+
+          return HttpResponse.json(results)
+        }),
+      )
+    })
+
+    test.each([
+      ['no refetch', pokemonApi],
+      ['with refetch', pokemonApiWithRefetch],
+    ])(`useInfiniteQuery %s`, async (_, pokemonApi) => {
+      const storeRef = setupApiStore(pokemonApi, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      const { takeRender, render, getCurrentRender } = createRenderStream({
+        snapshotDOM: true,
+      })
+
+      const checkNumQueries = (count: number) => {
+        const cacheEntries = Object.keys(storeRef.store.getState().api.queries)
+        const queries = cacheEntries.length
+
+        expect(queries).toBe(count)
+      }
+
+      const checkEntryFlags = (
+        arg: string,
+        expectedFlags: Partial<InfiniteQueryResultFlags>,
+      ) => {
+        const selector = pokemonApi.endpoints.getInfinitePokemon.select(arg)
+        const entry = selector(storeRef.store.getState())
+
+        const actualFlags: InfiniteQueryResultFlags = {
+          hasNextPage: false,
+          hasPreviousPage: false,
+          isFetchingNextPage: false,
+          isFetchingPreviousPage: false,
+          isFetchNextPageError: false,
+          isFetchPreviousPageError: false,
+          ...expectedFlags,
+        }
+
+        expect(entry).toMatchObject(actualFlags)
+      }
+
+      const checkPageRows = (
+        withinDOM: () => SyncScreen,
+        type: string,
+        ids: number[],
+      ) => {
+        expect(withinDOM().getByText(`Type: ${type}`)).toBeTruthy()
+        for (const id of ids) {
+          expect(withinDOM().getByText(`Pokemon ${id}`)).toBeTruthy()
+        }
+      }
+
+      async function waitForFetch(handleExtraMiddleRender = false) {
+        {
+          const { withinDOM } = await takeRender()
+          expect(withinDOM().getByTestId('isFetching').textContent).toBe('true')
+        }
+
+        // We seem to do an extra render when fetching an uninitialized entry
+        if (handleExtraMiddleRender) {
+          {
+            const { withinDOM } = await takeRender()
+            expect(withinDOM().getByTestId('isFetching').textContent).toBe(
+              'true',
+            )
+          }
+        }
+
+        {
+          // Second fetch complete
+          const { withinDOM } = await takeRender()
+          expect(withinDOM().getByTestId('isFetching').textContent).toBe(
+            'false',
+          )
+        }
+      }
+
+      const utils = render(<PokemonList api={pokemonApi} />, {
+        wrapper: storeRef.wrapper,
+      })
+      checkNumQueries(1)
+      checkEntryFlags('fire', {})
+      await waitForFetch(true)
+      checkNumQueries(1)
+      checkPageRows(getCurrentRender().withinDOM, 'fire', [0])
+      checkEntryFlags('fire', {
+        hasNextPage: true,
+      })
+
+      fireEvent.click(screen.getByTestId('nextPage'), {})
+      checkEntryFlags('fire', {
+        hasNextPage: true,
+        isFetchingNextPage: true,
+      })
+      await waitForFetch()
+      checkPageRows(getCurrentRender().withinDOM, 'fire', [0, 1])
+      checkEntryFlags('fire', {
+        hasNextPage: true,
+      })
+
+      fireEvent.click(screen.getByTestId('nextPage'))
+      await waitForFetch()
+      checkPageRows(getCurrentRender().withinDOM, 'fire', [0, 1, 2])
+
+      utils.rerender(
+        <PokemonList api={pokemonApi} arg="water" initialPageParam={3} />,
+      )
+      checkEntryFlags('water', {})
+      await waitForFetch(true)
+      checkNumQueries(2)
+      checkPageRows(getCurrentRender().withinDOM, 'water', [3])
+      checkEntryFlags('water', {
+        hasNextPage: true,
+        hasPreviousPage: true,
+      })
+
+      fireEvent.click(screen.getByTestId('nextPage'))
+      checkEntryFlags('water', {
+        hasNextPage: true,
+        hasPreviousPage: true,
+        isFetchingNextPage: true,
+      })
+      await waitForFetch()
+      checkPageRows(getCurrentRender().withinDOM, 'water', [3, 4])
+      checkEntryFlags('water', {
+        hasNextPage: true,
+        hasPreviousPage: true,
+      })
+
+      fireEvent.click(screen.getByTestId('prevPage'))
+      checkEntryFlags('water', {
+        hasNextPage: true,
+        hasPreviousPage: true,
+        isFetchingPreviousPage: true,
+      })
+      await waitForFetch()
+      checkPageRows(getCurrentRender().withinDOM, 'water', [2, 3, 4])
+      checkEntryFlags('water', {
+        hasNextPage: true,
+        hasPreviousPage: true,
+      })
+
+      fireEvent.click(screen.getByTestId('refetch'))
+      checkEntryFlags('water', {
+        hasNextPage: true,
+        hasPreviousPage: true,
+      })
+      await waitForFetch()
+      checkPageRows(getCurrentRender().withinDOM, 'water', [2, 3, 4])
+      checkEntryFlags('water', {
+        hasNextPage: true,
+        hasPreviousPage: true,
+      })
+    })
+
+    test('Object page params does not keep forcing refetching', async () => {
+      type Project = {
+        id: number
+        createdAt: string
+      }
+
+      type ProjectsResponse = {
+        projects: Project[]
+        numFound: number
+        serverTime: string
+      }
+
+      interface ProjectsInitialPageParam {
+        offset: number
+        limit: number
+      }
+
+      const apiWithInfiniteScroll = createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com/' }),
+        endpoints: (builder) => ({
+          projectsLimitOffset: builder.infiniteQuery<
+            ProjectsResponse,
+            void,
+            ProjectsInitialPageParam
+          >({
+            infiniteQueryOptions: {
+              initialPageParam: {
+                offset: 0,
+                limit: 20,
+              },
+              getNextPageParam: (
+                lastPage,
+                allPages,
+                lastPageParam,
+                allPageParams,
+              ) => {
+                const nextOffset = lastPageParam.offset + lastPageParam.limit
+                const remainingItems = lastPage?.numFound - nextOffset
+
+                if (remainingItems <= 0) {
+                  return undefined
+                }
+
+                return {
+                  ...lastPageParam,
+                  offset: nextOffset,
+                }
+              },
+              getPreviousPageParam: (
+                firstPage,
+                allPages,
+                firstPageParam,
+                allPageParams,
+              ) => {
+                const prevOffset = firstPageParam.offset - firstPageParam.limit
+                if (prevOffset < 0) return undefined
+
+                return {
+                  ...firstPageParam,
+                  offset: firstPageParam.offset - firstPageParam.limit,
+                }
+              },
+            },
+            query: ({ pageParam }) => {
+              const { offset, limit } = pageParam
+              return {
+                url: `https://example.com/api/projectsLimitOffset?offset=${offset}&limit=${limit}`,
+                method: 'GET',
+              }
+            },
+          }),
+        }),
+      })
+
+      const projects = Array.from({ length: 50 }, (_, i) => {
+        return {
+          id: i,
+          createdAt: Date.now() + i * 1000,
+        }
+      })
+
+      let numRequests = 0
+
+      server.use(
+        http.get(
+          'https://example.com/api/projectsLimitOffset',
+          async ({ request }) => {
+            const url = new URL(request.url)
+            const limit = parseInt(url.searchParams.get('limit') ?? '5', 10)
+            let offset = parseInt(url.searchParams.get('offset') ?? '0', 10)
+
+            numRequests++
+
+            if (isNaN(offset) || offset < 0) {
+              offset = 0
+            }
+            if (isNaN(limit) || limit <= 0) {
+              return HttpResponse.json(
+                {
+                  message:
+                    "Invalid 'limit' parameter. It must be a positive integer.",
+                } as any,
+                { status: 400 },
+              )
+            }
+
+            const result = projects.slice(offset, offset + limit)
+
+            await delay(10)
+            return HttpResponse.json({
+              projects: result,
+              serverTime: Date.now(),
+              numFound: projects.length,
+            })
+          },
+        ),
+      )
+
+      function LimitOffsetExample() {
+        const {
+          data,
+          hasPreviousPage,
+          hasNextPage,
+          error,
+          isFetching,
+          isLoading,
+          isError,
+          fetchNextPage,
+          fetchPreviousPage,
+          isFetchingNextPage,
+          isFetchingPreviousPage,
+          status,
+        } = apiWithInfiniteScroll.useProjectsLimitOffsetInfiniteQuery(
+          undefined,
+          {
+            initialPageParam: {
+              offset: 10,
+              limit: 10,
+            },
+          },
+        )
+
+        const [counter, setCounter] = useState(0)
+
+        const combinedData = useMemo(() => {
+          return data?.pages?.map((item) => item?.projects)?.flat()
+        }, [data])
+
+        return (
+          <div>
+            <h2>Limit and Offset Infinite Scroll</h2>
+            <button onClick={() => setCounter((c) => c + 1)}>Increment</button>
+            <div>Counter: {counter}</div>
+            {isLoading ? (
+              <p>Loading...</p>
+            ) : isError ? (
+              <span>Error: {error.message}</span>
+            ) : null}
+
+            <>
+              <div>
+                <button
+                  onClick={() => fetchPreviousPage()}
+                  disabled={!hasPreviousPage || isFetchingPreviousPage}
+                >
+                  {isFetchingPreviousPage
+                    ? 'Loading more...'
+                    : hasPreviousPage
+                      ? 'Load Older'
+                      : 'Nothing more to load'}
+                </button>
+              </div>
+              <div data-testid="projects">
+                {combinedData?.map((project, index, arr) => {
+                  return (
+                    <div key={project.id}>
+                      <div data-testid="project">
+                        <div>{`Project ${project.id} (created at: ${project.createdAt})`}</div>
+                      </div>
+                    </div>
+                  )
+                })}
+              </div>
+              <div>
+                <button
+                  onClick={() => fetchNextPage()}
+                  disabled={!hasNextPage || isFetchingNextPage}
+                >
+                  {isFetchingNextPage
+                    ? 'Loading more...'
+                    : hasNextPage
+                      ? 'Load Newer'
+                      : 'Nothing more to load'}
+                </button>
+              </div>
+              <div>
+                {isFetching && !isFetchingPreviousPage && !isFetchingNextPage
+                  ? 'Background Updating...'
+                  : null}
+              </div>
+            </>
+          </div>
+        )
+      }
+
+      const storeRef = setupApiStore(
+        apiWithInfiniteScroll,
+        { ...actionsReducer },
+        {
+          withoutTestLifecycles: true,
+        },
+      )
+
+      const { takeRender, render, totalRenderCount } = createRenderStream({
+        snapshotDOM: true,
+      })
+
+      render(<LimitOffsetExample />, {
+        wrapper: storeRef.wrapper,
+      })
+
+      {
+        const { withinDOM } = await takeRender()
+        withinDOM().getByText('Counter: 0')
+        withinDOM().getByText('Loading...')
+      }
+
+      {
+        const { withinDOM } = await takeRender()
+        withinDOM().getByText('Counter: 0')
+        withinDOM().getByText('Loading...')
+      }
+
+      {
+        const { withinDOM } = await takeRender()
+        withinDOM().getByText('Counter: 0')
+
+        expect(withinDOM().getAllByTestId('project').length).toBe(10)
+        expect(withinDOM().queryByTestId('Loading...')).toBeNull()
+      }
+
+      expect(totalRenderCount()).toBe(3)
+      expect(numRequests).toBe(1)
+    })
+
+    test.each([
+      ['skip token', true],
+      ['skip option', false],
+    ])(
+      'useInfiniteQuery hook does not fetch when skipped via %s',
+      async (_, useSkipToken) => {
+        function Pokemon() {
+          const [value, setValue] = useState(0)
+
+          const shouldFetch = value > 0
+
+          const arg = shouldFetch || !useSkipToken ? 'fire' : skipToken
+          const skip = useSkipToken ? undefined : shouldFetch ? undefined : true
+
+          const { isFetching } = pokemonApi.useGetInfinitePokemonInfiniteQuery(
+            arg,
+            {
+              skip,
+            },
+          )
+          getRenderCount = useRenderCounter()
+
+          return (
+            <div>
+              <div data-testid="isFetching">{String(isFetching)}</div>
+              <button onClick={() => setValue((val) => val + 1)}>
+                Increment value
+              </button>
+            </div>
+          )
+        }
+
+        render(<Pokemon />, { wrapper: storeRef.wrapper })
+        expect(getRenderCount()).toBe(1)
+
+        await waitFor(() =>
+          expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+        )
+        fireEvent.click(screen.getByText('Increment value'))
+        await waitFor(() =>
+          expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+        )
+        expect(getRenderCount()).toBe(2)
+      },
+    )
+
+    test('useInfiniteQuery hook option refetchCachedPages: false only refetches first page', async () => {
+      const storeRef = setupApiStore(pokemonApi, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      function PokemonList() {
+        const { data, fetchNextPage, refetch } =
+          pokemonApi.useGetInfinitePokemonInfiniteQuery('fire', {
+            refetchCachedPages: false,
+          })
+
+        return (
+          <div>
+            <div data-testid="data">
+              {data?.pages.map((page, i) => (
+                <div key={i} data-testid={`page-${i}`}>
+                  {page.name}
+                </div>
+              ))}
+            </div>
+            <button data-testid="nextPage" onClick={() => fetchNextPage()}>
+              Next Page
+            </button>
+            <button data-testid="refetch" onClick={() => refetch()}>
+              Refetch
+            </button>
+          </div>
+        )
+      }
+
+      render(<PokemonList />, { wrapper: storeRef.wrapper })
+
+      // Wait for initial page to load
+      await waitFor(() => {
+        expect(screen.getByTestId('page-0').textContent).toBe('Pokemon 0')
+      })
+
+      // Fetch second page
+      fireEvent.click(screen.getByTestId('nextPage'))
+      await waitFor(() => {
+        expect(screen.getByTestId('page-1').textContent).toBe('Pokemon 1')
+      })
+
+      // Fetch third page
+      fireEvent.click(screen.getByTestId('nextPage'))
+      await waitFor(() => {
+        expect(screen.getByTestId('page-2').textContent).toBe('Pokemon 2')
+      })
+
+      // Now we have 3 pages. Refetch with refetchCachedPages: false should only refetch page 0
+      fireEvent.click(screen.getByTestId('refetch'))
+
+      await waitFor(
+        () => {
+          // Should only have 1 page
+          expect(screen.queryByTestId('page-0')).toBeTruthy()
+          expect(screen.queryByTestId('page-1')).toBeNull()
+          expect(screen.queryByTestId('page-2')).toBeNull()
+        },
+        { timeout: 1000 },
+      )
+
+      // Verify we only have 1 page (not refetched all)
+      const pages = screen.getAllByTestId(/^page-/)
+      expect(pages).toHaveLength(1)
+    })
+
+    test('useInfiniteQuery refetch() method option refetchCachedPages: false only refetches first page', async () => {
+      const storeRef = setupApiStore(pokemonApi, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      function PokemonList() {
+        const { data, fetchNextPage, refetch } =
+          pokemonApi.useGetInfinitePokemonInfiniteQuery('fire')
+
+        return (
+          <div>
+            <div data-testid="data">
+              {data?.pages.map((page, i) => (
+                <div key={i} data-testid={`page-${i}`}>
+                  {page.name}
+                </div>
+              ))}
+            </div>
+            <button data-testid="nextPage" onClick={() => fetchNextPage()}>
+              Next Page
+            </button>
+            <button
+              data-testid="refetch"
+              onClick={() => refetch({ refetchCachedPages: false })}
+            >
+              Refetch
+            </button>
+          </div>
+        )
+      }
+
+      render(<PokemonList />, { wrapper: storeRef.wrapper })
+
+      // Wait for initial page to load
+      await waitFor(() => {
+        expect(screen.getByTestId('page-0').textContent).toBe('Pokemon 0')
+      })
+
+      // Fetch second page
+      fireEvent.click(screen.getByTestId('nextPage'))
+      await waitFor(() => {
+        expect(screen.getByTestId('page-1').textContent).toBe('Pokemon 1')
+      })
+
+      // Fetch third page
+      fireEvent.click(screen.getByTestId('nextPage'))
+      await waitFor(() => {
+        expect(screen.getByTestId('page-2').textContent).toBe('Pokemon 2')
+      })
+
+      // Now we have 3 pages. Refetch with refetchCachedPages: false should only refetch page 0
+      fireEvent.click(screen.getByTestId('refetch'))
+
+      await waitFor(() => {
+        // Should only have 1 page
+        expect(screen.queryByTestId('page-0')).toBeTruthy()
+        expect(screen.queryByTestId('page-1')).toBeNull()
+        expect(screen.queryByTestId('page-2')).toBeNull()
+      })
+
+      // Verify we only have 1 page (not refetched all)
+      const pages = screen.getAllByTestId(/^page-/)
+      expect(pages).toHaveLength(1)
+    })
+  })
+
+  describe('useMutation', () => {
+    test('useMutation hook sets and unsets the isLoading flag when running', async () => {
+      function User() {
+        const [updateUser, { isLoading }] =
+          api.endpoints.updateUser.useMutation()
+
+        return (
+          <div>
+            <div data-testid="isLoading">{String(isLoading)}</div>
+            <button onClick={() => updateUser({ name: 'Banana' })}>
+              Update User
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+      )
+      fireEvent.click(screen.getByText('Update User'))
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+      )
+    })
+
+    test('useMutation hook sets data to the resolved response on success', async () => {
+      const result = { name: 'Banana' }
+
+      function User() {
+        const [updateUser, { data }] = api.endpoints.updateUser.useMutation()
+
+        return (
+          <div>
+            <div data-testid="result">{JSON.stringify(data)}</div>
+            <button onClick={() => updateUser({ name: 'Banana' })}>
+              Update User
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      fireEvent.click(screen.getByText('Update User'))
+      await waitFor(() =>
+        expect(screen.getByTestId('result').textContent).toBe(
+          JSON.stringify(result),
+        ),
+      )
+    })
+
+    test('useMutation hook callback returns various properties to handle the result', async () => {
+      const user = userEvent.setup()
+
+      function User() {
+        const [updateUser] = api.endpoints.updateUser.useMutation()
+        const [successMsg, setSuccessMsg] = useState('')
+        const [errMsg, setErrMsg] = useState('')
+        const [isAborted, setIsAborted] = useState(false)
+
+        const handleClick = async () => {
+          const res = updateUser({ name: 'Banana' })
+
+          // abort the mutation immediately to force an error
+          res.abort()
+          res
+            .unwrap()
+            .then((result) => {
+              setSuccessMsg(`Successfully updated user ${result.name}`)
+            })
+            .catch((err) => {
+              setErrMsg(
+                `An error has occurred updating user ${res.arg.originalArgs.name}`,
+              )
+              if (err.name === 'AbortError') {
+                setIsAborted(true)
+              }
+            })
+        }
+
+        return (
+          <div>
+            <button onClick={handleClick}>Update User and abort</button>
+            <div>{successMsg}</div>
+            <div>{errMsg}</div>
+            <div>{isAborted ? 'Request was aborted' : ''}</div>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+      expect(screen.queryByText(/An error has occurred/i)).toBeNull()
+      expect(screen.queryByText(/Successfully updated user/i)).toBeNull()
+      expect(screen.queryByText('Request was aborted')).toBeNull()
+
+      await user.click(
+        screen.getByRole('button', { name: 'Update User and abort' }),
+      )
+      await screen.findByText('An error has occurred updating user Banana')
+      expect(screen.queryByText(/Successfully updated user/i)).toBeNull()
+      screen.getByText('Request was aborted')
+    })
+
+    test('useMutation return value contains originalArgs', async () => {
+      const { result } = renderHook(
+        () => api.endpoints.updateUser.useMutation(),
+        {
+          wrapper: storeRef.wrapper,
+        },
+      )
+      const arg = { name: 'Foo' }
+
+      const firstRenderResult = result.current
+      expect(firstRenderResult[1].originalArgs).toBe(undefined)
+      await act(async () => {
+        await firstRenderResult[0](arg)
+      })
+      const secondRenderResult = result.current
+      expect(firstRenderResult[1].originalArgs).toBe(undefined)
+      expect(secondRenderResult[1].originalArgs).toBe(arg)
+    })
+
+    test('`reset` sets state back to original state', async () => {
+      const user = userEvent.setup()
+
+      function User() {
+        const [updateUser, result] = api.endpoints.updateUser.useMutation()
+        return (
+          <>
+            <span>
+              {result.isUninitialized
+                ? 'isUninitialized'
+                : result.isSuccess
+                  ? 'isSuccess'
+                  : 'other'}
+            </span>
+            <span>{result.originalArgs?.name}</span>
+            <button onClick={() => updateUser({ name: 'Yay' })}>trigger</button>
+            <button onClick={result.reset}>reset</button>
+          </>
+        )
+      }
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      await screen.findByText(/isUninitialized/i)
+      expect(screen.queryByText('Yay')).toBeNull()
+      expect(countObjectKeys(storeRef.store.getState().api.mutations)).toBe(0)
+
+      await user.click(screen.getByRole('button', { name: 'trigger' }))
+
+      await screen.findByText(/isSuccess/i)
+      expect(screen.queryByText('Yay')).not.toBeNull()
+      expect(countObjectKeys(storeRef.store.getState().api.mutations)).toBe(1)
+
+      await user.click(screen.getByRole('button', { name: 'reset' }))
+
+      await screen.findByText(/isUninitialized/i)
+      expect(screen.queryByText('Yay')).toBeNull()
+      expect(countObjectKeys(storeRef.store.getState().api.mutations)).toBe(0)
+    })
+  })
+
+  describe('usePrefetch', () => {
+    test('usePrefetch respects force arg', async () => {
+      const user = userEvent.setup()
+
+      const { usePrefetch } = api
+      const USER_ID = 4
+      function User() {
+        const { isFetching } = api.endpoints.getUser.useQuery(USER_ID)
+        const prefetchUser = usePrefetch('getUser', { force: true })
+
+        return (
+          <div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <button
+              onMouseEnter={() => prefetchUser(USER_ID, { force: true })}
+              data-testid="highPriority"
+            >
+              High priority action intent
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      // Resolve initial query
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+
+      await user.hover(screen.getByTestId('highPriority'))
+
+      expect(
+        api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any),
+      ).toEqual({
+        data: { name: 'Timmy' },
+        endpointName: 'getUser',
+        error: undefined,
+        fulfilledTimeStamp: expect.any(Number),
+        isError: false,
+        isLoading: true,
+        isSuccess: false,
+        isUninitialized: false,
+        originalArgs: USER_ID,
+        requestId: expect.any(String),
+        startedTimeStamp: expect.any(Number),
+        status: QueryStatus.pending,
+      })
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+
+      expect(
+        api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any),
+      ).toEqual({
+        data: { name: 'Timmy' },
+        endpointName: 'getUser',
+        fulfilledTimeStamp: expect.any(Number),
+        isError: false,
+        isLoading: false,
+        isSuccess: true,
+        isUninitialized: false,
+        originalArgs: USER_ID,
+        requestId: expect.any(String),
+        startedTimeStamp: expect.any(Number),
+        status: QueryStatus.fulfilled,
+      })
+    })
+
+    test('usePrefetch does not make an additional request if already in the cache and force=false', async () => {
+      const user = userEvent.setup()
+
+      const { usePrefetch } = api
+      const USER_ID = 2
+
+      function User() {
+        // Load the initial query
+        const { isFetching } = api.endpoints.getUser.useQuery(USER_ID)
+        const prefetchUser = usePrefetch('getUser', { force: false })
+
+        return (
+          <div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <button
+              onMouseEnter={() => prefetchUser(USER_ID)}
+              data-testid="lowPriority"
+            >
+              Low priority user action intent
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      // Let the initial query resolve
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+      // Try to prefetch what we just loaded
+      await user.hover(screen.getByTestId('lowPriority'))
+
+      expect(
+        api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any),
+      ).toEqual({
+        data: { name: 'Timmy' },
+        endpointName: 'getUser',
+        fulfilledTimeStamp: expect.any(Number),
+        isError: false,
+        isLoading: false,
+        isSuccess: true,
+        isUninitialized: false,
+        originalArgs: USER_ID,
+        requestId: expect.any(String),
+        startedTimeStamp: expect.any(Number),
+        status: QueryStatus.fulfilled,
+      })
+
+      await waitMs()
+
+      expect(
+        api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any),
+      ).toEqual({
+        data: { name: 'Timmy' },
+        endpointName: 'getUser',
+        fulfilledTimeStamp: expect.any(Number),
+        isError: false,
+        isLoading: false,
+        isSuccess: true,
+        isUninitialized: false,
+        originalArgs: USER_ID,
+        requestId: expect.any(String),
+        startedTimeStamp: expect.any(Number),
+        status: QueryStatus.fulfilled,
+      })
+    })
+
+    test('usePrefetch respects ifOlderThan when it evaluates to true', async () => {
+      const user = userEvent.setup()
+
+      const { usePrefetch } = api
+      const USER_ID = 47
+
+      function User() {
+        // Load the initial query
+        const { isFetching } = api.endpoints.getUser.useQuery(USER_ID)
+        const prefetchUser = usePrefetch('getUser', { ifOlderThan: 0.2 })
+
+        return (
+          <div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <button
+              onMouseEnter={() => prefetchUser(USER_ID)}
+              data-testid="lowPriority"
+            >
+              Low priority user action intent
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+
+      // Wait 400ms, making it respect ifOlderThan
+      await waitMs(400)
+
+      // This should run the query being that we're past the threshold
+      await user.hover(screen.getByTestId('lowPriority'))
+
+      expect(
+        api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any),
+      ).toEqual({
+        data: { name: 'Timmy' },
+        endpointName: 'getUser',
+        fulfilledTimeStamp: expect.any(Number),
+        isError: false,
+        isLoading: true,
+        isSuccess: false,
+        isUninitialized: false,
+        originalArgs: USER_ID,
+        requestId: expect.any(String),
+        startedTimeStamp: expect.any(Number),
+        status: QueryStatus.pending,
+      })
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+
+      expect(
+        api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any),
+      ).toEqual({
+        data: { name: 'Timmy' },
+        endpointName: 'getUser',
+        fulfilledTimeStamp: expect.any(Number),
+        isError: false,
+        isLoading: false,
+        isSuccess: true,
+        isUninitialized: false,
+        originalArgs: USER_ID,
+        requestId: expect.any(String),
+        startedTimeStamp: expect.any(Number),
+        status: QueryStatus.fulfilled,
+      })
+    })
+
+    test('usePrefetch returns the last success result when ifOlderThan evaluates to false', async () => {
+      const user = userEvent.setup()
+
+      const { usePrefetch } = api
+      const USER_ID = 2
+
+      function User() {
+        // Load the initial query
+        const { isFetching } = api.endpoints.getUser.useQuery(USER_ID)
+        const prefetchUser = usePrefetch('getUser', { ifOlderThan: 10 })
+
+        return (
+          <div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <button
+              onMouseEnter={() => prefetchUser(USER_ID)}
+              data-testid="lowPriority"
+            >
+              Low priority user action intent
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+      await waitMs()
+
+      // Get a snapshot of the last result
+      const latestQueryData = api.endpoints.getUser.select(USER_ID)(
+        storeRef.store.getState() as any,
+      )
+
+      await user.hover(screen.getByTestId('lowPriority'))
+
+      //  Serve up the result from the cache being that the condition wasn't met
+      expect(
+        api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any),
+      ).toEqual(latestQueryData)
+    })
+
+    test('usePrefetch executes a query even if conditions fail when the cache is empty', async () => {
+      const user = userEvent.setup()
+
+      const { usePrefetch } = api
+      const USER_ID = 2
+
+      function User() {
+        const prefetchUser = usePrefetch('getUser', { ifOlderThan: 10 })
+
+        return (
+          <div>
+            <button
+              onMouseEnter={() => prefetchUser(USER_ID)}
+              data-testid="lowPriority"
+            >
+              Low priority user action intent
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      await user.hover(screen.getByTestId('lowPriority'))
+
+      expect(
+        api.endpoints.getUser.select(USER_ID)(storeRef.store.getState()),
+      ).toEqual({
+        endpointName: 'getUser',
+        isError: false,
+        isLoading: true,
+        isSuccess: false,
+        isUninitialized: false,
+        originalArgs: USER_ID,
+        requestId: expect.any(String),
+        startedTimeStamp: expect.any(Number),
+        status: 'pending',
+      })
+    })
+
+    it('should create subscription when hook mounts after prefetch', async () => {
+      const api = createApi({
+        baseQuery: async () => ({ data: 'test data' }),
+        endpoints: (build) => ({
+          getTest: build.query<string, void>({
+            query: () => '',
+          }),
+        }),
+      })
+      const storeRef = setupApiStore(api, undefined, { withoutListeners: true })
+
+      // 1. Prefetch data (no subscription)
+      await storeRef.store.dispatch(api.util.prefetch('getTest', undefined))
+
+      // Verify data is cached
+      await waitFor(() => {
+        let state = storeRef.store.getState()
+        expect(state.api.queries['getTest(undefined)']?.data).toBe('test data')
+      })
+
+      // Verify no subscription exists
+      const subscriptions = storeRef.store.dispatch(
+        api.internalActions.internal_getRTKQSubscriptions(),
+      ) as any
+      expect(subscriptions.getSubscriptionCount('getTest(undefined)')).toBe(0)
+
+      // 2. Mount component with useQuery hook
+      function TestComponent() {
+        const result = api.endpoints.getTest.useQuery()
+        return <div>{result.data}</div>
+      }
+
+      const { unmount } = render(<TestComponent />, {
+        wrapper: storeRef.wrapper,
+      })
+
+      // Wait for hook to initialize
+      await waitFor(() => {
+        // EXPECTED: Subscription should be created
+        expect(subscriptions.getSubscriptionCount('getTest(undefined)')).toBe(1)
+      })
+
+      // 3. Verify data is still available
+      let state = storeRef.store.getState()
+      expect(state.api.queries['getTest(undefined)']?.data).toBe('test data')
+
+      // 4. Unmount and verify subscription is removed
+      unmount()
+
+      await waitFor(() => {
+        expect(subscriptions.getSubscriptionCount('getTest(undefined)')).toBe(0)
+      })
+    })
+  })
+
+  describe('useQuery and useMutation invalidation behavior', () => {
+    const api = createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+      tagTypes: ['User'],
+      endpoints: (build) => ({
+        checkSession: build.query<any, void>({
+          query: () => '/me',
+          providesTags: ['User'],
+        }),
+        login: build.mutation<any, any>({
+          query: () => ({ url: '/login', method: 'POST' }),
+          invalidatesTags: ['User'],
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, { ...actionsReducer })
+    test('initially failed useQueries that provide an tag will refetch after a mutation invalidates it', async () => {
+      const checkSessionData = { name: 'matt' }
+      server.use(
+        http.get(
+          'https://example.com/me',
+          () => {
+            return HttpResponse.json(null, { status: 500 })
+          },
+          { once: true },
+        ),
+        http.get('https://example.com/me', () => {
+          return HttpResponse.json(checkSessionData)
+        }),
+        http.post('https://example.com/login', () => {
+          return HttpResponse.json(null, { status: 200 })
+        }),
+      )
+      let data, isLoading, isError
+      function User() {
+        ;({ data, isError, isLoading } = api.endpoints.checkSession.useQuery())
+        const [login, { isLoading: loginLoading }] =
+          api.endpoints.login.useMutation()
+
+        return (
+          <div>
+            <div data-testid="isLoading">{String(isLoading)}</div>
+            <div data-testid="isError">{String(isError)}</div>
+            <div data-testid="user">{JSON.stringify(data)}</div>
+            <div data-testid="loginLoading">{String(loginLoading)}</div>
+            <button onClick={() => login(null)}>Login</button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isError').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('user').textContent).toBe(''),
+      )
+
+      fireEvent.click(screen.getByRole('button', { name: /Login/i }))
+
+      await waitFor(() =>
+        expect(screen.getByTestId('loginLoading').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('loginLoading').textContent).toBe('false'),
+      )
+      // login mutation will cause the original errored out query to refire, clearing the error and setting the user
+      await waitFor(() =>
+        expect(screen.getByTestId('isError').textContent).toBe('false'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('user').textContent).toBe(
+          JSON.stringify(checkSessionData),
+        ),
+      )
+
+      const { checkSession, login } = api.endpoints
+      expect(storeRef.store.getState().actions).toMatchSequence(
+        api.internalActions.middlewareRegistered.match,
+        checkSession.matchPending,
+        checkSession.matchRejected,
+        login.matchPending,
+        login.matchFulfilled,
+        checkSession.matchPending,
+        checkSession.matchFulfilled,
+      )
+    })
+  })
+})
+
+describe('hooks with createApi defaults set', () => {
+  const defaultApi = createApi({
+    baseQuery: async (arg: any) => {
+      await waitMs()
+      if ('amount' in arg?.body) {
+        amount += 1
+      }
+      return {
+        data: arg?.body
+          ? { ...arg.body, ...(amount ? { amount } : {}) }
+          : undefined,
+      }
+    },
+    endpoints: (build) => ({
+      getIncrementedAmount: build.query<any, void>({
+        query: () => ({
+          url: '',
+          body: {
+            amount,
+          },
+        }),
+      }),
+    }),
+    refetchOnMountOrArgChange: true,
+  })
+
+  const storeRef = setupApiStore(defaultApi)
+  test('useQuery hook respects refetchOnMountOrArgChange: true when set in createApi options', async () => {
+    let data, isLoading, isFetching
+
+    function User() {
+      ;({ data, isLoading } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery())
+      return (
+        <div>
+          <div data-testid="isLoading">{String(isLoading)}</div>
+          <div data-testid="amount">{String(data?.amount)}</div>
+        </div>
+      )
+    }
+
+    const { unmount } = render(<User />, { wrapper: storeRef.wrapper })
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+
+    unmount()
+
+    function OtherUser() {
+      ;({ data, isFetching } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {
+          refetchOnMountOrArgChange: true,
+        }))
+      return (
+        <div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <div data-testid="amount">{String(data?.amount)}</div>
+        </div>
+      )
+    }
+
+    render(<OtherUser />, { wrapper: storeRef.wrapper })
+    // Let's make sure we actually fetch, and we increment
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+    )
+
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('2'),
+    )
+  })
+
+  test('useQuery hook overrides default refetchOnMountOrArgChange: false that was set by createApi', async () => {
+    let data, isLoading, isFetching
+
+    function User() {
+      ;({ data, isLoading } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery())
+      return (
+        <div>
+          <div data-testid="isLoading">{String(isLoading)}</div>
+          <div data-testid="amount">{String(data?.amount)}</div>
+        </div>
+      )
+    }
+
+    let { unmount } = render(<User />, { wrapper: storeRef.wrapper })
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+
+    unmount()
+
+    function OtherUser() {
+      ;({ data, isFetching } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {
+          refetchOnMountOrArgChange: false,
+        }))
+      return (
+        <div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <div data-testid="amount">{String(data?.amount)}</div>
+        </div>
+      )
+    }
+
+    render(<OtherUser />, { wrapper: storeRef.wrapper })
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+  })
+
+  describe('selectFromResult (query) behaviors', () => {
+    let startingId = 3
+    const initialPosts = [
+      { id: 1, name: 'A sample post', fetched_at: new Date().toUTCString() },
+      {
+        id: 2,
+        name: 'A post about rtk-query',
+        fetched_at: new Date().toUTCString(),
+      },
+    ]
+    let posts = [] as typeof initialPosts
+
+    beforeEach(() => {
+      startingId = 3
+      posts = [...initialPosts]
+
+      const handlers = [
+        http.get('https://example.com/posts', () => {
+          return HttpResponse.json(posts)
+        }),
+        http.put<{ id: string }, Partial<Post>>(
+          'https://example.com/post/:id',
+          async ({ request, params }) => {
+            const body = await request.json()
+            const id = Number(params.id)
+            const idx = posts.findIndex((post) => post.id === id)
+
+            const newPosts = posts.map((post, index) =>
+              index !== idx
+                ? post
+                : {
+                    ...body,
+                    id,
+                    name: body?.name || post.name,
+                    fetched_at: new Date().toUTCString(),
+                  },
+            )
+            posts = [...newPosts]
+
+            return HttpResponse.json(posts)
+          },
+        ),
+        http.post<any, Omit<Post, 'id'>>(
+          'https://example.com/post',
+          async ({ request }) => {
+            const body = await request.json()
+            const post = body
+            startingId += 1
+            posts.concat({
+              ...post,
+              fetched_at: new Date().toISOString(),
+              id: startingId,
+            })
+            return HttpResponse.json(posts)
+          },
+        ),
+      ]
+
+      server.use(...handlers)
+    })
+
+    interface Post {
+      id: number
+      name: string
+      fetched_at: string
+    }
+
+    type PostsResponse = Post[]
+
+    const api = createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com/' }),
+      tagTypes: ['Posts'],
+      endpoints: (build) => ({
+        getPosts: build.query<PostsResponse, void>({
+          query: () => ({ url: 'posts' }),
+          providesTags: (result) =>
+            result ? result.map(({ id }) => ({ type: 'Posts', id })) : [],
+        }),
+        updatePost: build.mutation<Post, Partial<Post>>({
+          query: ({ id, ...body }) => ({
+            url: `post/${id}`,
+            method: 'PUT',
+            body,
+          }),
+          invalidatesTags: (result, error, { id }) => [{ type: 'Posts', id }],
+        }),
+        addPost: build.mutation<Post, Partial<Post>>({
+          query: (body) => ({
+            url: `post`,
+            method: 'POST',
+            body,
+          }),
+          invalidatesTags: ['Posts'],
+        }),
+      }),
+    })
+
+    const counterSlice = createSlice({
+      name: 'counter',
+      initialState: { count: 0 },
+      reducers: {
+        increment(state) {
+          state.count++
+        },
+      },
+    })
+
+    const storeRef = setupApiStore(api, {
+      counter: counterSlice.reducer,
+    })
+
+    test('useQueryState serves a deeply memoized value and does not rerender unnecessarily', async () => {
+      function Posts() {
+        const { data: posts } = api.endpoints.getPosts.useQuery()
+        const [addPost] = api.endpoints.addPost.useMutation()
+        return (
+          <div>
+            <button
+              data-testid="addPost"
+              onClick={() => addPost({ name: `some text ${posts?.length}` })}
+            >
+              Add random post
+            </button>
+          </div>
+        )
+      }
+
+      function SelectedPost() {
+        const { post } = api.endpoints.getPosts.useQueryState(undefined, {
+          selectFromResult: ({ data }) => ({
+            post: data?.find((post) => post.id === 1),
+          }),
+        })
+        getRenderCount = useRenderCounter()
+
+        /**
+         * Notes on the renderCount behavior
+         *
+         * We initialize at 0, and the first render will bump that 1 while post is `undefined`.
+         * Once the request resolves, it will be at 2. What we're looking for is to make sure that
+         * any requests that don't directly change the value of the selected item will have no impact
+         * on rendering.
+         */
+
+        return <div />
+      }
+
+      render(
+        <div>
+          <Posts />
+          <SelectedPost />
+        </div>,
+        { wrapper: storeRef.wrapper },
+      )
+
+      expect(getRenderCount()).toBe(1)
+
+      const addBtn = screen.getByTestId('addPost')
+
+      await waitFor(() => expect(getRenderCount()).toBe(2))
+
+      fireEvent.click(addBtn)
+      await waitFor(() => expect(getRenderCount()).toBe(2))
+      // We fire off a few requests that would typically cause a rerender as JSON.parse() on a request would always be a new object.
+      fireEvent.click(addBtn)
+      fireEvent.click(addBtn)
+      await waitFor(() => expect(getRenderCount()).toBe(2))
+      // Being that it didn't rerender, we can be assured that the behavior is correct
+    })
+
+    /**
+     * This test shows that even though a user can select a specific post, the fetching/loading flags
+     * will still cause rerenders for the query. This should show that if you're using selectFromResult,
+     * the 'performance' value comes with selecting _only_ the data.
+     */
+    test('useQuery with selectFromResult with all flags destructured rerenders like the default useQuery behavior', async () => {
+      function Posts() {
+        const { data: posts } = api.endpoints.getPosts.useQuery()
+        const [addPost] = api.endpoints.addPost.useMutation()
+        getRenderCount = useRenderCounter()
+        return (
+          <div>
+            <button
+              data-testid="addPost"
+              onClick={() =>
+                addPost({
+                  name: `some text ${posts?.length}`,
+                  fetched_at: new Date().toISOString(),
+                })
+              }
+            >
+              Add random post
+            </button>
+          </div>
+        )
+      }
+
+      function SelectedPost() {
+        getRenderCount = useRenderCounter()
+
+        const { post } = api.endpoints.getPosts.useQuery(undefined, {
+          selectFromResult: ({
+            data,
+            isUninitialized,
+            isLoading,
+            isFetching,
+            isSuccess,
+            isError,
+          }) => ({
+            post: data?.find((post) => post.id === 1),
+            isUninitialized,
+            isLoading,
+            isFetching,
+            isSuccess,
+            isError,
+          }),
+        })
+
+        return <div />
+      }
+
+      render(
+        <div>
+          <Posts />
+          <SelectedPost />
+        </div>,
+        { wrapper: storeRef.wrapper },
+      )
+      expect(getRenderCount()).toBe(2)
+
+      const addBtn = screen.getByTestId('addPost')
+
+      await waitFor(() => expect(getRenderCount()).toBe(3))
+
+      fireEvent.click(addBtn)
+      await waitFor(() => expect(getRenderCount()).toBe(5))
+      fireEvent.click(addBtn)
+      fireEvent.click(addBtn)
+      await waitFor(() => expect(getRenderCount()).toBe(7))
+    })
+
+    test('useQuery with selectFromResult option serves a deeply memoized value and does not rerender unnecessarily', async () => {
+      function Posts() {
+        const { data: posts } = api.endpoints.getPosts.useQuery()
+        const [addPost] = api.endpoints.addPost.useMutation()
+        return (
+          <div>
+            <button
+              data-testid="addPost"
+              onClick={() =>
+                addPost({
+                  name: `some text ${posts?.length}`,
+                  fetched_at: new Date().toISOString(),
+                })
+              }
+            >
+              Add random post
+            </button>
+          </div>
+        )
+      }
+
+      function SelectedPost() {
+        getRenderCount = useRenderCounter()
+        const { post } = api.endpoints.getPosts.useQuery(undefined, {
+          selectFromResult: ({ data }) => ({
+            post: data?.find((post) => post.id === 1),
+          }),
+        })
+
+        return <div />
+      }
+
+      render(
+        <div>
+          <Posts />
+          <SelectedPost />
+        </div>,
+        { wrapper: storeRef.wrapper },
+      )
+      expect(getRenderCount()).toBe(1)
+
+      const addBtn = screen.getByTestId('addPost')
+
+      await waitFor(() => expect(getRenderCount()).toBe(2))
+
+      fireEvent.click(addBtn)
+      await waitFor(() => expect(getRenderCount()).toBe(2))
+      fireEvent.click(addBtn)
+      fireEvent.click(addBtn)
+      await waitFor(() => expect(getRenderCount()).toBe(2))
+    })
+
+    test('useQuery with selectFromResult option serves a deeply memoized value, then ONLY updates when the underlying data changes', async () => {
+      let expectablePost: Post | undefined
+      function Posts() {
+        const { data: posts } = api.endpoints.getPosts.useQuery()
+        const [addPost] = api.endpoints.addPost.useMutation()
+        const [updatePost] = api.endpoints.updatePost.useMutation()
+
+        return (
+          <div>
+            <button
+              data-testid="addPost"
+              onClick={() =>
+                addPost({
+                  name: `some text ${posts?.length}`,
+                  fetched_at: new Date().toISOString(),
+                })
+              }
+            >
+              Add random post
+            </button>
+            <button
+              data-testid="updatePost"
+              onClick={() => updatePost({ id: 1, name: 'supercoooll!' })}
+            >
+              Update post
+            </button>
+          </div>
+        )
+      }
+
+      function SelectedPost() {
+        const { post } = api.endpoints.getPosts.useQuery(undefined, {
+          selectFromResult: ({ data }) => ({
+            post: data?.find((post) => post.id === 1),
+          }),
+        })
+        getRenderCount = useRenderCounter()
+
+        useEffect(() => {
+          expectablePost = post
+        }, [post])
+
+        return (
+          <div>
+            <div data-testid="postName">{post?.name}</div>
+          </div>
+        )
+      }
+
+      render(
+        <div>
+          <Posts />
+          <SelectedPost />
+        </div>,
+        { wrapper: storeRef.wrapper },
+      )
+      expect(getRenderCount()).toBe(1)
+
+      const addBtn = screen.getByTestId('addPost')
+      const updateBtn = screen.getByTestId('updatePost')
+
+      fireEvent.click(addBtn)
+      await waitFor(() => expect(getRenderCount()).toBe(2))
+      fireEvent.click(addBtn)
+      fireEvent.click(addBtn)
+      await waitFor(() => expect(getRenderCount()).toBe(2))
+
+      fireEvent.click(updateBtn)
+      await waitFor(() => expect(getRenderCount()).toBe(3))
+      expect(expectablePost?.name).toBe('supercoooll!')
+
+      fireEvent.click(addBtn)
+      await waitFor(() => expect(getRenderCount()).toBe(3))
+    })
+
+    test('useQuery with selectFromResult option does not update when unrelated data in the store changes', async () => {
+      function Posts() {
+        const { posts } = api.endpoints.getPosts.useQuery(undefined, {
+          selectFromResult: ({ data }) => ({
+            // Intentionally use an unstable reference to force a rerender
+            posts: data?.filter((post) => post.name.includes('post')),
+          }),
+        })
+
+        getRenderCount = useRenderCounter()
+
+        return (
+          <div>
+            {posts?.map((post) => <div key={post.id}>{post.name}</div>)}
+          </div>
+        )
+      }
+
+      function CounterButton() {
+        return (
+          <div
+            data-testid="incrementButton"
+            onClick={() =>
+              storeRef.store.dispatch(counterSlice.actions.increment())
+            }
+          >
+            Increment Count
+          </div>
+        )
+      }
+
+      render(
+        <div>
+          <Posts />
+          <CounterButton />
+        </div>,
+        { wrapper: storeRef.wrapper },
+      )
+
+      await waitFor(() => expect(getRenderCount()).toBe(2))
+
+      const incrementBtn = screen.getByTestId('incrementButton')
+      fireEvent.click(incrementBtn)
+      expect(getRenderCount()).toBe(2)
+    })
+
+    test('useQuery with selectFromResult option has a type error if the result is not an object', async () => {
+      function SelectedPost() {
+        const res2 = api.endpoints.getPosts.useQuery(undefined, {
+          // selectFromResult must always return an object
+          selectFromResult: ({ data }) => ({ size: data?.length ?? 0 }),
+        })
+
+        return (
+          <div>
+            <div data-testid="size2">{res2.size}</div>
+          </div>
+        )
+      }
+
+      render(
+        <div>
+          <SelectedPost />
+        </div>,
+        { wrapper: storeRef.wrapper },
+      )
+
+      expect(screen.getByTestId('size2').textContent).toBe('0')
+    })
+  })
+
+  describe('selectFromResult (mutation) behavior', () => {
+    const api = createApi({
+      baseQuery: async (arg: any) => {
+        await waitMs()
+        if ('amount' in arg?.body) {
+          amount += 1
+        }
+        return {
+          data: arg?.body
+            ? { ...arg.body, ...(amount ? { amount } : {}) }
+            : undefined,
+        }
+      },
+      endpoints: (build) => ({
+        increment: build.mutation<{ amount: number }, number>({
+          query: (amount) => ({
+            url: '',
+            method: 'POST',
+            body: {
+              amount,
+            },
+          }),
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, {
+      ...actionsReducer,
+    })
+
+    it('causes no more than one rerender when using selectFromResult with an empty object', async () => {
+      function Counter() {
+        const [increment] = api.endpoints.increment.useMutation({
+          selectFromResult: () => ({}),
+        })
+        getRenderCount = useRenderCounter()
+
+        return (
+          <div>
+            <button
+              data-testid="incrementButton"
+              onClick={() => increment(1)}
+            ></button>
+          </div>
+        )
+      }
+
+      render(<Counter />, { wrapper: storeRef.wrapper })
+
+      expect(getRenderCount()).toBe(1)
+
+      fireEvent.click(screen.getByTestId('incrementButton'))
+      await waitMs(200) // give our baseQuery a chance to return
+      expect(getRenderCount()).toBe(2)
+
+      fireEvent.click(screen.getByTestId('incrementButton'))
+      await waitMs(200)
+      expect(getRenderCount()).toBe(3)
+
+      const { increment } = api.endpoints
+
+      expect(storeRef.store.getState().actions).toMatchSequence(
+        api.internalActions.middlewareRegistered.match,
+        increment.matchPending,
+        increment.matchFulfilled,
+        increment.matchPending,
+        api.internalActions.removeMutationResult.match,
+        increment.matchFulfilled,
+      )
+    })
+
+    it('causes rerenders when only selected data changes', async () => {
+      function Counter() {
+        const [increment, { data }] = api.endpoints.increment.useMutation({
+          selectFromResult: ({ data }) => ({ data }),
+        })
+        getRenderCount = useRenderCounter()
+
+        return (
+          <div>
+            <button
+              data-testid="incrementButton"
+              onClick={() => increment(1)}
+            ></button>
+            <div data-testid="data">{JSON.stringify(data)}</div>
+          </div>
+        )
+      }
+
+      render(<Counter />, { wrapper: storeRef.wrapper })
+
+      expect(getRenderCount()).toBe(1)
+
+      fireEvent.click(screen.getByTestId('incrementButton'))
+      await waitFor(() =>
+        expect(screen.getByTestId('data').textContent).toBe(
+          JSON.stringify({ amount: 1 }),
+        ),
+      )
+      expect(getRenderCount()).toBe(3)
+
+      fireEvent.click(screen.getByTestId('incrementButton'))
+      await waitFor(() =>
+        expect(screen.getByTestId('data').textContent).toBe(
+          JSON.stringify({ amount: 2 }),
+        ),
+      )
+      expect(getRenderCount()).toBe(5)
+    })
+
+    it('causes the expected # of rerenders when NOT using selectFromResult', async () => {
+      function Counter() {
+        const [increment, data] = api.endpoints.increment.useMutation()
+        getRenderCount = useRenderCounter()
+
+        return (
+          <div>
+            <button
+              data-testid="incrementButton"
+              onClick={() => increment(1)}
+            ></button>
+            <div data-testid="status">{String(data.status)}</div>
+          </div>
+        )
+      }
+
+      render(<Counter />, { wrapper: storeRef.wrapper })
+
+      expect(getRenderCount()).toBe(1) // mount, uninitialized status in substate
+
+      fireEvent.click(screen.getByTestId('incrementButton'))
+
+      expect(getRenderCount()).toBe(2) // will be pending, isLoading: true,
+      await waitFor(() =>
+        expect(screen.getByTestId('status').textContent).toBe('pending'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('status').textContent).toBe('fulfilled'),
+      )
+      expect(getRenderCount()).toBe(3)
+
+      fireEvent.click(screen.getByTestId('incrementButton'))
+      await waitFor(() =>
+        expect(screen.getByTestId('status').textContent).toBe('pending'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('status').textContent).toBe('fulfilled'),
+      )
+      expect(getRenderCount()).toBe(5)
+    })
+
+    it('useMutation with selectFromResult option has a type error if the result is not an object', async () => {
+      function Counter() {
+        const [increment] = api.endpoints.increment.useMutation({
+          // selectFromResult must always return an object
+          // @ts-expect-error
+          selectFromResult: () => 42,
+        })
+
+        return (
+          <div>
+            <button
+              data-testid="incrementButton"
+              onClick={() => increment(1)}
+            ></button>
+          </div>
+        )
+      }
+
+      render(<Counter />, { wrapper: storeRef.wrapper })
+    })
+  })
+})
+
+describe('skip behavior', () => {
+  const uninitialized = {
+    status: QueryStatus.uninitialized,
+    refetch: expect.any(Function),
+    data: undefined,
+    isError: false,
+    isFetching: false,
+    isLoading: false,
+    isSuccess: false,
+    isUninitialized: true,
+  }
+
+  test('normal skip', async () => {
+    const { result, rerender } = renderHook(
+      ([arg, options]: Parameters<typeof api.endpoints.getUser.useQuery>) =>
+        api.endpoints.getUser.useQuery(arg, options),
+      {
+        wrapper: storeRef.wrapper,
+        initialProps: [1, { skip: true }],
+      },
+    )
+
+    expect(result.current).toEqual(uninitialized)
+    await waitMs(1)
+    expect(getSubscriptionCount('getUser(1)')).toBe(0)
+
+    rerender([1])
+
+    await act(async () => {
+      await waitForFakeTimer(150)
+    })
+
+    expect(result.current).toMatchObject({ status: QueryStatus.fulfilled })
+    await waitMs(1)
+    expect(getSubscriptionCount('getUser(1)')).toBe(1)
+
+    rerender([1, { skip: true }])
+
+    expect(result.current).toEqual({
+      ...uninitialized,
+      isSuccess: true,
+      currentData: undefined,
+      data: { name: 'Timmy' },
+    })
+    await waitMs(1)
+    expect(getSubscriptionCount('getUser(1)')).toBe(0)
+  })
+
+  test('skipToken', async () => {
+    const { result, rerender } = renderHook(
+      ([arg, options]: Parameters<typeof api.endpoints.getUser.useQuery>) =>
+        api.endpoints.getUser.useQuery(arg, options),
+      {
+        wrapper: storeRef.wrapper,
+        initialProps: [skipToken],
+      },
+    )
+
+    expect(result.current).toEqual(uninitialized)
+    await waitMs(1)
+
+    expect(getSubscriptionCount('getUser(1)')).toBe(0)
+    // also no subscription on `getUser(skipToken)` or similar:
+    expect(getSubscriptions().size).toBe(0)
+
+    rerender([1])
+
+    await act(async () => {
+      await waitForFakeTimer(150)
+    })
+
+    expect(result.current).toMatchObject({ status: QueryStatus.fulfilled })
+    await waitMs(1)
+    expect(getSubscriptionCount('getUser(1)')).toBe(1)
+    expect(getSubscriptions().size).toBe(1)
+
+    rerender([skipToken])
+
+    expect(result.current).toEqual({
+      ...uninitialized,
+      isSuccess: true,
+      currentData: undefined,
+      data: { name: 'Timmy' },
+    })
+    await waitMs(1)
+    expect(getSubscriptionCount('getUser(1)')).toBe(0)
+  })
+
+  test('skipToken does not break serializeQueryArgs', async () => {
+    const { result, rerender } = renderHook(
+      ([arg, options]: Parameters<
+        typeof api.endpoints.queryWithDeepArg.useQuery
+      >) => api.endpoints.queryWithDeepArg.useQuery(arg, options),
+      {
+        wrapper: storeRef.wrapper,
+        initialProps: [skipToken],
+      },
+    )
+
+    expect(result.current).toEqual(uninitialized)
+    await waitMs(1)
+
+    expect(getSubscriptionCount('nestedValue')).toBe(0)
+    // also no subscription on `getUser(skipToken)` or similar:
+    expect(getSubscriptions().size).toBe(0)
+
+    rerender([{ param: { nested: 'nestedValue' } }])
+
+    await act(async () => {
+      await waitForFakeTimer(150)
+    })
+
+    expect(result.current).toMatchObject({ status: QueryStatus.fulfilled })
+    await waitMs(1)
+
+    expect(getSubscriptionCount('nestedValue')).toBe(1)
+    expect(getSubscriptions().size).toBe(1)
+
+    rerender([skipToken])
+
+    expect(result.current).toEqual({
+      ...uninitialized,
+      isSuccess: true,
+      currentData: undefined,
+      data: {},
+    })
+    await waitMs(1)
+    expect(getSubscriptionCount('nestedValue')).toBe(0)
+  })
+
+  test('skipping a previously fetched query retains the existing value as `data`, but clears `currentData`', async () => {
+    const { result, rerender } = renderHook(
+      ([arg, options]: Parameters<typeof api.endpoints.getUser.useQuery>) =>
+        api.endpoints.getUser.useQuery(arg, options),
+      {
+        wrapper: storeRef.wrapper,
+        initialProps: [1],
+      },
+    )
+
+    await act(async () => {
+      await waitForFakeTimer(150)
+    })
+
+    // Normal fulfilled result, with both `data` and `currentData`
+    expect(result.current).toMatchObject({
+      status: QueryStatus.fulfilled,
+      isSuccess: true,
+      data: { name: 'Timmy' },
+      currentData: { name: 'Timmy' },
+    })
+
+    rerender([1, { skip: true }])
+
+    // After skipping, the query is "uninitialized", but still retains the last fetched `data`
+    // even though it's skipped. `currentData` is undefined, since that matches the current arg.
+    expect(result.current).toMatchObject({
+      status: QueryStatus.uninitialized,
+      isSuccess: true,
+      data: { name: 'Timmy' },
+      currentData: undefined,
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/buildInitiate.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/buildInitiate.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/buildInitiate.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,306 @@
+import { setupApiStore } from '@internal/tests/utils/helpers'
+import { createApi } from '../core'
+import type { SubscriptionSelectors } from '../core/buildMiddleware/types'
+import { fakeBaseQuery } from '../fakeBaseQuery'
+import { delay } from '@internal/utils'
+
+let calls = 0
+const api = createApi({
+  baseQuery: fakeBaseQuery(),
+  endpoints: (build) => ({
+    increment: build.query<number, void>({
+      async queryFn() {
+        const data = calls++
+        await Promise.resolve()
+        return { data }
+      },
+    }),
+    incrementKeep0: build.query<number, void>({
+      async queryFn() {
+        const data = calls++
+        await delay(10)
+        return { data }
+      },
+      keepUnusedDataFor: 0,
+    }),
+    failing: build.query<void, void>({
+      async queryFn() {
+        await Promise.resolve()
+        return { error: { status: 500, data: 'error' } }
+      },
+    }),
+  }),
+})
+
+const storeRef = setupApiStore(api)
+
+let getSubscriptions: SubscriptionSelectors['getSubscriptions']
+let isRequestSubscribed: SubscriptionSelectors['isRequestSubscribed']
+
+beforeEach(() => {
+  ;({ getSubscriptions, isRequestSubscribed } = storeRef.store.dispatch(
+    api.internalActions.internal_getRTKQSubscriptions(),
+  ) as unknown as SubscriptionSelectors)
+})
+
+test('multiple synchonrous initiate calls with pre-existing cache entry', async () => {
+  const { store, api } = storeRef
+  // seed the store
+  const firstValue = await store.dispatch(api.endpoints.increment.initiate())
+
+  expect(firstValue).toMatchObject({ data: 0, status: 'fulfilled' })
+
+  // dispatch another increment
+  const secondValuePromise = store.dispatch(api.endpoints.increment.initiate())
+  // and one with a forced refresh
+  const thirdValuePromise = store.dispatch(
+    api.endpoints.increment.initiate(undefined, { forceRefetch: true }),
+  )
+  // and another increment
+  const fourthValuePromise = store.dispatch(api.endpoints.increment.initiate())
+
+  const secondValue = await secondValuePromise
+  const thirdValue = await thirdValuePromise
+  const fourthValue = await fourthValuePromise
+
+  expect(secondValue).toMatchObject({
+    data: firstValue.data,
+    status: 'fulfilled',
+    requestId: firstValue.requestId,
+  })
+
+  expect(thirdValue).toMatchObject({ data: 1, status: 'fulfilled' })
+  expect(thirdValue.requestId).not.toBe(firstValue.requestId)
+  expect(fourthValue).toMatchObject({
+    data: thirdValue.data,
+    status: 'fulfilled',
+    requestId: thirdValue.requestId,
+  })
+})
+
+describe('calling initiate without a cache entry, with subscribe: false still returns correct values', () => {
+  test('successful query', async () => {
+    const { store, api } = storeRef
+    calls = 0
+    const promise = store.dispatch(
+      api.endpoints.increment.initiate(undefined, { subscribe: false }),
+    )
+    expect(isRequestSubscribed('increment(undefined)', promise.requestId)).toBe(
+      false,
+    )
+
+    await expect(promise).resolves.toMatchObject({
+      data: 0,
+      status: 'fulfilled',
+    })
+  })
+
+  test('successful query with keepUnusedDataFor: 0', async () => {
+    const { store, api } = storeRef
+    calls = 0
+    const promise = store.dispatch(
+      api.endpoints.incrementKeep0.initiate(undefined, { subscribe: false }),
+    )
+    expect(isRequestSubscribed('increment(undefined)', promise.requestId)).toBe(
+      false,
+    )
+
+    await expect(promise.unwrap()).resolves.toBe(0)
+  })
+
+  test('rejected query', async () => {
+    const { store, api } = storeRef
+    calls = 0
+    const promise = store.dispatch(
+      api.endpoints.failing.initiate(undefined, { subscribe: false }),
+    )
+    expect(isRequestSubscribed('failing(undefined)', promise.requestId)).toBe(
+      false,
+    )
+
+    await expect(promise).resolves.toMatchObject({
+      status: 'rejected',
+    })
+  })
+})
+
+describe('calling initiate should have resulting queryCacheKey match baseQuery queryCacheKey', () => {
+  const baseQuery = vi.fn(() => ({ data: 'success' }))
+  function getNewApi() {
+    return createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        query: build.query<void, { arg1: string; arg2: string }>({
+          query: (args) => `queryUrl/${args.arg1}/${args.arg2}`,
+        }),
+        mutation: build.mutation<void, { arg1: string; arg2: string }>({
+          query: () => 'mutationUrl',
+        }),
+      }),
+    })
+  }
+  let api = getNewApi()
+  beforeEach(() => {
+    baseQuery.mockClear()
+    api = getNewApi()
+  })
+
+  test('should be a string and matching on queries', () => {
+    const { store: storeApi } = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+    const promise = storeApi.dispatch(
+      api.endpoints.query.initiate({ arg2: 'secondArg', arg1: 'firstArg' }),
+    )
+    expect(baseQuery).toHaveBeenCalledWith(
+      expect.any(String),
+      expect.objectContaining({
+        queryCacheKey: promise.queryCacheKey,
+      }),
+      undefined,
+    )
+  })
+
+  test('should be undefined and matching on mutations', () => {
+    const { store: storeApi } = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+    storeApi.dispatch(
+      api.endpoints.mutation.initiate({ arg2: 'secondArg', arg1: 'firstArg' }),
+    )
+    expect(baseQuery).toHaveBeenCalledWith(
+      expect.any(String),
+      expect.objectContaining({
+        queryCacheKey: undefined,
+      }),
+      undefined,
+    )
+  })
+})
+
+describe('getRunningQueryThunk with multiple stores', () => {
+  test('should isolate running queries between different store instances using the same API', async () => {
+    // Create a shared API instance
+    const sharedApi = createApi({
+      baseQuery: fakeBaseQuery(),
+      endpoints: (build) => ({
+        testQuery: build.query<string, string>({
+          async queryFn(arg) {
+            // Add delay to ensure queries are running when we check
+            await new Promise((resolve) => setTimeout(resolve, 50))
+            return { data: `result-${arg}` }
+          },
+        }),
+      }),
+    })
+
+    // Create two separate stores using the same API instance
+    const store1 = setupApiStore(sharedApi, undefined, {
+      withoutTestLifecycles: true,
+    }).store
+    const store2 = setupApiStore(sharedApi, undefined, {
+      withoutTestLifecycles: true,
+    }).store
+
+    // Start queries on both stores
+    const query1Promise = store1.dispatch(
+      sharedApi.endpoints.testQuery.initiate('arg1'),
+    )
+    const query2Promise = store2.dispatch(
+      sharedApi.endpoints.testQuery.initiate('arg2'),
+    )
+
+    // Verify that getRunningQueryThunk returns the correct query for each store
+    const runningQuery1 = store1.dispatch(
+      sharedApi.util.getRunningQueryThunk('testQuery', 'arg1'),
+    )
+    const runningQuery2 = store2.dispatch(
+      sharedApi.util.getRunningQueryThunk('testQuery', 'arg2'),
+    )
+
+    // Each store should only see its own running query
+    expect(runningQuery1).toBeDefined()
+    expect(runningQuery2).toBeDefined()
+    expect(runningQuery1?.requestId).toBe(query1Promise.requestId)
+    expect(runningQuery2?.requestId).toBe(query2Promise.requestId)
+
+    // Cross-store queries should not be visible
+    const crossQuery1 = store1.dispatch(
+      sharedApi.util.getRunningQueryThunk('testQuery', 'arg2'),
+    )
+    const crossQuery2 = store2.dispatch(
+      sharedApi.util.getRunningQueryThunk('testQuery', 'arg1'),
+    )
+
+    expect(crossQuery1).toBeUndefined()
+    expect(crossQuery2).toBeUndefined()
+
+    // Wait for queries to complete
+    await Promise.all([query1Promise, query2Promise])
+
+    // After completion, getRunningQueryThunk should return undefined for both stores
+    const completedQuery1 = store1.dispatch(
+      sharedApi.util.getRunningQueryThunk('testQuery', 'arg1'),
+    )
+    const completedQuery2 = store2.dispatch(
+      sharedApi.util.getRunningQueryThunk('testQuery', 'arg2'),
+    )
+
+    expect(completedQuery1).toBeUndefined()
+    expect(completedQuery2).toBeUndefined()
+  })
+
+  test('should handle same query args on different stores independently', async () => {
+    // Create a shared API instance
+    const sharedApi = createApi({
+      baseQuery: fakeBaseQuery(),
+      endpoints: (build) => ({
+        sameArgQuery: build.query<string, string>({
+          async queryFn(arg) {
+            await new Promise((resolve) => setTimeout(resolve, 50))
+            return { data: `result-${arg}-${Math.random()}` }
+          },
+        }),
+      }),
+    })
+
+    // Create two separate stores
+    const store1 = setupApiStore(sharedApi, undefined, {
+      withoutTestLifecycles: true,
+    }).store
+    const store2 = setupApiStore(sharedApi, undefined, {
+      withoutTestLifecycles: true,
+    }).store
+
+    // Start the same query on both stores
+    const sameArg = 'shared-arg'
+    const query1Promise = store1.dispatch(
+      sharedApi.endpoints.sameArgQuery.initiate(sameArg),
+    )
+    const query2Promise = store2.dispatch(
+      sharedApi.endpoints.sameArgQuery.initiate(sameArg),
+    )
+
+    // Both stores should see their own running query with the same cache key
+    const runningQuery1 = store1.dispatch(
+      sharedApi.util.getRunningQueryThunk('sameArgQuery', sameArg),
+    )
+    const runningQuery2 = store2.dispatch(
+      sharedApi.util.getRunningQueryThunk('sameArgQuery', sameArg),
+    )
+
+    expect(runningQuery1).toBeDefined()
+    expect(runningQuery2).toBeDefined()
+    expect(runningQuery1?.requestId).toBe(query1Promise.requestId)
+    expect(runningQuery2?.requestId).toBe(query2Promise.requestId)
+
+    // The request IDs should be different even though the cache key is the same
+    expect(runningQuery1?.requestId).not.toBe(runningQuery2?.requestId)
+
+    // But the cache keys should be the same
+    expect(runningQuery1?.queryCacheKey).toBe(runningQuery2?.queryCacheKey)
+
+    // Wait for completion
+    await Promise.all([query1Promise, query2Promise])
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/buildMiddleware.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/buildMiddleware.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/buildMiddleware.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,83 @@
+import { createApi } from '@reduxjs/toolkit/query'
+
+const baseQuery = (args?: any) => ({ data: args })
+
+const api = createApi({
+  baseQuery,
+  tagTypes: ['Banana', 'Bread'],
+  endpoints: (build) => ({
+    getBanana: build.query<unknown, number>({
+      query(id) {
+        return { url: `banana/${id}` }
+      },
+      providesTags: ['Banana'],
+    }),
+    getBananas: build.query<unknown, void>({
+      query() {
+        return { url: 'bananas' }
+      },
+      providesTags: ['Banana'],
+    }),
+    getBread: build.query<unknown, number>({
+      query(id) {
+        return { url: `bread/${id}` }
+      },
+      providesTags: ['Bread'],
+    }),
+  }),
+})
+
+describe('type tests', () => {
+  it('should allow for an array of string TagTypes', () => {
+    api.util.invalidateTags(['Banana', 'Bread'])
+  })
+
+  it('should allow for an array of full TagTypes descriptions', () => {
+    api.util.invalidateTags([{ type: 'Banana' }, { type: 'Bread', id: 1 }])
+  })
+
+  it('should allow for a mix of full descriptions as well as plain strings', () => {
+    api.util.invalidateTags(['Banana', { type: 'Bread', id: 1 }])
+  })
+
+  it('should error when using non-existing TagTypes', () => {
+    // @ts-expect-error
+    api.util.invalidateTags(['Missing Tag'])
+  })
+
+  it('should error when using non-existing TagTypes in the full format', () => {
+    // @ts-expect-error
+    api.util.invalidateTags([{ type: 'Missing' }])
+  })
+
+  it('should allow pre-fetching for an endpoint that takes an arg', () => {
+    api.util.prefetch('getBanana', 5, { force: true })
+    api.util.prefetch('getBanana', 5, { force: false })
+    api.util.prefetch('getBanana', 5, { ifOlderThan: false })
+    api.util.prefetch('getBanana', 5, { ifOlderThan: 30 })
+    api.util.prefetch('getBanana', 5, {})
+  })
+
+  it('should error when pre-fetching with the incorrect arg type', () => {
+    // @ts-expect-error arg should be number, not string
+    api.util.prefetch('getBanana', '5', { force: true })
+  })
+
+  it('should allow pre-fetching for an endpoint with a void arg', () => {
+    api.util.prefetch('getBananas', undefined, { force: true })
+    api.util.prefetch('getBananas', undefined, { force: false })
+    api.util.prefetch('getBananas', undefined, { ifOlderThan: false })
+    api.util.prefetch('getBananas', undefined, { ifOlderThan: 30 })
+    api.util.prefetch('getBananas', undefined, {})
+  })
+
+  it('should error when pre-fetching with a defined arg when expecting void', () => {
+    // @ts-expect-error arg should be void, not number
+    api.util.prefetch('getBananas', 5, { force: true })
+  })
+
+  it('should error when pre-fetching for an incorrect endpoint name', () => {
+    // @ts-expect-error endpoint name does not exist
+    api.util.prefetch('getPomegranates', undefined, { force: true })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/buildMiddleware.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/buildMiddleware.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/buildMiddleware.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,266 @@
+import { createApi } from '@reduxjs/toolkit/query'
+import { delay } from 'msw'
+import { actionsReducer, setupApiStore } from '../../tests/utils/helpers'
+import { vi } from 'vitest'
+
+const baseQuery = (args?: any) => ({ data: args })
+const api = createApi({
+  baseQuery,
+  tagTypes: ['Banana', 'Bread'],
+  endpoints: (build) => ({
+    getBanana: build.query<unknown, number>({
+      query(id) {
+        return { url: `banana/${id}` }
+      },
+      providesTags: ['Banana'],
+    }),
+    getBananas: build.query<unknown, void>({
+      query() {
+        return { url: 'bananas' }
+      },
+      providesTags: ['Banana'],
+    }),
+    getBread: build.query<unknown, number>({
+      query(id) {
+        return { url: `bread/${id}` }
+      },
+      providesTags: ['Bread'],
+    }),
+    invalidateFruit: build.mutation({
+      query: (fruit?: 'Banana' | 'Bread' | null) => ({
+        url: `invalidate/fruit/${fruit || ''}`,
+      }),
+      invalidatesTags(result, error, arg) {
+        return [arg]
+      },
+    }),
+  }),
+})
+const { getBanana, getBread, invalidateFruit } = api.endpoints
+
+const storeRef = setupApiStore(api, {
+  ...actionsReducer,
+})
+
+it('invalidates the specified tags', async () => {
+  await storeRef.store.dispatch(getBanana.initiate(1))
+  expect(storeRef.store.getState().actions).toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    getBanana.matchPending,
+    getBanana.matchFulfilled,
+  )
+
+  await storeRef.store.dispatch(api.util.invalidateTags(['Banana', 'Bread']))
+
+  // Slight pause to let the middleware run and such
+  await delay(20)
+
+  const firstSequence = [
+    api.internalActions.middlewareRegistered.match,
+    getBanana.matchPending,
+    getBanana.matchFulfilled,
+    api.util.invalidateTags.match,
+    getBanana.matchPending,
+    getBanana.matchFulfilled,
+  ]
+  expect(storeRef.store.getState().actions).toMatchSequence(...firstSequence)
+
+  await storeRef.store.dispatch(getBread.initiate(1))
+  await storeRef.store.dispatch(api.util.invalidateTags([{ type: 'Bread' }]))
+
+  await delay(20)
+
+  expect(storeRef.store.getState().actions).toMatchSequence(
+    ...firstSequence,
+    getBread.matchPending,
+    getBread.matchFulfilled,
+    api.util.invalidateTags.match,
+    getBread.matchPending,
+    getBread.matchFulfilled,
+  )
+})
+
+it('invalidates tags correctly when null or undefined are provided as tags', async () => {
+  await storeRef.store.dispatch(getBanana.initiate(1))
+  await storeRef.store.dispatch(
+    api.util.invalidateTags([undefined, null, 'Banana']),
+  )
+
+  // Slight pause to let the middleware run and such
+  await delay(20)
+
+  const apiActions = [
+    api.internalActions.middlewareRegistered.match,
+    getBanana.matchPending,
+    getBanana.matchFulfilled,
+    api.util.invalidateTags.match,
+    getBanana.matchPending,
+    getBanana.matchFulfilled,
+  ]
+
+  expect(storeRef.store.getState().actions).toMatchSequence(...apiActions)
+})
+
+it.each([
+  {
+    tags: [undefined, null, 'Bread'] as Parameters<
+      typeof api.util.invalidateTags
+    >['0'],
+  },
+  { tags: [undefined, null] },
+  { tags: [] },
+])(
+  'does not invalidate with tags=$tags if no query matches',
+  async ({ tags }) => {
+    await storeRef.store.dispatch(getBanana.initiate(1))
+    await storeRef.store.dispatch(api.util.invalidateTags(tags))
+
+    // Slight pause to let the middleware run and such
+    await delay(20)
+
+    const apiActions = [
+      api.internalActions.middlewareRegistered.match,
+      getBanana.matchPending,
+      getBanana.matchFulfilled,
+      api.util.invalidateTags.match,
+    ]
+
+    expect(storeRef.store.getState().actions).toMatchSequence(...apiActions)
+  },
+)
+
+it.each([
+  { mutationArg: 'Bread' as 'Bread' | null | undefined },
+  { mutationArg: undefined },
+  { mutationArg: null },
+])(
+  'does not invalidate queries when a mutation with tags=[$mutationArg] runs and does not match anything',
+  async ({ mutationArg }) => {
+    await storeRef.store.dispatch(getBanana.initiate(1))
+    await storeRef.store.dispatch(invalidateFruit.initiate(mutationArg))
+
+    // Slight pause to let the middleware run and such
+    await delay(20)
+
+    const apiActions = [
+      api.internalActions.middlewareRegistered.match,
+      getBanana.matchPending,
+      getBanana.matchFulfilled,
+      invalidateFruit.matchPending,
+      invalidateFruit.matchFulfilled,
+    ]
+
+    expect(storeRef.store.getState().actions).toMatchSequence(...apiActions)
+  },
+)
+
+it('correctly stringifies subscription state and dispatches subscriptionsUpdated', async () => {
+  // Create a fresh store for this test to avoid interference
+  const testStoreRef = setupApiStore(
+    api,
+    {
+      ...actionsReducer,
+    },
+    { withoutListeners: true },
+  )
+
+  // Start multiple subscriptions
+  const subscription1 = testStoreRef.store.dispatch(
+    getBanana.initiate(1, {
+      subscriptionOptions: { pollingInterval: 1000 },
+    }),
+  )
+  const subscription2 = testStoreRef.store.dispatch(
+    getBanana.initiate(2, {
+      subscriptionOptions: { refetchOnFocus: true },
+    }),
+  )
+  const subscription3 = testStoreRef.store.dispatch(
+    api.endpoints.getBananas.initiate(),
+  )
+
+  // Wait for the subscriptions to be established
+  await Promise.all([subscription1, subscription2, subscription3])
+
+  // Wait for the subscription sync timer (500ms + buffer)
+  await delay(600)
+
+  // Check the final subscription state in the store
+  const finalState = testStoreRef.store.getState()
+  const subscriptionState = finalState[api.reducerPath].subscriptions
+
+  // Should have subscriptions for getBanana(1), getBanana(2), and getBananas()
+  expect(subscriptionState).toMatchObject({
+    'getBanana(1)': {
+      [subscription1.requestId]: { pollingInterval: 1000 },
+    },
+    'getBanana(2)': {
+      [subscription2.requestId]: { refetchOnFocus: true },
+    },
+    'getBananas(undefined)': {
+      [subscription3.requestId]: {},
+    },
+  })
+
+  // Verify the subscription entries have the expected structure
+  expect(Object.keys(subscriptionState)).toHaveLength(3)
+  expect(subscriptionState['getBanana(1)']?.[subscription1.requestId]).toEqual({
+    pollingInterval: 1000,
+  })
+  expect(subscriptionState['getBanana(2)']?.[subscription2.requestId]).toEqual({
+    refetchOnFocus: true,
+  })
+  expect(
+    subscriptionState['getBananas(undefined)']?.[subscription3.requestId],
+  ).toEqual({})
+})
+
+it('does not leak subscription state between multiple stores using the same API instance (SSR scenario)', async () => {
+  vi.useFakeTimers()
+  // Simulate SSR: create API once at module level
+  const sharedApi = createApi({
+    baseQuery: (args?: any) => ({ data: args }),
+    tagTypes: ['Test'],
+    endpoints: (build) => ({
+      getTest: build.query<unknown, number>({
+        query(id) {
+          return { url: `test/${id}` }
+        },
+      }),
+    }),
+  })
+
+  // Create first store (simulating first SSR request)
+  const store1Ref = setupApiStore(sharedApi, {}, { withoutListeners: true })
+
+  // Add subscription in store1
+  const sub1 = store1Ref.store.dispatch(
+    sharedApi.endpoints.getTest.initiate(1, {
+      subscriptionOptions: { pollingInterval: 1000 },
+    }),
+  )
+  vi.advanceTimersByTime(10)
+  await sub1
+
+  // Wait for subscription sync (500ms + buffer)
+  vi.advanceTimersByTime(600)
+
+  // Verify store1 has the subscription
+  const store1SubscriptionSelectors = store1Ref.store.dispatch(
+    sharedApi.internalActions.internal_getRTKQSubscriptions(),
+  ) as any
+  const store1InternalSubs = store1SubscriptionSelectors.getSubscriptions()
+  expect(store1InternalSubs.size).toBe(1)
+
+  // Create second store (simulating second SSR request)
+  const store2Ref = setupApiStore(sharedApi, {}, { withoutListeners: true })
+
+  // Check subscriptions via internal action
+  const store2SubscriptionSelectors = store2Ref.store.dispatch(
+    sharedApi.internalActions.internal_getRTKQSubscriptions(),
+  ) as any
+
+  const store2InternalSubs = store2SubscriptionSelectors.getSubscriptions()
+
+  expect(store2InternalSubs.size).toBe(0)
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/buildSelector.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/buildSelector.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/buildSelector.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,111 @@
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+
+import { configureStore, createSelector } from '@reduxjs/toolkit'
+
+describe('type tests', () => {
+  test('buildSelector type test', () => {
+    interface Todo {
+      userId: number
+      id: number
+      title: string
+      completed: boolean
+    }
+
+    type Todos = Array<Todo>
+
+    const exampleApi = createApi({
+      reducerPath: 'api',
+      baseQuery: fetchBaseQuery({
+        baseUrl: 'https://jsonplaceholder.typicode.com',
+      }),
+      endpoints: (build) => ({
+        getTodos: build.query<Todos, string>({
+          query: () => '/todos',
+        }),
+      }),
+    })
+
+    const exampleQuerySelector = exampleApi.endpoints.getTodos.select('/')
+
+    const todosSelector = createSelector(
+      [exampleQuerySelector],
+      (queryState) => {
+        return queryState?.data?.[0] ?? ({} as Todo)
+      },
+    )
+
+    const firstTodoTitleSelector = createSelector(
+      [todosSelector],
+      (todo) => todo?.title,
+    )
+
+    const store = configureStore({
+      reducer: {
+        [exampleApi.reducerPath]: exampleApi.reducer,
+        other: () => 1,
+      },
+    })
+
+    const todoTitle = firstTodoTitleSelector(store.getState())
+
+    // This only compiles if we carried the types through
+    const upperTitle = todoTitle.toUpperCase()
+
+    expectTypeOf(upperTitle).toBeString()
+  })
+
+  test('selectCachedArgsForQuery type test', () => {
+    interface Todo {
+      userId: number
+      id: number
+      title: string
+      completed: boolean
+    }
+
+    type Todos = Array<Todo>
+
+    const exampleApi = createApi({
+      reducerPath: 'api',
+      baseQuery: fetchBaseQuery({
+        baseUrl: 'https://jsonplaceholder.typicode.com',
+      }),
+      endpoints: (build) => ({
+        getTodos: build.query<Todos, string>({
+          query: () => '/todos',
+        }),
+        getInfiniteTodos: build.infiniteQuery<Todos, string, number>({
+          infiniteQueryOptions: {
+            initialPageParam: 0,
+            maxPages: 3,
+            getNextPageParam: (
+              lastPage,
+              allPages,
+              lastPageParam,
+              allPageParams,
+            ) => lastPageParam + 1,
+          },
+          query({ pageParam }) {
+            return `/todos?page=${pageParam}`
+          },
+        }),
+      }),
+    })
+
+    const store = configureStore({
+      reducer: {
+        [exampleApi.reducerPath]: exampleApi.reducer,
+        other: () => 1,
+      },
+    })
+
+    expectTypeOf(
+      exampleApi.util.selectCachedArgsForQuery(store.getState(), 'getTodos'),
+    ).toEqualTypeOf<string[]>()
+    expectTypeOf(
+      exampleApi.util.selectCachedArgsForQuery(
+        store.getState(),
+        'getInfiniteTodos',
+      ),
+    ).toEqualTypeOf<string[]>()
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/buildSlice.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/buildSlice.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/buildSlice.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,239 @@
+import { createSlice, createAction } from '@reduxjs/toolkit'
+import type { CombinedState } from '@reduxjs/toolkit/query'
+import { createApi } from '@reduxjs/toolkit/query'
+import { delay } from 'msw'
+import { setupApiStore } from '../../tests/utils/helpers'
+
+let shouldApiResponseSuccess = true
+
+const rehydrateAction = createAction<{ api: CombinedState<any, any, any> }>(
+  'persist/REHYDRATE',
+)
+
+const baseQuery = (args?: any) => ({ data: args })
+const api = createApi({
+  baseQuery,
+  tagTypes: ['SUCCEED', 'FAILED'],
+  endpoints: (build) => ({
+    getUser: build.query<{ url: string; success: boolean }, number>({
+      query(id) {
+        return { url: `user/${id}`, success: shouldApiResponseSuccess }
+      },
+      providesTags: (result) => (result?.success ? ['SUCCEED'] : ['FAILED']),
+    }),
+  }),
+  extractRehydrationInfo(action, { reducerPath }) {
+    if (rehydrateAction.match(action)) {
+      return action.payload?.[reducerPath]
+    }
+    return undefined
+  },
+})
+const { getUser } = api.endpoints
+
+const authSlice = createSlice({
+  name: 'auth',
+  initialState: {
+    token: '1234',
+  },
+  reducers: {
+    setToken(state, action) {
+      state.token = action.payload
+    },
+  },
+})
+
+const storeRef = setupApiStore(api, { auth: authSlice.reducer })
+
+describe('buildSlice', () => {
+  beforeEach(() => {
+    shouldApiResponseSuccess = true
+  })
+
+  it('only resets the api state when resetApiState is dispatched', async () => {
+    storeRef.store.dispatch({ type: 'unrelated' }) // trigger "registered middleware" into place
+    const initialState = storeRef.store.getState()
+
+    await storeRef.store.dispatch(
+      getUser.initiate(1, { subscriptionOptions: { pollingInterval: 10 } }),
+    )
+
+    const initialQueryState = {
+      api: {
+        config: {
+          focused: true,
+          invalidationBehavior: 'delayed',
+          keepUnusedDataFor: 60,
+          middlewareRegistered: true,
+          online: true,
+          reducerPath: 'api',
+          refetchOnFocus: false,
+          refetchOnMountOrArgChange: false,
+          refetchOnReconnect: false,
+        },
+        mutations: {},
+        provided: expect.any(Object),
+        queries: {
+          'getUser(1)': {
+            data: {
+              success: true,
+              url: 'user/1',
+            },
+            endpointName: 'getUser',
+            fulfilledTimeStamp: expect.any(Number),
+            originalArgs: 1,
+            requestId: expect.any(String),
+            startedTimeStamp: expect.any(Number),
+            status: 'fulfilled',
+          },
+        },
+        // Filled some time later
+        subscriptions: {},
+      },
+      auth: {
+        token: '1234',
+      },
+    }
+
+    expect(storeRef.store.getState()).toEqual(initialQueryState)
+
+    storeRef.store.dispatch(api.util.resetApiState())
+
+    expect(storeRef.store.getState()).toEqual(initialState)
+  })
+
+  it('replaces previous tags with new provided tags', async () => {
+    await storeRef.store.dispatch(getUser.initiate(1))
+
+    expect(
+      api.util.selectInvalidatedBy(storeRef.store.getState(), ['SUCCEED']),
+    ).toHaveLength(1)
+    expect(
+      api.util.selectInvalidatedBy(storeRef.store.getState(), ['FAILED']),
+    ).toHaveLength(0)
+
+    shouldApiResponseSuccess = false
+
+    storeRef.store.dispatch(getUser.initiate(1)).refetch()
+
+    await delay(10)
+
+    expect(
+      api.util.selectInvalidatedBy(storeRef.store.getState(), ['SUCCEED']),
+    ).toHaveLength(0)
+    expect(
+      api.util.selectInvalidatedBy(storeRef.store.getState(), ['FAILED']),
+    ).toHaveLength(1)
+  })
+
+  it('handles extractRehydrationInfo correctly', async () => {
+    await storeRef.store.dispatch(getUser.initiate(1))
+    await storeRef.store.dispatch(getUser.initiate(2))
+
+    const stateWithUser = storeRef.store.getState()
+
+    storeRef.store.dispatch(api.util.resetApiState())
+
+    storeRef.store.dispatch(rehydrateAction({ api: stateWithUser.api }))
+
+    const rehydratedState = storeRef.store.getState()
+    expect(rehydratedState).toEqual(stateWithUser)
+  })
+})
+
+describe('`merge` callback', () => {
+  const baseQuery = (args?: any) => ({ data: args })
+
+  interface Todo {
+    id: string
+    text: string
+  }
+
+  it('Calls `merge` once there is existing data, and allows mutations of cache state', async () => {
+    let mergeCalled = false
+    let queryFnCalls = 0
+    const todoTexts = ['A', 'B', 'C', 'D']
+
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        getTodos: build.query<Todo[], void>({
+          async queryFn() {
+            const text = todoTexts[queryFnCalls]
+            return { data: [{ id: `${queryFnCalls++}`, text }] }
+          },
+          merge(currentCacheValue, responseData) {
+            mergeCalled = true
+            currentCacheValue.push(...responseData)
+          },
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    const selectTodoEntry = api.endpoints.getTodos.select()
+
+    const res = storeRef.store.dispatch(api.endpoints.getTodos.initiate())
+    await res
+    expect(mergeCalled).toBe(false)
+    const todoEntry1 = selectTodoEntry(storeRef.store.getState())
+    expect(todoEntry1.data).toEqual([{ id: '0', text: 'A' }])
+
+    res.refetch()
+
+    await delay(10)
+
+    expect(mergeCalled).toBe(true)
+    const todoEntry2 = selectTodoEntry(storeRef.store.getState())
+
+    expect(todoEntry2.data).toEqual([
+      { id: '0', text: 'A' },
+      { id: '1', text: 'B' },
+    ])
+  })
+
+  it('Allows returning a different value from `merge`', async () => {
+    let firstQueryFnCall = true
+
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        getTodos: build.query<Todo[], void>({
+          async queryFn() {
+            const item = firstQueryFnCall
+              ? { id: '0', text: 'A' }
+              : { id: '1', text: 'B' }
+            firstQueryFnCall = false
+            return { data: [item] }
+          },
+          merge(currentCacheValue, responseData) {
+            return responseData
+          },
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    const selectTodoEntry = api.endpoints.getTodos.select()
+
+    const res = storeRef.store.dispatch(api.endpoints.getTodos.initiate())
+    await res
+
+    const todoEntry1 = selectTodoEntry(storeRef.store.getState())
+    expect(todoEntry1.data).toEqual([{ id: '0', text: 'A' }])
+
+    res.refetch()
+
+    await delay(10)
+
+    const todoEntry2 = selectTodoEntry(storeRef.store.getState())
+
+    expect(todoEntry2.data).toEqual([{ id: '1', text: 'B' }])
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/buildThunks.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/buildThunks.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/buildThunks.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,420 @@
+import { configureStore } from '@reduxjs/toolkit'
+import { createApi } from '@reduxjs/toolkit/query/react'
+import { renderHook, waitFor } from '@testing-library/react'
+import {
+  actionsReducer,
+  setupApiStore,
+  withProvider,
+} from '../../tests/utils/helpers'
+import type { BaseQueryApi } from '../baseQueryTypes'
+
+describe('baseline thunk behavior', () => {
+  test('handles a non-async baseQuery without error', async () => {
+    const baseQuery = (args?: any) => ({ data: args })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        getUser: build.query<unknown, number>({
+          query(id) {
+            return { url: `user/${id}` }
+          },
+        }),
+      }),
+    })
+    const { getUser } = api.endpoints
+    const store = configureStore({
+      reducer: {
+        [api.reducerPath]: api.reducer,
+      },
+      middleware: (gDM) => gDM().concat(api.middleware),
+    })
+
+    const promise = store.dispatch(getUser.initiate(1))
+    const { data } = await promise
+
+    expect(data).toEqual({
+      url: 'user/1',
+    })
+
+    const storeResult = getUser.select(1)(store.getState())
+    expect(storeResult).toEqual({
+      data: {
+        url: 'user/1',
+      },
+      endpointName: 'getUser',
+      isError: false,
+      isLoading: false,
+      isSuccess: true,
+      isUninitialized: false,
+      originalArgs: 1,
+      requestId: expect.any(String),
+      status: 'fulfilled',
+      startedTimeStamp: expect.any(Number),
+      fulfilledTimeStamp: expect.any(Number),
+    })
+  })
+
+  test('passes the extraArgument property to the baseQueryApi', async () => {
+    const baseQuery = (_args: any, api: BaseQueryApi) => ({ data: api.extra })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        getUser: build.query<unknown, void>({
+          query: () => '',
+        }),
+      }),
+    })
+    const store = configureStore({
+      reducer: {
+        [api.reducerPath]: api.reducer,
+      },
+      middleware: (gDM) =>
+        gDM({ thunk: { extraArgument: 'cakes' } }).concat(api.middleware),
+    })
+    const { getUser } = api.endpoints
+    const { data } = await store.dispatch(getUser.initiate())
+    expect(data).toBe('cakes')
+  })
+
+  test('only triggers transformResponse when a query method is actually used', async () => {
+    const baseQuery = (args?: any) => ({ data: args })
+    const transformResponse = vi.fn((response: any) => response)
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        hasQuery: build.query<string, string>({
+          query: (arg) => 'test',
+          transformResponse,
+        }),
+        hasQueryFn: build.query<string, void>(
+          // @ts-expect-error
+          {
+            queryFn: () => ({ data: 'test' }),
+            transformResponse,
+          },
+        ),
+      }),
+    })
+
+    const store = configureStore({
+      reducer: {
+        [api.reducerPath]: api.reducer,
+      },
+      middleware: (gDM) =>
+        gDM({ thunk: { extraArgument: 'cakes' } }).concat(api.middleware),
+    })
+
+    await store.dispatch(api.util.upsertQueryData('hasQuery', 'a', 'test'))
+    expect(transformResponse).not.toHaveBeenCalled()
+
+    transformResponse.mockReset()
+
+    await store.dispatch(api.endpoints.hasQuery.initiate('b'))
+    expect(transformResponse).toHaveBeenCalledTimes(1)
+
+    transformResponse.mockReset()
+
+    await store.dispatch(api.endpoints.hasQueryFn.initiate())
+    expect(transformResponse).not.toHaveBeenCalled()
+  })
+})
+
+describe('re-triggering behavior on arg change', () => {
+  const api = createApi({
+    baseQuery: () => ({ data: null }),
+    endpoints: (build) => ({
+      getUser: build.query<any, any>({
+        query: (obj) => obj,
+      }),
+    }),
+  })
+  const { getUser } = api.endpoints
+  const store = configureStore({
+    reducer: { [api.reducerPath]: api.reducer },
+    middleware: (gDM) => gDM().concat(api.middleware),
+  })
+
+  const spy = vi.spyOn(getUser, 'initiate')
+  beforeEach(() => void spy.mockClear())
+
+  test('re-trigger on literal value change', async () => {
+    const { result, rerender } = renderHook(
+      (props) => getUser.useQuery(props),
+      {
+        wrapper: withProvider(store),
+        initialProps: 5,
+      },
+    )
+
+    await waitFor(() => {
+      expect(result.current.status).not.toBe('pending')
+    })
+
+    expect(spy).toHaveBeenCalledOnce()
+
+    for (let x = 1; x < 3; x++) {
+      rerender(6)
+      await waitFor(() => {
+        expect(result.current.status).not.toBe('pending')
+      })
+      expect(spy).toHaveBeenCalledTimes(2)
+    }
+
+    for (let x = 1; x < 3; x++) {
+      rerender(7)
+      await waitFor(() => {
+        expect(result.current.status).not.toBe('pending')
+      })
+      expect(spy).toHaveBeenCalledTimes(3)
+    }
+  })
+
+  test('only re-trigger on shallow-equal arg change', async () => {
+    const { result, rerender } = renderHook(
+      (props) => getUser.useQuery(props),
+      {
+        wrapper: withProvider(store),
+        initialProps: { name: 'Bob', likes: 'iceCream' },
+      },
+    )
+
+    await waitFor(() => {
+      expect(result.current.status).not.toBe('pending')
+    })
+    expect(spy).toHaveBeenCalledOnce()
+
+    for (let x = 1; x < 3; x++) {
+      rerender({ name: 'Bob', likes: 'waffles' })
+      await waitFor(() => {
+        expect(result.current.status).not.toBe('pending')
+      })
+      expect(spy).toHaveBeenCalledTimes(2)
+    }
+
+    for (let x = 1; x < 3; x++) {
+      rerender({ name: 'Alice', likes: 'waffles' })
+      await waitFor(() => {
+        expect(result.current.status).not.toBe('pending')
+      })
+      expect(spy).toHaveBeenCalledTimes(3)
+    }
+  })
+
+  test('re-triggers every time on deeper value changes', async () => {
+    const name = 'Tim'
+
+    const { result, rerender } = renderHook(
+      (props) => getUser.useQuery(props),
+      {
+        wrapper: withProvider(store),
+        initialProps: { person: { name } },
+      },
+    )
+
+    await waitFor(() => {
+      expect(result.current.status).not.toBe('pending')
+    })
+    expect(spy).toHaveBeenCalledOnce()
+
+    for (let x = 1; x < 3; x++) {
+      rerender({ person: { name: name + x } })
+      await waitFor(() => {
+        expect(result.current.status).not.toBe('pending')
+      })
+      expect(spy).toHaveBeenCalledTimes(x + 1)
+    }
+  })
+
+  test('do not re-trigger if the order of keys change while maintaining the same values', async () => {
+    const { result, rerender } = renderHook(
+      (props) => getUser.useQuery(props),
+      {
+        wrapper: withProvider(store),
+        initialProps: { name: 'Tim', likes: 'Bananas' },
+      },
+    )
+
+    await waitFor(() => {
+      expect(result.current.status).not.toBe('pending')
+    })
+    expect(spy).toHaveBeenCalledOnce()
+
+    for (let x = 1; x < 3; x++) {
+      rerender({ likes: 'Bananas', name: 'Tim' })
+      await waitFor(() => {
+        expect(result.current.status).not.toBe('pending')
+      })
+      expect(spy).toHaveBeenCalledOnce()
+    }
+  })
+})
+
+describe('prefetch', () => {
+  const baseQuery = () => ({ data: { name: 'Test User' } })
+
+  const api = createApi({
+    baseQuery,
+    tagTypes: ['User'],
+    endpoints: (build) => ({
+      getUser: build.query<any, number>({
+        query: (id) => ({ url: `user/${id}` }),
+        providesTags: (result, error, id) => [{ type: 'User', id }],
+      }),
+      updateUser: build.mutation<any, { id: number; name: string }>({
+        query: ({ id, name }) => ({
+          url: `user/${id}`,
+          method: 'PUT',
+          body: { name },
+        }),
+        invalidatesTags: (result, error, { id }) => [{ type: 'User', id }],
+      }),
+    }),
+    keepUnusedDataFor: 0.1, // 100ms for faster test cleanup
+  })
+
+  let storeRef = setupApiStore(
+    api,
+    { ...actionsReducer },
+    {
+      withoutListeners: true,
+    },
+  )
+
+  let getSubscriptions: () => Map<string, any>
+  let getSubscriptionCount: (queryCacheKey: string) => number
+
+  beforeEach(() => {
+    storeRef = setupApiStore(
+      api,
+      { ...actionsReducer },
+      {
+        withoutListeners: true,
+      },
+    )
+    // Get subscription helpers
+    const subscriptionSelectors = storeRef.store.dispatch(
+      api.internalActions.internal_getRTKQSubscriptions(),
+    ) as any
+    getSubscriptions = subscriptionSelectors.getSubscriptions
+    getSubscriptionCount = subscriptionSelectors.getSubscriptionCount
+  })
+
+  describe('subscription behavior', () => {
+    it('prefetch should NOT create a subscription', async () => {
+      const queryCacheKey = 'getUser(1)'
+
+      // Initially no subscriptions
+      expect(getSubscriptionCount(queryCacheKey)).toBe(0)
+
+      // Dispatch prefetch
+      storeRef.store.dispatch(api.util.prefetch('getUser', 1, {}))
+      await Promise.all(
+        storeRef.store.dispatch(api.util.getRunningQueriesThunk()),
+      )
+
+      expect(getSubscriptionCount(queryCacheKey)).toBe(0)
+    })
+
+    it('prefetch allows cache cleanup after keepUnusedDataFor', async () => {
+      const queryCacheKey = 'getUser(1)'
+
+      // Prefetch the data
+      storeRef.store.dispatch(api.util.prefetch('getUser', 1, {}))
+      await Promise.all(
+        storeRef.store.dispatch(api.util.getRunningQueriesThunk()),
+      )
+
+      // Verify data is in cache
+      let state = api.endpoints.getUser.select(1)(storeRef.store.getState())
+      expect(state.data).toEqual({ name: 'Test User' })
+
+      // Wait longer than keepUnusedDataFor
+      await new Promise((resolve) => setTimeout(resolve, 150))
+
+      state = api.endpoints.getUser.select(1)(storeRef.store.getState())
+      expect(state.status).toBe('uninitialized')
+      expect(state.data).toBeUndefined()
+    })
+
+    it('prefetch does NOT trigger refetch on tag invalidation', async () => {
+      // Prefetch user 1
+      storeRef.store.dispatch(api.util.prefetch('getUser', 1, {}))
+      await Promise.all(
+        storeRef.store.dispatch(api.util.getRunningQueriesThunk()),
+      )
+
+      // Verify data is in cache
+      let state = api.endpoints.getUser.select(1)(storeRef.store.getState())
+      expect(state.data).toEqual({ name: 'Test User' })
+
+      // Invalidate the tag by updating the user
+      await storeRef.store.dispatch(
+        api.endpoints.updateUser.initiate({ id: 1, name: 'Updated' }),
+      )
+
+      // Since there's no subscription, the cache entry gets removed on invalidation
+      await Promise.all(
+        storeRef.store.dispatch(api.util.getRunningQueriesThunk()),
+      )
+
+      // Cache entry should be cleared (no subscription to keep it alive)
+      state = api.endpoints.getUser.select(1)(storeRef.store.getState())
+      expect(state.status).toBe('uninitialized')
+      expect(state.data).toBeUndefined()
+    })
+
+    it('multiple prefetches do not accumulate subscriptions', async () => {
+      const queryCacheKey = 'getUser(1)'
+
+      expect(getSubscriptionCount(queryCacheKey)).toBe(0)
+
+      // First prefetch
+      storeRef.store.dispatch(api.util.prefetch('getUser', 1, {}))
+      await Promise.all(
+        storeRef.store.dispatch(api.util.getRunningQueriesThunk()),
+      )
+      expect(getSubscriptionCount(queryCacheKey)).toBe(0)
+
+      // Second prefetch (force refetch)
+      storeRef.store.dispatch(api.util.prefetch('getUser', 1, { force: true }))
+      await Promise.all(
+        storeRef.store.dispatch(api.util.getRunningQueriesThunk()),
+      )
+
+      // Still no subscriptions
+      expect(getSubscriptionCount(queryCacheKey)).toBe(0)
+
+      // Third prefetch
+      storeRef.store.dispatch(api.util.prefetch('getUser', 1, { force: true }))
+      await Promise.all(
+        storeRef.store.dispatch(api.util.getRunningQueriesThunk()),
+      )
+      expect(getSubscriptionCount(queryCacheKey)).toBe(0)
+    })
+
+    it('prefetch followed by regular query should work correctly', async () => {
+      const queryCacheKey = 'getUser(1)'
+
+      // Prefetch first
+      storeRef.store.dispatch(api.util.prefetch('getUser', 1, {}))
+      await Promise.all(
+        storeRef.store.dispatch(api.util.getRunningQueriesThunk()),
+      )
+
+      // No subscription from prefetch
+      expect(getSubscriptionCount(queryCacheKey)).toBe(0)
+
+      // Now create a real subscription via initiate
+      const promise = storeRef.store.dispatch(api.endpoints.getUser.initiate(1))
+
+      // Should have 1 subscription from the initiate call
+      expect(getSubscriptionCount(queryCacheKey)).toBe(1)
+
+      // Unsubscribe
+      promise.unsubscribe()
+
+      // Subscription should be cleaned up
+      expect(getSubscriptionCount(queryCacheKey)).toBe(0)
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/cacheCollection.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/cacheCollection.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/cacheCollection.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,231 @@
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+import { configureStore } from '@reduxjs/toolkit'
+import { vi } from 'vitest'
+import type { Middleware, Reducer } from 'redux'
+import {
+  THIRTY_TWO_BIT_MAX_INT,
+  THIRTY_TWO_BIT_MAX_TIMER_SECONDS,
+} from '../core/buildMiddleware/cacheCollection'
+import { countObjectKeys } from '../utils/countObjectKeys'
+
+beforeAll(() => {
+  vi.useFakeTimers()
+})
+
+const onCleanup = vi.fn()
+
+beforeEach(() => {
+  onCleanup.mockClear()
+})
+
+test(`query: await cleanup, defaults`, async () => {
+  const { store, api } = storeForApi(
+    createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+      endpoints: (build) => ({
+        query: build.query<unknown, string>({
+          query: () => '/success',
+        }),
+      }),
+    }),
+  )
+
+  const promise = store.dispatch(api.endpoints.query.initiate('arg'))
+  await promise
+  promise.unsubscribe()
+  vi.advanceTimersByTime(59000)
+  expect(onCleanup).not.toHaveBeenCalled()
+  vi.advanceTimersByTime(2000)
+  expect(onCleanup).toHaveBeenCalled()
+})
+
+test(`query: await cleanup, keepUnusedDataFor set`, async () => {
+  const { store, api } = storeForApi(
+    createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+      endpoints: (build) => ({
+        query: build.query<unknown, string>({
+          query: () => '/success',
+        }),
+      }),
+      keepUnusedDataFor: 29,
+    }),
+  )
+
+  const promise = store.dispatch(api.endpoints.query.initiate('arg'))
+  await promise
+  promise.unsubscribe()
+  vi.advanceTimersByTime(28000)
+  expect(onCleanup).not.toHaveBeenCalled()
+  vi.advanceTimersByTime(2000)
+  expect(onCleanup).toHaveBeenCalled()
+})
+
+test(`query: handles large keepUnuseDataFor values over 32-bit ms`, async () => {
+  const { store, api } = storeForApi(
+    createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+      endpoints: (build) => ({
+        query: build.query<unknown, string>({
+          query: () => '/success',
+        }),
+      }),
+      keepUnusedDataFor: THIRTY_TWO_BIT_MAX_TIMER_SECONDS - 10,
+    }),
+  )
+
+  const promise = store.dispatch(api.endpoints.query.initiate('arg'))
+  await promise
+  promise.unsubscribe()
+
+  // Shouldn't have been called right away
+  vi.advanceTimersByTime(1000)
+  expect(onCleanup).not.toHaveBeenCalled()
+
+  // Shouldn't have been called any time in the next few minutes
+  vi.advanceTimersByTime(1_000_000)
+  expect(onCleanup).not.toHaveBeenCalled()
+
+  // _Should_ be called _wayyyy_ in the future (like 24.8 days from now)
+  vi.advanceTimersByTime(THIRTY_TWO_BIT_MAX_TIMER_SECONDS * 1000),
+    expect(onCleanup).toHaveBeenCalled()
+})
+
+describe(`query: await cleanup, keepUnusedDataFor set`, () => {
+  const { store, api } = storeForApi(
+    createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+      endpoints: (build) => ({
+        query: build.query<unknown, string>({
+          query: () => '/success',
+        }),
+        query2: build.query<unknown, string>({
+          query: () => '/success',
+          keepUnusedDataFor: 35,
+        }),
+        query3: build.query<unknown, string>({
+          query: () => '/success',
+          keepUnusedDataFor: 0,
+        }),
+        query4: build.query<unknown, string>({
+          query: () => '/success',
+          keepUnusedDataFor: Infinity,
+        }),
+      }),
+      keepUnusedDataFor: 29,
+    }),
+  )
+
+  test('global keepUnusedDataFor', async () => {
+    const promise = store.dispatch(api.endpoints.query.initiate('arg'))
+    await promise
+    promise.unsubscribe()
+    vi.advanceTimersByTime(28000)
+    expect(onCleanup).not.toHaveBeenCalled()
+    vi.advanceTimersByTime(2000)
+    expect(onCleanup).toHaveBeenCalled()
+  })
+
+  test('endpoint keepUnusedDataFor', async () => {
+    const promise = store.dispatch(api.endpoints.query2.initiate('arg'))
+    await promise
+    promise.unsubscribe()
+
+    vi.advanceTimersByTime(34000)
+    expect(onCleanup).not.toHaveBeenCalled()
+    vi.advanceTimersByTime(2000)
+    expect(onCleanup).toHaveBeenCalled()
+  })
+
+  test('endpoint keepUnusedDataFor: 0 ', async () => {
+    expect(onCleanup).not.toHaveBeenCalled()
+    const promise = store.dispatch(api.endpoints.query3.initiate('arg'))
+    await promise
+    promise.unsubscribe()
+    expect(onCleanup).not.toHaveBeenCalled()
+    vi.advanceTimersByTime(1)
+    expect(onCleanup).toHaveBeenCalled()
+  })
+
+  test('endpoint keepUnusedDataFor: Infinity', async () => {
+    expect(onCleanup).not.toHaveBeenCalled()
+    store.dispatch(api.endpoints.query4.initiate('arg')).unsubscribe()
+    expect(onCleanup).not.toHaveBeenCalled()
+    vi.advanceTimersByTime(THIRTY_TWO_BIT_MAX_INT)
+    expect(onCleanup).not.toHaveBeenCalled()
+  })
+})
+
+describe('resetApiState cleanup', () => {
+  test('resetApiState aborts multiple running queries and mutations', async () => {
+    const { store, api } = storeForApi(
+      createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+        endpoints: (build) => ({
+          query1: build.query<unknown, string>({
+            query: () => '/success',
+          }),
+          query2: build.query<unknown, string>({
+            query: () => '/success',
+          }),
+          mutation: build.mutation<unknown, string>({
+            query: () => ({
+              url: '/success',
+              method: 'POST',
+            }),
+          }),
+        }),
+      }),
+    )
+
+    // Start multiple queries and a mutation
+    const queryPromise1 = store.dispatch(api.endpoints.query1.initiate('arg1'))
+    const queryPromise2 = store.dispatch(api.endpoints.query2.initiate('arg2'))
+    const mutationPromise = store.dispatch(
+      api.endpoints.mutation.initiate('arg'),
+    )
+
+    // Spy on abort methods
+    queryPromise1.abort = vi.fn(queryPromise1.abort)
+    queryPromise2.abort = vi.fn(queryPromise2.abort)
+    mutationPromise.abort = vi.fn(mutationPromise.abort)
+
+    // Dispatch resetApiState
+    store.dispatch(api.util.resetApiState())
+
+    // Verify all aborts were called
+    expect(queryPromise1.abort).toHaveBeenCalled()
+    expect(queryPromise2.abort).toHaveBeenCalled()
+    expect(mutationPromise.abort).toHaveBeenCalled()
+  })
+})
+
+function storeForApi<
+  A extends {
+    reducerPath: 'api'
+    reducer: Reducer<any, any>
+    middleware: Middleware
+    util: { resetApiState(): any }
+  },
+>(api: A) {
+  const store = configureStore({
+    reducer: { api: api.reducer },
+    middleware: (gdm) =>
+      gdm({ serializableCheck: false, immutableCheck: false }).concat(
+        api.middleware,
+      ),
+    enhancers: (gde) =>
+      gde({
+        autoBatch: false,
+      }),
+  })
+  let hadQueries = false
+  store.subscribe(() => {
+    const queryState = store.getState().api.queries
+    if (hadQueries && countObjectKeys(queryState) === 0) {
+      onCleanup()
+    }
+    hadQueries = hadQueries || countObjectKeys(queryState) > 0
+  })
+  return { api, store }
+}
Index: node_modules/@reduxjs/toolkit/src/query/tests/cacheLifecycle.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/cacheLifecycle.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/cacheLifecycle.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,31 @@
+import type { FetchBaseQueryMeta } from '@reduxjs/toolkit/query'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+
+const api = createApi({
+  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+  endpoints: () => ({}),
+})
+
+describe('type tests', () => {
+  test(`mutation: await cacheDataLoaded, await cacheEntryRemoved (success)`, () => {
+    const extended = api.injectEndpoints({
+      overrideExisting: true,
+      endpoints: (build) => ({
+        injected: build.mutation<number, string>({
+          query: () => '/success',
+          async onCacheEntryAdded(
+            arg,
+            { dispatch, getState, cacheEntryRemoved, cacheDataLoaded },
+          ) {
+            const firstValue = await cacheDataLoaded
+
+            expectTypeOf(firstValue).toMatchTypeOf<{
+              data: number
+              meta?: FetchBaseQueryMeta
+            }>()
+          },
+        }),
+      }),
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/cacheLifecycle.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/cacheLifecycle.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/cacheLifecycle.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,708 @@
+import {
+  DEFAULT_DELAY_MS,
+  fakeTimerWaitFor,
+  setupApiStore,
+} from '@internal/tests/utils/helpers'
+import type { QueryActionCreatorResult } from '@reduxjs/toolkit/query'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+
+beforeAll(() => {
+  vi.useFakeTimers()
+})
+
+const api = createApi({
+  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+  endpoints: () => ({}),
+})
+const storeRef = setupApiStore(api)
+
+const onNewCacheEntry = vi.fn()
+const gotFirstValue = vi.fn()
+const onCleanup = vi.fn()
+const onCatch = vi.fn()
+
+beforeEach(() => {
+  onNewCacheEntry.mockClear()
+  gotFirstValue.mockClear()
+  onCleanup.mockClear()
+  onCatch.mockClear()
+})
+
+describe.each([['query'], ['mutation']] as const)(
+  'generic cases: %s',
+  (type) => {
+    test(`${type}: new cache entry only`, async () => {
+      const extended = api.injectEndpoints({
+        overrideExisting: true,
+        endpoints: (build) => ({
+          injected: build[type as 'mutation']<unknown, string>({
+            query: () => '/success',
+            onCacheEntryAdded(arg, { dispatch, getState }) {
+              onNewCacheEntry(arg)
+            },
+          }),
+        }),
+      })
+      storeRef.store.dispatch(extended.endpoints.injected.initiate('arg'))
+      expect(onNewCacheEntry).toHaveBeenCalledWith('arg')
+    })
+
+    test(`${type}: await cacheEntryRemoved`, async () => {
+      const extended = api.injectEndpoints({
+        overrideExisting: true,
+        endpoints: (build) => ({
+          // Lying to TS here
+          injected: build[type as 'mutation']<unknown, string>({
+            query: () => '/success',
+            async onCacheEntryAdded(
+              arg,
+              { dispatch, getState, cacheEntryRemoved },
+            ) {
+              onNewCacheEntry(arg)
+              await cacheEntryRemoved
+              onCleanup()
+            },
+          }),
+        }),
+      })
+      const promise = storeRef.store.dispatch(
+        extended.endpoints.injected.initiate('arg'),
+      )
+
+      expect(onNewCacheEntry).toHaveBeenCalledWith('arg')
+      expect(onCleanup).not.toHaveBeenCalled()
+
+      await promise
+      if (type === 'mutation') {
+        promise.reset()
+      } else {
+        ;(promise as unknown as QueryActionCreatorResult<any>).unsubscribe()
+      }
+      await vi.advanceTimersByTimeAsync(DEFAULT_DELAY_MS)
+      if (type === 'query') {
+        await vi.advanceTimersByTimeAsync(59000)
+        expect(onCleanup).not.toHaveBeenCalled()
+        await vi.advanceTimersByTimeAsync(2000)
+      }
+
+      expect(onCleanup).toHaveBeenCalled()
+    })
+
+    test(`${type}: await cacheDataLoaded, await cacheEntryRemoved (success)`, async () => {
+      const extended = api.injectEndpoints({
+        overrideExisting: true,
+        endpoints: (build) => ({
+          injected: build[type as 'mutation']<number, string>({
+            query: () => '/success',
+            async onCacheEntryAdded(
+              arg,
+              { dispatch, getState, cacheEntryRemoved, cacheDataLoaded },
+            ) {
+              onNewCacheEntry(arg)
+              const firstValue = await cacheDataLoaded
+              gotFirstValue(firstValue)
+              await cacheEntryRemoved
+              onCleanup()
+            },
+          }),
+        }),
+      })
+      const promise = storeRef.store.dispatch(
+        extended.endpoints.injected.initiate('arg'),
+      )
+
+      expect(onNewCacheEntry).toHaveBeenCalledWith('arg')
+
+      expect(gotFirstValue).not.toHaveBeenCalled()
+      expect(onCleanup).not.toHaveBeenCalled()
+
+      await fakeTimerWaitFor(() => {
+        expect(gotFirstValue).toHaveBeenCalled()
+      })
+      expect(gotFirstValue).toHaveBeenCalledWith({
+        data: { value: 'success' },
+        meta: {
+          request: expect.any(Request),
+          response: expect.any(Object), // Response is not available in jest env
+        },
+      })
+      expect(onCleanup).not.toHaveBeenCalled()
+
+      if (type === 'mutation') {
+        promise.reset()
+      } else {
+        ;(promise as unknown as QueryActionCreatorResult<any>).unsubscribe()
+      }
+      await vi.advanceTimersByTimeAsync(DEFAULT_DELAY_MS)
+      if (type === 'query') {
+        await vi.advanceTimersByTimeAsync(59000)
+        expect(onCleanup).not.toHaveBeenCalled()
+        await vi.advanceTimersByTimeAsync(2000)
+      }
+
+      expect(onCleanup).toHaveBeenCalled()
+    })
+
+    test(`${type}: await cacheDataLoaded, await cacheEntryRemoved (cacheDataLoaded never resolves)`, async () => {
+      const extended = api.injectEndpoints({
+        overrideExisting: true,
+        endpoints: (build) => ({
+          injected: build[type as 'mutation']<unknown, string>({
+            query: () => '/error', // we will initiate only once and that one time will be an error -> cacheDataLoaded will never resolve
+            async onCacheEntryAdded(
+              arg,
+              { dispatch, getState, cacheEntryRemoved, cacheDataLoaded },
+            ) {
+              onNewCacheEntry(arg)
+              // this will wait until cacheEntryRemoved, then reject => nothing past that line will execute
+              // but since this special "cacheEntryRemoved" rejection is handled outside, there will be no
+              // uncaught rejection error
+              const firstValue = await cacheDataLoaded
+              gotFirstValue(firstValue)
+              await cacheEntryRemoved
+              onCleanup()
+            },
+          }),
+        }),
+      })
+      const promise = storeRef.store.dispatch(
+        extended.endpoints.injected.initiate('arg'),
+      )
+      expect(onNewCacheEntry).toHaveBeenCalledWith('arg')
+
+      if (type === 'mutation') {
+        promise.reset()
+      } else {
+        ;(promise as unknown as QueryActionCreatorResult<any>).unsubscribe()
+      }
+      await vi.advanceTimersByTimeAsync(DEFAULT_DELAY_MS)
+      if (type === 'query') {
+        await vi.advanceTimersByTimeAsync(120000)
+      }
+      expect(gotFirstValue).not.toHaveBeenCalled()
+      expect(onCleanup).not.toHaveBeenCalled()
+    })
+
+    test(`${type}: try { await cacheDataLoaded }, await cacheEntryRemoved (cacheDataLoaded never resolves)`, async () => {
+      const extended = api.injectEndpoints({
+        overrideExisting: true,
+        endpoints: (build) => ({
+          injected: build[type as 'mutation']<unknown, string>({
+            query: () => '/error', // we will initiate only once and that one time will be an error -> cacheDataLoaded will never resolve
+            async onCacheEntryAdded(
+              arg,
+              { dispatch, getState, cacheEntryRemoved, cacheDataLoaded },
+            ) {
+              onNewCacheEntry(arg)
+
+              try {
+                // this will wait until cacheEntryRemoved, then reject => nothing else in this try..catch block will execute
+                const firstValue = await cacheDataLoaded
+                gotFirstValue(firstValue)
+              } catch (e) {
+                onCatch(e)
+              }
+              await cacheEntryRemoved
+              onCleanup()
+            },
+          }),
+        }),
+      })
+      const promise = storeRef.store.dispatch(
+        extended.endpoints.injected.initiate('arg'),
+      )
+
+      expect(onNewCacheEntry).toHaveBeenCalledWith('arg')
+      await promise
+      if (type === 'mutation') {
+        promise.reset()
+      } else {
+        ;(promise as unknown as QueryActionCreatorResult<any>).unsubscribe()
+      }
+      await vi.advanceTimersByTimeAsync(DEFAULT_DELAY_MS)
+
+      if (type === 'query') {
+        await vi.advanceTimersByTimeAsync(59000)
+        expect(onCleanup).not.toHaveBeenCalled()
+        await vi.advanceTimersByTimeAsync(2000)
+      }
+
+      expect(onCleanup).toHaveBeenCalled()
+      expect(gotFirstValue).not.toHaveBeenCalled()
+      expect(onCatch.mock.calls[0][0]).toMatchObject({
+        message: 'Promise never resolved before cacheEntryRemoved.',
+      })
+    })
+
+    test(`${type}: try { await cacheDataLoaded, await cacheEntryRemoved } (cacheDataLoaded never resolves)`, async () => {
+      const extended = api.injectEndpoints({
+        overrideExisting: true,
+        endpoints: (build) => ({
+          injected: build[type as 'mutation']<unknown, string>({
+            query: () => '/error', // we will initiate only once and that one time will be an error -> cacheDataLoaded will never resolve
+            async onCacheEntryAdded(
+              arg,
+              { dispatch, getState, cacheEntryRemoved, cacheDataLoaded },
+            ) {
+              onNewCacheEntry(arg)
+
+              try {
+                // this will wait until cacheEntryRemoved, then reject => nothing else in this try..catch block will execute
+                const firstValue = await cacheDataLoaded
+                gotFirstValue(firstValue)
+                // cleanup in this scenario only needs to be done for stuff within this try..catch block - totally valid scenario
+                await cacheEntryRemoved
+                onCleanup()
+              } catch (e) {
+                onCatch(e)
+              }
+            },
+          }),
+        }),
+      })
+      const promise = storeRef.store.dispatch(
+        extended.endpoints.injected.initiate('arg'),
+      )
+
+      expect(onNewCacheEntry).toHaveBeenCalledWith('arg')
+      await promise
+
+      if (type === 'mutation') {
+        promise.reset()
+      } else {
+        ;(promise as unknown as QueryActionCreatorResult<any>).unsubscribe()
+      }
+      await vi.advanceTimersByTimeAsync(DEFAULT_DELAY_MS)
+      if (type === 'query') {
+        await vi.advanceTimersByTimeAsync(59000)
+        expect(onCleanup).not.toHaveBeenCalled()
+        await vi.advanceTimersByTimeAsync(2000)
+      }
+      expect(onCleanup).not.toHaveBeenCalled()
+      expect(gotFirstValue).not.toHaveBeenCalled()
+      expect(onCatch.mock.calls[0][0]).toMatchObject({
+        message: 'Promise never resolved before cacheEntryRemoved.',
+      })
+    })
+
+    test(`${type}: try { await cacheDataLoaded } finally { await cacheEntryRemoved } (cacheDataLoaded never resolves)`, async () => {
+      const extended = api.injectEndpoints({
+        overrideExisting: true,
+        endpoints: (build) => ({
+          injected: build[type as 'mutation']<unknown, string>({
+            query: () => '/error', // we will initiate only once and that one time will be an error -> cacheDataLoaded will never resolve
+            async onCacheEntryAdded(
+              arg,
+              { dispatch, getState, cacheEntryRemoved, cacheDataLoaded },
+            ) {
+              onNewCacheEntry(arg)
+
+              try {
+                // this will wait until cacheEntryRemoved, then reject => nothing else in this try..catch block will execute
+                const firstValue = await cacheDataLoaded
+                gotFirstValue(firstValue)
+              } catch (e) {
+                onCatch(e)
+              } finally {
+                await cacheEntryRemoved
+                onCleanup()
+              }
+            },
+          }),
+        }),
+      })
+      const promise = storeRef.store.dispatch(
+        extended.endpoints.injected.initiate('arg'),
+      )
+
+      expect(onNewCacheEntry).toHaveBeenCalledWith('arg')
+
+      await promise
+      if (type === 'mutation') {
+        promise.reset()
+      } else {
+        ;(promise as unknown as QueryActionCreatorResult<any>).unsubscribe()
+      }
+      await vi.advanceTimersByTimeAsync(DEFAULT_DELAY_MS)
+      if (type === 'query') {
+        await vi.advanceTimersByTimeAsync(59000)
+        expect(onCleanup).not.toHaveBeenCalled()
+        await vi.advanceTimersByTimeAsync(2000)
+      }
+      expect(onCleanup).toHaveBeenCalled()
+      expect(gotFirstValue).not.toHaveBeenCalled()
+      expect(onCatch.mock.calls[0][0]).toMatchObject({
+        message: 'Promise never resolved before cacheEntryRemoved.',
+      })
+    })
+  },
+)
+
+test(`query: getCacheEntry`, async () => {
+  const snapshot = vi.fn()
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      injected: build.query<unknown, string>({
+        query: () => '/success',
+        async onCacheEntryAdded(
+          arg,
+          {
+            dispatch,
+            getState,
+            getCacheEntry,
+            cacheEntryRemoved,
+            cacheDataLoaded,
+          },
+        ) {
+          snapshot(getCacheEntry())
+          gotFirstValue(await cacheDataLoaded)
+          snapshot(getCacheEntry())
+          await cacheEntryRemoved
+          snapshot(getCacheEntry())
+        },
+      }),
+    }),
+  })
+  const promise = storeRef.store.dispatch(
+    extended.endpoints.injected.initiate('arg'),
+  )
+  await promise
+  promise.unsubscribe()
+
+  await fakeTimerWaitFor(() => {
+    expect(gotFirstValue).toHaveBeenCalled()
+  })
+
+  await vi.advanceTimersByTimeAsync(120000)
+
+  expect(snapshot).toHaveBeenCalledTimes(3)
+  expect(snapshot.mock.calls[0][0]).toMatchObject({
+    endpointName: 'injected',
+    isError: false,
+    isLoading: true,
+    isSuccess: false,
+    isUninitialized: false,
+    originalArgs: 'arg',
+    requestId: promise.requestId,
+    startedTimeStamp: expect.any(Number),
+    status: 'pending',
+  })
+  expect(snapshot.mock.calls[1][0]).toMatchObject({
+    data: {
+      value: 'success',
+    },
+    endpointName: 'injected',
+    fulfilledTimeStamp: expect.any(Number),
+    isError: false,
+    isLoading: false,
+    isSuccess: true,
+    isUninitialized: false,
+    originalArgs: 'arg',
+    requestId: promise.requestId,
+    startedTimeStamp: expect.any(Number),
+    status: 'fulfilled',
+  })
+  expect(snapshot.mock.calls[2][0]).toMatchObject({
+    isError: false,
+    isLoading: false,
+    isSuccess: false,
+    isUninitialized: true,
+    status: 'uninitialized',
+  })
+})
+
+test(`mutation: getCacheEntry`, async () => {
+  const snapshot = vi.fn()
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      injected: build.mutation<unknown, string>({
+        query: () => '/success',
+        async onCacheEntryAdded(
+          arg,
+          {
+            dispatch,
+            getState,
+            getCacheEntry,
+            cacheEntryRemoved,
+            cacheDataLoaded,
+          },
+        ) {
+          snapshot(getCacheEntry())
+          gotFirstValue(await cacheDataLoaded)
+          snapshot(getCacheEntry())
+          await cacheEntryRemoved
+          snapshot(getCacheEntry())
+        },
+      }),
+    }),
+  })
+  const promise = storeRef.store.dispatch(
+    extended.endpoints.injected.initiate('arg'),
+  )
+  await fakeTimerWaitFor(() => {
+    expect(gotFirstValue).toHaveBeenCalled()
+  })
+
+  promise.reset()
+  await vi.advanceTimersByTimeAsync(DEFAULT_DELAY_MS)
+
+  expect(snapshot).toHaveBeenCalledTimes(3)
+  expect(snapshot.mock.calls[0][0]).toMatchObject({
+    endpointName: 'injected',
+    isError: false,
+    isLoading: true,
+    isSuccess: false,
+    isUninitialized: false,
+    startedTimeStamp: expect.any(Number),
+    status: 'pending',
+  })
+  expect(snapshot.mock.calls[1][0]).toMatchObject({
+    data: {
+      value: 'success',
+    },
+    endpointName: 'injected',
+    fulfilledTimeStamp: expect.any(Number),
+    isError: false,
+    isLoading: false,
+    isSuccess: true,
+    isUninitialized: false,
+    startedTimeStamp: expect.any(Number),
+    status: 'fulfilled',
+  })
+  expect(snapshot.mock.calls[2][0]).toMatchObject({
+    isError: false,
+    isLoading: false,
+    isSuccess: false,
+    isUninitialized: true,
+    status: 'uninitialized',
+  })
+})
+
+test('query: updateCachedData', async () => {
+  const trackCalls = vi.fn()
+
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      injected: build.query<{ value: string }, string>({
+        query: () => '/success',
+        async onCacheEntryAdded(
+          arg,
+          {
+            dispatch,
+            getState,
+            getCacheEntry,
+            updateCachedData,
+            cacheEntryRemoved,
+            cacheDataLoaded,
+          },
+        ) {
+          expect(getCacheEntry().data).toEqual(undefined)
+          // calling `updateCachedData` when there is no data yet should not do anything
+          updateCachedData((draft) => {
+            draft.value = 'TEST'
+            trackCalls()
+          })
+          expect(trackCalls).not.toHaveBeenCalled()
+          expect(getCacheEntry().data).toEqual(undefined)
+
+          gotFirstValue(await cacheDataLoaded)
+
+          expect(getCacheEntry().data).toEqual({ value: 'success' })
+          updateCachedData((draft) => {
+            draft.value = 'TEST'
+            trackCalls()
+          })
+          expect(trackCalls).toHaveBeenCalledOnce()
+          expect(getCacheEntry().data).toEqual({ value: 'TEST' })
+
+          await cacheEntryRemoved
+
+          expect(getCacheEntry().data).toEqual(undefined)
+          // calling `updateCachedData` when there is no data any more should not do anything
+          updateCachedData((draft) => {
+            draft.value = 'TEST2'
+            trackCalls()
+          })
+          expect(trackCalls).toHaveBeenCalledOnce()
+          expect(getCacheEntry().data).toEqual(undefined)
+
+          onCleanup()
+        },
+      }),
+    }),
+  })
+  const promise = storeRef.store.dispatch(
+    extended.endpoints.injected.initiate('arg'),
+  )
+  await promise
+  promise.unsubscribe()
+
+  await fakeTimerWaitFor(() => {
+    expect(gotFirstValue).toHaveBeenCalled()
+  })
+
+  await vi.advanceTimersByTimeAsync(61000)
+
+  await fakeTimerWaitFor(() => {
+    expect(onCleanup).toHaveBeenCalled()
+  })
+})
+
+test('updateCachedData - infinite query', async () => {
+  const trackCalls = vi.fn()
+
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      infiniteInjected: build.infiniteQuery<{ value: string }, string, number>({
+        query: () => '/success',
+        infiniteQueryOptions: {
+          initialPageParam: 1,
+          getNextPageParam: (
+            lastPage,
+            allPages,
+            lastPageParam,
+            allPageParams,
+          ) => lastPageParam + 1,
+        },
+        async onCacheEntryAdded(
+          arg,
+          {
+            dispatch,
+            getState,
+            getCacheEntry,
+            updateCachedData,
+            cacheEntryRemoved,
+            cacheDataLoaded,
+          },
+        ) {
+          expect(getCacheEntry().data).toEqual(undefined)
+          // calling `updateCachedData` when there is no data yet should not do anything
+          updateCachedData((draft) => {
+            draft.pages = [{ value: 'TEST' }]
+            draft.pageParams = [1]
+            trackCalls()
+          })
+          expect(trackCalls).not.toHaveBeenCalled()
+          expect(getCacheEntry().data).toEqual(undefined)
+
+          gotFirstValue(await cacheDataLoaded)
+
+          expect(getCacheEntry().data).toEqual({
+            pages: [{ value: 'success' }],
+            pageParams: [1],
+          })
+          updateCachedData((draft) => {
+            draft.pages = [{ value: 'TEST' }]
+            draft.pageParams = [1]
+            trackCalls()
+          })
+          expect(trackCalls).toHaveBeenCalledOnce()
+          expect(getCacheEntry().data).toEqual({
+            pages: [{ value: 'TEST' }],
+            pageParams: [1],
+          })
+
+          await cacheEntryRemoved
+
+          expect(getCacheEntry().data).toEqual(undefined)
+          // calling `updateCachedData` when there is no data any more should not do anything
+          updateCachedData((draft) => {
+            draft.pages = [{ value: 'TEST' }, { value: 'TEST2' }]
+            draft.pageParams = [1, 2]
+            trackCalls()
+          })
+          expect(trackCalls).toHaveBeenCalledOnce()
+          expect(getCacheEntry().data).toEqual(undefined)
+
+          onCleanup()
+        },
+      }),
+    }),
+  })
+  const promise = storeRef.store.dispatch(
+    extended.endpoints.infiniteInjected.initiate('arg'),
+  )
+  await promise
+  promise.unsubscribe()
+
+  await fakeTimerWaitFor(() => {
+    expect(gotFirstValue).toHaveBeenCalled()
+  })
+
+  await vi.advanceTimersByTimeAsync(61000)
+
+  await fakeTimerWaitFor(() => {
+    expect(onCleanup).toHaveBeenCalled()
+  })
+})
+
+test('dispatching further actions does not trigger another lifecycle', async () => {
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      injected: build.query<unknown, void>({
+        query: () => '/success',
+        async onCacheEntryAdded() {
+          onNewCacheEntry()
+        },
+      }),
+    }),
+  })
+  await storeRef.store.dispatch(extended.endpoints.injected.initiate())
+  expect(onNewCacheEntry).toHaveBeenCalledOnce()
+
+  await storeRef.store.dispatch(extended.endpoints.injected.initiate())
+  expect(onNewCacheEntry).toHaveBeenCalledOnce()
+
+  await storeRef.store.dispatch(
+    extended.endpoints.injected.initiate(undefined, { forceRefetch: true }),
+  )
+  expect(onNewCacheEntry).toHaveBeenCalledOnce()
+})
+
+test('dispatching a query initializer with `subscribe: false` does also start a lifecycle', async () => {
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      injected: build.query<unknown, void>({
+        query: () => '/success',
+        async onCacheEntryAdded() {
+          onNewCacheEntry()
+        },
+      }),
+    }),
+  })
+  await storeRef.store.dispatch(
+    extended.endpoints.injected.initiate(undefined, { subscribe: false }),
+  )
+  expect(onNewCacheEntry).toHaveBeenCalledOnce()
+
+  // will not be called a second time though
+  await storeRef.store.dispatch(extended.endpoints.injected.initiate(undefined))
+  expect(onNewCacheEntry).toHaveBeenCalledOnce()
+})
+
+test('dispatching a mutation initializer with `track: false` does not start a lifecycle', async () => {
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      injected: build.mutation<unknown, void>({
+        query: () => '/success',
+        async onCacheEntryAdded() {
+          onNewCacheEntry()
+        },
+      }),
+    }),
+  })
+  await storeRef.store.dispatch(
+    extended.endpoints.injected.initiate(undefined, { track: false }),
+  )
+  expect(onNewCacheEntry).not.toHaveBeenCalled()
+
+  await storeRef.store.dispatch(extended.endpoints.injected.initiate(undefined))
+  expect(onNewCacheEntry).toHaveBeenCalledOnce()
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/cleanup.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/cleanup.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/cleanup.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,200 @@
+// tests for "cleanup-after-unsubscribe" behavior
+import React from 'react'
+
+import { createListenerMiddleware } from '@reduxjs/toolkit'
+import { createApi, QueryStatus } from '@reduxjs/toolkit/query/react'
+import { act, render, screen, waitFor } from '@testing-library/react'
+import { setupApiStore } from '../../tests/utils/helpers'
+import type { SubscriptionSelectors } from '../core/buildMiddleware/types'
+
+const api = createApi({
+  baseQuery: () => ({ data: 42 }),
+  endpoints: (build) => ({
+    a: build.query<unknown, void>({ query: () => '' }),
+    b: build.query<unknown, void>({ query: () => '' }),
+  }),
+})
+const storeRef = setupApiStore(api)
+
+const getSubStateA = () => storeRef.store.getState().api.queries['a(undefined)']
+const getSubStateB = () => storeRef.store.getState().api.queries['b(undefined)']
+
+function UsingA() {
+  const { data } = api.endpoints.a.useQuery()
+
+  return <>Result: {data as React.ReactNode} </>
+}
+
+function UsingB() {
+  api.endpoints.b.useQuery()
+
+  return <></>
+}
+
+function UsingAB() {
+  api.endpoints.a.useQuery()
+  api.endpoints.b.useQuery()
+
+  return <></>
+}
+
+beforeAll(() => {
+  vi.useFakeTimers({ shouldAdvanceTime: true })
+})
+
+test('data stays in store when component stays rendered', async () => {
+  expect(getSubStateA()).toBeUndefined()
+
+  render(<UsingA />, { wrapper: storeRef.wrapper })
+  await waitFor(() =>
+    expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled),
+  )
+
+  vi.advanceTimersByTime(120_000)
+
+  expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled)
+})
+
+test('data is removed from store after 60 seconds', async () => {
+  expect(getSubStateA()).toBeUndefined()
+
+  const { unmount } = render(<UsingA />, { wrapper: storeRef.wrapper })
+  await waitFor(() =>
+    expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled),
+  )
+
+  unmount()
+
+  vi.advanceTimersByTime(59_000)
+
+  expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled)
+
+  vi.advanceTimersByTime(2000)
+
+  expect(getSubStateA()).toBeUndefined()
+})
+
+test('data stays in store when component stays rendered while data for another component is removed after it unmounted', async () => {
+  expect(getSubStateA()).toBeUndefined()
+  expect(getSubStateB()).toBeUndefined()
+
+  const { rerender } = render(
+    <>
+      <UsingA />
+      <UsingB />
+    </>,
+    { wrapper: storeRef.wrapper },
+  )
+  await waitFor(() => {
+    expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled)
+    expect(getSubStateB()?.status).toBe(QueryStatus.fulfilled)
+  })
+
+  const statusA = getSubStateA()
+
+  await act(async () => {
+    rerender(<UsingA />)
+
+    vi.advanceTimersByTime(10)
+  })
+
+  vi.advanceTimersByTime(120_000)
+
+  expect(getSubStateA()).toEqual(statusA)
+  expect(getSubStateB()).toBeUndefined()
+})
+
+test('data stays in store when one component requiring the data stays in the store', async () => {
+  expect(getSubStateA()).toBeUndefined()
+  expect(getSubStateB()).toBeUndefined()
+
+  const { rerender } = render(
+    <>
+      <UsingA key="a" />
+      <UsingAB key="ab" />
+    </>,
+    { wrapper: storeRef.wrapper },
+  )
+  await waitFor(() => {
+    expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled)
+    expect(getSubStateB()?.status).toBe(QueryStatus.fulfilled)
+  })
+
+  const statusA = getSubStateA()
+  const statusB = getSubStateB()
+
+  await act(async () => {
+    rerender(<UsingAB key="ab" />)
+    vi.advanceTimersByTime(10)
+    vi.runAllTimers()
+  })
+
+  await act(async () => {
+    vi.advanceTimersByTime(120000)
+    vi.runAllTimers()
+  })
+
+  expect(getSubStateA()).toEqual(statusA)
+  expect(getSubStateB()).toEqual(statusB)
+})
+
+test('Minimizes the number of subscription dispatches when multiple components ask for the same data', async () => {
+  const listenerMiddleware = createListenerMiddleware()
+  const storeRef = setupApiStore(api, undefined, {
+    middleware: {
+      concat: [listenerMiddleware.middleware],
+    },
+    withoutTestLifecycles: true,
+  })
+
+  const actionTypes: unknown[] = []
+
+  listenerMiddleware.startListening({
+    predicate: () => true,
+    effect: (action) => {
+      if (
+        action.type.includes('subscriptionsUpdated') ||
+        action.type.includes('internal_')
+      ) {
+        return
+      }
+
+      actionTypes.push(action.type)
+    },
+  })
+
+  const { getSubscriptionCount } = storeRef.store.dispatch(
+    api.internalActions.internal_getRTKQSubscriptions(),
+  ) as unknown as SubscriptionSelectors
+
+  const NUM_LIST_ITEMS = 1000
+
+  function ParentComponent() {
+    const listItems = Array.from({ length: NUM_LIST_ITEMS }).map((_, i) => (
+      <UsingA key={i} />
+    ))
+
+    return <>{listItems}</>
+  }
+
+  render(<ParentComponent />, {
+    wrapper: storeRef.wrapper,
+  })
+
+  await act(async () => {
+    vi.advanceTimersByTime(10)
+    vi.runAllTimers()
+  })
+
+  await waitFor(() => {
+    return screen.getAllByText(/42/).length > 0
+  })
+
+  expect(getSubscriptionCount('a(undefined)')).toBe(NUM_LIST_ITEMS)
+
+  expect(actionTypes).toEqual([
+    'api/config/middlewareRegistered',
+    'api/executeQuery/pending',
+    'api/executeQuery/fulfilled',
+  ])
+}, 25_000)
Index: node_modules/@reduxjs/toolkit/src/query/tests/copyWithStructuralSharing.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/copyWithStructuralSharing.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/copyWithStructuralSharing.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,88 @@
+import { copyWithStructuralSharing } from '@reduxjs/toolkit/query'
+
+test('equal object from JSON Object', () => {
+  const json = JSON.stringify({
+    a: { b: { c: { d: 1, e: '2', f: true }, g: false }, h: null },
+    i: null,
+  })
+  const objA = JSON.parse(json)
+  const objB = JSON.parse(json)
+  expect(objA).toStrictEqual(objB)
+  expect(objA).not.toBe(objB)
+  const newCopy = copyWithStructuralSharing(objA, objB)
+  expect(newCopy).toBe(objA)
+  expect(newCopy).not.toBe(objB)
+  expect(newCopy).toStrictEqual(objB)
+})
+
+test('equal object from JSON Object', () => {
+  const json = JSON.stringify({
+    a: { b: { c: { d: 1, e: '2', f: true }, g: false }, h: null },
+    i: null,
+  })
+  const objA = JSON.parse(json)
+  const objB = JSON.parse(json)
+  objB.a.h = 4
+  expect(objA).not.toStrictEqual(objB)
+  expect(objA).not.toBe(objB)
+  expect(objA.a.b).toStrictEqual(objB.a.b)
+  expect(objA.a.b).not.toBe(objB.a.b)
+
+  const newCopy = copyWithStructuralSharing(objA, objB)
+  expect(newCopy).not.toBe(objA)
+  expect(newCopy).not.toStrictEqual(objA)
+  expect(newCopy).toStrictEqual(objB)
+
+  expect(newCopy.a.b).toBe(objA.a.b)
+  expect(newCopy.a.b).not.toBe(objB.a.b)
+  expect(newCopy.a.b).toStrictEqual(objB.a.b)
+})
+
+test('equal object from JSON Array', () => {
+  const json = JSON.stringify([
+    1,
+    'a',
+    { 2: 'b' },
+    { 3: { 4: 'c' }, d: null },
+    null,
+    5,
+  ])
+  const objA = JSON.parse(json)
+  const objB = JSON.parse(json)
+
+  expect(objA).toStrictEqual(objB)
+  expect(objA).not.toBe(objB)
+  const newCopy = copyWithStructuralSharing(objA, objB)
+  expect(newCopy).toBe(objA)
+  expect(newCopy).not.toBe(objB)
+  expect(newCopy).toStrictEqual(objB)
+})
+
+test('equal object from JSON Array', () => {
+  const json = JSON.stringify([
+    1,
+    'a',
+    { 2: 'b' },
+    { 3: { 4: 'c' }, d: null },
+    null,
+    5,
+  ])
+  const objA = JSON.parse(json)
+  const objB = JSON.parse(json)
+  objB[2][2] = 'x'
+
+  expect(objA).not.toStrictEqual(objB)
+  expect(objA).not.toBe(objB)
+  const newCopy = copyWithStructuralSharing(objA, objB)
+  expect(newCopy).not.toBe(objA)
+  expect(newCopy).not.toBe(objB)
+  expect(newCopy).toStrictEqual(objB)
+
+  expect(newCopy[3]).toBe(objA[3])
+  expect(newCopy[3]).not.toBe(objB[3])
+  expect(newCopy[3]).toStrictEqual(objB[3])
+
+  expect(newCopy[2]).not.toBe(objA[2])
+  expect(newCopy[2]).not.toBe(objB[2])
+  expect(newCopy[2]).toStrictEqual(objB[2])
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/createApi.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/createApi.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/createApi.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,521 @@
+import { setupApiStore } from '@internal/tests/utils/helpers'
+import type { EntityState, SerializedError } from '@reduxjs/toolkit'
+import { configureStore, createEntityAdapter } from '@reduxjs/toolkit'
+import type {
+  DefinitionsFromApi,
+  FetchBaseQueryError,
+  FetchBaseQueryMeta,
+  MutationDefinition,
+  OverrideResultType,
+  QueryDefinition,
+  TagDescription,
+  TagTypesFromApi,
+} from '@reduxjs/toolkit/query'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+import * as v from 'valibot'
+import type { Post } from './mocks/handlers'
+
+describe('type tests', () => {
+  test('sensible defaults', () => {
+    const api = createApi({
+      baseQuery: fetchBaseQuery(),
+      endpoints: (build) => ({
+        getUser: build.query<unknown, void>({
+          query(id) {
+            return { url: `user/${id}` }
+          },
+        }),
+        updateUser: build.mutation<unknown, void>({
+          query: () => '',
+        }),
+      }),
+    })
+
+    configureStore({
+      reducer: {
+        [api.reducerPath]: api.reducer,
+      },
+      middleware: (gDM) => gDM().concat(api.middleware),
+    })
+
+    expectTypeOf(api.reducerPath).toEqualTypeOf<'api'>()
+
+    expectTypeOf(api.util.invalidateTags)
+      .parameter(0)
+      .toEqualTypeOf<(null | undefined | TagDescription<never>)[]>()
+  })
+
+  describe('endpoint definition typings', () => {
+    const api = createApi({
+      baseQuery: (from: 'From'): { data: 'To' } | Promise<{ data: 'To' }> => ({
+        data: 'To',
+      }),
+      endpoints: () => ({}),
+      tagTypes: ['typeA', 'typeB'],
+    })
+
+    test('query: query & transformResponse types', () => {
+      api.injectEndpoints({
+        endpoints: (build) => ({
+          query: build.query<'RetVal', 'Arg'>({
+            query: (x: 'Arg') => 'From' as const,
+            transformResponse(r: 'To') {
+              return 'RetVal' as const
+            },
+          }),
+          query1: build.query<'RetVal', 'Arg'>({
+            // @ts-expect-error
+            query: (x: 'Error') => 'From' as const,
+            transformResponse(r: 'To') {
+              return 'RetVal' as const
+            },
+          }),
+          query2: build.query<'RetVal', 'Arg'>({
+            // @ts-expect-error
+            query: (x: 'Arg') => 'Error' as const,
+            transformResponse(r: 'To') {
+              return 'RetVal' as const
+            },
+          }),
+          query3: build.query<'RetVal', 'Arg'>({
+            query: (x: 'Arg') => 'From' as const,
+            // @ts-expect-error
+            transformResponse(r: 'Error') {
+              return 'RetVal' as const
+            },
+          }),
+          query4: build.query<'RetVal', 'Arg'>({
+            query: (x: 'Arg') => 'From' as const,
+            // @ts-expect-error
+            transformResponse(r: 'To') {
+              return 'Error' as const
+            },
+          }),
+          queryInference1: build.query<'RetVal', 'Arg'>({
+            query: (x) => {
+              expectTypeOf(x).toEqualTypeOf<'Arg'>()
+
+              return 'From'
+            },
+            transformResponse(r) {
+              expectTypeOf(r).toEqualTypeOf<'To'>()
+
+              return 'RetVal'
+            },
+          }),
+          queryInference2: (() => {
+            const query = build.query({
+              query: (x: 'Arg') => 'From' as const,
+              transformResponse(r: 'To') {
+                return 'RetVal' as const
+              },
+            })
+
+            expectTypeOf(query).toMatchTypeOf<
+              QueryDefinition<'Arg', any, any, 'RetVal'>
+            >()
+
+            return query
+          })(),
+        }),
+      })
+    })
+
+    test('mutation: query & transformResponse types', () => {
+      api.injectEndpoints({
+        endpoints: (build) => ({
+          query: build.mutation<'RetVal', 'Arg'>({
+            query: (x: 'Arg') => 'From' as const,
+            transformResponse(r: 'To') {
+              return 'RetVal' as const
+            },
+          }),
+          query1: build.mutation<'RetVal', 'Arg'>({
+            // @ts-expect-error
+            query: (x: 'Error') => 'From' as const,
+            transformResponse(r: 'To') {
+              return 'RetVal' as const
+            },
+          }),
+          query2: build.mutation<'RetVal', 'Arg'>({
+            // @ts-expect-error
+            query: (x: 'Arg') => 'Error' as const,
+            transformResponse(r: 'To') {
+              return 'RetVal' as const
+            },
+          }),
+          query3: build.mutation<'RetVal', 'Arg'>({
+            query: (x: 'Arg') => 'From' as const,
+            // @ts-expect-error
+            transformResponse(r: 'Error') {
+              return 'RetVal' as const
+            },
+          }),
+          query4: build.mutation<'RetVal', 'Arg'>({
+            query: (x: 'Arg') => 'From' as const,
+            // @ts-expect-error
+            transformResponse(r: 'To') {
+              return 'Error' as const
+            },
+          }),
+          mutationInference1: build.mutation<'RetVal', 'Arg'>({
+            query: (x) => {
+              expectTypeOf(x).toEqualTypeOf<'Arg'>()
+
+              return 'From'
+            },
+            transformResponse(r) {
+              expectTypeOf(r).toEqualTypeOf<'To'>()
+
+              return 'RetVal'
+            },
+          }),
+          mutationInference2: (() => {
+            const query = build.mutation({
+              query: (x: 'Arg') => 'From' as const,
+              transformResponse(r: 'To') {
+                return 'RetVal' as const
+              },
+            })
+
+            expectTypeOf(query).toMatchTypeOf<
+              MutationDefinition<'Arg', any, any, 'RetVal'>
+            >()
+
+            return query
+          })(),
+        }),
+      })
+    })
+
+    describe('enhancing endpoint definitions', () => {
+      const baseQuery = (x: string) => ({ data: 'success' })
+
+      function getNewApi() {
+        return createApi({
+          baseQuery,
+          tagTypes: ['old'],
+          endpoints: (build) => ({
+            query1: build.query<'out1', 'in1'>({ query: (id) => `${id}` }),
+            query2: build.query<'out2', 'in2'>({ query: (id) => `${id}` }),
+            mutation1: build.mutation<'out1', 'in1'>({
+              query: (id) => `${id}`,
+            }),
+            mutation2: build.mutation<'out2', 'in2'>({
+              query: (id) => `${id}`,
+            }),
+          }),
+        })
+      }
+
+      const api1 = getNewApi()
+
+      test('warn on wrong tagType', () => {
+        const storeRef = setupApiStore(api1, undefined, {
+          withoutTestLifecycles: true,
+        })
+
+        api1.enhanceEndpoints({
+          endpoints: {
+            query1: {
+              // @ts-expect-error
+              providesTags: ['new'],
+            },
+            query2: {
+              // @ts-expect-error
+              providesTags: ['missing'],
+            },
+          },
+        })
+
+        const enhanced = api1.enhanceEndpoints({
+          addTagTypes: ['new'],
+          endpoints: {
+            query1: {
+              providesTags: ['new'],
+            },
+            query2: {
+              // @ts-expect-error
+              providesTags: ['missing'],
+            },
+          },
+        })
+
+        storeRef.store.dispatch(api1.endpoints.query1.initiate('in1'))
+
+        storeRef.store.dispatch(api1.endpoints.query2.initiate('in2'))
+
+        enhanced.enhanceEndpoints({
+          endpoints: {
+            query1: {
+              // returned `enhanced` api contains "new" entityType
+              providesTags: ['new'],
+            },
+            query2: {
+              // @ts-expect-error
+              providesTags: ['missing'],
+            },
+          },
+        })
+      })
+
+      test('modify', () => {
+        const storeRef = setupApiStore(api1, undefined, {
+          withoutTestLifecycles: true,
+        })
+
+        api1.enhanceEndpoints({
+          endpoints: {
+            query1: {
+              query: (x) => {
+                expectTypeOf(x).toEqualTypeOf<'in1'>()
+
+                return 'modified1'
+              },
+            },
+            query2(definition) {
+              definition.query = (x) => {
+                expectTypeOf(x).toEqualTypeOf<'in2'>()
+
+                return 'modified2'
+              }
+            },
+            mutation1: {
+              query: (x) => {
+                expectTypeOf(x).toEqualTypeOf<'in1'>()
+
+                return 'modified1'
+              },
+            },
+            mutation2(definition) {
+              definition.query = (x) => {
+                expectTypeOf(x).toEqualTypeOf<'in2'>()
+
+                return 'modified2'
+              }
+            },
+            // @ts-expect-error
+            nonExisting: {},
+          },
+        })
+
+        storeRef.store.dispatch(api1.endpoints.query1.initiate('in1'))
+        storeRef.store.dispatch(api1.endpoints.query2.initiate('in2'))
+        storeRef.store.dispatch(api1.endpoints.mutation1.initiate('in1'))
+        storeRef.store.dispatch(api1.endpoints.mutation2.initiate('in2'))
+      })
+
+      test('updated transform response types', async () => {
+        const baseApi = createApi({
+          baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+          tagTypes: ['old'],
+          endpoints: (build) => ({
+            query1: build.query<'out1', void>({ query: () => 'success' }),
+            mutation1: build.mutation<'out1', void>({ query: () => 'success' }),
+          }),
+        })
+
+        type Transformed = { value: string }
+
+        type Definitions = DefinitionsFromApi<typeof api1>
+
+        type TagTypes = TagTypesFromApi<typeof api1>
+
+        type Q1Definition = OverrideResultType<
+          Definitions['query1'],
+          Transformed
+        >
+
+        type M1Definition = OverrideResultType<
+          Definitions['mutation1'],
+          Transformed
+        >
+
+        type UpdatedDefinitions = Omit<Definitions, 'query1' | 'mutation1'> & {
+          query1: Q1Definition
+          mutation1: M1Definition
+        }
+
+        const enhancedApi = baseApi.enhanceEndpoints<
+          TagTypes,
+          UpdatedDefinitions
+        >({
+          endpoints: {
+            query1: {
+              transformResponse: (a, b, c) => ({
+                value: 'transformed',
+              }),
+            },
+            mutation1: {
+              transformResponse: (a, b, c) => ({
+                value: 'transformed',
+              }),
+            },
+          },
+        })
+
+        const storeRef = setupApiStore(enhancedApi, undefined, {
+          withoutTestLifecycles: true,
+        })
+
+        const queryResponse = await storeRef.store.dispatch(
+          enhancedApi.endpoints.query1.initiate(),
+        )
+
+        expectTypeOf(queryResponse.data).toMatchTypeOf<
+          Transformed | undefined
+        >()
+
+        const mutationResponse = await storeRef.store.dispatch(
+          enhancedApi.endpoints.mutation1.initiate(),
+        )
+
+        expectTypeOf(mutationResponse).toMatchTypeOf<
+          | { data: Transformed }
+          | { error: FetchBaseQueryError | SerializedError }
+        >()
+      })
+    })
+    describe('endpoint schemas', () => {
+      const argSchema = v.object({ id: v.number() })
+      const postSchema = v.object({
+        id: v.number(),
+        title: v.string(),
+        body: v.string(),
+      }) satisfies v.GenericSchema<Post>
+      const errorResponseSchema = v.object({
+        status: v.number(),
+        data: v.unknown(),
+      }) satisfies v.GenericSchema<FetchBaseQueryError>
+      const metaSchema = v.object({
+        request: v.instance(Request),
+        response: v.optional(v.instance(Response)),
+      }) satisfies v.GenericSchema<FetchBaseQueryMeta>
+      test('schemas must match', () => {
+        createApi({
+          baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+          endpoints: (build) => ({
+            query: build.query<Post, { id: number }>({
+              query: ({ id }) => `/post/${id}`,
+              argSchema,
+              responseSchema: postSchema,
+              errorResponseSchema,
+              metaSchema,
+            }),
+            bothMismatch: build.query<Post, { id: number }>({
+              query: ({ id }) => `/post/${id}`,
+              // @ts-expect-error wrong schema
+              argSchema: v.object({ id: v.string() }),
+              // @ts-expect-error wrong schema
+              responseSchema: v.object({ id: v.string() }),
+              // @ts-expect-error wrong schema
+              errorResponseSchema: v.object({ status: v.string() }),
+              // @ts-expect-error wrong schema
+              metaSchema: v.object({ request: v.string() }),
+            }),
+            inputMismatch: build.query<Post, { id: number }>({
+              query: ({ id }) => `/post/${id}`,
+              // @ts-expect-error can't expect different input
+              argSchema: v.object({
+                id: v.pipe(v.string(), v.transform(Number), v.number()),
+              }),
+              // @ts-expect-error can't expect different input
+              responseSchema: v.object({
+                ...postSchema.entries,
+                id: v.pipe(v.string(), v.transform(Number)),
+              }) satisfies v.GenericSchema<any, Post>,
+              // @ts-expect-error can't expect different input
+              errorResponseSchema: v.object({
+                ...errorResponseSchema.entries,
+                status: v.pipe(v.string(), v.transform(Number)),
+              }) satisfies v.GenericSchema<any, FetchBaseQueryError>,
+              // @ts-expect-error can't expect different input
+              metaSchema: v.object({
+                ...metaSchema.entries,
+                request: v.pipe(
+                  v.string(),
+                  v.transform((url) => new Request(url)),
+                ),
+              }) satisfies v.GenericSchema<any, FetchBaseQueryMeta>,
+            }),
+            outputMismatch: build.query<Post, { id: number }>({
+              query: ({ id }) => `/post/${id}`,
+              // @ts-expect-error can't provide different output
+              argSchema: v.object({
+                id: v.pipe(v.number(), v.transform(String)),
+              }),
+              // @ts-expect-error can't provide different output
+              responseSchema: v.object({
+                ...postSchema.entries,
+                id: v.pipe(v.number(), v.transform(String)),
+              }) satisfies v.GenericSchema<Post, any>,
+              // @ts-expect-error can't provide different output
+              errorResponseSchema: v.object({
+                ...errorResponseSchema.entries,
+                status: v.pipe(v.number(), v.transform(String)),
+              }) satisfies v.GenericSchema<FetchBaseQueryError, any>,
+              // @ts-expect-error can't provide different output
+              metaSchema: v.object({
+                ...metaSchema.entries,
+                request: v.pipe(
+                  v.instance(Request),
+                  v.transform((r) => r.url),
+                ),
+              }) satisfies v.GenericSchema<FetchBaseQueryMeta, any>,
+            }),
+          }),
+        })
+      })
+      test('schemas as a source of inference', () => {
+        const postAdapter = createEntityAdapter<Post>()
+        const api = createApi({
+          baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+          endpoints: (build) => ({
+            query: build.query({
+              query: ({ id }: { id: number }) => `/post/${id}`,
+              responseSchema: postSchema,
+            }),
+            query2: build.query({
+              query: (arg) => {
+                expectTypeOf(arg).toEqualTypeOf<{ id: number }>()
+                return `/post/${arg.id}`
+              },
+              argSchema,
+              responseSchema: postSchema,
+            }),
+            query3: build.query({
+              query: (_arg: void) => `/posts`,
+              rawResponseSchema: v.array(postSchema),
+              transformResponse: (posts) => {
+                expectTypeOf(posts).toEqualTypeOf<Post[]>()
+                return postAdapter.getInitialState(undefined, posts)
+              },
+            }),
+          }),
+        })
+
+        expectTypeOf(api.endpoints.query.Types.QueryArg).toEqualTypeOf<{
+          id: number
+        }>()
+        expectTypeOf(api.endpoints.query.Types.ResultType).toEqualTypeOf<Post>()
+        expectTypeOf(api.endpoints.query.Types.RawResultType).toBeAny()
+
+        expectTypeOf(api.endpoints.query2.Types.QueryArg).toEqualTypeOf<{
+          id: number
+        }>()
+        expectTypeOf(
+          api.endpoints.query2.Types.ResultType,
+        ).toEqualTypeOf<Post>()
+        expectTypeOf(api.endpoints.query2.Types.RawResultType).toBeAny()
+
+        expectTypeOf(api.endpoints.query3.Types.QueryArg).toEqualTypeOf<void>()
+        expectTypeOf(api.endpoints.query3.Types.ResultType).toEqualTypeOf<
+          EntityState<Post, Post['id']>
+        >()
+        expectTypeOf(api.endpoints.query3.Types.RawResultType).toEqualTypeOf<
+          Post[]
+        >()
+      })
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/createApi.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/createApi.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/createApi.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1833 @@
+import { noop } from '@internal/listenerMiddleware/utils'
+import { server } from '@internal/query/tests/mocks/server'
+import {
+  getSerializedHeaders,
+  setupApiStore,
+} from '@internal/tests/utils/helpers'
+import type { SerializedError } from '@reduxjs/toolkit'
+import { configureStore, createAction, createReducer } from '@reduxjs/toolkit'
+import type {
+  DefinitionsFromApi,
+  FetchBaseQueryError,
+  FetchBaseQueryMeta,
+  OverrideResultType,
+  SchemaFailureConverter,
+  SchemaType,
+  SerializeQueryArgs,
+  TagTypesFromApi,
+} from '@reduxjs/toolkit/query'
+import {
+  createApi,
+  fetchBaseQuery,
+  NamedSchemaError,
+} from '@reduxjs/toolkit/query'
+import { HttpResponse, delay, http } from 'msw'
+import nodeFetch from 'node-fetch'
+import * as v from 'valibot'
+import type { SchemaFailureHandler } from '../endpointDefinitions'
+
+beforeAll(() => {
+  vi.stubEnv('NODE_ENV', 'development')
+
+  return vi.unstubAllEnvs
+})
+
+const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
+
+afterEach(() => {
+  vi.clearAllMocks()
+  server.resetHandlers()
+})
+
+afterAll(() => {
+  vi.restoreAllMocks()
+})
+
+function paginate<T>(array: T[], page_size: number, page_number: number) {
+  // human-readable page numbers usually start with 1, so we reduce 1 in the first argument
+  return array.slice((page_number - 1) * page_size, page_number * page_size)
+}
+
+test('sensible defaults', () => {
+  const api = createApi({
+    baseQuery: fetchBaseQuery(),
+    endpoints: (build) => ({
+      getUser: build.query<unknown, void>({
+        query(id) {
+          return { url: `user/${id}` }
+        },
+      }),
+      updateUser: build.mutation<unknown, void>({
+        query: () => '',
+      }),
+    }),
+  })
+  configureStore({
+    reducer: {
+      [api.reducerPath]: api.reducer,
+    },
+    middleware: (gDM) => gDM().concat(api.middleware),
+  })
+  expect(api.reducerPath).toBe('api')
+
+  expect(api.endpoints.getUser.name).toBe('getUser')
+  expect(api.endpoints.updateUser.name).toBe('updateUser')
+})
+
+describe('wrong tagTypes log errors', () => {
+  const baseQuery = vi.fn()
+  const api = createApi({
+    baseQuery,
+    tagTypes: ['User'],
+    endpoints: (build) => ({
+      provideNothing: build.query<unknown, void>({
+        query: () => '',
+      }),
+      provideTypeString: build.query<unknown, void>({
+        query: () => '',
+        providesTags: ['User'],
+      }),
+      provideTypeWithId: build.query<unknown, void>({
+        query: () => '',
+        providesTags: [{ type: 'User', id: 5 }],
+      }),
+      provideTypeWithIdAndCallback: build.query<unknown, void>({
+        query: () => '',
+        providesTags: () => [{ type: 'User', id: 5 }],
+      }),
+      provideWrongTypeString: build.query<unknown, void>({
+        query: () => '',
+        // @ts-expect-error
+        providesTags: ['Users'],
+      }),
+      provideWrongTypeWithId: build.query<unknown, void>({
+        query: () => '',
+        // @ts-expect-error
+        providesTags: [{ type: 'Users', id: 5 }],
+      }),
+      provideWrongTypeWithIdAndCallback: build.query<unknown, void>({
+        query: () => '',
+        // @ts-expect-error
+        providesTags: () => [{ type: 'Users', id: 5 }],
+      }),
+      invalidateNothing: build.query<unknown, void>({
+        query: () => '',
+      }),
+      invalidateTypeString: build.mutation<unknown, void>({
+        query: () => '',
+        invalidatesTags: ['User'],
+      }),
+      invalidateTypeWithId: build.mutation<unknown, void>({
+        query: () => '',
+        invalidatesTags: [{ type: 'User', id: 5 }],
+      }),
+      invalidateTypeWithIdAndCallback: build.mutation<unknown, void>({
+        query: () => '',
+        invalidatesTags: () => [{ type: 'User', id: 5 }],
+      }),
+
+      invalidateWrongTypeString: build.mutation<unknown, void>({
+        query: () => '',
+        // @ts-expect-error
+        invalidatesTags: ['Users'],
+      }),
+      invalidateWrongTypeWithId: build.mutation<unknown, void>({
+        query: () => '',
+        // @ts-expect-error
+        invalidatesTags: [{ type: 'Users', id: 5 }],
+      }),
+      invalidateWrongTypeWithIdAndCallback: build.mutation<unknown, void>({
+        query: () => '',
+        // @ts-expect-error
+        invalidatesTags: () => [{ type: 'Users', id: 5 }],
+      }),
+    }),
+  })
+  const store = configureStore({
+    reducer: {
+      [api.reducerPath]: api.reducer,
+    },
+    middleware: (gDM) => gDM().concat(api.middleware),
+  })
+
+  beforeEach(() => {
+    baseQuery.mockResolvedValue({ data: 'foo' })
+  })
+
+  test.each<[keyof typeof api.endpoints, boolean?]>([
+    ['provideNothing', false],
+    ['provideTypeString', false],
+    ['provideTypeWithId', false],
+    ['provideTypeWithIdAndCallback', false],
+    ['provideWrongTypeString', true],
+    ['provideWrongTypeWithId', true],
+    ['provideWrongTypeWithIdAndCallback', true],
+    ['invalidateNothing', false],
+    ['invalidateTypeString', false],
+    ['invalidateTypeWithId', false],
+    ['invalidateTypeWithIdAndCallback', false],
+    ['invalidateWrongTypeString', true],
+    ['invalidateWrongTypeWithId', true],
+    ['invalidateWrongTypeWithIdAndCallback', true],
+  ])(`endpoint %s should log an error? %s`, async (endpoint, shouldError) => {
+    vi.stubEnv('NODE_ENV', 'development')
+
+    // @ts-ignore
+    store.dispatch(api.endpoints[endpoint].initiate())
+    let result: { status: string }
+    do {
+      await delay(5)
+      // @ts-ignore
+      result = api.endpoints[endpoint].select()(store.getState())
+    } while (result.status === 'pending')
+
+    if (shouldError) {
+      expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+        "Tag type 'Users' was used, but not specified in `tagTypes`!",
+      )
+    } else {
+      expect(consoleErrorSpy).not.toHaveBeenCalled()
+    }
+  })
+})
+
+describe('endpoint definition typings', () => {
+  const api = createApi({
+    baseQuery: (from: 'From'): { data: 'To' } | Promise<{ data: 'To' }> => ({
+      data: 'To',
+    }),
+    endpoints: () => ({}),
+    tagTypes: ['typeA', 'typeB'],
+  })
+  test('query: query & transformResponse types', () => {
+    api.injectEndpoints({
+      endpoints: (build) => ({
+        query: build.query<'RetVal', 'Arg'>({
+          query: (x: 'Arg') => 'From' as const,
+          transformResponse(r: 'To') {
+            return 'RetVal' as const
+          },
+        }),
+        query1: build.query<'RetVal', 'Arg'>({
+          // @ts-expect-error
+          query: (x: 'Error') => 'From' as const,
+          transformResponse(r: 'To') {
+            return 'RetVal' as const
+          },
+        }),
+        query2: build.query<'RetVal', 'Arg'>({
+          // @ts-expect-error
+          query: (x: 'Arg') => 'Error' as const,
+          transformResponse(r: 'To') {
+            return 'RetVal' as const
+          },
+        }),
+        query3: build.query<'RetVal', 'Arg'>({
+          query: (x: 'Arg') => 'From' as const,
+          // @ts-expect-error
+          transformResponse(r: 'Error') {
+            return 'RetVal' as const
+          },
+        }),
+        query4: build.query<'RetVal', 'Arg'>({
+          query: (x: 'Arg') => 'From' as const,
+          // @ts-expect-error
+          transformResponse(r: 'To') {
+            return 'Error' as const
+          },
+        }),
+        queryInference1: build.query<'RetVal', 'Arg'>({
+          query: (x) => {
+            return 'From'
+          },
+          transformResponse(r) {
+            return 'RetVal'
+          },
+        }),
+        queryInference2: (() => {
+          const query = build.query({
+            query: (x: 'Arg') => 'From' as const,
+            transformResponse(r: 'To') {
+              return 'RetVal' as const
+            },
+          })
+          return query
+        })(),
+      }),
+    })
+  })
+  test('mutation: query & transformResponse types', () => {
+    api.injectEndpoints({
+      endpoints: (build) => ({
+        query: build.mutation<'RetVal', 'Arg'>({
+          query: (x: 'Arg') => 'From' as const,
+          transformResponse(r: 'To') {
+            return 'RetVal' as const
+          },
+        }),
+        query1: build.mutation<'RetVal', 'Arg'>({
+          // @ts-expect-error
+          query: (x: 'Error') => 'From' as const,
+          transformResponse(r: 'To') {
+            return 'RetVal' as const
+          },
+        }),
+        query2: build.mutation<'RetVal', 'Arg'>({
+          // @ts-expect-error
+          query: (x: 'Arg') => 'Error' as const,
+          transformResponse(r: 'To') {
+            return 'RetVal' as const
+          },
+        }),
+        query3: build.mutation<'RetVal', 'Arg'>({
+          query: (x: 'Arg') => 'From' as const,
+          // @ts-expect-error
+          transformResponse(r: 'Error') {
+            return 'RetVal' as const
+          },
+        }),
+        query4: build.mutation<'RetVal', 'Arg'>({
+          query: (x: 'Arg') => 'From' as const,
+          // @ts-expect-error
+          transformResponse(r: 'To') {
+            return 'Error' as const
+          },
+        }),
+        mutationInference1: build.mutation<'RetVal', 'Arg'>({
+          query: (x) => {
+            return 'From'
+          },
+          transformResponse(r) {
+            return 'RetVal'
+          },
+        }),
+        mutationInference2: (() => {
+          const query = build.mutation({
+            query: (x: 'Arg') => 'From' as const,
+            transformResponse(r: 'To') {
+              return 'RetVal' as const
+            },
+          })
+          return query
+        })(),
+      }),
+    })
+  })
+
+  describe('enhancing endpoint definitions', () => {
+    const baseQuery = vi.fn((x: string) => ({ data: 'success' }))
+    const commonBaseQueryApi = {
+      dispatch: expect.any(Function),
+      endpoint: expect.any(String),
+      abort: expect.any(Function),
+      extra: undefined,
+      forced: expect.any(Boolean),
+      getState: expect.any(Function),
+      signal: expect.any(Object),
+      type: expect.any(String),
+      queryCacheKey: expect.any(String),
+    }
+    beforeEach(() => {
+      baseQuery.mockClear()
+    })
+    function getNewApi() {
+      return createApi({
+        baseQuery,
+        tagTypes: ['old'],
+        endpoints: (build) => ({
+          query1: build.query<'out1', 'in1'>({ query: (id) => `${id}` }),
+          query2: build.query<'out2', 'in2'>({ query: (id) => `${id}` }),
+          mutation1: build.mutation<'out1', 'in1'>({ query: (id) => `${id}` }),
+          mutation2: build.mutation<'out2', 'in2'>({ query: (id) => `${id}` }),
+        }),
+      })
+    }
+    let api = getNewApi()
+    beforeEach(() => {
+      api = getNewApi()
+    })
+
+    test('pre-modification behavior', async () => {
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      storeRef.store.dispatch(api.endpoints.query1.initiate('in1'))
+      storeRef.store.dispatch(api.endpoints.query2.initiate('in2'))
+      storeRef.store.dispatch(api.endpoints.mutation1.initiate('in1'))
+      storeRef.store.dispatch(api.endpoints.mutation2.initiate('in2'))
+
+      expect(baseQuery.mock.calls).toEqual([
+        [
+          'in1',
+          {
+            dispatch: expect.any(Function),
+            endpoint: expect.any(String),
+            getState: expect.any(Function),
+            signal: expect.any(Object),
+            abort: expect.any(Function),
+            forced: expect.any(Boolean),
+            type: expect.any(String),
+            queryCacheKey: expect.any(String),
+          },
+          undefined,
+        ],
+        [
+          'in2',
+          {
+            dispatch: expect.any(Function),
+            endpoint: expect.any(String),
+            getState: expect.any(Function),
+            signal: expect.any(Object),
+            abort: expect.any(Function),
+            forced: expect.any(Boolean),
+            type: expect.any(String),
+            queryCacheKey: expect.any(String),
+          },
+          undefined,
+        ],
+        [
+          'in1',
+          {
+            dispatch: expect.any(Function),
+            endpoint: expect.any(String),
+            getState: expect.any(Function),
+            signal: expect.any(Object),
+            abort: expect.any(Function),
+            // forced: undefined,
+            type: expect.any(String),
+          },
+          undefined,
+        ],
+        [
+          'in2',
+          {
+            dispatch: expect.any(Function),
+            endpoint: expect.any(String),
+            getState: expect.any(Function),
+            signal: expect.any(Object),
+            abort: expect.any(Function),
+            // forced: undefined,
+            type: expect.any(String),
+          },
+          undefined,
+        ],
+      ])
+    })
+
+    test('warn on wrong tagType', async () => {
+      vi.stubEnv('NODE_ENV', 'development')
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      // only type-test this part
+      if (2 > 1) {
+        api.enhanceEndpoints({
+          endpoints: {
+            query1: {
+              // @ts-expect-error
+              providesTags: ['new'],
+            },
+            query2: {
+              // @ts-expect-error
+              providesTags: ['missing'],
+            },
+          },
+        })
+      }
+
+      const enhanced = api.enhanceEndpoints({
+        addTagTypes: ['new'],
+        endpoints: {
+          query1: {
+            providesTags: ['new'],
+          },
+          query2: {
+            // @ts-expect-error
+            providesTags: ['missing'],
+          },
+        },
+      })
+
+      storeRef.store.dispatch(api.endpoints.query1.initiate('in1'))
+      await delay(1)
+      expect(consoleErrorSpy).not.toHaveBeenCalled()
+
+      storeRef.store.dispatch(api.endpoints.query2.initiate('in2'))
+      await delay(1)
+
+      expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+      expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+        "Tag type 'missing' was used, but not specified in `tagTypes`!",
+      )
+
+      // only type-test this part
+      if (2 > 1) {
+        enhanced.enhanceEndpoints({
+          endpoints: {
+            query1: {
+              // returned `enhanced` api contains "new" enitityType
+              providesTags: ['new'],
+            },
+            query2: {
+              // @ts-expect-error
+              providesTags: ['missing'],
+            },
+          },
+        })
+      }
+    })
+
+    test('modify', () => {
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      api.enhanceEndpoints({
+        endpoints: {
+          query1: {
+            query: (x) => {
+              return 'modified1'
+            },
+          },
+          query2(definition) {
+            definition.query = (x) => {
+              return 'modified2'
+            }
+          },
+          mutation1: {
+            query: (x) => {
+              return 'modified1'
+            },
+          },
+          mutation2(definition) {
+            definition.query = (x) => {
+              return 'modified2'
+            }
+          },
+          // @ts-expect-error
+          nonExisting: {},
+        },
+      })
+
+      storeRef.store.dispatch(api.endpoints.query1.initiate('in1'))
+      storeRef.store.dispatch(api.endpoints.query2.initiate('in2'))
+      storeRef.store.dispatch(api.endpoints.mutation1.initiate('in1'))
+      storeRef.store.dispatch(api.endpoints.mutation2.initiate('in2'))
+
+      expect(baseQuery.mock.calls).toEqual([
+        ['modified1', commonBaseQueryApi, undefined],
+        ['modified2', commonBaseQueryApi, undefined],
+        [
+          'modified1',
+          {
+            ...commonBaseQueryApi,
+            forced: undefined,
+            queryCacheKey: undefined,
+          },
+          undefined,
+        ],
+        [
+          'modified2',
+          {
+            ...commonBaseQueryApi,
+            forced: undefined,
+            queryCacheKey: undefined,
+          },
+          undefined,
+        ],
+      ])
+    })
+
+    test('updated transform response types', async () => {
+      const baseApi = createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+        tagTypes: ['old'],
+        endpoints: (build) => ({
+          query1: build.query<'out1', void>({ query: () => 'success' }),
+          mutation1: build.mutation<'out1', void>({ query: () => 'success' }),
+        }),
+      })
+
+      type Transformed = { value: string }
+
+      type Definitions = DefinitionsFromApi<typeof api>
+      type TagTypes = TagTypesFromApi<typeof api>
+
+      type Q1Definition = OverrideResultType<Definitions['query1'], Transformed>
+      type M1Definition = OverrideResultType<
+        Definitions['mutation1'],
+        Transformed
+      >
+
+      type UpdatedDefitions = Omit<Definitions, 'query1' | 'mutation1'> & {
+        query1: Q1Definition
+        mutation1: M1Definition
+      }
+
+      const enhancedApi = baseApi.enhanceEndpoints<TagTypes, UpdatedDefitions>({
+        endpoints: {
+          query1: {
+            transformResponse: (a, b, c) => ({
+              value: 'transformed',
+            }),
+          },
+          mutation1: {
+            transformResponse: (a, b, c) => ({
+              value: 'transformed',
+            }),
+          },
+        },
+      })
+
+      const storeRef = setupApiStore(enhancedApi, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      const queryResponse = await storeRef.store.dispatch(
+        enhancedApi.endpoints.query1.initiate(),
+      )
+      expect(queryResponse.data).toEqual({ value: 'transformed' })
+
+      const mutationResponse = await storeRef.store.dispatch(
+        enhancedApi.endpoints.mutation1.initiate(),
+      )
+      expect('data' in mutationResponse && mutationResponse.data).toEqual({
+        value: 'transformed',
+      })
+    })
+  })
+})
+
+describe('additional transformResponse behaviors', () => {
+  type SuccessResponse = { value: 'success' }
+  type EchoResponseData = { banana: 'bread' }
+  type ErrorResponse = { value: 'error' }
+  const api = createApi({
+    baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+    endpoints: (build) => ({
+      echo: build.mutation({
+        query: () => ({ method: 'PUT', url: '/echo' }),
+      }),
+      mutation: build.mutation({
+        query: () => ({
+          url: '/echo',
+          method: 'POST',
+          body: { nested: { banana: 'bread' } },
+        }),
+        transformResponse: (response: { body: { nested: EchoResponseData } }) =>
+          response.body.nested,
+      }),
+      mutationWithError: build.mutation({
+        query: () => ({
+          url: '/error',
+          method: 'POST',
+        }),
+        transformErrorResponse: (response) => {
+          const data = response.data as ErrorResponse
+          return data.value
+        },
+      }),
+      mutationWithMeta: build.mutation({
+        query: () => ({
+          url: '/echo',
+          method: 'POST',
+          body: { nested: { banana: 'bread' } },
+        }),
+        transformResponse: (
+          response: { body: { nested: EchoResponseData } },
+          meta,
+        ) => {
+          return {
+            ...response.body.nested,
+            meta: {
+              request: { headers: getSerializedHeaders(meta?.request.headers) },
+              response: {
+                headers: getSerializedHeaders(meta?.response?.headers),
+              },
+            },
+          }
+        },
+      }),
+      query: build.query<SuccessResponse & EchoResponseData, void>({
+        query: () => '/success',
+        transformResponse: async (response: SuccessResponse) => {
+          const res: any = await nodeFetch('https://example.com/echo', {
+            method: 'POST',
+            body: JSON.stringify({ banana: 'bread' }),
+          }).then((res) => res.json())
+
+          const additionalData = res.body as EchoResponseData
+          return { ...response, ...additionalData }
+        },
+      }),
+      queryWithMeta: build.query<SuccessResponse, void>({
+        query: () => '/success',
+        transformResponse: async (response: SuccessResponse, meta) => {
+          return {
+            ...response,
+            meta: {
+              request: { headers: getSerializedHeaders(meta?.request.headers) },
+              response: {
+                headers: getSerializedHeaders(meta?.response?.headers),
+              },
+            },
+          }
+        },
+      }),
+    }),
+  })
+
+  const storeRef = setupApiStore(api)
+
+  test('transformResponse handles an async transformation and returns the merged data (query)', async () => {
+    const result = await storeRef.store.dispatch(api.endpoints.query.initiate())
+
+    expect(result.data).toEqual({ value: 'success', banana: 'bread' })
+  })
+
+  test('transformResponse transforms a response from a mutation', async () => {
+    const result = await storeRef.store.dispatch(
+      api.endpoints.mutation.initiate({}),
+    )
+
+    expect('data' in result && result.data).toEqual({ banana: 'bread' })
+  })
+
+  test('transformResponse transforms a response from a mutation with an error', async () => {
+    const result = await storeRef.store.dispatch(
+      api.endpoints.mutationWithError.initiate({}),
+    )
+
+    expect('error' in result && result.error).toEqual('error')
+  })
+
+  test('transformResponse can inject baseQuery meta into the end result from a mutation', async () => {
+    const result = await storeRef.store.dispatch(
+      api.endpoints.mutationWithMeta.initiate({}),
+    )
+
+    expect('data' in result && result.data).toEqual({
+      banana: 'bread',
+      meta: {
+        request: {
+          headers: {
+            accept: 'application/json',
+            'content-type': 'application/json',
+          },
+        },
+        response: {
+          headers: {
+            'content-type': 'application/json',
+          },
+        },
+      },
+    })
+  })
+
+  test('transformResponse can inject baseQuery meta into the end result from a query', async () => {
+    const result = await storeRef.store.dispatch(
+      api.endpoints.queryWithMeta.initiate(),
+    )
+
+    expect(result.data).toEqual({
+      value: 'success',
+      meta: {
+        request: {
+          headers: {
+            accept: 'application/json',
+          },
+        },
+        response: {
+          headers: {
+            'content-type': 'application/json',
+          },
+        },
+      },
+    })
+  })
+})
+
+describe('query endpoint lifecycles - onStart, onSuccess, onError', () => {
+  const initialState = {
+    count: null as null | number,
+  }
+  const setCount = createAction<number>('setCount')
+  const testReducer = createReducer(initialState, (builder) => {
+    builder.addCase(setCount, (state, action) => {
+      state.count = action.payload
+    })
+  })
+
+  type SuccessResponse = { value: 'success' }
+  const api = createApi({
+    baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+    endpoints: (build) => ({
+      echo: build.mutation({
+        query: () => ({ method: 'PUT', url: '/echo' }),
+      }),
+      query: build.query<SuccessResponse, void>({
+        query: () => '/success',
+        async onQueryStarted(_, api) {
+          api.dispatch(setCount(0))
+          try {
+            await api.queryFulfilled
+            api.dispatch(setCount(1))
+          } catch {
+            api.dispatch(setCount(-1))
+          }
+        },
+      }),
+      mutation: build.mutation<SuccessResponse, void>({
+        query: () => ({ url: '/success', method: 'POST' }),
+        async onQueryStarted(_, api) {
+          api.dispatch(setCount(0))
+          try {
+            await api.queryFulfilled
+            api.dispatch(setCount(1))
+          } catch {
+            api.dispatch(setCount(-1))
+          }
+        },
+      }),
+    }),
+  })
+
+  const storeRef = setupApiStore(api, { testReducer })
+
+  test('query lifecycle events fire properly', async () => {
+    // We intentionally fail the first request so we can test all lifecycles
+    server.use(
+      http.get(
+        'https://example.com/success',
+        () => HttpResponse.json({ value: 'failed' }, { status: 500 }),
+        { once: true },
+      ),
+    )
+
+    expect(storeRef.store.getState().testReducer.count).toBe(null)
+    const failAttempt = storeRef.store.dispatch(api.endpoints.query.initiate())
+    expect(storeRef.store.getState().testReducer.count).toBe(0)
+    await failAttempt
+    await delay(10)
+    expect(storeRef.store.getState().testReducer.count).toBe(-1)
+
+    const successAttempt = storeRef.store.dispatch(
+      api.endpoints.query.initiate(),
+    )
+    expect(storeRef.store.getState().testReducer.count).toBe(0)
+    await successAttempt
+    await delay(10)
+    expect(storeRef.store.getState().testReducer.count).toBe(1)
+  })
+
+  test('mutation lifecycle events fire properly', async () => {
+    // We intentionally fail the first request so we can test all lifecycles
+    server.use(
+      http.post(
+        'https://example.com/success',
+        () => HttpResponse.json({ value: 'failed' }, { status: 500 }),
+        { once: true },
+      ),
+    )
+
+    expect(storeRef.store.getState().testReducer.count).toBe(null)
+    const failAttempt = storeRef.store.dispatch(
+      api.endpoints.mutation.initiate(),
+    )
+    expect(storeRef.store.getState().testReducer.count).toBe(0)
+    await failAttempt
+    expect(storeRef.store.getState().testReducer.count).toBe(-1)
+
+    const successAttempt = storeRef.store.dispatch(
+      api.endpoints.mutation.initiate(),
+    )
+    expect(storeRef.store.getState().testReducer.count).toBe(0)
+    await successAttempt
+    expect(storeRef.store.getState().testReducer.count).toBe(1)
+  })
+})
+
+test('providesTags and invalidatesTags can use baseQueryMeta', async () => {
+  let _meta: FetchBaseQueryMeta | undefined
+
+  type SuccessResponse = { value: 'success' }
+
+  const api = createApi({
+    baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+    tagTypes: ['success'],
+    endpoints: (build) => ({
+      query: build.query<SuccessResponse, void>({
+        query: () => '/success',
+        providesTags: (_result, _error, _arg, meta) => {
+          _meta = meta
+          return ['success']
+        },
+      }),
+      mutation: build.mutation<SuccessResponse, void>({
+        query: () => ({ url: '/success', method: 'POST' }),
+        invalidatesTags: (_result, _error, _arg, meta) => {
+          _meta = meta
+          return ['success']
+        },
+      }),
+    }),
+  })
+
+  const storeRef = setupApiStore(api, undefined, {
+    withoutTestLifecycles: true,
+  })
+
+  await storeRef.store.dispatch(api.endpoints.query.initiate())
+  expect('request' in _meta! && 'response' in _meta!).toBe(true)
+
+  _meta = undefined
+
+  await storeRef.store.dispatch(api.endpoints.mutation.initiate())
+
+  expect('request' in _meta! && 'response' in _meta!).toBe(true)
+})
+
+describe('structuralSharing flag behaviors', () => {
+  type SuccessResponse = { value: 'success' }
+
+  const api = createApi({
+    baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+    tagTypes: ['success'],
+    endpoints: (build) => ({
+      enabled: build.query<SuccessResponse, void>({
+        query: () => '/success',
+      }),
+      disabled: build.query<SuccessResponse, void>({
+        query: () => ({ url: '/success' }),
+        structuralSharing: false,
+      }),
+    }),
+  })
+
+  const storeRef = setupApiStore(api)
+
+  it('enables structural sharing for query endpoints by default', async () => {
+    await storeRef.store.dispatch(api.endpoints.enabled.initiate())
+    const firstRef = api.endpoints.enabled.select()(storeRef.store.getState())
+
+    await storeRef.store.dispatch(
+      api.endpoints.enabled.initiate(undefined, { forceRefetch: true }),
+    )
+
+    const secondRef = api.endpoints.enabled.select()(storeRef.store.getState())
+
+    expect(firstRef.requestId).not.toEqual(secondRef.requestId)
+    expect(firstRef.data === secondRef.data).toBeTruthy()
+  })
+
+  it('allows a query endpoint to opt-out of structural sharing', async () => {
+    await storeRef.store.dispatch(api.endpoints.disabled.initiate())
+    const firstRef = api.endpoints.disabled.select()(storeRef.store.getState())
+
+    await storeRef.store.dispatch(
+      api.endpoints.disabled.initiate(undefined, { forceRefetch: true }),
+    )
+
+    const secondRef = api.endpoints.disabled.select()(storeRef.store.getState())
+
+    expect(firstRef.requestId).not.toEqual(secondRef.requestId)
+    expect(firstRef.data === secondRef.data).toBeFalsy()
+  })
+})
+
+describe('custom serializeQueryArgs per endpoint', () => {
+  const customArgsSerializer: SerializeQueryArgs<number> = ({
+    endpointName,
+    queryArgs,
+  }) => `${endpointName}-${queryArgs}`
+
+  type SuccessResponse = { value: 'success' }
+
+  const serializer1 = vi.fn(customArgsSerializer)
+
+  interface MyApiClient {
+    fetchPost: (id: string) => Promise<SuccessResponse>
+  }
+
+  const dummyClient: MyApiClient = {
+    async fetchPost() {
+      return { value: 'success' }
+    },
+  }
+
+  const api = createApi({
+    baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+    serializeQueryArgs: ({ endpointName, queryArgs }) =>
+      `base-${endpointName}-${queryArgs}`,
+    endpoints: (build) => ({
+      queryWithNoSerializer: build.query<SuccessResponse, number>({
+        query: (arg) => `${arg}`,
+      }),
+      queryWithCustomSerializer: build.query<SuccessResponse, number>({
+        query: (arg) => `${arg}`,
+        serializeQueryArgs: serializer1,
+      }),
+      queryWithCustomObjectSerializer: build.query<
+        SuccessResponse,
+        { id: number; client: MyApiClient }
+      >({
+        query: (arg) => `${arg.id}`,
+        serializeQueryArgs: ({
+          endpointDefinition,
+          endpointName,
+          queryArgs,
+        }) => {
+          const { id } = queryArgs
+          return { id }
+        },
+      }),
+      queryWithCustomNumberSerializer: build.query<
+        SuccessResponse,
+        { id: number; client: MyApiClient }
+      >({
+        query: (arg) => `${arg.id}`,
+        serializeQueryArgs: ({
+          endpointDefinition,
+          endpointName,
+          queryArgs,
+        }) => {
+          const { id } = queryArgs
+          return id
+        },
+      }),
+      listItems: build.query<string[], number>({
+        query: (pageNumber) => `/listItems?page=${pageNumber}`,
+        serializeQueryArgs: ({ endpointName }) => {
+          return endpointName
+        },
+        merge: (currentCache, newItems) => {
+          currentCache.push(...newItems)
+        },
+        forceRefetch({ currentArg, previousArg }) {
+          return currentArg !== previousArg
+        },
+      }),
+      listItems2: build.query<{ items: string[]; meta?: any }, number>({
+        query: (pageNumber) => `/listItems2?page=${pageNumber}`,
+        serializeQueryArgs: ({ endpointName }) => {
+          return endpointName
+        },
+        transformResponse(items: string[]) {
+          return { items }
+        },
+        merge: (currentCache, newData, meta) => {
+          currentCache.items.push(...newData.items)
+          currentCache.meta = meta
+        },
+        forceRefetch({ currentArg, previousArg }) {
+          return currentArg !== previousArg
+        },
+      }),
+    }),
+  })
+
+  const storeRef = setupApiStore(api)
+
+  it('Works via createApi', async () => {
+    await storeRef.store.dispatch(
+      api.endpoints.queryWithNoSerializer.initiate(99),
+    )
+
+    expect(serializer1).not.toHaveBeenCalled()
+
+    await storeRef.store.dispatch(
+      api.endpoints.queryWithCustomSerializer.initiate(42),
+    )
+
+    expect(serializer1).toHaveBeenCalled()
+
+    expect(
+      storeRef.store.getState().api.queries['base-queryWithNoSerializer-99'],
+    ).toBeTruthy()
+
+    expect(
+      storeRef.store.getState().api.queries['queryWithCustomSerializer-42'],
+    ).toBeTruthy()
+  })
+
+  const serializer2 = vi.fn(customArgsSerializer)
+
+  const injectedApi = api.injectEndpoints({
+    endpoints: (build) => ({
+      injectedQueryWithCustomSerializer: build.query<SuccessResponse, number>({
+        query: (arg) => `${arg}`,
+        serializeQueryArgs: serializer2,
+      }),
+    }),
+  })
+
+  it('Works via injectEndpoints', async () => {
+    expect(serializer2).not.toHaveBeenCalled()
+
+    await storeRef.store.dispatch(
+      injectedApi.endpoints.injectedQueryWithCustomSerializer.initiate(5),
+    )
+
+    expect(serializer2).toHaveBeenCalled()
+    expect(
+      storeRef.store.getState().api.queries[
+        'injectedQueryWithCustomSerializer-5'
+      ],
+    ).toBeTruthy()
+  })
+
+  test('Serializes a returned object for query args', async () => {
+    await storeRef.store.dispatch(
+      api.endpoints.queryWithCustomObjectSerializer.initiate({
+        id: 42,
+        client: dummyClient,
+      }),
+    )
+
+    expect(
+      storeRef.store.getState().api.queries[
+        'queryWithCustomObjectSerializer({"id":42})'
+      ],
+    ).toBeTruthy()
+  })
+
+  test('Serializes a returned primitive for query args', async () => {
+    await storeRef.store.dispatch(
+      api.endpoints.queryWithCustomNumberSerializer.initiate({
+        id: 42,
+        client: dummyClient,
+      }),
+    )
+
+    expect(
+      storeRef.store.getState().api.queries[
+        'queryWithCustomNumberSerializer(42)'
+      ],
+    ).toBeTruthy()
+  })
+
+  test('serializeQueryArgs + merge allows refetching as args change with same cache key', async () => {
+    const allItems = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i']
+    const PAGE_SIZE = 3
+
+    server.use(
+      http.get('https://example.com/listItems', ({ request }) => {
+        const url = new URL(request.url)
+        const pageString = url.searchParams.get('page')
+        const pageNum = parseInt(pageString || '0')
+
+        const results = paginate(allItems, PAGE_SIZE, pageNum)
+        return HttpResponse.json(results)
+      }),
+    )
+
+    // Page number shouldn't matter here, because the cache key ignores that.
+    // We just need to select the only cache entry.
+    const selectListItems = api.endpoints.listItems.select(0)
+
+    await storeRef.store.dispatch(api.endpoints.listItems.initiate(1))
+
+    const initialEntry = selectListItems(storeRef.store.getState())
+    expect(initialEntry.data).toEqual(['a', 'b', 'c'])
+
+    await storeRef.store.dispatch(api.endpoints.listItems.initiate(2))
+    const updatedEntry = selectListItems(storeRef.store.getState())
+    expect(updatedEntry.data).toEqual(['a', 'b', 'c', 'd', 'e', 'f'])
+  })
+
+  test('merge receives a meta object as an argument', async () => {
+    const allItems = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i']
+    const PAGE_SIZE = 3
+
+    server.use(
+      http.get('https://example.com/listItems2', ({ request }) => {
+        const url = new URL(request.url)
+        const pageString = url.searchParams.get('page')
+        const pageNum = parseInt(pageString || '0')
+
+        const results = paginate(allItems, PAGE_SIZE, pageNum)
+        return HttpResponse.json(results)
+      }),
+    )
+
+    const selectListItems = api.endpoints.listItems2.select(0)
+
+    await storeRef.store.dispatch(api.endpoints.listItems2.initiate(1))
+    await storeRef.store.dispatch(api.endpoints.listItems2.initiate(2))
+    const cacheEntry = selectListItems(storeRef.store.getState())
+
+    // Should have passed along the third arg from `merge` containing these fields
+    expect(cacheEntry.data?.meta).toEqual({
+      requestId: expect.any(String),
+      fulfilledTimeStamp: expect.any(Number),
+      arg: 2,
+      baseQueryMeta: expect.any(Object),
+    })
+  })
+})
+
+describe('timeout behavior', () => {
+  test('triggers TIMEOUT_ERROR', async () => {
+    const api = createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com', timeout: 5 }),
+      endpoints: (build) => ({
+        query: build.query<unknown, void>({
+          query: () => '/success',
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    server.use(
+      http.get(
+        'https://example.com/success',
+        async () => {
+          await delay(50)
+          return HttpResponse.json({ value: 'failed' }, { status: 500 })
+        },
+        { once: true },
+      ),
+    )
+
+    const result = await storeRef.store.dispatch(api.endpoints.query.initiate())
+
+    expect(result?.error).toEqual({
+      status: 'TIMEOUT_ERROR',
+      error: expect.stringMatching(/^TimeoutError/),
+    })
+  })
+})
+
+describe('endpoint schemas', () => {
+  const schemaConverter: SchemaFailureConverter<
+    ReturnType<typeof fetchBaseQuery>
+  > = (error) => {
+    return {
+      status: 'CUSTOM_ERROR',
+      error: error.schemaName + ' failed validation',
+      data: error.issues,
+    }
+  }
+
+  const serializedSchemaError = {
+    name: 'SchemaError',
+    message: expect.any(String),
+    stack: expect.any(String),
+  } satisfies SerializedError
+
+  const onSchemaFailureGlobal = vi.fn<SchemaFailureHandler>()
+  const onSchemaFailureEndpoint = vi.fn<SchemaFailureHandler>()
+  afterEach(() => {
+    onSchemaFailureGlobal.mockClear()
+    onSchemaFailureEndpoint.mockClear()
+  })
+
+  function expectFailureHandlersToHaveBeenCalled({
+    schemaName,
+    value,
+    arg,
+  }: {
+    schemaName: `${SchemaType}Schema`
+    value: unknown
+    arg: unknown
+  }) {
+    for (const handler of [onSchemaFailureGlobal, onSchemaFailureEndpoint]) {
+      expect(handler).toHaveBeenCalledOnce()
+      const [namedError, info] = handler.mock.calls[0]
+      expect(namedError).toBeInstanceOf(NamedSchemaError)
+      expect(namedError.issues.length).toBeGreaterThan(0)
+      expect(namedError.value).toEqual(value)
+      expect(namedError.schemaName).toBe(schemaName)
+      expect(info.endpoint).toBe('query')
+      expect(info.type).toBe('query')
+      expect(info.arg).toEqual(arg)
+    }
+  }
+
+  interface SkipApiOptions {
+    globalSkip?: boolean
+    endpointSkip?: boolean
+    useArray?: boolean
+    globalCatch?: boolean
+    endpointCatch?: boolean
+  }
+
+  const apiOptions = (
+    type: SchemaType,
+    { useArray, globalSkip, globalCatch }: SkipApiOptions = {},
+  ) => ({
+    onSchemaFailure: onSchemaFailureGlobal,
+    skipSchemaValidation: useArray ? globalSkip && [type] : globalSkip,
+    catchSchemaFailure: globalCatch ? schemaConverter : undefined,
+  })
+
+  const endpointOptions = (
+    type: SchemaType,
+    { useArray, endpointSkip, endpointCatch }: SkipApiOptions = {},
+  ) => ({
+    onSchemaFailure: onSchemaFailureEndpoint,
+    skipSchemaValidation: useArray ? endpointSkip && [type] : endpointSkip,
+    catchSchemaFailure: endpointCatch ? schemaConverter : undefined,
+  })
+
+  const skipCases: [string, SkipApiOptions][] = [
+    ['globally', { globalSkip: true }],
+    ['on the endpoint', { endpointSkip: true }],
+    ['globally (array)', { globalSkip: true, useArray: true }],
+    ['on the endpoint (array)', { endpointSkip: true, useArray: true }],
+  ]
+
+  describe('argSchema', () => {
+    const makeApi = (opts?: SkipApiOptions) =>
+      createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+        ...apiOptions('arg', opts),
+        endpoints: (build) => ({
+          query: build.query<unknown, { id: number }>({
+            query: ({ id }) => `/post/${id}`,
+            argSchema: v.object({ id: v.number() }),
+            ...endpointOptions('arg', opts),
+          }),
+        }),
+      })
+    test("can be used to validate the endpoint's arguments", async () => {
+      const api = makeApi()
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate({ id: 1 }),
+      )
+
+      expect(result?.error).toBeUndefined()
+
+      const invalidResult = await storeRef.store.dispatch(
+        // @ts-expect-error
+        api.endpoints.query.initiate({ id: '1' }),
+      )
+
+      expect(invalidResult?.error).toEqual(serializedSchemaError)
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'argSchema',
+        value: { id: '1' },
+        arg: { id: '1' },
+      })
+    })
+
+    test.each(skipCases)('can be skipped %s', async (_, arg) => {
+      const api = makeApi(arg)
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      const result = await storeRef.store.dispatch(
+        // @ts-expect-error
+        api.endpoints.query.initiate({ id: '1' }),
+      )
+
+      expect(result?.error).toBeUndefined()
+    })
+    // we only need to test this once
+    test('endpoint overrides global skip', async () => {
+      const api = makeApi({ globalSkip: true, endpointSkip: false })
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      const result = await storeRef.store.dispatch(
+        // @ts-expect-error
+        api.endpoints.query.initiate({ id: '1' }),
+      )
+
+      expect(result?.error).toEqual(serializedSchemaError)
+    })
+
+    test('can be converted to a standard error object at global level', async () => {
+      const api = makeApi({ globalCatch: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      const result = await storeRef.store.dispatch(
+        // @ts-expect-error
+        api.endpoints.query.initiate({ id: '1' }),
+      )
+
+      expect(result?.error).toEqual({
+        status: 'CUSTOM_ERROR',
+        error: 'argSchema failed validation',
+        data: expect.any(Array),
+      })
+
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'argSchema',
+        value: { id: '1' },
+        arg: { id: '1' },
+      })
+    })
+    test('can be converted to a standard error object at endpoint level', async () => {
+      const api = makeApi({ endpointCatch: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      const result = await storeRef.store.dispatch(
+        // @ts-expect-error
+        api.endpoints.query.initiate({ id: '1' }),
+      )
+
+      expect(result?.error).toEqual({
+        status: 'CUSTOM_ERROR',
+        error: 'argSchema failed validation',
+        data: expect.any(Array),
+      })
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'argSchema',
+        value: { id: '1' },
+        arg: { id: '1' },
+      })
+    })
+  })
+  describe('rawResponseSchema', () => {
+    const makeApi = (opts?: SkipApiOptions) =>
+      createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+        ...apiOptions('rawResponse', opts),
+        endpoints: (build) => ({
+          query: build.query<{ success: boolean }, void>({
+            query: () => '/success',
+            rawResponseSchema: v.object({ value: v.literal('success!') }),
+            ...endpointOptions('rawResponse', opts),
+          }),
+        }),
+      })
+    test("can be used to validate the endpoint's raw result", async () => {
+      const api = makeApi()
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual(serializedSchemaError)
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'rawResponseSchema',
+        value: { value: 'success' },
+        arg: undefined,
+      })
+    })
+    test.each(skipCases)('can be skipped %s', async (_, arg) => {
+      const api = makeApi(arg)
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toBeUndefined()
+    })
+    test('can be skipped on the endpoint', async () => {
+      const api = makeApi({ endpointSkip: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toBeUndefined()
+    })
+    test('can be converted to a standard error object at global level', async () => {
+      const api = makeApi({ globalCatch: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual({
+        status: 'CUSTOM_ERROR',
+        error: 'rawResponseSchema failed validation',
+        data: expect.any(Array),
+      })
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'rawResponseSchema',
+        value: { value: 'success' },
+        arg: undefined,
+      })
+    })
+    test('can be converted to a standard error object at endpoint level', async () => {
+      const api = makeApi({ endpointCatch: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual({
+        status: 'CUSTOM_ERROR',
+        error: 'rawResponseSchema failed validation',
+        data: expect.any(Array),
+      })
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'rawResponseSchema',
+        value: { value: 'success' },
+        arg: undefined,
+      })
+    })
+  })
+  describe('responseSchema', () => {
+    const makeApi = (opts?: SkipApiOptions) =>
+      createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+        ...apiOptions('response', opts),
+        endpoints: (build) => ({
+          query: build.query<{ success: boolean }, void>({
+            query: () => '/success',
+            transformResponse: () => ({ success: false }),
+            responseSchema: v.object({ success: v.literal(true) }),
+            ...endpointOptions('response', opts),
+          }),
+        }),
+      })
+    test("can be used to validate the endpoint's final result", async () => {
+      const api = makeApi()
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual(serializedSchemaError)
+
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'responseSchema',
+        value: { success: false },
+        arg: undefined,
+      })
+    })
+    test.each(skipCases)('can be skipped %s', async (_, arg) => {
+      const api = makeApi(arg)
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toBeUndefined()
+    })
+    test('can be converted to a standard error object at global level', async () => {
+      const api = makeApi({ globalCatch: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual({
+        status: 'CUSTOM_ERROR',
+        error: 'responseSchema failed validation',
+        data: expect.any(Array),
+      })
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'responseSchema',
+        value: { success: false },
+        arg: undefined,
+      })
+    })
+    test('can be converted to a standard error object at endpoint level', async () => {
+      const api = makeApi({ endpointCatch: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual({
+        status: 'CUSTOM_ERROR',
+        error: 'responseSchema failed validation',
+        data: expect.any(Array),
+      })
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'responseSchema',
+        value: { success: false },
+        arg: undefined,
+      })
+    })
+  })
+  describe('rawErrorResponseSchema', () => {
+    const makeApi = (opts?: SkipApiOptions) =>
+      createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+        ...apiOptions('rawErrorResponse', opts),
+        endpoints: (build) => ({
+          query: build.query<{ success: boolean }, void>({
+            query: () => '/error',
+            rawErrorResponseSchema: v.object({
+              status: v.pipe(v.number(), v.minValue(400), v.maxValue(499)),
+              data: v.unknown(),
+            }),
+            ...endpointOptions('rawErrorResponse', opts),
+          }),
+        }),
+      })
+    test("can be used to validate the endpoint's raw error result", async () => {
+      const api = makeApi()
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual(serializedSchemaError)
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'rawErrorResponseSchema',
+        value: { status: 500, data: { value: 'error' } },
+        arg: undefined,
+      })
+    })
+    test.each(skipCases)('can be skipped %s', async (_, arg) => {
+      const api = makeApi(arg)
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).not.toEqual(serializedSchemaError)
+    })
+    test('can be converted to a standard error object at global level', async () => {
+      const api = makeApi({ globalCatch: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual({
+        status: 'CUSTOM_ERROR',
+        error: 'rawErrorResponseSchema failed validation',
+        data: expect.any(Array),
+      })
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'rawErrorResponseSchema',
+        value: { status: 500, data: { value: 'error' } },
+        arg: undefined,
+      })
+    })
+    test('can be converted to a standard error object at endpoint level', async () => {
+      const api = makeApi({ endpointCatch: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual({
+        status: 'CUSTOM_ERROR',
+        error: 'rawErrorResponseSchema failed validation',
+        data: expect.any(Array),
+      })
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'rawErrorResponseSchema',
+        value: { status: 500, data: { value: 'error' } },
+        arg: undefined,
+      })
+    })
+  })
+  describe('errorResponseSchema', () => {
+    const makeApi = (opts?: SkipApiOptions) =>
+      createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+        ...apiOptions('errorResponse', opts),
+        endpoints: (build) => ({
+          query: build.query<{ success: boolean }, void>({
+            query: () => '/error',
+            transformErrorResponse: (error): FetchBaseQueryError => ({
+              status: 'CUSTOM_ERROR',
+              data: error,
+              error: 'whoops',
+            }),
+            errorResponseSchema: v.object({
+              status: v.literal('CUSTOM_ERROR'),
+              error: v.literal('oh no'),
+              data: v.unknown(),
+            }),
+            ...endpointOptions('errorResponse', opts),
+          }),
+        }),
+      })
+    test("can be used to validate the endpoint's final error result", async () => {
+      const api = makeApi()
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual(serializedSchemaError)
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'errorResponseSchema',
+        value: {
+          status: 'CUSTOM_ERROR',
+          error: 'whoops',
+          data: { status: 500, data: { value: 'error' } },
+        },
+        arg: undefined,
+      })
+    })
+    test.each(skipCases)('can be skipped %s', async (_, arg) => {
+      const api = makeApi(arg)
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).not.toEqual(serializedSchemaError)
+    })
+    test('can be converted to a standard error object at global level', async () => {
+      const api = makeApi({ globalCatch: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual({
+        status: 'CUSTOM_ERROR',
+        error: 'errorResponseSchema failed validation',
+        data: expect.any(Array),
+      })
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'errorResponseSchema',
+        value: {
+          status: 'CUSTOM_ERROR',
+          error: 'whoops',
+          data: { status: 500, data: { value: 'error' } },
+        },
+        arg: undefined,
+      })
+    })
+    test('can be converted to a standard error object at endpoint level', async () => {
+      const api = makeApi({ endpointCatch: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual({
+        status: 'CUSTOM_ERROR',
+        error: 'errorResponseSchema failed validation',
+        data: expect.any(Array),
+      })
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'errorResponseSchema',
+        value: {
+          status: 'CUSTOM_ERROR',
+          error: 'whoops',
+          data: { status: 500, data: { value: 'error' } },
+        },
+        arg: undefined,
+      })
+    })
+  })
+  describe('metaSchema', () => {
+    const makeApi = (opts?: SkipApiOptions) =>
+      createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+        ...apiOptions('meta', opts),
+        endpoints: (build) => ({
+          query: build.query<{ success: boolean }, void>({
+            query: () => '/success',
+            metaSchema: v.object({
+              request: v.instance(Request),
+              response: v.instance(Response),
+              timestamp: v.number(),
+            }),
+            ...endpointOptions('meta', opts),
+          }),
+        }),
+      })
+    test("can be used to validate the endpoint's meta result", async () => {
+      const api = makeApi()
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual(serializedSchemaError)
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'metaSchema',
+        value: {
+          request: expect.any(Request),
+          response: expect.any(Response),
+        },
+        arg: undefined,
+      })
+    })
+    test.each(skipCases)('can be skipped %s', async (_, arg) => {
+      const api = makeApi(arg)
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toBeUndefined()
+    })
+    test('can be converted to a standard error object at global level', async () => {
+      const api = makeApi({ globalCatch: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual({
+        status: 'CUSTOM_ERROR',
+        error: 'metaSchema failed validation',
+        data: expect.any(Array),
+      })
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'metaSchema',
+        value: {
+          request: expect.any(Request),
+          response: expect.any(Response),
+        },
+        arg: undefined,
+      })
+    })
+    test('can be converted to a standard error object at endpoint level', async () => {
+      const api = makeApi({ endpointCatch: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual({
+        status: 'CUSTOM_ERROR',
+        error: 'metaSchema failed validation',
+        data: expect.any(Array),
+      })
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'metaSchema',
+        value: {
+          request: expect.any(Request),
+          response: expect.any(Response),
+        },
+        arg: undefined,
+      })
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/defaultSerializeQueryArgs.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/defaultSerializeQueryArgs.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/defaultSerializeQueryArgs.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,122 @@
+import { defaultSerializeQueryArgs } from '@internal/query/defaultSerializeQueryArgs'
+
+const endpointDefinition: any = {}
+const endpointName = 'test'
+
+test('string arg', () => {
+  expect(
+    defaultSerializeQueryArgs({
+      endpointDefinition,
+      endpointName,
+      queryArgs: 'arg',
+    }),
+  ).toMatchInlineSnapshot(`"test("arg")"`)
+})
+
+test('number arg', () => {
+  expect(
+    defaultSerializeQueryArgs({
+      endpointDefinition,
+      endpointName,
+      queryArgs: 5,
+    }),
+  ).toMatchInlineSnapshot(`"test(5)"`)
+})
+
+test('bigint arg has non-default serialization (intead of throwing)', () => {
+  expect(
+    defaultSerializeQueryArgs({
+      endpointDefinition,
+      endpointName,
+      queryArgs: BigInt(10),
+    }),
+  ).toMatchInlineSnapshot(`"test({"$bigint":"10"})"`)
+})
+
+test('simple object arg is sorted', () => {
+  expect(
+    defaultSerializeQueryArgs({
+      endpointDefinition,
+      endpointName,
+      queryArgs: { name: 'arg', age: 5 },
+    }),
+  ).toMatchInlineSnapshot(`"test({"age":5,"name":"arg"})"`)
+})
+
+test('nested object arg is sorted recursively', () => {
+  expect(
+    defaultSerializeQueryArgs({
+      endpointDefinition,
+      endpointName,
+      queryArgs: { name: { last: 'Split', first: 'Banana' }, age: 5 },
+    }),
+  ).toMatchInlineSnapshot(
+    `"test({"age":5,"name":{"first":"Banana","last":"Split"}})"`,
+  )
+})
+
+test('Fully serializes a deeply nested object', () => {
+  const nestedObj = {
+    a: {
+      a1: {
+        a11: {
+          a111: 1,
+        },
+      },
+    },
+    b: {
+      b2: {
+        b21: 3,
+      },
+      b1: {
+        b11: 2,
+      },
+    },
+  }
+
+  const res = defaultSerializeQueryArgs({
+    endpointDefinition,
+    endpointName,
+    queryArgs: nestedObj,
+  })
+  expect(res).toMatchInlineSnapshot(
+    `"test({"a":{"a1":{"a11":{"a111":1}}},"b":{"b1":{"b11":2},"b2":{"b21":3}}})"`,
+  )
+})
+
+test('Caches results for plain objects', () => {
+  const testData = Array.from({ length: 10000 }).map((_, i) => {
+    return {
+      albumId: i,
+      id: i,
+      title: 'accusamus beatae ad facilis cum similique qui sunt',
+      url: 'https://via.placeholder.com/600/92c952',
+      thumbnailUrl: 'https://via.placeholder.com/150/92c952',
+    }
+  })
+
+  const data = {
+    testData,
+  }
+
+  const runWithTimer = (data: any) => {
+    const start = Date.now()
+    const res = defaultSerializeQueryArgs({
+      endpointDefinition,
+      endpointName,
+      queryArgs: data,
+    })
+    const end = Date.now()
+    const duration = end - start
+    return [res, duration] as const
+  }
+
+  const [res1, time1] = runWithTimer(data)
+  const [res2, time2] = runWithTimer(data)
+
+  expect(res1).toBe(res2)
+  expect(time2).toBeLessThanOrEqual(time1)
+  // Locally, stringifying 10K items takes 25-30ms.
+  // Assuming the WeakMap cache hit, this _should_ be 0
+  expect(time2).toBeLessThan(2)
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/devWarnings.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/devWarnings.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/devWarnings.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,552 @@
+import { noop } from '@internal/listenerMiddleware/utils'
+import { configureStore } from '@reduxjs/toolkit'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+
+const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(noop)
+
+const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
+
+beforeEach(() => {
+  vi.stubEnv('NODE_ENV', 'development')
+})
+
+afterEach(() => {
+  vi.unstubAllEnvs()
+  vi.clearAllMocks()
+})
+
+afterAll(() => {
+  vi.restoreAllMocks()
+  vi.unstubAllEnvs()
+})
+
+const baseUrl = 'https://example.com'
+
+function createApis() {
+  const api1 = createApi({
+    baseQuery: fetchBaseQuery({ baseUrl }),
+    endpoints: (builder) => ({
+      q1: builder.query({ query: () => '/success' }),
+    }),
+  })
+
+  const api1_2 = createApi({
+    baseQuery: fetchBaseQuery({ baseUrl }),
+    endpoints: (builder) => ({
+      q1: builder.query({ query: () => '/success' }),
+    }),
+  })
+
+  const api2 = createApi({
+    reducerPath: 'api2',
+    baseQuery: fetchBaseQuery({ baseUrl }),
+    endpoints: (builder) => ({
+      q1: builder.query({ query: () => '/success' }),
+    }),
+  })
+  return [api1, api1_2, api2] as const
+}
+
+let [api1, api1_2, api2] = createApis()
+beforeEach(() => {
+  ;[api1, api1_2, api2] = createApis()
+})
+
+const reMatchMissingMiddlewareError =
+  /Warning: Middleware for RTK-Query API at reducerPath "api" has not been added to the store/
+
+describe('missing middleware', () => {
+  test.each([
+    ['development', true],
+    ['production', false],
+  ])('%s warns if middleware is missing: %s', (env, shouldWarn) => {
+    vi.stubEnv('NODE_ENV', env)
+
+    const store = configureStore({
+      reducer: { [api1.reducerPath]: api1.reducer },
+    })
+    const doDispatch = () => {
+      store.dispatch(api1.endpoints.q1.initiate(undefined))
+    }
+    if (shouldWarn) {
+      expect(doDispatch).toThrowError(reMatchMissingMiddlewareError)
+    } else {
+      expect(doDispatch).not.toThrowError()
+    }
+  })
+
+  test('does not warn if middleware is not missing', () => {
+    const store = configureStore({
+      reducer: { [api1.reducerPath]: api1.reducer },
+      middleware: (gdm) => gdm().concat(api1.middleware),
+    })
+    store.dispatch(api1.endpoints.q1.initiate(undefined))
+
+    expect(consoleErrorSpy).not.toHaveBeenCalled()
+
+    expect(consoleWarnSpy).not.toHaveBeenCalled()
+  })
+
+  test('warns only once per api', () => {
+    const store = configureStore({
+      reducer: { [api1.reducerPath]: api1.reducer },
+    })
+    const doDispatch = () => {
+      store.dispatch(api1.endpoints.q1.initiate(undefined))
+    }
+
+    expect(doDispatch).toThrowError(reMatchMissingMiddlewareError)
+    expect(doDispatch).not.toThrowError()
+  })
+
+  test('warns multiple times for multiple apis', () => {
+    const store = configureStore({
+      reducer: {
+        [api1.reducerPath]: api1.reducer,
+        [api2.reducerPath]: api2.reducer,
+      },
+    })
+    const doDispatch1 = () => {
+      store.dispatch(api1.endpoints.q1.initiate(undefined))
+    }
+    const doDispatch2 = () => {
+      store.dispatch(api2.endpoints.q1.initiate(undefined))
+    }
+    expect(doDispatch1).toThrowError(reMatchMissingMiddlewareError)
+    expect(doDispatch2).toThrowError(
+      /Warning: Middleware for RTK-Query API at reducerPath "api2" has not been added to the store/,
+    )
+  })
+})
+
+describe('missing reducer', () => {
+  describe.each([
+    ['development', true],
+    ['production', false],
+  ])('%s warns if reducer is missing: %s', (env, shouldWarn) => {
+    beforeEach(() => {
+      vi.stubEnv('NODE_ENV', env)
+    })
+
+    afterAll(() => {
+      vi.unstubAllEnvs()
+    })
+
+    test('middleware not crashing if reducer is missing', async () => {
+      const store = configureStore({
+        reducer: { x: () => 0 },
+        // @ts-expect-error
+        middleware: (gdm) => gdm().concat(api1.middleware),
+      })
+      await store.dispatch(api1.endpoints.q1.initiate(undefined))
+
+      expect(process.env.NODE_ENV).toBe(env)
+    })
+
+    test(`warning behavior`, () => {
+      const store = configureStore({
+        reducer: { x: () => 0 },
+        // @ts-expect-error
+        middleware: (gdm) => gdm().concat(api1.middleware),
+      })
+      // @ts-expect-error
+      api1.endpoints.q1.select(undefined)(store.getState())
+
+      expect(consoleWarnSpy).not.toHaveBeenCalled()
+
+      expect(process.env.NODE_ENV).toBe(env)
+
+      if (shouldWarn) {
+        expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+        expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+          'Error: No data found at `state.api`. Did you forget to add the reducer to the store?',
+        )
+      } else {
+        expect(consoleErrorSpy).not.toHaveBeenCalled()
+      }
+    })
+  })
+
+  test('does not warn if reducer is not missing', () => {
+    const store = configureStore({
+      reducer: { [api1.reducerPath]: api1.reducer },
+      middleware: (gdm) => gdm().concat(api1.middleware),
+    })
+    api1.endpoints.q1.select(undefined)(store.getState())
+
+    expect(consoleErrorSpy).not.toHaveBeenCalled()
+
+    expect(consoleWarnSpy).not.toHaveBeenCalled()
+  })
+
+  test('warns only once per api', () => {
+    const store = configureStore({
+      reducer: { x: () => 0 },
+      // @ts-expect-error
+      middleware: (gdm) => gdm().concat(api1.middleware),
+    })
+    // @ts-expect-error
+    api1.endpoints.q1.select(undefined)(store.getState())
+    // @ts-expect-error
+    api1.endpoints.q1.select(undefined)(store.getState())
+
+    expect(consoleWarnSpy).not.toHaveBeenCalled()
+
+    expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+    expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+      'Error: No data found at `state.api`. Did you forget to add the reducer to the store?',
+    )
+  })
+
+  test('warns multiple times for multiple apis', () => {
+    const store = configureStore({
+      reducer: { x: () => 0 },
+      // @ts-expect-error
+      middleware: (gdm) => gdm().concat(api1.middleware),
+    })
+    // @ts-expect-error
+    api1.endpoints.q1.select(undefined)(store.getState())
+    // @ts-expect-error
+    api2.endpoints.q1.select(undefined)(store.getState())
+
+    expect(consoleWarnSpy).not.toHaveBeenCalled()
+
+    expect(consoleErrorSpy).toHaveBeenCalledTimes(2)
+
+    expect(consoleErrorSpy).toHaveBeenNthCalledWith(
+      1,
+      'Error: No data found at `state.api`. Did you forget to add the reducer to the store?',
+    )
+
+    expect(consoleErrorSpy).toHaveBeenNthCalledWith(
+      2,
+      'Error: No data found at `state.api2`. Did you forget to add the reducer to the store?',
+    )
+  })
+})
+
+test('warns for reducer and also throws error if everything is missing', async () => {
+  const store = configureStore({
+    reducer: { x: () => 0 },
+  })
+  // @ts-expect-error
+  api1.endpoints.q1.select(undefined)(store.getState())
+  const doDispatch = () => {
+    store.dispatch(api1.endpoints.q1.initiate(undefined))
+  }
+  expect(doDispatch).toThrowError(reMatchMissingMiddlewareError)
+
+  expect(consoleWarnSpy).not.toHaveBeenCalled()
+
+  expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+  expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+    'Error: No data found at `state.api`. Did you forget to add the reducer to the store?',
+  )
+})
+
+describe('warns on multiple apis using the same `reducerPath`', () => {
+  test('common: two apis, same order', async () => {
+    const store = configureStore({
+      reducer: {
+        // TS 5.3 now errors on identical object keys. We want to force that behavior.
+        // @ts-ignore
+        [api1.reducerPath]: api1.reducer,
+        // @ts-ignore
+        [api1_2.reducerPath]: api1_2.reducer,
+      },
+      middleware: (gDM) => gDM().concat(api1.middleware, api1_2.middleware),
+    })
+    await store.dispatch(api1.endpoints.q1.initiate(undefined))
+
+    expect(consoleErrorSpy).not.toHaveBeenCalled()
+
+    expect(consoleWarnSpy).toHaveBeenCalledOnce()
+
+    // only second api prints
+    expect(consoleWarnSpy).toHaveBeenLastCalledWith(
+      `There is a mismatch between slice and middleware for the reducerPath "api".
+You can only have one api per reducer path, this will lead to crashes in various situations!
+If you have multiple apis, you *have* to specify the reducerPath option when using createApi!`,
+    )
+  })
+
+  test('common: two apis, opposing order', async () => {
+    const store = configureStore({
+      reducer: {
+        // @ts-ignore
+        [api1.reducerPath]: api1.reducer,
+        // @ts-ignore
+        [api1_2.reducerPath]: api1_2.reducer,
+      },
+      middleware: (gDM) => gDM().concat(api1_2.middleware, api1.middleware),
+    })
+    await store.dispatch(api1.endpoints.q1.initiate(undefined))
+
+    expect(consoleErrorSpy).not.toHaveBeenCalled()
+
+    expect(consoleWarnSpy).toHaveBeenCalledTimes(2)
+
+    // both apis print
+    expect(consoleWarnSpy).toHaveBeenNthCalledWith(
+      1,
+      `There is a mismatch between slice and middleware for the reducerPath "api".
+You can only have one api per reducer path, this will lead to crashes in various situations!
+If you have multiple apis, you *have* to specify the reducerPath option when using createApi!`,
+    )
+
+    expect(consoleWarnSpy).toHaveBeenNthCalledWith(
+      2,
+      `There is a mismatch between slice and middleware for the reducerPath "api".
+You can only have one api per reducer path, this will lead to crashes in various situations!
+If you have multiple apis, you *have* to specify the reducerPath option when using createApi!`,
+    )
+  })
+
+  test('common: two apis, only first middleware', async () => {
+    const store = configureStore({
+      reducer: {
+        // @ts-ignore
+        [api1.reducerPath]: api1.reducer,
+        // @ts-ignore
+        [api1_2.reducerPath]: api1_2.reducer,
+      },
+      middleware: (gDM) => gDM().concat(api1.middleware),
+    })
+    await store.dispatch(api1.endpoints.q1.initiate(undefined))
+
+    expect(consoleErrorSpy).not.toHaveBeenCalled()
+
+    expect(consoleWarnSpy).toHaveBeenCalledOnce()
+
+    expect(consoleWarnSpy).toHaveBeenLastCalledWith(
+      `There is a mismatch between slice and middleware for the reducerPath "api".
+You can only have one api per reducer path, this will lead to crashes in various situations!
+If you have multiple apis, you *have* to specify the reducerPath option when using createApi!`,
+    )
+  })
+
+  /**
+   * This is the one edge case that we currently cannot detect:
+   * Multiple apis with the same reducer key and only the middleware of the last api is being used.
+   *
+   * It would be great to support this case as well, but for now:
+   * "It is what it is."
+   */
+  test.todo('common: two apis, only second middleware', async () => {
+    const store = configureStore({
+      reducer: {
+        // @ts-ignore
+        [api1.reducerPath]: api1.reducer,
+        // @ts-ignore
+        [api1_2.reducerPath]: api1_2.reducer,
+      },
+      middleware: (gDM) => gDM().concat(api1_2.middleware),
+    })
+    await store.dispatch(api1.endpoints.q1.initiate(undefined))
+
+    expect(consoleErrorSpy).not.toHaveBeenCalled()
+
+    expect(consoleWarnSpy).toHaveBeenCalledOnce()
+
+    expect(consoleWarnSpy).toHaveBeenLastCalledWith(
+      `There is a mismatch between slice and middleware for the reducerPath "api".
+You can only have one api per reducer path, this will lead to crashes in various situations!
+If you have multiple apis, you *have* to specify the reducerPath option when using createApi!`,
+    )
+  })
+})
+
+describe('`console.error` on unhandled errors during `initiate`', () => {
+  test('error thrown in `baseQuery`', async () => {
+    const api = createApi({
+      baseQuery(): { data: any } {
+        throw new Error('this was kinda expected')
+      },
+      endpoints: (build) => ({
+        baseQuery: build.query<any, void>({ query() {} }),
+      }),
+    })
+    const store = configureStore({
+      reducer: { [api.reducerPath]: api.reducer },
+      middleware: (gdm) => gdm().concat(api.middleware),
+    })
+    await store.dispatch(api.endpoints.baseQuery.initiate())
+
+    expect(consoleWarnSpy).not.toHaveBeenCalled()
+
+    expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+    expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+      `An unhandled error occurred processing a request for the endpoint "baseQuery".
+In the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+      Error('this was kinda expected'),
+    )
+  })
+
+  test('error thrown in `queryFn`', async () => {
+    const api = createApi({
+      baseQuery() {
+        return { data: {} }
+      },
+      endpoints: (build) => ({
+        queryFn: build.query<any, void>({
+          queryFn() {
+            throw new Error('this was kinda expected')
+          },
+        }),
+      }),
+    })
+    const store = configureStore({
+      reducer: { [api.reducerPath]: api.reducer },
+      middleware: (gdm) => gdm().concat(api.middleware),
+    })
+    await store.dispatch(api.endpoints.queryFn.initiate())
+
+    expect(consoleWarnSpy).not.toHaveBeenCalled()
+
+    expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+    expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+      `An unhandled error occurred processing a request for the endpoint "queryFn".
+In the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+      Error('this was kinda expected'),
+    )
+  })
+
+  test('error thrown in `transformResponse`', async () => {
+    const api = createApi({
+      baseQuery() {
+        return { data: {} }
+      },
+      endpoints: (build) => ({
+        transformRspn: build.query<any, void>({
+          query() {},
+          transformResponse() {
+            throw new Error('this was kinda expected')
+          },
+        }),
+      }),
+    })
+    const store = configureStore({
+      reducer: { [api.reducerPath]: api.reducer },
+      middleware: (gdm) => gdm().concat(api.middleware),
+    })
+    await store.dispatch(api.endpoints.transformRspn.initiate())
+
+    expect(consoleWarnSpy).not.toHaveBeenCalled()
+
+    expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+    expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+      `An unhandled error occurred processing a request for the endpoint "transformRspn".
+In the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+      Error('this was kinda expected'),
+    )
+  })
+
+  test('error thrown in `transformErrorResponse`', async () => {
+    const api = createApi({
+      baseQuery() {
+        return { error: {} }
+      },
+      endpoints: (build) => ({
+        // @ts-ignore TS doesn't like `() => never` for `tER`
+        transformErRspn: build.query<number, void>({
+          // @ts-ignore TS doesn't like `() => never` for `tER`
+          query: () => '/dummy',
+          // @ts-ignore TS doesn't like `() => never` for `tER`
+          transformErrorResponse() {
+            throw new Error('this was kinda expected')
+          },
+        }),
+      }),
+    })
+    const store = configureStore({
+      reducer: { [api.reducerPath]: api.reducer },
+      middleware: (gdm) => gdm().concat(api.middleware),
+    })
+    await store.dispatch(api.endpoints.transformErRspn.initiate())
+
+    expect(consoleWarnSpy).not.toHaveBeenCalled()
+
+    expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+    expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+      `An unhandled error occurred processing a request for the endpoint "transformErRspn".
+In the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+      Error('this was kinda expected'),
+    )
+  })
+
+  test('`fetchBaseQuery`: error thrown in `prepareHeaders`', async () => {
+    const api = createApi({
+      baseQuery: fetchBaseQuery({
+        baseUrl,
+        prepareHeaders() {
+          throw new Error('this was kinda expected')
+        },
+      }),
+      endpoints: (build) => ({
+        prep: build.query<any, void>({
+          query() {
+            return '/success'
+          },
+        }),
+      }),
+    })
+    const store = configureStore({
+      reducer: { [api.reducerPath]: api.reducer },
+      middleware: (gdm) => gdm().concat(api.middleware),
+    })
+    await store.dispatch(api.endpoints.prep.initiate())
+
+    expect(consoleWarnSpy).not.toHaveBeenCalled()
+
+    expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+    expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+      `An unhandled error occurred processing a request for the endpoint "prep".
+In the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+      Error('this was kinda expected'),
+    )
+  })
+
+  test('`fetchBaseQuery`: error thrown in `validateStatus`', async () => {
+    const api = createApi({
+      baseQuery: fetchBaseQuery({
+        baseUrl,
+      }),
+      endpoints: (build) => ({
+        val: build.query<any, void>({
+          query() {
+            return {
+              url: '/success',
+
+              validateStatus() {
+                throw new Error('this was kinda expected')
+              },
+            }
+          },
+        }),
+      }),
+    })
+    const store = configureStore({
+      reducer: { [api.reducerPath]: api.reducer },
+      middleware: (gdm) => gdm().concat(api.middleware),
+    })
+    await store.dispatch(api.endpoints.val.initiate())
+
+    expect(consoleWarnSpy).not.toHaveBeenCalled()
+
+    expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+    expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+      `An unhandled error occurred processing a request for the endpoint "val".
+In the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+      Error('this was kinda expected'),
+    )
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/errorHandling.test-d.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/errorHandling.test-d.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/errorHandling.test-d.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,52 @@
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+import { useState } from 'react'
+
+const mockSuccessResponse = { value: 'success' }
+
+const api = createApi({
+  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+  endpoints: (build) => ({
+    update: build.mutation<typeof mockSuccessResponse, any>({
+      query: () => ({ url: 'success' }),
+    }),
+    failedUpdate: build.mutation<typeof mockSuccessResponse, any>({
+      query: () => ({ url: 'error' }),
+    }),
+  }),
+})
+
+describe('type tests', () => {
+  test('a mutation is unwrappable and has the correct types', () => {
+    function User() {
+      const [manualError, setManualError] = useState<any>()
+
+      const [update, { isLoading, data, error }] =
+        api.endpoints.update.useMutation()
+
+      return (
+        <div>
+          <div data-testid="isLoading">{String(isLoading)}</div>
+          <div data-testid="data">{JSON.stringify(data)}</div>
+          <div data-testid="error">{JSON.stringify(error)}</div>
+          <div data-testid="manuallySetError">
+            {JSON.stringify(manualError)}
+          </div>
+          <button
+            onClick={() => {
+              update({ name: 'hello' })
+                .unwrap()
+                .then((result) => {
+                  expectTypeOf(result).toEqualTypeOf(mockSuccessResponse)
+
+                  setManualError(undefined)
+                })
+                .catch(setManualError)
+            }}
+          >
+            Update User
+          </button>
+        </div>
+      )
+    }
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/errorHandling.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/errorHandling.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/errorHandling.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,657 @@
+import type { ThunkDispatch, UnknownAction } from '@reduxjs/toolkit'
+import type { BaseQueryFn, BaseQueryApi } from '@reduxjs/toolkit/query/react'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+import {
+  act,
+  fireEvent,
+  render,
+  renderHook,
+  screen,
+  waitFor,
+} from '@testing-library/react'
+import type { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios'
+import axios from 'axios'
+import { HttpResponse, http } from 'msw'
+import * as React from 'react'
+import { useDispatch } from 'react-redux'
+import { hookWaitFor, setupApiStore } from '@internal/tests/utils/helpers'
+import { server } from '@internal/query/tests/mocks/server'
+
+const baseQuery = fetchBaseQuery({ baseUrl: 'https://example.com' })
+
+const api = createApi({
+  baseQuery,
+  endpoints(build) {
+    return {
+      query: build.query({ query: () => '/query' }),
+      mutation: build.mutation({
+        query: () => ({ url: '/mutation', method: 'POST' }),
+      }),
+    }
+  },
+})
+
+const storeRef = setupApiStore(api)
+
+const failQueryOnce = http.get(
+  '/query',
+  () => HttpResponse.json({ value: 'failed' }, { status: 500 }),
+  { once: true },
+)
+
+describe('fetchBaseQuery', () => {
+  let commonBaseQueryApiArgs: BaseQueryApi = {} as any
+  beforeEach(() => {
+    const abortController = new AbortController()
+    commonBaseQueryApiArgs = {
+      signal: abortController.signal,
+      abort: (reason) =>
+        //@ts-ignore
+        abortController.abort(reason),
+      dispatch: storeRef.store.dispatch,
+      getState: storeRef.store.getState,
+      extra: undefined,
+      type: 'query',
+      endpoint: 'doesntmatterhere',
+    }
+  })
+  test('success', async () => {
+    await expect(
+      baseQuery('/success', commonBaseQueryApiArgs, {}),
+    ).resolves.toEqual({
+      data: { value: 'success' },
+      meta: {
+        request: expect.any(Object),
+        response: expect.any(Object),
+      },
+    })
+  })
+  test('error', async () => {
+    server.use(failQueryOnce)
+    await expect(
+      baseQuery('/error', commonBaseQueryApiArgs, {}),
+    ).resolves.toEqual({
+      error: {
+        data: { value: 'error' },
+        status: 500,
+      },
+      meta: {
+        request: expect.any(Object),
+        response: expect.any(Object),
+      },
+    })
+  })
+})
+
+describe('query error handling', () => {
+  test('success', async () => {
+    server.use(
+      http.get('https://example.com/query', () =>
+        HttpResponse.json({ value: 'success' }),
+      ),
+    )
+    const { result } = renderHook(() => api.endpoints.query.useQuery({}), {
+      wrapper: storeRef.wrapper,
+    })
+
+    await hookWaitFor(() => expect(result.current.isFetching).toBeFalsy())
+    expect(result.current).toEqual(
+      expect.objectContaining({
+        isLoading: false,
+        isError: false,
+        isSuccess: true,
+        data: { value: 'success' },
+      }),
+    )
+  })
+
+  test('error', async () => {
+    server.use(
+      http.get('https://example.com/query', () =>
+        HttpResponse.json({ value: 'error' }, { status: 500 }),
+      ),
+    )
+    const { result } = renderHook(() => api.endpoints.query.useQuery({}), {
+      wrapper: storeRef.wrapper,
+    })
+
+    await hookWaitFor(() => expect(result.current.isFetching).toBeFalsy())
+    expect(result.current).toEqual(
+      expect.objectContaining({
+        isLoading: false,
+        isError: true,
+        isSuccess: false,
+        error: {
+          status: 500,
+          data: { value: 'error' },
+        },
+      }),
+    )
+  })
+
+  test('success -> error', async () => {
+    server.use(
+      http.get('https://example.com/query', () =>
+        HttpResponse.json({ value: 'success' }),
+      ),
+    )
+    const { result } = renderHook(() => api.endpoints.query.useQuery({}), {
+      wrapper: storeRef.wrapper,
+    })
+
+    await hookWaitFor(() => expect(result.current.isFetching).toBeFalsy())
+    expect(result.current).toEqual(
+      expect.objectContaining({
+        isLoading: false,
+        isError: false,
+        isSuccess: true,
+        data: { value: 'success' },
+      }),
+    )
+
+    server.use(
+      http.get(
+        'https://example.com/query',
+        () => HttpResponse.json({ value: 'error' }, { status: 500 }),
+        { once: true },
+      ),
+    )
+
+    act(() => void result.current.refetch())
+
+    await hookWaitFor(() => expect(result.current.isFetching).toBeFalsy())
+    expect(result.current).toEqual(
+      expect.objectContaining({
+        isLoading: false,
+        isError: true,
+        isSuccess: false,
+        error: {
+          status: 500,
+          data: { value: 'error' },
+        },
+        // last data will stay available
+        data: { value: 'success' },
+      }),
+    )
+  })
+
+  test('error -> success', async () => {
+    server.use(
+      http.get('https://example.com/query', () =>
+        HttpResponse.json({ value: 'success' }),
+      ),
+    )
+    server.use(
+      http.get(
+        'https://example.com/query',
+        () => HttpResponse.json({ value: 'error' }, { status: 500 }),
+        { once: true },
+      ),
+    )
+    const { result } = renderHook(() => api.endpoints.query.useQuery({}), {
+      wrapper: storeRef.wrapper,
+    })
+
+    await hookWaitFor(() => expect(result.current.isFetching).toBeFalsy())
+    expect(result.current).toEqual(
+      expect.objectContaining({
+        isLoading: false,
+        isError: true,
+        isSuccess: false,
+        error: {
+          status: 500,
+          data: { value: 'error' },
+        },
+      }),
+    )
+
+    act(() => void result.current.refetch())
+
+    await hookWaitFor(() => expect(result.current.isFetching).toBeFalsy())
+    expect(result.current).toEqual(
+      expect.objectContaining({
+        isLoading: false,
+        isError: false,
+        isSuccess: true,
+        data: { value: 'success' },
+      }),
+    )
+  })
+})
+
+describe('mutation error handling', () => {
+  test('success', async () => {
+    server.use(
+      http.post('https://example.com/mutation', () =>
+        HttpResponse.json({ value: 'success' }),
+      ),
+    )
+    const { result } = renderHook(() => api.endpoints.mutation.useMutation(), {
+      wrapper: storeRef.wrapper,
+    })
+
+    const [trigger] = result.current
+
+    act(() => void trigger({}))
+
+    await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())
+    expect(result.current[1]).toEqual(
+      expect.objectContaining({
+        isLoading: false,
+        isError: false,
+        isSuccess: true,
+        data: { value: 'success' },
+      }),
+    )
+  })
+
+  test('error', async () => {
+    server.use(
+      http.post('https://example.com/mutation', () =>
+        HttpResponse.json({ value: 'error' }, { status: 500 }),
+      ),
+    )
+    const { result } = renderHook(() => api.endpoints.mutation.useMutation(), {
+      wrapper: storeRef.wrapper,
+    })
+
+    const [trigger] = result.current
+
+    act(() => void trigger({}))
+
+    await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())
+    expect(result.current[1]).toEqual(
+      expect.objectContaining({
+        isLoading: false,
+        isError: true,
+        isSuccess: false,
+        error: {
+          status: 500,
+          data: { value: 'error' },
+        },
+      }),
+    )
+  })
+
+  test('success -> error', async () => {
+    server.use(
+      http.post('https://example.com/mutation', () =>
+        HttpResponse.json({ value: 'success' }),
+      ),
+    )
+    const { result } = renderHook(() => api.endpoints.mutation.useMutation(), {
+      wrapper: storeRef.wrapper,
+    })
+
+    {
+      const [trigger] = result.current
+
+      act(() => void trigger({}))
+
+      await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())
+      expect(result.current[1]).toEqual(
+        expect.objectContaining({
+          isLoading: false,
+          isError: false,
+          isSuccess: true,
+          data: { value: 'success' },
+        }),
+      )
+    }
+
+    server.use(
+      http.post(
+        'https://example.com/mutation',
+        () => HttpResponse.json({ value: 'error' }, { status: 500 }),
+        { once: true },
+      ),
+    )
+
+    {
+      const [trigger] = result.current
+
+      act(() => void trigger({}))
+
+      await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())
+      expect(result.current[1]).toEqual(
+        expect.objectContaining({
+          isLoading: false,
+          isError: true,
+          isSuccess: false,
+          error: {
+            status: 500,
+            data: { value: 'error' },
+          },
+        }),
+      )
+      expect(result.current[1].data).toBeUndefined()
+    }
+  })
+
+  test('error -> success', async () => {
+    server.use(
+      http.post('https://example.com/mutation', () =>
+        HttpResponse.json({ value: 'success' }),
+      ),
+    )
+    server.use(
+      http.post(
+        'https://example.com/mutation',
+        () => HttpResponse.json({ value: 'error' }, { status: 500 }),
+        { once: true },
+      ),
+    )
+
+    const { result } = renderHook(() => api.endpoints.mutation.useMutation(), {
+      wrapper: storeRef.wrapper,
+    })
+
+    {
+      const [trigger] = result.current
+
+      act(() => void trigger({}))
+
+      await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())
+      expect(result.current[1]).toEqual(
+        expect.objectContaining({
+          isLoading: false,
+          isError: true,
+          isSuccess: false,
+          error: {
+            status: 500,
+            data: { value: 'error' },
+          },
+        }),
+      )
+    }
+
+    {
+      const [trigger] = result.current
+
+      act(() => void trigger({}))
+
+      await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())
+      expect(result.current[1]).toEqual(
+        expect.objectContaining({
+          isLoading: false,
+          isError: false,
+          isSuccess: true,
+        }),
+      )
+      expect(result.current[1].error).toBeUndefined()
+    }
+  })
+})
+
+describe('custom axios baseQuery', () => {
+  const axiosBaseQuery =
+    (
+      { baseUrl }: { baseUrl: string } = { baseUrl: '' },
+    ): BaseQueryFn<
+      {
+        url: string
+        method?: AxiosRequestConfig['method']
+        data?: AxiosRequestConfig['data']
+      },
+      unknown,
+      unknown,
+      unknown,
+      { response: AxiosResponse; request: AxiosRequestConfig }
+    > =>
+    async ({ url, method, data }) => {
+      const config = { url: baseUrl + url, method, data }
+      try {
+        const result = await axios(config)
+        return {
+          data: result.data,
+          meta: { request: config, response: result },
+        }
+      } catch (axiosError) {
+        const err = axiosError as AxiosError
+        return {
+          error: {
+            status: err.response?.status,
+            data: err.response?.data,
+          },
+          meta: { request: config, response: err.response as AxiosResponse },
+        }
+      }
+    }
+
+  type SuccessResponse = { value: 'success' }
+  const api = createApi({
+    baseQuery: axiosBaseQuery({
+      baseUrl: 'https://example.com',
+    }),
+    endpoints(build) {
+      return {
+        query: build.query<SuccessResponse, void>({
+          query: () => ({ url: '/success', method: 'get' }),
+          transformResponse: (result: SuccessResponse, meta) => {
+            return { ...result, metaResponseData: meta?.response.data }
+          },
+        }),
+        mutation: build.mutation<SuccessResponse, any>({
+          query: () => ({ url: '/success', method: 'post' }),
+        }),
+      }
+    },
+  })
+
+  const storeRef = setupApiStore(api)
+
+  test('axiosBaseQuery transformResponse uses its custom meta format', async () => {
+    const result = await storeRef.store.dispatch(api.endpoints.query.initiate())
+
+    expect(result.data).toEqual({
+      value: 'success',
+      metaResponseData: { value: 'success' },
+    })
+  })
+
+  test('axios errors behave as expected', async () => {
+    server.use(
+      http.get('https://example.com/success', () =>
+        HttpResponse.json({ value: 'error' }, { status: 500 }),
+      ),
+    )
+    const { result } = renderHook(() => api.endpoints.query.useQuery(), {
+      wrapper: storeRef.wrapper,
+    })
+
+    await hookWaitFor(() => expect(result.current.isFetching).toBeFalsy())
+    expect(result.current).toEqual(
+      expect.objectContaining({
+        isLoading: false,
+        isError: true,
+        isSuccess: false,
+        error: { status: 500, data: { value: 'error' } },
+      }),
+    )
+  })
+})
+
+describe('error handling in a component', () => {
+  const mockErrorResponse = { value: 'error', very: 'mean' }
+  const mockSuccessResponse = { value: 'success' }
+
+  const api = createApi({
+    baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+    endpoints: (build) => ({
+      update: build.mutation<typeof mockSuccessResponse, any>({
+        query: () => ({ url: 'success' }),
+      }),
+      failedUpdate: build.mutation<typeof mockSuccessResponse, any>({
+        query: () => ({ url: 'error' }),
+      }),
+    }),
+  })
+  const storeRef = setupApiStore(api)
+
+  test('a mutation is unwrappable and has the correct types', async () => {
+    server.use(
+      http.get(
+        'https://example.com/success',
+        () => HttpResponse.json(mockErrorResponse, { status: 500 }),
+        { once: true },
+      ),
+    )
+
+    function User() {
+      const [manualError, setManualError] = React.useState<any>()
+      const [update, { isLoading, data, error }] =
+        api.endpoints.update.useMutation()
+
+      return (
+        <div>
+          <div data-testid="isLoading">{String(isLoading)}</div>
+          <div data-testid="data">{JSON.stringify(data)}</div>
+          <div data-testid="error">{JSON.stringify(error)}</div>
+          <div data-testid="manuallySetError">
+            {JSON.stringify(manualError)}
+          </div>
+          <button
+            onClick={() => {
+              update({ name: 'hello' })
+                .unwrap()
+                .then((result) => {
+                  setManualError(undefined)
+                })
+                .catch((error) => act(() => setManualError(error)))
+            }}
+          >
+            Update User
+          </button>
+        </div>
+      )
+    }
+
+    render(<User />, { wrapper: storeRef.wrapper })
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+    fireEvent.click(screen.getByText('Update User'))
+    expect(screen.getByTestId('isLoading').textContent).toBe('true')
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+
+    // Make sure the hook and the unwrapped action return the same things in an error state
+    await waitFor(() =>
+      expect(screen.getByTestId('error').textContent).toEqual(
+        screen.getByTestId('manuallySetError').textContent,
+      ),
+    )
+
+    fireEvent.click(screen.getByText('Update User'))
+    expect(screen.getByTestId('isLoading').textContent).toBe('true')
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('error').textContent).toBeFalsy(),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('manuallySetError').textContent).toBeFalsy(),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('data').textContent).toEqual(
+        JSON.stringify(mockSuccessResponse),
+      ),
+    )
+  })
+
+  for (const track of [true, false]) {
+    test(`an un-subscribed mutation will still return something useful (success case, track: ${track})`, async () => {
+      const hook = renderHook(useDispatch, { wrapper: storeRef.wrapper })
+
+      const dispatch = hook.result.current as ThunkDispatch<
+        any,
+        any,
+        UnknownAction
+      >
+      let mutationqueryFulfilled: ReturnType<
+        ReturnType<typeof api.endpoints.update.initiate>
+      >
+      act(() => {
+        mutationqueryFulfilled = dispatch(
+          api.endpoints.update.initiate({}, { track }),
+        )
+      })
+      const result = await mutationqueryFulfilled!
+      expect(result).toMatchObject({
+        data: { value: 'success' },
+      })
+    })
+
+    test(`an un-subscribed mutation will still return something useful (error case, track: ${track})`, async () => {
+      const hook = renderHook(useDispatch, { wrapper: storeRef.wrapper })
+
+      const dispatch = hook.result.current as ThunkDispatch<
+        any,
+        any,
+        UnknownAction
+      >
+      let mutationqueryFulfilled: ReturnType<
+        ReturnType<typeof api.endpoints.failedUpdate.initiate>
+      >
+      act(() => {
+        mutationqueryFulfilled = dispatch(
+          api.endpoints.failedUpdate.initiate({}, { track }),
+        )
+      })
+      const result = await mutationqueryFulfilled!
+      expect(result).toMatchObject({
+        error: {
+          status: 500,
+          data: { value: 'error' },
+        },
+      })
+    })
+    test(`an un-subscribed mutation will still be unwrappable (success case), track: ${track}`, async () => {
+      const hook = renderHook(useDispatch, { wrapper: storeRef.wrapper })
+
+      const dispatch = hook.result.current as ThunkDispatch<
+        any,
+        any,
+        UnknownAction
+      >
+      let mutationqueryFulfilled: ReturnType<
+        ReturnType<typeof api.endpoints.update.initiate>
+      >
+      act(() => {
+        mutationqueryFulfilled = dispatch(
+          api.endpoints.update.initiate({}, { track }),
+        )
+      })
+      const result = await mutationqueryFulfilled!.unwrap()
+      expect(result).toMatchObject({
+        value: 'success',
+      })
+    })
+
+    test(`an un-subscribed mutation will still be unwrappable (error case, track: ${track})`, async () => {
+      const hook = renderHook(useDispatch, { wrapper: storeRef.wrapper })
+
+      const dispatch = hook.result.current as ThunkDispatch<
+        any,
+        any,
+        UnknownAction
+      >
+      let mutationqueryFulfilled: ReturnType<
+        ReturnType<typeof api.endpoints.failedUpdate.initiate>
+      >
+      act(() => {
+        mutationqueryFulfilled = dispatch(
+          api.endpoints.failedUpdate.initiate({}, { track }),
+        )
+      })
+      const unwrappedPromise = mutationqueryFulfilled!.unwrap()
+      await expect(unwrappedPromise).rejects.toMatchObject({
+        status: 500,
+        data: { value: 'error' },
+      })
+    })
+  }
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/fakeBaseQuery.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/fakeBaseQuery.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/fakeBaseQuery.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,148 @@
+import { noop } from '@internal/listenerMiddleware/utils'
+import { configureStore } from '@reduxjs/toolkit'
+import { createApi, fakeBaseQuery } from '@reduxjs/toolkit/query'
+
+type CustomErrorType = { type: 'Custom' }
+
+const api = createApi({
+  baseQuery: fakeBaseQuery<CustomErrorType>(),
+  endpoints: (build) => ({
+    withQuery: build.query<string, string>({
+      // @ts-expect-error
+      query(arg: string) {
+        return `resultFrom(${arg})`
+      },
+      // @ts-expect-error
+      transformResponse(response) {
+        return response.wrappedByBaseQuery
+      },
+    }),
+    withQueryFn: build.query<string, string>({
+      queryFn(arg: string) {
+        return { data: `resultFrom(${arg})` }
+      },
+    }),
+    withInvalidDataQueryFn: build.query<string, string>({
+      // @ts-expect-error
+      queryFn(arg: string) {
+        return { data: 5 }
+      },
+    }),
+    withErrorQueryFn: build.query<string, string>({
+      queryFn(arg: string) {
+        return { error: { type: 'Custom' } }
+      },
+    }),
+    withInvalidErrorQueryFn: build.query<string, string>({
+      // @ts-expect-error
+      queryFn(arg: string) {
+        return { error: 5 }
+      },
+    }),
+    withAsyncQueryFn: build.query<string, string>({
+      async queryFn(arg: string) {
+        return { data: `resultFrom(${arg})` }
+      },
+    }),
+    withInvalidDataAsyncQueryFn: build.query<string, string>({
+      // @ts-expect-error
+      async queryFn(arg: string) {
+        return { data: 5 }
+      },
+    }),
+    withAsyncErrorQueryFn: build.query<string, string>({
+      async queryFn(arg: string) {
+        return { error: { type: 'Custom' } }
+      },
+    }),
+    withInvalidAsyncErrorQueryFn: build.query<string, string>({
+      // @ts-expect-error
+      async queryFn(arg: string) {
+        return { error: 5 }
+      },
+    }),
+
+    mutationWithQueryFn: build.mutation<string, string>({
+      queryFn(arg: string) {
+        return { data: `resultFrom(${arg})` }
+      },
+    }),
+    mutationWithInvalidDataQueryFn: build.mutation<string, string>({
+      // @ts-expect-error
+      queryFn(arg: string) {
+        return { data: 5 }
+      },
+    }),
+    mutationWithErrorQueryFn: build.mutation<string, string>({
+      queryFn(arg: string) {
+        return { error: { type: 'Custom' } }
+      },
+    }),
+    mutationWithInvalidErrorQueryFn: build.mutation<string, string>({
+      // @ts-expect-error
+      queryFn(arg: string) {
+        return { error: 5 }
+      },
+    }),
+
+    mutationWithAsyncQueryFn: build.mutation<string, string>({
+      async queryFn(arg: string) {
+        return { data: `resultFrom(${arg})` }
+      },
+    }),
+    mutationWithInvalidAsyncQueryFn: build.mutation<string, string>({
+      // @ts-expect-error
+      async queryFn(arg: string) {
+        return { data: 5 }
+      },
+    }),
+    mutationWithAsyncErrorQueryFn: build.mutation<string, string>({
+      async queryFn(arg: string) {
+        return { error: { type: 'Custom' } }
+      },
+    }),
+    mutationWithInvalidAsyncErrorQueryFn: build.mutation<string, string>({
+      // @ts-expect-error
+      async queryFn(arg: string) {
+        return { error: 5 }
+      },
+    }),
+    // @ts-expect-error
+    withNeither: build.query<string, string>({}),
+    // @ts-expect-error
+    mutationWithNeither: build.mutation<string, string>({}),
+  }),
+})
+
+const store = configureStore({
+  reducer: {
+    [api.reducerPath]: api.reducer,
+  },
+  middleware: (gDM) => gDM({}).concat(api.middleware),
+})
+
+test('fakeBaseQuery throws when invoking query', async () => {
+  const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
+
+  const thunk = api.endpoints.withQuery.initiate('')
+
+  const result = await store.dispatch(thunk)
+
+  expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+  expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+    `An unhandled error occurred processing a request for the endpoint "withQuery".\nIn the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+    Error(
+      'When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.',
+    ),
+  )
+
+  expect(result!.error).toEqual({
+    message:
+      'When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.',
+    name: 'Error',
+    stack: expect.any(String),
+  })
+
+  consoleErrorSpy.mockRestore()
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/fetchBaseQuery.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/fetchBaseQuery.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/fetchBaseQuery.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1545 @@
+import { createSlice } from '@reduxjs/toolkit'
+import type { FetchArgs } from '@reduxjs/toolkit/query'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+import { headersToObject } from 'headers-polyfill'
+import { HttpResponse, delay, http } from 'msw'
+import nodeFetch from 'node-fetch'
+import queryString from 'query-string'
+import { vi } from 'vitest'
+import { setupApiStore } from '../../tests/utils/helpers'
+import type { BaseQueryApi } from '../baseQueryTypes'
+import { server } from './mocks/server'
+
+const defaultHeaders: Record<string, string> = {
+  fake: 'header',
+  delete: 'true',
+  delete2: '1',
+}
+
+const baseUrl = 'https://example.com'
+
+const baseQuery = fetchBaseQuery({
+  baseUrl,
+  prepareHeaders: (headers, { getState }) => {
+    const { token } = (getState() as RootState).auth
+
+    // If we have a token set in state, let's assume that we should be passing it.
+    if (token) {
+      headers.set('authorization', `Bearer ${token}`)
+    }
+    // A user could customize their behavior here, so we'll just test that custom scenarios would work.
+    const potentiallyConflictingKeys = Object.keys(defaultHeaders)
+    potentiallyConflictingKeys.forEach((key) => {
+      // Check for presence of a default key, if the incoming endpoint headers don't specify it as '', then set it
+      const existingValue = headers.get(key)
+      if (!existingValue && existingValue !== '') {
+        headers.set(key, String(defaultHeaders[key]))
+        // If an endpoint sets a header with a value of '', just delete the header.
+      } else if (headers.get(key) === '') {
+        headers.delete(key)
+      }
+    })
+
+    return headers
+  },
+})
+
+const api = createApi({
+  baseQuery,
+  endpoints(build) {
+    return {
+      query: build.query({ query: () => ({ url: '/echo', headers: {} }) }),
+      mutation: build.mutation({
+        query: () => ({ url: '/echo', method: 'POST', credentials: 'omit' }),
+      }),
+    }
+  },
+})
+
+const authSlice = createSlice({
+  name: 'auth',
+  initialState: {
+    token: '',
+  },
+  reducers: {
+    setToken(state, action) {
+      state.token = action.payload
+    },
+  },
+})
+
+const storeRef = setupApiStore(api, { auth: authSlice.reducer })
+type RootState = ReturnType<typeof storeRef.store.getState>
+
+let commonBaseQueryApi: BaseQueryApi = {} as any
+beforeEach(() => {
+  let abortController = new AbortController()
+  commonBaseQueryApi = {
+    signal: abortController.signal,
+    abort: (reason) =>
+      // @ts-ignore
+      abortController.abort(reason),
+    dispatch: storeRef.store.dispatch,
+    getState: storeRef.store.getState,
+    extra: undefined,
+    type: 'query',
+    endpoint: 'doesntmatterhere',
+  }
+})
+
+describe('fetchBaseQuery', () => {
+  describe('basic functionality', () => {
+    it('should return an object for a simple GET request when it is json data', async () => {
+      const req = baseQuery('/success', commonBaseQueryApi, {})
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.data).toEqual({ value: 'success' })
+    })
+
+    it('should return undefined for a simple GET request when the response is empty', async () => {
+      const req = baseQuery('/empty', commonBaseQueryApi, {})
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.meta?.request).toBeInstanceOf(Request)
+      expect(res.meta?.response).toBeInstanceOf(Object)
+
+      expect(res.data).toBeNull()
+    })
+
+    it('should return an error and status for error responses', async () => {
+      const req = baseQuery('/error', commonBaseQueryApi, {})
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.meta?.request).toBeInstanceOf(Request)
+      expect(res.meta?.response).toBeInstanceOf(Object)
+      expect(res.error).toEqual({
+        status: 500,
+        data: { value: 'error' },
+      })
+    })
+
+    it('should handle a connection loss semi-gracefully', async () => {
+      const fetchFn = vi
+        .fn()
+        .mockRejectedValueOnce(new TypeError('Failed to fetch'))
+
+      const req = fetchBaseQuery({
+        baseUrl,
+        fetchFn,
+      })('/success', commonBaseQueryApi, {})
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.meta?.request).toBeInstanceOf(Request)
+      expect(res.meta?.response).toBe(undefined)
+      expect(res.error).toEqual({
+        status: 'FETCH_ERROR',
+        error: 'TypeError: Failed to fetch',
+      })
+    })
+  })
+
+  describe('non-JSON-body', () => {
+    it('success: should return data ("text" responseHandler)', async () => {
+      server.use(
+        http.get(
+          'https://example.com/success',
+          () => HttpResponse.text(`this is not json!`),
+          { once: true },
+        ),
+      )
+
+      const req = baseQuery(
+        { url: '/success', responseHandler: 'text' },
+        commonBaseQueryApi,
+        {},
+      )
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.meta?.request).toBeInstanceOf(Request)
+      expect(res.meta?.response).toBeInstanceOf(Object)
+      expect(res.data).toEqual(`this is not json!`)
+    })
+
+    it('success: should fail gracefully (default="json" responseHandler)', async () => {
+      server.use(
+        http.get(
+          'https://example.com/success',
+          () => HttpResponse.text(`this is not json!`),
+          { once: true },
+        ),
+      )
+
+      const req = baseQuery('/success', commonBaseQueryApi, {})
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.meta?.request).toBeInstanceOf(Request)
+      expect(res.meta?.response).toBeInstanceOf(Object)
+      expect(res.error).toEqual({
+        status: 'PARSING_ERROR',
+        error: expect.stringMatching(/SyntaxError: Unexpected token/),
+        originalStatus: 200,
+        data: `this is not json!`,
+      })
+    })
+
+    it('success: parse text without error ("content-type" responseHandler)', async () => {
+      server.use(
+        http.get(
+          'https://example.com/success',
+          () => HttpResponse.text(`this is not json!`),
+          { once: true },
+        ),
+      )
+
+      const req = baseQuery(
+        {
+          url: '/success',
+          responseHandler: 'content-type',
+        },
+        commonBaseQueryApi,
+        {},
+      )
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.meta?.response?.headers.get('content-type')).toEqual(
+        'text/plain',
+      )
+      expect(res.meta?.request).toBeInstanceOf(Request)
+      expect(res.meta?.response).toBeInstanceOf(Object)
+      expect(res.data).toEqual(`this is not json!`)
+    })
+
+    it('success: parse json without error ("content-type" responseHandler)', async () => {
+      server.use(
+        http.get(
+          'https://example.com/success',
+          () => HttpResponse.json(`this will become json!`),
+          { once: true },
+        ),
+      )
+
+      const req = baseQuery(
+        {
+          url: '/success',
+          responseHandler: 'content-type',
+        },
+        commonBaseQueryApi,
+        {},
+      )
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.meta?.response?.headers.get('content-type')).toEqual(
+        'application/json',
+      )
+      expect(res.meta?.request).toBeInstanceOf(Request)
+      expect(res.meta?.response).toBeInstanceOf(Object)
+      expect(res.data).toEqual(`this will become json!`)
+    })
+
+    it('server error: should fail normally with a 500 status ("text" responseHandler)', async () => {
+      server.use(
+        http.get('https://example.com/error', () =>
+          HttpResponse.text(`this is not json!`, { status: 500 }),
+        ),
+      )
+
+      const req = baseQuery(
+        { url: '/error', responseHandler: 'text' },
+        commonBaseQueryApi,
+        {},
+      )
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.meta?.request).toBeInstanceOf(Request)
+      expect(res.meta?.response).toBeInstanceOf(Object)
+      expect(res.error).toEqual({
+        status: 500,
+        data: `this is not json!`,
+      })
+    })
+
+    it('server error: should fail normally with a 500 status as text ("content-type" responseHandler)', async () => {
+      const serverResponse = 'Internal Server Error'
+      server.use(
+        http.get('https://example.com/error', () =>
+          HttpResponse.text(serverResponse, { status: 500 }),
+        ),
+      )
+
+      const req = baseQuery(
+        { url: '/error', responseHandler: 'content-type' },
+        commonBaseQueryApi,
+        {},
+      )
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.meta?.request).toBeInstanceOf(Request)
+      expect(res.meta?.response).toBeInstanceOf(Object)
+      expect(res.meta?.response?.headers.get('content-type')).toEqual(
+        'text/plain',
+      )
+      expect(res.error).toEqual({
+        status: 500,
+        data: serverResponse,
+      })
+    })
+
+    it('server error: should fail normally with a 500 status as json ("content-type" responseHandler)', async () => {
+      const serverResponse = {
+        errors: { field1: "Password cannot be 'password'" },
+      }
+      server.use(
+        http.get('https://example.com/error', () =>
+          HttpResponse.json(serverResponse, { status: 500 }),
+        ),
+      )
+
+      const req = baseQuery(
+        { url: '/error', responseHandler: 'content-type' },
+        commonBaseQueryApi,
+        {},
+      )
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.meta?.request).toBeInstanceOf(Request)
+      expect(res.meta?.response).toBeInstanceOf(Object)
+      expect(res.meta?.response?.headers.get('content-type')).toEqual(
+        'application/json',
+      )
+      expect(res.error).toEqual({
+        status: 500,
+        data: serverResponse,
+      })
+    })
+
+    it('server error: should fail gracefully (default="json" responseHandler)', async () => {
+      server.use(
+        http.get('https://example.com/error', () =>
+          HttpResponse.text(`this is not json!`, { status: 500 }),
+        ),
+      )
+
+      const req = baseQuery('/error', commonBaseQueryApi, {})
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.meta?.request).toBeInstanceOf(Request)
+      expect(res.meta?.response).toBeInstanceOf(Object)
+      expect(res.error).toEqual({
+        status: 'PARSING_ERROR',
+        error: expect.stringMatching(/SyntaxError: Unexpected token/),
+        originalStatus: 500,
+        data: `this is not json!`,
+      })
+    })
+  })
+
+  describe('arg.body', () => {
+    test('an object provided to body will be serialized when content-type is json', async () => {
+      const data = {
+        test: 'value',
+      }
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        { url: '/echo', body: data, method: 'POST' },
+        { ...commonBaseQueryApi, type: 'mutation' },
+        {},
+      ))
+
+      expect(request.headers['content-type']).toBe('application/json')
+      expect(request.body).toEqual(data)
+    })
+
+    test('an array provided to body will be serialized when content-type is json', async () => {
+      const data = ['test', 'value']
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        { url: '/echo', body: data, method: 'POST' },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.headers['content-type']).toBe('application/json')
+      expect(request.body).toEqual(data)
+    })
+
+    test('an object provided to body will not be serialized when content-type is not json', async () => {
+      const data = {
+        test: 'value',
+      }
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        {
+          url: '/echo',
+          body: data,
+          method: 'POST',
+          headers: { 'content-type': 'text/html' },
+        },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.headers['content-type']).toBe('text/html')
+      expect(request.body).toEqual('[object Object]')
+    })
+
+    test('an array provided to body will not be serialized when content-type is not json', async () => {
+      const data = ['test', 'value']
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        {
+          url: '/echo',
+          body: data,
+          method: 'POST',
+          headers: { 'content-type': 'text/html' },
+        },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.headers['content-type']).toBe('text/html')
+      expect(request.body).toEqual(data.join(','))
+    })
+
+    it('supports a custom jsonContentType', async () => {
+      const baseQuery = fetchBaseQuery({
+        baseUrl,
+        jsonContentType: 'application/vnd.api+json',
+      })
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        {
+          url: '/echo',
+          body: {},
+          method: 'POST',
+        },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.headers['content-type']).toBe('application/vnd.api+json')
+    })
+
+    it('supports a custom jsonReplacer', async () => {
+      const body = {
+        items: new Set(['A', 'B', 'C']),
+      }
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        {
+          url: '/echo',
+          body,
+          method: 'POST',
+        },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.headers['content-type']).toBe('application/json')
+      expect(request.body).toEqual({ items: {} }) // Set is not properly marshalled by default
+
+      // Use jsonReplacer
+      const baseQueryWithReplacer = fetchBaseQuery({
+        baseUrl,
+        jsonReplacer: (key, value) =>
+          value instanceof Set ? [...value] : value,
+      })
+
+      ;({ data: request } = await baseQueryWithReplacer(
+        {
+          url: '/echo',
+          body,
+          method: 'POST',
+        },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.headers['content-type']).toBe('application/json')
+      expect(request.body).toEqual({ items: ['A', 'B', 'C'] }) // Set is marshalled correctly by jsonReplacer
+    })
+  })
+
+  describe('arg.params', () => {
+    it('should not serialize missing params', async () => {
+      let request: any
+      ;({ data: request } = await baseQuery(
+        { url: '/echo' },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.url).toEqual(`${baseUrl}/echo`)
+    })
+
+    it('should serialize numeric and boolean params', async () => {
+      const params = { a: 1, b: true }
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        { url: '/echo', params },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.url).toEqual(`${baseUrl}/echo?a=1&b=true`)
+    })
+
+    it('should merge params into existing url querystring', async () => {
+      const params = { a: 1, b: true }
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        { url: '/echo?banana=pudding', params },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.url).toEqual(`${baseUrl}/echo?banana=pudding&a=1&b=true`)
+    })
+
+    it('should accept a URLSearchParams instance', async () => {
+      const params = new URLSearchParams({ apple: 'fruit' })
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        { url: '/echo', params },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.url).toEqual(`${baseUrl}/echo?apple=fruit`)
+    })
+
+    it('should strip undefined values from the end params', async () => {
+      const params = { apple: 'fruit', banana: undefined, randy: null }
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        { url: '/echo', params },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.url).toEqual(`${baseUrl}/echo?apple=fruit&randy=null`)
+    })
+
+    it('should support a paramsSerializer', async () => {
+      const baseQuery = fetchBaseQuery({
+        baseUrl,
+        paramsSerializer: (params: Record<string, unknown>) =>
+          queryString.stringify(params, { arrayFormat: 'bracket' }),
+      })
+
+      const api = createApi({
+        baseQuery,
+        endpoints(build) {
+          return {
+            query: build.query({
+              query: () => ({ url: '/echo', headers: {} }),
+            }),
+            mutation: build.mutation({
+              query: () => ({
+                url: '/echo',
+                method: 'POST',
+                credentials: 'omit',
+              }),
+            }),
+          }
+        },
+      })
+
+      const params = {
+        someArray: ['a', 'b', 'c'],
+      }
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        { url: '/echo', params },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.url).toEqual(
+        `${baseUrl}/echo?someArray[]=a&someArray[]=b&someArray[]=c`,
+      )
+    })
+
+    it('should supports a custom isJsonContentType function', async () => {
+      const testBody = {
+        i_should_be_stringified: true,
+      }
+      const baseQuery = fetchBaseQuery({
+        baseUrl,
+        isJsonContentType: (headers) =>
+          [
+            'application/vnd.api+json',
+            'application/json',
+            'application/vnd.hal+json',
+          ].includes(headers.get('content-type') ?? ''),
+      })
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        {
+          url: '/echo',
+          method: 'POST',
+          body: testBody,
+          headers: { 'content-type': 'application/vnd.hal+json' },
+        },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.body).toMatchObject(testBody)
+    })
+  })
+
+  describe('validateStatus', () => {
+    test('validateStatus can return an error even on normal 200 responses', async () => {
+      // This is a scenario where an API may always return a 200, but indicates there is an error when success = false
+      const res = await baseQuery(
+        {
+          url: '/nonstandard-error',
+          validateStatus: (response, body) =>
+            response.status === 200 && body.success === false ? false : true,
+        },
+        commonBaseQueryApi,
+        {},
+      )
+
+      expect(res.error).toEqual({
+        status: 200,
+        data: {
+          success: false,
+          message: 'This returns a 200 but is really an error',
+        },
+      })
+    })
+  })
+
+  describe('arg.headers and prepareHeaders', () => {
+    test('uses the default headers set in prepareHeaders', async () => {
+      let request: any
+      ;({ data: request } = await baseQuery(
+        { url: '/echo' },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.headers['fake']).toBe(defaultHeaders['fake'])
+      expect(request.headers['delete']).toBe(defaultHeaders['delete'])
+      expect(request.headers['delete2']).toBe(defaultHeaders['delete2'])
+    })
+
+    test('adds endpoint-level headers to the defaults', async () => {
+      let request: any
+      ;({ data: request } = await baseQuery(
+        { url: '/echo', headers: { authorization: 'Bearer banana' } },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.headers['authorization']).toBe('Bearer banana')
+      expect(request.headers['fake']).toBe(defaultHeaders['fake'])
+      expect(request.headers['delete']).toBe(defaultHeaders['delete'])
+      expect(request.headers['delete2']).toBe(defaultHeaders['delete2'])
+    })
+
+    test('it does not set application/json when content-type is set', async () => {
+      let request: any
+      ;({ data: request } = await baseQuery(
+        {
+          url: '/echo',
+          headers: {
+            authorization: 'Bearer banana',
+            'content-type': 'custom-content-type',
+          },
+        },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.headers['authorization']).toBe('Bearer banana')
+      expect(request.headers['content-type']).toBe('custom-content-type')
+      expect(request.headers['fake']).toBe(defaultHeaders['fake'])
+      expect(request.headers['delete']).toBe(defaultHeaders['delete'])
+      expect(request.headers['delete2']).toBe(defaultHeaders['delete2'])
+    })
+
+    test('respects the headers from an endpoint over the base headers', async () => {
+      const fake = 'fake endpoint value'
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        { url: '/echo', headers: { fake, delete: '', delete2: '' } },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.headers['fake']).toBe(fake)
+      expect(request.headers['delete']).toBeUndefined()
+      expect(request.headers['delete2']).toBeUndefined()
+    })
+
+    test('prepareHeaders can return undefined', async () => {
+      let request: any
+
+      const token = 'accessToken'
+
+      const _baseQuery = fetchBaseQuery({
+        baseUrl,
+        prepareHeaders: (headers) => {
+          headers.set('authorization', `Bearer ${token}`)
+        },
+      })
+
+      const doRequest = async () =>
+        _baseQuery({ url: '/echo' }, commonBaseQueryApi, {})
+
+      ;({ data: request } = await doRequest())
+
+      expect(request.headers['authorization']).toBe(`Bearer ${token}`)
+    })
+
+    test('prepareHeaders is able to be an async function', async () => {
+      let request: any
+
+      const token = 'accessToken'
+      const getAccessTokenAsync = async () => token
+
+      const _baseQuery = fetchBaseQuery({
+        baseUrl,
+        prepareHeaders: async (headers) => {
+          headers.set('authorization', `Bearer ${await getAccessTokenAsync()}`)
+          return headers
+        },
+      })
+
+      const doRequest = async () =>
+        _baseQuery({ url: '/echo' }, commonBaseQueryApi, {})
+
+      ;({ data: request } = await doRequest())
+
+      expect(request.headers['authorization']).toBe(`Bearer ${token}`)
+    })
+
+    test('prepareHeaders is able to be an async function returning undefined', async () => {
+      let request: any
+
+      const token = 'accessToken'
+      const getAccessTokenAsync = async () => token
+
+      const _baseQuery = fetchBaseQuery({
+        baseUrl,
+        prepareHeaders: async (headers) => {
+          headers.set('authorization', `Bearer ${await getAccessTokenAsync()}`)
+        },
+      })
+
+      const doRequest = async () =>
+        _baseQuery({ url: '/echo' }, commonBaseQueryApi, {})
+
+      ;({ data: request } = await doRequest())
+
+      expect(request.headers['authorization']).toBe(`Bearer ${token}`)
+    })
+
+    test('prepareHeaders is able to select from a state', async () => {
+      let request: any
+
+      const doRequest = async () => {
+        const abortController = new AbortController()
+        return baseQuery(
+          { url: '/echo' },
+          {
+            signal: abortController.signal,
+            abort: (reason) =>
+              // @ts-ignore
+              abortController.abort(reason),
+            dispatch: storeRef.store.dispatch,
+            getState: storeRef.store.getState,
+            extra: undefined,
+            type: 'query',
+            endpoint: '',
+          },
+          {},
+        )
+      }
+
+      ;({ data: request } = await doRequest())
+
+      expect(request.headers['authorization']).toBeUndefined()
+
+      // Set a token and the follow up request should have the header injected by prepareHeaders
+      const token = 'fakeToken!'
+      storeRef.store.dispatch(authSlice.actions.setToken(token))
+      ;({ data: request } = await doRequest())
+
+      expect(request.headers['authorization']).toBe(`Bearer ${token}`)
+    })
+
+    test('prepareHeaders provides extra api information for getState, extra, endpoint, type and forced', async () => {
+      let _getState, _arg: any, _extra, _endpoint, _type, _forced
+
+      const baseQuery = fetchBaseQuery({
+        baseUrl,
+        prepareHeaders: (
+          headers,
+          { getState, arg, extra, endpoint, type, forced },
+        ) => {
+          _getState = getState
+          _arg = arg
+          _endpoint = endpoint
+          _type = type
+          _forced = forced
+          _extra = extra
+
+          return headers
+        },
+      })
+
+      const fakeAuth0Client = {
+        getTokenSilently: async () => 'fakeToken',
+      }
+
+      const doRequest = async () => {
+        const abortController = new AbortController()
+        return baseQuery(
+          { url: '/echo' },
+          {
+            signal: abortController.signal,
+            abort: (reason) =>
+              // @ts-ignore
+              abortController.abort(reason),
+            dispatch: storeRef.store.dispatch,
+            getState: storeRef.store.getState,
+            extra: fakeAuth0Client,
+            type: 'query',
+            forced: true,
+            endpoint: 'someEndpointName',
+          },
+          {},
+        )
+      }
+
+      await doRequest()
+
+      expect(_getState).toBeDefined()
+      expect(_arg!.url).toBe('/echo')
+      expect(_endpoint).toBe('someEndpointName')
+      expect(_type).toBe('query')
+      expect(_forced).toBe(true)
+      expect(_extra).toBe(fakeAuth0Client)
+    })
+
+    test('can be instantiated with a `ExtraOptions` generic and `extraOptions` will be available in `prepareHeaders', async () => {
+      const prepare = vitest.fn()
+      const baseQuery = fetchBaseQuery({
+        prepareHeaders(headers, api) {
+          expectTypeOf(api.extraOptions).toEqualTypeOf<unknown>()
+          prepare.apply(undefined, arguments as unknown as any[])
+        },
+      })
+      baseQuery('https://example.com', commonBaseQueryApi, {
+        foo: 'baz',
+        bar: 5,
+      })
+      expect(prepare).toHaveBeenCalledWith(
+        expect.anything(),
+        expect.objectContaining({ extraOptions: { foo: 'baz', bar: 5 } }),
+      )
+
+      // ensure types
+      createApi({
+        baseQuery,
+        endpoints(build) {
+          return {
+            testQuery: build.query({
+              query: () => ({ url: '/echo', headers: {} }),
+              extraOptions: {
+                foo: 'asd',
+                bar: 1,
+              },
+            }),
+            testMutation: build.mutation({
+              query: () => ({
+                url: '/echo',
+                method: 'POST',
+                credentials: 'omit',
+              }),
+              extraOptions: {
+                foo: 'qwe',
+                bar: 15,
+              },
+            }),
+          }
+        },
+      })
+    })
+  })
+
+  test('can pass `headers` into `fetchBaseQuery`', async () => {
+    let request: any
+
+    const token = 'accessToken'
+
+    const _baseQuery = fetchBaseQuery({
+      baseUrl,
+      headers: { authorization: `Bearer ${token}` },
+    })
+
+    const doRequest = async () =>
+      _baseQuery({ url: '/echo' }, commonBaseQueryApi, {})
+
+    ;({ data: request } = await doRequest())
+
+    expect(request.headers['authorization']).toBe(`Bearer ${token}`)
+  })
+
+  test('lets a header be undefined', async () => {
+    let request: any
+    ;({ data: request } = await baseQuery(
+      { url: '/echo', headers: undefined },
+      commonBaseQueryApi,
+      {},
+    ))
+
+    expect(request.headers['fake']).toBe(defaultHeaders['fake'])
+    expect(request.headers['delete']).toBe(defaultHeaders['delete'])
+    expect(request.headers['delete2']).toBe(defaultHeaders['delete2'])
+  })
+
+  test('allows for possibly undefined header key/values', async () => {
+    const banana = '1' as '1' | undefined
+    let request: any
+    ;({ data: request } = await baseQuery(
+      { url: '/echo', headers: { banana } },
+      commonBaseQueryApi,
+      {},
+    ))
+
+    expect(request.headers['banana']).toBe('1')
+    expect(request.headers['fake']).toBe(defaultHeaders['fake'])
+    expect(request.headers['delete']).toBe(defaultHeaders['delete'])
+    expect(request.headers['delete2']).toBe(defaultHeaders['delete2'])
+  })
+
+  test('strips undefined values from the headers', async () => {
+    const banana = undefined as '1' | undefined
+    let request: any
+    ;({ data: request } = await baseQuery(
+      { url: '/echo', headers: { banana } },
+      commonBaseQueryApi,
+      {},
+    ))
+
+    expect(request.headers['banana']).toBeUndefined()
+    expect(request.headers['fake']).toBe(defaultHeaders['fake'])
+    expect(request.headers['delete']).toBe(defaultHeaders['delete'])
+    expect(request.headers['delete2']).toBe(defaultHeaders['delete2'])
+  })
+
+  describe('Accepts global arguments', () => {
+    test('Global responseHandler', async () => {
+      server.use(
+        http.get(
+          'https://example.com/success',
+          () => HttpResponse.text(`this is not json!`),
+          { once: true },
+        ),
+      )
+
+      const globalizedBaseQuery = fetchBaseQuery({
+        baseUrl,
+        responseHandler: 'text',
+      })
+
+      const req = globalizedBaseQuery(
+        { url: '/success' },
+        commonBaseQueryApi,
+        {},
+      )
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.meta?.request).toBeInstanceOf(Request)
+      expect(res.meta?.response).toBeInstanceOf(Object)
+      expect(res.error).toBeUndefined()
+      expect(res.data).toEqual(`this is not json!`)
+    })
+
+    test('Global responseHandler: content-type with text response', async () => {
+      server.use(
+        http.get(
+          'https://example.com/success',
+          () => HttpResponse.text(`this is plain text!`),
+          { once: true },
+        ),
+      )
+
+      const globalizedBaseQuery = fetchBaseQuery({
+        baseUrl,
+        responseHandler: 'content-type',
+      })
+
+      const res = await globalizedBaseQuery(
+        { url: '/success' },
+        commonBaseQueryApi,
+        {},
+      )
+
+      expect(res.error).toBeUndefined()
+      expect(res.data).toEqual(`this is plain text!`)
+      expect(res.meta?.response?.headers.get('content-type')).toEqual(
+        'text/plain',
+      )
+    })
+
+    test('Global responseHandler: content-type with JSON response', async () => {
+      server.use(
+        http.get(
+          'https://example.com/success',
+          () => HttpResponse.json({ message: 'this is json!' }),
+          { once: true },
+        ),
+      )
+
+      const globalizedBaseQuery = fetchBaseQuery({
+        baseUrl,
+        responseHandler: 'content-type',
+      })
+
+      const res = await globalizedBaseQuery(
+        { url: '/success' },
+        commonBaseQueryApi,
+        {},
+      )
+
+      expect(res.error).toBeUndefined()
+      expect(res.data).toEqual({ message: 'this is json!' })
+      expect(res.meta?.response?.headers.get('content-type')).toEqual(
+        'application/json',
+      )
+    })
+
+    test('Global responseHandler: content-type can be overridden at endpoint level', async () => {
+      server.use(
+        http.get(
+          'https://example.com/success',
+          () => HttpResponse.text(`this is text but will be parsed as json`),
+          { once: true },
+        ),
+      )
+
+      const globalizedBaseQuery = fetchBaseQuery({
+        baseUrl,
+        responseHandler: 'content-type',
+      })
+
+      // Override global content-type handler with explicit text handler
+      const res = await globalizedBaseQuery(
+        { url: '/success', responseHandler: 'text' },
+        commonBaseQueryApi,
+        {},
+      )
+
+      expect(res.error).toBeUndefined()
+      expect(res.data).toEqual(`this is text but will be parsed as json`)
+    })
+
+    test('Global responseHandler: content-type with error response (text)', async () => {
+      const errorMessage = 'Internal Server Error'
+      server.use(
+        http.get('https://example.com/error', () =>
+          HttpResponse.text(errorMessage, { status: 500 }),
+        ),
+      )
+
+      const globalizedBaseQuery = fetchBaseQuery({
+        baseUrl,
+        responseHandler: 'content-type',
+      })
+
+      const res = await globalizedBaseQuery(
+        { url: '/error' },
+        commonBaseQueryApi,
+        {},
+      )
+
+      expect(res.error).toEqual({
+        status: 500,
+        data: errorMessage,
+      })
+      expect(res.meta?.response?.headers.get('content-type')).toEqual(
+        'text/plain',
+      )
+    })
+
+    test('Global responseHandler: content-type with error response (JSON)', async () => {
+      const errorData = { error: 'Something went wrong', code: 'ERR_500' }
+      server.use(
+        http.get('https://example.com/error', () =>
+          HttpResponse.json(errorData, { status: 500 }),
+        ),
+      )
+
+      const globalizedBaseQuery = fetchBaseQuery({
+        baseUrl,
+        responseHandler: 'content-type',
+      })
+
+      const res = await globalizedBaseQuery(
+        { url: '/error' },
+        commonBaseQueryApi,
+        {},
+      )
+
+      expect(res.error).toEqual({
+        status: 500,
+        data: errorData,
+      })
+      expect(res.meta?.response?.headers.get('content-type')).toEqual(
+        'application/json',
+      )
+    })
+
+    test('Global validateStatus', async () => {
+      const globalizedBaseQuery = fetchBaseQuery({
+        baseUrl,
+        validateStatus: (response, body) =>
+          response.status === 200 && body.success === false ? false : true,
+      })
+
+      // This is a scenario where an API may always return a 200, but indicates there is an error when success = false
+      const res = await globalizedBaseQuery(
+        {
+          url: '/nonstandard-error',
+        },
+        commonBaseQueryApi,
+        {},
+      )
+
+      expect(res.error).toEqual({
+        status: 200,
+        data: {
+          success: false,
+          message: 'This returns a 200 but is really an error',
+        },
+      })
+    })
+
+    test('Global timeout', async () => {
+      server.use(
+        http.get(
+          'https://example.com/empty1',
+          async ({ request, cookies, params, requestId }) => {
+            await delay(300)
+
+            return HttpResponse.json({
+              ...request,
+              cookies,
+              params,
+              requestId,
+              url: new URL(request.url),
+              headers: headersToObject(request.headers),
+            })
+          },
+          { once: true },
+        ),
+      )
+
+      const globalizedBaseQuery = fetchBaseQuery({
+        baseUrl,
+        timeout: 200,
+      })
+
+      const result = await globalizedBaseQuery(
+        { url: '/empty1' },
+        commonBaseQueryApi,
+        {},
+      )
+
+      expect(result?.error).toEqual({
+        status: 'TIMEOUT_ERROR',
+        error: expect.stringMatching(/^TimeoutError/),
+      })
+    })
+  })
+})
+
+describe('fetchFn', () => {
+  test('accepts a custom fetchFn', async () => {
+    const baseUrl = 'https://example.com'
+    const params = new URLSearchParams({ apple: 'fruit' })
+
+    const baseQuery = fetchBaseQuery({
+      baseUrl,
+      fetchFn: nodeFetch as any,
+    })
+    let request: any
+    ;({ data: request } = await baseQuery(
+      { url: '/echo', params },
+      commonBaseQueryApi,
+      {},
+    ))
+
+    expect(request.url).toEqual(`${baseUrl}/echo?apple=fruit`)
+  })
+
+  test('respects mocking window.fetch after a fetch base query is created', async () => {
+    const baseUrl = 'https://example.com'
+    const baseQuery = fetchBaseQuery({ baseUrl })
+
+    const fakeResponse = {
+      ok: true,
+      status: 200,
+      text: async () => `{ "url": "mock-return-url" }`,
+      clone: () => fakeResponse,
+    }
+
+    const spiedFetch = vi.spyOn(window, 'fetch')
+    spiedFetch.mockResolvedValueOnce(fakeResponse as any)
+
+    const { data } = await baseQuery({ url: '/echo' }, commonBaseQueryApi, {})
+    expect(data).toEqual({ url: 'mock-return-url' })
+
+    spiedFetch.mockClear()
+  })
+})
+
+describe('FormData', () => {
+  test('sets the right headers when sending FormData', async () => {
+    const body = new FormData()
+
+    body.append('username', 'test')
+
+    body.append(
+      'file',
+      new Blob([JSON.stringify({ hello: 'there' }, null, 2)], {
+        type: 'application/json',
+      }),
+    )
+
+    const res = await baseQuery(
+      { url: '/echo', method: 'POST', body },
+      commonBaseQueryApi,
+      {},
+    )
+
+    const request: any = res.data
+
+    expect(request.headers['content-type']).not.toContain('application/json')
+  })
+
+  test('FormData works correctly when prepareHeaders sets Content-Type to application/json', async () => {
+    // This test covers the exact scenario from issue #4669
+    const baseQueryWithJsonDefault = fetchBaseQuery({
+      baseUrl,
+      prepareHeaders: (headers) => {
+        // Set default Content-Type for all requests
+        headers.set('Content-Type', 'application/json')
+        return headers
+      },
+    })
+
+    const body = new FormData()
+    body.append('username', 'test')
+    body.append(
+      'file',
+      new Blob([JSON.stringify({ hello: 'there' }, null, 2)], {
+        type: 'application/json',
+      }),
+    )
+
+    const res = await baseQueryWithJsonDefault(
+      { url: '/echo', method: 'POST', body },
+      commonBaseQueryApi,
+      {},
+    )
+
+    const request: any = res.data
+
+    // The Content-Type should NOT be application/json when FormData is used
+    expect(request.headers['content-type']).not.toContain('application/json')
+    // It should contain multipart/form-data (set automatically by the browser)
+    expect(request.headers['content-type']).toContain('multipart/form-data')
+  })
+
+  test('FormData works when prepareHeaders conditionally removes Content-Type', async () => {
+    // This tests the workaround solution from the issue comments
+    const baseQueryWithConditionalHeader = fetchBaseQuery({
+      baseUrl,
+      prepareHeaders: (headers, { arg }) => {
+        // Check if body is FormData and skip setting Content-Type
+        if ((arg as FetchArgs).body instanceof FormData) {
+          // Delete Content-Type to let browser set it automatically
+          headers.delete('Content-Type')
+        } else {
+          // Set default Content-Type for non-FormData requests
+          headers.set('Content-Type', 'application/json')
+        }
+        return headers
+      },
+    })
+
+    const body = new FormData()
+    body.append('username', 'test')
+    body.append('file', new Blob(['test content'], { type: 'text/plain' }))
+
+    const res = await baseQueryWithConditionalHeader(
+      { url: '/echo', method: 'POST', body },
+      commonBaseQueryApi,
+      {},
+    )
+
+    const request: any = res.data
+
+    // Should have multipart/form-data set by browser
+    expect(request.headers['content-type']).toContain('multipart/form-data')
+    expect(request.headers['content-type']).not.toContain('application/json')
+  })
+
+  test('endpoint-level headers cannot override to multipart/form-data manually', async () => {
+    // This tests the fetch API quirk mentioned in the issue
+    const baseQueryWithJsonDefault = fetchBaseQuery({
+      baseUrl,
+      prepareHeaders: (headers) => {
+        headers.set('Content-Type', 'application/json')
+        return headers
+      },
+    })
+
+    const body = new FormData()
+    body.append('test', 'value')
+
+    const res = await baseQueryWithJsonDefault(
+      {
+        url: '/echo',
+        method: 'POST',
+        body,
+        // Attempting to manually set multipart/form-data (this won't work as expected)
+        headers: { 'Content-Type': 'multipart/form-data' },
+      },
+      commonBaseQueryApi,
+      {},
+    )
+
+    const request: any = res.data
+
+    // Due to prepareHeaders running after endpoint headers,
+    // and the fetch API not allowing manual multipart/form-data setting,
+    // this demonstrates the problem from the issue
+    // The actual behavior depends on fetchBaseQuery implementation
+    expect(request.headers['content-type']).toBeDefined()
+  })
+
+  test('non-FormData requests still get application/json from prepareHeaders', async () => {
+    // Verify that the workaround doesn't break normal JSON requests
+    const baseQueryWithConditionalHeader = fetchBaseQuery({
+      baseUrl,
+      prepareHeaders: (headers, { arg }) => {
+        if (!((arg as FetchArgs).body instanceof FormData)) {
+          headers.set('Content-Type', 'application/json')
+        }
+        return headers
+      },
+    })
+
+    const jsonBody = { test: 'value' }
+
+    const res = await baseQueryWithConditionalHeader(
+      { url: '/echo', method: 'POST', body: jsonBody },
+      commonBaseQueryApi,
+      {},
+    )
+
+    const request: any = res.data
+
+    // Regular JSON requests should still get application/json
+    expect(request.headers['content-type']).toBe('application/json')
+    expect(request.body).toEqual(jsonBody)
+  })
+})
+
+describe('Accept header handling', () => {
+  test('sets Accept header to application/json for json responseHandler', async () => {
+    let request: any
+    ;({ data: request } = await baseQuery(
+      { url: '/echo', responseHandler: 'json' },
+      commonBaseQueryApi,
+      {},
+    ))
+
+    expect(request.headers['accept']).toBe('application/json')
+  })
+
+  test('sets Accept header to application/json by default (json is default responseHandler)', async () => {
+    let request: any
+    ;({ data: request } = await baseQuery(
+      { url: '/echo' },
+      commonBaseQueryApi,
+      {},
+    ))
+
+    expect(request.headers['accept']).toBe('application/json')
+  })
+
+  test('sets Accept header for text responseHandler', async () => {
+    // Create a baseQuery with text as the global responseHandler
+    const textBaseQuery = fetchBaseQuery({
+      baseUrl,
+      responseHandler: 'text',
+    })
+
+    let request: any
+      // Override to json just for this test so we can inspect the echoed request object
+    ;({ data: request } = await textBaseQuery(
+      { url: '/echo', responseHandler: 'json' },
+      commonBaseQueryApi,
+      {},
+    ))
+
+    // The endpoint-level 'json' responseHandler overrides the global 'text',
+    // so the Accept header should be application/json
+    expect(request.headers['accept']).toBe('application/json')
+  })
+
+  test('does not override explicit Accept header from endpoint', async () => {
+    let request: any
+    ;({ data: request } = await baseQuery(
+      {
+        url: '/echo',
+        responseHandler: 'json',
+        headers: { Accept: 'application/xml' },
+      },
+      commonBaseQueryApi,
+      {},
+    ))
+
+    expect(request.headers['accept']).toBe('application/xml')
+  })
+
+  test('does not override Accept header set in prepareHeaders', async () => {
+    const customBaseQuery = fetchBaseQuery({
+      baseUrl,
+      prepareHeaders: (headers) => {
+        headers.set('Accept', 'application/vnd.api+json')
+        return headers
+      },
+    })
+
+    let request: any
+    ;({ data: request } = await customBaseQuery(
+      { url: '/echo', responseHandler: 'json' },
+      commonBaseQueryApi,
+      {},
+    ))
+
+    expect(request.headers['accept']).toBe('application/vnd.api+json')
+  })
+
+  test('does not set Accept header for content-type responseHandler', async () => {
+    let request: any
+    ;({ data: request } = await baseQuery(
+      { url: '/echo', responseHandler: 'content-type' },
+      commonBaseQueryApi,
+      {},
+    ))
+
+    // Should either not have accept header or have a permissive one
+    // content-type handler adapts to whatever server sends
+    const acceptHeader = request.headers['accept']
+    if (acceptHeader) {
+      expect(acceptHeader).toMatch(/\*\/\*/)
+    }
+  })
+
+  test('respects global responseHandler for Accept header', async () => {
+    const textBaseQuery = fetchBaseQuery({
+      baseUrl,
+      responseHandler: 'text',
+    })
+
+    let request: any
+      // Override to json just for this test so we can inspect the echoed request object
+    ;({ data: request } = await textBaseQuery(
+      { url: '/echo', responseHandler: 'json' },
+      commonBaseQueryApi,
+      {},
+    ))
+
+    // The endpoint-level 'json' responseHandler overrides the global 'text',
+    // so the Accept header should be application/json (proving endpoint-level takes precedence)
+    expect(request.headers['accept']).toBe('application/json')
+  })
+})
+
+describe('still throws on completely unexpected errors', () => {
+  test('', async () => {
+    const error = new Error('some unexpected error')
+    const req = baseQuery(
+      {
+        url: '/success',
+        validateStatus() {
+          throw error
+        },
+      },
+      commonBaseQueryApi,
+      {},
+    )
+    expect(req).toBeInstanceOf(Promise)
+    await expect(req).rejects.toBe(error)
+  })
+})
+
+describe('timeout', () => {
+  test('throws a timeout error when a request takes longer than specified timeout duration', async () => {
+    server.use(
+      http.get(
+        'https://example.com/empty2',
+        async ({ request, cookies, params, requestId }) => {
+          await delay(300)
+
+          return HttpResponse.json({
+            ...request,
+            url: new URL(request.url),
+            cookies,
+            params,
+            requestId,
+            headers: headersToObject(request.headers),
+          })
+        },
+        { once: true },
+      ),
+    )
+
+    const result = await baseQuery(
+      { url: '/empty2', timeout: 200 },
+      commonBaseQueryApi,
+      {},
+    )
+
+    expect(result?.error).toEqual({
+      status: 'TIMEOUT_ERROR',
+      error: expect.stringMatching(/^TimeoutError/),
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/infiniteQueries.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/infiniteQueries.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/infiniteQueries.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,171 @@
+import type { skipToken, InfiniteData } from '@reduxjs/toolkit/query/react'
+import {
+  createApi,
+  fetchBaseQuery,
+  QueryStatus,
+} from '@reduxjs/toolkit/query/react'
+import { setupApiStore } from '../../tests/utils/helpers'
+import { createSlice } from '@internal/createSlice'
+
+describe('Infinite queries', () => {
+  test('Basic infinite query behavior', async () => {
+    type Pokemon = {
+      id: string
+      name: string
+    }
+
+    const pokemonApi = createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
+      endpoints: (build) => ({
+        getInfinitePokemon: build.infiniteQuery<Pokemon[], string, number>({
+          infiniteQueryOptions: {
+            initialPageParam: 0,
+            getNextPageParam: (
+              lastPage,
+              allPages,
+              lastPageParam,
+              allPageParams,
+              queryArg,
+            ) => {
+              expectTypeOf(lastPage).toEqualTypeOf<Pokemon[]>()
+
+              expectTypeOf(allPages).toEqualTypeOf<Pokemon[][]>()
+
+              expectTypeOf(lastPageParam).toBeNumber()
+
+              expectTypeOf(allPageParams).toEqualTypeOf<number[]>()
+
+              expectTypeOf(queryArg).toBeString()
+
+              return lastPageParam + 1
+            },
+          },
+          query({ pageParam, queryArg }) {
+            expectTypeOf(pageParam).toBeNumber()
+            expectTypeOf(queryArg).toBeString()
+
+            return `https://example.com/listItems?page=${pageParam}`
+          },
+          async onCacheEntryAdded(arg, api) {
+            const data = await api.cacheDataLoaded
+            expectTypeOf(data.data).toEqualTypeOf<
+              InfiniteData<Pokemon[], number>
+            >()
+          },
+          async onQueryStarted(arg, api) {
+            const data = await api.queryFulfilled
+            expectTypeOf(data.data).toEqualTypeOf<
+              InfiniteData<Pokemon[], number>
+            >()
+          },
+          providesTags: (result) => {
+            expectTypeOf(result).toEqualTypeOf<
+              InfiniteData<Pokemon[], number> | undefined
+            >()
+            return []
+          },
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(pokemonApi, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    expectTypeOf(pokemonApi.endpoints.getInfinitePokemon.initiate)
+      .parameter(0)
+      .toBeString()
+
+    expectTypeOf(pokemonApi.useGetInfinitePokemonInfiniteQuery).toBeFunction()
+
+    expectTypeOf<
+      Parameters<
+        typeof pokemonApi.endpoints.getInfinitePokemon.useInfiniteQuery
+      >[0]
+    >().toEqualTypeOf<string | typeof skipToken>()
+
+    expectTypeOf(pokemonApi.endpoints.getInfinitePokemon.useInfiniteQueryState)
+      .parameter(0)
+      .toEqualTypeOf<string | typeof skipToken>()
+
+    expectTypeOf(
+      pokemonApi.endpoints.getInfinitePokemon.useInfiniteQuerySubscription,
+    )
+      .parameter(0)
+      .toEqualTypeOf<string | typeof skipToken>()
+
+    const slice = createSlice({
+      name: 'pokemon',
+      initialState: {} as { data: Pokemon[] },
+      reducers: {},
+      extraReducers: (builder) => {
+        builder.addMatcher(
+          pokemonApi.endpoints.getInfinitePokemon.matchFulfilled,
+          (state, action) => {
+            expectTypeOf(action.payload).toEqualTypeOf<
+              InfiniteData<Pokemon[], number>
+            >()
+          },
+        )
+      },
+    })
+
+    const res = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {}),
+    )
+
+    const firstResult = await res
+
+    if (firstResult.status === QueryStatus.fulfilled) {
+      expectTypeOf(firstResult.data.pages).toEqualTypeOf<Pokemon[][]>()
+      expectTypeOf(firstResult.data.pageParams).toEqualTypeOf<number[]>()
+    }
+
+    storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {
+        direction: 'forward',
+      }),
+    )
+
+    const useGetInfinitePokemonQuery =
+      pokemonApi.endpoints.getInfinitePokemon.useInfiniteQuery
+
+    expectTypeOf<
+      Parameters<typeof useGetInfinitePokemonQuery>[0]
+    >().toEqualTypeOf<string | typeof skipToken>()
+
+    function PokemonList() {
+      const {
+        data,
+        currentData,
+        isFetching,
+        isUninitialized,
+        isSuccess,
+        fetchNextPage,
+      } = useGetInfinitePokemonQuery('a')
+
+      expectTypeOf(data).toEqualTypeOf<
+        InfiniteData<Pokemon[], number> | undefined
+      >()
+
+      if (isSuccess) {
+        expectTypeOf(data.pages).toEqualTypeOf<Pokemon[][]>()
+        expectTypeOf(data.pageParams).toEqualTypeOf<number[]>()
+      }
+
+      if (currentData) {
+        expectTypeOf(currentData.pages).toEqualTypeOf<Pokemon[][]>()
+        expectTypeOf(currentData.pageParams).toEqualTypeOf<number[]>()
+      }
+
+      const handleClick = async () => {
+        const res = await fetchNextPage()
+
+        if (res.status === QueryStatus.fulfilled) {
+          expectTypeOf(res.data.pages).toEqualTypeOf<Pokemon[][]>()
+          expectTypeOf(res.data.pageParams).toEqualTypeOf<number[]>()
+        }
+      }
+    }
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/infiniteQueries.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/infiniteQueries.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/infiniteQueries.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1814 @@
+import { server } from '@internal/query/tests/mocks/server'
+import type { InfiniteQueryActionCreatorResult } from '@reduxjs/toolkit/query/react'
+import {
+  QueryStatus,
+  createApi,
+  fakeBaseQuery,
+  fetchBaseQuery,
+} from '@reduxjs/toolkit/query/react'
+import { HttpResponse, delay, http } from 'msw'
+import { actionsReducer, setupApiStore } from '../../tests/utils/helpers'
+import type { InfiniteQueryResultFlags } from '../core/buildSelectors'
+
+describe('Infinite queries', () => {
+  type Pokemon = {
+    id: string
+    name: string
+  }
+
+  type HitCounter = { page: number; hitCounter: number }
+  let counters: Record<string, number> = {}
+  let queryCounter = 0
+
+  const pokemonApi = createApi({
+    baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
+    endpoints: (build) => ({
+      getInfinitePokemon: build.infiniteQuery<Pokemon[], string, number>({
+        infiniteQueryOptions: {
+          initialPageParam: 0,
+          getNextPageParam: (
+            lastPage,
+            allPages,
+            lastPageParam,
+            allPageParams,
+            queryArg,
+          ) => {
+            expect(typeof queryArg).toBe('string')
+            return lastPageParam + 1
+          },
+          getPreviousPageParam: (
+            firstPage,
+            allPages,
+            firstPageParam,
+            allPageParams,
+            queryArg,
+          ) => {
+            expect(typeof queryArg).toBe('string')
+            return firstPageParam > 0 ? firstPageParam - 1 : undefined
+          },
+        },
+        query({ pageParam }) {
+          return `https://example.com/listItems?page=${pageParam}`
+        },
+      }),
+      getInfinitePokemonWithMax: build.infiniteQuery<Pokemon[], string, number>(
+        {
+          infiniteQueryOptions: {
+            initialPageParam: 0,
+            maxPages: 3,
+            getNextPageParam: (
+              lastPage,
+              allPages,
+              lastPageParam,
+              allPageParams,
+            ) => lastPageParam + 1,
+            getPreviousPageParam: (
+              firstPage,
+              allPages,
+              firstPageParam,
+              allPageParams,
+            ) => {
+              return firstPageParam > 0 ? firstPageParam - 1 : undefined
+            },
+          },
+          query({ pageParam }) {
+            return `https://example.com/listItems?page=${pageParam}`
+          },
+        },
+      ),
+      counters: build.query<{ id: string; counter: number }, string>({
+        queryFn: async (arg) => {
+          if (!(arg in counters)) {
+            counters[arg] = 0
+          }
+          counters[arg]++
+
+          return { data: { id: arg, counter: counters[arg] } }
+        },
+      }),
+    }),
+  })
+
+  function createCountersApi() {
+    let hitCounter = 0
+
+    const countersApi = createApi({
+      baseQuery: fakeBaseQuery(),
+      tagTypes: ['Counter'],
+      endpoints: (build) => ({
+        counters: build.infiniteQuery<HitCounter, string, number>({
+          queryFn({ pageParam }) {
+            hitCounter++
+
+            return { data: { page: pageParam, hitCounter } }
+          },
+          infiniteQueryOptions: {
+            initialPageParam: 0,
+            getNextPageParam: (
+              lastPage,
+              allPages,
+              lastPageParam,
+              allPageParams,
+            ) => lastPageParam + 1,
+          },
+          providesTags: ['Counter'],
+        }),
+        mutation: build.mutation<null, void>({
+          queryFn: async () => {
+            return { data: null }
+          },
+          invalidatesTags: ['Counter'],
+        }),
+      }),
+    })
+
+    return countersApi
+  }
+
+  let storeRef = setupApiStore(
+    pokemonApi,
+    { ...actionsReducer },
+    {
+      withoutTestLifecycles: true,
+    },
+  )
+
+  beforeEach(() => {
+    server.use(
+      http.get('https://example.com/listItems', ({ request }) => {
+        const url = new URL(request.url)
+        const pageString = url.searchParams.get('page')
+        const pageNum = parseInt(pageString || '0')
+        queryCounter++
+
+        const results: Pokemon[] = [
+          { id: `${pageNum}`, name: `Pokemon ${pageNum}` },
+        ]
+        return HttpResponse.json(results)
+      }),
+    )
+
+    storeRef = setupApiStore(
+      pokemonApi,
+      { ...actionsReducer },
+      {
+        withoutTestLifecycles: true,
+      },
+    )
+
+    counters = {}
+
+    queryCounter = 0
+  })
+
+  type InfiniteQueryResult = Awaited<InfiniteQueryActionCreatorResult<any>>
+
+  const checkResultData = (
+    result: InfiniteQueryResult,
+    expectedValues: Pokemon[][],
+  ) => {
+    expect(result.status).toBe(QueryStatus.fulfilled)
+    if (result.status === QueryStatus.fulfilled) {
+      expect(result.data.pages).toEqual(expectedValues)
+    }
+  }
+
+  const checkResultLength = (
+    result: InfiniteQueryResult,
+    expectedLength: number,
+  ) => {
+    expect(result.status).toBe(QueryStatus.fulfilled)
+    if (result.status === QueryStatus.fulfilled) {
+      expect(result.data.pages).toHaveLength(expectedLength)
+    }
+  }
+
+  test('Basic infinite query behavior', async () => {
+    const checkFlags = (
+      value: unknown,
+      expectedFlags: Partial<InfiniteQueryResultFlags>,
+    ) => {
+      const actualFlags: InfiniteQueryResultFlags = {
+        hasNextPage: false,
+        hasPreviousPage: false,
+        isFetchingNextPage: false,
+        isFetchingPreviousPage: false,
+        isFetchNextPageError: false,
+        isFetchPreviousPageError: false,
+        ...expectedFlags,
+      }
+
+      expect(value).toMatchObject(actualFlags)
+    }
+
+    const checkEntryFlags = (
+      arg: string,
+      expectedFlags: Partial<InfiniteQueryResultFlags>,
+    ) => {
+      const selector = pokemonApi.endpoints.getInfinitePokemon.select(arg)
+      const entry = selector(storeRef.store.getState())
+
+      checkFlags(entry, expectedFlags)
+    }
+
+    const res1 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {}),
+    )
+
+    checkEntryFlags('fire', {})
+
+    const entry1InitialLoad = await res1
+
+    checkResultData(entry1InitialLoad, [[{ id: '0', name: 'Pokemon 0' }]])
+    checkFlags(entry1InitialLoad, {
+      hasNextPage: true,
+    })
+
+    const res2 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {
+        direction: 'forward',
+      }),
+    )
+
+    checkEntryFlags('fire', {
+      hasNextPage: true,
+      isFetchingNextPage: true,
+    })
+
+    const entry1SecondPage = await res2
+
+    checkResultData(entry1SecondPage, [
+      [{ id: '0', name: 'Pokemon 0' }],
+      [{ id: '1', name: 'Pokemon 1' }],
+    ])
+    checkFlags(entry1SecondPage, {
+      hasNextPage: true,
+    })
+
+    const res3 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {
+        direction: 'backward',
+      }),
+    )
+
+    checkEntryFlags('fire', {
+      hasNextPage: true,
+      isFetchingPreviousPage: true,
+    })
+
+    const entry1PrevPageMissing = await res3
+
+    checkResultData(entry1PrevPageMissing, [
+      [{ id: '0', name: 'Pokemon 0' }],
+      [{ id: '1', name: 'Pokemon 1' }],
+    ])
+    checkFlags(entry1PrevPageMissing, {
+      hasNextPage: true,
+    })
+
+    const res4 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('water', {
+        initialPageParam: 3,
+      }),
+    )
+
+    checkEntryFlags('water', {})
+
+    const entry2InitialLoad = await res4
+
+    checkResultData(entry2InitialLoad, [[{ id: '3', name: 'Pokemon 3' }]])
+    checkFlags(entry2InitialLoad, {
+      hasNextPage: true,
+      hasPreviousPage: true,
+    })
+
+    const res5 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('water', {
+        direction: 'forward',
+      }),
+    )
+
+    checkEntryFlags('water', {
+      hasNextPage: true,
+      hasPreviousPage: true,
+      isFetchingNextPage: true,
+    })
+
+    const entry2NextPage = await res5
+
+    checkResultData(entry2NextPage, [
+      [{ id: '3', name: 'Pokemon 3' }],
+      [{ id: '4', name: 'Pokemon 4' }],
+    ])
+    checkFlags(entry2NextPage, {
+      hasNextPage: true,
+      hasPreviousPage: true,
+    })
+
+    const res6 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('water', {
+        direction: 'backward',
+      }),
+    )
+
+    checkEntryFlags('water', {
+      hasNextPage: true,
+      hasPreviousPage: true,
+      isFetchingPreviousPage: true,
+    })
+
+    const entry2PrevPage = await res6
+
+    checkResultData(entry2PrevPage, [
+      [{ id: '2', name: 'Pokemon 2' }],
+      [{ id: '3', name: 'Pokemon 3' }],
+      [{ id: '4', name: 'Pokemon 4' }],
+    ])
+    checkFlags(entry2PrevPage, {
+      hasNextPage: true,
+      hasPreviousPage: true,
+    })
+  })
+
+  test('does not have a page limit without maxPages', async () => {
+    for (let i = 1; i <= 10; i++) {
+      const res = await storeRef.store.dispatch(
+        pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {
+          direction: 'forward',
+        }),
+      )
+
+      checkResultLength(res, i)
+    }
+  })
+
+  test('applies a page limit with maxPages', async () => {
+    for (let i = 1; i <= 10; i++) {
+      const res = await storeRef.store.dispatch(
+        pokemonApi.endpoints.getInfinitePokemonWithMax.initiate('fire', {
+          direction: 'forward',
+        }),
+      )
+
+      checkResultLength(res, Math.min(i, 3))
+    }
+
+    // Should now have entries 7, 8, 9 after the loop
+
+    const res = await storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemonWithMax.initiate('fire', {
+        direction: 'backward',
+      }),
+    )
+
+    checkResultData(res, [
+      [{ id: '6', name: 'Pokemon 6' }],
+      [{ id: '7', name: 'Pokemon 7' }],
+      [{ id: '8', name: 'Pokemon 8' }],
+    ])
+  })
+
+  test('validates maxPages during createApi call', async () => {
+    vi.stubEnv('NODE_ENV', 'development')
+
+    const createApiWithMaxPages = (
+      maxPages: number,
+      getPreviousPageParam: (() => number) | undefined,
+    ) => {
+      createApi({
+        baseQuery: fakeBaseQuery(),
+        endpoints: (build) => ({
+          getInfinitePokemon: build.infiniteQuery<Pokemon[], string, number>({
+            query(pageParam) {
+              return `https://example.com/listItems?page=${pageParam}`
+            },
+            infiniteQueryOptions: {
+              initialPageParam: 0,
+              maxPages,
+              getNextPageParam: () => 1,
+              getPreviousPageParam,
+            },
+          }),
+        }),
+      })
+    }
+
+    expect(() => createApiWithMaxPages(0, () => 0)).toThrowError(
+      `maxPages for endpoint 'getInfinitePokemon' must be a number greater than 0`,
+    )
+
+    expect(() => createApiWithMaxPages(1, undefined)).toThrowError(
+      `getPreviousPageParam for endpoint 'getInfinitePokemon' must be a function if maxPages is used`,
+    )
+  })
+
+  test('refetches all existing pages', async () => {
+    const checkResultData = (
+      result: InfiniteQueryResult,
+      expectedValues: HitCounter[],
+    ) => {
+      expect(result.status).toBe(QueryStatus.fulfilled)
+      if (result.status === QueryStatus.fulfilled) {
+        expect(result.data.pages).toEqual(expectedValues)
+      }
+    }
+
+    const countersApi = createCountersApi()
+
+    const storeRef = setupApiStore(
+      countersApi,
+      { ...actionsReducer },
+      {
+        withoutTestLifecycles: true,
+      },
+    )
+
+    await storeRef.store.dispatch(
+      countersApi.endpoints.counters.initiate('item', {
+        initialPageParam: 3,
+      }),
+    )
+
+    await storeRef.store.dispatch(
+      countersApi.endpoints.counters.initiate('item', {
+        direction: 'forward',
+      }),
+    )
+
+    const thirdPromise = storeRef.store.dispatch(
+      countersApi.endpoints.counters.initiate('item', {
+        direction: 'forward',
+      }),
+    )
+
+    const thirdRes = await thirdPromise
+
+    checkResultData(thirdRes, [
+      { page: 3, hitCounter: 1 },
+      { page: 4, hitCounter: 2 },
+      { page: 5, hitCounter: 3 },
+    ])
+
+    const fourthRes = await thirdPromise.refetch()
+
+    checkResultData(fourthRes, [
+      { page: 3, hitCounter: 4 },
+      { page: 4, hitCounter: 5 },
+      { page: 5, hitCounter: 6 },
+    ])
+  })
+
+  test('Refetches on invalidation', async () => {
+    const checkResultData = (
+      result: InfiniteQueryResult,
+      expectedValues: HitCounter[],
+    ) => {
+      expect(result.status).toBe(QueryStatus.fulfilled)
+      if (result.status === QueryStatus.fulfilled) {
+        expect(result.data.pages).toEqual(expectedValues)
+      }
+    }
+
+    const countersApi = createCountersApi()
+
+    const storeRef = setupApiStore(
+      countersApi,
+      { ...actionsReducer },
+      {
+        withoutTestLifecycles: true,
+      },
+    )
+
+    await storeRef.store.dispatch(
+      countersApi.endpoints.counters.initiate('item', {
+        initialPageParam: 3,
+      }),
+    )
+
+    await storeRef.store.dispatch(
+      countersApi.endpoints.counters.initiate('item', {
+        direction: 'forward',
+      }),
+    )
+
+    const thirdPromise = storeRef.store.dispatch(
+      countersApi.endpoints.counters.initiate('item', {
+        direction: 'forward',
+      }),
+    )
+
+    const thirdRes = await thirdPromise
+
+    checkResultData(thirdRes, [
+      { page: 3, hitCounter: 1 },
+      { page: 4, hitCounter: 2 },
+      { page: 5, hitCounter: 3 },
+    ])
+
+    await storeRef.store.dispatch(countersApi.endpoints.mutation.initiate())
+
+    let entry = countersApi.endpoints.counters.select('item')(
+      storeRef.store.getState(),
+    )
+    const promise = storeRef.store.dispatch(
+      countersApi.util.getRunningQueryThunk('counters', 'item'),
+    )
+    const promises = storeRef.store.dispatch(
+      countersApi.util.getRunningQueriesThunk(),
+    )
+    expect(entry).toMatchObject({
+      status: 'pending',
+    })
+
+    expect(promise).toBeInstanceOf(Promise)
+
+    expect(promises).toEqual([promise])
+
+    const finalRes = await promise
+
+    checkResultData(finalRes as any, [
+      { page: 3, hitCounter: 4 },
+      { page: 4, hitCounter: 5 },
+      { page: 5, hitCounter: 6 },
+    ])
+  })
+
+  test('Refetches on polling', async () => {
+    const countersApi = createCountersApi()
+    const checkResultData = (
+      result: InfiniteQueryResult,
+      expectedValues: HitCounter[],
+    ) => {
+      expect(result.status).toBe(QueryStatus.fulfilled)
+      if (result.status === QueryStatus.fulfilled) {
+        expect(result.data.pages).toEqual(expectedValues)
+      }
+    }
+
+    const storeRef = setupApiStore(
+      countersApi,
+      { ...actionsReducer },
+      {
+        withoutTestLifecycles: true,
+      },
+    )
+
+    await storeRef.store.dispatch(
+      countersApi.endpoints.counters.initiate('item', {
+        initialPageParam: 3,
+      }),
+    )
+
+    await storeRef.store.dispatch(
+      countersApi.endpoints.counters.initiate('item', {
+        direction: 'forward',
+      }),
+    )
+
+    const thirdPromise = storeRef.store.dispatch(
+      countersApi.endpoints.counters.initiate('item', {
+        direction: 'forward',
+      }),
+    )
+
+    const thirdRes = await thirdPromise
+
+    checkResultData(thirdRes, [
+      { page: 3, hitCounter: 1 },
+      { page: 4, hitCounter: 2 },
+      { page: 5, hitCounter: 3 },
+    ])
+
+    thirdPromise.updateSubscriptionOptions({
+      pollingInterval: 50,
+    })
+
+    await delay(25)
+
+    let entry = countersApi.endpoints.counters.select('item')(
+      storeRef.store.getState(),
+    )
+
+    checkResultData(thirdRes, [
+      { page: 3, hitCounter: 1 },
+      { page: 4, hitCounter: 2 },
+      { page: 5, hitCounter: 3 },
+    ])
+
+    await delay(50)
+
+    entry = countersApi.endpoints.counters.select('item')(
+      storeRef.store.getState(),
+    )
+
+    checkResultData(entry as any, [
+      { page: 3, hitCounter: 4 },
+      { page: 4, hitCounter: 5 },
+      { page: 5, hitCounter: 6 },
+    ])
+  })
+
+  test('Handles multiple next page fetches at once', async () => {
+    const initialEntry = await storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {}),
+    )
+
+    checkResultData(initialEntry, [[{ id: '0', name: 'Pokemon 0' }]])
+
+    expect(queryCounter).toBe(1)
+
+    const promise1 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {
+        direction: 'forward',
+      }),
+    )
+
+    expect(queryCounter).toBe(1)
+
+    const promise2 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {
+        direction: 'forward',
+      }),
+    )
+
+    const entry1 = await promise1
+    const entry2 = await promise2
+
+    // The second thunk should have bailed out because the entry was now
+    // pending, so we should only have sent one request.
+    expect(queryCounter).toBe(2)
+
+    expect(entry1).toEqual(entry2)
+
+    checkResultData(entry1, [
+      [{ id: '0', name: 'Pokemon 0' }],
+      [{ id: '1', name: 'Pokemon 1' }],
+    ])
+
+    expect(queryCounter).toBe(2)
+
+    const promise3 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {
+        direction: 'forward',
+      }),
+    )
+
+    expect(queryCounter).toBe(2)
+
+    // We can abort an existing promise, but due to timing issues,
+    // we have to await the promise first before triggering the next request.
+    promise3.abort()
+    const entry3 = await promise3
+
+    const promise4 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {
+        direction: 'forward',
+      }),
+    )
+
+    const entry4 = await promise4
+
+    expect(queryCounter).toBe(4)
+
+    checkResultData(entry4, [
+      [{ id: '0', name: 'Pokemon 0' }],
+      [{ id: '1', name: 'Pokemon 1' }],
+      [{ id: '2', name: 'Pokemon 2' }],
+    ])
+  })
+
+  test('can fetch pages with refetchOnMountOrArgChange active', async () => {
+    const pokemonApiWithRefetch = createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
+      endpoints: (build) => ({
+        getInfinitePokemon: build.infiniteQuery<Pokemon[], string, number>({
+          infiniteQueryOptions: {
+            initialPageParam: 0,
+            getNextPageParam: (
+              lastPage,
+              allPages,
+              // Page param type should be `number`
+              lastPageParam,
+              allPageParams,
+            ) => lastPageParam + 1,
+            getPreviousPageParam: (
+              firstPage,
+              allPages,
+              firstPageParam,
+              allPageParams,
+            ) => {
+              return firstPageParam > 0 ? firstPageParam - 1 : undefined
+            },
+          },
+          query({ pageParam }) {
+            return `https://example.com/listItems?page=${pageParam}`
+          },
+        }),
+      }),
+      refetchOnMountOrArgChange: true,
+    })
+
+    const storeRef = setupApiStore(
+      pokemonApiWithRefetch,
+      { ...actionsReducer },
+      {
+        withoutTestLifecycles: true,
+      },
+    )
+
+    const res1 = storeRef.store.dispatch(
+      pokemonApiWithRefetch.endpoints.getInfinitePokemon.initiate('fire', {}),
+    )
+
+    const entry1InitialLoad = await res1
+    checkResultData(entry1InitialLoad, [[{ id: '0', name: 'Pokemon 0' }]])
+
+    const res2 = storeRef.store.dispatch(
+      pokemonApiWithRefetch.endpoints.getInfinitePokemon.initiate('fire', {
+        direction: 'forward',
+      }),
+    )
+
+    const entry1SecondPage = await res2
+    checkResultData(entry1SecondPage, [
+      [{ id: '0', name: 'Pokemon 0' }],
+      [{ id: '1', name: 'Pokemon 1' }],
+    ])
+
+    expect(queryCounter).toBe(2)
+
+    const entry2InitialLoad = await storeRef.store.dispatch(
+      pokemonApiWithRefetch.endpoints.getInfinitePokemon.initiate('water', {}),
+    )
+
+    checkResultData(entry2InitialLoad, [[{ id: '0', name: 'Pokemon 0' }]])
+
+    expect(queryCounter).toBe(3)
+
+    const entry2SecondPage = await storeRef.store.dispatch(
+      pokemonApiWithRefetch.endpoints.getInfinitePokemon.initiate('water', {
+        direction: 'forward',
+      }),
+    )
+    checkResultData(entry2SecondPage, [
+      [{ id: '0', name: 'Pokemon 0' }],
+      [{ id: '1', name: 'Pokemon 1' }],
+    ])
+
+    expect(queryCounter).toBe(4)
+
+    // Should now be able to switch back to the first query.
+    // The hooks dispatch on arg change without a direction.
+    // That should trigger a refetch of the first query, meaning two requests.
+    // It should also _replace_ the existing results, rather than appending
+    // duplicate entries ([0, 1, 0, 1])
+    const entry1Refetched = await storeRef.store.dispatch(
+      pokemonApiWithRefetch.endpoints.getInfinitePokemon.initiate('fire', {}),
+    )
+
+    checkResultData(entry1Refetched, [
+      [{ id: '0', name: 'Pokemon 0' }],
+      [{ id: '1', name: 'Pokemon 1' }],
+    ])
+
+    expect(queryCounter).toBe(6)
+  })
+
+  test('Works with cache manipulation utils', async () => {
+    const res1 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {}),
+    )
+
+    const entry1InitialLoad = await res1
+    checkResultData(entry1InitialLoad, [[{ id: '0', name: 'Pokemon 0' }]])
+
+    storeRef.store.dispatch(
+      pokemonApi.util.updateQueryData('getInfinitePokemon', 'fire', (draft) => {
+        draft.pages.push([{ id: '1', name: 'Pokemon 1' }])
+        draft.pageParams.push(1)
+      }),
+    )
+
+    const selectFire = pokemonApi.endpoints.getInfinitePokemon.select('fire')
+    const entry1Updated = selectFire(storeRef.store.getState())
+
+    expect(entry1Updated.data).toEqual({
+      pages: [
+        [{ id: '0', name: 'Pokemon 0' }],
+        [{ id: '1', name: 'Pokemon 1' }],
+      ],
+      pageParams: [0, 1],
+    })
+
+    const res2 = storeRef.store.dispatch(
+      pokemonApi.util.upsertQueryData('getInfinitePokemon', 'water', {
+        pages: [[{ id: '2', name: 'Pokemon 2' }]],
+        pageParams: [2],
+      }),
+    )
+
+    const entry2InitialLoad = await res2
+    const selectWater = pokemonApi.endpoints.getInfinitePokemon.select('water')
+    const entry2Updated = selectWater(storeRef.store.getState())
+
+    expect(entry2Updated.data).toEqual({
+      pages: [[{ id: '2', name: 'Pokemon 2' }]],
+      pageParams: [2],
+    })
+
+    storeRef.store.dispatch(
+      pokemonApi.util.upsertQueryEntries([
+        {
+          endpointName: 'getInfinitePokemon',
+          arg: 'air',
+          value: {
+            pages: [[{ id: '3', name: 'Pokemon 3' }]],
+            pageParams: [3],
+          },
+        },
+      ]),
+    )
+
+    const selectAir = pokemonApi.endpoints.getInfinitePokemon.select('air')
+    const entry3Initial = selectAir(storeRef.store.getState())
+
+    expect(entry3Initial.data).toEqual({
+      pages: [[{ id: '3', name: 'Pokemon 3' }]],
+      pageParams: [3],
+    })
+
+    await storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('air', {
+        direction: 'forward',
+      }),
+    )
+
+    const entry3Updated = selectAir(storeRef.store.getState())
+
+    expect(entry3Updated.data).toEqual({
+      pages: [
+        [{ id: '3', name: 'Pokemon 3' }],
+        [{ id: '4', name: 'Pokemon 4' }],
+      ],
+      pageParams: [3, 4],
+    })
+  })
+
+  test('Cache lifecycle methods are called', async () => {
+    const cacheEntryAddedCallback = vi.fn()
+    const queryStartedCallback = vi.fn()
+
+    const pokemonApi = createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
+      endpoints: (build) => ({
+        getInfinitePokemonWithLifecycles: build.infiniteQuery<
+          Pokemon[],
+          string,
+          number
+        >({
+          infiniteQueryOptions: {
+            initialPageParam: 0,
+            getNextPageParam: (
+              lastPage,
+              allPages,
+              // Page param type should be `number`
+              lastPageParam,
+              allPageParams,
+            ) => lastPageParam + 1,
+            getPreviousPageParam: (
+              firstPage,
+              allPages,
+              firstPageParam,
+              allPageParams,
+            ) => {
+              return firstPageParam > 0 ? firstPageParam - 1 : undefined
+            },
+          },
+          query({ pageParam }) {
+            return `https://example.com/listItems?page=${pageParam}`
+          },
+          async onCacheEntryAdded(arg, api) {
+            const data = await api.cacheDataLoaded
+            cacheEntryAddedCallback(arg, data)
+          },
+          async onQueryStarted(arg, api) {
+            const data = await api.queryFulfilled
+            queryStartedCallback(arg, data)
+          },
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(
+      pokemonApi,
+      { ...actionsReducer },
+      {
+        withoutTestLifecycles: true,
+      },
+    )
+
+    const res1 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemonWithLifecycles.initiate(
+        'fire',
+        {},
+      ),
+    )
+
+    const entry1InitialLoad = await res1
+    checkResultData(entry1InitialLoad, [[{ id: '0', name: 'Pokemon 0' }]])
+
+    expect(cacheEntryAddedCallback).toHaveBeenCalledWith('fire', {
+      data: {
+        pages: [[{ id: '0', name: 'Pokemon 0' }]],
+        pageParams: [0],
+      },
+      meta: expect.objectContaining({
+        request: expect.anything(),
+        response: expect.anything(),
+      }),
+    })
+
+    expect(queryStartedCallback).toHaveBeenCalledWith('fire', {
+      data: {
+        pages: [[{ id: '0', name: 'Pokemon 0' }]],
+        pageParams: [0],
+      },
+      meta: expect.objectContaining({
+        request: expect.anything(),
+        response: expect.anything(),
+      }),
+    })
+  })
+
+  test('Can use transformResponse', async () => {
+    type PokemonPage = { items: Pokemon[]; page: number }
+    const pokemonApi = createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
+      endpoints: (build) => ({
+        getInfinitePokemonWithTransform: build.infiniteQuery<
+          PokemonPage,
+          string,
+          number
+        >({
+          infiniteQueryOptions: {
+            initialPageParam: 0,
+            getNextPageParam: (
+              lastPage,
+              allPages,
+              // Page param type should be `number`
+              lastPageParam,
+              allPageParams,
+            ) => lastPageParam + 1,
+          },
+          query({ pageParam }) {
+            return `https://example.com/listItems?page=${pageParam}`
+          },
+          transformResponse(baseQueryReturnValue: Pokemon[], meta, arg) {
+            expect(Array.isArray(baseQueryReturnValue)).toBe(true)
+            return {
+              items: baseQueryReturnValue,
+              page: arg.pageParam,
+            }
+          },
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(
+      pokemonApi,
+      { ...actionsReducer },
+      {
+        withoutTestLifecycles: true,
+      },
+    )
+
+    const checkResultData = (
+      result: InfiniteQueryResult,
+      expectedValues: PokemonPage[],
+    ) => {
+      expect(result.status).toBe(QueryStatus.fulfilled)
+      if (result.status === QueryStatus.fulfilled) {
+        expect(result.data.pages).toEqual(expectedValues)
+      }
+    }
+
+    const res1 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemonWithTransform.initiate('fire', {}),
+    )
+
+    const entry1InitialLoad = await res1
+    checkResultData(entry1InitialLoad, [
+      { items: [{ id: '0', name: 'Pokemon 0' }], page: 0 },
+    ])
+
+    const entry1Updated = await storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemonWithTransform.initiate('fire', {
+        direction: 'forward',
+      }),
+    )
+
+    checkResultData(entry1Updated, [
+      { items: [{ id: '0', name: 'Pokemon 0' }], page: 0 },
+      { items: [{ id: '1', name: 'Pokemon 1' }], page: 1 },
+    ])
+  })
+
+  describe('refetchCachedPages option', () => {
+    test('refetches all pages by default (refetchCachedPages: true)', async () => {
+      let hitCounter = 0
+
+      const countersApi = createApi({
+        baseQuery: fakeBaseQuery(),
+        tagTypes: ['Counter'],
+        endpoints: (build) => ({
+          counters: build.infiniteQuery<HitCounter, string, number>({
+            queryFn({ pageParam }) {
+              hitCounter++
+              return { data: { page: pageParam, hitCounter } }
+            },
+            infiniteQueryOptions: {
+              initialPageParam: 0,
+              getNextPageParam: (
+                lastPage,
+                allPages,
+                lastPageParam,
+                allPageParams,
+              ) => lastPageParam + 1,
+            },
+            providesTags: ['Counter'],
+          }),
+        }),
+      })
+
+      const storeRef = setupApiStore(
+        countersApi,
+        { ...actionsReducer },
+        {
+          withoutTestLifecycles: true,
+        },
+      )
+
+      // Load 3 pages
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          initialPageParam: 0,
+        }),
+      )
+
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      const thirdPromise = storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      const thirdRes = await thirdPromise
+
+      // Should have 3 pages with hitCounters 1, 2, 3
+      expect(thirdRes.data!.pages).toEqual([
+        { page: 0, hitCounter: 1 },
+        { page: 1, hitCounter: 2 },
+        { page: 2, hitCounter: 3 },
+      ])
+
+      // Refetch without specifying refetchCachedPages
+      const refetchRes = await thirdPromise.refetch()
+
+      // All 3 pages should be refetched (hitCounters 4, 5, 6)
+      expect(refetchRes.data!.pages).toEqual([
+        { page: 0, hitCounter: 4 },
+        { page: 1, hitCounter: 5 },
+        { page: 2, hitCounter: 6 },
+      ])
+      expect(refetchRes.data!.pages).toHaveLength(3)
+    })
+
+    test('refetches all pages when refetchCachedPages is explicitly true', async () => {
+      let hitCounter = 0
+
+      const countersApi = createApi({
+        baseQuery: fakeBaseQuery(),
+        tagTypes: ['Counter'],
+        endpoints: (build) => ({
+          counters: build.infiniteQuery<HitCounter, string, number>({
+            queryFn({ pageParam }) {
+              hitCounter++
+              return { data: { page: pageParam, hitCounter } }
+            },
+            infiniteQueryOptions: {
+              initialPageParam: 0,
+              getNextPageParam: (
+                lastPage,
+                allPages,
+                lastPageParam,
+                allPageParams,
+              ) => lastPageParam + 1,
+              refetchCachedPages: true, // Explicit true
+            },
+            providesTags: ['Counter'],
+          }),
+        }),
+      })
+
+      const storeRef = setupApiStore(
+        countersApi,
+        { ...actionsReducer },
+        {
+          withoutTestLifecycles: true,
+        },
+      )
+
+      // Load 3 pages
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          initialPageParam: 0,
+        }),
+      )
+
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      const thirdPromise = storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      const thirdRes = await thirdPromise
+
+      expect(thirdRes.data!.pages).toHaveLength(3)
+
+      // Refetch
+      const refetchRes = await thirdPromise.refetch()
+
+      // All 3 pages should be refetched
+      expect(refetchRes.data!.pages).toHaveLength(3)
+      expect(refetchRes.data!.pages[0].hitCounter).toBeGreaterThan(
+        thirdRes.data!.pages[0].hitCounter,
+      )
+    })
+
+    test('refetches only first page when refetchCachedPages is false', async () => {
+      let hitCounter = 0
+
+      const countersApi = createApi({
+        baseQuery: fakeBaseQuery(),
+        tagTypes: ['Counter'],
+        endpoints: (build) => ({
+          counters: build.infiniteQuery<HitCounter, string, number>({
+            queryFn({ pageParam }) {
+              hitCounter++
+              return { data: { page: pageParam, hitCounter } }
+            },
+            infiniteQueryOptions: {
+              initialPageParam: 0,
+              getNextPageParam: (
+                lastPage,
+                allPages,
+                lastPageParam,
+                allPageParams,
+              ) => lastPageParam + 1,
+              refetchCachedPages: false, // Only refetch first page
+            },
+            providesTags: ['Counter'],
+          }),
+        }),
+      })
+
+      const storeRef = setupApiStore(
+        countersApi,
+        { ...actionsReducer },
+        {
+          withoutTestLifecycles: true,
+        },
+      )
+
+      // Load 3 pages
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          initialPageParam: 0,
+        }),
+      )
+
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      const thirdPromise = storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      const thirdRes = await thirdPromise
+
+      // Should have 3 pages with hitCounters 1, 2, 3
+      expect(thirdRes.data!.pages).toEqual([
+        { page: 0, hitCounter: 1 },
+        { page: 1, hitCounter: 2 },
+        { page: 2, hitCounter: 3 },
+      ])
+
+      // Refetch with refetchCachedPages: false
+      const refetchRes = await thirdPromise.refetch()
+
+      // Only first page should be refetched, cache reset to 1 page
+      expect(refetchRes.data!.pages).toEqual([{ page: 0, hitCounter: 4 }])
+      expect(refetchRes.data!.pageParams).toEqual([0])
+    })
+
+    test('refetches only first page on tag invalidation when refetchCachedPages is false', async () => {
+      let hitCounter = 0
+
+      const countersApi = createApi({
+        baseQuery: fakeBaseQuery(),
+        tagTypes: ['Counter'],
+        endpoints: (build) => ({
+          counters: build.infiniteQuery<HitCounter, string, number>({
+            queryFn({ pageParam }) {
+              hitCounter++
+              return { data: { page: pageParam, hitCounter } }
+            },
+            infiniteQueryOptions: {
+              initialPageParam: 0,
+              getNextPageParam: (
+                lastPage,
+                allPages,
+                lastPageParam,
+                allPageParams,
+              ) => lastPageParam + 1,
+              refetchCachedPages: false,
+            },
+            providesTags: ['Counter'],
+          }),
+          mutation: build.mutation<null, void>({
+            queryFn: async () => ({ data: null }),
+            invalidatesTags: ['Counter'],
+          }),
+        }),
+      })
+
+      const storeRef = setupApiStore(
+        countersApi,
+        { ...actionsReducer },
+        {
+          withoutTestLifecycles: true,
+        },
+      )
+
+      // Load 3 pages
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          initialPageParam: 0,
+        }),
+      )
+
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      // Verify we have 3 pages
+      let entry = countersApi.endpoints.counters.select('item')(
+        storeRef.store.getState(),
+      )
+      expect(entry.data?.pages).toHaveLength(3)
+
+      // Trigger mutation to invalidate tags
+      await storeRef.store.dispatch(countersApi.endpoints.mutation.initiate())
+
+      // Wait for refetch to complete
+      const promise = storeRef.store.dispatch(
+        countersApi.util.getRunningQueryThunk('counters', 'item'),
+      )
+      const finalRes = await promise
+
+      // Only first page should be refetched
+      expect((finalRes as any).data.pages).toEqual([{ page: 0, hitCounter: 4 }])
+    })
+
+    test('refetches only first page during polling when refetchCachedPages is false', async () => {
+      let hitCounter = 0
+
+      const countersApi = createApi({
+        baseQuery: fakeBaseQuery(),
+        endpoints: (build) => ({
+          counters: build.infiniteQuery<HitCounter, string, number>({
+            queryFn({ pageParam }) {
+              hitCounter++
+              return { data: { page: pageParam, hitCounter } }
+            },
+            infiniteQueryOptions: {
+              initialPageParam: 0,
+              getNextPageParam: (
+                lastPage,
+                allPages,
+                lastPageParam,
+                allPageParams,
+              ) => lastPageParam + 1,
+              refetchCachedPages: false,
+            },
+          }),
+        }),
+      })
+
+      const storeRef = setupApiStore(
+        countersApi,
+        { ...actionsReducer },
+        {
+          withoutTestLifecycles: true,
+        },
+      )
+
+      // Load 3 pages
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          initialPageParam: 0,
+        }),
+      )
+
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      const thirdPromise = storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      await thirdPromise
+
+      // Enable polling
+      thirdPromise.updateSubscriptionOptions({
+        pollingInterval: 50,
+      })
+
+      // Wait for first poll
+      await delay(75)
+
+      const entry = countersApi.endpoints.counters.select('item')(
+        storeRef.store.getState(),
+      )
+
+      // Should only have 1 page after poll
+      expect(entry.data?.pages).toEqual([{ page: 0, hitCounter: 4 }])
+    })
+
+    test('refetchCachedPages: false works with maxPages', async () => {
+      let hitCounter = 0
+
+      const countersApi = createApi({
+        baseQuery: fakeBaseQuery(),
+        endpoints: (build) => ({
+          counters: build.infiniteQuery<HitCounter, string, number>({
+            queryFn({ pageParam }) {
+              hitCounter++
+              return { data: { page: pageParam, hitCounter } }
+            },
+            infiniteQueryOptions: {
+              initialPageParam: 0,
+              maxPages: 3,
+              getNextPageParam: (
+                lastPage,
+                allPages,
+                lastPageParam,
+                allPageParams,
+              ) => lastPageParam + 1,
+              getPreviousPageParam: (
+                firstPage,
+                allPages,
+                firstPageParam,
+                allPageParams,
+              ) => (firstPageParam > 0 ? firstPageParam - 1 : undefined),
+              refetchCachedPages: false,
+            },
+          }),
+        }),
+      })
+
+      const storeRef = setupApiStore(
+        countersApi,
+        { ...actionsReducer },
+        {
+          withoutTestLifecycles: true,
+        },
+      )
+
+      // Load 5 pages (but maxPages will limit to 3)
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          initialPageParam: 0,
+        }),
+      )
+
+      for (let i = 0; i < 4; i++) {
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            direction: 'forward',
+          }),
+        )
+      }
+
+      let entry = countersApi.endpoints.counters.select('item')(
+        storeRef.store.getState(),
+      )
+
+      // Should have 3 pages due to maxPages
+      expect(entry.data?.pages).toHaveLength(3)
+
+      // Refetch
+      const refetchPromise = storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          forceRefetch: true,
+        }),
+      )
+
+      const refetchRes = await refetchPromise
+
+      // Should only have 1 page after refetch (refetchCachedPages: false)
+      // Note: With maxPages: 3, the cache kept pages 2, 3, 4
+      // So refetch starts from the first cached page param, which is 2
+      expect(refetchRes.data!.pages).toHaveLength(1)
+      expect(refetchRes.data!.pages[0].page).toBe(2)
+    })
+
+    test('can fetch next page after refetch with refetchCachedPages: false', async () => {
+      let hitCounter = 0
+
+      const countersApi = createApi({
+        baseQuery: fakeBaseQuery(),
+        endpoints: (build) => ({
+          counters: build.infiniteQuery<HitCounter, string, number>({
+            queryFn({ pageParam }) {
+              hitCounter++
+              return { data: { page: pageParam, hitCounter } }
+            },
+            infiniteQueryOptions: {
+              initialPageParam: 0,
+              getNextPageParam: (
+                lastPage,
+                allPages,
+                lastPageParam,
+                allPageParams,
+              ) => lastPageParam + 1,
+              refetchCachedPages: false,
+            },
+          }),
+        }),
+      })
+
+      const storeRef = setupApiStore(
+        countersApi,
+        { ...actionsReducer },
+        {
+          withoutTestLifecycles: true,
+        },
+      )
+
+      // Load 3 pages
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          initialPageParam: 0,
+        }),
+      )
+
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      const thirdPromise = storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      await thirdPromise
+
+      // Refetch (resets to 1 page)
+      await thirdPromise.refetch()
+
+      let entry = countersApi.endpoints.counters.select('item')(
+        storeRef.store.getState(),
+      )
+      expect(entry.data?.pages).toHaveLength(1)
+
+      // Fetch next page
+      const nextPageRes = await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      // Should now have 2 pages
+      expect(nextPageRes.data!.pages).toEqual([
+        { page: 0, hitCounter: 4 },
+        { page: 1, hitCounter: 5 },
+      ])
+    })
+
+    describe('per-call refetchCachedPages override', () => {
+      test('per-call false overrides endpoint true', async () => {
+        let hitCounter = 0
+
+        const countersApi = createApi({
+          baseQuery: fakeBaseQuery(),
+          endpoints: (build) => ({
+            counters: build.infiniteQuery<HitCounter, string, number>({
+              queryFn({ pageParam }) {
+                hitCounter++
+                return { data: { page: pageParam, hitCounter } }
+              },
+              infiniteQueryOptions: {
+                initialPageParam: 0,
+                getNextPageParam: (
+                  lastPage,
+                  allPages,
+                  lastPageParam,
+                  allPageParams,
+                ) => lastPageParam + 1,
+                refetchCachedPages: true, // Endpoint default: refetch all
+              },
+            }),
+          }),
+        })
+
+        const storeRef = setupApiStore(
+          countersApi,
+          { ...actionsReducer },
+          {
+            withoutTestLifecycles: true,
+          },
+        )
+
+        // Load 3 pages
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            initialPageParam: 0,
+          }),
+        )
+
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            direction: 'forward',
+          }),
+        )
+
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            direction: 'forward',
+          }),
+        )
+
+        // Should have 3 pages with hitCounters 1, 2, 3
+        let entry = countersApi.endpoints.counters.select('item')(
+          storeRef.store.getState(),
+        )
+        expect(entry.data?.pages).toEqual([
+          { page: 0, hitCounter: 1 },
+          { page: 1, hitCounter: 2 },
+          { page: 2, hitCounter: 3 },
+        ])
+
+        // Refetch with per-call override: false
+        const refetchRes = await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            forceRefetch: true,
+            refetchCachedPages: false, // Override to false
+          }),
+        )
+
+        // Only first page should be refetched (hitCounter 4)
+        expect(refetchRes.data!.pages).toEqual([{ page: 0, hitCounter: 4 }])
+        expect(refetchRes.data!.pageParams).toEqual([0])
+      })
+
+      test('per-call true overrides endpoint false', async () => {
+        let hitCounter = 0
+
+        const countersApi = createApi({
+          baseQuery: fakeBaseQuery(),
+          endpoints: (build) => ({
+            counters: build.infiniteQuery<HitCounter, string, number>({
+              queryFn({ pageParam }) {
+                hitCounter++
+                return { data: { page: pageParam, hitCounter } }
+              },
+              infiniteQueryOptions: {
+                initialPageParam: 0,
+                getNextPageParam: (
+                  lastPage,
+                  allPages,
+                  lastPageParam,
+                  allPageParams,
+                ) => lastPageParam + 1,
+                refetchCachedPages: false, // Endpoint default: only first page
+              },
+            }),
+          }),
+        })
+
+        const storeRef = setupApiStore(
+          countersApi,
+          { ...actionsReducer },
+          {
+            withoutTestLifecycles: true,
+          },
+        )
+
+        // Load 3 pages
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            initialPageParam: 0,
+          }),
+        )
+
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            direction: 'forward',
+          }),
+        )
+
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            direction: 'forward',
+          }),
+        )
+
+        // Should have 3 pages
+        let entry = countersApi.endpoints.counters.select('item')(
+          storeRef.store.getState(),
+        )
+        expect(entry.data?.pages).toHaveLength(3)
+
+        // Refetch with per-call override: true
+        const refetchRes = await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            forceRefetch: true,
+            refetchCachedPages: true, // Override to true
+          }),
+        )
+
+        // All 3 pages should be refetched
+        expect(refetchRes.data!.pages).toEqual([
+          { page: 0, hitCounter: 4 },
+          { page: 1, hitCounter: 5 },
+          { page: 2, hitCounter: 6 },
+        ])
+        expect(refetchRes.data!.pages).toHaveLength(3)
+      })
+
+      test('uses endpoint config when no per-call override', async () => {
+        let hitCounter = 0
+
+        const countersApi = createApi({
+          baseQuery: fakeBaseQuery(),
+          endpoints: (build) => ({
+            counters: build.infiniteQuery<HitCounter, string, number>({
+              queryFn({ pageParam }) {
+                hitCounter++
+                return { data: { page: pageParam, hitCounter } }
+              },
+              infiniteQueryOptions: {
+                initialPageParam: 0,
+                getNextPageParam: (
+                  lastPage,
+                  allPages,
+                  lastPageParam,
+                  allPageParams,
+                ) => lastPageParam + 1,
+                refetchCachedPages: false, // Endpoint config
+              },
+            }),
+          }),
+        })
+
+        const storeRef = setupApiStore(
+          countersApi,
+          { ...actionsReducer },
+          {
+            withoutTestLifecycles: true,
+          },
+        )
+
+        // Load 3 pages
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            initialPageParam: 0,
+          }),
+        )
+
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            direction: 'forward',
+          }),
+        )
+
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            direction: 'forward',
+          }),
+        )
+
+        // Refetch without per-call override
+        const refetchRes = await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            forceRefetch: true,
+            // No refetchCachedPages specified
+          }),
+        )
+
+        // Should use endpoint config (false) - only first page
+        expect(refetchRes.data!.pages).toEqual([{ page: 0, hitCounter: 4 }])
+      })
+
+      test('defaults to true when no config at any level', async () => {
+        let hitCounter = 0
+
+        const countersApi = createApi({
+          baseQuery: fakeBaseQuery(),
+          endpoints: (build) => ({
+            counters: build.infiniteQuery<HitCounter, string, number>({
+              queryFn({ pageParam }) {
+                hitCounter++
+                return { data: { page: pageParam, hitCounter } }
+              },
+              infiniteQueryOptions: {
+                initialPageParam: 0,
+                getNextPageParam: (
+                  lastPage,
+                  allPages,
+                  lastPageParam,
+                  allPageParams,
+                ) => lastPageParam + 1,
+                // No refetchCachedPages specified
+              },
+            }),
+          }),
+        })
+
+        const storeRef = setupApiStore(
+          countersApi,
+          { ...actionsReducer },
+          {
+            withoutTestLifecycles: true,
+          },
+        )
+
+        // Load 3 pages
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            initialPageParam: 0,
+          }),
+        )
+
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            direction: 'forward',
+          }),
+        )
+
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            direction: 'forward',
+          }),
+        )
+
+        // Refetch without any config
+        const refetchRes = await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            forceRefetch: true,
+          }),
+        )
+
+        // Should default to true - refetch all pages
+        expect(refetchRes.data!.pages).toEqual([
+          { page: 0, hitCounter: 4 },
+          { page: 1, hitCounter: 5 },
+          { page: 2, hitCounter: 6 },
+        ])
+      })
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/injectEndpoints.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/injectEndpoints.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/injectEndpoints.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,121 @@
+import { noop } from '@internal/listenerMiddleware/utils'
+import { configureStore } from '@internal/configureStore'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+
+const api = createApi({
+  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+  endpoints: () => ({}),
+})
+
+describe('injectEndpoints', () => {
+  const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
+
+  afterEach(() => {
+    vi.clearAllMocks()
+    vi.unstubAllEnvs()
+  })
+
+  afterAll(() => {
+    vi.restoreAllMocks()
+    vi.unstubAllEnvs()
+  })
+
+  test("query: overriding with `overrideEndpoints`='throw' throws an error", async () => {
+    const extended = api.injectEndpoints({
+      endpoints: (build) => ({
+        injected: build.query<unknown, string>({
+          query: () => '/success',
+        }),
+      }),
+    })
+
+    expect(() => {
+      extended.injectEndpoints({
+        overrideExisting: 'throw',
+        endpoints: (build) => ({
+          injected: build.query<unknown, string>({
+            query: () => '/success',
+          }),
+        }),
+      })
+    }).toThrowError(
+      new Error(
+        `called \`injectEndpoints\` to override already-existing endpointName injected without specifying \`overrideExisting: true\``,
+      ),
+    )
+  })
+
+  test('query: overriding an endpoint with `overrideEndpoints`=false does nothing in production', async () => {
+    vi.stubEnv('NODE_ENV', 'development')
+
+    const extended = api.injectEndpoints({
+      endpoints: (build) => ({
+        injected: build.query<unknown, string>({
+          query: () => '/success',
+        }),
+      }),
+    })
+
+    extended.injectEndpoints({
+      overrideExisting: false,
+      endpoints: (build) => ({
+        injected: build.query<unknown, string>({
+          query: () => '/success',
+        }),
+      }),
+    })
+
+    expect(consoleErrorSpy).toHaveBeenCalledWith(
+      `called \`injectEndpoints\` to override already-existing endpointName injected without specifying \`overrideExisting: true\``,
+    )
+  })
+
+  test('query: overriding with `overrideEndpoints`=false logs an error in development', async () => {
+    vi.stubEnv('NODE_ENV', 'production')
+
+    const extended = api.injectEndpoints({
+      endpoints: (build) => ({
+        injected: build.query<unknown, string>({
+          query: () => '/success',
+        }),
+      }),
+    })
+
+    extended.injectEndpoints({
+      overrideExisting: false,
+      endpoints: (build) => ({
+        injected: build.query<unknown, string>({
+          query: () => '/success',
+        }),
+      }),
+    })
+
+    expect(consoleErrorSpy).not.toHaveBeenCalled()
+  })
+
+  test('adding the same middleware to the store twice throws an error', () => {
+    // Strictly speaking this is a duplicate of the tests in configureStore.test.ts,
+    // but this helps confirm that we throw the error for adding
+    // the same API middleware twice.
+    const extendedApi = api.injectEndpoints({
+      endpoints: (build) => ({
+        injected: build.query<unknown, string>({
+          query: () => '/success',
+        }),
+      }),
+    })
+
+    const makeStore = () =>
+      configureStore({
+        reducer: {
+          api: api.reducer,
+        },
+        middleware: (getDefaultMiddleware) =>
+          getDefaultMiddleware().concat(api.middleware, extendedApi.middleware),
+      })
+
+    expect(makeStore).toThrowError(
+      'Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.',
+    )
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/invalidation.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/invalidation.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/invalidation.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,146 @@
+import type { TagDescription } from '@reduxjs/toolkit/query'
+import { createApi, fakeBaseQuery } from '@reduxjs/toolkit/query'
+import { waitFor } from '@testing-library/react'
+import { delay } from 'msw'
+import { setupApiStore } from '../../tests/utils/helpers'
+
+const tagTypes = [
+  'apple',
+  'pear',
+  'banana',
+  'tomato',
+  'cat',
+  'dog',
+  'giraffe',
+] as const
+type TagTypes = (typeof tagTypes)[number]
+type ProvidedTags = TagDescription<TagTypes>[] 
+type InvalidatesTags = (ProvidedTags[number] | null | undefined)[]
+/** providesTags, invalidatesTags, shouldInvalidate */
+const caseMatrix: [ProvidedTags, InvalidatesTags, boolean][] = [
+  // *****************************
+  // basic invalidation behavior
+  // *****************************
+
+  // string
+  [['apple'], ['apple'], true],
+  [['apple'], ['pear'], false],
+  // string and type only behave identical
+  [[{ type: 'apple' }], ['apple'], true],
+  [[{ type: 'apple' }], ['pear'], false],
+  [['apple'], [{ type: 'apple' }], true],
+  [['apple'], [{ type: 'pear' }], false],
+  // type only invalidates type + id
+  [[{ type: 'apple', id: 1 }], [{ type: 'apple' }], true],
+  [[{ type: 'pear', id: 1 }], ['apple'], false],
+  // type + id never invalidates type only
+  [['apple'], [{ type: 'apple', id: 1 }], false],
+  [['pear'], [{ type: 'apple', id: 1 }], false],
+  // type + id invalidates type + id
+  [[{ type: 'apple', id: 1 }], [{ type: 'apple', id: 1 }], true],
+  [[{ type: 'apple', id: 1 }], [{ type: 'apple', id: 2 }], false],
+  // null and undefined
+  [['apple'], [null], false],
+  [['apple'], [undefined], false],
+  [['apple'], [null, 'apple'], true],
+  [['apple'], [undefined, 'apple'], true],
+  // *****************************
+  // test multiple values in array
+  // *****************************
+
+  [['apple', 'banana', 'tomato'], ['apple'], true],
+  [['apple'], ['pear', 'banana', 'tomato'], false],
+  [
+    [
+      { type: 'apple', id: 1 },
+      { type: 'apple', id: 3 },
+      { type: 'apple', id: 4 },
+    ],
+    [{ type: 'apple', id: 1 }],
+    true,
+  ],
+  [
+    [{ type: 'apple', id: 1 }],
+    [
+      { type: 'apple', id: 2 },
+      { type: 'apple', id: 3 },
+      { type: 'apple', id: 4 },
+    ],
+    false,
+  ],
+]
+
+test.each(caseMatrix)(
+  '\tprovidesTags: %O,\n\tinvalidatesTags: %O,\n\tshould invalidate: %s',
+  async (providesTags, invalidatesTags, shouldInvalidate) => {
+    let queryCount = 0
+    const {
+      store,
+      api,
+      api: {
+        endpoints: { invalidating, providing, unrelated },
+      },
+    } = setupApiStore(
+      createApi({
+        baseQuery: fakeBaseQuery(),
+        tagTypes,
+        endpoints: (build) => ({
+          providing: build.query<unknown, void>({
+            queryFn() {
+              queryCount++
+              return { data: {} }
+            },
+            providesTags,
+          }),
+          unrelated: build.query<unknown, void>({
+            queryFn() {
+              return { data: {} }
+            },
+            providesTags: ['cat', 'dog', { type: 'giraffe', id: 8 }],
+          }),
+          invalidating: build.mutation<unknown, void>({
+            queryFn() {
+              return { data: {} }
+            },
+            invalidatesTags,
+          }),
+        }),
+      }),
+      undefined,
+      { withoutTestLifecycles: true },
+    )
+
+    store.dispatch(providing.initiate())
+    store.dispatch(unrelated.initiate())
+    expect(queryCount).toBe(1)
+    await waitFor(() => {
+      expect(api.endpoints.providing.select()(store.getState()).status).toBe(
+        'fulfilled',
+      )
+      expect(api.endpoints.unrelated.select()(store.getState()).status).toBe(
+        'fulfilled',
+      )
+    })
+    const toInvalidate = api.util.selectInvalidatedBy(
+      store.getState(),
+      invalidatesTags,
+    )
+
+    if (shouldInvalidate) {
+      expect(toInvalidate).toEqual([
+        {
+          queryCacheKey: 'providing(undefined)',
+          endpointName: 'providing',
+          originalArgs: undefined,
+        },
+      ])
+    } else {
+      expect(toInvalidate).toEqual([])
+    }
+
+    store.dispatch(invalidating.initiate())
+    expect(queryCount).toBe(1)
+    await delay(2)
+    expect(queryCount).toBe(shouldInvalidate ? 2 : 1)
+  },
+)
Index: node_modules/@reduxjs/toolkit/src/query/tests/matchers.test-d.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/matchers.test-d.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/matchers.test-d.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,80 @@
+import type { SerializedError } from '@reduxjs/toolkit'
+import { createSlice } from '@reduxjs/toolkit'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+
+interface ResultType {
+  result: 'complex'
+}
+
+interface ArgType {
+  foo: 'bar'
+  count: 3
+}
+
+const baseQuery = fetchBaseQuery({ baseUrl: 'https://example.com' })
+const api = createApi({
+  baseQuery,
+  endpoints(build) {
+    return {
+      querySuccess: build.query<ResultType, ArgType>({
+        query: () => '/success',
+      }),
+      querySuccess2: build.query({ query: () => '/success' }),
+      queryFail: build.query({ query: () => '/error' }),
+      mutationSuccess: build.mutation({
+        query: () => ({ url: '/success', method: 'POST' }),
+      }),
+      mutationSuccess2: build.mutation({
+        query: () => ({ url: '/success', method: 'POST' }),
+      }),
+      mutationFail: build.mutation({
+        query: () => ({ url: '/error', method: 'POST' }),
+      }),
+    }
+  },
+})
+
+describe('type tests', () => {
+  test('inferred types', () => {
+    createSlice({
+      name: 'auth',
+      initialState: {},
+      reducers: {},
+      extraReducers: (builder) => {
+        builder
+          .addMatcher(
+            api.endpoints.querySuccess.matchPending,
+            (state, action) => {
+              expectTypeOf(action.payload).toBeUndefined()
+
+              expectTypeOf(
+                action.meta.arg.originalArgs,
+              ).toEqualTypeOf<ArgType>()
+            },
+          )
+          .addMatcher(
+            api.endpoints.querySuccess.matchFulfilled,
+            (state, action) => {
+              expectTypeOf(action.payload).toEqualTypeOf<ResultType>()
+
+              expectTypeOf(action.meta.fulfilledTimeStamp).toBeNumber()
+
+              expectTypeOf(
+                action.meta.arg.originalArgs,
+              ).toEqualTypeOf<ArgType>()
+            },
+          )
+          .addMatcher(
+            api.endpoints.querySuccess.matchRejected,
+            (state, action) => {
+              expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+
+              expectTypeOf(
+                action.meta.arg.originalArgs,
+              ).toEqualTypeOf<ArgType>()
+            },
+          )
+      },
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/matchers.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/matchers.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/matchers.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,241 @@
+import {
+  actionsReducer,
+  hookWaitFor,
+  setupApiStore,
+} from '@internal/tests/utils/helpers'
+import { createSlice } from '@reduxjs/toolkit'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+import { act, renderHook } from '@testing-library/react'
+
+interface ResultType {
+  result: 'complex'
+}
+
+interface ArgType {
+  foo: 'bar'
+  count: 3
+}
+
+const baseQuery = fetchBaseQuery({ baseUrl: 'https://example.com' })
+const api = createApi({
+  baseQuery,
+  endpoints(build) {
+    return {
+      querySuccess: build.query<ResultType, ArgType>({
+        query: () => '/success',
+      }),
+      querySuccess2: build.query({ query: () => '/success' }),
+      queryFail: build.query({ query: () => '/error' }),
+      mutationSuccess: build.mutation({
+        query: () => ({ url: '/success', method: 'POST' }),
+      }),
+      mutationSuccess2: build.mutation({
+        query: () => ({ url: '/success', method: 'POST' }),
+      }),
+      mutationFail: build.mutation({
+        query: () => ({ url: '/error', method: 'POST' }),
+      }),
+    }
+  },
+})
+
+const storeRef = setupApiStore(api, {
+  ...actionsReducer,
+})
+
+const {
+  mutationFail,
+  mutationSuccess,
+  mutationSuccess2,
+  queryFail,
+  querySuccess,
+  querySuccess2,
+} = api.endpoints
+
+test('matches query pending & fulfilled actions for the given endpoint', async () => {
+  const endpoint = querySuccess2
+  const otherEndpoint = queryFail
+  const { result } = renderHook(() => endpoint.useQuery({} as any), {
+    wrapper: storeRef.wrapper,
+  })
+  await hookWaitFor(() => expect(result.current.isLoading).toBeFalsy())
+
+  expect(storeRef.store.getState().actions).toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchPending,
+    endpoint.matchFulfilled,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    otherEndpoint.matchPending,
+    otherEndpoint.matchFulfilled,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchFulfilled,
+    api.endpoints.mutationSuccess.matchFulfilled,
+    endpoint.matchRejected,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchPending,
+    endpoint.matchRejected,
+  )
+})
+test('matches query pending & rejected actions for the given endpoint', async () => {
+  const endpoint = queryFail
+  const { result } = renderHook(() => endpoint.useQuery({}), {
+    wrapper: storeRef.wrapper,
+  })
+  await hookWaitFor(() => expect(result.current.isLoading).toBeFalsy())
+  expect(storeRef.store.getState().actions).toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchPending,
+    endpoint.matchRejected,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchFulfilled,
+    endpoint.matchRejected,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchPending,
+    endpoint.matchFulfilled,
+  )
+})
+
+test('matches lazy query pending & fulfilled actions for given endpoint', async () => {
+  const endpoint = querySuccess
+  const { result } = renderHook(() => endpoint.useLazyQuery(), {
+    wrapper: storeRef.wrapper,
+  })
+  act(() => void result.current[0]({} as any))
+  await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())
+
+  expect(storeRef.store.getState().actions).toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchPending,
+    endpoint.matchFulfilled,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchFulfilled,
+    endpoint.matchRejected,
+  )
+
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchPending,
+    endpoint.matchRejected,
+  )
+})
+
+test('matches lazy query pending & rejected actions for given endpoint', async () => {
+  const endpoint = queryFail
+  const { result } = renderHook(() => endpoint.useLazyQuery(), {
+    wrapper: storeRef.wrapper,
+  })
+  act(() => void result.current[0]({}))
+  await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())
+
+  expect(storeRef.store.getState().actions).toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchPending,
+    endpoint.matchRejected,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchFulfilled,
+    endpoint.matchRejected,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchPending,
+    endpoint.matchFulfilled,
+  )
+})
+
+test('matches mutation pending & fulfilled actions for the given endpoint', async () => {
+  const endpoint = mutationSuccess
+  const otherEndpoint = mutationSuccess2
+  const { result } = renderHook(() => endpoint.useMutation(), {
+    wrapper: storeRef.wrapper,
+  })
+  act(() => void result.current[0]({}))
+  await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())
+
+  expect(storeRef.store.getState().actions).toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchPending,
+    endpoint.matchFulfilled,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    otherEndpoint.matchPending,
+    otherEndpoint.matchFulfilled,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchFulfilled,
+    endpoint.matchRejected,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchPending,
+    endpoint.matchRejected,
+  )
+})
+test('matches mutation pending & rejected actions for the given endpoint', async () => {
+  const endpoint = mutationFail
+  const { result } = renderHook(() => endpoint.useMutation(), {
+    wrapper: storeRef.wrapper,
+  })
+  act(() => void result.current[0]({}))
+  await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())
+
+  expect(storeRef.store.getState().actions).toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchPending,
+    endpoint.matchRejected,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchFulfilled,
+    endpoint.matchRejected,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchPending,
+    endpoint.matchFulfilled,
+  )
+})
+
+test('inferred types', () => {
+  createSlice({
+    name: 'auth',
+    initialState: {},
+    reducers: {},
+    extraReducers: (builder) => {
+      builder
+        .addMatcher(
+          api.endpoints.querySuccess.matchPending,
+          (state, action) => {
+            // @ts-expect-error
+            console.log(action.error)
+          },
+        )
+        .addMatcher(
+          api.endpoints.querySuccess.matchFulfilled,
+          (state, action) => {
+            // @ts-expect-error
+            console.log(action.error)
+          },
+        )
+        .addMatcher(
+          api.endpoints.querySuccess.matchRejected,
+          (state, action) => {},
+        )
+    },
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/mocks/handlers.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/mocks/handlers.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/mocks/handlers.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,107 @@
+import { headersToObject } from 'headers-polyfill'
+import { HttpResponse, http } from 'msw'
+
+export type Post = {
+  id: number
+  title: string
+  body: string
+}
+
+export const posts: Record<string, Post> = {
+  1: { id: 1, title: 'hello', body: 'extra body!' },
+}
+
+export const handlers = [
+  http.get(
+    'https://example.com',
+    async ({ request, params, cookies, requestId }) => {
+      HttpResponse.json({ value: 'success' })
+    },
+  ),
+  http.get(
+    'https://example.com/echo',
+    async ({ request, params, cookies, requestId }) => {
+      return HttpResponse.json({
+        ...request,
+        params,
+        cookies,
+        requestId,
+        url: new URL(request.url),
+        headers: headersToObject(request.headers),
+      })
+    },
+  ),
+
+  http.post(
+    'https://example.com/echo',
+    async ({ request, cookies, params, requestId }) => {
+      let body
+
+      try {
+        body =
+          headersToObject(request.headers)['content-type'] === 'text/html'
+            ? await request.text()
+            : await request.json()
+      } catch (err) {
+        body = request.body
+      }
+
+      return HttpResponse.json({
+        ...request,
+        cookies,
+        params,
+        requestId,
+        body,
+        url: new URL(request.url),
+        headers: headersToObject(request.headers),
+      })
+    },
+  ),
+
+  http.get('https://example.com/success', () =>
+    HttpResponse.json({ value: 'success' }),
+  ),
+
+  http.post('https://example.com/success', () =>
+    HttpResponse.json({ value: 'success' }),
+  ),
+
+  http.get('https://example.com/empty', () => new HttpResponse('')),
+
+  http.get('https://example.com/error', () =>
+    HttpResponse.json({ value: 'error' }, { status: 500 }),
+  ),
+
+  http.post('https://example.com/error', () =>
+    HttpResponse.json({ value: 'error' }, { status: 500 }),
+  ),
+
+  http.get('https://example.com/nonstandard-error', () =>
+    HttpResponse.json(
+      {
+        success: false,
+        message: 'This returns a 200 but is really an error',
+      },
+      { status: 200 },
+    ),
+  ),
+
+  http.get('https://example.com/mirror', ({ params }) =>
+    HttpResponse.json(params),
+  ),
+
+  http.post('https://example.com/mirror', ({ params }) =>
+    HttpResponse.json(params),
+  ),
+
+  http.get('https://example.com/posts/random', () => {
+    // just simulate an api that returned a random ID
+    const { id } = posts[1]
+    return HttpResponse.json({ id })
+  }),
+
+  http.get<{ id: string }, any, Pick<Post, 'id'>>(
+    'https://example.com/post/:id',
+    ({ params }) => HttpResponse.json(posts[params.id]),
+  ),
+]
Index: node_modules/@reduxjs/toolkit/src/query/tests/mocks/server.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/mocks/server.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/mocks/server.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,5 @@
+import { setupServer } from 'msw/node'
+import { handlers } from './handlers'
+
+// This configures a request mocking server with the given request handlers.
+export const server = setupServer(...handlers)
Index: node_modules/@reduxjs/toolkit/src/query/tests/optimisticUpdates.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/optimisticUpdates.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/optimisticUpdates.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,476 @@
+import { createApi } from '@reduxjs/toolkit/query/react'
+import { act, renderHook } from '@testing-library/react'
+import { delay } from 'msw'
+import {
+  actionsReducer,
+  hookWaitFor,
+  setupApiStore,
+} from '../../tests/utils/helpers'
+import type { InvalidationState } from '../core/apiState'
+
+interface Post {
+  id: string
+  title: string
+  contents: string
+}
+
+const baseQuery = vi.fn()
+beforeEach(() => {
+  baseQuery.mockReset()
+})
+
+const api = createApi({
+  baseQuery: (...args: any[]) => {
+    const result = baseQuery(...args)
+    if (typeof result === 'object' && 'then' in result)
+      return result
+        .then((data: any) => ({ data, meta: 'meta' }))
+        .catch((e: any) => ({ error: e }))
+    return { data: result, meta: 'meta' }
+  },
+  tagTypes: ['Post'],
+  endpoints: (build) => ({
+    post: build.query<Post, string>({
+      query: (id) => `post/${id}`,
+      providesTags: ['Post'],
+    }),
+    listPosts: build.query<Post[], void>({
+      query: () => `posts`,
+      providesTags: (result) => [
+        ...(result?.map(({ id }) => ({ type: 'Post' as const, id })) ?? []),
+        'Post',
+      ],
+    }),
+    updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({
+      query: ({ id, ...patch }) => ({
+        url: `post/${id}`,
+        method: 'PATCH',
+        body: patch,
+      }),
+      async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
+        const { undo } = dispatch(
+          api.util.updateQueryData('post', id, (draft) => {
+            Object.assign(draft, patch)
+          }),
+        )
+        queryFulfilled.catch(undo)
+      },
+      invalidatesTags: (result) => (result ? ['Post'] : []),
+    }),
+  }),
+})
+
+const storeRef = setupApiStore(api, { ...actionsReducer })
+
+describe('basic lifecycle', () => {
+  let onStart = vi.fn(),
+    onError = vi.fn(),
+    onSuccess = vi.fn()
+
+  const extendedApi = api.injectEndpoints({
+    endpoints: (build) => ({
+      test: build.mutation({
+        query: (x) => x,
+        async onQueryStarted(arg, api) {
+          onStart(arg)
+          try {
+            const result = await api.queryFulfilled
+            onSuccess(result)
+          } catch (e) {
+            onError(e)
+          }
+        },
+      }),
+    }),
+    overrideExisting: true,
+  })
+
+  beforeEach(() => {
+    onStart.mockReset()
+    onError.mockReset()
+    onSuccess.mockReset()
+  })
+
+  test('success', async () => {
+    const { result } = renderHook(
+      () => extendedApi.endpoints.test.useMutation(),
+      { wrapper: storeRef.wrapper },
+    )
+
+    baseQuery.mockResolvedValue('success')
+
+    expect(onStart).not.toHaveBeenCalled()
+    expect(baseQuery).not.toHaveBeenCalled()
+    act(() => void result.current[0]('arg'))
+    expect(onStart).toHaveBeenCalledWith('arg')
+    expect(baseQuery).toHaveBeenCalledWith('arg', expect.any(Object), undefined)
+
+    expect(onError).not.toHaveBeenCalled()
+    expect(onSuccess).not.toHaveBeenCalled()
+    await act(() => delay(5))
+    expect(onError).not.toHaveBeenCalled()
+    expect(onSuccess).toHaveBeenCalledWith({ data: 'success', meta: 'meta' })
+  })
+
+  test('error', async () => {
+    const { result } = renderHook(
+      () => extendedApi.endpoints.test.useMutation(),
+      { wrapper: storeRef.wrapper },
+    )
+
+    baseQuery.mockRejectedValueOnce('error')
+    expect(onStart).not.toHaveBeenCalled()
+    expect(baseQuery).not.toHaveBeenCalled()
+
+    act(() => void result.current[0]('arg'))
+    expect(onStart).toHaveBeenCalledWith('arg')
+    expect(baseQuery).toHaveBeenCalledWith('arg', expect.any(Object), undefined)
+    expect(onError).not.toHaveBeenCalled()
+    expect(onSuccess).not.toHaveBeenCalled()
+    await act(() => delay(5))
+    expect(onError).toHaveBeenCalledWith({
+      error: 'error',
+      isUnhandledError: false,
+      meta: undefined,
+    })
+    expect(onSuccess).not.toHaveBeenCalled()
+  })
+})
+
+describe('updateQueryData', () => {
+  test('updates cache values, can apply inverse patch', async () => {
+    baseQuery
+      .mockResolvedValueOnce({
+        id: '3',
+        title: 'All about cheese.',
+        contents: 'TODO',
+      })
+      // TODO I have no idea why the query is getting called multiple times,
+      // but passing an additional mocked value (_any_ value)
+      // seems to silence some annoying "got an undefined result" logging
+      .mockResolvedValueOnce(42)
+    const { result } = renderHook(() => api.endpoints.post.useQuery('3'), {
+      wrapper: storeRef.wrapper,
+    })
+    await hookWaitFor(() => expect(result.current.isSuccess).toBeTruthy())
+
+    const dataBefore = result.current.data
+    expect(dataBefore).toEqual({
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'TODO',
+    })
+
+    let returnValue!: ReturnType<ReturnType<typeof api.util.updateQueryData>>
+    act(() => {
+      returnValue = storeRef.store.dispatch(
+        api.util.updateQueryData('post', '3', (draft) => {
+          draft.contents = 'I love cheese!'
+        }),
+      )
+    })
+
+    expect(result.current.data).not.toBe(dataBefore)
+    expect(result.current.data).toEqual({
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'I love cheese!',
+    })
+
+    expect(returnValue).toEqual({
+      inversePatches: [{ op: 'replace', path: ['contents'], value: 'TODO' }],
+      patches: [{ op: 'replace', path: ['contents'], value: 'I love cheese!' }],
+      undo: expect.any(Function),
+    })
+
+    act(() => {
+      storeRef.store.dispatch(
+        api.util.patchQueryData('post', '3', returnValue.inversePatches),
+      )
+    })
+
+    expect(result.current.data).toEqual(dataBefore)
+  })
+
+  test('updates (list) cache values including provided tags, undos that', async () => {
+    baseQuery
+      .mockResolvedValueOnce([
+        { id: '3', title: 'All about cheese.', contents: 'TODO' },
+      ])
+      .mockResolvedValueOnce(42)
+    const { result } = renderHook(() => api.endpoints.listPosts.useQuery(), {
+      wrapper: storeRef.wrapper,
+    })
+    await hookWaitFor(() => expect(result.current.isSuccess).toBeTruthy())
+
+    let provided!: InvalidationState<'Post'>
+    act(() => {
+      provided = storeRef.store.getState().api.provided
+    })
+
+    const provided3 = provided.tags.Post['3']
+
+    let returnValue!: ReturnType<ReturnType<typeof api.util.updateQueryData>>
+    act(() => {
+      returnValue = storeRef.store.dispatch(
+        api.util.updateQueryData(
+          'listPosts',
+          undefined,
+          (draft) => {
+            draft.push({
+              id: '4',
+              title: 'Mostly about cheese.',
+              contents: 'TODO',
+            })
+          },
+          true,
+        ),
+      )
+    })
+
+    act(() => {
+      provided = storeRef.store.getState().api.provided
+    })
+
+    const provided4 = provided.tags.Post['4']
+
+    expect(provided4).toEqual(provided3)
+
+    act(() => {
+      returnValue.undo()
+    })
+
+    act(() => {
+      provided = storeRef.store.getState().api.provided
+    })
+
+    const provided4Next = provided.tags.Post['4']
+
+    expect(provided4Next).toEqual([])
+  })
+
+  test('updates (list) cache values excluding provided tags, undoes that', async () => {
+    baseQuery
+      .mockResolvedValueOnce([
+        { id: '3', title: 'All about cheese.', contents: 'TODO' },
+      ])
+      .mockResolvedValueOnce(42)
+    const { result } = renderHook(() => api.endpoints.listPosts.useQuery(), {
+      wrapper: storeRef.wrapper,
+    })
+    await hookWaitFor(() => expect(result.current.isSuccess).toBeTruthy())
+
+    let provided!: InvalidationState<'Post'>
+    act(() => {
+      provided = storeRef.store.getState().api.provided
+    })
+
+    let returnValue!: ReturnType<ReturnType<typeof api.util.updateQueryData>>
+    act(() => {
+      returnValue = storeRef.store.dispatch(
+        api.util.updateQueryData(
+          'listPosts',
+          undefined,
+          (draft) => {
+            draft.push({
+              id: '4',
+              title: 'Mostly about cheese.',
+              contents: 'TODO',
+            })
+          },
+          false,
+        ),
+      )
+    })
+
+    act(() => {
+      provided = storeRef.store.getState().api.provided
+    })
+
+    const provided4 = provided.tags.Post['4']
+
+    expect(provided4).toEqual(undefined)
+
+    act(() => {
+      returnValue.undo()
+    })
+
+    act(() => {
+      provided = storeRef.store.getState().api.provided
+    })
+
+    const provided4Next = provided.tags.Post['4']
+
+    expect(provided4Next).toEqual(undefined)
+  })
+
+  test('does not update non-existing values', async () => {
+    baseQuery
+      .mockImplementationOnce(async () => ({
+        id: '3',
+        title: 'All about cheese.',
+        contents: 'TODO',
+      }))
+      .mockResolvedValueOnce(42)
+
+    const { result } = renderHook(() => api.endpoints.post.useQuery('3'), {
+      wrapper: storeRef.wrapper,
+    })
+    await hookWaitFor(() => expect(result.current.isSuccess).toBeTruthy())
+
+    const dataBefore = result.current.data
+    expect(dataBefore).toEqual({
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'TODO',
+    })
+
+    let returnValue!: ReturnType<ReturnType<typeof api.util.updateQueryData>>
+    act(() => {
+      returnValue = storeRef.store.dispatch(
+        api.util.updateQueryData('post', '4', (draft) => {
+          draft.contents = 'I love cheese!'
+        }),
+      )
+    })
+
+    expect(result.current.data).toBe(dataBefore)
+
+    expect(returnValue).toEqual({
+      inversePatches: [],
+      patches: [],
+      undo: expect.any(Function),
+    })
+  })
+})
+
+describe('full integration', () => {
+  test('success case', async () => {
+    baseQuery
+      .mockResolvedValueOnce({
+        id: '3',
+        title: 'All about cheese.',
+        contents: 'TODO',
+      })
+      .mockResolvedValueOnce({
+        id: '3',
+        title: 'Meanwhile, this changed server-side.',
+        contents: 'Delicious cheese!',
+      })
+      .mockResolvedValueOnce({
+        id: '3',
+        title: 'Meanwhile, this changed server-side.',
+        contents: 'Delicious cheese!',
+      })
+      .mockResolvedValueOnce(42)
+    const { result } = renderHook(
+      () => ({
+        query: api.endpoints.post.useQuery('3'),
+        mutation: api.endpoints.updatePost.useMutation(),
+      }),
+      { wrapper: storeRef.wrapper },
+    )
+    await hookWaitFor(() => expect(result.current.query.isSuccess).toBeTruthy())
+
+    expect(result.current.query.data).toEqual({
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'TODO',
+    })
+
+    act(() => {
+      result.current.mutation[0]({ id: '3', contents: 'Delicious cheese!' })
+    })
+
+    expect(result.current.query.data).toEqual({
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'Delicious cheese!',
+    })
+
+    await hookWaitFor(() =>
+      expect(result.current.query.data).toEqual({
+        id: '3',
+        title: 'Meanwhile, this changed server-side.',
+        contents: 'Delicious cheese!',
+      }),
+    )
+  })
+
+  test('error case', async () => {
+    baseQuery
+      .mockResolvedValueOnce({
+        id: '3',
+        title: 'All about cheese.',
+        contents: 'TODO',
+      })
+      .mockRejectedValueOnce('some error!')
+      .mockResolvedValueOnce({
+        id: '3',
+        title: 'Meanwhile, this changed server-side.',
+        contents: 'TODO',
+      })
+      .mockResolvedValueOnce(42)
+
+    const { result } = renderHook(
+      () => ({
+        query: api.endpoints.post.useQuery('3'),
+        mutation: api.endpoints.updatePost.useMutation(),
+      }),
+      { wrapper: storeRef.wrapper },
+    )
+    await hookWaitFor(() => expect(result.current.query.isSuccess).toBeTruthy())
+
+    expect(result.current.query.data).toEqual({
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'TODO',
+    })
+
+    act(() => {
+      result.current.mutation[0]({ id: '3', contents: 'Delicious cheese!' })
+    })
+
+    // optimistic update
+    expect(result.current.query.data).toEqual({
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'Delicious cheese!',
+    })
+
+    // rollback
+    await hookWaitFor(() =>
+      expect(result.current.query.data).toEqual({
+        id: '3',
+        title: 'All about cheese.',
+        contents: 'TODO',
+      }),
+    )
+
+    // mutation failed - will not invalidate query and not refetch data from the server
+    await expect(() =>
+      hookWaitFor(
+        () =>
+          expect(result.current.query.data).toEqual({
+            id: '3',
+            title: 'Meanwhile, this changed server-side.',
+            contents: 'TODO',
+          }),
+        50,
+      ),
+    ).rejects.toBeTruthy()
+
+    act(() => void result.current.query.refetch())
+
+    // manually refetching gives up-to-date data
+    await hookWaitFor(
+      () =>
+        expect(result.current.query.data).toEqual({
+          id: '3',
+          title: 'Meanwhile, this changed server-side.',
+          contents: 'TODO',
+        }),
+      50,
+    )
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/optimisticUpserts.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/optimisticUpserts.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/optimisticUpserts.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,662 @@
+import { createApi } from '@reduxjs/toolkit/query/react'
+import { createAction } from '@reduxjs/toolkit'
+import {
+  actionsReducer,
+  hookWaitFor,
+  setupApiStore,
+} from '../../tests/utils/helpers'
+import {
+  render,
+  renderHook,
+  act,
+  waitFor,
+  screen,
+} from '@testing-library/react'
+import { delay } from 'msw'
+
+interface Post {
+  id: string
+  title: string
+  contents: string
+}
+
+interface FolderT {
+  id: number
+  children: FolderT[]
+}
+
+const baseQuery = vi.fn()
+beforeEach(() => baseQuery.mockReset())
+
+const postAddedAction = createAction<string>('postAdded')
+
+const api = createApi({
+  baseQuery: (...args: any[]) => {
+    const result = baseQuery(...args)
+    if (typeof result === 'object' && 'then' in result)
+      return result
+        .then((data: any) => ({ data, meta: 'meta' }))
+        .catch((e: any) => ({ error: e }))
+    return { data: result, meta: 'meta' }
+  },
+  tagTypes: ['Post', 'Folder'],
+  endpoints: (build) => ({
+    getPosts: build.query<Post[], void>({ query: () => '/posts' }),
+    post: build.query<Post, string>({
+      query: (id) => `post/${id}`,
+      providesTags: ['Post'],
+    }),
+    updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({
+      query: ({ id, ...patch }) => ({
+        url: `post/${id}`,
+        method: 'PATCH',
+        body: patch,
+      }),
+      async onQueryStarted(arg, { dispatch, queryFulfilled, getState }) {
+        const currentItem = api.endpoints.post.select(arg.id)(getState())
+        if (currentItem?.data) {
+          dispatch(
+            api.util.upsertQueryData('post', arg.id, {
+              ...currentItem.data,
+              ...arg,
+            }),
+          )
+        }
+      },
+      invalidatesTags: (result) => (result ? ['Post'] : []),
+    }),
+    post2: build.query<Post, string>({
+      queryFn: async (id) => {
+        await delay(20)
+        return { data: { id, title: 'All about cheese.', contents: 'TODO' } }
+      },
+    }),
+    postWithSideEffect: build.query<Post, string>({
+      query: (id) => `post/${id}`,
+      providesTags: (result) => {
+        if (result) {
+          return [{ type: 'Post', id: result.id } as const]
+        }
+        return []
+      },
+      async onCacheEntryAdded(arg, api) {
+        // Verify that lifecycle promise resolution works
+        const res = await api.cacheDataLoaded
+
+        // and leave a side effect we can check in the test
+        api.dispatch(postAddedAction(res.data.id))
+      },
+      keepUnusedDataFor: 0.1,
+    }),
+    getFolder: build.query<FolderT, number>({
+      queryFn: async (args) => {
+        return {
+          data: {
+            id: args,
+            // Folder contains children that are as well folders
+            children: [{ id: 2, children: [] }],
+          },
+        }
+      },
+      providesTags: (result, err, args) => [{ type: 'Folder', id: args }],
+      onQueryStarted: async (args, queryApi) => {
+        const { data } = await queryApi.queryFulfilled
+
+        // Upsert getFolder endpoint with children from response data
+        const upsertData = data.children.map((child) => ({
+          arg: child.id,
+          endpointName: 'getFolder' as const,
+          value: child,
+        }))
+
+        queryApi.dispatch(api.util.upsertQueryEntries(upsertData))
+      },
+    }),
+  }),
+})
+
+const storeRef = setupApiStore(api, { ...actionsReducer })
+
+describe('basic lifecycle', () => {
+  let onStart = vi.fn(),
+    onError = vi.fn(),
+    onSuccess = vi.fn()
+
+  const extendedApi = api.injectEndpoints({
+    endpoints: (build) => ({
+      test: build.mutation({
+        query: (x) => x,
+        async onQueryStarted(arg, api) {
+          onStart(arg)
+          try {
+            const result = await api.queryFulfilled
+            onSuccess(result)
+          } catch (e) {
+            onError(e)
+          }
+        },
+      }),
+    }),
+    overrideExisting: true,
+  })
+
+  beforeEach(() => {
+    onStart.mockReset()
+    onError.mockReset()
+    onSuccess.mockReset()
+  })
+
+  test('Does basic inserts and upserts', async () => {
+    const newPost: Post = {
+      id: '3',
+      contents: 'Inserted content',
+      title: 'Inserted title',
+    }
+    const insertPromise = storeRef.store.dispatch(
+      api.util.upsertQueryData('post', newPost.id, newPost),
+    )
+
+    await insertPromise
+
+    const selectPost3 = api.endpoints.post.select(newPost.id)
+    const insertedPostEntry = selectPost3(storeRef.store.getState())
+    expect(insertedPostEntry.isSuccess).toBe(true)
+    expect(insertedPostEntry.data).toEqual(newPost)
+
+    const updatedPost: Post = {
+      id: '3',
+      contents: 'Updated content',
+      title: 'Updated title',
+    }
+
+    const updatePromise = storeRef.store.dispatch(
+      api.util.upsertQueryData('post', updatedPost.id, updatedPost),
+    )
+
+    await updatePromise
+
+    const updatedPostEntry = selectPost3(storeRef.store.getState())
+
+    expect(updatedPostEntry.isSuccess).toBe(true)
+    expect(updatedPostEntry.data).toEqual(updatedPost)
+  })
+
+  test('success', async () => {
+    const { result } = renderHook(
+      () => extendedApi.endpoints.test.useMutation(),
+      { wrapper: storeRef.wrapper },
+    )
+
+    baseQuery.mockResolvedValue('success')
+
+    expect(onStart).not.toHaveBeenCalled()
+    expect(baseQuery).not.toHaveBeenCalled()
+    act(() => void result.current[0]('arg'))
+    expect(onStart).toHaveBeenCalledWith('arg')
+    expect(baseQuery).toHaveBeenCalledWith('arg', expect.any(Object), undefined)
+
+    expect(onError).not.toHaveBeenCalled()
+    expect(onSuccess).not.toHaveBeenCalled()
+    await act(() => delay(5))
+    expect(onError).not.toHaveBeenCalled()
+    expect(onSuccess).toHaveBeenCalledWith({ data: 'success', meta: 'meta' })
+  })
+
+  test('error', async () => {
+    const { result } = renderHook(
+      () => extendedApi.endpoints.test.useMutation(),
+      { wrapper: storeRef.wrapper },
+    )
+
+    baseQuery.mockRejectedValueOnce('error')
+
+    expect(onStart).not.toHaveBeenCalled()
+    expect(baseQuery).not.toHaveBeenCalled()
+    act(() => void result.current[0]('arg'))
+    expect(onStart).toHaveBeenCalledWith('arg')
+    expect(baseQuery).toHaveBeenCalledWith('arg', expect.any(Object), undefined)
+
+    expect(onError).not.toHaveBeenCalled()
+    expect(onSuccess).not.toHaveBeenCalled()
+    await act(() => delay(5))
+    expect(onError).toHaveBeenCalledWith({
+      error: 'error',
+      isUnhandledError: false,
+      meta: undefined,
+    })
+    expect(onSuccess).not.toHaveBeenCalled()
+  })
+})
+
+describe('upsertQueryData', () => {
+  test('inserts cache entry', async () => {
+    baseQuery
+      .mockResolvedValueOnce({
+        id: '3',
+        title: 'All about cheese.',
+        contents: 'TODO',
+      })
+      // TODO I have no idea why the query is getting called multiple times,
+      // but passing an additional mocked value (_any_ value)
+      // seems to silence some annoying "got an undefined result" logging
+      .mockResolvedValueOnce(42)
+    const { result } = renderHook(() => api.endpoints.post.useQuery('3'), {
+      wrapper: storeRef.wrapper,
+    })
+    await hookWaitFor(() => expect(result.current.isSuccess).toBeTruthy())
+
+    const dataBefore = result.current.data
+    expect(dataBefore).toEqual({
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'TODO',
+    })
+
+    await act(async () => {
+      storeRef.store.dispatch(
+        api.util.upsertQueryData('post', '3', {
+          id: '3',
+          title: 'All about cheese.',
+          contents: 'I love cheese!',
+        }),
+      )
+    })
+
+    expect(result.current.data).not.toBe(dataBefore)
+    expect(result.current.data).toEqual({
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'I love cheese!',
+    })
+  })
+
+  test('does update non-existing values', async () => {
+    baseQuery
+      // throw an error to make sure there is no cached data
+      .mockImplementationOnce(async () => {
+        throw new Error('failed to load')
+      })
+      .mockResolvedValueOnce(42)
+
+    // a subscriber is needed to have the data stay in the cache
+    // Not sure if this is the wanted behavior, I would have liked
+    // it to stay in the cache for the x amount of time the cache
+    // is preserved normally after the last subscriber was unmounted
+    const { result, rerender } = renderHook(
+      () => api.endpoints.post.useQuery('4'),
+      { wrapper: storeRef.wrapper },
+    )
+    await hookWaitFor(() => expect(result.current.isError).toBeTruthy())
+
+    // upsert the data
+    act(() => {
+      storeRef.store.dispatch(
+        api.util.upsertQueryData('post', '4', {
+          id: '4',
+          title: 'All about cheese',
+          contents: 'I love cheese!',
+        }),
+      )
+    })
+
+    // rerender the hook
+    rerender()
+    // wait until everything has settled
+    await hookWaitFor(() => expect(result.current.isSuccess).toBeTruthy())
+
+    // the cached data is returned as the result
+    expect(result.current.data).toStrictEqual({
+      id: '4',
+      title: 'All about cheese',
+      contents: 'I love cheese!',
+    })
+  })
+
+  test('upsert while a normal query is running (success)', async () => {
+    const fetchedData = {
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'Yummy',
+    }
+    baseQuery.mockImplementation(() => delay(20).then(() => fetchedData))
+    const upsertedData = {
+      id: '3',
+      title: 'Data from a SSR Render',
+      contents: 'This is just some random data',
+    }
+
+    const selector = api.endpoints.post.select('3')
+    const fetchRes = storeRef.store.dispatch(api.endpoints.post.initiate('3'))
+    const upsertRes = storeRef.store.dispatch(
+      api.util.upsertQueryData('post', '3', upsertedData),
+    )
+
+    await upsertRes
+    let state = selector(storeRef.store.getState())
+    expect(state.data).toEqual(upsertedData)
+
+    await fetchRes
+    state = selector(storeRef.store.getState())
+    expect(state.data).toEqual(fetchedData)
+  })
+  test('upsert while a normal query is running (rejected)', async () => {
+    baseQuery.mockImplementationOnce(async () => {
+      await delay(20)
+      // eslint-disable-next-line no-throw-literal
+      throw 'Error!'
+    })
+    const upsertedData = {
+      id: '3',
+      title: 'Data from a SSR Render',
+      contents: 'This is just some random data',
+    }
+
+    const selector = api.endpoints.post.select('3')
+    const fetchRes = storeRef.store.dispatch(api.endpoints.post.initiate('3'))
+    const upsertRes = storeRef.store.dispatch(
+      api.util.upsertQueryData('post', '3', upsertedData),
+    )
+
+    await upsertRes
+    let state = selector(storeRef.store.getState())
+    expect(state.data).toEqual(upsertedData)
+    expect(state.isSuccess).toBeTruthy()
+
+    await fetchRes
+    state = selector(storeRef.store.getState())
+    expect(state.data).toEqual(upsertedData)
+    expect(state.isError).toBeTruthy()
+  })
+})
+
+describe('upsertQueryEntries', () => {
+  const posts: Post[] = [
+    { id: '1', contents: 'A', title: 'A' },
+    { id: '2', contents: 'B', title: 'B' },
+    { id: '3', contents: 'C', title: 'C' },
+  ]
+
+  const entriesAction = api.util.upsertQueryEntries([
+    { endpointName: 'getPosts', arg: undefined, value: posts },
+    ...posts.map((post) => ({
+      endpointName: 'postWithSideEffect' as const,
+      arg: post.id,
+      value: post,
+    })),
+  ])
+
+  test('Upserts many entries at once', async () => {
+    storeRef.store.dispatch(entriesAction)
+
+    const state = storeRef.store.getState()
+
+    expect(api.endpoints.getPosts.select()(state).data).toBe(posts)
+
+    for (const post of posts) {
+      expect(api.endpoints.postWithSideEffect.select(post.id)(state).data).toBe(
+        post,
+      )
+
+      // Should have added tags
+      expect(state.api.provided.tags.Post[post.id]).toEqual([
+        `postWithSideEffect("${post.id}")`,
+      ])
+    }
+  })
+
+  test('Triggers cache lifecycles and side effects', async () => {
+    storeRef.store.dispatch(entriesAction)
+
+    // Tricky timing. The cache data promises will be resolved
+    // in microtasks. We need to wait for them. Best to do this
+    // in a loop just to avoid a hardcoded delay, but also this
+    // needs to complete before `keepUnusedDataFor` expires them.
+    await waitFor(
+      () => {
+        const state = storeRef.store.getState()
+
+        // onCacheEntryAdded should have run for each post,
+        // including cache data being resolved
+        for (const post of posts) {
+          const matchingSideEffectAction = state.actions.find(
+            (action) =>
+              postAddedAction.match(action) && action.payload === post.id,
+          )
+          expect(matchingSideEffectAction).toBeTruthy()
+        }
+
+        const selectedData =
+          api.endpoints.postWithSideEffect.select('1')(state).data
+
+        expect(selectedData).toBe(posts[0])
+      },
+      { timeout: 150, interval: 5 },
+    )
+
+    // The cache data should be removed after the keepUnusedDataFor time,
+    // so wait longer than that
+    await delay(300)
+
+    const stateAfter = storeRef.store.getState()
+
+    expect(api.endpoints.postWithSideEffect.select('1')(stateAfter).data).toBe(
+      undefined,
+    )
+  })
+
+  test('Handles repeated upserts and async lifecycles', async () => {
+    const StateForUpsertFolder = ({ folderId }: { folderId: number }) => {
+      const { status } = api.useGetFolderQuery(folderId)
+
+      return (
+        <>
+          <div>
+            Status getFolder with ID (
+            {folderId === 1 ? 'original request' : 'upserted'}) {folderId}:{' '}
+            <span data-testid={`status-${folderId}`}>{status}</span>
+          </div>
+        </>
+      )
+    }
+
+    const Folder = () => {
+      const { data, isLoading, isError } = api.useGetFolderQuery(1)
+
+      return (
+        <div>
+          <h1>Folders</h1>
+
+          {isLoading && <div>Loading...</div>}
+
+          {isError && <div>Error...</div>}
+
+          <StateForUpsertFolder key={`state-${1}`} folderId={1} />
+          <StateForUpsertFolder key={`state-${2}`} folderId={2} />
+        </div>
+      )
+    }
+
+    render(<Folder />, { wrapper: storeRef.wrapper })
+
+    await waitFor(() => {
+      const { actions } = storeRef.store.getState()
+      // Inspection:
+      // - 2 inits
+      // - 2 pendings, 2 fulfilleds for the hook queries
+      // - 2 upserts
+      expect(actions.length).toBe(8)
+      expect(
+        actions.filter((a) => api.util.upsertQueryEntries.match(a)).length,
+      ).toBe(2)
+    })
+    expect(screen.getByTestId('status-2').textContent).toBe('fulfilled')
+  })
+})
+
+describe('full integration', () => {
+  test('success case', async () => {
+    baseQuery
+      .mockResolvedValueOnce({
+        id: '3',
+        title: 'All about cheese.',
+        contents: 'TODO',
+      })
+      .mockResolvedValueOnce({
+        id: '3',
+        title: 'Meanwhile, this changed server-side.',
+        contents: 'Delicious cheese!',
+      })
+      .mockResolvedValueOnce({
+        id: '3',
+        title: 'Meanwhile, this changed server-side.',
+        contents: 'Delicious cheese!',
+      })
+      .mockResolvedValueOnce(42)
+    const { result } = renderHook(
+      () => ({
+        query: api.endpoints.post.useQuery('3'),
+        mutation: api.endpoints.updatePost.useMutation(),
+      }),
+      { wrapper: storeRef.wrapper },
+    )
+    await hookWaitFor(() => expect(result.current.query.isSuccess).toBeTruthy())
+
+    expect(result.current.query.data).toEqual({
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'TODO',
+    })
+
+    await act(async () => {
+      await result.current.mutation[0]({
+        id: '3',
+        contents: 'Delicious cheese!',
+      })
+    })
+
+    expect(result.current.query.data).toEqual({
+      id: '3',
+      title: 'Meanwhile, this changed server-side.',
+      contents: 'Delicious cheese!',
+    })
+
+    await hookWaitFor(() =>
+      expect(result.current.query.data).toEqual({
+        id: '3',
+        title: 'Meanwhile, this changed server-side.',
+        contents: 'Delicious cheese!',
+      }),
+    )
+  })
+
+  test('error case', async () => {
+    baseQuery
+      .mockResolvedValueOnce({
+        id: '3',
+        title: 'All about cheese.',
+        contents: 'TODO',
+      })
+      .mockRejectedValueOnce('some error!')
+      .mockResolvedValueOnce({
+        id: '3',
+        title: 'Meanwhile, this changed server-side.',
+        contents: 'TODO',
+      })
+      .mockResolvedValueOnce(42)
+
+    const { result } = renderHook(
+      () => ({
+        query: api.endpoints.post.useQuery('3'),
+        mutation: api.endpoints.updatePost.useMutation(),
+      }),
+      { wrapper: storeRef.wrapper },
+    )
+    await hookWaitFor(() => expect(result.current.query.isSuccess).toBeTruthy())
+
+    expect(result.current.query.data).toEqual({
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'TODO',
+    })
+
+    await act(async () => {
+      await result.current.mutation[0]({
+        id: '3',
+        contents: 'Delicious cheese!',
+      })
+    })
+
+    // optimistic update
+    expect(result.current.query.data).toEqual({
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'Delicious cheese!',
+    })
+
+    // mutation failed - will not invalidate query and not refetch data from the server
+    await expect(() =>
+      hookWaitFor(
+        () =>
+          expect(result.current.query.data).toEqual({
+            id: '3',
+            title: 'Meanwhile, this changed server-side.',
+            contents: 'TODO',
+          }),
+        50,
+      ),
+    ).rejects.toBeTruthy()
+
+    act(() => void result.current.query.refetch())
+
+    // manually refetching gives up-to-date data
+    await hookWaitFor(
+      () =>
+        expect(result.current.query.data).toEqual({
+          id: '3',
+          title: 'Meanwhile, this changed server-side.',
+          contents: 'TODO',
+        }),
+      50,
+    )
+  })
+
+  test('Interop with in-flight requests', async () => {
+    await act(async () => {
+      const fetchRes = storeRef.store.dispatch(
+        api.endpoints.post2.initiate('3'),
+      )
+
+      const upsertRes = storeRef.store.dispatch(
+        api.util.upsertQueryData('post2', '3', {
+          id: '3',
+          title: 'Upserted title',
+          contents: 'Upserted contents',
+        }),
+      )
+
+      const selectEntry = api.endpoints.post2.select('3')
+      await waitFor(
+        () => {
+          const entry1 = selectEntry(storeRef.store.getState())
+          expect(entry1.data).toEqual({
+            id: '3',
+            title: 'Upserted title',
+            contents: 'Upserted contents',
+          })
+        },
+        { interval: 1, timeout: 15 },
+      )
+      await waitFor(
+        () => {
+          const entry2 = selectEntry(storeRef.store.getState())
+          expect(entry2.data).toEqual({
+            id: '3',
+            title: 'All about cheese.',
+            contents: 'TODO',
+          })
+        },
+        { interval: 1 },
+      )
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/polling.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/polling.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/polling.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,286 @@
+import { createApi } from '@reduxjs/toolkit/query'
+import type { QueryActionCreatorResult } from '@reduxjs/toolkit/query'
+import { delay } from 'msw'
+import { setupApiStore } from '../../tests/utils/helpers'
+import type { SubscriptionSelectors } from '../core/buildMiddleware/types'
+
+const mockBaseQuery = vi
+  .fn()
+  .mockImplementation((args: any) => ({ data: args }))
+
+const api = createApi({
+  baseQuery: mockBaseQuery,
+  tagTypes: ['Posts'],
+  endpoints: (build) => ({
+    getPosts: build.query<unknown, number>({
+      query(pageNumber) {
+        return { url: 'posts', params: pageNumber }
+      },
+      providesTags: ['Posts'],
+    }),
+  }),
+})
+const { getPosts } = api.endpoints
+
+const storeRef = setupApiStore(api)
+
+let getSubscriptions: SubscriptionSelectors['getSubscriptions']
+
+beforeEach(() => {
+  ;({ getSubscriptions } = storeRef.store.dispatch(
+    api.internalActions.internal_getRTKQSubscriptions(),
+  ) as unknown as SubscriptionSelectors)
+
+  const currentPolls = storeRef.store.dispatch({
+    type: `${api.reducerPath}/getPolling`,
+  }) as any
+  ;(currentPolls as any).pollUpdateCounters = {}
+})
+
+const getSubscribersForQueryCacheKey = (queryCacheKey: string) =>
+  getSubscriptions().get(queryCacheKey) ?? new Map()
+const createSubscriptionGetter = (queryCacheKey: string) => () =>
+  getSubscribersForQueryCacheKey(queryCacheKey)
+
+describe('polling tests', () => {
+  it('clears intervals when seeing a resetApiState action', async () => {
+    await storeRef.store.dispatch(
+      getPosts.initiate(1, {
+        subscriptionOptions: { pollingInterval: 10 },
+        subscribe: true,
+      }),
+    )
+
+    expect(mockBaseQuery).toHaveBeenCalledOnce()
+
+    storeRef.store.dispatch(api.util.resetApiState())
+
+    await delay(30)
+
+    expect(mockBaseQuery).toHaveBeenCalledOnce()
+  })
+
+  it('replaces polling interval when the subscription options are updated', async () => {
+    const { requestId, queryCacheKey, ...subscription } =
+      storeRef.store.dispatch(
+        getPosts.initiate(1, {
+          subscriptionOptions: { pollingInterval: 10 },
+          subscribe: true,
+        }),
+      )
+
+    const getSubs = createSubscriptionGetter(queryCacheKey)
+
+    await delay(1)
+    expect(getSubs().size).toBe(1)
+    expect(getSubs()?.get(requestId)?.pollingInterval).toBe(10)
+
+    subscription.updateSubscriptionOptions({ pollingInterval: 20 })
+
+    await delay(1)
+    expect(getSubs().size).toBe(1)
+    expect(getSubs()?.get(requestId)?.pollingInterval).toBe(20)
+  })
+
+  it(`doesn't replace the interval when removing a shared query instance with a poll `, async () => {
+    const subscriptionOne = storeRef.store.dispatch(
+      getPosts.initiate(1, {
+        subscriptionOptions: { pollingInterval: 10 },
+        subscribe: true,
+      }),
+    )
+
+    storeRef.store.dispatch(
+      getPosts.initiate(1, {
+        subscriptionOptions: { pollingInterval: 10 },
+        subscribe: true,
+      }),
+    )
+
+    await delay(10)
+
+    const getSubs = createSubscriptionGetter(subscriptionOne.queryCacheKey)
+
+    expect(getSubs().size).toBe(2)
+
+    subscriptionOne.unsubscribe()
+
+    await delay(1)
+    expect(getSubs().size).toBe(1)
+  })
+
+  it('uses lowest specified interval when two components are mounted', async () => {
+    storeRef.store.dispatch(
+      getPosts.initiate(1, {
+        subscriptionOptions: { pollingInterval: 30000 },
+        subscribe: true,
+      }),
+    )
+
+    storeRef.store.dispatch(
+      getPosts.initiate(1, {
+        subscriptionOptions: { pollingInterval: 10 },
+        subscribe: true,
+      }),
+    )
+
+    await delay(20)
+
+    expect(mockBaseQuery.mock.calls.length).toBeGreaterThanOrEqual(2)
+  })
+
+  it('respects skipPollingIfUnfocused', async () => {
+    mockBaseQuery.mockClear()
+    storeRef.store.dispatch(
+      getPosts.initiate(2, {
+        subscriptionOptions: {
+          pollingInterval: 10,
+          skipPollingIfUnfocused: true,
+        },
+        subscribe: true,
+      }),
+    )
+    storeRef.store.dispatch(api.internalActions?.onFocusLost())
+
+    await delay(50)
+    const callsWithSkip = mockBaseQuery.mock.calls.length
+
+    storeRef.store.dispatch(
+      getPosts.initiate(2, {
+        subscriptionOptions: {
+          pollingInterval: 10,
+          skipPollingIfUnfocused: false,
+        },
+        subscribe: true,
+      }),
+    )
+
+    storeRef.store.dispatch(api.internalActions?.onFocus())
+
+    await delay(50)
+    const callsWithoutSkip = mockBaseQuery.mock.calls.length
+
+    expect(callsWithSkip).toBe(1)
+    expect(callsWithoutSkip).toBeGreaterThanOrEqual(2)
+
+    storeRef.store.dispatch(api.util.resetApiState())
+  })
+
+  it('respects skipPollingIfUnfocused if at least one subscription has it', async () => {
+    storeRef.store.dispatch(
+      getPosts.initiate(3, {
+        subscriptionOptions: {
+          pollingInterval: 10,
+          skipPollingIfUnfocused: false,
+        },
+        subscribe: true,
+      }),
+    )
+
+    await delay(50)
+    const callsWithoutSkip = mockBaseQuery.mock.calls.length
+
+    storeRef.store.dispatch(
+      getPosts.initiate(3, {
+        subscriptionOptions: {
+          pollingInterval: 15,
+          skipPollingIfUnfocused: true,
+        },
+        subscribe: true,
+      }),
+    )
+
+    storeRef.store.dispatch(
+      getPosts.initiate(3, {
+        subscriptionOptions: {
+          pollingInterval: 20,
+          skipPollingIfUnfocused: false,
+        },
+        subscribe: true,
+      }),
+    )
+
+    storeRef.store.dispatch(api.internalActions?.onFocusLost())
+
+    await delay(50)
+    const callsWithSkip = mockBaseQuery.mock.calls.length
+
+    expect(callsWithoutSkip).toBeGreaterThan(2)
+    expect(callsWithSkip).toBe(callsWithoutSkip + 1)
+  })
+
+  it('replaces skipPollingIfUnfocused when the subscription options are updated', async () => {
+    const { requestId, queryCacheKey, ...subscription } =
+      storeRef.store.dispatch(
+        getPosts.initiate(1, {
+          subscriptionOptions: {
+            pollingInterval: 10,
+            skipPollingIfUnfocused: false,
+          },
+          subscribe: true,
+        }),
+      )
+
+    const getSubs = createSubscriptionGetter(queryCacheKey)
+
+    await delay(1)
+    expect(getSubs().size).toBe(1)
+    expect(getSubs().get(requestId)?.skipPollingIfUnfocused).toBe(false)
+
+    subscription.updateSubscriptionOptions({
+      pollingInterval: 20,
+      skipPollingIfUnfocused: true,
+    })
+
+    await delay(1)
+    expect(getSubs().size).toBe(1)
+    expect(getSubs().get(requestId)?.skipPollingIfUnfocused).toBe(true)
+  })
+
+  it('should minimize polling recalculations when adding multiple subscribers', async () => {
+    // Reset any existing state
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    const SUBSCRIBER_COUNT = 10
+    const subscriptions: QueryActionCreatorResult<any>[] = []
+
+    // Add 10 subscribers to the same endpoint with polling enabled
+    for (let i = 0; i < SUBSCRIBER_COUNT; i++) {
+      const subscription = storeRef.store.dispatch(
+        getPosts.initiate(1, {
+          subscriptionOptions: { pollingInterval: 1000 },
+          subscribe: true,
+        }),
+      )
+      subscriptions.push(subscription)
+    }
+
+    // Wait a bit for all subscriptions to be processed
+    await Promise.all(subscriptions)
+
+    // Wait for the poll update timer
+    await delay(25)
+
+    // Get the polling state using the secret "getPolling" action
+    const currentPolls = storeRef.store.dispatch({
+      type: `${api.reducerPath}/getPolling`,
+    }) as any
+
+    // Get the query cache key for our endpoint
+    const queryCacheKey = subscriptions[0].queryCacheKey
+
+    // Check the poll update counters
+    const pollUpdateCounters = currentPolls.pollUpdateCounters || {}
+    const updateCount = pollUpdateCounters[queryCacheKey] || 0
+
+    // With batching optimization, this should be much lower than SUBSCRIBER_COUNT
+    // Ideally 1, but could be slightly higher due to timing
+    expect(updateCount).toBeGreaterThanOrEqual(1)
+    expect(updateCount).toBeLessThanOrEqual(2)
+
+    // Clean up subscriptions
+    subscriptions.forEach((sub) => sub.unsubscribe())
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/queryFn.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/queryFn.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/queryFn.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,445 @@
+import { noop } from '@internal/listenerMiddleware/utils'
+import type { QuerySubState } from '@internal/query/core/apiState'
+import type { Post } from '@internal/query/tests/mocks/handlers'
+import { posts } from '@internal/query/tests/mocks/handlers'
+import { actionsReducer, setupApiStore } from '@internal/tests/utils/helpers'
+import type { SerializedError } from '@reduxjs/toolkit'
+import { configureStore } from '@reduxjs/toolkit'
+import type { BaseQueryFn, FetchBaseQueryError } from '@reduxjs/toolkit/query'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+
+describe('queryFn base implementation tests', () => {
+  const baseQuery: BaseQueryFn<string, { wrappedByBaseQuery: string }, string> =
+    vi.fn((arg: string) =>
+      arg.includes('withErrorQuery')
+        ? { error: `cut${arg}` }
+        : { data: { wrappedByBaseQuery: arg } },
+    )
+
+  const api = createApi({
+    baseQuery,
+    endpoints: (build) => ({
+      withQuery: build.query<string, string>({
+        query(arg: string) {
+          return `resultFrom(${arg})`
+        },
+        transformResponse(response) {
+          return response.wrappedByBaseQuery
+        },
+      }),
+      withErrorQuery: build.query<string, string>({
+        query(arg: string) {
+          return `resultFrom(${arg})`
+        },
+        transformErrorResponse(response) {
+          return response.slice(3)
+        },
+      }),
+      withQueryFn: build.query<string, string>({
+        queryFn(arg: string) {
+          return { data: `resultFrom(${arg})` }
+        },
+      }),
+      withInvalidDataQueryFn: build.query<string, string>({
+        // @ts-expect-error
+        queryFn(arg: string) {
+          return { data: 5 }
+        },
+      }),
+      withErrorQueryFn: build.query<string, string>({
+        queryFn(arg: string) {
+          return { error: `resultFrom(${arg})` }
+        },
+      }),
+      withInvalidErrorQueryFn: build.query<string, string>({
+        // @ts-expect-error
+        queryFn(arg: string) {
+          return { error: 5 }
+        },
+      }),
+      withThrowingQueryFn: build.query<string, string>({
+        queryFn(arg: string) {
+          throw new Error(`resultFrom(${arg})`)
+        },
+      }),
+      withAsyncQueryFn: build.query<string, string>({
+        async queryFn(arg: string) {
+          return { data: `resultFrom(${arg})` }
+        },
+      }),
+      withInvalidDataAsyncQueryFn: build.query<string, string>({
+        // @ts-expect-error
+        async queryFn(arg: string) {
+          return { data: 5 }
+        },
+      }),
+      withAsyncErrorQueryFn: build.query<string, string>({
+        async queryFn(arg: string) {
+          return { error: `resultFrom(${arg})` }
+        },
+      }),
+      withInvalidAsyncErrorQueryFn: build.query<string, string>({
+        // @ts-expect-error
+        async queryFn(arg: string) {
+          return { error: 5 }
+        },
+      }),
+      withAsyncThrowingQueryFn: build.query<string, string>({
+        async queryFn(arg: string) {
+          throw new Error(`resultFrom(${arg})`)
+        },
+      }),
+      mutationWithQueryFn: build.mutation<string, string>({
+        queryFn(arg: string) {
+          return { data: `resultFrom(${arg})` }
+        },
+      }),
+      mutationWithInvalidDataQueryFn: build.mutation<string, string>({
+        // @ts-expect-error
+        queryFn(arg: string) {
+          return { data: 5 }
+        },
+      }),
+      mutationWithErrorQueryFn: build.mutation<string, string>({
+        queryFn(arg: string) {
+          return { error: `resultFrom(${arg})` }
+        },
+      }),
+      mutationWithInvalidErrorQueryFn: build.mutation<string, string>({
+        // @ts-expect-error
+        queryFn(arg: string) {
+          return { error: 5 }
+        },
+      }),
+      mutationWithThrowingQueryFn: build.mutation<string, string>({
+        queryFn(arg: string) {
+          throw new Error(`resultFrom(${arg})`)
+        },
+      }),
+      mutationWithAsyncQueryFn: build.mutation<string, string>({
+        async queryFn(arg: string) {
+          return { data: `resultFrom(${arg})` }
+        },
+      }),
+      mutationWithInvalidAsyncQueryFn: build.mutation<string, string>({
+        // @ts-expect-error
+        async queryFn(arg: string) {
+          return { data: 5 }
+        },
+      }),
+      mutationWithAsyncErrorQueryFn: build.mutation<string, string>({
+        async queryFn(arg: string) {
+          return { error: `resultFrom(${arg})` }
+        },
+      }),
+      mutationWithInvalidAsyncErrorQueryFn: build.mutation<string, string>({
+        // @ts-expect-error
+        async queryFn(arg: string) {
+          return { error: 5 }
+        },
+      }),
+      mutationWithAsyncThrowingQueryFn: build.mutation<string, string>({
+        async queryFn(arg: string) {
+          throw new Error(`resultFrom(${arg})`)
+        },
+      }),
+      // @ts-expect-error
+      withNeither: build.query<string, string>({}),
+      // @ts-expect-error
+      mutationWithNeither: build.mutation<string, string>({}),
+    }),
+  })
+
+  const {
+    withQuery,
+    withErrorQuery,
+    withQueryFn,
+    withErrorQueryFn,
+    withThrowingQueryFn,
+    withAsyncQueryFn,
+    withAsyncErrorQueryFn,
+    withAsyncThrowingQueryFn,
+    mutationWithQueryFn,
+    mutationWithErrorQueryFn,
+    mutationWithThrowingQueryFn,
+    mutationWithAsyncQueryFn,
+    mutationWithAsyncErrorQueryFn,
+    mutationWithAsyncThrowingQueryFn,
+    withNeither,
+    mutationWithNeither,
+  } = api.endpoints
+
+  const store = configureStore({
+    reducer: {
+      [api.reducerPath]: api.reducer,
+    },
+    middleware: (gDM) => gDM({}).concat(api.middleware),
+  })
+
+  test.each([
+    ['withQuery', withQuery, 'data'],
+    ['withErrorQuery', withErrorQuery, 'error'],
+    ['withQueryFn', withQueryFn, 'data'],
+    ['withErrorQueryFn', withErrorQueryFn, 'error'],
+    ['withThrowingQueryFn', withThrowingQueryFn, 'throw'],
+    ['withAsyncQueryFn', withAsyncQueryFn, 'data'],
+    ['withAsyncErrorQueryFn', withAsyncErrorQueryFn, 'error'],
+    ['withAsyncThrowingQueryFn', withAsyncThrowingQueryFn, 'throw'],
+  ])('%s', async (endpointName, endpoint, expectedResult) => {
+    const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
+
+    const thunk = endpoint.initiate(endpointName)
+
+    const result: undefined | QuerySubState<any> = await store.dispatch(thunk)
+
+    if (endpointName.includes('Throw')) {
+      expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+      expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+        `An unhandled error occurred processing a request for the endpoint "${endpointName}".\nIn the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+        Error(`resultFrom(${endpointName})`),
+      )
+    } else {
+      expect(consoleErrorSpy).not.toHaveBeenCalled()
+    }
+
+    if (expectedResult === 'data') {
+      expect(result).toEqual(
+        expect.objectContaining({
+          data: `resultFrom(${endpointName})`,
+        }),
+      )
+    } else if (expectedResult === 'error') {
+      expect(result).toEqual(
+        expect.objectContaining({
+          error: `resultFrom(${endpointName})`,
+        }),
+      )
+    } else {
+      expect(result).toEqual(
+        expect.objectContaining({
+          error: expect.objectContaining({
+            message: `resultFrom(${endpointName})`,
+          }),
+        }),
+      )
+    }
+
+    consoleErrorSpy.mockRestore()
+  })
+
+  test.each([
+    ['mutationWithQueryFn', mutationWithQueryFn, 'data'],
+    ['mutationWithErrorQueryFn', mutationWithErrorQueryFn, 'error'],
+    ['mutationWithThrowingQueryFn', mutationWithThrowingQueryFn, 'throw'],
+    ['mutationWithAsyncQueryFn', mutationWithAsyncQueryFn, 'data'],
+    ['mutationWithAsyncErrorQueryFn', mutationWithAsyncErrorQueryFn, 'error'],
+    [
+      'mutationWithAsyncThrowingQueryFn',
+      mutationWithAsyncThrowingQueryFn,
+      'throw',
+    ],
+  ])('%s', async (endpointName, endpoint, expectedResult) => {
+    const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
+
+    const thunk = endpoint.initiate(endpointName)
+
+    const result:
+      | undefined
+      | { data: string }
+      | { error: string | SerializedError } = await store.dispatch(thunk)
+
+    if (endpointName.includes('Throw')) {
+      expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+      expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+        `An unhandled error occurred processing a request for the endpoint "${endpointName}".\nIn the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+        Error(`resultFrom(${endpointName})`),
+      )
+    } else {
+      expect(consoleErrorSpy).not.toHaveBeenCalled()
+    }
+
+    if (expectedResult === 'data') {
+      expect(result).toEqual(
+        expect.objectContaining({
+          data: `resultFrom(${endpointName})`,
+        }),
+      )
+    } else if (expectedResult === 'error') {
+      expect(result).toEqual(
+        expect.objectContaining({
+          error: `resultFrom(${endpointName})`,
+        }),
+      )
+    } else {
+      expect(result).toEqual(
+        expect.objectContaining({
+          error: expect.objectContaining({
+            message: `resultFrom(${endpointName})`,
+          }),
+        }),
+      )
+    }
+
+    consoleErrorSpy.mockRestore()
+  })
+
+  test('neither provided', async () => {
+    const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
+
+    {
+      const thunk = withNeither.initiate('withNeither')
+
+      const result: QuerySubState<any> = await store.dispatch(thunk)
+
+      expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+      expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+        `An unhandled error occurred processing a request for the endpoint "withNeither".\nIn the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+        TypeError('endpointDefinition.queryFn is not a function'),
+      )
+
+      expect(result.error).toEqual(
+        expect.objectContaining({
+          message: 'endpointDefinition.queryFn is not a function',
+        }),
+      )
+
+      consoleErrorSpy.mockClear()
+    }
+    {
+      const thunk = mutationWithNeither.initiate('mutationWithNeither')
+
+      const result:
+        | undefined
+        | { data: string }
+        | { error: string | SerializedError } = await store.dispatch(thunk)
+
+      expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+      expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+        `An unhandled error occurred processing a request for the endpoint "mutationWithNeither".\nIn the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+        TypeError('endpointDefinition.queryFn is not a function'),
+      )
+
+      if (!('error' in result)) {
+        expect.fail()
+      }
+
+      expect(result.error).toEqual(
+        expect.objectContaining({
+          message: 'endpointDefinition.queryFn is not a function',
+        }),
+      )
+    }
+
+    consoleErrorSpy.mockRestore()
+  })
+})
+
+describe('usage scenario tests', () => {
+  const mockData = { id: 1, name: 'Banana' }
+  const mockDocResult = {
+    exists: () => true,
+    data: () => mockData,
+  }
+  const get = vi.fn(() => Promise.resolve(mockDocResult))
+  const doc = vi.fn((name) => ({
+    get,
+  }))
+  const collection = vi.fn((name) => ({ get, doc }))
+  const firestore = () => {
+    return { collection, doc }
+  }
+
+  const baseQuery = fetchBaseQuery({ baseUrl: 'https://example.com/' })
+  const api = createApi({
+    baseQuery,
+    endpoints: (build) => ({
+      getRandomUser: build.query<Post, void>({
+        async queryFn(_arg: void, _queryApi, _extraOptions, fetchWithBQ) {
+          // get a random post
+          const randomResult = await fetchWithBQ('posts/random')
+          if (randomResult.error) {
+            throw randomResult.error
+          }
+          const post = randomResult.data as Post
+          const result = await fetchWithBQ(`/post/${post.id}`)
+          return result.data
+            ? { data: result.data as Post }
+            : { error: result.error as FetchBaseQueryError }
+        },
+      }),
+      getFirebaseUser: build.query<typeof mockData, number>({
+        async queryFn(arg: number) {
+          const getResult = await firestore().collection('users').doc(arg).get()
+          if (!getResult.exists()) {
+            throw new Error('Missing user')
+          }
+          return { data: getResult.data() }
+        },
+      }),
+      getMissingFirebaseUser: build.query<typeof mockData, number>({
+        async queryFn(arg: number) {
+          const getResult = await firestore().collection('users').doc(arg).get()
+          // intentionally throw if it exists to keep the mocking overhead low
+          if (getResult.exists()) {
+            throw new Error('Missing user')
+          }
+          return { data: getResult.data() }
+        },
+      }),
+    }),
+  })
+
+  const storeRef = setupApiStore(api, {
+    ...actionsReducer,
+  })
+
+  /**
+   * Allow for a scenario where you can chain X requests
+   * https://discord.com/channels/102860784329052160/103538784460615680/825430959247720449
+   * const resp1 = await api.get(url);
+   * const resp2 = await api.get(`${url2}/id=${resp1.data.id}`);
+   */
+
+  it('can chain multiple queries together', async () => {
+    const result = await storeRef.store.dispatch(
+      api.endpoints.getRandomUser.initiate(),
+    )
+    expect(result.data).toEqual(posts[1])
+  })
+
+  it('can wrap a service like Firebase', async () => {
+    const result = await storeRef.store.dispatch(
+      api.endpoints.getFirebaseUser.initiate(1),
+    )
+    expect(result.data).toEqual(mockData)
+  })
+
+  it('can wrap a service like Firebase and handle errors', async () => {
+    const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
+
+    const result: QuerySubState<any> = await storeRef.store.dispatch(
+      api.endpoints.getMissingFirebaseUser.initiate(1),
+    )
+
+    expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+    expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+      `An unhandled error occurred processing a request for the endpoint "getMissingFirebaseUser".\nIn the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+      Error('Missing user'),
+    )
+
+    expect(result.data).toBeUndefined()
+    expect(result.error).toEqual(
+      expect.objectContaining({
+        message: 'Missing user',
+        name: 'Error',
+      }),
+    )
+
+    consoleErrorSpy.mockRestore()
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/queryLifecycle.test-d.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/queryLifecycle.test-d.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/queryLifecycle.test-d.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,371 @@
+import type { PatchCollection, Recipe } from '@internal/query/core/buildThunks'
+import type { ThunkDispatch, UnknownAction } from '@reduxjs/toolkit'
+import type {
+  FetchBaseQueryError,
+  FetchBaseQueryMeta,
+  RootState,
+  TypedMutationOnQueryStarted,
+  TypedQueryOnQueryStarted,
+} from '@reduxjs/toolkit/query'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+
+const api = createApi({
+  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+  endpoints: () => ({}),
+})
+
+describe('type tests', () => {
+  test(`mutation: onStart and onSuccess`, async () => {
+    const extended = api.injectEndpoints({
+      overrideExisting: true,
+      endpoints: (build) => ({
+        injected: build.mutation<number, string>({
+          query: () => '/success',
+          async onQueryStarted(arg, { queryFulfilled }) {
+            // awaiting without catching like this would result in an `unhandledRejection` exception if there was an error
+            // unfortunately we cannot test for that in jest.
+            const result = await queryFulfilled
+
+            expectTypeOf(result).toMatchTypeOf<{
+              data: number
+              meta?: FetchBaseQueryMeta
+            }>()
+          },
+        }),
+      }),
+    })
+  })
+
+  test('query types', () => {
+    const extended = api.injectEndpoints({
+      overrideExisting: true,
+      endpoints: (build) => ({
+        injected: build.query<number, string>({
+          query: () => '/success',
+          async onQueryStarted(arg, { queryFulfilled }) {
+            queryFulfilled.then(
+              (result) => {
+                expectTypeOf(result).toMatchTypeOf<{
+                  data: number
+                  meta?: FetchBaseQueryMeta
+                }>()
+              },
+              (reason) => {
+                if (reason.isUnhandledError) {
+                  expectTypeOf(reason).toEqualTypeOf<{
+                    error: unknown
+                    meta?: undefined
+                    isUnhandledError: true
+                  }>()
+                } else {
+                  expectTypeOf(reason).toEqualTypeOf<{
+                    error: FetchBaseQueryError
+                    isUnhandledError: false
+                    meta: FetchBaseQueryMeta | undefined
+                  }>()
+                }
+              },
+            )
+
+            queryFulfilled.catch((reason) => {
+              if (reason.isUnhandledError) {
+                expectTypeOf(reason).toEqualTypeOf<{
+                  error: unknown
+                  meta?: undefined
+                  isUnhandledError: true
+                }>()
+              } else {
+                expectTypeOf(reason).toEqualTypeOf<{
+                  error: FetchBaseQueryError
+                  isUnhandledError: false
+                  meta: FetchBaseQueryMeta | undefined
+                }>()
+              }
+            })
+
+            const result = await queryFulfilled
+
+            expectTypeOf(result).toMatchTypeOf<{
+              data: number
+              meta?: FetchBaseQueryMeta
+            }>()
+          },
+        }),
+      }),
+    })
+  })
+
+  test('mutation types', () => {
+    const extended = api.injectEndpoints({
+      overrideExisting: true,
+      endpoints: (build) => ({
+        injected: build.query<number, string>({
+          query: () => '/success',
+          async onQueryStarted(arg, { queryFulfilled }) {
+            queryFulfilled.then(
+              (result) => {
+                expectTypeOf(result).toMatchTypeOf<{
+                  data: number
+                  meta?: FetchBaseQueryMeta
+                }>()
+              },
+              (reason) => {
+                if (reason.isUnhandledError) {
+                  expectTypeOf(reason).toEqualTypeOf<{
+                    error: unknown
+                    meta?: undefined
+                    isUnhandledError: true
+                  }>()
+                } else {
+                  expectTypeOf(reason).toEqualTypeOf<{
+                    error: FetchBaseQueryError
+                    isUnhandledError: false
+                    meta: FetchBaseQueryMeta | undefined
+                  }>()
+                }
+              },
+            )
+
+            queryFulfilled.catch((reason) => {
+              if (reason.isUnhandledError) {
+                expectTypeOf(reason).toEqualTypeOf<{
+                  error: unknown
+                  meta?: undefined
+                  isUnhandledError: true
+                }>()
+              } else {
+                expectTypeOf(reason).toEqualTypeOf<{
+                  error: FetchBaseQueryError
+                  isUnhandledError: false
+                  meta: FetchBaseQueryMeta | undefined
+                }>()
+              }
+            })
+
+            const result = await queryFulfilled
+
+            expectTypeOf(result).toMatchTypeOf<{
+              data: number
+              meta?: FetchBaseQueryMeta
+            }>()
+          },
+        }),
+      }),
+    })
+  })
+
+  describe('typed `onQueryStarted` function', () => {
+    test('TypedQueryOnQueryStarted creates a pre-typed version of onQueryStarted', () => {
+      type Post = {
+        id: number
+        title: string
+        userId: number
+      }
+
+      type PostsApiResponse = {
+        posts: Post[]
+        total: number
+        skip: number
+        limit: number
+      }
+
+      type QueryArgument = number | undefined
+
+      type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>
+
+      const baseApiSlice = createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),
+        reducerPath: 'postsApi',
+        tagTypes: ['Posts'],
+        endpoints: (builder) => ({
+          getPosts: builder.query<PostsApiResponse, void>({
+            query: () => `/posts`,
+          }),
+
+          getPostById: builder.query<Post, QueryArgument>({
+            query: (postId) => `/posts/${postId}`,
+          }),
+        }),
+      })
+
+      const updatePostOnFulfilled: TypedQueryOnQueryStarted<
+        PostsApiResponse,
+        QueryArgument,
+        BaseQueryFunction,
+        'postsApi'
+      > = async (queryArgument, queryLifeCycleApi) => {
+        const {
+          dispatch,
+          extra,
+          getCacheEntry,
+          getState,
+          queryFulfilled,
+          requestId,
+          updateCachedData,
+        } = queryLifeCycleApi
+
+        expectTypeOf(queryArgument).toEqualTypeOf<QueryArgument>()
+
+        expectTypeOf(dispatch).toEqualTypeOf<
+          ThunkDispatch<any, any, UnknownAction>
+        >()
+
+        expectTypeOf(extra).toBeUnknown()
+
+        expectTypeOf(getState).toEqualTypeOf<
+          () => RootState<any, any, 'postsApi'>
+        >()
+
+        expectTypeOf(requestId).toBeString()
+
+        expectTypeOf(getCacheEntry).toBeFunction()
+
+        expectTypeOf(updateCachedData).toEqualTypeOf<
+          (updateRecipe: Recipe<PostsApiResponse>) => PatchCollection
+        >()
+
+        expectTypeOf(queryFulfilled).resolves.toEqualTypeOf<{
+          data: PostsApiResponse
+          meta: FetchBaseQueryMeta | undefined
+        }>()
+
+        const result = await queryFulfilled
+
+        const { posts } = result.data
+
+        dispatch(
+          baseApiSlice.util.upsertQueryEntries(
+            posts.map((post) => ({
+              // Without `as const` this will result in a TS error in TS 4.7.
+              endpointName: 'getPostById' as const,
+              arg: post.id,
+              value: post,
+            })),
+          ),
+        )
+      }
+
+      const extendedApiSlice = baseApiSlice.injectEndpoints({
+        endpoints: (builder) => ({
+          getPostsByUserId: builder.query<PostsApiResponse, QueryArgument>({
+            query: (userId) => `/posts/user/${userId}`,
+
+            onQueryStarted: updatePostOnFulfilled,
+          }),
+        }),
+      })
+    })
+
+    test('TypedMutationOnQueryStarted creates a pre-typed version of onQueryStarted', () => {
+      type Post = {
+        id: number
+        title: string
+        userId: number
+      }
+
+      type PostsApiResponse = {
+        posts: Post[]
+        total: number
+        skip: number
+        limit: number
+      }
+
+      type QueryArgument = Pick<Post, 'id'> & Partial<Post>
+
+      type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>
+
+      const baseApiSlice = createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),
+        reducerPath: 'postsApi',
+        tagTypes: ['Posts'],
+        endpoints: (builder) => ({
+          getPosts: builder.query<PostsApiResponse, void>({
+            query: () => `/posts`,
+          }),
+
+          getPostById: builder.query<Post, number>({
+            query: (postId) => `/posts/${postId}`,
+          }),
+        }),
+      })
+
+      const updatePostOnFulfilled: TypedMutationOnQueryStarted<
+        Post,
+        QueryArgument,
+        BaseQueryFunction,
+        'postsApi'
+      > = async (queryArgument, mutationLifeCycleApi) => {
+        const { id, ...patch } = queryArgument
+        const {
+          dispatch,
+          extra,
+          getCacheEntry,
+          getState,
+          queryFulfilled,
+          requestId,
+        } = mutationLifeCycleApi
+
+        const patchCollection = dispatch(
+          baseApiSlice.util.updateQueryData('getPostById', id, (draftPost) => {
+            Object.assign(draftPost, patch)
+          }),
+        )
+
+        expectTypeOf(queryFulfilled).resolves.toEqualTypeOf<{
+          data: Post
+          meta: FetchBaseQueryMeta | undefined
+        }>()
+
+        expectTypeOf(queryArgument).toEqualTypeOf<QueryArgument>()
+
+        expectTypeOf(dispatch).toEqualTypeOf<
+          ThunkDispatch<any, any, UnknownAction>
+        >()
+
+        expectTypeOf(extra).toBeUnknown()
+
+        expectTypeOf(getState).toEqualTypeOf<
+          () => RootState<any, any, 'postsApi'>
+        >()
+
+        expectTypeOf(requestId).toBeString()
+
+        expectTypeOf(getCacheEntry).toBeFunction()
+
+        expectTypeOf(mutationLifeCycleApi).not.toHaveProperty(
+          'updateCachedData',
+        )
+
+        try {
+          await queryFulfilled
+        } catch {
+          patchCollection.undo()
+        }
+      }
+
+      const extendedApiSlice = baseApiSlice.injectEndpoints({
+        endpoints: (builder) => ({
+          addPost: builder.mutation<Post, Omit<QueryArgument, 'id'>>({
+            query: (body) => ({
+              url: `posts/add`,
+              method: 'POST',
+              body,
+            }),
+
+            onQueryStarted: updatePostOnFulfilled,
+          }),
+
+          updatePost: builder.mutation<Post, QueryArgument>({
+            query: ({ id, ...patch }) => ({
+              url: `post/${id}`,
+              method: 'PATCH',
+              body: patch,
+            }),
+
+            onQueryStarted: updatePostOnFulfilled,
+          }),
+        }),
+      })
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/queryLifecycle.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/queryLifecycle.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/queryLifecycle.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,547 @@
+import { server } from '@internal/query/tests/mocks/server'
+import { setupApiStore } from '@internal/tests/utils/helpers'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+import { waitFor } from '@testing-library/react'
+import { HttpResponse, http } from 'msw'
+import { vi } from 'vitest'
+
+const api = createApi({
+  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+  endpoints: () => ({}),
+})
+const storeRef = setupApiStore(api)
+
+const onStart = vi.fn()
+const onSuccess = vi.fn()
+const onError = vi.fn()
+
+beforeEach(() => {
+  onStart.mockClear()
+  onSuccess.mockClear()
+  onError.mockClear()
+})
+
+describe.each([['query'], ['mutation']] as const)(
+  'generic cases: %s',
+  (type) => {
+    test(`${type}: onStart only`, async () => {
+      const extended = api.injectEndpoints({
+        overrideExisting: true,
+        endpoints: (build) => ({
+          injected: build[type as 'mutation']<unknown, string>({
+            query: () => '/success',
+            onQueryStarted(arg) {
+              onStart(arg)
+            },
+          }),
+        }),
+      })
+      storeRef.store.dispatch(extended.endpoints.injected.initiate('arg'))
+      expect(onStart).toHaveBeenCalledWith('arg')
+    })
+
+    test(`${type}: onStart and onSuccess`, async () => {
+      const extended = api.injectEndpoints({
+        overrideExisting: true,
+        endpoints: (build) => ({
+          injected: build[type as 'mutation']<number, string>({
+            query: () => '/success',
+            async onQueryStarted(arg, { queryFulfilled }) {
+              onStart(arg)
+              // awaiting without catching like this would result in an `unhandledRejection` exception if there was an error
+              // unfortunately we cannot test for that in jest.
+              const result = await queryFulfilled
+              onSuccess(result)
+            },
+          }),
+        }),
+      })
+      storeRef.store.dispatch(extended.endpoints.injected.initiate('arg'))
+      expect(onStart).toHaveBeenCalledWith('arg')
+      await waitFor(() => {
+        expect(onSuccess).toHaveBeenCalledWith({
+          data: { value: 'success' },
+          meta: {
+            request: expect.any(Request),
+            response: expect.any(Object), // Response is not available in jest env
+          },
+        })
+      })
+    })
+
+    test(`${type}: onStart and onError`, async () => {
+      const extended = api.injectEndpoints({
+        overrideExisting: true,
+        endpoints: (build) => ({
+          injected: build[type as 'mutation']<unknown, string>({
+            query: () => '/error',
+            async onQueryStarted(arg, { queryFulfilled }) {
+              onStart(arg)
+              try {
+                const result = await queryFulfilled
+                onSuccess(result)
+              } catch (e) {
+                onError(e)
+              }
+            },
+          }),
+        }),
+      })
+      storeRef.store.dispatch(extended.endpoints.injected.initiate('arg'))
+      expect(onStart).toHaveBeenCalledWith('arg')
+      await waitFor(() => {
+        expect(onError).toHaveBeenCalledWith({
+          error: {
+            status: 500,
+            data: { value: 'error' },
+          },
+          isUnhandledError: false,
+          meta: {
+            request: expect.any(Request),
+            response: expect.any(Object), // Response is not available in jest env
+          },
+        })
+      })
+      expect(onSuccess).not.toHaveBeenCalled()
+    })
+  },
+)
+
+test('query: getCacheEntry (success)', async () => {
+  const snapshot = vi.fn()
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      injected: build.query<unknown, string>({
+        query: () => '/success',
+        async onQueryStarted(
+          arg,
+          { dispatch, getState, getCacheEntry, queryFulfilled },
+        ) {
+          try {
+            snapshot(getCacheEntry())
+            const result = await queryFulfilled
+            onSuccess(result)
+            snapshot(getCacheEntry())
+          } catch (e) {
+            onError(e)
+            snapshot(getCacheEntry())
+          }
+        },
+      }),
+    }),
+  })
+  const promise = storeRef.store.dispatch(
+    extended.endpoints.injected.initiate('arg'),
+  )
+
+  await waitFor(() => {
+    expect(onSuccess).toHaveBeenCalled()
+  })
+
+  expect(snapshot).toHaveBeenCalledTimes(2)
+  expect(snapshot.mock.calls[0][0]).toMatchObject({
+    endpointName: 'injected',
+    isError: false,
+    isLoading: true,
+    isSuccess: false,
+    isUninitialized: false,
+    originalArgs: 'arg',
+    requestId: promise.requestId,
+    startedTimeStamp: expect.any(Number),
+    status: 'pending',
+  })
+  expect(snapshot.mock.calls[1][0]).toMatchObject({
+    data: {
+      value: 'success',
+    },
+    endpointName: 'injected',
+    fulfilledTimeStamp: expect.any(Number),
+    isError: false,
+    isLoading: false,
+    isSuccess: true,
+    isUninitialized: false,
+    originalArgs: 'arg',
+    requestId: promise.requestId,
+    startedTimeStamp: expect.any(Number),
+    status: 'fulfilled',
+  })
+})
+
+test('query: getCacheEntry (error)', async () => {
+  const snapshot = vi.fn()
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      injected: build.query<unknown, string>({
+        query: () => '/error',
+        async onQueryStarted(
+          arg,
+          { dispatch, getState, getCacheEntry, queryFulfilled },
+        ) {
+          try {
+            snapshot(getCacheEntry())
+            const result = await queryFulfilled
+            onSuccess(result)
+            snapshot(getCacheEntry())
+          } catch (e) {
+            onError(e)
+            snapshot(getCacheEntry())
+          }
+        },
+      }),
+    }),
+  })
+  const promise = storeRef.store.dispatch(
+    extended.endpoints.injected.initiate('arg'),
+  )
+
+  await waitFor(() => {
+    expect(onError).toHaveBeenCalled()
+  })
+
+  expect(snapshot.mock.calls[0][0]).toMatchObject({
+    endpointName: 'injected',
+    isError: false,
+    isLoading: true,
+    isSuccess: false,
+    isUninitialized: false,
+    originalArgs: 'arg',
+    requestId: promise.requestId,
+    startedTimeStamp: expect.any(Number),
+    status: 'pending',
+  })
+  expect(snapshot.mock.calls[1][0]).toMatchObject({
+    error: {
+      data: { value: 'error' },
+      status: 500,
+    },
+    endpointName: 'injected',
+    isError: true,
+    isLoading: false,
+    isSuccess: false,
+    isUninitialized: false,
+    originalArgs: 'arg',
+    requestId: promise.requestId,
+    startedTimeStamp: expect.any(Number),
+    status: 'rejected',
+  })
+})
+
+test('mutation: getCacheEntry (success)', async () => {
+  const snapshot = vi.fn()
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      injected: build.mutation<unknown, string>({
+        query: () => '/success',
+        async onQueryStarted(
+          arg,
+          { dispatch, getState, getCacheEntry, queryFulfilled },
+        ) {
+          try {
+            snapshot(getCacheEntry())
+            const result = await queryFulfilled
+            onSuccess(result)
+            snapshot(getCacheEntry())
+          } catch (e) {
+            onError(e)
+            snapshot(getCacheEntry())
+          }
+        },
+      }),
+    }),
+  })
+  const promise = storeRef.store.dispatch(
+    extended.endpoints.injected.initiate('arg'),
+  )
+
+  await waitFor(() => {
+    expect(onSuccess).toHaveBeenCalled()
+  })
+
+  expect(snapshot).toHaveBeenCalledTimes(2)
+  expect(snapshot.mock.calls[0][0]).toMatchObject({
+    endpointName: 'injected',
+    isError: false,
+    isLoading: true,
+    isSuccess: false,
+    isUninitialized: false,
+    startedTimeStamp: expect.any(Number),
+    status: 'pending',
+  })
+  expect(snapshot.mock.calls[1][0]).toMatchObject({
+    data: {
+      value: 'success',
+    },
+    endpointName: 'injected',
+    fulfilledTimeStamp: expect.any(Number),
+    isError: false,
+    isLoading: false,
+    isSuccess: true,
+    isUninitialized: false,
+    startedTimeStamp: expect.any(Number),
+    status: 'fulfilled',
+  })
+})
+
+test('mutation: getCacheEntry (error)', async () => {
+  const snapshot = vi.fn()
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      injected: build.mutation<unknown, string>({
+        query: () => '/error',
+        async onQueryStarted(
+          arg,
+          { dispatch, getState, getCacheEntry, queryFulfilled },
+        ) {
+          try {
+            snapshot(getCacheEntry())
+            const result = await queryFulfilled
+            onSuccess(result)
+            snapshot(getCacheEntry())
+          } catch (e) {
+            onError(e)
+            snapshot(getCacheEntry())
+          }
+        },
+      }),
+    }),
+  })
+  const promise = storeRef.store.dispatch(
+    extended.endpoints.injected.initiate('arg'),
+  )
+
+  await waitFor(() => {
+    expect(onError).toHaveBeenCalled()
+  })
+
+  expect(snapshot.mock.calls[0][0]).toMatchObject({
+    endpointName: 'injected',
+    isError: false,
+    isLoading: true,
+    isSuccess: false,
+    isUninitialized: false,
+    startedTimeStamp: expect.any(Number),
+    status: 'pending',
+  })
+  expect(snapshot.mock.calls[1][0]).toMatchObject({
+    error: {
+      data: { value: 'error' },
+      status: 500,
+    },
+    endpointName: 'injected',
+    isError: true,
+    isLoading: false,
+    isSuccess: false,
+    isUninitialized: false,
+    startedTimeStamp: expect.any(Number),
+    status: 'rejected',
+  })
+})
+
+test('query: updateCachedData', async () => {
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      injected: build.query<{ value: string }, string>({
+        query: () => '/success',
+        async onQueryStarted(
+          arg,
+          {
+            dispatch,
+            getState,
+            getCacheEntry,
+            updateCachedData,
+            queryFulfilled,
+          },
+        ) {
+          // calling `updateCachedData` when there is no data yet should not do anything
+          // but if there is a cache value it will be updated & overwritten by the next successful result
+          updateCachedData((draft) => {
+            draft.value += '.'
+          })
+
+          try {
+            await queryFulfilled
+            onSuccess(getCacheEntry().data)
+          } catch (error) {
+            updateCachedData((draft) => {
+              draft.value += 'x'
+            })
+            onError(getCacheEntry().data)
+          }
+        },
+      }),
+    }),
+  })
+
+  // request 1: success
+  expect(onSuccess).not.toHaveBeenCalled()
+  storeRef.store.dispatch(extended.endpoints.injected.initiate('arg'))
+
+  await waitFor(() => {
+    expect(onSuccess).toHaveBeenCalled()
+  })
+  expect(onSuccess).toHaveBeenCalledWith({ value: 'success' })
+  onSuccess.mockClear()
+
+  // request 2: error
+  expect(onError).not.toHaveBeenCalled()
+  server.use(
+    http.get(
+      'https://example.com/success',
+      () => {
+        return HttpResponse.json({ value: 'failed' }, { status: 500 })
+      },
+      { once: true },
+    ),
+  )
+  storeRef.store.dispatch(
+    extended.endpoints.injected.initiate('arg', { forceRefetch: true }),
+  )
+
+  await waitFor(() => {
+    expect(onError).toHaveBeenCalled()
+  })
+  expect(onError).toHaveBeenCalledWith({ value: 'success.x' })
+
+  // request 3: success
+  expect(onSuccess).not.toHaveBeenCalled()
+
+  storeRef.store.dispatch(
+    extended.endpoints.injected.initiate('arg', { forceRefetch: true }),
+  )
+
+  await waitFor(() => {
+    expect(onSuccess).toHaveBeenCalled()
+  })
+  expect(onSuccess).toHaveBeenCalledWith({ value: 'success' })
+  onSuccess.mockClear()
+})
+
+test('infinite query: updateCachedData', async () => {
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      infiniteInjected: build.infiniteQuery<{ value: string }, string, number>({
+        query: () => '/success',
+        infiniteQueryOptions: {
+          initialPageParam: 1,
+          getNextPageParam: (
+            lastPage,
+            allPages,
+            lastPageParam,
+            allPageParams,
+          ) => lastPageParam + 1,
+        },
+        async onQueryStarted(
+          arg,
+          {
+            dispatch,
+            getState,
+            getCacheEntry,
+            updateCachedData,
+            queryFulfilled,
+          },
+        ) {
+          // calling `updateCachedData` when there is no data yet should not do anything
+          // but if there is a cache value it will be updated & overwritten by the next successful result
+          updateCachedData((draft) => {
+            draft.pages = [{ value: '.' }]
+            draft.pageParams = [1]
+          })
+
+          try {
+            await queryFulfilled
+            onSuccess(getCacheEntry().data)
+          } catch (error) {
+            updateCachedData((draft) => {
+              draft.pages = [{ value: 'success.x' }]
+              draft.pageParams = [1]
+            })
+            onError(getCacheEntry().data)
+          }
+        },
+      }),
+    }),
+  })
+
+  // request 1: success
+  expect(onSuccess).not.toHaveBeenCalled()
+  storeRef.store.dispatch(extended.endpoints.infiniteInjected.initiate('arg'))
+
+  await waitFor(() => {
+    expect(onSuccess).toHaveBeenCalled()
+  })
+  expect(onSuccess).toHaveBeenCalledWith({
+    pages: [{ value: 'success' }],
+    pageParams: [1],
+  })
+  onSuccess.mockClear()
+
+  // request 2: error
+  expect(onError).not.toHaveBeenCalled()
+  server.use(
+    http.get(
+      'https://example.com/success',
+      () => {
+        return HttpResponse.json({ value: 'failed' }, { status: 500 })
+      },
+      { once: true },
+    ),
+  )
+  storeRef.store.dispatch(
+    extended.endpoints.infiniteInjected.initiate('arg', { forceRefetch: true }),
+  )
+
+  await waitFor(() => {
+    expect(onError).toHaveBeenCalled()
+  })
+  expect(onError).toHaveBeenCalledWith({
+    pages: [{ value: 'success.x' }],
+    pageParams: [1],
+  })
+
+  // request 3: success
+  expect(onSuccess).not.toHaveBeenCalled()
+
+  storeRef.store.dispatch(
+    extended.endpoints.infiniteInjected.initiate('arg', { forceRefetch: true }),
+  )
+
+  await waitFor(() => {
+    expect(onSuccess).toHaveBeenCalled()
+  })
+  expect(onSuccess).toHaveBeenCalledWith({
+    pages: [{ value: 'success' }],
+    pageParams: [1],
+  })
+  onSuccess.mockClear()
+})
+
+test('query: will only start lifecycle if query is not skipped due to `condition`', async () => {
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      injected: build.query<unknown, string>({
+        query: () => '/success',
+        onQueryStarted(arg) {
+          onStart(arg)
+        },
+      }),
+    }),
+  })
+  const promise = storeRef.store.dispatch(
+    extended.endpoints.injected.initiate('arg'),
+  )
+  expect(onStart).toHaveBeenCalledOnce()
+  storeRef.store.dispatch(extended.endpoints.injected.initiate('arg'))
+  expect(onStart).toHaveBeenCalledOnce()
+  await promise
+  storeRef.store.dispatch(
+    extended.endpoints.injected.initiate('arg', { forceRefetch: true }),
+  )
+  expect(onStart).toHaveBeenCalledTimes(2)
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/raceConditions.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/raceConditions.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/raceConditions.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,109 @@
+import { createApi, QueryStatus } from '@reduxjs/toolkit/query'
+import { delay } from 'msw'
+import { actionsReducer, setupApiStore } from '../../tests/utils/helpers'
+
+// We need to be able to control when which query resolves to simulate race
+// conditions properly, that's the purpose of this factory.
+const createPromiseFactory = () => {
+  const resolveQueue: (() => void)[] = []
+  const createPromise = () =>
+    new Promise<void>((resolve) => {
+      resolveQueue.push(resolve)
+    })
+  const resolveOldest = () => {
+    resolveQueue.shift()?.()
+  }
+  return { createPromise, resolveOldest }
+}
+
+const getEatenBananaPromises = createPromiseFactory()
+const eatBananaPromises = createPromiseFactory()
+
+let eatenBananas = 0
+const api = createApi({
+  invalidationBehavior: 'delayed',
+  baseQuery: () => undefined as any,
+  tagTypes: ['Banana'],
+  endpoints: (build) => ({
+    // Eat a banana.
+    eatBanana: build.mutation<unknown, void>({
+      queryFn: async () => {
+        await eatBananaPromises.createPromise()
+        eatenBananas += 1
+        return { data: null, meta: {} }
+      },
+      invalidatesTags: ['Banana'],
+    }),
+
+    // Get the number of eaten bananas.
+    getEatenBananas: build.query<number, void>({
+      queryFn: async (arg, arg1, arg2, arg3) => {
+        const result = eatenBananas
+        await getEatenBananaPromises.createPromise()
+        return { data: result }
+      },
+      providesTags: ['Banana'],
+    }),
+  }),
+})
+const { getEatenBananas, eatBanana } = api.endpoints
+
+const storeRef = setupApiStore(api, {
+  ...actionsReducer,
+})
+
+it('invalidates a query after a corresponding mutation', async () => {
+  eatenBananas = 0
+
+  const query = storeRef.store.dispatch(getEatenBananas.initiate())
+  const getQueryState = () =>
+    storeRef.store.getState().api.queries[query.queryCacheKey]
+  getEatenBananaPromises.resolveOldest()
+  await delay(2)
+
+  expect(getQueryState()?.data).toBe(0)
+  expect(getQueryState()?.status).toBe(QueryStatus.fulfilled)
+
+  const mutation = storeRef.store.dispatch(eatBanana.initiate())
+  const getMutationState = () =>
+    storeRef.store.getState().api.mutations[mutation.requestId]
+  eatBananaPromises.resolveOldest()
+  await delay(2)
+
+  expect(getMutationState()?.status).toBe(QueryStatus.fulfilled)
+  expect(getQueryState()?.data).toBe(0)
+  expect(getQueryState()?.status).toBe(QueryStatus.pending)
+
+  getEatenBananaPromises.resolveOldest()
+  await delay(2)
+
+  expect(getQueryState()?.data).toBe(1)
+  expect(getQueryState()?.status).toBe(QueryStatus.fulfilled)
+})
+
+it('invalidates a query whose corresponding mutation finished while the query was in flight', async () => {
+  eatenBananas = 0
+
+  const query = storeRef.store.dispatch(getEatenBananas.initiate())
+  const getQueryState = () =>
+    storeRef.store.getState().api.queries[query.queryCacheKey]
+
+  const mutation = storeRef.store.dispatch(eatBanana.initiate())
+  const getMutationState = () =>
+    storeRef.store.getState().api.mutations[mutation.requestId]
+  eatBananaPromises.resolveOldest()
+  await delay(2)
+  expect(getMutationState()?.status).toBe(QueryStatus.fulfilled)
+
+  getEatenBananaPromises.resolveOldest()
+  await delay(2)
+  expect(getQueryState()?.data).toBe(0)
+  expect(getQueryState()?.status).toBe(QueryStatus.pending)
+
+  // should already be refetching
+  getEatenBananaPromises.resolveOldest()
+  await delay(2)
+
+  expect(getQueryState()?.status).toBe(QueryStatus.fulfilled)
+  expect(getQueryState()?.data).toBe(1)
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/refetchingBehaviors.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/refetchingBehaviors.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/refetchingBehaviors.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,447 @@
+import { createApi, setupListeners } from '@reduxjs/toolkit/query/react'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { delay } from 'msw'
+import { setupApiStore } from '../../tests/utils/helpers'
+
+// Just setup a temporary in-memory counter for tests that `getIncrementedAmount`.
+// This can be used to test how many renders happen due to data changes or
+// the refetching behavior of components.
+let amount = 0
+
+const defaultApi = createApi({
+  baseQuery: async (arg: any) => {
+    await delay(150)
+    if ('amount' in arg?.body) {
+      amount += 1
+    }
+    return {
+      data: arg?.body
+        ? { ...arg.body, ...(amount ? { amount } : {}) }
+        : undefined,
+    }
+  },
+  endpoints: (build) => ({
+    getIncrementedAmount: build.query<any, void>({
+      query: () => ({
+        url: '',
+        body: {
+          amount,
+        },
+      }),
+    }),
+  }),
+  refetchOnFocus: true,
+  refetchOnReconnect: true,
+})
+
+const storeRef = setupApiStore(defaultApi)
+
+const getIncrementedAmountState = () =>
+  storeRef.store.getState().api.queries['getIncrementedAmount(undefined)']
+
+afterEach(() => {
+  amount = 0
+})
+
+describe('refetchOnFocus tests', () => {
+  test('useQuery hook respects refetchOnFocus: true when set in createApi options', async () => {
+    let data, isLoading, isFetching
+
+    function User() {
+      ;({ data, isFetching, isLoading } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery())
+      return (
+        <div>
+          <div data-testid="isLoading">{String(isLoading)}</div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <div data-testid="amount">{String(data?.amount)}</div>
+        </div>
+      )
+    }
+
+    render(<User />, { wrapper: storeRef.wrapper })
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+
+    fireEvent.focus(window)
+
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('2'),
+    )
+  })
+
+  test('useQuery hook respects refetchOnFocus: false from a hook and overrides createApi defaults', async () => {
+    let data, isLoading, isFetching
+
+    function User() {
+      ;({ data, isFetching, isLoading } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {
+          refetchOnFocus: false,
+        }))
+      return (
+        <div>
+          <div data-testid="isLoading">{String(isLoading)}</div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <div data-testid="amount">{String(data?.amount)}</div>
+        </div>
+      )
+    }
+
+    render(<User />, { wrapper: storeRef.wrapper })
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+
+    fireEvent.focus(window)
+
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+  })
+
+  test('useQuery hook prefers refetchOnFocus: true when multiple components have different configurations', async () => {
+    let data, isLoading, isFetching
+
+    function User() {
+      ;({ data, isFetching, isLoading } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {
+          refetchOnFocus: false,
+        }))
+      return (
+        <div>
+          <div data-testid="isLoading">{String(isLoading)}</div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <div data-testid="amount">{String(data?.amount)}</div>
+        </div>
+      )
+    }
+
+    function UserWithRefetchTrue() {
+      ;({ data, isFetching, isLoading } =
+      defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {
+        refetchOnFocus: true,
+        }))
+      return <div />
+    }
+
+    render(
+      <div>
+        <User />
+        <UserWithRefetchTrue />
+      </div>,
+      { wrapper: storeRef.wrapper },
+    )
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+
+    fireEvent.focus(window)
+    expect(screen.getByTestId('isLoading').textContent).toBe('false')
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('2'),
+    )
+  })
+
+  test('useQuery hook cleans data if refetch without active subscribers', async () => {
+    let data, isLoading, isFetching
+
+    function User() {
+      ;({ data, isFetching, isLoading } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {
+          refetchOnFocus: true,
+        }))
+      return (
+        <div>
+          <div data-testid="isLoading">{String(isLoading)}</div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <div data-testid="amount">{String(data?.amount)}</div>
+        </div>
+      )
+    }
+
+    const { unmount } = render(<User />, { wrapper: storeRef.wrapper })
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+
+    unmount()
+
+    expect(getIncrementedAmountState()).not.toBeUndefined()
+
+    fireEvent.focus(window)
+
+    await delay(1)
+    expect(getIncrementedAmountState()).toBeUndefined()
+  })
+})
+
+describe('refetchOnReconnect tests', () => {
+  test('useQuery hook respects refetchOnReconnect: true when set in createApi options', async () => {
+    let data, isLoading, isFetching
+
+    function User() {
+      ;({ data, isFetching, isLoading } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery())
+      return (
+        <div>
+          <div data-testid="isLoading">{String(isLoading)}</div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <div data-testid="amount">{String(data?.amount)}</div>
+        </div>
+      )
+    }
+
+    render(<User />, { wrapper: storeRef.wrapper })
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+
+    act(() => {
+      window.dispatchEvent(new Event('offline'))
+      window.dispatchEvent(new Event('online'))
+    })
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('2'),
+    )
+  })
+
+  test('useQuery hook should not refetch when refetchOnReconnect: false from a hook and overrides createApi defaults', async () => {
+    let data, isLoading, isFetching
+
+    function User() {
+      ;({ data, isFetching, isLoading } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {
+          refetchOnReconnect: false,
+        }))
+      return (
+        <div>
+          <div data-testid="isLoading">{String(isLoading)}</div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <div data-testid="amount">{String(data?.amount)}</div>
+        </div>
+      )
+    }
+
+    render(<User />, { wrapper: storeRef.wrapper })
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+
+    act(() => {
+      window.dispatchEvent(new Event('offline'))
+      window.dispatchEvent(new Event('online'))
+    })
+    expect(screen.getByTestId('isFetching').textContent).toBe('false')
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+  })
+
+  test('useQuery hook prefers refetchOnReconnect: true when multiple components have different configurations', async () => {
+    let data, isLoading, isFetching
+
+    function User() {
+      ;({ data, isFetching, isLoading } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {
+          refetchOnReconnect: false,
+        }))
+      return (
+        <div>
+          <div data-testid="isLoading">{String(isLoading)}</div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <div data-testid="amount">{String(data?.amount)}</div>
+        </div>
+      )
+    }
+
+    function UserWithRefetchTrue() {
+      ;({ data, isFetching, isLoading } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {
+          refetchOnReconnect: true,
+        }))
+      return <div />
+    }
+
+    render(
+      <div>
+        <User />
+        <UserWithRefetchTrue />
+      </div>,
+      { wrapper: storeRef.wrapper },
+    )
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+
+    act(() => {
+      window.dispatchEvent(new Event('offline'))
+      window.dispatchEvent(new Event('online'))
+    })
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('2'),
+    )
+  })
+})
+
+describe('customListenersHandler', () => {
+  const storeRef = setupApiStore(defaultApi, undefined, {
+    withoutListeners: true,
+  })
+
+  test('setupListeners accepts a custom callback and executes it', async () => {
+    const consoleSpy = vi.spyOn(console, 'log')
+    consoleSpy.mockImplementation((...args: any[]) => {
+      // console.info(...args)
+    })
+    const dispatchSpy = vi.spyOn(storeRef.store, 'dispatch')
+
+    let unsubscribe = () => {}
+    unsubscribe = setupListeners(
+      storeRef.store.dispatch,
+      (dispatch, actions) => {
+        const handleOnline = () =>
+          dispatch(defaultApi.internalActions.onOnline())
+        window.addEventListener('online', handleOnline, false)
+        console.log('setup!')
+        return () => {
+          window.removeEventListener('online', handleOnline)
+          console.log('cleanup!')
+        }
+      },
+    )
+
+    await delay(150)
+
+    let data, isLoading, isFetching
+
+    function User() {
+      ;({ data, isFetching, isLoading } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {
+          refetchOnReconnect: true,
+        }))
+      return (
+        <div>
+          <div data-testid="isLoading">{String(isLoading)}</div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <div data-testid="amount">{String(data?.amount)}</div>
+        </div>
+      )
+    }
+
+    render(<User />, { wrapper: storeRef.wrapper })
+
+    expect(consoleSpy).toHaveBeenCalledWith('setup!')
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+
+    act(() => {
+      window.dispatchEvent(new Event('offline'))
+      window.dispatchEvent(new Event('online'))
+    })
+    expect(dispatchSpy).toHaveBeenCalled()
+
+    // Ignore RTKQ middleware internal data calls
+    const mockCallsWithoutInternals = dispatchSpy.mock.calls.filter((call) => {
+      const type = (call[0] as any)?.type ?? ''
+      const reIsInternal = /internal/i
+      return !reIsInternal.test(type)
+    })
+
+    expect(
+      defaultApi.internalActions.onOnline.match(
+        mockCallsWithoutInternals[1][0] as any,
+      ),
+    ).toBe(true)
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('2'),
+    )
+
+    unsubscribe()
+    expect(consoleSpy).toHaveBeenCalledWith('cleanup!')
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/retry.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/retry.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/retry.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,46 @@
+import { retry, type RetryOptions } from '@internal/query/retry'
+import {
+  fetchBaseQuery,
+  type FetchBaseQueryError,
+  type FetchBaseQueryMeta,
+} from '@internal/query/fetchBaseQuery'
+
+describe('type tests', () => {
+  test('RetryOptions only accepts one of maxRetries or retryCondition', () => {
+    // Should not complain if only `maxRetries` exists
+    expectTypeOf({ maxRetries: 5 }).toMatchTypeOf<RetryOptions>()
+
+    // Should not complain if only `retryCondition` exists
+    expectTypeOf({ retryCondition: () => false }).toMatchTypeOf<RetryOptions>()
+
+    // Should complain if both `maxRetries` and `retryCondition` exist at once
+    expectTypeOf({
+      maxRetries: 5,
+      retryCondition: () => false,
+    }).not.toMatchTypeOf<RetryOptions>()
+  })
+  test('fail can be pretyped to only accept correct error and meta', () => {
+    expectTypeOf(retry.fail).parameter(0).toEqualTypeOf<unknown>()
+    expectTypeOf(retry.fail).parameter(1).toEqualTypeOf<{} | undefined>()
+    expectTypeOf(retry.fail).toBeCallableWith('Literally anything', {})
+
+    const myBaseQuery = fetchBaseQuery()
+    const typedFail = retry.fail<typeof myBaseQuery>
+
+    expectTypeOf(typedFail).parameter(0).toMatchTypeOf<FetchBaseQueryError>()
+    expectTypeOf(typedFail)
+      .parameter(1)
+      .toMatchTypeOf<FetchBaseQueryMeta | undefined>()
+
+    expectTypeOf(typedFail).toBeCallableWith(
+      {
+        status: 401,
+        data: 'Unauthorized',
+      },
+      { request: new Request('http://localhost') },
+    )
+
+    expectTypeOf(typedFail).parameter(0).not.toMatchTypeOf<string>()
+    expectTypeOf(typedFail).parameter(1).not.toMatchTypeOf<{}>()
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/retry.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/retry.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/retry.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,921 @@
+import type { BaseQueryFn, FetchBaseQueryError } from '@reduxjs/toolkit/query'
+import { createApi, retry } from '@reduxjs/toolkit/query'
+import { setupApiStore } from '../../tests/utils/helpers'
+
+beforeEach(() => {
+  vi.useFakeTimers()
+})
+
+const loopTimers = async (max: number = 12) => {
+  let count = 0
+  while (count < max) {
+    await vi.advanceTimersByTimeAsync(1)
+    vi.advanceTimersByTime(120_000)
+    count++
+  }
+}
+
+describe('configuration', () => {
+  test('retrying without any config options', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery.mockResolvedValue({ error: 'rejected' })
+
+    const baseQuery = retry(baseBaseQuery)
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+    await loopTimers(7)
+
+    expect(baseBaseQuery).toHaveBeenCalledTimes(6)
+  })
+
+  test('retrying with baseQuery config that overrides default behavior (maxRetries: 5)', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery.mockResolvedValue({ error: 'rejected' })
+
+    const baseQuery = retry(baseBaseQuery, { maxRetries: 3 })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+    await loopTimers(5)
+
+    expect(baseBaseQuery).toHaveBeenCalledTimes(4)
+  })
+
+  test('retrying with endpoint config that overrides baseQuery config', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery.mockResolvedValue({ error: 'rejected' })
+
+    const baseQuery = retry(baseBaseQuery, { maxRetries: 3 })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+        }),
+        q2: build.query({
+          query: () => {},
+          extraOptions: { maxRetries: 8 },
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+    await loopTimers(5)
+
+    expect(baseBaseQuery).toHaveBeenCalledTimes(4)
+
+    baseBaseQuery.mockClear()
+
+    storeRef.store.dispatch(api.endpoints.q2.initiate({}))
+
+    await loopTimers(10)
+
+    expect(baseBaseQuery).toHaveBeenCalledTimes(9)
+  })
+
+  test('stops retrying a query after a success', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery
+      .mockResolvedValueOnce({ error: 'rejected' })
+      .mockResolvedValueOnce({ error: 'rejected' })
+      .mockResolvedValue({ data: { success: true } })
+
+    const baseQuery = retry(baseBaseQuery, { maxRetries: 10 })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.mutation({
+          query: () => {},
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+    await loopTimers(6)
+
+    expect(baseBaseQuery).toHaveBeenCalledTimes(3)
+  })
+
+  test('retrying also works with mutations', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery.mockResolvedValue({ error: 'rejected' })
+
+    const baseQuery = retry(baseBaseQuery, { maxRetries: 3 })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        m1: build.mutation({
+          query: () => ({ method: 'PUT' }),
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    storeRef.store.dispatch(api.endpoints.m1.initiate({}))
+
+    await loopTimers(5)
+
+    expect(baseBaseQuery).toHaveBeenCalledTimes(4)
+  })
+
+  test('retrying stops after a success from a mutation', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery
+      .mockRejectedValueOnce(new Error('rejected'))
+      .mockRejectedValueOnce(new Error('rejected'))
+      .mockResolvedValue({ data: { success: true } })
+
+    const baseQuery = retry(baseBaseQuery, { maxRetries: 3 })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        m1: build.mutation({
+          query: () => ({ method: 'PUT' }),
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    storeRef.store.dispatch(api.endpoints.m1.initiate({}))
+
+    await loopTimers(5)
+
+    expect(baseBaseQuery).toHaveBeenCalledTimes(3)
+  })
+  test('non-error-cases should **not** retry', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery.mockResolvedValue({ data: { success: true } })
+
+    const baseQuery = retry(baseBaseQuery, { maxRetries: 3 })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+    await loopTimers(2)
+
+    expect(baseBaseQuery).toHaveBeenCalledOnce()
+  })
+  test('calling retry.fail(error) will skip retrying and expose the error directly', async () => {
+    const error = { message: 'banana' }
+
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery.mockImplementation((input) => {
+      retry.fail(error)
+      return { data: `this won't happen` }
+    })
+
+    const baseQuery = retry(baseBaseQuery)
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    const result = await storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+    await loopTimers(2)
+
+    expect(baseBaseQuery).toHaveBeenCalledOnce()
+    expect(result.error).toEqual(error)
+    expect(result).toEqual({
+      endpointName: 'q1',
+      error,
+      isError: true,
+      isLoading: false,
+      isSuccess: false,
+      isUninitialized: false,
+      originalArgs: expect.any(Object),
+      requestId: expect.any(String),
+      startedTimeStamp: expect.any(Number),
+      status: 'rejected',
+    })
+  })
+
+  test('wrapping retry(retry(..., { maxRetries: 3 }), { maxRetries: 3 }) should retry 16 times', async () => {
+    /**
+     * Note:
+     * This will retry 16 total times because we try the initial + 3 retries (sum: 4), then retry that process 3 times (starting at 0 for a total of 4)... 4x4=16 (allegedly)
+     */
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery.mockResolvedValue({ error: 'rejected' })
+
+    const baseQuery = retry(retry(baseBaseQuery, { maxRetries: 3 }), {
+      maxRetries: 3,
+    })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+    await loopTimers(18)
+
+    expect(baseBaseQuery).toHaveBeenCalledTimes(16)
+  })
+
+  test('accepts a custom backoff fn', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery.mockResolvedValue({ error: 'rejected' })
+
+    const baseQuery = retry(baseBaseQuery, {
+      maxRetries: 8,
+      backoff: async (attempt, maxRetries) => {
+        const attempts = Math.min(attempt, maxRetries)
+        const timeout = attempts * 300 // Scale up by 300ms per request, ex: 300ms, 600ms, 900ms, 1200ms...
+        await new Promise((resolve) =>
+          setTimeout((res: any) => resolve(res), timeout),
+        )
+      },
+    })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+    await loopTimers()
+
+    expect(baseBaseQuery).toHaveBeenCalledTimes(9)
+  })
+
+  test('accepts a custom retryCondition fn', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery.mockResolvedValue({ error: 'rejected' })
+
+    const overrideMaxRetries = 3
+
+    const baseQuery = retry(baseBaseQuery, {
+      retryCondition: (_, __, { attempt }) => attempt <= overrideMaxRetries,
+    })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+    await loopTimers()
+
+    expect(baseBaseQuery).toHaveBeenCalledTimes(overrideMaxRetries + 1)
+  })
+
+  test('retryCondition with endpoint config that overrides baseQuery config', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery.mockResolvedValue({ error: 'rejected' })
+
+    const baseQuery = retry(baseBaseQuery, {
+      maxRetries: 10,
+    })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+          extraOptions: {
+            retryCondition: (_, __, { attempt }) => attempt <= 5,
+          },
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+    await loopTimers()
+
+    expect(baseBaseQuery).toHaveBeenCalledTimes(6)
+  })
+
+  test('retryCondition also works with mutations', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+
+    baseBaseQuery
+      .mockRejectedValueOnce(new Error('rejected'))
+      .mockRejectedValueOnce(new Error('hello retryCondition'))
+      .mockRejectedValueOnce(new Error('rejected'))
+      .mockResolvedValue({ error: 'hello retryCondition' })
+
+    const baseQuery = retry(baseBaseQuery, {})
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        m1: build.mutation({
+          query: () => ({ method: 'PUT' }),
+          extraOptions: {
+            retryCondition: (e) =>
+              (e as FetchBaseQueryError).data === 'hello retryCondition',
+          },
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+    storeRef.store.dispatch(api.endpoints.m1.initiate({}))
+
+    await loopTimers()
+
+    expect(baseBaseQuery).toHaveBeenCalledTimes(4)
+  })
+
+  test('Specifying maxRetries as 0 in RetryOptions prevents retries', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery.mockResolvedValue({ error: 'rejected' })
+
+    const baseQuery = retry(baseBaseQuery, { maxRetries: 0 })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+    await loopTimers(2)
+
+    expect(baseBaseQuery).toHaveBeenCalledOnce()
+  })
+
+  test('retryCondition receives abort signal and stops retrying when cache entry is removed', async () => {
+    let capturedSignal: AbortSignal | undefined
+    let retryAttempts = 0
+
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+
+    // Always return an error to trigger retries
+    baseBaseQuery.mockResolvedValue({ error: 'network error' })
+
+    let retryConditionCalled = false
+
+    const baseQuery = retry(baseBaseQuery, {
+      retryCondition: (error, args, { attempt, baseQueryApi }) => {
+        retryConditionCalled = true
+        retryAttempts = attempt
+        capturedSignal = baseQueryApi.signal
+
+        // Stop retrying if the signal is aborted
+        if (baseQueryApi.signal.aborted) {
+          return false
+        }
+
+        // Otherwise, retry up to 10 times
+        return attempt <= 10
+      },
+      backoff: async () => {
+        // Short backoff for faster test
+        await new Promise((resolve) => setTimeout(resolve, 10))
+      },
+    })
+
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        getTest: build.query<string, number>({
+          query: (id) => ({ url: `test/${id}` }),
+          keepUnusedDataFor: 0.01, // Very short timeout (10ms)
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    // Start the query
+    const queryPromise = storeRef.store.dispatch(
+      api.endpoints.getTest.initiate(1),
+    )
+
+    // Wait for the first retry to happen so we capture the signal
+    await loopTimers(2)
+
+    // Verify the retry condition was called and we have a signal
+    expect(retryConditionCalled).toBe(true)
+    expect(capturedSignal).toBeDefined()
+    expect(capturedSignal!.aborted).toBe(false)
+
+    // Unsubscribe to trigger cache removal
+    queryPromise.unsubscribe()
+
+    // Wait for the cache entry to be removed (keepUnusedDataFor: 0.01s = 10ms)
+    await vi.advanceTimersByTimeAsync(50)
+
+    // Allow some time for more retries to potentially happen
+    await loopTimers(3)
+
+    // The signal should now be aborted
+    expect(capturedSignal!.aborted).toBe(true)
+
+    // We should have stopped retrying early due to the abort signal
+    // If abort signal wasn't working, we'd see many more retry attempts
+    expect(retryAttempts).toBeLessThan(10)
+
+    // The base query should have been called at least once (initial attempt)
+    // but not the full 10+ times it would without abort signal
+    expect(baseBaseQuery).toHaveBeenCalled()
+    expect(baseBaseQuery.mock.calls.length).toBeLessThan(10)
+  })
+
+  // Tests for issue #4079: Thrown errors should respect maxRetries
+  test('thrown errors (not HandledError) should respect maxRetries', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    // Simulate network error that keeps throwing
+    baseBaseQuery.mockRejectedValue(new Error('Network timeout'))
+
+    const baseQuery = retry(baseBaseQuery, { maxRetries: 3 })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+    await loopTimers(5)
+
+    // Should try initial + 3 retries = 4 total, then stop
+    // Currently this will fail because it retries infinitely
+    expect(baseBaseQuery).toHaveBeenCalledTimes(4)
+  })
+
+  test('graphql-style thrown errors should respect maxRetries', async () => {
+    class ClientError extends Error {
+      constructor(message: string) {
+        super(message)
+        this.name = 'ClientError'
+      }
+    }
+
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    // Simulate graphql-request throwing ClientError
+    baseBaseQuery.mockImplementation(() => {
+      throw new ClientError('GraphQL network error')
+    })
+
+    const baseQuery = retry(baseBaseQuery, { maxRetries: 2 })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+    await loopTimers(4)
+
+    // Should try initial + 2 retries = 3 total, then stop
+    // Currently this will fail because it retries infinitely
+    expect(baseBaseQuery).toHaveBeenCalledTimes(3)
+  })
+
+  test('handles mix of returned errors and thrown errors', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery
+      .mockResolvedValueOnce({ error: 'returned error' }) // HandledError
+      .mockRejectedValueOnce(new Error('thrown error')) // Not HandledError
+      .mockResolvedValueOnce({ error: 'returned error' }) // HandledError
+      .mockResolvedValue({ data: { success: true } })
+
+    const baseQuery = retry(baseBaseQuery, { maxRetries: 5 })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+    await loopTimers(6)
+
+    // Should eventually succeed after 4 attempts
+    expect(baseBaseQuery).toHaveBeenCalledTimes(4)
+  })
+
+  test('thrown errors with mutations should respect maxRetries', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    // Simulate persistent network error
+    baseBaseQuery.mockRejectedValue(new Error('Connection refused'))
+
+    const baseQuery = retry(baseBaseQuery, { maxRetries: 2 })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        m1: build.mutation({
+          query: () => ({ method: 'POST' }),
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    storeRef.store.dispatch(api.endpoints.m1.initiate({}))
+
+    await loopTimers(4)
+
+    // Should try initial + 2 retries = 3 total, then stop
+    // Currently this will fail because it retries infinitely
+    expect(baseBaseQuery).toHaveBeenCalledTimes(3)
+  })
+
+  // These tests validate the abort signal handling implementation
+  describe('abort signal handling', () => {
+    test('retry loop exits immediately when signal is aborted before retry', async () => {
+      const baseBaseQuery = vi.fn<BaseQueryFn>()
+      baseBaseQuery.mockResolvedValue({ error: 'network error' })
+
+      const baseQuery = retry(baseBaseQuery, { maxRetries: 10 })
+      const api = createApi({
+        baseQuery,
+        endpoints: (build) => ({
+          q1: build.query({ query: () => {} }),
+        }),
+      })
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const promise = storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+      // Let first attempt fail
+      await loopTimers(1)
+      expect(baseBaseQuery).toHaveBeenCalledTimes(1)
+
+      // Abort the query
+      promise.abort()
+
+      // Advance timers to allow retry attempts
+      await loopTimers(5)
+
+      // Should not have retried after abort
+      expect(baseBaseQuery).toHaveBeenCalledTimes(1)
+    })
+
+    test('abort during active request prevents retry', async () => {
+      let requestInProgress = false
+      const baseBaseQuery = vi.fn<BaseQueryFn>()
+
+      baseBaseQuery.mockImplementation(async () => {
+        requestInProgress = true
+        await new Promise((resolve) => setTimeout(resolve, 100))
+        requestInProgress = false
+        return { error: 'network error' }
+      })
+
+      const baseQuery = retry(baseBaseQuery, { maxRetries: 5 })
+      const api = createApi({
+        baseQuery,
+        endpoints: (build) => ({
+          q1: build.query({ query: () => {} }),
+        }),
+      })
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const promise = storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+      // Wait for request to start
+      await vi.advanceTimersByTimeAsync(50)
+      expect(requestInProgress).toBe(true)
+
+      // Abort while request is in progress
+      promise.abort()
+
+      // Let request complete
+      await loopTimers(2)
+
+      // Should not retry after abort
+      expect(baseBaseQuery).toHaveBeenCalledTimes(1)
+    })
+
+    test('custom backoff without signal parameter still works', async () => {
+      const baseBaseQuery = vi.fn<BaseQueryFn>()
+      baseBaseQuery.mockResolvedValue({ error: 'network error' })
+
+      // Custom backoff that doesn't accept signal (backward compatibility)
+      const customBackoff = async (attempt: number, maxRetries: number) => {
+        await new Promise((resolve) => setTimeout(resolve, 100))
+      }
+
+      const baseQuery = retry(baseBaseQuery, {
+        maxRetries: 3,
+        backoff: customBackoff,
+      })
+
+      const api = createApi({
+        baseQuery,
+        endpoints: (build) => ({
+          q1: build.query({ query: () => {} }),
+        }),
+      })
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+      await loopTimers(5)
+
+      // Should complete all retries (not cancellable without signal)
+      expect(baseBaseQuery).toHaveBeenCalledTimes(4)
+    })
+
+    test('abort signal is checked before each retry attempt', async () => {
+      const attemptNumbers: number[] = []
+      const baseBaseQuery = vi.fn<BaseQueryFn>()
+      baseBaseQuery.mockImplementation(async () => {
+        attemptNumbers.push(attemptNumbers.length + 1)
+        return { error: 'network error' }
+      })
+
+      const baseQuery = retry(baseBaseQuery, { maxRetries: 10 })
+      const api = createApi({
+        baseQuery,
+        endpoints: (build) => ({
+          q1: build.query({ query: () => {} }),
+        }),
+      })
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const promise = storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+      // Let 3 attempts happen
+      await loopTimers(3)
+      expect(attemptNumbers).toEqual([1, 2, 3])
+
+      // Abort
+      promise.abort()
+
+      // Try to let more attempts happen
+      await loopTimers(5)
+
+      // Should not have any more attempts
+      expect(attemptNumbers).toEqual([1, 2, 3])
+    })
+
+    test('mutations respect abort signal during retry', async () => {
+      const baseBaseQuery = vi.fn<BaseQueryFn>()
+      baseBaseQuery.mockResolvedValue({ error: 'network error' })
+
+      const baseQuery = retry(baseBaseQuery, { maxRetries: 5 })
+      const api = createApi({
+        baseQuery,
+        endpoints: (build) => ({
+          m1: build.mutation({ query: () => ({ method: 'POST' }) }),
+        }),
+      })
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const promise = storeRef.store.dispatch(api.endpoints.m1.initiate({}))
+
+      // Let first attempt fail
+      await loopTimers(1)
+      expect(baseBaseQuery).toHaveBeenCalledTimes(1)
+
+      // Abort
+      promise.abort()
+
+      // Try to let retries happen
+      await loopTimers(5)
+
+      // Should not have retried
+      expect(baseBaseQuery).toHaveBeenCalledTimes(1)
+    })
+
+    test('abort after successful retry does not affect result', async () => {
+      const baseBaseQuery = vi.fn<BaseQueryFn>()
+      baseBaseQuery
+        .mockResolvedValueOnce({ error: 'network error' })
+        .mockResolvedValue({ data: { success: true } })
+
+      const baseQuery = retry(baseBaseQuery, { maxRetries: 5 })
+      const api = createApi({
+        baseQuery,
+        endpoints: (build) => ({
+          q1: build.query({ query: () => {} }),
+        }),
+      })
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const promise = storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+      // Let it succeed on retry
+      await loopTimers(3)
+      expect(baseBaseQuery).toHaveBeenCalledTimes(2)
+
+      const result = await promise
+
+      // Abort after success
+      promise.abort()
+
+      // Result should still be successful
+      expect(result.isSuccess).toBe(true)
+      expect(result.data).toEqual({ success: true })
+    })
+
+    test('multiple aborts are handled gracefully', async () => {
+      const baseBaseQuery = vi.fn<BaseQueryFn>()
+      baseBaseQuery.mockResolvedValue({ error: 'network error' })
+
+      const baseQuery = retry(baseBaseQuery, { maxRetries: 10 })
+      const api = createApi({
+        baseQuery,
+        endpoints: (build) => ({
+          q1: build.query({ query: () => {} }),
+        }),
+      })
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const promise = storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+      await loopTimers(1)
+
+      // Call abort multiple times
+      promise.abort()
+      promise.abort()
+      promise.abort()
+
+      await loopTimers(3)
+
+      // Should handle gracefully
+      expect(baseBaseQuery).toHaveBeenCalledTimes(1)
+    })
+
+    test('abort signal already aborted before retry starts', async () => {
+      const baseBaseQuery = vi.fn<BaseQueryFn>()
+      baseBaseQuery.mockResolvedValue({ error: 'network error' })
+
+      const baseQuery = retry(baseBaseQuery, { maxRetries: 5 })
+      const api = createApi({
+        baseQuery,
+        endpoints: (build) => ({
+          q1: build.query({ query: () => {} }),
+        }),
+      })
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const promise = storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+      // Abort immediately
+      promise.abort()
+
+      await loopTimers(5)
+
+      // May have started the first attempt before abort was processed
+      // but should not retry
+      expect(baseBaseQuery.mock.calls.length).toBeLessThanOrEqual(1)
+    })
+
+    test('resetApiState aborts retrying queries', async () => {
+      const baseBaseQuery = vi.fn<BaseQueryFn>()
+      baseBaseQuery.mockResolvedValue({ error: 'network error' })
+
+      const baseQuery = retry(baseBaseQuery, { maxRetries: 10 })
+      const api = createApi({
+        baseQuery,
+        endpoints: (build) => ({
+          q1: build.query({ query: () => {} }),
+        }),
+      })
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+      // Let first attempt fail and start retrying
+      await loopTimers(2)
+      expect(baseBaseQuery).toHaveBeenCalledTimes(2)
+
+      // Reset API state (should abort the retry loop)
+      storeRef.store.dispatch(api.util.resetApiState())
+
+      // Try to let more retries happen
+      await loopTimers(5)
+
+      // Should not have retried after resetApiState
+      expect(baseBaseQuery).toHaveBeenCalledTimes(2)
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/unionTypes.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/unionTypes.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/unionTypes.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,914 @@
+import type { UseQueryStateOptions } from '@internal/query/react/buildHooks'
+import type { SerializedError } from '@reduxjs/toolkit'
+import type {
+  FetchBaseQueryError,
+  QueryDefinition,
+  TypedUseMutationResult,
+  TypedUseQueryHookResult,
+  TypedUseQueryState,
+  TypedUseQueryStateResult,
+  TypedUseQuerySubscriptionResult,
+  TypedLazyQueryTrigger,
+  TypedUseLazyQueryStateResult,
+  TypedUseLazyQuery,
+  TypedUseLazyQuerySubscription,
+  TypedUseMutation,
+  TypedMutationTrigger,
+  TypedUseQuerySubscription,
+  TypedUseQuery,
+  TypedUseQueryStateOptions,
+} from '@reduxjs/toolkit/query/react'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+
+const baseQuery = fetchBaseQuery()
+
+const api = createApi({
+  baseQuery,
+  endpoints: (build) => ({
+    getTest: build.query<string, void>({ query: () => '' }),
+    mutation: build.mutation<string, void>({ query: () => '' }),
+  }),
+})
+
+describe('union types', () => {
+  test('query selector union', () => {
+    const result = api.endpoints.getTest.select()({} as any)
+
+    if (result.isUninitialized) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+    }
+
+    if (result.isLoading) {
+      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError | undefined
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+    }
+
+    if (result.isError) {
+      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+    }
+
+    if (result.isSuccess) {
+      expectTypeOf(result.data).toBeString()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+    }
+
+    expectTypeOf(result).not.toBeNever()
+
+    // is always one of those four
+    if (
+      !result.isUninitialized &&
+      !result.isLoading &&
+      !result.isError &&
+      !result.isSuccess
+    ) {
+      expectTypeOf(result).toBeNever()
+    }
+  })
+
+  test('useQuery union', () => {
+    const result = api.endpoints.getTest.useQuery()
+
+    if (result.isUninitialized) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toEqualTypeOf<false>()
+    }
+
+    if (result.isLoading) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError | undefined
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toBeBoolean()
+    }
+
+    if (result.isError) {
+      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toEqualTypeOf<false>()
+    }
+
+    if (result.isSuccess) {
+      expectTypeOf(result.data).toBeString()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toBeBoolean()
+    }
+
+    if (result.isFetching) {
+      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError | undefined
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toBeBoolean()
+
+      expectTypeOf(result.isSuccess).toBeBoolean()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+    }
+
+    expectTypeOf(result.currentData).toEqualTypeOf<string | undefined>()
+
+    if (result.isSuccess) {
+      if (!result.isFetching) {
+        expectTypeOf(result.currentData).toBeString()
+      } else {
+        expectTypeOf(result.currentData).toEqualTypeOf<string | undefined>()
+      }
+    }
+
+    expectTypeOf(result).not.toBeNever()
+
+    // is always one of those four
+    if (
+      !result.isUninitialized &&
+      !result.isLoading &&
+      !result.isError &&
+      !result.isSuccess
+    ) {
+      expectTypeOf(result).toBeNever()
+    }
+  })
+  test('useQuery TS4.1 union', () => {
+    const result = api.useGetTestQuery()
+
+    if (result.isUninitialized) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toEqualTypeOf<false>()
+    }
+
+    if (result.isLoading) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError | undefined
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toBeBoolean()
+    }
+
+    if (result.isError) {
+      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toEqualTypeOf<false>()
+    }
+
+    if (result.isSuccess) {
+      expectTypeOf(result.data).toBeString()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toBeBoolean()
+    }
+
+    if (result.isFetching) {
+      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError | undefined
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toBeBoolean()
+
+      expectTypeOf(result.isSuccess).toBeBoolean()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+    }
+
+    expectTypeOf(result).not.toBeNever()
+
+    // is always one of those four
+    if (
+      !result.isUninitialized &&
+      !result.isLoading &&
+      !result.isError &&
+      !result.isSuccess
+    ) {
+      expectTypeOf(result).toBeNever()
+    }
+  })
+
+  test('useLazyQuery union', () => {
+    const [_trigger, result] = api.endpoints.getTest.useLazyQuery()
+
+    if (result.isUninitialized) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toEqualTypeOf<false>()
+    }
+
+    if (result.isLoading) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError | undefined
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toBeBoolean()
+    }
+
+    if (result.isError) {
+      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toEqualTypeOf<false>()
+    }
+
+    if (result.isSuccess) {
+      expectTypeOf(result.data).toBeString()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toBeBoolean()
+    }
+
+    if (result.isFetching) {
+      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError | undefined
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toBeBoolean()
+
+      expectTypeOf(result.isSuccess).toBeBoolean()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+    }
+
+    expectTypeOf(result).not.toBeNever()
+
+    // is always one of those four
+    if (
+      !result.isUninitialized &&
+      !result.isLoading &&
+      !result.isError &&
+      !result.isSuccess
+    ) {
+      expectTypeOf(result).toBeNever()
+    }
+  })
+
+  test('useLazyQuery TS4.1 union', () => {
+    const [_trigger, result] = api.useLazyGetTestQuery()
+
+    if (result.isUninitialized) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toEqualTypeOf<false>()
+    }
+
+    if (result.isLoading) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError | undefined
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toBeBoolean()
+    }
+
+    if (result.isError) {
+      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toEqualTypeOf<false>()
+    }
+
+    if (result.isSuccess) {
+      expectTypeOf(result.data).toBeString()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toBeBoolean()
+    }
+
+    if (result.isFetching) {
+      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError | undefined
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toBeBoolean()
+
+      expectTypeOf(result.isSuccess).toBeBoolean()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+    }
+
+    expectTypeOf(result).not.toBeNever()
+
+    // is always one of those four
+    if (
+      !result.isUninitialized &&
+      !result.isLoading &&
+      !result.isError &&
+      !result.isSuccess
+    ) {
+      expectTypeOf(result).toBeNever()
+    }
+  })
+
+  test('queryHookResult (without selector) union', async () => {
+    const useQueryStateResult = api.endpoints.getTest.useQueryState()
+
+    const useQueryResult = api.endpoints.getTest.useQuery()
+
+    const useQueryStateWithSelectFromResult =
+      api.endpoints.getTest.useQueryState(undefined, {
+        selectFromResult: () => ({ x: true }),
+      })
+
+    const { refetch, ...useQueryResultWithoutMethods } = useQueryResult
+
+    assertType<typeof useQueryResultWithoutMethods>(useQueryStateResult)
+
+    expectTypeOf(useQueryStateResult).toMatchTypeOf(
+      useQueryResultWithoutMethods,
+    )
+
+    expectTypeOf(useQueryStateWithSelectFromResult)
+      .parameter(0)
+      .not.toMatchTypeOf(useQueryResultWithoutMethods)
+
+    expectTypeOf(api.endpoints.getTest.select).returns.returns.toEqualTypeOf<
+      Awaited<ReturnType<typeof refetch>>
+    >()
+  })
+
+  test('useQueryState (with selectFromResult)', () => {
+    const result = api.endpoints.getTest.useQueryState(undefined, {
+      selectFromResult({
+        data,
+        isLoading,
+        isFetching,
+        isError,
+        isSuccess,
+        isUninitialized,
+      }) {
+        return {
+          data: data ?? 1,
+          isLoading,
+          isFetching,
+          isError,
+          isSuccess,
+          isUninitialized,
+        }
+      },
+    })
+
+    expectTypeOf({
+      data: '' as string | number,
+      isUninitialized: false,
+      isLoading: true,
+      isFetching: true,
+      isSuccess: false,
+      isError: false,
+    }).toEqualTypeOf(result)
+  })
+
+  test('useQuery (with selectFromResult)', async () => {
+    const { refetch, ...result } = api.endpoints.getTest.useQuery(undefined, {
+      selectFromResult({
+        data,
+        isLoading,
+        isFetching,
+        isError,
+        isSuccess,
+        isUninitialized,
+      }) {
+        return {
+          data: data ?? 1,
+          isLoading,
+          isFetching,
+          isError,
+          isSuccess,
+          isUninitialized,
+        }
+      },
+    })
+
+    expectTypeOf({
+      data: '' as string | number,
+      isUninitialized: false,
+      isLoading: true,
+      isFetching: true,
+      isSuccess: false,
+      isError: false,
+    }).toEqualTypeOf(result)
+
+    expectTypeOf(api.endpoints.getTest.select).returns.returns.toEqualTypeOf<
+      Awaited<ReturnType<typeof refetch>>
+    >()
+  })
+
+  test('useMutation union', () => {
+    const [_trigger, result] = api.endpoints.mutation.useMutation()
+
+    if (result.isUninitialized) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+    }
+
+    if (result.isLoading) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError | undefined
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+    }
+
+    if (result.isError) {
+      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+    }
+
+    if (result.isSuccess) {
+      expectTypeOf(result.data).toBeString()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+    }
+
+    expectTypeOf(result).not.toBeNever()
+
+    // is always one of those four
+    if (
+      !result.isUninitialized &&
+      !result.isLoading &&
+      !result.isError &&
+      !result.isSuccess
+    ) {
+      expectTypeOf(result).toBeNever()
+    }
+  })
+
+  test('useMutation (with selectFromResult)', () => {
+    const [_trigger, result] = api.endpoints.mutation.useMutation({
+      selectFromResult({
+        data,
+        isLoading,
+        isError,
+        isSuccess,
+        isUninitialized,
+      }) {
+        return {
+          data: data ?? 'hi',
+          isLoading,
+          isError,
+          isSuccess,
+          isUninitialized,
+        }
+      },
+    })
+
+    expectTypeOf({
+      data: '' as string,
+      isUninitialized: false,
+      isLoading: true,
+      isSuccess: false,
+      isError: false,
+      reset: () => {},
+    }).toMatchTypeOf(result)
+  })
+
+  test('useMutation TS4.1 union', () => {
+    const [_trigger, result] = api.useMutationMutation()
+
+    if (result.isUninitialized) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+    }
+
+    if (result.isLoading) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError | undefined
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+    }
+
+    if (result.isError) {
+      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+    }
+
+    if (result.isSuccess) {
+      expectTypeOf(result.data).toBeString()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+    }
+
+    expectTypeOf(result).not.toBeNever()
+
+    // is always one of those four
+    if (
+      !result.isUninitialized &&
+      !result.isLoading &&
+      !result.isError &&
+      !result.isSuccess
+    ) {
+      expectTypeOf(result).toBeNever()
+    }
+  })
+})
+
+describe('"Typed" helper types', () => {
+  test('useQuery', () => {
+    expectTypeOf<TypedUseQuery<string, void, typeof baseQuery>>().toMatchTypeOf(
+      api.endpoints.getTest.useQuery,
+    )
+
+    const result = api.endpoints.getTest.useQuery()
+
+    expectTypeOf<
+      TypedUseQueryHookResult<string, void, typeof baseQuery>
+    >().toEqualTypeOf(result)
+  })
+
+  test('useQuery with selectFromResult', () => {
+    const result = api.endpoints.getTest.useQuery(undefined, {
+      selectFromResult: () => ({ x: true }),
+    })
+
+    expectTypeOf<
+      TypedUseQueryHookResult<string, void, typeof baseQuery, { x: boolean }>
+    >().toEqualTypeOf(result)
+  })
+
+  test('useQueryState', () => {
+    expectTypeOf<
+      TypedUseQueryState<string, void, typeof baseQuery>
+    >().toMatchTypeOf(api.endpoints.getTest.useQueryState)
+
+    const result = api.endpoints.getTest.useQueryState()
+
+    expectTypeOf<
+      TypedUseQueryStateResult<string, void, typeof baseQuery>
+    >().toEqualTypeOf(result)
+  })
+
+  test('useQueryState with selectFromResult', () => {
+    const result = api.endpoints.getTest.useQueryState(undefined, {
+      selectFromResult: () => ({ x: true }),
+    })
+
+    expectTypeOf<
+      TypedUseQueryStateResult<string, void, typeof baseQuery, { x: boolean }>
+    >().toEqualTypeOf(result)
+  })
+
+  test('useQueryState options', () => {
+    expectTypeOf<
+      TypedUseQueryStateOptions<string, void, typeof baseQuery>
+    >().toMatchTypeOf<
+      Parameters<typeof api.endpoints.getTest.useQueryState>[1]
+    >()
+
+    expectTypeOf<
+      UseQueryStateOptions<
+        QueryDefinition<void, typeof baseQuery, string, string>,
+        { x: boolean }
+      >
+    >().toEqualTypeOf<
+      TypedUseQueryStateOptions<string, void, typeof baseQuery, { x: boolean }>
+    >()
+  })
+
+  test('useQuerySubscription', () => {
+    expectTypeOf<
+      TypedUseQuerySubscription<string, void, typeof baseQuery>
+    >().toMatchTypeOf(api.endpoints.getTest.useQuerySubscription)
+
+    const result = api.endpoints.getTest.useQuerySubscription()
+
+    expectTypeOf<
+      TypedUseQuerySubscriptionResult<string, void, typeof baseQuery>
+    >().toEqualTypeOf(result)
+  })
+
+  test('useLazyQuery', () => {
+    expectTypeOf<
+      TypedUseLazyQuery<string, void, typeof baseQuery>
+    >().toMatchTypeOf(api.endpoints.getTest.useLazyQuery)
+
+    const [trigger, result] = api.endpoints.getTest.useLazyQuery()
+
+    expectTypeOf<
+      TypedLazyQueryTrigger<string, void, typeof baseQuery>
+    >().toMatchTypeOf(trigger)
+
+    expectTypeOf<
+      TypedUseLazyQueryStateResult<string, void, typeof baseQuery>
+    >().toMatchTypeOf(result)
+  })
+
+  test('useLazyQuery with selectFromResult', () => {
+    const [trigger, result] = api.endpoints.getTest.useLazyQuery({
+      selectFromResult: () => ({ x: true }),
+    })
+
+    expectTypeOf<
+      TypedLazyQueryTrigger<string, void, typeof baseQuery>
+    >().toMatchTypeOf(trigger)
+
+    expectTypeOf<
+      TypedUseLazyQueryStateResult<
+        string,
+        void,
+        typeof baseQuery,
+        { x: boolean }
+      >
+    >().toMatchTypeOf(result)
+  })
+
+  test('useLazyQuerySubscription', () => {
+    expectTypeOf<
+      TypedUseLazyQuerySubscription<string, void, typeof baseQuery>
+    >().toMatchTypeOf(api.endpoints.getTest.useLazyQuerySubscription)
+
+    const [trigger] = api.endpoints.getTest.useLazyQuerySubscription()
+
+    expectTypeOf<
+      TypedLazyQueryTrigger<string, void, typeof baseQuery>
+    >().toMatchTypeOf(trigger)
+  })
+
+  test('useMutation', () => {
+    expectTypeOf<
+      TypedUseMutation<string, void, typeof baseQuery>
+    >().toMatchTypeOf(api.endpoints.mutation.useMutation)
+
+    const [trigger, result] = api.endpoints.mutation.useMutation()
+
+    expectTypeOf<
+      TypedMutationTrigger<string, void, typeof baseQuery>
+    >().toMatchTypeOf(trigger)
+
+    expectTypeOf<
+      TypedUseMutationResult<string, void, typeof baseQuery>
+    >().toMatchTypeOf(result)
+  })
+
+  test('useQuery - defining selectFromResult separately', () => {
+    const selectFromResult = (
+      result: TypedUseQueryStateResult<string, void, typeof baseQuery>,
+    ) => ({ x: true })
+
+    const result = api.endpoints.getTest.useQuery(undefined, {
+      selectFromResult,
+    })
+
+    expectTypeOf(result).toEqualTypeOf<
+      TypedUseQueryHookResult<
+        string,
+        void,
+        typeof baseQuery,
+        ReturnType<typeof selectFromResult>
+      >
+    >()
+  })
+
+  test('useMutation - defining selectFromResult separately', () => {
+    const selectFromResult = (
+      result: Omit<
+        TypedUseMutationResult<string, void, typeof baseQuery>,
+        'reset' | 'originalArgs'
+      >,
+    ) => ({ x: true })
+
+    const [trigger, result] = api.endpoints.mutation.useMutation({
+      selectFromResult,
+    })
+    expectTypeOf(result).toEqualTypeOf<
+      TypedUseMutationResult<
+        string,
+        void,
+        typeof baseQuery,
+        ReturnType<typeof selectFromResult>
+      >
+    >()
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/useMutation-fixedCacheKey.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/useMutation-fixedCacheKey.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/useMutation-fixedCacheKey.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,394 @@
+import { createApi } from '@reduxjs/toolkit/query/react'
+import {
+  act,
+  getByTestId,
+  render,
+  screen,
+  waitFor,
+} from '@testing-library/react'
+import { delay } from 'msw'
+import { vi } from 'vitest'
+import { setupApiStore } from '../../tests/utils/helpers'
+
+describe('fixedCacheKey', () => {
+  const onNewCacheEntry = vi.fn()
+
+  const api = createApi({
+    async baseQuery(arg: string | Promise<string>) {
+      return { data: await arg }
+    },
+    endpoints: (build) => ({
+      send: build.mutation<string, string | Promise<string>>({
+        query: (arg) => arg,
+      }),
+    }),
+  })
+  const storeRef = setupApiStore(api)
+
+  function Component({
+    name,
+    fixedCacheKey,
+    value = name,
+  }: {
+    name: string
+    fixedCacheKey?: string
+    value?: string | Promise<string>
+  }) {
+    const [trigger, result] = api.endpoints.send.useMutation({ fixedCacheKey })
+
+    return (
+      <div data-testid={name}>
+        <div data-testid="status">{result.status}</div>
+        <div data-testid="data">{result.data}</div>
+        <div data-testid="originalArgs">{String(result.originalArgs)}</div>
+        <button data-testid="trigger" onClick={() => trigger(value)}>
+          trigger
+        </button>
+        <button data-testid="reset" onClick={result.reset}>
+          reset
+        </button>
+      </div>
+    )
+  }
+
+  test('two mutations without `fixedCacheKey` do not influence each other', async () => {
+    render(
+      <>
+        <Component name="C1" />
+        <Component name="C2" />
+      </>,
+      { wrapper: storeRef.wrapper },
+    )
+    const c1 = screen.getByTestId('C1')
+    const c2 = screen.getByTestId('C2')
+    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')
+    expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')
+
+    act(() => {
+      getByTestId(c1, 'trigger').click()
+    })
+
+    await waitFor(() =>
+      expect(getByTestId(c1, 'status').textContent).toBe('fulfilled'),
+    )
+    expect(getByTestId(c1, 'data').textContent).toBe('C1')
+    expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')
+  })
+
+  test('two mutations with the same `fixedCacheKey` do influence each other', async () => {
+    render(
+      <>
+        <Component name="C1" fixedCacheKey="test" />
+        <Component name="C2" fixedCacheKey="test" />
+      </>,
+      { wrapper: storeRef.wrapper },
+    )
+    const c1 = screen.getByTestId('C1')
+    const c2 = screen.getByTestId('C2')
+    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')
+    expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')
+
+    act(() => {
+      getByTestId(c1, 'trigger').click()
+    })
+
+    await waitFor(() => {
+      expect(getByTestId(c1, 'status').textContent).toBe('fulfilled')
+      expect(getByTestId(c1, 'data').textContent).toBe('C1')
+      expect(getByTestId(c2, 'status').textContent).toBe('fulfilled')
+      expect(getByTestId(c2, 'data').textContent).toBe('C1')
+    })
+
+    // test reset from the other component
+    act(() => {
+      getByTestId(c2, 'reset').click()
+    })
+    await waitFor(() => {
+      expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')
+      expect(getByTestId(c1, 'data').textContent).toBe('')
+      expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')
+      expect(getByTestId(c2, 'data').textContent).toBe('')
+    })
+  })
+
+  test('resetting from the component that triggered the mutation resets for each shared result', async () => {
+    render(
+      <>
+        <Component name="C1" fixedCacheKey="test-A" />
+        <Component name="C2" fixedCacheKey="test-A" />
+        <Component name="C3" fixedCacheKey="test-B" />
+        <Component name="C4" fixedCacheKey="test-B" />
+      </>,
+      { wrapper: storeRef.wrapper },
+    )
+    const c1 = screen.getByTestId('C1')
+    const c2 = screen.getByTestId('C2')
+    const c3 = screen.getByTestId('C3')
+    const c4 = screen.getByTestId('C4')
+    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')
+    expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')
+    expect(getByTestId(c3, 'status').textContent).toBe('uninitialized')
+    expect(getByTestId(c4, 'status').textContent).toBe('uninitialized')
+
+    // trigger with a component using the first cache key
+
+    act(() => {
+      getByTestId(c1, 'trigger').click()
+    })
+
+    await waitFor(() =>
+      expect(getByTestId(c1, 'status').textContent).toBe('fulfilled'),
+    )
+
+    // the components with the first cache key should be affected
+    expect(getByTestId(c1, 'data').textContent).toBe('C1')
+    expect(getByTestId(c2, 'status').textContent).toBe('fulfilled')
+    expect(getByTestId(c2, 'data').textContent).toBe('C1')
+    expect(getByTestId(c2, 'status').textContent).toBe('fulfilled')
+
+    // the components with the second cache key should be unaffected
+    expect(getByTestId(c3, 'data').textContent).toBe('')
+    expect(getByTestId(c3, 'status').textContent).toBe('uninitialized')
+    expect(getByTestId(c4, 'data').textContent).toBe('')
+    expect(getByTestId(c4, 'status').textContent).toBe('uninitialized')
+
+    // trigger with a component using the second cache key
+
+    act(() => {
+      getByTestId(c3, 'trigger').click()
+    })
+
+    await waitFor(() =>
+      expect(getByTestId(c3, 'status').textContent).toBe('fulfilled'),
+    )
+
+    // the components with the first cache key should be unaffected
+    await waitFor(() => {
+      expect(getByTestId(c1, 'data').textContent).toBe('C1')
+      expect(getByTestId(c2, 'status').textContent).toBe('fulfilled')
+      expect(getByTestId(c2, 'data').textContent).toBe('C1')
+      expect(getByTestId(c2, 'status').textContent).toBe('fulfilled')
+
+      // the component with the second cache key should be affected
+      expect(getByTestId(c3, 'data').textContent).toBe('C3')
+      expect(getByTestId(c3, 'status').textContent).toBe('fulfilled')
+      expect(getByTestId(c4, 'data').textContent).toBe('C3')
+      expect(getByTestId(c4, 'status').textContent).toBe('fulfilled')
+    })
+
+    // test reset from the component that triggered the mutation for the first cache key
+
+    act(() => {
+      getByTestId(c1, 'reset').click()
+    })
+
+    await waitFor(() => {
+      // the components with the first cache key should be affected
+      expect(getByTestId(c1, 'data').textContent).toBe('')
+      expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')
+      expect(getByTestId(c2, 'data').textContent).toBe('')
+      expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')
+
+      // the components with the second cache key should be unaffected
+      expect(getByTestId(c3, 'data').textContent).toBe('C3')
+      expect(getByTestId(c3, 'status').textContent).toBe('fulfilled')
+      expect(getByTestId(c4, 'data').textContent).toBe('C3')
+      expect(getByTestId(c4, 'status').textContent).toBe('fulfilled')
+    })
+  })
+
+  test('two mutations with different `fixedCacheKey` do not influence each other', async () => {
+    render(
+      <>
+        <Component name="C1" fixedCacheKey="test" />
+        <Component name="C2" fixedCacheKey="toast" />
+      </>,
+      { wrapper: storeRef.wrapper },
+    )
+    const c1 = screen.getByTestId('C1')
+    const c2 = screen.getByTestId('C2')
+    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')
+    expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')
+
+    act(() => {
+      getByTestId(c1, 'trigger').click()
+    })
+
+    await waitFor(() =>
+      expect(getByTestId(c1, 'status').textContent).toBe('fulfilled'),
+    )
+    expect(getByTestId(c1, 'data').textContent).toBe('C1')
+    expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')
+  })
+
+  test('unmounting and remounting keeps data intact', async () => {
+    const { rerender } = render(<Component name="C1" fixedCacheKey="test" />, {
+      wrapper: storeRef.wrapper,
+    })
+    let c1 = screen.getByTestId('C1')
+    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')
+
+    act(() => {
+      getByTestId(c1, 'trigger').click()
+    })
+
+    await waitFor(() =>
+      expect(getByTestId(c1, 'status').textContent).toBe('fulfilled'),
+    )
+    expect(getByTestId(c1, 'data').textContent).toBe('C1')
+
+    rerender(<div />)
+    expect(screen.queryByTestId('C1')).toBe(null)
+
+    rerender(<Component name="C1" fixedCacheKey="test" />)
+    c1 = screen.getByTestId('C1')
+    expect(getByTestId(c1, 'status').textContent).toBe('fulfilled')
+    expect(getByTestId(c1, 'data').textContent).toBe('C1')
+  })
+
+  test('(limitation) mutations using `fixedCacheKey` do not return `originalArgs`', async () => {
+    render(
+      <>
+        <Component name="C1" fixedCacheKey="test" />
+        <Component name="C2" fixedCacheKey="test" />
+      </>,
+      { wrapper: storeRef.wrapper },
+    )
+    const c1 = screen.getByTestId('C1')
+    const c2 = screen.getByTestId('C2')
+    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')
+    expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')
+
+    act(() => {
+      getByTestId(c1, 'trigger').click()
+    })
+
+    await waitFor(() =>
+      expect(getByTestId(c1, 'status').textContent).toBe('fulfilled'),
+    )
+    expect(getByTestId(c1, 'data').textContent).toBe('C1')
+    expect(getByTestId(c2, 'status').textContent).toBe('fulfilled')
+    expect(getByTestId(c2, 'data').textContent).toBe('C1')
+  })
+
+  test('a component without `fixedCacheKey` has `originalArgs`', async () => {
+    render(<Component name="C1" />, {
+      wrapper: storeRef.wrapper,
+    })
+    let c1 = screen.getByTestId('C1')
+    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')
+    expect(getByTestId(c1, 'originalArgs').textContent).toBe('undefined')
+
+    await act(async () => {
+      getByTestId(c1, 'trigger').click()
+      await Promise.resolve()
+    })
+
+    expect(getByTestId(c1, 'originalArgs').textContent).toBe('C1')
+  })
+
+  test('a component with `fixedCacheKey` does never have `originalArgs`', async () => {
+    render(<Component name="C1" fixedCacheKey="test" />, {
+      wrapper: storeRef.wrapper,
+    })
+    let c1 = screen.getByTestId('C1')
+    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')
+    expect(getByTestId(c1, 'originalArgs').textContent).toBe('undefined')
+
+    await act(async () => {
+      getByTestId(c1, 'trigger').click()
+    })
+
+    expect(getByTestId(c1, 'originalArgs').textContent).toBe('undefined')
+  })
+
+  test('using `fixedCacheKey` will always use the latest dispatched thunk, prevent races', async () => {
+    let resolve1: (str: string) => void, resolve2: (str: string) => void
+    const p1 = new Promise<string>((resolve) => {
+      resolve1 = resolve
+    })
+    const p2 = new Promise<string>((resolve) => {
+      resolve2 = resolve
+    })
+    render(
+      <>
+        <Component name="C1" fixedCacheKey="test" value={p1} />
+        <Component name="C2" fixedCacheKey="test" value={p2} />
+      </>,
+      { wrapper: storeRef.wrapper },
+    )
+    const c1 = screen.getByTestId('C1')
+    const c2 = screen.getByTestId('C2')
+    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')
+    expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')
+
+    await act(async () => {
+      getByTestId(c1, 'trigger').click()
+      await Promise.resolve()
+    })
+
+    expect(getByTestId(c1, 'status').textContent).toBe('pending')
+    expect(getByTestId(c1, 'data').textContent).toBe('')
+
+    act(() => {
+      getByTestId(c2, 'trigger').click()
+    })
+
+    expect(getByTestId(c1, 'status').textContent).toBe('pending')
+    expect(getByTestId(c1, 'data').textContent).toBe('')
+
+    await act(async () => {
+      resolve1!('this should not show up any more')
+      await Promise.resolve()
+    })
+
+    await delay(150)
+
+    expect(getByTestId(c1, 'status').textContent).toBe('pending')
+    expect(getByTestId(c1, 'data').textContent).toBe('')
+
+    await act(async () => {
+      resolve2!('this should be visible')
+      await Promise.resolve()
+    })
+
+    await delay(150)
+
+    expect(getByTestId(c1, 'status').textContent).toBe('fulfilled')
+    expect(getByTestId(c1, 'data').textContent).toBe('this should be visible')
+  })
+
+  test('using fixedCacheKey should create a new cache entry', async () => {
+    api.enhanceEndpoints({
+      endpoints: {
+        send: {
+          onCacheEntryAdded: (arg) => onNewCacheEntry(arg),
+        },
+      },
+    })
+
+    render(<Component name="C1" fixedCacheKey={'testKey'} />, {
+      wrapper: storeRef.wrapper,
+    })
+
+    let c1 = screen.getByTestId('C1')
+
+    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')
+    expect(getByTestId(c1, 'originalArgs').textContent).toBe('undefined')
+
+    await act(async () => {
+      getByTestId(c1, 'trigger').click()
+      await Promise.resolve()
+    })
+
+    expect(onNewCacheEntry).toHaveBeenCalledWith('C1')
+
+    api.enhanceEndpoints({
+      endpoints: {
+        send: {
+          onCacheEntryAdded: undefined,
+        },
+      },
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/utils.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/utils.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/utils.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,93 @@
+import { vi } from 'vitest'
+import { isOnline, isDocumentVisible, joinUrls } from '@internal/query/utils'
+
+afterAll(() => {
+  vi.restoreAllMocks()
+})
+
+describe('isOnline', () => {
+  test('Assumes online=true in a node env', () => {
+    vi.spyOn(window, 'navigator', 'get').mockImplementation(
+      () => undefined as any,
+    )
+
+    expect(navigator).toBeUndefined()
+    expect(isOnline()).toBe(true)
+  })
+
+  test('Returns false if navigator isOnline=false', () => {
+    vi.spyOn(window, 'navigator', 'get').mockImplementation(
+      () => ({ onLine: false }) as any,
+    )
+    expect(isOnline()).toBe(false)
+  })
+
+  test('Returns true if navigator isOnline=true', () => {
+    vi.spyOn(window, 'navigator', 'get').mockImplementation(
+      () => ({ onLine: true }) as any,
+    )
+    expect(isOnline()).toBe(true)
+  })
+})
+
+describe('isDocumentVisible', () => {
+  test('Assumes true when in a non-browser env', () => {
+    vi.spyOn(window, 'document', 'get').mockImplementation(
+      () => undefined as any,
+    )
+    expect(window.document).toBeUndefined()
+    expect(isDocumentVisible()).toBe(true)
+  })
+
+  test('Returns false when hidden=true', () => {
+    vi.spyOn(window, 'document', 'get').mockImplementation(
+      () => ({ visibilityState: 'hidden' }) as any,
+    )
+    expect(isDocumentVisible()).toBe(false)
+  })
+
+  test('Returns true when visibilityState=prerender', () => {
+    vi.spyOn(window, 'document', 'get').mockImplementation(
+      () => ({ visibilityState: 'prerender' }) as any,
+    )
+    expect(document.visibilityState).toBe('prerender')
+    expect(isDocumentVisible()).toBe(true)
+  })
+  test('Returns true when visibilityState=visible', () => {
+    vi.spyOn(window, 'document', 'get').mockImplementation(
+      () => ({ visibilityState: 'visible' }) as any,
+    )
+    expect(document.visibilityState).toBe('visible')
+    expect(isDocumentVisible()).toBe(true)
+  })
+  test('Returns true when visibilityState=undefined', () => {
+    vi.spyOn(window, 'document', 'get').mockImplementation(
+      () => ({ visibilityState: undefined }) as any,
+    )
+    expect(document.visibilityState).toBeUndefined()
+    expect(isDocumentVisible()).toBe(true)
+  })
+})
+
+describe('joinUrls', () => {
+  test.each([
+    ['/api/', '/banana', '/api/banana'],
+    ['/api/', 'banana', '/api/banana'],
+    ['/api', '/banana', '/api/banana'],
+    ['/api', 'banana', '/api/banana'],
+    ['', '/banana', '/banana'],
+    ['', 'banana', 'banana'],
+    ['api', '?a=1', 'api?a=1'],
+    ['api/', '?a=1', 'api/?a=1'],
+    ['api', 'banana?a=1', 'api/banana?a=1'],
+    ['api/', 'banana?a=1', 'api/banana?a=1'],
+    ['https://example.com/api', 'banana', 'https://example.com/api/banana'],
+    ['https://example.com/api', '/banana', 'https://example.com/api/banana'],
+    ['https://example.com/api/', 'banana', 'https://example.com/api/banana'],
+    ['https://example.com/api/', '/banana', 'https://example.com/api/banana'],
+    ['https://example.com/api/', 'https://example.org', 'https://example.org'],
+    ['https://example.com/api/', '//example.org', '//example.org'],
+  ])('%s and %s join to %s', (base, url, expected) => {
+    expect(joinUrls(base, url)).toBe(expected)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tsHelpers.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tsHelpers.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tsHelpers.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,50 @@
+export type Id<T> = { [K in keyof T]: T[K] } & {}
+export type WithRequiredProp<T, K extends keyof T> = Omit<T, K> &
+  Required<Pick<T, K>>
+export type Override<T1, T2> = T2 extends any ? Omit<T1, keyof T2> & T2 : never
+export function assertCast<T>(v: any): asserts v is T {}
+
+export function safeAssign<T extends object>(
+  target: T,
+  ...args: Array<Partial<NoInfer<T>>>
+): T {
+  return Object.assign(target, ...args)
+}
+
+/**
+ * Convert a Union type `(A|B)` to an intersection type `(A&B)`
+ */
+export type UnionToIntersection<U> = (
+  U extends any ? (k: U) => void : never
+) extends (k: infer I) => void
+  ? I
+  : never
+
+export type NonOptionalKeys<T> = {
+  [K in keyof T]-?: undefined extends T[K] ? never : K
+}[keyof T]
+
+export type HasRequiredProps<T, True, False> =
+  NonOptionalKeys<T> extends never ? False : True
+
+export type OptionalIfAllPropsOptional<T> = HasRequiredProps<T, T, T | never>
+
+export type NoInfer<T> = [T][T extends any ? 0 : never]
+
+export type NonUndefined<T> = T extends undefined ? never : T
+
+export type UnwrapPromise<T> = T extends PromiseLike<infer V> ? V : T
+
+export type MaybePromise<T> = T | PromiseLike<T>
+
+export type OmitFromUnion<T, K extends keyof T> = T extends any
+  ? Omit<T, K>
+  : never
+
+export type IsAny<T, True, False = never> = true | false extends (
+  T extends never ? true : false
+)
+  ? True
+  : False
+
+export type CastAny<T, CastTo> = IsAny<T, CastTo, T>
Index: node_modules/@reduxjs/toolkit/src/query/utils/capitalize.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/capitalize.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/capitalize.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,3 @@
+export function capitalize(str: string) {
+  return str.replace(str[0], str[0].toUpperCase())
+}
Index: node_modules/@reduxjs/toolkit/src/query/utils/copyWithStructuralSharing.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/copyWithStructuralSharing.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/copyWithStructuralSharing.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,27 @@
+import { isPlainObject as _iPO } from '../core/rtkImports'
+
+// remove type guard
+const isPlainObject: (_: any) => boolean = _iPO
+
+export function copyWithStructuralSharing<T>(oldObj: any, newObj: T): T
+export function copyWithStructuralSharing(oldObj: any, newObj: any): any {
+  if (
+    oldObj === newObj ||
+    !(
+      (isPlainObject(oldObj) && isPlainObject(newObj)) ||
+      (Array.isArray(oldObj) && Array.isArray(newObj))
+    )
+  ) {
+    return newObj
+  }
+  const newKeys = Object.keys(newObj)
+  const oldKeys = Object.keys(oldObj)
+
+  let isSameObject = newKeys.length === oldKeys.length
+  const mergeObj: any = Array.isArray(newObj) ? [] : {}
+  for (const key of newKeys) {
+    mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key])
+    if (isSameObject) isSameObject = oldObj[key] === mergeObj[key]
+  }
+  return isSameObject ? oldObj : mergeObj
+}
Index: node_modules/@reduxjs/toolkit/src/query/utils/countObjectKeys.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/countObjectKeys.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/countObjectKeys.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,14 @@
+// Fast method for counting an object's keys
+// without resorting to `Object.keys(obj).length
+// Will this make a big difference in perf? Probably not
+// But we can save a few allocations.
+
+export function countObjectKeys(obj: Record<any, any>) {
+  let count = 0
+
+  for (const _key in obj) {
+    count++
+  }
+
+  return count
+}
Index: node_modules/@reduxjs/toolkit/src/query/utils/filterMap.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/filterMap.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/filterMap.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,27 @@
+// Preserve type guard predicate behavior when passing to mapper
+export function filterMap<T, U, S extends T = T>(
+  array: readonly T[],
+  predicate: (item: T, index: number) => item is S,
+  mapper: (item: S, index: number) => U | U[],
+): U[]
+
+export function filterMap<T, U>(
+  array: readonly T[],
+  predicate: (item: T, index: number) => boolean,
+  mapper: (item: T, index: number) => U | U[],
+): U[]
+
+export function filterMap<T, U>(
+  array: readonly T[],
+  predicate: (item: T, index: number) => boolean,
+  mapper: (item: T, index: number) => U | U[],
+): U[] {
+  return array
+    .reduce<(U | U[])[]>((acc, item, i) => {
+      if (predicate(item as any, i)) {
+        acc.push(mapper(item as any, i))
+      }
+      return acc
+    }, [])
+    .flat() as U[]
+}
Index: node_modules/@reduxjs/toolkit/src/query/utils/getCurrent.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/getCurrent.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/getCurrent.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,6 @@
+import type { Draft } from 'immer'
+import { current, isDraft } from '../utils/immerImports'
+
+export function getCurrent<T>(value: T | Draft<T>): T {
+  return (isDraft(value) ? current(value) : value) as T
+}
Index: node_modules/@reduxjs/toolkit/src/query/utils/getOrInsert.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/getOrInsert.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/getOrInsert.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,41 @@
+// Duplicate some of the utils in `/src/utils` to ensure
+// we don't end up dragging in larger chunks of the RTK core
+// into the RTKQ bundle
+
+export function getOrInsert<K extends object, V>(
+  map: WeakMap<K, V>,
+  key: K,
+  value: V,
+): V
+export function getOrInsert<K, V>(map: Map<K, V>, key: K, value: V): V
+export function getOrInsert<K extends object, V>(
+  map: Map<K, V> | WeakMap<K, V>,
+  key: K,
+  value: V,
+): V {
+  if (map.has(key)) return map.get(key) as V
+
+  return map.set(key, value).get(key) as V
+}
+
+export function getOrInsertComputed<K extends object, V>(
+  map: WeakMap<K, V>,
+  key: K,
+  compute: (key: K) => V,
+): V
+export function getOrInsertComputed<K, V>(
+  map: Map<K, V>,
+  key: K,
+  compute: (key: K) => V,
+): V
+export function getOrInsertComputed<K extends object, V>(
+  map: Map<K, V> | WeakMap<K, V>,
+  key: K,
+  compute: (key: K) => V,
+): V {
+  if (map.has(key)) return map.get(key) as V
+
+  return map.set(key, compute(key)).get(key) as V
+}
+
+export const createNewMap = () => new Map()
Index: node_modules/@reduxjs/toolkit/src/query/utils/immerImports.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/immerImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/immerImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,9 @@
+export {
+  current,
+  isDraft,
+  applyPatches,
+  original,
+  isDraftable,
+  produceWithPatches,
+  enablePatches,
+} from 'immer'
Index: node_modules/@reduxjs/toolkit/src/query/utils/index.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,11 @@
+export * from './capitalize'
+export * from './copyWithStructuralSharing'
+export * from './countObjectKeys'
+export * from './filterMap'
+export * from './isAbsoluteUrl'
+export * from './isDocumentVisible'
+export * from './isNotNullish'
+export * from './isOnline'
+export * from './isValidUrl'
+export * from './joinUrls'
+export * from './getOrInsert'
Index: node_modules/@reduxjs/toolkit/src/query/utils/isAbsoluteUrl.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/isAbsoluteUrl.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/isAbsoluteUrl.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,9 @@
+/**
+ * If either :// or // is present consider it to be an absolute url
+ *
+ * @param url string
+ */
+
+export function isAbsoluteUrl(url: string) {
+  return new RegExp(`(^|:)//`).test(url)
+}
Index: node_modules/@reduxjs/toolkit/src/query/utils/isDocumentVisible.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/isDocumentVisible.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/isDocumentVisible.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,12 @@
+/**
+ * Assumes true for a non-browser env, otherwise makes a best effort
+ * @link https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState
+ */
+export function isDocumentVisible(): boolean {
+  // `document` may not exist in non-browser envs (like RN)
+  if (typeof document === 'undefined') {
+    return true
+  }
+  // Match true for visible, prerender, undefined
+  return document.visibilityState !== 'hidden'
+}
Index: node_modules/@reduxjs/toolkit/src/query/utils/isNotNullish.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/isNotNullish.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/isNotNullish.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,7 @@
+export function isNotNullish<T>(v: T | null | undefined): v is T {
+  return v != null
+}
+
+export function filterNullishValues<T>(map?: Map<any, T>) {
+  return [...(map?.values() ?? [])].filter(isNotNullish) as NonNullable<T>[]
+}
Index: node_modules/@reduxjs/toolkit/src/query/utils/isOnline.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/isOnline.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/isOnline.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,12 @@
+/**
+ * Assumes a browser is online if `undefined`, otherwise makes a best effort
+ * @link https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine
+ */
+export function isOnline() {
+  // We set the default config value in the store, so we'd need to check for this in a SSR env
+  return typeof navigator === 'undefined'
+    ? true
+    : navigator.onLine === undefined
+      ? true
+      : navigator.onLine
+}
Index: node_modules/@reduxjs/toolkit/src/query/utils/isValidUrl.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/isValidUrl.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/isValidUrl.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,9 @@
+export function isValidUrl(string: string) {
+  try {
+    new URL(string)
+  } catch (_) {
+    return false
+  }
+
+  return true
+}
Index: node_modules/@reduxjs/toolkit/src/query/utils/joinUrls.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/joinUrls.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/joinUrls.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,26 @@
+import { isAbsoluteUrl } from './isAbsoluteUrl'
+
+const withoutTrailingSlash = (url: string) => url.replace(/\/$/, '')
+const withoutLeadingSlash = (url: string) => url.replace(/^\//, '')
+
+export function joinUrls(
+  base: string | undefined,
+  url: string | undefined,
+): string {
+  if (!base) {
+    return url!
+  }
+  if (!url) {
+    return base
+  }
+
+  if (isAbsoluteUrl(url)) {
+    return url
+  }
+
+  const delimiter = base.endsWith('/') || !url.startsWith('?') ? '/' : ''
+  base = withoutTrailingSlash(base)
+  url = withoutLeadingSlash(url)
+
+  return `${base}${delimiter}${url}`
+}
Index: node_modules/@reduxjs/toolkit/src/query/utils/signals.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/signals.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/signals.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,33 @@
+// AbortSignal.timeout() is currently baseline 2024
+export const timeoutSignal = (milliseconds: number) => {
+  const abortController = new AbortController()
+  setTimeout(() => {
+    const message = 'signal timed out'
+    const name = 'TimeoutError'
+    abortController.abort(
+      // some environments (React Native, Node) don't have DOMException
+      typeof DOMException !== 'undefined'
+        ? new DOMException(message, name)
+        : Object.assign(new Error(message), { name }),
+    )
+  }, milliseconds)
+  return abortController.signal
+}
+
+// AbortSignal.any() is currently baseline 2024
+export const anySignal = (...signals: AbortSignal[]) => {
+  // if any are already aborted, return an already aborted signal
+  for (const signal of signals)
+    if (signal.aborted) return AbortSignal.abort(signal.reason)
+
+  // otherwise, create a new signal that aborts when any of the given signals abort
+  const abortController = new AbortController()
+  for (const signal of signals) {
+    signal.addEventListener(
+      'abort',
+      () => abortController.abort(signal.reason),
+      { signal: abortController.signal, once: true },
+    )
+  }
+  return abortController.signal
+}
Index: node_modules/@reduxjs/toolkit/src/react/index.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/react/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/react/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,7 @@
+// This must remain here so that the `mangleErrors.cjs` build script
+// does not have to import this into each source file it rewrites.
+import { formatProdErrorMessage } from '@reduxjs/toolkit'
+export * from '@reduxjs/toolkit'
+
+export { createDynamicMiddleware } from '../dynamicMiddleware/react'
+export type { CreateDispatchWithMiddlewareHook } from '../dynamicMiddleware/react/index'
Index: node_modules/@reduxjs/toolkit/src/reduxImports.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/reduxImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/reduxImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,8 @@
+export {
+  createStore,
+  combineReducers,
+  applyMiddleware,
+  compose,
+  isPlainObject,
+  isAction,
+} from 'redux'
Index: node_modules/@reduxjs/toolkit/src/reselectImports.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/reselectImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/reselectImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+export { createSelectorCreator, weakMapMemoize } from 'reselect'
Index: node_modules/@reduxjs/toolkit/src/serializableStateInvariantMiddleware.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/serializableStateInvariantMiddleware.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/serializableStateInvariantMiddleware.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,285 @@
+import type { Middleware } from 'redux'
+import { isAction, isPlainObject } from './reduxImports'
+import { getTimeMeasureUtils } from './utils'
+
+/**
+ * Returns true if the passed value is "plain", i.e. a value that is either
+ * directly JSON-serializable (boolean, number, string, array, plain object)
+ * or `undefined`.
+ *
+ * @param val The value to check.
+ *
+ * @public
+ */
+export function isPlain(val: any) {
+  const type = typeof val
+  return (
+    val == null ||
+    type === 'string' ||
+    type === 'boolean' ||
+    type === 'number' ||
+    Array.isArray(val) ||
+    isPlainObject(val)
+  )
+}
+
+interface NonSerializableValue {
+  keyPath: string
+  value: unknown
+}
+
+export type IgnorePaths = readonly (string | RegExp)[]
+
+/**
+ * @public
+ */
+export function findNonSerializableValue(
+  value: unknown,
+  path: string = '',
+  isSerializable: (value: unknown) => boolean = isPlain,
+  getEntries?: (value: unknown) => [string, any][],
+  ignoredPaths: IgnorePaths = [],
+  cache?: WeakSet<object>,
+): NonSerializableValue | false {
+  let foundNestedSerializable: NonSerializableValue | false
+
+  if (!isSerializable(value)) {
+    return {
+      keyPath: path || '<root>',
+      value: value,
+    }
+  }
+
+  if (typeof value !== 'object' || value === null) {
+    return false
+  }
+
+  if (cache?.has(value)) return false
+
+  const entries = getEntries != null ? getEntries(value) : Object.entries(value)
+
+  const hasIgnoredPaths = ignoredPaths.length > 0
+
+  for (const [key, nestedValue] of entries) {
+    const nestedPath = path ? path + '.' + key : key
+
+    if (hasIgnoredPaths) {
+      const hasMatches = ignoredPaths.some((ignored) => {
+        if (ignored instanceof RegExp) {
+          return ignored.test(nestedPath)
+        }
+        return nestedPath === ignored
+      })
+      if (hasMatches) {
+        continue
+      }
+    }
+
+    if (!isSerializable(nestedValue)) {
+      return {
+        keyPath: nestedPath,
+        value: nestedValue,
+      }
+    }
+
+    if (typeof nestedValue === 'object') {
+      foundNestedSerializable = findNonSerializableValue(
+        nestedValue,
+        nestedPath,
+        isSerializable,
+        getEntries,
+        ignoredPaths,
+        cache,
+      )
+
+      if (foundNestedSerializable) {
+        return foundNestedSerializable
+      }
+    }
+  }
+
+  if (cache && isNestedFrozen(value)) cache.add(value)
+
+  return false
+}
+
+export function isNestedFrozen(value: object) {
+  if (!Object.isFrozen(value)) return false
+
+  for (const nestedValue of Object.values(value)) {
+    if (typeof nestedValue !== 'object' || nestedValue === null) continue
+
+    if (!isNestedFrozen(nestedValue)) return false
+  }
+
+  return true
+}
+
+/**
+ * Options for `createSerializableStateInvariantMiddleware()`.
+ *
+ * @public
+ */
+export interface SerializableStateInvariantMiddlewareOptions {
+  /**
+   * The function to check if a value is considered serializable. This
+   * function is applied recursively to every value contained in the
+   * state. Defaults to `isPlain()`.
+   */
+  isSerializable?: (value: any) => boolean
+  /**
+   * The function that will be used to retrieve entries from each
+   * value.  If unspecified, `Object.entries` will be used. Defaults
+   * to `undefined`.
+   */
+  getEntries?: (value: any) => [string, any][]
+
+  /**
+   * An array of action types to ignore when checking for serializability.
+   * Defaults to []
+   */
+  ignoredActions?: string[]
+
+  /**
+   * An array of dot-separated path strings or regular expressions to ignore
+   * when checking for serializability, Defaults to
+   * ['meta.arg', 'meta.baseQueryMeta']
+   */
+  ignoredActionPaths?: (string | RegExp)[]
+
+  /**
+   * An array of dot-separated path strings or regular expressions to ignore
+   * when checking for serializability, Defaults to []
+   */
+  ignoredPaths?: (string | RegExp)[]
+  /**
+   * Execution time warning threshold. If the middleware takes longer
+   * than `warnAfter` ms, a warning will be displayed in the console.
+   * Defaults to 32ms.
+   */
+  warnAfter?: number
+
+  /**
+   * Opt out of checking state. When set to `true`, other state-related params will be ignored.
+   */
+  ignoreState?: boolean
+
+  /**
+   * Opt out of checking actions. When set to `true`, other action-related params will be ignored.
+   */
+  ignoreActions?: boolean
+
+  /**
+   * Opt out of caching the results. The cache uses a WeakSet and speeds up repeated checking processes.
+   * The cache is automatically disabled if no browser support for WeakSet is present.
+   */
+  disableCache?: boolean
+}
+
+/**
+ * Creates a middleware that, after every state change, checks if the new
+ * state is serializable. If a non-serializable value is found within the
+ * state, an error is printed to the console.
+ *
+ * @param options Middleware options.
+ *
+ * @public
+ */
+export function createSerializableStateInvariantMiddleware(
+  options: SerializableStateInvariantMiddlewareOptions = {},
+): Middleware {
+  if (process.env.NODE_ENV === 'production') {
+    return () => (next) => (action) => next(action)
+  } else {
+    const {
+      isSerializable = isPlain,
+      getEntries,
+      ignoredActions = [],
+      ignoredActionPaths = ['meta.arg', 'meta.baseQueryMeta'],
+      ignoredPaths = [],
+      warnAfter = 32,
+      ignoreState = false,
+      ignoreActions = false,
+      disableCache = false,
+    } = options
+
+    const cache: WeakSet<object> | undefined =
+      !disableCache && WeakSet ? new WeakSet() : undefined
+
+    return (storeAPI) => (next) => (action) => {
+      if (!isAction(action)) {
+        return next(action)
+      }
+
+      const result = next(action)
+
+      const measureUtils = getTimeMeasureUtils(
+        warnAfter,
+        'SerializableStateInvariantMiddleware',
+      )
+
+      if (
+        !ignoreActions &&
+        !(
+          ignoredActions.length &&
+          ignoredActions.indexOf(action.type as any) !== -1
+        )
+      ) {
+        measureUtils.measureTime(() => {
+          const foundActionNonSerializableValue = findNonSerializableValue(
+            action,
+            '',
+            isSerializable,
+            getEntries,
+            ignoredActionPaths,
+            cache,
+          )
+
+          if (foundActionNonSerializableValue) {
+            const { keyPath, value } = foundActionNonSerializableValue
+
+            console.error(
+              `A non-serializable value was detected in an action, in the path: \`${keyPath}\`. Value:`,
+              value,
+              '\nTake a look at the logic that dispatched this action: ',
+              action,
+              '\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)',
+              '\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)',
+            )
+          }
+        })
+      }
+
+      if (!ignoreState) {
+        measureUtils.measureTime(() => {
+          const state = storeAPI.getState()
+
+          const foundStateNonSerializableValue = findNonSerializableValue(
+            state,
+            '',
+            isSerializable,
+            getEntries,
+            ignoredPaths,
+            cache,
+          )
+
+          if (foundStateNonSerializableValue) {
+            const { keyPath, value } = foundStateNonSerializableValue
+
+            console.error(
+              `A non-serializable value was detected in the state, in the path: \`${keyPath}\`. Value:`,
+              value,
+              `
+Take a look at the reducer(s) handling this action type: ${action.type}.
+(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`,
+            )
+          }
+        })
+
+        measureUtils.warnIfExceeded()
+      }
+
+      return result
+    }
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/tests/Tuple.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/Tuple.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/Tuple.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,83 @@
+import { Tuple } from '@reduxjs/toolkit'
+
+describe('type tests', () => {
+  test('compatibility is checked between described types', () => {
+    const stringTuple = new Tuple('')
+
+    expectTypeOf(stringTuple).toEqualTypeOf<Tuple<[string]>>()
+
+    expectTypeOf(stringTuple).toMatchTypeOf<Tuple<string[]>>()
+
+    expectTypeOf(stringTuple).not.toMatchTypeOf<Tuple<[string, string]>>()
+
+    const numberTuple = new Tuple(0, 1)
+
+    expectTypeOf(numberTuple).not.toMatchTypeOf<Tuple<string[]>>()
+  })
+
+  test('concat is inferred properly', () => {
+    const singleString = new Tuple('')
+
+    expectTypeOf(singleString).toEqualTypeOf<Tuple<[string]>>()
+
+    expectTypeOf(singleString.concat('')).toEqualTypeOf<
+      Tuple<[string, string]>
+    >()
+
+    expectTypeOf(singleString.concat([''] as const)).toMatchTypeOf<
+      Tuple<[string, string]>
+    >()
+  })
+
+  test('prepend is inferred properly', () => {
+    const singleString = new Tuple('')
+
+    expectTypeOf(singleString).toEqualTypeOf<Tuple<[string]>>()
+
+    expectTypeOf(singleString.prepend('')).toEqualTypeOf<
+      Tuple<[string, string]>
+    >()
+
+    expectTypeOf(singleString.prepend([''] as const)).toMatchTypeOf<
+      Tuple<[string, string]>
+    >()
+  })
+
+  test('push must match existing items', () => {
+    const stringTuple = new Tuple('')
+
+    expectTypeOf(stringTuple.push).toBeCallableWith('')
+
+    expectTypeOf(stringTuple.push).parameter(0).not.toBeNumber()
+  })
+
+  test('Tuples can be combined', () => {
+    const stringTuple = new Tuple('')
+
+    const numberTuple = new Tuple(0, 1)
+
+    expectTypeOf(stringTuple.concat(numberTuple)).toEqualTypeOf<
+      Tuple<[string, number, number]>
+    >()
+
+    expectTypeOf(stringTuple.prepend(numberTuple)).toEqualTypeOf<
+      Tuple<[number, number, string]>
+    >()
+
+    expectTypeOf(numberTuple.concat(stringTuple)).toEqualTypeOf<
+      Tuple<[number, number, string]>
+    >()
+
+    expectTypeOf(numberTuple.prepend(stringTuple)).toEqualTypeOf<
+      Tuple<[string, number, number]>
+    >()
+
+    expectTypeOf(stringTuple.prepend(numberTuple)).not.toMatchTypeOf<
+      Tuple<[string, number, number]>
+    >()
+
+    expectTypeOf(stringTuple.concat(numberTuple)).not.toMatchTypeOf<
+      Tuple<[number, number, string]>
+    >()
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/actionCreatorInvariantMiddleware.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/actionCreatorInvariantMiddleware.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/actionCreatorInvariantMiddleware.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,61 @@
+import type { ActionCreatorInvariantMiddlewareOptions } from '@internal/actionCreatorInvariantMiddleware'
+import { getMessage } from '@internal/actionCreatorInvariantMiddleware'
+import { createActionCreatorInvariantMiddleware } from '@internal/actionCreatorInvariantMiddleware'
+import type { MiddlewareAPI } from '@reduxjs/toolkit'
+import { createAction } from '@reduxjs/toolkit'
+
+describe('createActionCreatorInvariantMiddleware', () => {
+  const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+
+  afterEach(() => {
+    consoleSpy.mockClear()
+  })
+  afterAll(() => {
+    consoleSpy.mockRestore()
+  })
+
+  const dummyAction = createAction('aSlice/anAction')
+
+  it('sends the action through the middleware chain', () => {
+    const next = vi.fn()
+    const dispatch = createActionCreatorInvariantMiddleware()(
+      {} as MiddlewareAPI,
+    )(next)
+    dispatch({ type: 'SOME_ACTION' })
+
+    expect(next).toHaveBeenCalledWith({
+      type: 'SOME_ACTION',
+    })
+  })
+
+  const makeActionTester = (
+    options?: ActionCreatorInvariantMiddlewareOptions,
+  ) =>
+    createActionCreatorInvariantMiddleware(options)({} as MiddlewareAPI)(
+      (action) => action,
+    )
+
+  it('logs a warning to console if an action creator is mistakenly dispatched', () => {
+    const testAction = makeActionTester()
+
+    testAction(dummyAction())
+
+    expect(consoleSpy).not.toHaveBeenCalled()
+
+    testAction(dummyAction)
+
+    expect(consoleSpy).toHaveBeenLastCalledWith(getMessage(dummyAction.type))
+  })
+
+  it('allows passing a custom predicate', () => {
+    let predicateCalled = false
+    const testAction = makeActionTester({
+      isActionCreator(action): action is Function {
+        predicateCalled = true
+        return false
+      },
+    })
+    testAction(dummyAction())
+    expect(predicateCalled).toBe(true)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/autoBatchEnhancer.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/autoBatchEnhancer.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/autoBatchEnhancer.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,208 @@
+import { configureStore } from '../configureStore'
+import { createSlice } from '../createSlice'
+import type { AutoBatchOptions } from '../autoBatchEnhancer'
+import { autoBatchEnhancer, prepareAutoBatched } from '../autoBatchEnhancer'
+import { delay } from '../utils'
+import { debounce } from 'lodash'
+
+interface CounterState {
+  value: number
+}
+
+const counterSlice = createSlice({
+  name: 'counter',
+  initialState: { value: 0 } as CounterState,
+  reducers: {
+    incrementBatched: {
+      // Batched, low-priority
+      reducer(state) {
+        state.value += 1
+      },
+      prepare: prepareAutoBatched<void>(),
+    },
+    // Not batched, normal priority
+    decrementUnbatched(state) {
+      state.value -= 1
+    },
+  },
+})
+const { incrementBatched, decrementUnbatched } = counterSlice.actions
+
+const makeStore = (autoBatchOptions?: AutoBatchOptions) => {
+  return configureStore({
+    reducer: counterSlice.reducer,
+    enhancers: (getDefaultEnhancers) =>
+      getDefaultEnhancers({
+        autoBatch: autoBatchOptions,
+      }),
+  })
+}
+
+let store: ReturnType<typeof makeStore>
+
+let subscriptionNotifications = 0
+
+const cases: AutoBatchOptions[] = [
+  { type: 'tick' },
+  { type: 'raf' },
+  { type: 'timer', timeout: 0 },
+  { type: 'timer', timeout: 10 },
+  { type: 'timer', timeout: 20 },
+  {
+    type: 'callback',
+    queueNotification: debounce((notify: () => void) => {
+      notify()
+    }, 5),
+  },
+]
+
+describe.each(cases)('autoBatchEnhancer: %j', (autoBatchOptions) => {
+  beforeEach(() => {
+    subscriptionNotifications = 0
+    store = makeStore(autoBatchOptions)
+
+    store.subscribe(() => {
+      subscriptionNotifications++
+    })
+  })
+  test('Does not alter normal subscription notification behavior', async () => {
+    store.dispatch(decrementUnbatched())
+    expect(subscriptionNotifications).toBe(1)
+    store.dispatch(decrementUnbatched())
+    expect(subscriptionNotifications).toBe(2)
+    store.dispatch(decrementUnbatched())
+    expect(subscriptionNotifications).toBe(3)
+    store.dispatch(decrementUnbatched())
+
+    await delay(25)
+
+    expect(subscriptionNotifications).toBe(4)
+  })
+
+  test('Only notifies once if several batched actions are dispatched in a row', async () => {
+    store.dispatch(incrementBatched())
+    expect(subscriptionNotifications).toBe(0)
+    store.dispatch(incrementBatched())
+    expect(subscriptionNotifications).toBe(0)
+    store.dispatch(incrementBatched())
+    expect(subscriptionNotifications).toBe(0)
+    store.dispatch(incrementBatched())
+
+    await delay(25)
+
+    expect(subscriptionNotifications).toBe(1)
+  })
+
+  test('Notifies immediately if a non-batched action is dispatched', async () => {
+    store.dispatch(incrementBatched())
+    expect(subscriptionNotifications).toBe(0)
+    store.dispatch(incrementBatched())
+    expect(subscriptionNotifications).toBe(0)
+    store.dispatch(decrementUnbatched())
+    expect(subscriptionNotifications).toBe(1)
+    store.dispatch(incrementBatched())
+
+    await delay(25)
+
+    expect(subscriptionNotifications).toBe(2)
+  })
+
+  test('Does not notify at end of tick if last action was normal priority', async () => {
+    store.dispatch(incrementBatched())
+    expect(subscriptionNotifications).toBe(0)
+    store.dispatch(incrementBatched())
+    expect(subscriptionNotifications).toBe(0)
+    store.dispatch(decrementUnbatched())
+    expect(subscriptionNotifications).toBe(1)
+    store.dispatch(incrementBatched())
+    store.dispatch(decrementUnbatched())
+    expect(subscriptionNotifications).toBe(2)
+    store.dispatch(decrementUnbatched())
+    expect(subscriptionNotifications).toBe(3)
+
+    await delay(25)
+
+    expect(subscriptionNotifications).toBe(3)
+  })
+})
+
+describe.each(cases)(
+  'autoBatchEnhancer with fake timers: %j',
+  (autoBatchOptions) => {
+    beforeAll(() => {
+      vitest.useFakeTimers({
+        toFake: ['setTimeout', 'queueMicrotask', 'requestAnimationFrame'],
+      })
+    })
+    afterAll(() => {
+      vitest.useRealTimers()
+    })
+    beforeEach(() => {
+      subscriptionNotifications = 0
+      store = makeStore(autoBatchOptions)
+
+      store.subscribe(() => {
+        subscriptionNotifications++
+      })
+    })
+    test('Does not alter normal subscription notification behavior', () => {
+      store.dispatch(decrementUnbatched())
+      expect(subscriptionNotifications).toBe(1)
+      store.dispatch(decrementUnbatched())
+      expect(subscriptionNotifications).toBe(2)
+      store.dispatch(decrementUnbatched())
+      expect(subscriptionNotifications).toBe(3)
+      store.dispatch(decrementUnbatched())
+
+      vitest.runAllTimers()
+
+      expect(subscriptionNotifications).toBe(4)
+    })
+
+    test('Only notifies once if several batched actions are dispatched in a row', () => {
+      store.dispatch(incrementBatched())
+      expect(subscriptionNotifications).toBe(0)
+      store.dispatch(incrementBatched())
+      expect(subscriptionNotifications).toBe(0)
+      store.dispatch(incrementBatched())
+      expect(subscriptionNotifications).toBe(0)
+      store.dispatch(incrementBatched())
+
+      vitest.runAllTimers()
+
+      expect(subscriptionNotifications).toBe(1)
+    })
+
+    test('Notifies immediately if a non-batched action is dispatched', () => {
+      store.dispatch(incrementBatched())
+      expect(subscriptionNotifications).toBe(0)
+      store.dispatch(incrementBatched())
+      expect(subscriptionNotifications).toBe(0)
+      store.dispatch(decrementUnbatched())
+      expect(subscriptionNotifications).toBe(1)
+      store.dispatch(incrementBatched())
+
+      vitest.runAllTimers()
+
+      expect(subscriptionNotifications).toBe(2)
+    })
+
+    test('Does not notify at end of tick if last action was normal priority', () => {
+      store.dispatch(incrementBatched())
+      expect(subscriptionNotifications).toBe(0)
+      store.dispatch(incrementBatched())
+      expect(subscriptionNotifications).toBe(0)
+      store.dispatch(decrementUnbatched())
+      expect(subscriptionNotifications).toBe(1)
+      store.dispatch(incrementBatched())
+      store.dispatch(decrementUnbatched())
+      expect(subscriptionNotifications).toBe(2)
+      store.dispatch(decrementUnbatched())
+      expect(subscriptionNotifications).toBe(3)
+
+      vitest.runAllTimers()
+
+      expect(subscriptionNotifications).toBe(3)
+    })
+  },
+)
Index: node_modules/@reduxjs/toolkit/src/tests/combineSlices.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/combineSlices.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/combineSlices.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,284 @@
+import type {
+  Action,
+  Reducer,
+  Slice,
+  WithSlice,
+  WithSlicePreloadedState,
+} from '@reduxjs/toolkit'
+import { combineSlices } from '@reduxjs/toolkit'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+
+declare const stringSlice: Slice<string, {}, 'string'>
+
+declare const numberSlice: Slice<number, {}, 'number'>
+
+declare const booleanReducer: Reducer<boolean>
+
+declare const mixedReducer: Reducer<string, Action, number>
+
+declare const mixedSliceLike: {
+  reducerPath: 'mixedSlice'
+  reducer: typeof mixedReducer
+}
+
+const exampleApi = createApi({
+  baseQuery: fetchBaseQuery(),
+  endpoints: (build) => ({
+    getThing: build.query({
+      query: () => '',
+    }),
+  }),
+})
+
+type ExampleApiState = ReturnType<typeof exampleApi.reducer>
+
+describe('type tests', () => {
+  test('combineSlices correctly combines static state', () => {
+    const rootReducer = combineSlices(
+      stringSlice,
+      numberSlice,
+      exampleApi,
+      {
+        boolean: booleanReducer,
+        mixed: mixedReducer,
+      },
+      mixedSliceLike,
+    )
+
+    expectTypeOf(rootReducer(undefined, { type: '' })).toEqualTypeOf<{
+      string: string
+      number: number
+      boolean: boolean
+      api: ExampleApiState
+      mixed: string
+      mixedSlice: string
+    }>()
+
+    // test for correct preloaded state handling
+    expectTypeOf(rootReducer).toBeCallableWith(
+      { mixed: 9, mixedSlice: 9 },
+      { type: '' },
+    )
+  })
+
+  test('combineSlices allows passing no initial reducers', () => {
+    const rootReducer = combineSlices()
+
+    expectTypeOf(rootReducer(undefined, { type: '' })).toEqualTypeOf<{}>()
+
+    const declaredLazy =
+      combineSlices().withLazyLoadedSlices<WithSlice<typeof numberSlice>>()
+
+    expectTypeOf(declaredLazy(undefined, { type: '' })).toEqualTypeOf<{
+      number?: number
+    }>()
+  })
+
+  test('withLazyLoadedSlices adds partial to state', () => {
+    const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<
+      WithSlice<typeof numberSlice> & WithSlice<typeof exampleApi>
+    >()
+
+    expectTypeOf(rootReducer(undefined, { type: '' }).number).toEqualTypeOf<
+      number | undefined
+    >()
+
+    expectTypeOf(rootReducer(undefined, { type: '' }).api).toEqualTypeOf<
+      ExampleApiState | undefined
+    >()
+  })
+
+  test('inject marks injected keys as required', () => {
+    const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<
+      WithSlice<typeof numberSlice> &
+        WithSlice<typeof exampleApi> & { boolean: boolean } & WithSlice<
+          typeof mixedSliceLike
+        > &
+        WithSlice<{
+          reducerPath: 'mixedReducer'
+          reducer: typeof mixedReducer
+        }>,
+      WithSlicePreloadedState<typeof numberSlice> &
+        WithSlicePreloadedState<typeof exampleApi> & {
+          boolean: boolean
+        } & WithSlicePreloadedState<typeof mixedSliceLike> &
+        WithSlicePreloadedState<{
+          reducerPath: 'mixedReducer'
+          reducer: typeof mixedReducer
+        }>
+    >()
+
+    expectTypeOf(rootReducer(undefined, { type: '' }).number).toEqualTypeOf<
+      number | undefined
+    >()
+
+    expectTypeOf(rootReducer(undefined, { type: '' }).boolean).toEqualTypeOf<
+      boolean | undefined
+    >()
+
+    expectTypeOf(rootReducer(undefined, { type: '' }).api).toEqualTypeOf<
+      ExampleApiState | undefined
+    >()
+
+    expectTypeOf(rootReducer(undefined, { type: '' }).mixedSlice).toEqualTypeOf<
+      string | undefined
+    >()
+
+    expectTypeOf(
+      rootReducer(undefined, { type: '' }).mixedReducer,
+    ).toEqualTypeOf<string | undefined>()
+
+    const withNumber = rootReducer.inject(numberSlice)
+
+    expectTypeOf(withNumber(undefined, { type: '' }).number).toBeNumber()
+
+    const withBool = rootReducer.inject({
+      reducerPath: 'boolean' as const,
+      reducer: booleanReducer,
+    })
+
+    expectTypeOf(withBool(undefined, { type: '' }).boolean).toBeBoolean()
+
+    const withApi = rootReducer.inject(exampleApi)
+
+    expectTypeOf(
+      withApi(undefined, { type: '' }).api,
+    ).toEqualTypeOf<ExampleApiState>()
+
+    const withMixedSlice = rootReducer.inject(mixedSliceLike)
+
+    expectTypeOf(
+      withMixedSlice(undefined, { type: '' }).mixedSlice,
+    ).toBeString()
+
+    const withMixedReducer = rootReducer.inject({
+      reducerPath: 'mixedReducer',
+      reducer: mixedReducer,
+    })
+
+    expectTypeOf(
+      withMixedReducer(undefined, { type: '' }).mixedReducer,
+    ).toBeString()
+  })
+
+  test('selector() allows defining selectors with injected reducers defined', () => {
+    const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<
+      WithSlice<typeof numberSlice> & { boolean: boolean }
+    >()
+
+    type RootState = ReturnType<typeof rootReducer>
+
+    const withoutInjection = rootReducer.selector(
+      (state: RootState) => state.number,
+    )
+
+    expectTypeOf(
+      withoutInjection(rootReducer(undefined, { type: '' })),
+    ).toEqualTypeOf<number | undefined>()
+
+    const withInjection = rootReducer
+      .inject(numberSlice)
+      .selector((state) => state.number)
+
+    expectTypeOf(
+      withInjection(rootReducer(undefined, { type: '' })),
+    ).toBeNumber()
+  })
+
+  test('selector() passes arguments through', () => {
+    const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<
+      WithSlice<typeof numberSlice> & { boolean: boolean }
+    >()
+
+    const selector = rootReducer
+      .inject(numberSlice)
+      .selector((state, num: number) => state.number)
+
+    const state = rootReducer(undefined, { type: '' })
+
+    expectTypeOf(selector).toBeCallableWith(state, 0)
+
+    // required argument
+    expectTypeOf(selector).parameters.not.toMatchTypeOf([state])
+
+    // number not string
+    expectTypeOf(selector).parameters.not.toMatchTypeOf([state, ''])
+  })
+
+  test('nested calls inferred correctly', () => {
+    const innerReducer =
+      combineSlices(stringSlice).withLazyLoadedSlices<
+        WithSlice<typeof numberSlice>
+      >()
+
+    const innerSelector = innerReducer.inject(numberSlice).selector(
+      (state) => state.number,
+      (rootState: RootState) => rootState.inner,
+    )
+
+    const outerReducer = combineSlices({ inner: innerReducer })
+
+    type RootState = ReturnType<typeof outerReducer>
+
+    expectTypeOf(outerReducer(undefined, { type: '' })).toMatchTypeOf<{
+      inner: { string: string }
+    }>()
+
+    expectTypeOf(
+      innerSelector(outerReducer(undefined, { type: '' })),
+    ).toBeNumber()
+  })
+
+  test('selector errors if selectorFn and selectState are mismatched', () => {
+    const combinedReducer =
+      combineSlices(stringSlice).withLazyLoadedSlices<
+        WithSlice<typeof numberSlice>
+      >()
+
+    const outerReducer = combineSlices({ inner: combinedReducer })
+
+    type RootState = ReturnType<typeof outerReducer>
+
+    combinedReducer.selector(
+      (state) => state.number,
+      // @ts-expect-error wrong state returned
+      (rootState: RootState) => rootState.inner.number,
+    )
+
+    combinedReducer.selector(
+      (state, num: number) => state.number,
+      // @ts-expect-error wrong arguments
+      (rootState: RootState, str: string) => rootState.inner,
+    )
+
+    combinedReducer.selector(
+      (state, num: number) => state.number,
+      (rootState: RootState) => rootState.inner,
+    )
+
+    // TODO: see if there's a way of making this work
+    // probably a rare case so not the end of the world if not
+    combinedReducer.selector(
+      (state) => state.number,
+      // @ts-ignore
+      (rootState: RootState, num: number) => rootState.inner,
+    )
+  })
+
+  test('correct type of state is inferred when not declared via `withLazyLoadedSlices`', () => {
+    // Related to https://github.com/reduxjs/redux-toolkit/issues/4171
+
+    const combinedReducer = combineSlices(stringSlice)
+
+    const withNumber = combinedReducer.inject(numberSlice)
+
+    expectTypeOf(withNumber).returns.toEqualTypeOf<{
+      string: string
+      number: number
+    }>()
+
+    expectTypeOf(
+      withNumber(undefined, { type: '' }).number,
+    ).toMatchTypeOf<number>()
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/combineSlices.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/combineSlices.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/combineSlices.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,215 @@
+import type { WithSlice } from '@reduxjs/toolkit'
+import {
+  combineSlices,
+  createAction,
+  createReducer,
+  createSlice,
+} from '@reduxjs/toolkit'
+
+const dummyAction = createAction<void>('dummy')
+
+const stringSlice = createSlice({
+  name: 'string',
+  initialState: '',
+  reducers: {},
+})
+
+const numberSlice = createSlice({
+  name: 'number',
+  initialState: 0,
+  reducers: {},
+})
+
+const booleanReducer = createReducer(false, () => {})
+
+const counterReducer = createSlice({
+  name: 'counter',
+  initialState: () => ({ value: 0 }),
+  reducers: {},
+})
+
+// mimic - we can't use RTKQ here directly
+const api = {
+  reducerPath: 'api' as const,
+  reducer: createReducer(
+    {
+      queries: {},
+      mutations: {},
+      provided: {},
+      subscriptions: {},
+      config: {
+        reducerPath: 'api',
+        invalidationBehavior: 'delayed',
+        online: false,
+        focused: false,
+        keepUnusedDataFor: 60,
+        middlewareRegistered: false,
+        refetchOnMountOrArgChange: false,
+        refetchOnReconnect: false,
+        refetchOnFocus: false,
+      },
+    },
+    () => {},
+  ),
+}
+
+describe('combineSlices', () => {
+  it('calls combineReducers to combine static slices/reducers', () => {
+    const combinedReducer = combineSlices(
+      stringSlice,
+      {
+        num: numberSlice.reducer,
+        boolean: booleanReducer,
+      },
+      api,
+    )
+    expect(combinedReducer(undefined, dummyAction())).toEqual({
+      string: stringSlice.getInitialState(),
+      num: numberSlice.getInitialState(),
+      boolean: booleanReducer.getInitialState(),
+      api: api.reducer.getInitialState(),
+    })
+  })
+  it('allows passing no initial reducers', () => {
+    const combinedReducer = combineSlices()
+
+    const result = combinedReducer(undefined, dummyAction())
+
+    expect(result).toEqual({})
+
+    // no-op if we have no reducers yet
+    expect(combinedReducer(result, dummyAction())).toBe(result)
+  })
+  describe('injects', () => {
+    beforeEach(() => {
+      vi.stubEnv('NODE_ENV', 'development')
+
+      return vi.unstubAllEnvs
+    })
+
+    it('injects slice', () => {
+      const combinedReducer =
+        combineSlices(stringSlice).withLazyLoadedSlices<
+          WithSlice<typeof numberSlice>
+        >()
+
+      expect(combinedReducer(undefined, dummyAction()).number).toBe(undefined)
+
+      const injectedReducer = combinedReducer.inject(numberSlice)
+
+      expect(injectedReducer(undefined, dummyAction()).number).toBe(
+        numberSlice.getInitialState(),
+      )
+    })
+    it('logs error when same name is used for different reducers', () => {
+      const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+      const combinedReducer = combineSlices(stringSlice).withLazyLoadedSlices<{
+        boolean: boolean
+      }>()
+
+      combinedReducer.inject({
+        reducerPath: 'boolean' as const,
+        reducer: booleanReducer,
+      })
+
+      combinedReducer.inject({
+        reducerPath: 'boolean' as const,
+        reducer: booleanReducer,
+      })
+
+      expect(consoleSpy).not.toHaveBeenCalled()
+
+      combinedReducer.inject({
+        reducerPath: 'boolean' as const,
+        // @ts-expect-error wrong reducer
+        reducer: stringSlice.reducer,
+      })
+
+      expect(consoleSpy).toHaveBeenCalledWith(
+        `called \`inject\` to override already-existing reducer boolean without specifying \`overrideExisting: true\``,
+      )
+      consoleSpy.mockRestore()
+    })
+    it('allows replacement of reducers if overrideExisting is true', () => {
+      const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+      const combinedReducer = combineSlices(stringSlice).withLazyLoadedSlices<
+        WithSlice<typeof numberSlice> &
+          WithSlice<typeof api> & { boolean: boolean }
+      >()
+
+      combinedReducer.inject(numberSlice)
+
+      combinedReducer.inject(
+        { reducerPath: 'number' as const, reducer: () => 0 },
+        { overrideExisting: true },
+      )
+
+      expect(consoleSpy).not.toHaveBeenCalled()
+    })
+  })
+  describe('selector', () => {
+    const combinedReducer = combineSlices(stringSlice).withLazyLoadedSlices<{
+      boolean: boolean
+      counter: { value: number }
+    }>()
+
+    const uninjectedState = combinedReducer(undefined, dummyAction())
+
+    const injectedReducer = combinedReducer.inject({
+      reducerPath: 'boolean' as const,
+      reducer: booleanReducer,
+    })
+
+    it('ensures state is defined in selector even if action has not been dispatched', () => {
+      expect(uninjectedState.boolean).toBe(undefined)
+
+      const selectBoolean = injectedReducer.selector((state) => state.boolean)
+
+      expect(selectBoolean(uninjectedState)).toBe(
+        booleanReducer.getInitialState(),
+      )
+    })
+    it('exposes original to allow for logging', () => {
+      const selectBoolean = injectedReducer.selector(
+        (state) => injectedReducer.selector.original(state).boolean,
+      )
+      expect(selectBoolean(uninjectedState)).toBe(undefined)
+    })
+    it('throws if original is called on something other than state proxy', () => {
+      expect(() => injectedReducer.selector.original({} as any)).toThrow(
+        'original must be used on state Proxy',
+      )
+    })
+    it('allows passing a selectState selector, to handle nested state', () => {
+      const wrappedReducer = combineSlices({
+        inner: combinedReducer,
+      })
+
+      type RootState = ReturnType<typeof wrappedReducer>
+
+      const selector = injectedReducer.selector(
+        (state) => state.boolean,
+        (rootState: RootState) => rootState.inner,
+      )
+
+      expect(selector(wrappedReducer(undefined, dummyAction()))).toBe(
+        booleanReducer.getInitialState(),
+      )
+    })
+    it('caches initial state', () => {
+      const beforeInject = combinedReducer(undefined, dummyAction())
+      const injectedReducer = combinedReducer.inject(counterReducer)
+      const selectCounter = injectedReducer.selector((state) => state.counter)
+      const counter = selectCounter(beforeInject)
+      expect(counter).toBe(selectCounter(beforeInject))
+
+      injectedReducer.inject(
+        { reducerPath: 'counter', reducer: () => ({ value: 0 }) },
+        { overrideExisting: true },
+      )
+      const counter2 = selectCounter(beforeInject)
+      expect(counter2).not.toBe(counter)
+      expect(counter2).toBe(selectCounter(beforeInject))
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/combinedTest.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/combinedTest.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/combinedTest.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,133 @@
+import type { PayloadAction } from '@reduxjs/toolkit'
+import {
+  createAsyncThunk,
+  createAction,
+  createSlice,
+  configureStore,
+  createEntityAdapter,
+} from '@reduxjs/toolkit'
+import type { EntityAdapter } from '@internal/entities/models'
+import type { BookModel } from '@internal/entities/tests/fixtures/book'
+
+describe('Combined entity slice', () => {
+  let adapter: EntityAdapter<BookModel, string>
+
+  beforeEach(() => {
+    adapter = createEntityAdapter({
+      selectId: (book: BookModel) => book.id,
+      sortComparer: (a, b) => a.title.localeCompare(b.title),
+    })
+  })
+
+  it('Entity and async features all works together', async () => {
+    const upsertBook = createAction<BookModel>('otherBooks/upsert')
+
+    type BooksState = ReturnType<typeof adapter.getInitialState> & {
+      loading: 'initial' | 'pending' | 'finished' | 'failed'
+      lastRequestId: string | null
+    }
+
+    const initialState: BooksState = adapter.getInitialState({
+      loading: 'initial',
+      lastRequestId: null,
+    })
+
+    const fakeBooks: BookModel[] = [
+      { id: 'b', title: 'Second' },
+      { id: 'a', title: 'First' },
+    ]
+
+    const fetchBooksTAC = createAsyncThunk<
+      BookModel[],
+      void,
+      {
+        state: { books: BooksState }
+      }
+    >(
+      'books/fetch',
+      async (arg, { getState, dispatch, extra, requestId, signal }) => {
+        const state = getState()
+        return fakeBooks
+      },
+    )
+
+    const booksSlice = createSlice({
+      name: 'books',
+      initialState,
+      reducers: {
+        addOne: adapter.addOne,
+        removeOne(state, action: PayloadAction<string>) {
+          const sizeBefore = state.ids.length
+          // Originally, having nested `produce` calls don't mutate `state` here as I would have expected.
+          // (note that `state` here is actually an Immer Draft<S>, from `createReducer`)
+          // One woarkound was to return the new plain result value instead
+          // See https://github.com/immerjs/immer/issues/533
+          // However, after tweaking `createStateOperator` to check if the argument is a draft,
+          // we can just treat the operator as strictly mutating, without returning a result,
+          // and the result should be correct.
+          const result = adapter.removeOne(state, action)
+
+          const sizeAfter = state.ids.length
+          if (sizeBefore > 0) {
+            expect(sizeAfter).toBe(sizeBefore - 1)
+          }
+
+          //Deliberately _don't_ return result
+        },
+      },
+      extraReducers: (builder) => {
+        builder.addCase(upsertBook, (state, action) => {
+          return adapter.upsertOne(state, action)
+        })
+        builder.addCase(fetchBooksTAC.pending, (state, action) => {
+          state.loading = 'pending'
+          state.lastRequestId = action.meta.requestId
+        })
+        builder.addCase(fetchBooksTAC.fulfilled, (state, action) => {
+          if (
+            state.loading === 'pending' &&
+            action.meta.requestId === state.lastRequestId
+          ) {
+            adapter.setAll(state, action.payload)
+            state.loading = 'finished'
+            state.lastRequestId = null
+          }
+        })
+      },
+    })
+
+    const { addOne, removeOne } = booksSlice.actions
+    const { reducer } = booksSlice
+
+    const store = configureStore({
+      reducer: {
+        books: reducer,
+      },
+    })
+
+    await store.dispatch(fetchBooksTAC())
+
+    const { books: booksAfterLoaded } = store.getState()
+    // Sorted, so "First" goes first
+    expect(booksAfterLoaded.ids).toEqual(['a', 'b'])
+    expect(booksAfterLoaded.lastRequestId).toBe(null)
+    expect(booksAfterLoaded.loading).toBe('finished')
+
+    store.dispatch(addOne({ id: 'd', title: 'Remove Me' }))
+    store.dispatch(removeOne('d'))
+
+    store.dispatch(addOne({ id: 'c', title: 'Middle' }))
+
+    const { books: booksAfterAddOne } = store.getState()
+
+    // Sorted, so "Middle" goes in the middle
+    expect(booksAfterAddOne.ids).toEqual(['a', 'c', 'b'])
+
+    store.dispatch(upsertBook({ id: 'c', title: 'Zeroth' }))
+
+    const { books: booksAfterUpsert } = store.getState()
+
+    // Sorted, so "Zeroth" goes last
+    expect(booksAfterUpsert.ids).toEqual(['a', 'b', 'c'])
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/configureStore.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/configureStore.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/configureStore.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,805 @@
+import type {
+  Action,
+  ConfigureStoreOptions,
+  Dispatch,
+  Middleware,
+  PayloadAction,
+  Reducer,
+  Store,
+  StoreEnhancer,
+  ThunkAction,
+  ThunkDispatch,
+  ThunkMiddleware,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import {
+  Tuple,
+  applyMiddleware,
+  combineReducers,
+  configureStore,
+  createSlice,
+} from '@reduxjs/toolkit'
+import { thunk } from 'redux-thunk'
+
+const _anyMiddleware: any = () => () => () => {}
+
+describe('type tests', () => {
+  test('configureStore() requires a valid reducer or reducer map.', () => {
+    configureStore({
+      reducer: (state, action) => 0,
+    })
+
+    configureStore({
+      reducer: {
+        counter1: () => 0,
+        counter2: () => 1,
+      },
+    })
+
+    // @ts-expect-error
+    configureStore({ reducer: 'not a reducer' })
+
+    // @ts-expect-error
+    configureStore({ reducer: { a: 'not a reducer' } })
+
+    // @ts-expect-error
+    configureStore({})
+  })
+
+  test('configureStore() infers the store state type.', () => {
+    const reducer: Reducer<number> = () => 0
+
+    const store = configureStore({ reducer })
+
+    expectTypeOf(store).toMatchTypeOf<Store<number, UnknownAction>>()
+
+    expectTypeOf(store).not.toMatchTypeOf<Store<string, UnknownAction>>()
+  })
+
+  test('configureStore() infers the store action type.', () => {
+    const reducer: Reducer<number, PayloadAction<number>> = () => 0
+
+    const store = configureStore({ reducer })
+
+    expectTypeOf(store).toMatchTypeOf<Store<number, PayloadAction<number>>>()
+
+    expectTypeOf(store).not.toMatchTypeOf<
+      Store<number, PayloadAction<string>>
+    >()
+  })
+
+  test('configureStore() accepts Tuple for middleware, but not plain array.', () => {
+    const middleware: Middleware = (store) => (next) => next
+
+    configureStore({
+      reducer: () => 0,
+      middleware: () => new Tuple(middleware),
+    })
+
+    configureStore({
+      reducer: () => 0,
+      // @ts-expect-error
+      middleware: () => [middleware],
+    })
+
+    configureStore({
+      reducer: () => 0,
+      // @ts-expect-error
+      middleware: () => new Tuple('not middleware'),
+    })
+  })
+
+  test('configureStore() accepts devTools flag.', () => {
+    configureStore({
+      reducer: () => 0,
+      devTools: true,
+    })
+
+    configureStore({
+      reducer: () => 0,
+      // @ts-expect-error
+      devTools: 'true',
+    })
+  })
+
+  test('configureStore() accepts devTools EnhancerOptions.', () => {
+    configureStore({
+      reducer: () => 0,
+      devTools: { name: 'myApp' },
+    })
+
+    configureStore({
+      reducer: () => 0,
+      // @ts-expect-error
+      devTools: { appName: 'myApp' },
+    })
+  })
+
+  test('configureStore() accepts preloadedState.', () => {
+    configureStore({
+      reducer: () => 0,
+      preloadedState: 0,
+    })
+
+    configureStore({
+      // @ts-expect-error
+      reducer: (_: number) => 0,
+      preloadedState: 'non-matching state type',
+    })
+  })
+
+  test('nullable state is preserved', () => {
+    const store = configureStore({
+      reducer: (): string | null => null,
+    })
+
+    expectTypeOf(store.getState()).toEqualTypeOf<string | null>()
+  })
+
+  test('configureStore() accepts store Tuple for enhancers, but not plain array', () => {
+    const enhancer = applyMiddleware(() => (next) => next)
+
+    const store = configureStore({
+      reducer: () => 0,
+      enhancers: () => new Tuple(enhancer),
+    })
+
+    const store2 = configureStore({
+      reducer: () => 0,
+      // @ts-expect-error
+      enhancers: () => [enhancer],
+    })
+
+    expectTypeOf(store.dispatch).toMatchTypeOf<
+      Dispatch & ThunkDispatch<number, undefined, UnknownAction>
+    >()
+
+    configureStore({
+      reducer: () => 0,
+      // @ts-expect-error
+      enhancers: () => new Tuple('not a store enhancer'),
+    })
+
+    const somePropertyStoreEnhancer: StoreEnhancer<{
+      someProperty: string
+    }> = (next) => {
+      return (reducer, preloadedState) => {
+        return {
+          ...next(reducer, preloadedState),
+          someProperty: 'some value',
+        }
+      }
+    }
+
+    const anotherPropertyStoreEnhancer: StoreEnhancer<{
+      anotherProperty: number
+    }> = (next) => {
+      return (reducer, preloadedState) => {
+        return {
+          ...next(reducer, preloadedState),
+          anotherProperty: 123,
+        }
+      }
+    }
+
+    const store3 = configureStore({
+      reducer: () => 0,
+      enhancers: () =>
+        new Tuple(somePropertyStoreEnhancer, anotherPropertyStoreEnhancer),
+    })
+
+    expectTypeOf(store3.dispatch).toEqualTypeOf<Dispatch>()
+
+    expectTypeOf(store3.someProperty).toBeString()
+
+    expectTypeOf(store3.anotherProperty).toBeNumber()
+
+    const storeWithCallback = configureStore({
+      reducer: () => 0,
+      enhancers: (getDefaultEnhancers) =>
+        getDefaultEnhancers()
+          .prepend(anotherPropertyStoreEnhancer)
+          .concat(somePropertyStoreEnhancer),
+    })
+
+    expectTypeOf(store3.dispatch).toMatchTypeOf<
+      Dispatch & ThunkDispatch<number, undefined, UnknownAction>
+    >()
+
+    expectTypeOf(store3.someProperty).toBeString()
+
+    expectTypeOf(store3.anotherProperty).toBeNumber()
+
+    const someStateExtendingEnhancer: StoreEnhancer<
+      {},
+      { someProperty: string }
+    > =
+      (next) =>
+      (...args) => {
+        const store = next(...args)
+        const getState = () => ({
+          ...store.getState(),
+          someProperty: 'some value',
+        })
+        return {
+          ...store,
+          getState,
+        } as any
+      }
+
+    const anotherStateExtendingEnhancer: StoreEnhancer<
+      {},
+      { anotherProperty: number }
+    > =
+      (next) =>
+      (...args) => {
+        const store = next(...args)
+        const getState = () => ({
+          ...store.getState(),
+          anotherProperty: 123,
+        })
+        return {
+          ...store,
+          getState,
+        } as any
+      }
+
+    const store4 = configureStore({
+      reducer: () => ({ aProperty: 0 }),
+      enhancers: () =>
+        new Tuple(someStateExtendingEnhancer, anotherStateExtendingEnhancer),
+    })
+
+    const state = store4.getState()
+
+    expectTypeOf(state.aProperty).toBeNumber()
+
+    expectTypeOf(state.someProperty).toBeString()
+
+    expectTypeOf(state.anotherProperty).toBeNumber()
+
+    const storeWithCallback2 = configureStore({
+      reducer: () => ({ aProperty: 0 }),
+      enhancers: (gDE) =>
+        gDE().concat(someStateExtendingEnhancer, anotherStateExtendingEnhancer),
+    })
+
+    const stateWithCallback = storeWithCallback2.getState()
+
+    expectTypeOf(stateWithCallback.aProperty).toBeNumber()
+
+    expectTypeOf(stateWithCallback.someProperty).toBeString()
+
+    expectTypeOf(stateWithCallback.anotherProperty).toBeNumber()
+  })
+
+  test('Preloaded state typings', () => {
+    const counterReducer1: Reducer<number> = () => 0
+    const counterReducer2: Reducer<number> = () => 0
+
+    test('partial preloaded state', () => {
+      const store = configureStore({
+        reducer: {
+          counter1: counterReducer1,
+          counter2: counterReducer2,
+        },
+        preloadedState: {
+          counter1: 0,
+        },
+      })
+
+      expectTypeOf(store.getState().counter1).toBeNumber()
+
+      expectTypeOf(store.getState().counter2).toBeNumber()
+    })
+
+    test('empty preloaded state', () => {
+      const store = configureStore({
+        reducer: {
+          counter1: counterReducer1,
+          counter2: counterReducer2,
+        },
+        preloadedState: {},
+      })
+
+      expectTypeOf(store.getState().counter1).toBeNumber()
+
+      expectTypeOf(store.getState().counter2).toBeNumber()
+    })
+
+    test('excess properties in preloaded state', () => {
+      const store = configureStore({
+        reducer: {
+          // @ts-expect-error
+          counter1: counterReducer1,
+          counter2: counterReducer2,
+        },
+        preloadedState: {
+          counter1: 0,
+          counter3: 5,
+        },
+      })
+
+      expectTypeOf(store.getState().counter1).toBeNumber()
+
+      expectTypeOf(store.getState().counter2).toBeNumber()
+    })
+
+    test('mismatching properties in preloaded state', () => {
+      const store = configureStore({
+        reducer: {
+          // @ts-expect-error
+          counter1: counterReducer1,
+          counter2: counterReducer2,
+        },
+        preloadedState: {
+          counter3: 5,
+        },
+      })
+
+      expectTypeOf(store.getState().counter1).toBeNumber()
+
+      expectTypeOf(store.getState().counter2).toBeNumber()
+    })
+
+    test('string preloaded state when expecting object', () => {
+      const store = configureStore({
+        reducer: {
+          // @ts-expect-error
+          counter1: counterReducer1,
+          counter2: counterReducer2,
+        },
+        preloadedState: 'test',
+      })
+
+      expectTypeOf(store.getState().counter1).toBeNumber()
+
+      expectTypeOf(store.getState().counter2).toBeNumber()
+    })
+
+    test('nested combineReducers allows partial', () => {
+      const store = configureStore({
+        reducer: {
+          group1: combineReducers({
+            counter1: counterReducer1,
+            counter2: counterReducer2,
+          }),
+          group2: combineReducers({
+            counter1: counterReducer1,
+            counter2: counterReducer2,
+          }),
+        },
+        preloadedState: {
+          group1: {
+            counter1: 5,
+          },
+        },
+      })
+
+      expectTypeOf(store.getState().group1.counter1).toBeNumber()
+
+      expectTypeOf(store.getState().group1.counter2).toBeNumber()
+
+      expectTypeOf(store.getState().group2.counter1).toBeNumber()
+
+      expectTypeOf(store.getState().group2.counter2).toBeNumber()
+    })
+
+    test('non-nested combineReducers does not allow partial', () => {
+      interface GroupState {
+        counter1: number
+        counter2: number
+      }
+
+      const initialState = { counter1: 0, counter2: 0 }
+
+      const group1Reducer: Reducer<GroupState> = (state = initialState) => state
+      const group2Reducer: Reducer<GroupState> = (state = initialState) => state
+
+      const store = configureStore({
+        reducer: {
+          // @ts-expect-error
+          group1: group1Reducer,
+          group2: group2Reducer,
+        },
+        preloadedState: {
+          group1: {
+            counter1: 5,
+          },
+        },
+      })
+
+      expectTypeOf(store.getState().group1.counter1).toBeNumber()
+
+      expectTypeOf(store.getState().group1.counter2).toBeNumber()
+
+      expectTypeOf(store.getState().group2.counter1).toBeNumber()
+
+      expectTypeOf(store.getState().group2.counter2).toBeNumber()
+    })
+  })
+
+  test('Dispatch typings', () => {
+    type StateA = number
+    const reducerA = () => 0
+    const thunkA = () => {
+      return (() => {}) as any as ThunkAction<Promise<'A'>, StateA, any, any>
+    }
+
+    type StateB = string
+    const thunkB = () => {
+      return (dispatch: Dispatch, getState: () => StateB) => {}
+    }
+
+    test('by default, dispatching Thunks is possible', () => {
+      const store = configureStore({
+        reducer: reducerA,
+      })
+
+      store.dispatch(thunkA())
+      // @ts-expect-error
+      store.dispatch(thunkB())
+
+      const res = store.dispatch((dispatch, getState) => {
+        return 42
+      })
+
+      const action = store.dispatch({ type: 'foo' })
+    })
+
+    test('return type of thunks and actions is inferred correctly', () => {
+      const slice = createSlice({
+        name: 'counter',
+        initialState: {
+          value: 0,
+        },
+        reducers: {
+          incrementByAmount: (state, action: PayloadAction<number>) => {
+            state.value += action.payload
+          },
+        },
+      })
+
+      const store = configureStore({
+        reducer: {
+          counter: slice.reducer,
+        },
+      })
+
+      const action = slice.actions.incrementByAmount(2)
+
+      const dispatchResult = store.dispatch(action)
+
+      expectTypeOf(dispatchResult).toMatchTypeOf<{
+        type: string
+        payload: number
+      }>()
+
+      const promiseResult = store.dispatch(async (dispatch) => {
+        return 42
+      })
+
+      expectTypeOf(promiseResult).toEqualTypeOf<Promise<number>>()
+
+      const store2 = configureStore({
+        reducer: {
+          counter: slice.reducer,
+        },
+        middleware: (gDM) =>
+          gDM({
+            thunk: {
+              extraArgument: 42,
+            },
+          }),
+      })
+
+      const dispatchResult2 = store2.dispatch(action)
+
+      expectTypeOf(dispatchResult2).toMatchTypeOf<{
+        type: string
+        payload: number
+      }>()
+    })
+
+    test('removing the Thunk Middleware', () => {
+      const store = configureStore({
+        reducer: reducerA,
+        middleware: () => new Tuple(),
+      })
+
+      expectTypeOf(store.dispatch).parameter(0).not.toMatchTypeOf(thunkA())
+
+      expectTypeOf(store.dispatch).parameter(0).not.toMatchTypeOf(thunkB())
+    })
+
+    test('adding the thunk middleware by hand', () => {
+      const store = configureStore({
+        reducer: reducerA,
+        middleware: () => new Tuple(thunk as ThunkMiddleware<StateA>),
+      })
+
+      store.dispatch(thunkA())
+      // @ts-expect-error
+      store.dispatch(thunkB())
+    })
+
+    test('custom middleware', () => {
+      const store = configureStore({
+        reducer: reducerA,
+        middleware: () =>
+          new Tuple(0 as unknown as Middleware<(a: StateA) => boolean, StateA>),
+      })
+
+      expectTypeOf(store.dispatch(5)).toBeBoolean()
+
+      expectTypeOf(store.dispatch(5)).not.toBeString()
+    })
+
+    test('multiple custom middleware', () => {
+      const middleware = [] as any as Tuple<
+        [
+          Middleware<(a: 'a') => 'A', StateA>,
+          Middleware<(b: 'b') => 'B', StateA>,
+          ThunkMiddleware<StateA>,
+        ]
+      >
+
+      const store = configureStore({
+        reducer: reducerA,
+        middleware: () => middleware,
+      })
+
+      expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()
+
+      expectTypeOf(store.dispatch('b')).toEqualTypeOf<'B'>()
+
+      expectTypeOf(store.dispatch(thunkA())).toEqualTypeOf<Promise<'A'>>()
+    })
+
+    test('Accepts thunk with `unknown`, `undefined` or `null` ThunkAction extraArgument per default', () => {
+      const store = configureStore({ reducer: {} })
+      // undefined is the default value for the ThunkMiddleware extraArgument
+      store.dispatch(function () {} as ThunkAction<
+        void,
+        {},
+        undefined,
+        UnknownAction
+      >)
+      // `null` for the `extra` generic was previously documented in the RTK "Advanced Tutorial", but
+      // is a bad pattern and users should use `unknown` instead
+      // @ts-expect-error
+      store.dispatch(function () {} as ThunkAction<
+        void,
+        {},
+        null,
+        UnknownAction
+      >)
+      // unknown is the best way to type a ThunkAction if you do not care
+      // about the value of the extraArgument, as it will always work with every
+      // ThunkMiddleware, no matter the actual extraArgument type
+      store.dispatch(function () {} as ThunkAction<
+        void,
+        {},
+        unknown,
+        UnknownAction
+      >)
+      // @ts-expect-error
+      store.dispatch(function () {} as ThunkAction<
+        void,
+        {},
+        boolean,
+        UnknownAction
+      >)
+    })
+
+    test('custom middleware and getDefaultMiddleware', () => {
+      const store = configureStore({
+        reducer: reducerA,
+        middleware: (gDM) =>
+          gDM().prepend((() => {}) as any as Middleware<
+            (a: 'a') => 'A',
+            StateA
+          >),
+      })
+
+      expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()
+
+      expectTypeOf(store.dispatch(thunkA())).toEqualTypeOf<Promise<'A'>>()
+
+      expectTypeOf(store.dispatch).parameter(0).not.toMatchTypeOf(thunkB())
+    })
+
+    test('custom middleware and getDefaultMiddleware, using prepend', () => {
+      const otherMiddleware: Middleware<(a: 'a') => 'A', StateA> =
+        _anyMiddleware
+
+      const store = configureStore({
+        reducer: reducerA,
+        middleware: (gDM) => {
+          const concatenated = gDM().prepend(otherMiddleware)
+
+          expectTypeOf(concatenated).toMatchTypeOf<
+            ReadonlyArray<
+              typeof otherMiddleware | ThunkMiddleware | Middleware<{}>
+            >
+          >()
+
+          return concatenated
+        },
+      })
+
+      expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()
+
+      expectTypeOf(store.dispatch(thunkA())).toEqualTypeOf<Promise<'A'>>()
+
+      expectTypeOf(store.dispatch).parameter(0).not.toMatchTypeOf(thunkB())
+    })
+
+    test('custom middleware and getDefaultMiddleware, using concat', () => {
+      const otherMiddleware: Middleware<(a: 'a') => 'A', StateA> =
+        _anyMiddleware
+
+      const store = configureStore({
+        reducer: reducerA,
+        middleware: (gDM) => {
+          const concatenated = gDM().concat(otherMiddleware)
+
+          expectTypeOf(concatenated).toMatchTypeOf<
+            ReadonlyArray<
+              typeof otherMiddleware | ThunkMiddleware | Middleware<{}>
+            >
+          >()
+
+          return concatenated
+        },
+      })
+
+      expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()
+
+      expectTypeOf(store.dispatch(thunkA())).toEqualTypeOf<Promise<'A'>>()
+
+      expectTypeOf(store.dispatch).parameter(0).not.toMatchTypeOf(thunkB())
+    })
+
+    test('middlewareBuilder notation, getDefaultMiddleware (unconfigured)', () => {
+      const store = configureStore({
+        reducer: reducerA,
+        middleware: (getDefaultMiddleware) =>
+          getDefaultMiddleware().prepend((() => {}) as any as Middleware<
+            (a: 'a') => 'A',
+            StateA
+          >),
+      })
+
+      expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()
+
+      expectTypeOf(store.dispatch(thunkA())).toEqualTypeOf<Promise<'A'>>()
+
+      expectTypeOf(store.dispatch).parameter(0).not.toMatchTypeOf(thunkB())
+    })
+
+    test('middlewareBuilder notation, getDefaultMiddleware, concat & prepend', () => {
+      const otherMiddleware: Middleware<(a: 'a') => 'A', StateA> =
+        _anyMiddleware
+
+      const otherMiddleware2: Middleware<(a: 'b') => 'B', StateA> =
+        _anyMiddleware
+
+      const store = configureStore({
+        reducer: reducerA,
+        middleware: (getDefaultMiddleware) =>
+          getDefaultMiddleware()
+            .concat(otherMiddleware)
+            .prepend(otherMiddleware2),
+      })
+
+      expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()
+
+      expectTypeOf(store.dispatch(thunkA())).toEqualTypeOf<Promise<'A'>>()
+
+      expectTypeOf(store.dispatch('b')).toEqualTypeOf<'B'>()
+
+      expectTypeOf(store.dispatch).parameter(0).not.toMatchTypeOf(thunkB())
+    })
+
+    test('middlewareBuilder notation, getDefaultMiddleware (thunk: false)', () => {
+      const store = configureStore({
+        reducer: reducerA,
+        middleware: (getDefaultMiddleware) =>
+          getDefaultMiddleware({ thunk: false }).prepend(
+            (() => {}) as any as Middleware<(a: 'a') => 'A', StateA>,
+          ),
+      })
+
+      expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()
+
+      expectTypeOf(store.dispatch).parameter(0).not.toMatchTypeOf(thunkA())
+    })
+
+    test("badly typed middleware won't make `dispatch` `any`", () => {
+      const store = configureStore({
+        reducer: reducerA,
+        middleware: (getDefaultMiddleware) =>
+          getDefaultMiddleware().concat(_anyMiddleware as Middleware<any>),
+      })
+
+      expectTypeOf(store.dispatch).not.toBeAny()
+    })
+
+    test("decorated `configureStore` won't make `dispatch` `never`", () => {
+      const someSlice = createSlice({
+        name: 'something',
+        initialState: null as any,
+        reducers: {
+          set(state) {
+            return state
+          },
+        },
+      })
+
+      function configureMyStore<S>(
+        options: Omit<ConfigureStoreOptions<S>, 'reducer'>,
+      ) {
+        return configureStore({
+          ...options,
+          reducer: someSlice.reducer,
+        })
+      }
+
+      const store = configureMyStore({})
+
+      expectTypeOf(store.dispatch).toBeFunction()
+    })
+
+    interface CounterState {
+      value: number
+    }
+
+    const counterSlice = createSlice({
+      name: 'counter',
+      initialState: { value: 0 } as CounterState,
+      reducers: {
+        increment(state) {
+          state.value += 1
+        },
+        decrement(state) {
+          state.value -= 1
+        },
+        // Use the PayloadAction type to declare the contents of `action.payload`
+        incrementByAmount: (state, action: PayloadAction<number>) => {
+          state.value += action.payload
+        },
+      },
+    })
+
+    type Unsubscribe = () => void
+
+    // A fake middleware that tells TS that an unsubscribe callback is being returned for a given action
+    // This is the same signature that the "listener" middleware uses
+    const dummyMiddleware: Middleware<
+      {
+        (action: Action<'actionListenerMiddleware/add'>): Unsubscribe
+      },
+      CounterState
+    > = (storeApi) => (next) => (action) => {}
+
+    const store = configureStore({
+      reducer: counterSlice.reducer,
+      middleware: (gDM) => gDM().prepend(dummyMiddleware),
+    })
+
+    // Order matters here! We need the listener type to come first, otherwise
+    // the thunk middleware type kicks in and TS thinks a plain action is being returned
+    expectTypeOf(store.dispatch).toEqualTypeOf<
+      ((action: Action<'actionListenerMiddleware/add'>) => Unsubscribe) &
+        ThunkDispatch<CounterState, undefined, UnknownAction> &
+        Dispatch<UnknownAction>
+    >()
+
+    const unsubscribe = store.dispatch({
+      type: 'actionListenerMiddleware/add',
+    } as const)
+
+    expectTypeOf(unsubscribe).toEqualTypeOf<Unsubscribe>()
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/configureStore.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/configureStore.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/configureStore.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,371 @@
+import * as DevTools from '@internal/devtoolsExtension'
+import type { Middleware, StoreEnhancer } from '@reduxjs/toolkit'
+import { Tuple } from '@reduxjs/toolkit'
+import type * as Redux from 'redux'
+import { vi } from 'vitest'
+
+vi.doMock('redux', async (importOriginal) => {
+  const redux = await importOriginal<typeof import('redux')>()
+
+  vi.spyOn(redux, 'applyMiddleware')
+  vi.spyOn(redux, 'combineReducers')
+  vi.spyOn(redux, 'compose')
+  vi.spyOn(redux, 'createStore')
+
+  return redux
+})
+
+describe('configureStore', async () => {
+  const composeWithDevToolsSpy = vi.spyOn(DevTools, 'composeWithDevTools')
+
+  const redux = await import('redux')
+
+  const { configureStore } = await import('@reduxjs/toolkit')
+
+  const reducer: Redux.Reducer = (state = {}, _action) => state
+
+  beforeEach(() => {
+    vi.clearAllMocks()
+  })
+
+  describe('given a function reducer', () => {
+    it('calls createStore with the reducer', () => {
+      configureStore({ reducer })
+      expect(configureStore({ reducer })).toBeInstanceOf(Object)
+
+      expect(redux.createStore).toHaveBeenCalledWith(
+        reducer,
+        undefined,
+        expect.any(Function),
+      )
+      expect(redux.applyMiddleware).toHaveBeenCalled()
+      if (process.env.TEST_DIST) {
+        expect(composeWithDevToolsSpy).not.toHaveBeenCalled()
+      } else {
+        expect(composeWithDevToolsSpy).toHaveBeenCalledTimes(2)
+      }
+    })
+  })
+
+  describe('given an object of reducers', () => {
+    it('calls createStore with the combined reducers', () => {
+      const reducer = {
+        reducer() {
+          return true
+        },
+      }
+      expect(configureStore({ reducer })).toBeInstanceOf(Object)
+      expect(redux.combineReducers).toHaveBeenCalledWith(reducer)
+      expect(redux.applyMiddleware).toHaveBeenCalled()
+      if (process.env.TEST_DIST) {
+        expect(composeWithDevToolsSpy).not.toHaveBeenCalled()
+      } else {
+        expect(composeWithDevToolsSpy).toHaveBeenCalledOnce()
+      }
+      expect(redux.createStore).toHaveBeenCalledWith(
+        expect.any(Function),
+        undefined,
+        expect.any(Function),
+      )
+    })
+  })
+
+  describe('given no reducer', () => {
+    it('throws', () => {
+      expect(configureStore).toThrow(
+        '`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers',
+      )
+    })
+  })
+
+  describe('given no middleware', () => {
+    it('calls createStore without any middleware', () => {
+      expect(
+        configureStore({ middleware: () => new Tuple(), reducer }),
+      ).toBeInstanceOf(Object)
+      expect(redux.applyMiddleware).toHaveBeenCalledWith()
+      if (process.env.TEST_DIST) {
+        expect(composeWithDevToolsSpy).not.toHaveBeenCalled()
+      } else {
+        expect(composeWithDevToolsSpy).toHaveBeenCalledOnce()
+      }
+      expect(redux.createStore).toHaveBeenCalledWith(
+        reducer,
+        undefined,
+        expect.any(Function),
+      )
+    })
+  })
+
+  describe('given an array of middleware', () => {
+    it('throws an error requiring a callback', () => {
+      // @ts-expect-error
+      expect(() => configureStore({ middleware: [], reducer })).toThrow(
+        '`middleware` field must be a callback',
+      )
+    })
+  })
+
+  describe('given undefined middleware', () => {
+    it('calls createStore with default middleware', () => {
+      expect(configureStore({ middleware: undefined, reducer })).toBeInstanceOf(
+        Object,
+      )
+      expect(redux.applyMiddleware).toHaveBeenCalledWith(
+        expect.any(Function), // immutableCheck
+        expect.any(Function), // thunk
+        expect.any(Function), // serializableCheck
+        expect.any(Function), // actionCreatorCheck
+      )
+      if (process.env.TEST_DIST) {
+        expect(composeWithDevToolsSpy).not.toHaveBeenCalled()
+      } else {
+        expect(composeWithDevToolsSpy).toHaveBeenCalledOnce()
+      }
+      expect(redux.createStore).toHaveBeenCalledWith(
+        reducer,
+        undefined,
+        expect.any(Function),
+      )
+    })
+  })
+
+  describe('given any middleware', () => {
+    const exampleMiddleware: Middleware<any, any> = () => (next) => (action) =>
+      next(action)
+    it('throws an error by default if there are duplicate middleware', () => {
+      const makeStore = () => {
+        return configureStore({
+          reducer,
+          middleware: (gDM) =>
+            gDM().concat(exampleMiddleware, exampleMiddleware),
+        })
+      }
+
+      expect(makeStore).toThrowError(
+        'Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.',
+      )
+    })
+
+    it('does not throw a duplicate middleware error if duplicateMiddlewareCheck is disabled', () => {
+      const makeStore = () => {
+        return configureStore({
+          reducer,
+          middleware: (gDM) =>
+            gDM().concat(exampleMiddleware, exampleMiddleware),
+          duplicateMiddlewareCheck: false,
+        })
+      }
+
+      expect(makeStore).not.toThrowError()
+    })
+  })
+
+  describe('given a middleware creation function that returns undefined', () => {
+    it('throws an error', () => {
+      const invalidBuilder = vi.fn((getDefaultMiddleware) => undefined as any)
+      expect(() =>
+        configureStore({ middleware: invalidBuilder, reducer }),
+      ).toThrow(
+        'when using a middleware builder function, an array of middleware must be returned',
+      )
+    })
+  })
+
+  describe('given a middleware creation function that returns an array with non-functions', () => {
+    it('throws an error', () => {
+      const invalidBuilder = vi.fn((getDefaultMiddleware) => [true] as any)
+      expect(() =>
+        configureStore({ middleware: invalidBuilder, reducer }),
+      ).toThrow('each middleware provided to configureStore must be a function')
+    })
+  })
+
+  describe('given custom middleware', () => {
+    it('calls createStore with custom middleware and without default middleware', () => {
+      const thank: Redux.Middleware = (_store) => (next) => (action) =>
+        next(action)
+      expect(
+        configureStore({ middleware: () => new Tuple(thank), reducer }),
+      ).toBeInstanceOf(Object)
+      expect(redux.applyMiddleware).toHaveBeenCalledWith(thank)
+      if (process.env.TEST_DIST) {
+        expect(composeWithDevToolsSpy).not.toHaveBeenCalled()
+      } else {
+        expect(composeWithDevToolsSpy).toHaveBeenCalledOnce()
+      }
+      expect(redux.createStore).toHaveBeenCalledWith(
+        reducer,
+        undefined,
+        expect.any(Function),
+      )
+    })
+  })
+
+  describe('middleware builder notation', () => {
+    it('calls builder, passes getDefaultMiddleware and uses returned middlewares', () => {
+      const thank = vi.fn(
+        ((_store) => (next) => (action) => 'foobar') as Redux.Middleware,
+      )
+
+      const builder = vi.fn((getDefaultMiddleware) => {
+        expect(getDefaultMiddleware).toEqual(expect.any(Function))
+        expect(getDefaultMiddleware()).toEqual(expect.any(Array))
+
+        return new Tuple(thank)
+      })
+
+      const store = configureStore({ middleware: builder, reducer })
+
+      expect(builder).toHaveBeenCalled()
+
+      expect(store.dispatch({ type: 'test' })).toBe('foobar')
+    })
+  })
+
+  describe('with devTools disabled', () => {
+    it('calls createStore without devTools enhancer', () => {
+      expect(configureStore({ devTools: false, reducer })).toBeInstanceOf(
+        Object,
+      )
+      expect(redux.applyMiddleware).toHaveBeenCalled()
+      expect(redux.compose).toHaveBeenCalled()
+      expect(redux.createStore).toHaveBeenCalledWith(
+        reducer,
+        undefined,
+        expect.any(Function),
+      )
+    })
+  })
+
+  describe('with devTools options', () => {
+    it('calls createStore with devTools enhancer and option', () => {
+      const options = {
+        name: 'myApp',
+        trace: true,
+      }
+      expect(configureStore({ devTools: options, reducer })).toBeInstanceOf(
+        Object,
+      )
+      expect(redux.applyMiddleware).toHaveBeenCalled()
+      if (process.env.TEST_DIST) {
+        expect(composeWithDevToolsSpy).not.toHaveBeenCalled()
+      } else {
+        expect(composeWithDevToolsSpy).toHaveBeenCalledOnce()
+
+        expect(composeWithDevToolsSpy).toHaveBeenLastCalledWith(options)
+      }
+      expect(redux.createStore).toHaveBeenCalledWith(
+        reducer,
+        undefined,
+        expect.any(Function),
+      )
+    })
+  })
+
+  describe('given preloadedState', () => {
+    it('calls createStore with preloadedState', () => {
+      expect(configureStore({ reducer })).toBeInstanceOf(Object)
+      expect(redux.applyMiddleware).toHaveBeenCalled()
+      if (process.env.TEST_DIST) {
+        expect(composeWithDevToolsSpy).not.toHaveBeenCalled()
+      } else {
+        expect(composeWithDevToolsSpy).toHaveBeenCalledOnce()
+      }
+      expect(redux.createStore).toHaveBeenCalledWith(
+        reducer,
+        undefined,
+        expect.any(Function),
+      )
+    })
+  })
+
+  describe('given enhancers', () => {
+    let dummyEnhancerCalled = false
+
+    const dummyEnhancer: StoreEnhancer =
+      (createStore) => (reducer, preloadedState) => {
+        dummyEnhancerCalled = true
+
+        return createStore(reducer, preloadedState)
+      }
+
+    beforeEach(() => {
+      dummyEnhancerCalled = false
+    })
+
+    it('calls createStore with enhancers', () => {
+      expect(
+        configureStore({
+          enhancers: (gDE) => gDE().concat(dummyEnhancer),
+          reducer,
+        }),
+      ).toBeInstanceOf(Object)
+      expect(redux.applyMiddleware).toHaveBeenCalled()
+      if (process.env.TEST_DIST) {
+        expect(composeWithDevToolsSpy).not.toHaveBeenCalled()
+      } else {
+        expect(composeWithDevToolsSpy).toHaveBeenCalledOnce()
+      }
+      expect(redux.createStore).toHaveBeenCalledWith(
+        reducer,
+        undefined,
+        expect.any(Function),
+      )
+
+      expect(dummyEnhancerCalled).toBe(true)
+    })
+
+    describe('invalid arguments', () => {
+      test('enhancers is not a callback', () => {
+        expect(() => configureStore({ reducer, enhancers: [] as any })).toThrow(
+          '`enhancers` field must be a callback',
+        )
+      })
+
+      test('callback fails to return array', () => {
+        expect(() =>
+          configureStore({ reducer, enhancers: (() => {}) as any }),
+        ).toThrow('`enhancers` callback must return an array')
+      })
+
+      test('array contains non-function', () => {
+        expect(() =>
+          configureStore({ reducer, enhancers: (() => ['']) as any }),
+        ).toThrow('each enhancer provided to configureStore must be a function')
+      })
+    })
+
+    const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+    beforeEach(() => {
+      consoleSpy.mockClear()
+    })
+    afterAll(() => {
+      consoleSpy.mockRestore()
+    })
+
+    it('warns if middleware enhancer is excluded from final array when middlewares are provided', () => {
+      const store = configureStore({
+        reducer,
+        enhancers: () => new Tuple(dummyEnhancer),
+      })
+
+      expect(dummyEnhancerCalled).toBe(true)
+
+      expect(consoleSpy).toHaveBeenCalledWith(
+        'middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`',
+      )
+    })
+    it("doesn't warn when middleware enhancer is excluded if no middlewares provided", () => {
+      const store = configureStore({
+        reducer,
+        middleware: () => new Tuple(),
+        enhancers: () => new Tuple(dummyEnhancer),
+      })
+
+      expect(dummyEnhancerCalled).toBe(true)
+
+      expect(consoleSpy).not.toHaveBeenCalled()
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/createAction.test-d.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/createAction.test-d.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/createAction.test-d.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,326 @@
+import type {
+  Action,
+  ActionCreator,
+  ActionCreatorWithNonInferrablePayload,
+  ActionCreatorWithOptionalPayload,
+  ActionCreatorWithPayload,
+  ActionCreatorWithPreparedPayload,
+  ActionCreatorWithoutPayload,
+  PayloadAction,
+  PayloadActionCreator,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import { createAction } from '@reduxjs/toolkit'
+
+describe('type tests', () => {
+  describe('PayloadAction', () => {
+    test('PayloadAction has type parameter for the payload.', () => {
+      const action: PayloadAction<number> = { type: '', payload: 5 }
+
+      expectTypeOf(action.payload).toBeNumber()
+
+      expectTypeOf(action.payload).not.toBeString()
+    })
+
+    test('PayloadAction type parameter is required.', () => {
+      expectTypeOf({ type: '', payload: 5 }).not.toMatchTypeOf<PayloadAction>()
+    })
+
+    test('PayloadAction has a string type tag.', () => {
+      expectTypeOf({ type: '', payload: 5 }).toEqualTypeOf<
+        PayloadAction<number>
+      >()
+
+      expectTypeOf({ type: 1, payload: 5 }).not.toMatchTypeOf<PayloadAction>()
+    })
+
+    test('PayloadAction is compatible with Action<string>', () => {
+      const action: PayloadAction<number> = { type: '', payload: 5 }
+
+      expectTypeOf(action).toMatchTypeOf<Action<string>>()
+    })
+  })
+
+  describe('PayloadActionCreator', () => {
+    test('PayloadActionCreator returns correctly typed PayloadAction depending on whether a payload is passed.', () => {
+      const actionCreator = Object.assign(
+        (payload?: number) => ({
+          type: 'action',
+          payload,
+        }),
+        { type: 'action' },
+      ) as PayloadActionCreator<number | undefined>
+
+      expectTypeOf(actionCreator(1)).toEqualTypeOf<
+        PayloadAction<number | undefined>
+      >()
+
+      expectTypeOf(actionCreator()).toEqualTypeOf<
+        PayloadAction<number | undefined>
+      >()
+
+      expectTypeOf(actionCreator(undefined)).toEqualTypeOf<
+        PayloadAction<number | undefined>
+      >()
+
+      expectTypeOf(actionCreator()).not.toMatchTypeOf<PayloadAction<number>>()
+
+      expectTypeOf(actionCreator(1)).not.toMatchTypeOf<
+        PayloadAction<undefined>
+      >()
+    })
+
+    test('PayloadActionCreator is compatible with ActionCreator.', () => {
+      const payloadActionCreator = Object.assign(
+        (payload?: number) => ({
+          type: 'action',
+          payload,
+        }),
+        { type: 'action' },
+      ) as PayloadActionCreator
+
+      expectTypeOf(payloadActionCreator).toMatchTypeOf<
+        ActionCreator<UnknownAction>
+      >()
+
+      const payloadActionCreator2 = Object.assign(
+        (payload?: number) => ({
+          type: 'action',
+          payload: payload || 1,
+        }),
+        { type: 'action' },
+      ) as PayloadActionCreator<number>
+
+      expectTypeOf(payloadActionCreator2).toMatchTypeOf<
+        ActionCreator<PayloadAction<number>>
+      >()
+    })
+  })
+
+  test('createAction() has type parameter for the action payload.', () => {
+    const increment = createAction<number, 'increment'>('increment')
+
+    expectTypeOf(increment).parameter(0).toBeNumber()
+
+    expectTypeOf(increment).parameter(0).not.toBeString()
+  })
+
+  test('createAction() type parameter is required, not inferred (defaults to `void`).', () => {
+    const increment = createAction('increment')
+
+    expectTypeOf(increment).parameter(0).not.toBeNumber()
+
+    expectTypeOf(increment().payload).not.toBeNumber()
+  })
+
+  test('createAction().type is a string literal.', () => {
+    const increment = createAction<number, 'increment'>('increment')
+
+    expectTypeOf(increment(1).type).toBeString()
+
+    expectTypeOf(increment(1).type).toEqualTypeOf<'increment'>()
+
+    expectTypeOf(increment(1).type).not.toMatchTypeOf<'other'>()
+
+    expectTypeOf(increment(1).type).not.toBeNumber()
+  })
+
+  test('type still present when using prepareAction', () => {
+    const strLenAction = createAction('strLen', (payload: string) => ({
+      payload: payload.length,
+    }))
+
+    expectTypeOf(strLenAction('test').type).toBeString()
+  })
+
+  test('changing payload type with prepareAction', () => {
+    const strLenAction = createAction('strLen', (payload: string) => ({
+      payload: payload.length,
+    }))
+
+    expectTypeOf(strLenAction('test').payload).toBeNumber()
+
+    expectTypeOf(strLenAction('test').payload).not.toBeString()
+
+    expectTypeOf(strLenAction('test')).not.toHaveProperty('error')
+  })
+
+  test('adding metadata with prepareAction', () => {
+    const strLenMetaAction = createAction('strLenMeta', (payload: string) => ({
+      payload,
+      meta: payload.length,
+    }))
+
+    expectTypeOf(strLenMetaAction('test').meta).toBeNumber()
+
+    expectTypeOf(strLenMetaAction('test').meta).not.toBeString()
+
+    expectTypeOf(strLenMetaAction('test')).not.toHaveProperty('error')
+  })
+
+  test('adding boolean error with prepareAction', () => {
+    const boolErrorAction = createAction('boolError', (payload: string) => ({
+      payload,
+      error: true,
+    }))
+
+    expectTypeOf(boolErrorAction('test').error).toBeBoolean()
+
+    expectTypeOf(boolErrorAction('test').error).not.toBeString()
+  })
+
+  test('adding string error with prepareAction', () => {
+    const strErrorAction = createAction('strError', (payload: string) => ({
+      payload,
+      error: 'this is an error',
+    }))
+
+    expectTypeOf(strErrorAction('test').error).toBeString()
+
+    expectTypeOf(strErrorAction('test').error).not.toBeBoolean()
+  })
+
+  test('regression test for https://github.com/reduxjs/redux-toolkit/issues/214', () => {
+    const action = createAction<{ input?: string }>('ACTION')
+
+    expectTypeOf(action({ input: '' }).payload.input).toEqualTypeOf<
+      string | undefined
+    >()
+
+    expectTypeOf(action({ input: '' }).payload.input).not.toBeNumber()
+
+    expectTypeOf(action).parameter(0).not.toMatchTypeOf({ input: 3 })
+  })
+
+  test('regression test for https://github.com/reduxjs/redux-toolkit/issues/224', () => {
+    const oops = createAction('oops', (x: any) => ({
+      payload: x,
+      error: x,
+      meta: x,
+    }))
+
+    expectTypeOf(oops('').payload).toBeAny()
+
+    expectTypeOf(oops('').error).toBeAny()
+
+    expectTypeOf(oops('').meta).toBeAny()
+  })
+
+  describe('createAction.match()', () => {
+    test('simple use case', () => {
+      const actionCreator = createAction<string, 'test'>('test')
+
+      const x: Action<string> = {} as any
+
+      if (actionCreator.match(x)) {
+        expectTypeOf(x.type).toEqualTypeOf<'test'>()
+
+        expectTypeOf(x.payload).toBeString()
+      } else {
+        expectTypeOf(x.type).not.toMatchTypeOf<'test'>()
+
+        expectTypeOf(x).not.toHaveProperty('payload')
+      }
+    })
+
+    test('special case: optional argument', () => {
+      const actionCreator = createAction<string | undefined, 'test'>('test')
+
+      const x: Action<string> = {} as any
+
+      if (actionCreator.match(x)) {
+        expectTypeOf(x.type).toEqualTypeOf<'test'>()
+
+        expectTypeOf(x.payload).toEqualTypeOf<string | undefined>()
+      }
+    })
+
+    test('special case: without argument', () => {
+      const actionCreator = createAction('test')
+
+      const x: Action<string> = {} as any
+
+      if (actionCreator.match(x)) {
+        expectTypeOf(x.type).toEqualTypeOf<'test'>()
+
+        expectTypeOf(x.payload).not.toMatchTypeOf<{}>()
+      }
+    })
+
+    test('special case: with prepareAction', () => {
+      const actionCreator = createAction('test', () => ({
+        payload: '',
+        meta: '',
+        error: false,
+      }))
+
+      const x: Action<string> = {} as any
+
+      if (actionCreator.match(x)) {
+        expectTypeOf(x.type).toEqualTypeOf<'test'>()
+
+        expectTypeOf(x.payload).toBeString()
+
+        expectTypeOf(x.meta).toBeString()
+
+        expectTypeOf(x.error).toBeBoolean()
+
+        expectTypeOf(x.payload).not.toBeNumber()
+
+        expectTypeOf(x.meta).not.toBeNumber()
+
+        expectTypeOf(x.error).not.toBeNumber()
+      }
+    })
+    test('potential use: as array filter', () => {
+      const actionCreator = createAction<string, 'test'>('test')
+
+      const x: Action<string>[] = []
+
+      expectTypeOf(x.filter(actionCreator.match)).toEqualTypeOf<
+        PayloadAction<string, 'test'>[]
+      >()
+    })
+  })
+
+  test('ActionCreatorWithOptionalPayload', () => {
+    expectTypeOf(createAction<string | undefined>('')).toEqualTypeOf<
+      ActionCreatorWithOptionalPayload<string | undefined>
+    >()
+
+    expectTypeOf(
+      createAction<void>(''),
+    ).toEqualTypeOf<ActionCreatorWithoutPayload>()
+
+    assertType<ActionCreatorWithNonInferrablePayload>(createAction(''))
+
+    expectTypeOf(createAction<string>('')).toEqualTypeOf<
+      ActionCreatorWithPayload<string>
+    >()
+
+    expectTypeOf(
+      createAction('', (_: 0) => ({
+        payload: 1 as 1,
+        error: 2 as 2,
+        meta: 3 as 3,
+      })),
+    ).toEqualTypeOf<ActionCreatorWithPreparedPayload<[0], 1, '', 2, 3>>()
+
+    const anyCreator = createAction<any>('')
+
+    expectTypeOf(anyCreator).toEqualTypeOf<ActionCreatorWithPayload<any>>()
+
+    expectTypeOf(anyCreator({}).payload).toBeAny()
+  })
+
+  test("Verify action creators should not be passed directly as arguments to React event handlers if there shouldn't be a payload", () => {
+    const emptyAction = createAction<void>('empty/action')
+
+    function TestComponent() {
+      // This typically leads to an error like:
+      //  // A non-serializable value was detected in an action, in the path: `payload`.
+      // @ts-expect-error Should error because `void` and `MouseEvent` aren't compatible
+      return <button onClick={emptyAction}>+</button>
+    }
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/createAction.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/createAction.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/createAction.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,148 @@
+import { createAction, isActionCreator } from '@reduxjs/toolkit'
+
+describe('createAction', () => {
+  it('should create an action', () => {
+    const actionCreator = createAction<string>('A_TYPE')
+    expect(actionCreator('something')).toEqual({
+      type: 'A_TYPE',
+      payload: 'something',
+    })
+  })
+
+  describe('when stringifying action', () => {
+    it('should return the action type', () => {
+      const actionCreator = createAction('A_TYPE')
+      expect(`${actionCreator}`).toEqual('A_TYPE')
+    })
+  })
+
+  describe('when passing a prepareAction method only returning a payload', () => {
+    it('should use the payload returned from the prepareAction method', () => {
+      const actionCreator = createAction('A_TYPE', (a: number) => ({
+        payload: a * 2,
+      }))
+      expect(actionCreator(5).payload).toBe(10)
+    })
+    it('should not have a meta attribute on the resulting Action', () => {
+      const actionCreator = createAction('A_TYPE', (a: number) => ({
+        payload: a * 2,
+      }))
+      expect('meta' in actionCreator(5)).toBeFalsy()
+    })
+  })
+
+  describe('when passing a prepareAction method returning a payload and meta', () => {
+    it('should use the payload returned from the prepareAction method', () => {
+      const actionCreator = createAction('A_TYPE', (a: number) => ({
+        payload: a * 2,
+        meta: a / 2,
+      }))
+      expect(actionCreator(5).payload).toBe(10)
+    })
+    it('should use the meta returned from the prepareAction method', () => {
+      const actionCreator = createAction('A_TYPE', (a: number) => ({
+        payload: a * 2,
+        meta: a / 2,
+      }))
+      expect(actionCreator(10).meta).toBe(5)
+    })
+  })
+
+  describe('when passing a prepareAction method returning a payload and error', () => {
+    it('should use the payload returned from the prepareAction method', () => {
+      const actionCreator = createAction('A_TYPE', (a: number) => ({
+        payload: a * 2,
+        error: true,
+      }))
+      expect(actionCreator(5).payload).toBe(10)
+    })
+    it('should use the error returned from the prepareAction method', () => {
+      const actionCreator = createAction('A_TYPE', (a: number) => ({
+        payload: a * 2,
+        error: true,
+      }))
+      expect(actionCreator(10).error).toBe(true)
+    })
+  })
+
+  describe('when passing a prepareAction method returning a payload, meta and error', () => {
+    it('should use the payload returned from the prepareAction method', () => {
+      const actionCreator = createAction('A_TYPE', (a: number) => ({
+        payload: a * 2,
+        meta: a / 2,
+        error: true,
+      }))
+      expect(actionCreator(5).payload).toBe(10)
+    })
+    it('should use the error returned from the prepareAction method', () => {
+      const actionCreator = createAction('A_TYPE', (a: number) => ({
+        payload: a * 2,
+        meta: a / 2,
+        error: true,
+      }))
+      expect(actionCreator(10).error).toBe(true)
+    })
+    it('should use the meta returned from the prepareAction method', () => {
+      const actionCreator = createAction('A_TYPE', (a: number) => ({
+        payload: a * 2,
+        meta: a / 2,
+        error: true,
+      }))
+      expect(actionCreator(10).meta).toBe(5)
+    })
+  })
+
+  describe('when passing a prepareAction that accepts multiple arguments', () => {
+    it('should pass all arguments of the resulting actionCreator to prepareAction', () => {
+      const actionCreator = createAction(
+        'A_TYPE',
+        (a: string, b: string, c: string) => ({
+          payload: a + b + c,
+        }),
+      )
+      expect(actionCreator('1', '2', '3').payload).toBe('123')
+    })
+  })
+
+  describe('actionCreator.match', () => {
+    test('should return true for actions generated by own actionCreator', () => {
+      const actionCreator = createAction('test')
+      expect(actionCreator.match(actionCreator())).toBe(true)
+    })
+
+    test('should return true for matching actions', () => {
+      const actionCreator = createAction('test')
+      expect(actionCreator.match({ type: 'test' })).toBe(true)
+    })
+
+    test('should return false for other actions', () => {
+      const actionCreator = createAction('test')
+      expect(actionCreator.match({ type: 'test-abc' })).toBe(false)
+    })
+  })
+})
+
+const actionCreator = createAction('anAction')
+
+class Action {
+  type = 'totally an action'
+}
+
+describe('isActionCreator', () => {
+  it('should only return true for action creators', () => {
+    expect(isActionCreator(actionCreator)).toBe(true)
+    const notActionCreators = [
+      { type: 'an action' },
+      { type: 'more props', extra: true },
+      actionCreator(),
+      Promise.resolve({ type: 'an action' }),
+      new Action(),
+      false,
+      'a string',
+      false,
+    ]
+    for (const notActionCreator of notActionCreators) {
+      expect(isActionCreator(notActionCreator)).toBe(false)
+    }
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/createAsyncThunk.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/createAsyncThunk.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/createAsyncThunk.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,899 @@
+import type {
+  AsyncThunk,
+  SerializedError,
+  ThunkDispatch,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import {
+  configureStore,
+  createAsyncThunk,
+  createReducer,
+  createSlice,
+  unwrapResult,
+} from '@reduxjs/toolkit'
+
+import type { TSVersion } from '@phryneas/ts-version'
+import type { AxiosError } from 'axios'
+import apiRequest from 'axios'
+import type { AsyncThunkDispatchConfig } from '@internal/createAsyncThunk'
+
+const defaultDispatch = (() => {}) as ThunkDispatch<{}, any, UnknownAction>
+const unknownAction = { type: 'foo' } as UnknownAction
+
+describe('type tests', () => {
+  test('basic usage', async () => {
+    const asyncThunk = createAsyncThunk('test', (id: number) =>
+      Promise.resolve(id * 2),
+    )
+
+    const reducer = createReducer({}, (builder) =>
+      builder
+        .addCase(asyncThunk.pending, (_, action) => {
+          expectTypeOf(action).toEqualTypeOf<
+            ReturnType<(typeof asyncThunk)['pending']>
+          >()
+        })
+
+        .addCase(asyncThunk.fulfilled, (_, action) => {
+          expectTypeOf(action).toEqualTypeOf<
+            ReturnType<(typeof asyncThunk)['fulfilled']>
+          >()
+
+          expectTypeOf(action.payload).toBeNumber()
+        })
+
+        .addCase(asyncThunk.rejected, (_, action) => {
+          expectTypeOf(action).toEqualTypeOf<
+            ReturnType<(typeof asyncThunk)['rejected']>
+          >()
+
+          expectTypeOf(action.error).toMatchTypeOf<Partial<Error> | undefined>()
+        }),
+    )
+
+    const promise = defaultDispatch(asyncThunk(3))
+
+    expectTypeOf(promise.requestId).toBeString()
+
+    expectTypeOf(promise.arg).toBeNumber()
+
+    expectTypeOf(promise.abort).toEqualTypeOf<(reason?: string) => void>()
+
+    const result = await promise
+
+    if (asyncThunk.fulfilled.match(result)) {
+      expectTypeOf(result).toEqualTypeOf<
+        ReturnType<(typeof asyncThunk)['fulfilled']>
+      >()
+    } else {
+      expectTypeOf(result).toEqualTypeOf<
+        ReturnType<(typeof asyncThunk)['rejected']>
+      >()
+    }
+
+    promise
+      .then(unwrapResult)
+      .then((result) => {
+        expectTypeOf(result).toBeNumber()
+
+        expectTypeOf(result).not.toMatchTypeOf<Error>()
+      })
+      .catch((error) => {
+        // catch is always any-typed, nothing we can do here
+        expectTypeOf(error).toBeAny()
+      })
+  })
+
+  test('More complex usage of thunk args', () => {
+    interface BookModel {
+      id: string
+      title: string
+    }
+
+    type BooksState = BookModel[]
+
+    const fakeBooks: BookModel[] = [
+      { id: 'b', title: 'Second' },
+      { id: 'a', title: 'First' },
+    ]
+
+    const correctDispatch = (() => {}) as ThunkDispatch<
+      BookModel[],
+      { userAPI: Function },
+      UnknownAction
+    >
+
+    // Verify that the the first type args to createAsyncThunk line up right
+    const fetchBooksTAC = createAsyncThunk<
+      BookModel[],
+      number,
+      {
+        state: BooksState
+        extra: { userAPI: Function }
+      }
+    >(
+      'books/fetch',
+      async (arg, { getState, dispatch, extra, requestId, signal }) => {
+        const state = getState()
+
+        expectTypeOf(arg).toBeNumber()
+
+        expectTypeOf(state).toEqualTypeOf<BookModel[]>()
+
+        expectTypeOf(extra).toEqualTypeOf<{ userAPI: Function }>()
+
+        return fakeBooks
+      },
+    )
+
+    correctDispatch(fetchBooksTAC(1))
+    // @ts-expect-error
+    defaultDispatch(fetchBooksTAC(1))
+  })
+
+  test('returning a rejected action from the promise creator is possible', async () => {
+    type ReturnValue = { data: 'success' }
+    type RejectValue = { data: 'error' }
+
+    const fetchBooksTAC = createAsyncThunk<
+      ReturnValue,
+      number,
+      {
+        rejectValue: RejectValue
+      }
+    >('books/fetch', async (arg, { rejectWithValue }) => {
+      return rejectWithValue({ data: 'error' })
+    })
+
+    const returned = await defaultDispatch(fetchBooksTAC(1))
+    if (fetchBooksTAC.rejected.match(returned)) {
+      expectTypeOf(returned.payload).toEqualTypeOf<undefined | RejectValue>()
+
+      expectTypeOf(returned.payload).toBeNullable()
+    } else {
+      expectTypeOf(returned.payload).toEqualTypeOf<ReturnValue>()
+    }
+
+    expectTypeOf(unwrapResult(returned)).toEqualTypeOf<ReturnValue>()
+
+    expectTypeOf(unwrapResult(returned)).not.toMatchTypeOf<RejectValue>()
+  })
+
+  test('regression #1156: union return values fall back to allowing only single member', () => {
+    const fn = createAsyncThunk('session/isAdmin', async () => {
+      const response: boolean = false
+      return response
+    })
+  })
+
+  test('Should handle reject with value within a try catch block. Note: this is a sample code taken from #1605', () => {
+    type ResultType = {
+      text: string
+    }
+    const demoPromise = async (): Promise<ResultType> =>
+      new Promise((resolve, _) => resolve({ text: '' }))
+    const thunk = createAsyncThunk('thunk', async (args, thunkAPI) => {
+      try {
+        const result = await demoPromise()
+        return result
+      } catch (error) {
+        return thunkAPI.rejectWithValue(error)
+      }
+    })
+    createReducer({}, (builder) =>
+      builder.addCase(thunk.fulfilled, (s, action) => {
+        expectTypeOf(action.payload).toEqualTypeOf<ResultType>()
+      }),
+    )
+  })
+
+  test('reject with value', () => {
+    interface Item {
+      name: string
+    }
+
+    interface ErrorFromServer {
+      error: string
+    }
+
+    interface CallsResponse {
+      data: Item[]
+    }
+
+    const fetchLiveCallsError = createAsyncThunk<
+      Item[],
+      string,
+      {
+        rejectValue: ErrorFromServer
+      }
+    >('calls/fetchLiveCalls', async (organizationId, { rejectWithValue }) => {
+      try {
+        const result = await apiRequest.get<CallsResponse>(
+          `organizations/${organizationId}/calls/live/iwill404`,
+        )
+        return result.data.data
+      } catch (err) {
+        const error: AxiosError<ErrorFromServer> = err as any // cast for access to AxiosError properties
+        if (!error.response) {
+          // let it be handled as any other unknown error
+          throw err
+        }
+        return rejectWithValue(error.response && error.response.data)
+      }
+    })
+
+    defaultDispatch(fetchLiveCallsError('asd')).then((result) => {
+      if (fetchLiveCallsError.fulfilled.match(result)) {
+        //success
+        expectTypeOf(result).toEqualTypeOf<
+          ReturnType<(typeof fetchLiveCallsError)['fulfilled']>
+        >()
+
+        expectTypeOf(result.payload).toEqualTypeOf<Item[]>()
+      } else {
+        expectTypeOf(result).toEqualTypeOf<
+          ReturnType<(typeof fetchLiveCallsError)['rejected']>
+        >()
+
+        if (result.payload) {
+          // rejected with value
+          expectTypeOf(result.payload).toEqualTypeOf<ErrorFromServer>()
+        } else {
+          // rejected by throw
+          expectTypeOf(result.payload).toBeUndefined()
+
+          expectTypeOf(result.error).toEqualTypeOf<SerializedError>()
+
+          expectTypeOf(result.error).not.toBeAny()
+        }
+      }
+      defaultDispatch(fetchLiveCallsError('asd'))
+        .then((result) => {
+          expectTypeOf(result.payload).toEqualTypeOf<
+            Item[] | ErrorFromServer | undefined
+          >()
+
+          return result
+        })
+        .then(unwrapResult)
+        .then((unwrapped) => {
+          expectTypeOf(unwrapped).toEqualTypeOf<Item[]>()
+
+          expectTypeOf(unwrapResult).parameter(0).not.toMatchTypeOf(unwrapped)
+        })
+    })
+  })
+
+  describe('payloadCreator first argument type has impact on asyncThunk argument', () => {
+    test('asyncThunk has no argument', () => {
+      const asyncThunk = createAsyncThunk('test', () => 0)
+
+      expectTypeOf(asyncThunk).toMatchTypeOf<() => any>()
+
+      expectTypeOf(asyncThunk).parameters.toEqualTypeOf<
+        [undefined?, AsyncThunkDispatchConfig?]
+      >()
+
+      expectTypeOf(asyncThunk).returns.toBeFunction()
+    })
+
+    test('one argument, specified as undefined: asyncThunk has no argument', () => {
+      const asyncThunk = createAsyncThunk('test', (arg: undefined) => 0)
+
+      expectTypeOf(asyncThunk).toMatchTypeOf<() => any>()
+
+      expectTypeOf(asyncThunk).parameters.toEqualTypeOf<
+        [undefined?, AsyncThunkDispatchConfig?]
+      >()
+    })
+
+    test('one argument, specified as void: asyncThunk has no argument', () => {
+      const asyncThunk = createAsyncThunk('test', (arg: void) => 0)
+
+      expectTypeOf(asyncThunk).toMatchTypeOf<() => any>()
+    })
+
+    test('one argument, specified as optional number: asyncThunk has optional number argument', () => {
+      // this test will fail with strictNullChecks: false, that is to be expected
+      // in that case, we have to forbid this behavior or it will make arguments optional everywhere
+      const asyncThunk = createAsyncThunk('test', (arg?: number) => 0)
+
+      // Per https://github.com/reduxjs/redux-toolkit/issues/3758#issuecomment-1742152774 , this is a bug in
+      // TS 5.1 and 5.2, that is fixed in 5.3. Conditionally run the TS assertion here.
+      type IsTS51Or52 = TSVersion.Major extends 5
+        ? TSVersion.Minor extends 1 | 2
+          ? true
+          : false
+        : false
+
+      type expectedType = IsTS51Or52 extends true
+        ? (arg: number) => any
+        : (arg?: number) => any
+
+      expectTypeOf(asyncThunk).toMatchTypeOf<expectedType>()
+
+      // We _should_ be able to call this with no arguments, but we run into that error in 5.1 and 5.2.
+      // Disabling this for now.
+      // asyncThunk()
+      expectTypeOf(asyncThunk).toBeCallableWith(5)
+
+      expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[string]>()
+    })
+
+    test('one argument, specified as number|undefined: asyncThunk has optional number argument', () => {
+      // this test will fail with strictNullChecks: false, that is to be expected
+      // in that case, we have to forbid this behavior or it will make arguments optional everywhere
+      const asyncThunk = createAsyncThunk(
+        'test',
+        (arg: number | undefined) => 0,
+      )
+
+      expectTypeOf(asyncThunk).toMatchTypeOf<(arg?: number) => any>()
+
+      expectTypeOf(asyncThunk).toBeCallableWith()
+
+      expectTypeOf(asyncThunk).toBeCallableWith(undefined)
+
+      expectTypeOf(asyncThunk).toBeCallableWith(5)
+
+      expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[string]>()
+    })
+
+    test('one argument, specified as number|void: asyncThunk has optional number argument', () => {
+      const asyncThunk = createAsyncThunk('test', (arg: number | void) => 0)
+
+      expectTypeOf(asyncThunk).toMatchTypeOf<(arg?: number) => any>()
+
+      expectTypeOf(asyncThunk).toBeCallableWith()
+
+      expectTypeOf(asyncThunk).toBeCallableWith(undefined)
+
+      expectTypeOf(asyncThunk).toBeCallableWith(5)
+
+      expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[string]>()
+    })
+
+    test('one argument, specified as any: asyncThunk has required any argument', () => {
+      const asyncThunk = createAsyncThunk('test', (arg: any) => 0)
+
+      expectTypeOf(asyncThunk).parameter(0).toBeAny()
+
+      expectTypeOf(asyncThunk).toBeCallableWith(5)
+
+      expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[]>()
+    })
+
+    test('one argument, specified as unknown: asyncThunk has required unknown argument', () => {
+      const asyncThunk = createAsyncThunk('test', (arg: unknown) => 0)
+
+      expectTypeOf(asyncThunk).parameter(0).toBeUnknown()
+
+      expectTypeOf(asyncThunk).toBeCallableWith(5)
+
+      expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[]>()
+    })
+
+    test('one argument, specified as number: asyncThunk has required number argument', () => {
+      const asyncThunk = createAsyncThunk('test', (arg: number) => 0)
+
+      expectTypeOf(asyncThunk).toMatchTypeOf<(arg: number) => any>()
+
+      expectTypeOf(asyncThunk).toBeCallableWith(5)
+
+      expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[]>()
+    })
+
+    test('two arguments, first specified as undefined: asyncThunk has no argument', () => {
+      const asyncThunk = createAsyncThunk(
+        'test',
+        (arg: undefined, thunkApi) => 0,
+      )
+
+      expectTypeOf(asyncThunk).toMatchTypeOf<() => any>()
+
+      expectTypeOf(asyncThunk).toBeCallableWith()
+
+      expectTypeOf(asyncThunk).toBeCallableWith(undefined)
+
+      // cannot be called with an argument
+      expectTypeOf(asyncThunk).parameter(0).not.toBeAny()
+
+      expectTypeOf(asyncThunk).parameters.toEqualTypeOf<
+        [undefined?, AsyncThunkDispatchConfig?]
+      >()
+    })
+
+    test('two arguments, first specified as void: asyncThunk has no argument', () => {
+      const asyncThunk = createAsyncThunk('test', (arg: void, thunkApi) => 0)
+
+      expectTypeOf(asyncThunk).toMatchTypeOf<() => any>()
+
+      expectTypeOf(asyncThunk).toBeCallableWith()
+
+      expectTypeOf(asyncThunk).parameter(0).toBeVoid()
+
+      // cannot be called with an argument
+      expectTypeOf(asyncThunk).parameter(0).not.toBeAny()
+
+      expectTypeOf(asyncThunk).parameters.toEqualTypeOf<
+        [undefined?, AsyncThunkDispatchConfig?]
+      >()
+    })
+
+    test('two arguments, first specified as number|undefined: asyncThunk has optional number argument', () => {
+      // this test will fail with strictNullChecks: false, that is to be expected
+      // in that case, we have to forbid this behavior or it will make arguments optional everywhere
+      const asyncThunk = createAsyncThunk(
+        'test',
+        (arg: number | undefined, thunkApi) => 0,
+      )
+
+      expectTypeOf(asyncThunk).toMatchTypeOf<(arg?: number) => any>()
+
+      expectTypeOf(asyncThunk).toBeCallableWith()
+
+      expectTypeOf(asyncThunk).toBeCallableWith(undefined)
+
+      expectTypeOf(asyncThunk).toBeCallableWith(5)
+
+      expectTypeOf(asyncThunk).parameter(0).not.toBeString()
+    })
+
+    test('two arguments, first specified as number|void: asyncThunk has optional number argument', () => {
+      const asyncThunk = createAsyncThunk(
+        'test',
+        (arg: number | void, thunkApi) => 0,
+      )
+
+      expectTypeOf(asyncThunk).toMatchTypeOf<(arg?: number) => any>()
+
+      expectTypeOf(asyncThunk).toBeCallableWith()
+
+      expectTypeOf(asyncThunk).toBeCallableWith(undefined)
+
+      expectTypeOf(asyncThunk).toBeCallableWith(5)
+
+      expectTypeOf(asyncThunk).parameter(0).not.toBeString()
+    })
+
+    test('two arguments, first specified as any: asyncThunk has required any argument', () => {
+      const asyncThunk = createAsyncThunk('test', (arg: any, thunkApi) => 0)
+
+      expectTypeOf(asyncThunk).parameter(0).toBeAny()
+
+      expectTypeOf(asyncThunk).toBeCallableWith(5)
+
+      expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[]>()
+    })
+
+    test('two arguments, first specified as unknown: asyncThunk has required unknown argument', () => {
+      const asyncThunk = createAsyncThunk('test', (arg: unknown, thunkApi) => 0)
+
+      expectTypeOf(asyncThunk).parameter(0).toBeUnknown()
+
+      expectTypeOf(asyncThunk).toBeCallableWith(5)
+
+      expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[]>()
+    })
+
+    test('two arguments, first specified as number: asyncThunk has required number argument', () => {
+      const asyncThunk = createAsyncThunk('test', (arg: number, thunkApi) => 0)
+
+      expectTypeOf(asyncThunk).toMatchTypeOf<(arg: number) => any>()
+
+      expectTypeOf(asyncThunk).parameter(0).toBeNumber()
+
+      expectTypeOf(asyncThunk).toBeCallableWith(5)
+
+      expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[]>()
+    })
+  })
+
+  test('createAsyncThunk without generics', () => {
+    const thunk = createAsyncThunk('test', () => {
+      return 'ret' as const
+    })
+
+    expectTypeOf(thunk).toEqualTypeOf<AsyncThunk<'ret', void, {}>>()
+  })
+
+  test('createAsyncThunk without generics, accessing `api` does not break return type', () => {
+    const thunk = createAsyncThunk('test', (_: void, api) => {
+      return 'ret' as const
+    })
+
+    expectTypeOf(thunk).toEqualTypeOf<AsyncThunk<'ret', void, {}>>()
+  })
+
+  test('createAsyncThunk rejectWithValue without generics: Expect correct return type', () => {
+    const asyncThunk = createAsyncThunk(
+      'test',
+      (_: void, { rejectWithValue }) => {
+        try {
+          return Promise.resolve(true)
+        } catch (e) {
+          return rejectWithValue(e)
+        }
+      },
+    )
+
+    defaultDispatch(asyncThunk())
+      .then((result) => {
+        if (asyncThunk.fulfilled.match(result)) {
+          expectTypeOf(result).toEqualTypeOf<
+            ReturnType<(typeof asyncThunk)['fulfilled']>
+          >()
+
+          expectTypeOf(result.payload).toBeBoolean()
+
+          expectTypeOf(result).not.toHaveProperty('error')
+        } else {
+          expectTypeOf(result).toEqualTypeOf<
+            ReturnType<(typeof asyncThunk)['rejected']>
+          >()
+
+          expectTypeOf(result.error).toEqualTypeOf<SerializedError>()
+
+          expectTypeOf(result.payload).toBeUnknown()
+        }
+
+        return result
+      })
+      .then(unwrapResult)
+      .then((unwrapped) => {
+        expectTypeOf(unwrapped).toBeBoolean()
+      })
+  })
+
+  test('createAsyncThunk with generics', () => {
+    type Funky = { somethingElse: 'Funky!' }
+    function funkySerializeError(err: any): Funky {
+      return { somethingElse: 'Funky!' }
+    }
+
+    // has to stay on one line or type tests fail in older TS versions
+    // prettier-ignore
+    // @ts-expect-error
+    const shouldFail = createAsyncThunk('without generics', () => {}, { serializeError: funkySerializeError })
+
+    const shouldWork = createAsyncThunk<
+      any,
+      void,
+      { serializedErrorType: Funky }
+    >('with generics', () => {}, {
+      serializeError: funkySerializeError,
+    })
+
+    if (shouldWork.rejected.match(unknownAction)) {
+      expectTypeOf(unknownAction.error).toEqualTypeOf<Funky>()
+    }
+  })
+
+  test('`idGenerator` option takes no arguments, and returns a string', () => {
+    const returnsNumWithArgs = (foo: any) => 100
+    // has to stay on one line or type tests fail in older TS versions
+    // prettier-ignore
+    // @ts-expect-error
+    const shouldFailNumWithArgs = createAsyncThunk('foo', () => {}, { idGenerator: returnsNumWithArgs })
+
+    const returnsNumWithoutArgs = () => 100
+    // prettier-ignore
+    // @ts-expect-error
+    const shouldFailNumWithoutArgs = createAsyncThunk('foo', () => {}, { idGenerator: returnsNumWithoutArgs })
+
+    const returnsStrWithNumberArg = (foo: number) => 'foo'
+    // prettier-ignore
+    // @ts-expect-error
+    const shouldFailWrongArgs = createAsyncThunk('foo', (arg: string) => {}, { idGenerator: returnsStrWithNumberArg })
+
+    const returnsStrWithStringArg = (foo: string) => 'foo'
+    const shoulducceedCorrectArgs = createAsyncThunk(
+      'foo',
+      (arg: string) => {},
+      {
+        idGenerator: returnsStrWithStringArg,
+      },
+    )
+
+    const returnsStrWithoutArgs = () => 'foo'
+    const shouldSucceed = createAsyncThunk('foo', () => {}, {
+      idGenerator: returnsStrWithoutArgs,
+    })
+  })
+
+  test('fulfillWithValue should infer return value', () => {
+    // https://github.com/reduxjs/redux-toolkit/issues/2886
+
+    const initialState = {
+      loading: false,
+      obj: { magic: '' },
+    }
+
+    const getObj = createAsyncThunk(
+      'slice/getObj',
+      async (_: any, { fulfillWithValue, rejectWithValue }) => {
+        try {
+          return fulfillWithValue({ magic: 'object' })
+        } catch (rejected: any) {
+          return rejectWithValue(rejected?.response?.error || rejected)
+        }
+      },
+    )
+
+    createSlice({
+      name: 'slice',
+      initialState,
+      reducers: {},
+      extraReducers: (builder) => {
+        builder.addCase(getObj.fulfilled, (state, action) => {
+          expectTypeOf(action.payload).toEqualTypeOf<{ magic: string }>()
+        })
+      },
+    })
+  })
+
+  test('meta return values', () => {
+    // return values
+    createAsyncThunk<'ret', void, {}>('test', (_, api) => 'ret' as const)
+    createAsyncThunk<'ret', void, {}>('test', async (_, api) => 'ret' as const)
+    createAsyncThunk<'ret', void, { fulfilledMeta: string }>('test', (_, api) =>
+      api.fulfillWithValue('ret' as const, ''),
+    )
+    createAsyncThunk<'ret', void, { fulfilledMeta: string }>(
+      'test',
+      async (_, api) => api.fulfillWithValue('ret' as const, ''),
+    )
+    createAsyncThunk<'ret', void, { fulfilledMeta: string }>(
+      'test',
+      // @ts-expect-error has to be a fulfilledWithValue call
+      (_, api) => 'ret' as const,
+    )
+    createAsyncThunk<'ret', void, { fulfilledMeta: string }>(
+      'test',
+      // @ts-expect-error has to be a fulfilledWithValue call
+      async (_, api) => 'ret' as const,
+    )
+    createAsyncThunk<'ret', void, { fulfilledMeta: string }>(
+      'test', // @ts-expect-error should only allow returning with 'test'
+      (_, api) => api.fulfillWithValue(5, ''),
+    )
+    createAsyncThunk<'ret', void, { fulfilledMeta: string }>(
+      'test', // @ts-expect-error should only allow returning with 'test'
+      async (_, api) => api.fulfillWithValue(5, ''),
+    )
+
+    // reject values
+    createAsyncThunk<'ret', void, { rejectValue: string }>('test', (_, api) =>
+      api.rejectWithValue('ret'),
+    )
+    createAsyncThunk<'ret', void, { rejectValue: string }>(
+      'test',
+      async (_, api) => api.rejectWithValue('ret'),
+    )
+    createAsyncThunk<
+      'ret',
+      void,
+      { rejectValue: string; rejectedMeta: number }
+    >('test', (_, api) => api.rejectWithValue('ret', 5))
+    createAsyncThunk<
+      'ret',
+      void,
+      { rejectValue: string; rejectedMeta: number }
+    >('test', async (_, api) => api.rejectWithValue('ret', 5))
+    createAsyncThunk<
+      'ret',
+      void,
+      { rejectValue: string; rejectedMeta: number }
+    >('test', (_, api) => api.rejectWithValue('ret', 5))
+    createAsyncThunk<
+      'ret',
+      void,
+      { rejectValue: string; rejectedMeta: number }
+    >(
+      'test',
+      // @ts-expect-error wrong rejectedMeta type
+      (_, api) => api.rejectWithValue('ret', ''),
+    )
+    createAsyncThunk<
+      'ret',
+      void,
+      { rejectValue: string; rejectedMeta: number }
+    >(
+      'test',
+      // @ts-expect-error wrong rejectedMeta type
+      async (_, api) => api.rejectWithValue('ret', ''),
+    )
+    createAsyncThunk<
+      'ret',
+      void,
+      { rejectValue: string; rejectedMeta: number }
+    >(
+      'test',
+      // @ts-expect-error wrong rejectValue type
+      (_, api) => api.rejectWithValue(5, ''),
+    )
+    createAsyncThunk<
+      'ret',
+      void,
+      { rejectValue: string; rejectedMeta: number }
+    >(
+      'test',
+      // @ts-expect-error wrong rejectValue type
+      async (_, api) => api.rejectWithValue(5, ''),
+    )
+  })
+
+  test('usage with config override generic', () => {
+    const typedCAT = createAsyncThunk.withTypes<{
+      state: RootState
+      dispatch: AppDispatch
+      rejectValue: string
+      extra: { s: string; n: number }
+    }>()
+
+    // inferred usage
+    const thunk = typedCAT('foo', (arg: number, api) => {
+      // correct getState Type
+      const test1: number = api.getState().foo.value
+      // correct dispatch type
+      const test2: number = api.dispatch((dispatch, getState) => {
+        expectTypeOf(dispatch).toEqualTypeOf<
+          ThunkDispatch<{ foo: { value: number } }, undefined, UnknownAction>
+        >()
+
+        expectTypeOf(getState).toEqualTypeOf<() => { foo: { value: number } }>()
+
+        return getState().foo.value
+      })
+
+      // correct extra type
+      const { s, n } = api.extra
+
+      expectTypeOf(s).toBeString()
+
+      expectTypeOf(n).toBeNumber()
+
+      if (1 < 2)
+        // @ts-expect-error
+        return api.rejectWithValue(5)
+      if (1 < 2) return api.rejectWithValue('test')
+      return test1 + test2
+    })
+
+    // usage with two generics
+    const thunk2 = typedCAT<number, string>('foo', (arg, api) => {
+      expectTypeOf(arg).toBeString()
+
+      // correct getState Type
+      const test1: number = api.getState().foo.value
+      // correct dispatch type
+      const test2: number = api.dispatch((dispatch, getState) => {
+        expectTypeOf(dispatch).toEqualTypeOf<
+          ThunkDispatch<{ foo: { value: number } }, undefined, UnknownAction>
+        >()
+
+        expectTypeOf(getState).toEqualTypeOf<() => { foo: { value: number } }>()
+
+        return getState().foo.value
+      })
+      // correct extra type
+      const { s, n } = api.extra
+
+      expectTypeOf(s).toBeString()
+
+      expectTypeOf(n).toBeNumber()
+
+      if (1 < 2) expectTypeOf(api.rejectWithValue).toBeCallableWith('test')
+
+      expectTypeOf(api.rejectWithValue).parameter(0).not.toBeNumber()
+
+      expectTypeOf(api.rejectWithValue).parameters.toEqualTypeOf<[string]>()
+
+      return api.rejectWithValue('test')
+    })
+
+    // usage with config override generic
+    const thunk3 = typedCAT<number, string, { rejectValue: number }>(
+      'foo',
+      (arg, api) => {
+        expectTypeOf(arg).toBeString()
+
+        // correct getState Type
+        const test1: number = api.getState().foo.value
+        // correct dispatch type
+        const test2: number = api.dispatch((dispatch, getState) => {
+          expectTypeOf(dispatch).toEqualTypeOf<
+            ThunkDispatch<{ foo: { value: number } }, undefined, UnknownAction>
+          >()
+
+          expectTypeOf(getState).toEqualTypeOf<
+            () => { foo: { value: number } }
+          >()
+
+          return getState().foo.value
+        })
+        // correct extra type
+        const { s, n } = api.extra
+
+        expectTypeOf(s).toBeString()
+
+        expectTypeOf(n).toBeNumber()
+
+        if (1 < 2) return api.rejectWithValue(5)
+        if (1 < 2) expectTypeOf(api.rejectWithValue).toBeCallableWith(5)
+
+        expectTypeOf(api.rejectWithValue).parameter(0).not.toBeString()
+
+        expectTypeOf(api.rejectWithValue).parameters.toEqualTypeOf<[number]>()
+
+        return api.rejectWithValue(5)
+      },
+    )
+
+    const slice = createSlice({
+      name: 'foo',
+      initialState: { value: 0 },
+      reducers: {},
+      extraReducers(builder) {
+        builder
+          .addCase(thunk.fulfilled, (state, action) => {
+            state.value += action.payload
+          })
+          .addCase(thunk.rejected, (state, action) => {
+            expectTypeOf(action.payload).toEqualTypeOf<string | undefined>()
+          })
+          .addCase(thunk2.fulfilled, (state, action) => {
+            state.value += action.payload
+          })
+          .addCase(thunk2.rejected, (state, action) => {
+            expectTypeOf(action.payload).toEqualTypeOf<string | undefined>()
+          })
+          .addCase(thunk3.fulfilled, (state, action) => {
+            state.value += action.payload
+          })
+          .addCase(thunk3.rejected, (state, action) => {
+            expectTypeOf(action.payload).toEqualTypeOf<number | undefined>()
+          })
+      },
+    })
+
+    const store = configureStore({
+      reducer: {
+        foo: slice.reducer,
+      },
+    })
+
+    type RootState = ReturnType<typeof store.getState>
+    type AppDispatch = typeof store.dispatch
+  })
+
+  test('rejectedMeta', async () => {
+    const getNewStore = () =>
+      configureStore({
+        reducer(actions = [], action) {
+          return [...actions, action]
+        },
+      })
+
+    const store = getNewStore()
+
+    const fulfilledThunk = createAsyncThunk<
+      string,
+      string,
+      { rejectedMeta: { extraProp: string } }
+    >('test', (arg: string, { rejectWithValue }) => {
+      return rejectWithValue('damn!', { extraProp: 'baz' })
+    })
+
+    const promise = store.dispatch(fulfilledThunk('testArg'))
+
+    const ret = await promise
+
+    if (ret.meta.requestStatus === 'rejected' && ret.meta.rejectedWithValue) {
+      expectTypeOf(ret.meta.extraProp).toBeString()
+    } else {
+      // could be caused by a `throw`, `abort()` or `condition` - no `rejectedMeta` in that case
+      expectTypeOf(ret.meta).not.toHaveProperty('extraProp')
+    }
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/createAsyncThunk.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/createAsyncThunk.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/createAsyncThunk.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1045 @@
+import { noop } from '@internal/listenerMiddleware/utils'
+import { delay, promiseWithResolvers } from '@internal/utils'
+import type { CreateAsyncThunkFunction, UnknownAction } from '@reduxjs/toolkit'
+import {
+  configureStore,
+  createAsyncThunk,
+  createReducer,
+  miniSerializeError,
+  unwrapResult,
+} from '@reduxjs/toolkit'
+
+declare global {
+  interface Window {
+    AbortController: AbortController
+  }
+}
+
+describe('createAsyncThunk', () => {
+  it('creates the action types', () => {
+    const thunkActionCreator = createAsyncThunk('testType', async () => 42)
+
+    expect(thunkActionCreator.fulfilled.type).toBe('testType/fulfilled')
+    expect(thunkActionCreator.pending.type).toBe('testType/pending')
+    expect(thunkActionCreator.rejected.type).toBe('testType/rejected')
+  })
+
+  it('exposes the typePrefix it was created with', () => {
+    const thunkActionCreator = createAsyncThunk('testType', async () => 42)
+
+    expect(thunkActionCreator.typePrefix).toBe('testType')
+  })
+
+  it('includes a settled matcher', () => {
+    const thunkActionCreator = createAsyncThunk('testType', async () => 42)
+    expect(thunkActionCreator.settled).toEqual(expect.any(Function))
+    expect(thunkActionCreator.settled(thunkActionCreator.pending(''))).toBe(
+      false,
+    )
+    expect(
+      thunkActionCreator.settled(thunkActionCreator.rejected(null, '')),
+    ).toBe(true)
+    expect(
+      thunkActionCreator.settled(thunkActionCreator.fulfilled(42, '')),
+    ).toBe(true)
+  })
+
+  it('works without passing arguments to the payload creator', async () => {
+    const thunkActionCreator = createAsyncThunk('testType', async () => 42)
+
+    let timesReducerCalled = 0
+
+    const reducer = () => {
+      timesReducerCalled++
+    }
+
+    const store = configureStore({
+      reducer,
+    })
+
+    // reset from however many times the store called it
+    timesReducerCalled = 0
+
+    await store.dispatch(thunkActionCreator())
+
+    expect(timesReducerCalled).toBe(2)
+  })
+
+  it('accepts arguments and dispatches the actions on resolve', async () => {
+    const dispatch = vi.fn()
+
+    let passedArg: any
+
+    const result = 42
+    const args = 123
+    let generatedRequestId = ''
+
+    const thunkActionCreator = createAsyncThunk(
+      'testType',
+      async (arg: number, { requestId }) => {
+        passedArg = arg
+        generatedRequestId = requestId
+        return result
+      },
+    )
+
+    const thunkFunction = thunkActionCreator(args)
+
+    const thunkPromise = thunkFunction(dispatch, () => {}, undefined)
+
+    expect(thunkPromise.requestId).toBe(generatedRequestId)
+    expect(thunkPromise.arg).toBe(args)
+
+    await thunkPromise
+
+    expect(passedArg).toBe(args)
+
+    expect(dispatch).toHaveBeenNthCalledWith(
+      1,
+      thunkActionCreator.pending(generatedRequestId, args),
+    )
+
+    expect(dispatch).toHaveBeenNthCalledWith(
+      2,
+      thunkActionCreator.fulfilled(result, generatedRequestId, args),
+    )
+  })
+
+  it('accepts arguments and dispatches the actions on reject', async () => {
+    const dispatch = vi.fn()
+
+    const args = 123
+    let generatedRequestId = ''
+
+    const error = new Error('Panic!')
+
+    const thunkActionCreator = createAsyncThunk(
+      'testType',
+      async (args: number, { requestId }) => {
+        generatedRequestId = requestId
+        throw error
+      },
+    )
+
+    const thunkFunction = thunkActionCreator(args)
+
+    try {
+      await thunkFunction(dispatch, () => {}, undefined)
+    } catch (e) {}
+
+    expect(dispatch).toHaveBeenNthCalledWith(
+      1,
+      thunkActionCreator.pending(generatedRequestId, args),
+    )
+
+    expect(dispatch).toHaveBeenCalledTimes(2)
+
+    // Have to check the bits of the action separately since the error was processed
+    const errorAction = dispatch.mock.calls[1][0]
+    expect(errorAction.error).toEqual(miniSerializeError(error))
+    expect(errorAction.meta.requestId).toBe(generatedRequestId)
+    expect(errorAction.meta.arg).toBe(args)
+  })
+
+  it('dispatches an empty error when throwing a random object without serializedError properties', async () => {
+    const dispatch = vi.fn()
+
+    const args = 123
+    let generatedRequestId = ''
+
+    const errorObject = { wny: 'dothis' }
+
+    const thunkActionCreator = createAsyncThunk(
+      'testType',
+      async (args: number, { requestId }) => {
+        generatedRequestId = requestId
+        throw errorObject
+      },
+    )
+
+    const thunkFunction = thunkActionCreator(args)
+
+    try {
+      await thunkFunction(dispatch, () => {}, undefined)
+    } catch (e) {}
+
+    expect(dispatch).toHaveBeenNthCalledWith(
+      1,
+      thunkActionCreator.pending(generatedRequestId, args),
+    )
+
+    expect(dispatch).toHaveBeenCalledTimes(2)
+
+    const errorAction = dispatch.mock.calls[1][0]
+    expect(errorAction.error).toEqual({})
+    expect(errorAction.meta.requestId).toBe(generatedRequestId)
+    expect(errorAction.meta.arg).toBe(args)
+  })
+
+  it('dispatches an action with a formatted error when throwing an object with known error keys', async () => {
+    const dispatch = vi.fn()
+
+    const args = 123
+    let generatedRequestId = ''
+
+    const errorObject = {
+      name: 'Custom thrown error',
+      message: 'This is not necessary',
+      code: '400',
+    }
+
+    const thunkActionCreator = createAsyncThunk(
+      'testType',
+      async (args: number, { requestId }) => {
+        generatedRequestId = requestId
+        throw errorObject
+      },
+    )
+
+    const thunkFunction = thunkActionCreator(args)
+
+    try {
+      await thunkFunction(dispatch, () => {}, undefined)
+    } catch (e) {}
+
+    expect(dispatch).toHaveBeenNthCalledWith(
+      1,
+      thunkActionCreator.pending(generatedRequestId, args),
+    )
+
+    expect(dispatch).toHaveBeenCalledTimes(2)
+
+    // Have to check the bits of the action separately since the error was processed
+    const errorAction = dispatch.mock.calls[1][0]
+    expect(errorAction.error).toEqual(miniSerializeError(errorObject))
+    expect(Object.keys(errorAction.error)).not.toContain('stack')
+    expect(errorAction.meta.requestId).toBe(generatedRequestId)
+    expect(errorAction.meta.arg).toBe(args)
+  })
+
+  it('dispatches a rejected action with a customized payload when a user returns rejectWithValue()', async () => {
+    const dispatch = vi.fn()
+
+    const args = 123
+    let generatedRequestId = ''
+
+    const errorPayload = {
+      errorMessage:
+        'I am a fake server-provided 400 payload with validation details',
+      errors: [
+        { field_one: 'Must be a string' },
+        { field_two: 'Must be a number' },
+      ],
+    }
+
+    const thunkActionCreator = createAsyncThunk(
+      'testType',
+      async (args: number, { requestId, rejectWithValue }) => {
+        generatedRequestId = requestId
+
+        return rejectWithValue(errorPayload)
+      },
+    )
+
+    const thunkFunction = thunkActionCreator(args)
+
+    try {
+      await thunkFunction(dispatch, () => {}, undefined)
+    } catch (e) {}
+
+    expect(dispatch).toHaveBeenNthCalledWith(
+      1,
+      thunkActionCreator.pending(generatedRequestId, args),
+    )
+
+    expect(dispatch).toHaveBeenCalledTimes(2)
+
+    // Have to check the bits of the action separately since the error was processed
+    const errorAction = dispatch.mock.calls[1][0]
+
+    expect(errorAction.error.message).toEqual('Rejected')
+    expect(errorAction.payload).toBe(errorPayload)
+    expect(errorAction.meta.arg).toBe(args)
+  })
+
+  it('dispatches a rejected action with a customized payload when a user throws rejectWithValue()', async () => {
+    const dispatch = vi.fn()
+
+    const args = 123
+    let generatedRequestId = ''
+
+    const errorPayload = {
+      errorMessage:
+        'I am a fake server-provided 400 payload with validation details',
+      errors: [
+        { field_one: 'Must be a string' },
+        { field_two: 'Must be a number' },
+      ],
+    }
+
+    const thunkActionCreator = createAsyncThunk(
+      'testType',
+      async (args: number, { requestId, rejectWithValue }) => {
+        generatedRequestId = requestId
+
+        throw rejectWithValue(errorPayload)
+      },
+    )
+
+    const thunkFunction = thunkActionCreator(args)
+
+    try {
+      await thunkFunction(dispatch, () => {}, undefined)
+    } catch (e) {}
+
+    expect(dispatch).toHaveBeenNthCalledWith(
+      1,
+      thunkActionCreator.pending(generatedRequestId, args),
+    )
+
+    expect(dispatch).toHaveBeenCalledTimes(2)
+
+    // Have to check the bits of the action separately since the error was processed
+    const errorAction = dispatch.mock.calls[1][0]
+
+    expect(errorAction.error.message).toEqual('Rejected')
+    expect(errorAction.payload).toBe(errorPayload)
+    expect(errorAction.meta.arg).toBe(args)
+  })
+
+  it('dispatches a rejected action with a miniSerializeError when rejectWithValue conditions are not satisfied', async () => {
+    const dispatch = vi.fn()
+
+    const args = 123
+    let generatedRequestId = ''
+
+    const error = new Error('Panic!')
+
+    const errorPayload = {
+      errorMessage:
+        'I am a fake server-provided 400 payload with validation details',
+      errors: [
+        { field_one: 'Must be a string' },
+        { field_two: 'Must be a number' },
+      ],
+    }
+
+    const thunkActionCreator = createAsyncThunk(
+      'testType',
+      async (args: number, { requestId, rejectWithValue }) => {
+        generatedRequestId = requestId
+
+        try {
+          throw error
+        } catch (err) {
+          if (!(err as any).response) {
+            throw err
+          }
+          return rejectWithValue(errorPayload)
+        }
+      },
+    )
+
+    const thunkFunction = thunkActionCreator(args)
+
+    try {
+      await thunkFunction(dispatch, () => {}, undefined)
+    } catch (e) {}
+
+    expect(dispatch).toHaveBeenNthCalledWith(
+      1,
+      thunkActionCreator.pending(generatedRequestId, args),
+    )
+
+    expect(dispatch).toHaveBeenCalledTimes(2)
+
+    // Have to check the bits of the action separately since the error was processed
+    const errorAction = dispatch.mock.calls[1][0]
+    expect(errorAction.error).toEqual(miniSerializeError(error))
+    expect(errorAction.payload).toEqual(undefined)
+    expect(errorAction.meta.requestId).toBe(generatedRequestId)
+    expect(errorAction.meta.arg).toBe(args)
+  })
+})
+
+describe('createAsyncThunk with abortController', () => {
+  const asyncThunk = createAsyncThunk(
+    'test',
+    function abortablePayloadCreator(_: any, { signal }) {
+      return new Promise((resolve, reject) => {
+        if (signal.aborted) {
+          reject(
+            new DOMException(
+              'This should never be reached as it should already be handled.',
+              'AbortError',
+            ),
+          )
+        }
+        signal.addEventListener('abort', () => {
+          reject(new DOMException('Was aborted while running', 'AbortError'))
+        })
+        setTimeout(resolve, 100)
+      })
+    },
+  )
+
+  let store = configureStore({
+    reducer(store: UnknownAction[] = []) {
+      return store
+    },
+  })
+
+  beforeEach(() => {
+    store = configureStore({
+      reducer(store: UnknownAction[] = [], action) {
+        return [...store, action]
+      },
+    })
+  })
+
+  test('normal usage', async () => {
+    await store.dispatch(asyncThunk({}))
+    expect(store.getState()).toEqual([
+      expect.any(Object),
+      expect.objectContaining({ type: 'test/pending' }),
+      expect.objectContaining({ type: 'test/fulfilled' }),
+    ])
+  })
+
+  test('abort after dispatch', async () => {
+    const promise = store.dispatch(asyncThunk({}))
+    promise.abort('AbortReason')
+    const result = await promise
+    const expectedAbortedAction = {
+      type: 'test/rejected',
+      error: {
+        message: 'AbortReason',
+        name: 'AbortError',
+      },
+      meta: { aborted: true, requestId: promise.requestId },
+    }
+
+    // abortedAction with reason is dispatched after test/pending is dispatched
+    expect(store.getState()).toMatchObject([
+      {},
+      { type: 'test/pending' },
+      expectedAbortedAction,
+    ])
+
+    // same abortedAction is returned, but with the AbortError from the abortablePayloadCreator
+    expect(result).toMatchObject(expectedAbortedAction)
+
+    // calling unwrapResult on the returned object re-throws the error from the abortablePayloadCreator
+    expect(() => unwrapResult(result)).toThrowError(
+      expect.objectContaining(expectedAbortedAction.error),
+    )
+  })
+
+  test('even when the payloadCreator does not directly support the signal, no further actions are dispatched', async () => {
+    const unawareAsyncThunk = createAsyncThunk('unaware', async () => {
+      await new Promise((resolve) => setTimeout(resolve, 100))
+      return 'finished'
+    })
+
+    const promise = store.dispatch(unawareAsyncThunk())
+    promise.abort('AbortReason')
+    const result = await promise
+
+    const expectedAbortedAction = {
+      type: 'unaware/rejected',
+      error: {
+        message: 'AbortReason',
+        name: 'AbortError',
+      },
+    }
+
+    // abortedAction with reason is dispatched after test/pending is dispatched
+    expect(store.getState()).toEqual([
+      expect.any(Object),
+      expect.objectContaining({ type: 'unaware/pending' }),
+      expect.objectContaining(expectedAbortedAction),
+    ])
+
+    // same abortedAction is returned, but with the AbortError from the abortablePayloadCreator
+    expect(result).toMatchObject(expectedAbortedAction)
+
+    // calling unwrapResult on the returned object re-throws the error from the abortablePayloadCreator
+    expect(() => unwrapResult(result)).toThrowError(
+      expect.objectContaining(expectedAbortedAction.error),
+    )
+  })
+
+  test('dispatch(asyncThunk) returns on abort and does not wait for the promiseProvider to finish', async () => {
+    let running = false
+    const longRunningAsyncThunk = createAsyncThunk('longRunning', async () => {
+      running = true
+      await new Promise((resolve) => setTimeout(resolve, 30000))
+      running = false
+    })
+
+    const promise = store.dispatch(longRunningAsyncThunk())
+    expect(running).toBeTruthy()
+    promise.abort()
+    const result = await promise
+    expect(running).toBeTruthy()
+    expect(result).toMatchObject({
+      type: 'longRunning/rejected',
+      error: { message: 'Aborted', name: 'AbortError' },
+      meta: { aborted: true },
+    })
+  })
+
+  describe('behavior with missing AbortController', () => {
+    let keepAbortController: (typeof window)['AbortController']
+    let freshlyLoadedModule: typeof import('../createAsyncThunk')
+
+    beforeEach(async () => {
+      keepAbortController = window.AbortController
+      delete (window as any).AbortController
+      vi.resetModules()
+      freshlyLoadedModule = await import('../createAsyncThunk')
+      vi.stubEnv('NODE_ENV', 'development')
+    })
+
+    afterEach(() => {
+      vi.unstubAllEnvs()
+      vi.clearAllMocks()
+      vi.stubGlobal('AbortController', keepAbortController)
+      vi.resetModules()
+    })
+
+    test('calling a thunk made with createAsyncThunk should fail if no global abortController is not available', async () => {
+      const longRunningAsyncThunk = freshlyLoadedModule.createAsyncThunk(
+        'longRunning',
+        async () => {
+          await new Promise((resolve) => setTimeout(resolve, 30000))
+        },
+      )
+
+      expect(longRunningAsyncThunk()).toThrow('AbortController is not defined')
+    })
+  })
+})
+
+test('non-serializable arguments are ignored by serializableStateInvariantMiddleware', async () => {
+  const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
+  const nonSerializableValue = new Map()
+  const asyncThunk = createAsyncThunk('test', (arg: Map<any, any>) => {})
+
+  configureStore({
+    reducer: () => 0,
+  }).dispatch(asyncThunk(nonSerializableValue))
+
+  expect(consoleErrorSpy).not.toHaveBeenCalled()
+
+  consoleErrorSpy.mockRestore()
+})
+
+describe('conditional skipping of asyncThunks', () => {
+  const arg = {}
+  const getState = vi.fn(() => ({}))
+  const dispatch = vi.fn((x: any) => x)
+  const payloadCreator = vi.fn((x: typeof arg) => 10)
+  const condition = vi.fn(() => false)
+  const extra = {}
+
+  beforeEach(() => {
+    getState.mockClear()
+    dispatch.mockClear()
+    payloadCreator.mockClear()
+    condition.mockClear()
+  })
+
+  test('returning false from condition skips payloadCreator and returns a rejected action', async () => {
+    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })
+    const result = await asyncThunk(arg)(dispatch, getState, extra)
+
+    expect(condition).toHaveBeenCalled()
+    expect(payloadCreator).not.toHaveBeenCalled()
+    expect(asyncThunk.rejected.match(result)).toBe(true)
+    expect((result as any).meta.condition).toBe(true)
+  })
+
+  test('return falsy from condition does not skip payload creator', async () => {
+    // Override TS's expectation that this is a boolean
+    condition.mockReturnValueOnce(undefined as unknown as boolean)
+    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })
+    const result = await asyncThunk(arg)(dispatch, getState, extra)
+
+    expect(condition).toHaveBeenCalled()
+    expect(payloadCreator).toHaveBeenCalled()
+    expect(asyncThunk.fulfilled.match(result)).toBe(true)
+    expect(result.payload).toBe(10)
+  })
+
+  test('returning true from condition executes payloadCreator', async () => {
+    condition.mockReturnValueOnce(true)
+    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })
+    const result = await asyncThunk(arg)(dispatch, getState, extra)
+
+    expect(condition).toHaveBeenCalled()
+    expect(payloadCreator).toHaveBeenCalled()
+    expect(asyncThunk.fulfilled.match(result)).toBe(true)
+    expect(result.payload).toBe(10)
+  })
+
+  test('condition is called with arg, getState and extra', async () => {
+    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })
+    await asyncThunk(arg)(dispatch, getState, extra)
+
+    expect(condition).toHaveBeenCalledOnce()
+    expect(condition).toHaveBeenLastCalledWith(
+      arg,
+      expect.objectContaining({ getState, extra }),
+    )
+  })
+
+  test('pending is dispatched synchronously if condition is synchronous', async () => {
+    const condition = () => true
+    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })
+    const thunkCallPromise = asyncThunk(arg)(dispatch, getState, extra)
+    expect(dispatch).toHaveBeenCalledOnce()
+    await thunkCallPromise
+    expect(dispatch).toHaveBeenCalledTimes(2)
+  })
+
+  test('async condition', async () => {
+    const condition = () => Promise.resolve(false)
+    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })
+    await asyncThunk(arg)(dispatch, getState, extra)
+    expect(dispatch).not.toHaveBeenCalled()
+  })
+
+  test('async condition with rejected promise', async () => {
+    const condition = () => Promise.reject()
+    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })
+    await asyncThunk(arg)(dispatch, getState, extra)
+    expect(dispatch).toHaveBeenCalledOnce()
+    expect(dispatch).toHaveBeenLastCalledWith(
+      expect.objectContaining({ type: 'test/rejected' }),
+    )
+  })
+
+  test('async condition with AbortController signal first', async () => {
+    const condition = async () => {
+      await delay(25)
+      return true
+    }
+    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })
+
+    try {
+      const thunkPromise = asyncThunk(arg)(dispatch, getState, extra)
+      thunkPromise.abort()
+      await thunkPromise
+    } catch (err) {}
+    expect(dispatch).not.toHaveBeenCalled()
+  })
+
+  test('rejected action is not dispatched by default', async () => {
+    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })
+    await asyncThunk(arg)(dispatch, getState, extra)
+
+    expect(dispatch).not.toHaveBeenCalled()
+  })
+
+  test('does not fail when attempting to abort a canceled promise', async () => {
+    const asyncPayloadCreator = vi.fn(async (x: typeof arg) => {
+      await delay(200)
+      return 10
+    })
+
+    const asyncThunk = createAsyncThunk('test', asyncPayloadCreator, {
+      condition,
+    })
+    const promise = asyncThunk(arg)(dispatch, getState, extra)
+    promise.abort(
+      `If the promise was 1. somehow canceled, 2. in a 'started' state and 3. we attempted to abort, this would crash the tests`,
+    )
+  })
+
+  test('rejected action can be dispatched via option', async () => {
+    const asyncThunk = createAsyncThunk('test', payloadCreator, {
+      condition,
+      dispatchConditionRejection: true,
+    })
+    await asyncThunk(arg)(dispatch, getState, extra)
+
+    expect(dispatch).toHaveBeenCalledOnce()
+    expect(dispatch).toHaveBeenLastCalledWith(
+      expect.objectContaining({
+        error: {
+          message: 'Aborted due to condition callback returning false.',
+          name: 'ConditionError',
+        },
+        meta: {
+          aborted: false,
+          arg,
+          rejectedWithValue: false,
+          condition: true,
+          requestId: expect.stringContaining(''),
+          requestStatus: 'rejected',
+        },
+        payload: undefined,
+        type: 'test/rejected',
+      }),
+    )
+  })
+})
+
+test('serializeError implementation', async () => {
+  function serializeError() {
+    return 'serialized!'
+  }
+  const errorObject = 'something else!'
+
+  const store = configureStore({
+    reducer: (state = [], action) => [...state, action],
+  })
+
+  const asyncThunk = createAsyncThunk<
+    unknown,
+    void,
+    { serializedErrorType: string }
+  >('test', () => Promise.reject(errorObject), { serializeError })
+  const rejected = await store.dispatch(asyncThunk())
+  if (!asyncThunk.rejected.match(rejected)) {
+    throw new Error()
+  }
+
+  const expectation = {
+    type: 'test/rejected',
+    payload: undefined,
+    error: 'serialized!',
+    meta: expect.any(Object),
+  }
+  expect(rejected).toEqual(expectation)
+  expect(store.getState()[2]).toEqual(expectation)
+  expect(rejected.error).not.toEqual(miniSerializeError(errorObject))
+})
+
+describe('unwrapResult', () => {
+  const getState = vi.fn(() => ({}))
+  const dispatch = vi.fn((x: any) => x)
+  const extra = {}
+  test('fulfilled case', async () => {
+    const asyncThunk = createAsyncThunk('test', () => {
+      return 'fulfilled!' as const
+    })
+
+    const unwrapPromise = asyncThunk()(dispatch, getState, extra).then(
+      unwrapResult,
+    )
+
+    await expect(unwrapPromise).resolves.toBe('fulfilled!')
+
+    const unwrapPromise2 = asyncThunk()(dispatch, getState, extra)
+    const res = await unwrapPromise2.unwrap()
+    expect(res).toBe('fulfilled!')
+  })
+  test('error case', async () => {
+    const error = new Error('Panic!')
+    const asyncThunk = createAsyncThunk('test', () => {
+      throw error
+    })
+
+    const unwrapPromise = asyncThunk()(dispatch, getState, extra).then(
+      unwrapResult,
+    )
+
+    await expect(unwrapPromise).rejects.toEqual(miniSerializeError(error))
+
+    const unwrapPromise2 = asyncThunk()(dispatch, getState, extra)
+    await expect(unwrapPromise2.unwrap()).rejects.toEqual(
+      miniSerializeError(error),
+    )
+  })
+  test('rejectWithValue case', async () => {
+    const asyncThunk = createAsyncThunk('test', (_, { rejectWithValue }) => {
+      return rejectWithValue('rejectWithValue!')
+    })
+
+    const unwrapPromise = asyncThunk()(dispatch, getState, extra).then(
+      unwrapResult,
+    )
+
+    await expect(unwrapPromise).rejects.toBe('rejectWithValue!')
+
+    const unwrapPromise2 = asyncThunk()(dispatch, getState, extra)
+    await expect(unwrapPromise2.unwrap()).rejects.toBe('rejectWithValue!')
+  })
+})
+
+describe('idGenerator option', () => {
+  const getState = () => ({})
+  const dispatch = (x: any) => x
+  const extra = {}
+
+  test('idGenerator implementation - can customizes how request IDs are generated', async () => {
+    function makeFakeIdGenerator() {
+      let id = 0
+      return vi.fn(() => {
+        id++
+        return `fake-random-id-${id}`
+      })
+    }
+
+    let generatedRequestId = ''
+
+    const idGenerator = makeFakeIdGenerator()
+    const asyncThunk = createAsyncThunk(
+      'test',
+      async (args: void, { requestId }) => {
+        generatedRequestId = requestId
+      },
+      { idGenerator },
+    )
+
+    // dispatching the thunks should be using the custom id generator
+    const promise0 = asyncThunk()(dispatch, getState, extra)
+    expect(generatedRequestId).toEqual('fake-random-id-1')
+    expect(promise0.requestId).toEqual('fake-random-id-1')
+    expect((await promise0).meta.requestId).toEqual('fake-random-id-1')
+
+    const promise1 = asyncThunk()(dispatch, getState, extra)
+    expect(generatedRequestId).toEqual('fake-random-id-2')
+    expect(promise1.requestId).toEqual('fake-random-id-2')
+    expect((await promise1).meta.requestId).toEqual('fake-random-id-2')
+
+    const promise2 = asyncThunk()(dispatch, getState, extra)
+    expect(generatedRequestId).toEqual('fake-random-id-3')
+    expect(promise2.requestId).toEqual('fake-random-id-3')
+    expect((await promise2).meta.requestId).toEqual('fake-random-id-3')
+
+    generatedRequestId = ''
+    const defaultAsyncThunk = createAsyncThunk(
+      'test',
+      async (args: void, { requestId }) => {
+        generatedRequestId = requestId
+      },
+    )
+    // dispatching the default options thunk should still generate an id,
+    // but not using the custom id generator
+    const promise3 = defaultAsyncThunk()(dispatch, getState, extra)
+    expect(generatedRequestId).toEqual(promise3.requestId)
+    expect(promise3.requestId).not.toEqual('')
+    expect(promise3.requestId).not.toEqual(
+      expect.stringContaining('fake-random-id'),
+    )
+    expect((await promise3).meta.requestId).not.toEqual(
+      expect.stringContaining('fake-fandom-id'),
+    )
+  })
+
+  test('idGenerator should be called with thunkArg', async () => {
+    const customIdGenerator = vi.fn((seed) => `fake-unique-random-id-${seed}`)
+    let generatedRequestId = ''
+    const asyncThunk = createAsyncThunk(
+      'test',
+      async (args: any, { requestId }) => {
+        generatedRequestId = requestId
+      },
+      { idGenerator: customIdGenerator },
+    )
+
+    const thunkArg = 1
+    const expected = 'fake-unique-random-id-1'
+    const asyncThunkPromise = asyncThunk(thunkArg)(dispatch, getState, extra)
+
+    expect(customIdGenerator).toHaveBeenCalledWith(thunkArg)
+    expect(asyncThunkPromise.requestId).toEqual(expected)
+    expect((await asyncThunkPromise).meta.requestId).toEqual(expected)
+  })
+})
+
+test('`condition` will see state changes from a synchronously invoked asyncThunk', () => {
+  type State = ReturnType<typeof store.getState>
+  const onStart = vi.fn()
+  const asyncThunk = createAsyncThunk<
+    void,
+    { force?: boolean },
+    { state: State }
+  >('test', onStart, {
+    condition({ force }, { getState }) {
+      return force || !getState().started
+    },
+  })
+  const store = configureStore({
+    reducer: createReducer({ started: false }, (builder) => {
+      builder.addCase(asyncThunk.pending, (state) => {
+        state.started = true
+      })
+    }),
+  })
+
+  store.dispatch(asyncThunk({ force: false }))
+  expect(onStart).toHaveBeenCalledOnce()
+  store.dispatch(asyncThunk({ force: false }))
+  expect(onStart).toHaveBeenCalledOnce()
+  store.dispatch(asyncThunk({ force: true }))
+  expect(onStart).toHaveBeenCalledTimes(2)
+})
+
+const getNewStore = () =>
+  configureStore({
+    reducer(actions: UnknownAction[] = [], action) {
+      return [...actions, action]
+    },
+  })
+
+describe('meta', () => {
+  let store = getNewStore()
+
+  beforeEach(() => {
+    store = getNewStore()
+  })
+
+  test('pendingMeta', () => {
+    const pendingThunk = createAsyncThunk('test', (arg: string) => {}, {
+      getPendingMeta({ arg, requestId }) {
+        expect(arg).toBe('testArg')
+        expect(requestId).toEqual(expect.any(String))
+        return { extraProp: 'foo' }
+      },
+    })
+    const ret = store.dispatch(pendingThunk('testArg'))
+    expect(store.getState()[1]).toEqual({
+      meta: {
+        arg: 'testArg',
+        extraProp: 'foo',
+        requestId: ret.requestId,
+        requestStatus: 'pending',
+      },
+      payload: undefined,
+      type: 'test/pending',
+    })
+  })
+
+  test('fulfilledMeta', async () => {
+    const fulfilledThunk = createAsyncThunk<
+      string,
+      string,
+      { fulfilledMeta: { extraProp: string } }
+    >('test', (arg: string, { fulfillWithValue }) => {
+      return fulfillWithValue('hooray!', { extraProp: 'bar' })
+    })
+    const ret = store.dispatch(fulfilledThunk('testArg'))
+    expect(await ret).toEqual({
+      meta: {
+        arg: 'testArg',
+        extraProp: 'bar',
+        requestId: ret.requestId,
+        requestStatus: 'fulfilled',
+      },
+      payload: 'hooray!',
+      type: 'test/fulfilled',
+    })
+  })
+
+  test('rejectedMeta', async () => {
+    const fulfilledThunk = createAsyncThunk<
+      string,
+      string,
+      { rejectedMeta: { extraProp: string } }
+    >('test', (arg: string, { rejectWithValue }) => {
+      return rejectWithValue('damn!', { extraProp: 'baz' })
+    })
+    const promise = store.dispatch(fulfilledThunk('testArg'))
+    const ret = await promise
+    expect(ret).toEqual({
+      meta: {
+        arg: 'testArg',
+        extraProp: 'baz',
+        requestId: promise.requestId,
+        requestStatus: 'rejected',
+        rejectedWithValue: true,
+        aborted: false,
+        condition: false,
+      },
+      error: { message: 'Rejected' },
+      payload: 'damn!',
+      type: 'test/rejected',
+    })
+
+    if (ret.meta.requestStatus === 'rejected' && ret.meta.rejectedWithValue) {
+    } else {
+      // could be caused by a `throw`, `abort()` or `condition` - no `rejectedMeta` in that case
+      // @ts-expect-error
+      ret.meta.extraProp
+    }
+  })
+
+  test('typed createAsyncThunk.withTypes', () => {
+    const typedCAT = createAsyncThunk.withTypes<{
+      state: { s: string }
+      rejectValue: string
+      extra: { s: string; n: number }
+    }>()
+    const thunk = typedCAT('a', () => 'b')
+    const expectFunction = expect.any(Function)
+    expect(thunk.fulfilled).toEqual(expectFunction)
+    expect(thunk.pending).toEqual(expectFunction)
+    expect(thunk.rejected).toEqual(expectFunction)
+    expect(thunk.settled).toEqual(expectFunction)
+    expect(thunk.fulfilled.type).toBe('a/fulfilled')
+  })
+  test('createAsyncThunkWrapper using CreateAsyncThunkFunction', async () => {
+    const customSerializeError = () => 'serialized!'
+    const createAppAsyncThunk: CreateAsyncThunkFunction<{
+      serializedErrorType: ReturnType<typeof customSerializeError>
+    }> = (prefix: string, payloadCreator: any, options: any) =>
+      createAsyncThunk(prefix, payloadCreator, {
+        ...options,
+        serializeError: customSerializeError,
+      }) as any
+
+    const asyncThunk = createAppAsyncThunk('test', async () => {
+      throw new Error('Panic!')
+    })
+
+    const promise = store.dispatch(asyncThunk())
+    const result = await promise
+    if (!asyncThunk.rejected.match(result)) {
+      throw new Error('should have thrown')
+    }
+    expect(result.error).toEqual('serialized!')
+  })
+})
+
+describe('dispatch config', () => {
+  let store = getNewStore()
+
+  beforeEach(() => {
+    store = getNewStore()
+  })
+  test('accepts external signal', async () => {
+    const asyncThunk = createAsyncThunk('test', async (_: void, { signal }) => {
+      signal.throwIfAborted()
+      const { promise, reject } = promiseWithResolvers<never>()
+      signal.addEventListener('abort', () => reject(signal.reason))
+      return promise
+    })
+
+    const abortController = new AbortController()
+    const promise = store.dispatch(
+      asyncThunk(undefined, { signal: abortController.signal }),
+    )
+    abortController.abort()
+    await expect(promise.unwrap()).rejects.toThrow(
+      'External signal was aborted',
+    )
+  })
+  test('handles already aborted external signal', async () => {
+    const asyncThunk = createAsyncThunk('test', async (_: void, { signal }) => {
+      signal.throwIfAborted()
+      const { promise, reject } = promiseWithResolvers<never>()
+      signal.addEventListener('abort', () => reject(signal.reason))
+      return promise
+    })
+
+    const signal = AbortSignal.abort()
+    const promise = store.dispatch(asyncThunk(undefined, { signal }))
+    await expect(promise.unwrap()).rejects.toThrow(
+      'Aborted due to condition callback returning false.',
+    )
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/createDraftSafeSelector.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/createDraftSafeSelector.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/createDraftSafeSelector.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,43 @@
+import { createDraftSafeSelector, createSelector } from '@reduxjs/toolkit'
+import { produce } from 'immer'
+
+type State = { value: number }
+const selectSelf = (state: State) => state
+
+test('handles normal values correctly', () => {
+  const unsafeSelector = createSelector(selectSelf, (x) => x.value)
+  const draftSafeSelector = createDraftSafeSelector(selectSelf, (x) => x.value)
+
+  let state = { value: 1 }
+  expect(unsafeSelector(state)).toBe(1)
+  expect(draftSafeSelector(state)).toBe(1)
+  expect(draftSafeSelector).toHaveProperty('resultFunc')
+  expect(draftSafeSelector).toHaveProperty('memoizedResultFunc')
+  expect(draftSafeSelector).toHaveProperty('lastResult')
+  expect(draftSafeSelector).toHaveProperty('dependencies')
+  expect(draftSafeSelector).toHaveProperty('recomputations')
+  expect(draftSafeSelector).toHaveProperty('resetRecomputations')
+  expect(draftSafeSelector).toHaveProperty('clearCache')
+
+  state = { value: 2 }
+  expect(unsafeSelector(state)).toBe(2)
+  expect(draftSafeSelector(state)).toBe(2)
+})
+
+test('handles drafts correctly', () => {
+  const unsafeSelector = createSelector(selectSelf, (state) => state.value)
+  const draftSafeSelector = createDraftSafeSelector(
+    selectSelf,
+    (state) => state.value,
+  )
+
+  produce({ value: 1 }, (state) => {
+    expect(unsafeSelector(state)).toBe(1)
+    expect(draftSafeSelector(state)).toBe(1)
+
+    state.value = 2
+
+    expect(unsafeSelector(state)).toBe(1)
+    expect(draftSafeSelector(state)).toBe(2)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/createDraftSafeSelector.withTypes.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/createDraftSafeSelector.withTypes.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/createDraftSafeSelector.withTypes.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,49 @@
+import { createDraftSafeSelector } from '@reduxjs/toolkit'
+
+interface Todo {
+  id: number
+  completed: boolean
+}
+
+interface Alert {
+  id: number
+  read: boolean
+}
+
+interface RootState {
+  todos: Todo[]
+  alerts: Alert[]
+}
+
+const rootState: RootState = {
+  todos: [
+    { id: 0, completed: false },
+    { id: 1, completed: false },
+  ],
+  alerts: [
+    { id: 0, read: false },
+    { id: 1, read: false },
+  ],
+}
+
+describe(createDraftSafeSelector.withTypes, () => {
+  const createTypedDraftSafeSelector =
+    createDraftSafeSelector.withTypes<RootState>()
+
+  test('should return createDraftSafeSelector', () => {
+    expect(createTypedDraftSafeSelector.withTypes).toEqual(expect.any(Function))
+
+    expect(createTypedDraftSafeSelector.withTypes().withTypes).toEqual(
+      expect.any(Function),
+    )
+
+    expect(createTypedDraftSafeSelector).toBe(createDraftSafeSelector)
+
+    const selectTodoIds = createTypedDraftSafeSelector(
+      [(state) => state.todos],
+      (todos) => todos.map(({ id }) => id),
+    )
+
+    expect(selectTodoIds(rootState)).to.be.an('array').that.is.not.empty
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/createEntityAdapter.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/createEntityAdapter.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/createEntityAdapter.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,161 @@
+import type {
+  ActionCreatorWithPayload,
+  ActionCreatorWithoutPayload,
+  EntityAdapter,
+  EntityId,
+  EntityStateAdapter,
+  Update,
+} from '@reduxjs/toolkit'
+import { createEntityAdapter, createSlice } from '@reduxjs/toolkit'
+
+function extractReducers<T, Id extends EntityId>(
+  adapter: EntityAdapter<T, Id>,
+): EntityStateAdapter<T, Id> {
+  const { selectId, sortComparer, getInitialState, getSelectors, ...rest } =
+    adapter
+  return rest
+}
+
+describe('type tests', () => {
+  test('should be usable in a slice, with all the "reducer-like" functions', () => {
+    type Id = string & { readonly __tag: unique symbol }
+    type Entity = {
+      id: Id
+    }
+    const adapter = createEntityAdapter<Entity>()
+    const slice = createSlice({
+      name: 'test',
+      initialState: adapter.getInitialState(),
+      reducers: {
+        ...extractReducers(adapter),
+      },
+    })
+
+    expectTypeOf(slice.actions.addOne).toMatchTypeOf<
+      ActionCreatorWithPayload<Entity>
+    >()
+
+    expectTypeOf(slice.actions.addMany).toMatchTypeOf<
+      ActionCreatorWithPayload<ReadonlyArray<Entity> | Record<string, Entity>>
+    >()
+
+    expectTypeOf(slice.actions.setAll).toMatchTypeOf<
+      ActionCreatorWithPayload<ReadonlyArray<Entity> | Record<string, Entity>>
+    >()
+
+    expectTypeOf(slice.actions.removeOne).toMatchTypeOf<
+      ActionCreatorWithPayload<Id>
+    >()
+
+    expectTypeOf(slice.actions.addMany).not.toMatchTypeOf<
+      ActionCreatorWithPayload<Entity[] | Record<string, Entity>>
+    >()
+
+    expectTypeOf(slice.actions.setAll).not.toMatchTypeOf<
+      ActionCreatorWithPayload<ReadonlyArray<Id>>
+    >()
+
+    expectTypeOf(slice.actions.removeOne).toMatchTypeOf<
+      ActionCreatorWithPayload<Id>
+    >()
+
+    expectTypeOf(slice.actions.removeMany).toMatchTypeOf<
+      ActionCreatorWithPayload<ReadonlyArray<Id>>
+    >()
+
+    expectTypeOf(slice.actions.removeMany).not.toMatchTypeOf<
+      ActionCreatorWithPayload<EntityId[]>
+    >()
+
+    expectTypeOf(
+      slice.actions.removeAll,
+    ).toMatchTypeOf<ActionCreatorWithoutPayload>()
+
+    expectTypeOf(slice.actions.updateOne).toMatchTypeOf<
+      ActionCreatorWithPayload<Update<Entity, Id>>
+    >()
+
+    expectTypeOf(slice.actions.updateMany).not.toMatchTypeOf<
+      ActionCreatorWithPayload<Update<Entity, Id>[]>
+    >()
+
+    expectTypeOf(slice.actions.upsertOne).toMatchTypeOf<
+      ActionCreatorWithPayload<Entity>
+    >()
+
+    expectTypeOf(slice.actions.updateMany).toMatchTypeOf<
+      ActionCreatorWithPayload<ReadonlyArray<Update<Entity, Id>>>
+    >()
+
+    expectTypeOf(slice.actions.upsertOne).toMatchTypeOf<
+      ActionCreatorWithPayload<Entity>
+    >()
+
+    expectTypeOf(slice.actions.upsertMany).toMatchTypeOf<
+      ActionCreatorWithPayload<ReadonlyArray<Entity> | Record<string, Entity>>
+    >()
+
+    expectTypeOf(slice.actions.upsertMany).not.toMatchTypeOf<
+      ActionCreatorWithPayload<Entity[] | Record<string, Entity>>
+    >()
+  })
+
+  test('should not be able to mix with a different EntityAdapter', () => {
+    type Entity = {
+      id: EntityId
+      value: string
+    }
+    type Entity2 = {
+      id: EntityId
+      value2: string
+    }
+    const adapter = createEntityAdapter<Entity>()
+    const adapter2 = createEntityAdapter<Entity2>()
+    createSlice({
+      name: 'test',
+      initialState: adapter.getInitialState(),
+      reducers: {
+        addOne: adapter.addOne,
+        // @ts-expect-error
+        addOne2: adapter2.addOne,
+      },
+    })
+  })
+
+  test('should be usable in a slice with extra properties', () => {
+    type Entity = { id: EntityId; value: string }
+    const adapter = createEntityAdapter<Entity>()
+    createSlice({
+      name: 'test',
+      initialState: adapter.getInitialState({ extraData: 'test' }),
+      reducers: {
+        addOne: adapter.addOne,
+      },
+    })
+  })
+
+  test('should not be usable in a slice with an unfitting state', () => {
+    type Entity = { id: EntityId; value: string }
+    const adapter = createEntityAdapter<Entity>()
+    createSlice({
+      name: 'test',
+      initialState: { somethingElse: '' },
+      reducers: {
+        // @ts-expect-error
+        addOne: adapter.addOne,
+      },
+    })
+  })
+
+  test('should not be able to create an adapter unless the type has an Id or an idSelector is provided', () => {
+    type Entity = {
+      value: string
+    }
+    // @ts-expect-error
+    const adapter = createEntityAdapter<Entity>()
+    const adapter2: EntityAdapter<Entity, Entity['value']> =
+      createEntityAdapter({
+        selectId: (e: Entity) => e.value,
+      })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/createReducer.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/createReducer.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/createReducer.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,77 @@
+import type { ActionReducerMapBuilder, Reducer } from '@reduxjs/toolkit'
+import { createAction, createReducer } from '@reduxjs/toolkit'
+
+describe('type tests', () => {
+  test('createReducer() infers type of returned reducer.', () => {
+    const incrementHandler = (
+      state: number,
+      action: { type: 'increment'; payload: number },
+    ) => state + 1
+
+    const decrementHandler = (
+      state: number,
+      action: { type: 'decrement'; payload: number },
+    ) => state - 1
+
+    const reducer = createReducer(0 as number, (builder) => {
+      builder
+        .addCase('increment', incrementHandler)
+        .addCase('decrement', decrementHandler)
+    })
+
+    expectTypeOf(reducer).toMatchTypeOf<Reducer<number>>()
+
+    expectTypeOf(reducer).not.toMatchTypeOf<Reducer<string>>()
+  })
+
+  test('createReducer() state type can be specified explicitly.', () => {
+    const incrementHandler = (
+      state: number,
+      action: { type: 'increment'; payload: number },
+    ) => state + action.payload
+
+    const decrementHandler = (
+      state: number,
+      action: { type: 'decrement'; payload: number },
+    ) => state - action.payload
+
+    createReducer(0 as number, (builder) => {
+      builder
+        .addCase('increment', incrementHandler)
+        .addCase('decrement', decrementHandler)
+    })
+
+    // @ts-expect-error
+    createReducer<string>(0 as number, (builder) => {
+      expectTypeOf(builder.addCase)
+        .parameter(1)
+        .not.toMatchTypeOf(incrementHandler)
+
+      expectTypeOf(builder.addCase)
+        .parameter(1)
+        .not.toMatchTypeOf(decrementHandler)
+    })
+  })
+
+  test('createReducer() ensures state type is mutable within a case reducer.', () => {
+    const initialState: { readonly counter: number } = { counter: 0 }
+
+    createReducer(initialState, (builder) => {
+      builder.addCase('increment', (state) => {
+        state.counter += 1
+      })
+    })
+  })
+
+  test('builder callback for actionMap', () => {
+    const increment = createAction<number, 'increment'>('increment')
+
+    const reducer = createReducer(0, (builder) =>
+      expectTypeOf(builder).toEqualTypeOf<ActionReducerMapBuilder<number>>(),
+    )
+
+    expectTypeOf(reducer(0, increment(5))).toBeNumber()
+
+    expectTypeOf(reducer(0, increment(5))).not.toBeString()
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/createReducer.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/createReducer.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/createReducer.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,693 @@
+import type {
+  CaseReducer,
+  Draft,
+  PayloadAction,
+  Reducer,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import {
+  createAction,
+  createAsyncThunk,
+  createNextState,
+  createReducer,
+  isPlainObject,
+} from '@reduxjs/toolkit'
+import { waitMs } from './utils/helpers'
+
+interface Todo {
+  text: string
+  completed?: boolean
+}
+
+interface AddTodoPayload {
+  newTodo: Todo
+}
+
+interface ToggleTodoPayload {
+  index: number
+}
+
+type TodoState = Todo[]
+type TodosReducer = Reducer<TodoState, PayloadAction<any>>
+type AddTodoReducer = CaseReducer<
+  TodoState,
+  PayloadAction<AddTodoPayload, 'ADD_TODO'>
+>
+
+type ToggleTodoReducer = CaseReducer<
+  TodoState,
+  PayloadAction<ToggleTodoPayload, 'TOGGLE_TODO'>
+>
+
+type CreateReducer = typeof createReducer
+
+const addTodoThunk = createAsyncThunk('todos/add', (todo: Todo) => todo)
+
+describe('createReducer', () => {
+  describe('given impure reducers with immer', () => {
+    const addTodo: AddTodoReducer = (state, action) => {
+      const { newTodo } = action.payload
+
+      // Can safely call state.push() here
+      state.push({ ...newTodo, completed: false })
+    }
+
+    const toggleTodo: ToggleTodoReducer = (state, action) => {
+      const { index } = action.payload
+
+      const todo = state[index]
+      // Can directly modify the todo object
+      todo.completed = !todo.completed
+    }
+
+    const todosReducer = createReducer([] as TodoState, (builder) => {
+      builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)
+    })
+
+    behavesLikeReducer(todosReducer)
+  })
+
+  describe('Deprecation warnings', () => {
+    beforeEach(() => {
+      vi.resetModules()
+    })
+
+    afterEach(() => {
+      vi.unstubAllEnvs()
+    })
+
+    it('Throws an error if the legacy object notation is used', async () => {
+      const { createReducer } = await import('../createReducer')
+      const wrapper = () => {
+        const dummyReducer = (createReducer as CreateReducer)(
+          [] as TodoState,
+          // @ts-ignore
+          {},
+        )
+      }
+
+      expect(wrapper).toThrowError(
+        /The object notation for `createReducer` has been removed/,
+      )
+
+      expect(wrapper).toThrowError(
+        /The object notation for `createReducer` has been removed/,
+      )
+    })
+
+    it('Crashes in production', async () => {
+      vi.stubEnv('NODE_ENV', 'production')
+      const { createReducer } = await import('../createReducer')
+      const wrapper = () => {
+        const dummyReducer = (createReducer as CreateReducer)(
+          [] as TodoState,
+          // @ts-ignore
+          {},
+        )
+      }
+
+      expect(wrapper).toThrowError()
+    })
+  })
+
+  describe('Immer in a production environment', () => {
+    beforeEach(() => {
+      vi.resetModules()
+      vi.stubEnv('NODE_ENV', 'production')
+    })
+
+    afterEach(() => {
+      vi.unstubAllEnvs()
+    })
+
+    test('Freezes data in production', async () => {
+      const { createReducer } = await import('../createReducer')
+      const addTodo: AddTodoReducer = (state, action) => {
+        const { newTodo } = action.payload
+        state.push({ ...newTodo, completed: false })
+      }
+
+      const toggleTodo: ToggleTodoReducer = (state, action) => {
+        const { index } = action.payload
+        const todo = state[index]
+        todo.completed = !todo.completed
+      }
+
+      const todosReducer = createReducer([] as TodoState, (builder) => {
+        builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)
+      })
+
+      const result = todosReducer([], {
+        type: 'ADD_TODO',
+        payload: { text: 'Buy milk' },
+      })
+
+      const mutateStateOutsideReducer = () => (result[0].text = 'edited')
+      expect(mutateStateOutsideReducer).toThrowError(
+        'Cannot add property text, object is not extensible',
+      )
+    })
+
+    test('Freezes initial state', () => {
+      const initialState = [{ text: 'Buy milk' }]
+      const todosReducer = createReducer(initialState, () => {})
+      const frozenInitialState = todosReducer(undefined, { type: 'dummy' })
+
+      const mutateStateOutsideReducer = () =>
+        (frozenInitialState[0].text = 'edited')
+      expect(mutateStateOutsideReducer).toThrowError(
+        /Cannot assign to read only property/,
+      )
+    })
+    test('does not throw error if initial state is not draftable', () => {
+      expect(() =>
+        createReducer(new URLSearchParams(), () => {}),
+      ).not.toThrowError()
+    })
+  })
+
+  describe('given pure reducers with immutable updates', () => {
+    const addTodo: AddTodoReducer = (state, action) => {
+      const { newTodo } = action.payload
+
+      // Updates the state immutably without relying on immer
+      return state.concat({ ...newTodo, completed: false })
+    }
+
+    const toggleTodo: ToggleTodoReducer = (state, action) => {
+      const { index } = action.payload
+
+      // Updates the todo object immutably withot relying on immer
+      return state.map((todo, i) => {
+        if (i !== index) return todo
+        return { ...todo, completed: !todo.completed }
+      })
+    }
+
+    const todosReducer = createReducer([] as TodoState, (builder) => {
+      builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)
+    })
+
+    behavesLikeReducer(todosReducer)
+  })
+
+  describe('Accepts a lazy state init function to generate initial state', () => {
+    const addTodo: AddTodoReducer = (state, action) => {
+      const { newTodo } = action.payload
+      state.push({ ...newTodo, completed: false })
+    }
+
+    const toggleTodo: ToggleTodoReducer = (state, action) => {
+      const { index } = action.payload
+      const todo = state[index]
+      todo.completed = !todo.completed
+    }
+
+    const lazyStateInit = () => [] as TodoState
+
+    const todosReducer = createReducer([] as TodoState, (builder) => {
+      builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)
+    })
+
+    behavesLikeReducer(todosReducer)
+
+    it('Should only call the init function when `undefined` state is passed in', () => {
+      const spy = vi.fn().mockReturnValue(42)
+
+      const dummyReducer = createReducer(spy, () => {})
+      expect(spy).not.toHaveBeenCalled()
+
+      dummyReducer(123, { type: 'dummy' })
+      expect(spy).not.toHaveBeenCalled()
+
+      const initialState = dummyReducer(undefined, { type: 'dummy' })
+      expect(spy).toHaveBeenCalledOnce()
+    })
+  })
+
+  describe('given draft state from immer', () => {
+    const addTodo: AddTodoReducer = (state, action) => {
+      const { newTodo } = action.payload
+
+      // Can safely call state.push() here
+      state.push({ ...newTodo, completed: false })
+    }
+
+    const toggleTodo: ToggleTodoReducer = (state, action) => {
+      const { index } = action.payload
+
+      const todo = state[index]
+      // Can directly modify the todo object
+      todo.completed = !todo.completed
+    }
+
+    const todosReducer = createReducer([] as TodoState, (builder) => {
+      builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)
+    })
+
+    const wrappedReducer: TodosReducer = (state = [], action) => {
+      return createNextState(state, (draft: Draft<TodoState>) => {
+        todosReducer(draft, action)
+      })
+    }
+
+    behavesLikeReducer(wrappedReducer)
+  })
+
+  describe('builder callback for actionMap', () => {
+    const increment = createAction<number, 'increment'>('increment')
+    const decrement = createAction<number, 'decrement'>('decrement')
+
+    test('can be used with ActionCreators', () => {
+      const reducer = createReducer(0, (builder) =>
+        builder
+          .addCase(increment, (state, action) => state + action.payload)
+          .addCase(decrement, (state, action) => state - action.payload),
+      )
+      expect(reducer(0, increment(5))).toBe(5)
+      expect(reducer(5, decrement(5))).toBe(0)
+    })
+    test('can be used with string types', () => {
+      const reducer = createReducer(0, (builder) =>
+        builder
+          .addCase(
+            'increment',
+            (state, action: { type: 'increment'; payload: number }) =>
+              state + action.payload,
+          )
+          .addCase(
+            'decrement',
+            (state, action: { type: 'decrement'; payload: number }) =>
+              state - action.payload,
+          ),
+      )
+      expect(reducer(0, increment(5))).toBe(5)
+      expect(reducer(5, decrement(5))).toBe(0)
+    })
+    test('can be used with ActionCreators and string types combined', () => {
+      const reducer = createReducer(0, (builder) =>
+        builder
+          .addCase(increment, (state, action) => state + action.payload)
+          .addCase(
+            'decrement',
+            (state, action: { type: 'decrement'; payload: number }) =>
+              state - action.payload,
+          ),
+      )
+      expect(reducer(0, increment(5))).toBe(5)
+      expect(reducer(5, decrement(5))).toBe(0)
+    })
+    test('will throw an error when returning undefined from a non-draftable state', () => {
+      const reducer = createReducer(0, (builder) =>
+        builder.addCase(
+          'decrement',
+          (state, action: { type: 'decrement'; payload: number }) => {},
+        ),
+      )
+      expect(() => reducer(5, decrement(5))).toThrowErrorMatchingInlineSnapshot(
+        `[Error: A case reducer on a non-draftable value must not return undefined]`,
+      )
+    })
+    test('allows you to return undefined if the state was null, thus skipping an update', () => {
+      const reducer = createReducer(null as number | null, (builder) =>
+        builder.addCase(
+          'decrement',
+          (state, action: { type: 'decrement'; payload: number }) => {
+            if (typeof state === 'number') {
+              return state - action.payload
+            }
+            return undefined
+          },
+        ),
+      )
+      expect(reducer(0, decrement(5))).toBe(-5)
+      expect(reducer(null, decrement(5))).toBe(null)
+    })
+    test('allows you to return null', () => {
+      const reducer = createReducer(0 as number | null, (builder) =>
+        builder.addCase(
+          'decrement',
+          (state, action: { type: 'decrement'; payload: number }) => {
+            return null
+          },
+        ),
+      )
+      expect(reducer(5, decrement(5))).toBe(null)
+    })
+    test('allows you to return 0', () => {
+      const reducer = createReducer(0, (builder) =>
+        builder.addCase(
+          'decrement',
+          (state, action: { type: 'decrement'; payload: number }) =>
+            state - action.payload,
+        ),
+      )
+      expect(reducer(5, decrement(5))).toBe(0)
+    })
+    test('will throw if the same type is used twice', () => {
+      expect(() => {
+        createReducer(0, (builder) => {
+          builder
+            .addCase(increment, (state, action) => state + action.payload)
+            .addCase(increment, (state, action) => state + action.payload)
+            .addCase(decrement, (state, action) => state - action.payload)
+        })
+      }).toThrowErrorMatchingInlineSnapshot(
+        `[Error: \`builder.addCase\` cannot be called with two reducers for the same action type 'increment']`,
+      )
+      expect(() => {
+        createReducer(0, (builder) => {
+          builder
+            .addCase(increment, (state, action) => state + action.payload)
+            .addCase('increment', (state) => state + 1)
+            .addCase(decrement, (state, action) => state - action.payload)
+        })
+      }).toThrowErrorMatchingInlineSnapshot(
+        `[Error: \`builder.addCase\` cannot be called with two reducers for the same action type 'increment']`,
+      )
+    })
+
+    test('will throw if an empty type is used', () => {
+      const customActionCreator = (payload: number) => ({
+        type: 'custom_action',
+        payload,
+      })
+      customActionCreator.type = ''
+      expect(() => {
+        createReducer(0, (builder) => {
+          builder.addCase(
+            customActionCreator,
+            (state, action) => state + action.payload,
+          )
+        })
+      }).toThrowErrorMatchingInlineSnapshot(
+        `[Error: \`builder.addCase\` cannot be called with an empty action type]`,
+      )
+    })
+  })
+
+  describe('builder "addMatcher" method', () => {
+    const prepareNumberAction = (payload: number) => ({
+      payload,
+      meta: { type: 'number_action' },
+    })
+    const prepareStringAction = (payload: string) => ({
+      payload,
+      meta: { type: 'string_action' },
+    })
+
+    const numberActionMatcher = (
+      a: UnknownAction,
+    ): a is PayloadAction<number> =>
+      isPlainObject(a.meta) &&
+      'type' in a.meta &&
+      (a.meta as Record<'type', unknown>).type === 'number_action'
+
+    const stringActionMatcher = (
+      a: UnknownAction,
+    ): a is PayloadAction<string> =>
+      isPlainObject(a.meta) &&
+      'type' in a.meta &&
+      (a.meta as Record<'type', unknown>).type === 'string_action'
+
+    const incrementBy = createAction('increment', prepareNumberAction)
+    const decrementBy = createAction('decrement', prepareNumberAction)
+    const concatWith = createAction('concat', prepareStringAction)
+
+    const initialState = { numberActions: 0, stringActions: 0 }
+
+    test('uses the reducer of matching actionMatchers', () => {
+      const reducer = createReducer(initialState, (builder) =>
+        builder
+          .addMatcher(numberActionMatcher, (state) => {
+            state.numberActions += 1
+          })
+          .addMatcher(stringActionMatcher, (state) => {
+            state.stringActions += 1
+          }),
+      )
+      expect(reducer(undefined, incrementBy(1))).toEqual({
+        numberActions: 1,
+        stringActions: 0,
+      })
+      expect(reducer(undefined, decrementBy(1))).toEqual({
+        numberActions: 1,
+        stringActions: 0,
+      })
+      expect(reducer(undefined, concatWith('foo'))).toEqual({
+        numberActions: 0,
+        stringActions: 1,
+      })
+    })
+    test('falls back to defaultCase', () => {
+      const reducer = createReducer(initialState, (builder) =>
+        builder
+          .addCase(concatWith, (state) => {
+            state.stringActions += 1
+          })
+          .addMatcher(numberActionMatcher, (state) => {
+            state.numberActions += 1
+          })
+          .addDefaultCase((state) => {
+            state.numberActions = -1
+            state.stringActions = -1
+          }),
+      )
+      expect(reducer(undefined, { type: 'somethingElse' })).toEqual({
+        numberActions: -1,
+        stringActions: -1,
+      })
+    })
+    test('runs reducer cases followed by all matching actionMatchers', () => {
+      const reducer = createReducer(initialState, (builder) =>
+        builder
+          .addCase(incrementBy, (state) => {
+            state.numberActions = state.numberActions * 10 + 1
+          })
+          .addMatcher(numberActionMatcher, (state) => {
+            state.numberActions = state.numberActions * 10 + 2
+          })
+          .addMatcher(stringActionMatcher, (state) => {
+            state.stringActions = state.stringActions * 10 + 1
+          })
+          .addMatcher(numberActionMatcher, (state) => {
+            state.numberActions = state.numberActions * 10 + 3
+          }),
+      )
+      expect(reducer(undefined, incrementBy(1))).toEqual({
+        numberActions: 123,
+        stringActions: 0,
+      })
+      expect(reducer(undefined, decrementBy(1))).toEqual({
+        numberActions: 23,
+        stringActions: 0,
+      })
+      expect(reducer(undefined, concatWith('foo'))).toEqual({
+        numberActions: 0,
+        stringActions: 1,
+      })
+    })
+    test('works with `actionCreator.match`', () => {
+      const reducer = createReducer(initialState, (builder) =>
+        builder.addMatcher(incrementBy.match, (state) => {
+          state.numberActions += 100
+        }),
+      )
+      expect(reducer(undefined, incrementBy(1))).toEqual({
+        numberActions: 100,
+        stringActions: 0,
+      })
+    })
+    test('calling addCase, addMatcher and addDefaultCase in a nonsensical order should result in an error in development mode', () => {
+      expect(() =>
+        createReducer(initialState, (builder: any) =>
+          builder
+            .addMatcher(numberActionMatcher, () => {})
+            .addCase(incrementBy, () => {}),
+        ),
+      ).toThrowErrorMatchingInlineSnapshot(
+        `[Error: \`builder.addCase\` should only be called before calling \`builder.addMatcher\`]`,
+      )
+      expect(() =>
+        createReducer(initialState, (builder: any) =>
+          builder.addDefaultCase(() => {}).addCase(incrementBy, () => {}),
+        ),
+      ).toThrowErrorMatchingInlineSnapshot(
+        `[Error: \`builder.addCase\` should only be called before calling \`builder.addDefaultCase\`]`,
+      )
+      expect(() =>
+        createReducer(initialState, (builder: any) =>
+          builder
+            .addDefaultCase(() => {})
+            .addMatcher(numberActionMatcher, () => {}),
+        ),
+      ).toThrowErrorMatchingInlineSnapshot(
+        `[Error: \`builder.addMatcher\` should only be called before calling \`builder.addDefaultCase\`]`,
+      )
+      expect(() =>
+        createReducer(initialState, (builder: any) =>
+          builder.addDefaultCase(() => {}).addDefaultCase(() => {}),
+        ),
+      ).toThrowErrorMatchingInlineSnapshot(
+        `[Error: \`builder.addDefaultCase\` can only be called once]`,
+      )
+    })
+  })
+  describe('builder "addAsyncThunk" method', () => {
+    const initialState = { todos: [] as Todo[], loading: false, errored: false }
+    test('uses the matching reducer for each action type', () => {
+      const reducer = createReducer(initialState, (builder) =>
+        builder.addAsyncThunk(addTodoThunk, {
+          pending(state) {
+            state.loading = true
+          },
+          fulfilled(state, action) {
+            state.todos.push(action.payload)
+          },
+          rejected(state) {
+            state.errored = true
+          },
+          settled(state) {
+            state.loading = false
+          },
+        }),
+      )
+      const todo: Todo = { text: 'test' }
+      expect(reducer(undefined, addTodoThunk.pending('test', todo))).toEqual({
+        todos: [],
+        loading: true,
+        errored: false,
+      })
+      expect(
+        reducer(undefined, addTodoThunk.fulfilled(todo, 'test', todo)),
+      ).toEqual({
+        todos: [todo],
+        loading: false,
+        errored: false,
+      })
+      expect(
+        reducer(undefined, addTodoThunk.rejected(new Error(), 'test', todo)),
+      ).toEqual({
+        todos: [],
+        loading: false,
+        errored: true,
+      })
+    })
+    test('calling addAsyncThunk after addDefaultCase should result in an error in development mode', () => {
+      expect(() =>
+        createReducer(initialState, (builder: any) =>
+          builder.addDefaultCase(() => {}).addAsyncThunk(addTodoThunk, {}),
+        ),
+      ).toThrowErrorMatchingInlineSnapshot(
+        `[Error: \`builder.addAsyncThunk\` should only be called before calling \`builder.addDefaultCase\`]`,
+      )
+    })
+  })
+})
+
+function behavesLikeReducer(todosReducer: TodosReducer) {
+  it('should handle initial state', () => {
+    const initialAction = { type: '', payload: undefined }
+    expect(todosReducer(undefined, initialAction)).toEqual([])
+  })
+
+  it('should handle ADD_TODO', () => {
+    expect(
+      todosReducer([], {
+        type: 'ADD_TODO',
+        payload: { newTodo: { text: 'Run the tests' } },
+      }),
+    ).toEqual([
+      {
+        text: 'Run the tests',
+        completed: false,
+      },
+    ])
+
+    expect(
+      todosReducer(
+        [
+          {
+            text: 'Run the tests',
+            completed: false,
+          },
+        ],
+        {
+          type: 'ADD_TODO',
+          payload: { newTodo: { text: 'Use Redux' } },
+        },
+      ),
+    ).toEqual([
+      {
+        text: 'Run the tests',
+        completed: false,
+      },
+      {
+        text: 'Use Redux',
+        completed: false,
+      },
+    ])
+
+    expect(
+      todosReducer(
+        [
+          {
+            text: 'Run the tests',
+            completed: false,
+          },
+          {
+            text: 'Use Redux',
+            completed: false,
+          },
+        ],
+        {
+          type: 'ADD_TODO',
+          payload: { newTodo: { text: 'Fix the tests' } },
+        },
+      ),
+    ).toEqual([
+      {
+        text: 'Run the tests',
+        completed: false,
+      },
+      {
+        text: 'Use Redux',
+        completed: false,
+      },
+      {
+        text: 'Fix the tests',
+        completed: false,
+      },
+    ])
+  })
+
+  it('should handle TOGGLE_TODO', () => {
+    expect(
+      todosReducer(
+        [
+          {
+            text: 'Run the tests',
+            completed: false,
+          },
+          {
+            text: 'Use Redux',
+            completed: false,
+          },
+        ],
+        {
+          type: 'TOGGLE_TODO',
+          payload: { index: 0 },
+        },
+      ),
+    ).toEqual([
+      {
+        text: 'Run the tests',
+        completed: true,
+      },
+      {
+        text: 'Use Redux',
+        completed: false,
+      },
+    ])
+  })
+}
Index: node_modules/@reduxjs/toolkit/src/tests/createSlice.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/createSlice.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/createSlice.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,995 @@
+import type {
+  Action,
+  ActionCreatorWithNonInferrablePayload,
+  ActionCreatorWithOptionalPayload,
+  ActionCreatorWithPayload,
+  ActionCreatorWithPreparedPayload,
+  ActionCreatorWithoutPayload,
+  ActionReducerMapBuilder,
+  AsyncThunk,
+  CaseReducer,
+  PayloadAction,
+  PayloadActionCreator,
+  Reducer,
+  ReducerCreators,
+  SerializedError,
+  SliceCaseReducers,
+  ThunkDispatch,
+  UnknownAction,
+  ValidateSliceCaseReducers,
+} from '@reduxjs/toolkit'
+import {
+  asyncThunkCreator,
+  buildCreateSlice,
+  configureStore,
+  createAction,
+  createAsyncThunk,
+  createSlice,
+  isRejected,
+} from '@reduxjs/toolkit'
+import { castDraft } from 'immer'
+
+describe('type tests', () => {
+  const counterSlice = createSlice({
+    name: 'counter',
+    initialState: 0,
+    reducers: {
+      increment: (state: number, action) => state + action.payload,
+      decrement: (state: number, action) => state - action.payload,
+    },
+  })
+
+  test('Slice name is strongly typed.', () => {
+    const uiSlice = createSlice({
+      name: 'ui',
+      initialState: 0,
+      reducers: {
+        goToNext: (state: number, action) => state + action.payload,
+        goToPrevious: (state: number, action) => state - action.payload,
+      },
+    })
+
+    const actionCreators = {
+      [counterSlice.name]: { ...counterSlice.actions },
+      [uiSlice.name]: { ...uiSlice.actions },
+    }
+
+    expectTypeOf(counterSlice.actions).toEqualTypeOf(actionCreators.counter)
+
+    expectTypeOf(uiSlice.actions).toEqualTypeOf(actionCreators.ui)
+
+    expectTypeOf(actionCreators).not.toHaveProperty('anyKey')
+  })
+
+  test("createSlice() infers the returned slice's type.", () => {
+    const firstAction = createAction<{ count: number }>('FIRST_ACTION')
+
+    const slice = createSlice({
+      name: 'counter',
+      initialState: 0,
+      reducers: {
+        increment: (state: number, action) => state + action.payload,
+        decrement: (state: number, action) => state - action.payload,
+      },
+      extraReducers: (builder) => {
+        builder.addCase(
+          firstAction,
+          (state, action) => state + action.payload.count,
+        )
+      },
+    })
+
+    test('Reducer', () => {
+      expectTypeOf(slice.reducer).toMatchTypeOf<
+        Reducer<number, PayloadAction>
+      >()
+
+      expectTypeOf(slice.reducer).not.toMatchTypeOf<
+        Reducer<string, PayloadAction>
+      >()
+    })
+
+    test('Actions', () => {
+      slice.actions.increment(1)
+      slice.actions.decrement(1)
+
+      expectTypeOf(slice.actions).not.toHaveProperty('other')
+    })
+  })
+
+  test('Slice action creator types are inferred.', () => {
+    const counter = createSlice({
+      name: 'counter',
+      initialState: 0,
+      reducers: {
+        increment: (state) => state + 1,
+        decrement: (
+          state,
+          { payload = 1 }: PayloadAction<number | undefined>,
+        ) => state - payload,
+        multiply: (state, { payload }: PayloadAction<number | number[]>) =>
+          Array.isArray(payload)
+            ? payload.reduce((acc, val) => acc * val, state)
+            : state * payload,
+        addTwo: {
+          reducer: (s, { payload }: PayloadAction<number>) => s + payload,
+          prepare: (a: number, b: number) => ({
+            payload: a + b,
+          }),
+        },
+      },
+    })
+
+    expectTypeOf(
+      counter.actions.increment,
+    ).toMatchTypeOf<ActionCreatorWithoutPayload>()
+
+    counter.actions.increment()
+
+    expectTypeOf(counter.actions.decrement).toMatchTypeOf<
+      ActionCreatorWithOptionalPayload<number | undefined>
+    >()
+
+    counter.actions.decrement()
+    counter.actions.decrement(2)
+
+    expectTypeOf(counter.actions.multiply).toMatchTypeOf<
+      ActionCreatorWithPayload<number | number[]>
+    >()
+
+    counter.actions.multiply(2)
+    counter.actions.multiply([2, 3, 4])
+
+    expectTypeOf(counter.actions.addTwo).toMatchTypeOf<
+      ActionCreatorWithPreparedPayload<[number, number], number>
+    >()
+
+    counter.actions.addTwo(1, 2)
+
+    expectTypeOf(counter.actions.multiply).parameters.not.toMatchTypeOf<[]>()
+
+    expectTypeOf(counter.actions.multiply).parameter(0).not.toBeString()
+
+    expectTypeOf(counter.actions.addTwo).parameters.not.toMatchTypeOf<
+      [number]
+    >()
+
+    expectTypeOf(counter.actions.addTwo).parameters.toEqualTypeOf<
+      [number, number]
+    >()
+  })
+
+  test('Slice action creator types properties are strongly typed', () => {
+    const counter = createSlice({
+      name: 'counter',
+      initialState: 0,
+      reducers: {
+        increment: (state) => state + 1,
+        decrement: (state) => state - 1,
+        multiply: (state, { payload }: PayloadAction<number | number[]>) =>
+          Array.isArray(payload)
+            ? payload.reduce((acc, val) => acc * val, state)
+            : state * payload,
+      },
+    })
+
+    expectTypeOf(
+      counter.actions.increment.type,
+    ).toEqualTypeOf<'counter/increment'>()
+
+    expectTypeOf(
+      counter.actions.increment().type,
+    ).toEqualTypeOf<'counter/increment'>()
+
+    expectTypeOf(
+      counter.actions.decrement.type,
+    ).toEqualTypeOf<'counter/decrement'>()
+
+    expectTypeOf(
+      counter.actions.decrement().type,
+    ).toEqualTypeOf<'counter/decrement'>()
+
+    expectTypeOf(
+      counter.actions.multiply.type,
+    ).toEqualTypeOf<'counter/multiply'>()
+
+    expectTypeOf(
+      counter.actions.multiply(1).type,
+    ).toEqualTypeOf<'counter/multiply'>()
+
+    expectTypeOf(
+      counter.actions.increment.type,
+    ).not.toMatchTypeOf<'increment'>()
+  })
+
+  test('Slice action creator types are inferred for enhanced reducers.', () => {
+    const counter = createSlice({
+      name: 'test',
+      initialState: { counter: 0, concat: '' },
+      reducers: {
+        incrementByStrLen: {
+          reducer: (state, action: PayloadAction<number>) => {
+            state.counter += action.payload
+          },
+          prepare: (payload: string) => ({
+            payload: payload.length,
+          }),
+        },
+        concatMetaStrLen: {
+          reducer: (state, action: PayloadAction<string>) => {
+            state.concat += action.payload
+          },
+          prepare: (payload: string) => ({
+            payload,
+            meta: payload.length,
+          }),
+        },
+      },
+    })
+
+    expectTypeOf(
+      counter.actions.incrementByStrLen('test').type,
+    ).toEqualTypeOf<'test/incrementByStrLen'>()
+
+    expectTypeOf(counter.actions.incrementByStrLen('test').payload).toBeNumber()
+
+    expectTypeOf(counter.actions.concatMetaStrLen('test').payload).toBeString()
+
+    expectTypeOf(counter.actions.concatMetaStrLen('test').meta).toBeNumber()
+
+    expectTypeOf(
+      counter.actions.incrementByStrLen('test').payload,
+    ).not.toBeString()
+
+    expectTypeOf(counter.actions.concatMetaStrLen('test').meta).not.toBeString()
+  })
+
+  test('access meta and error from reducer', () => {
+    const counter = createSlice({
+      name: 'test',
+      initialState: { counter: 0, concat: '' },
+      reducers: {
+        // case: meta and error not used in reducer
+        testDefaultMetaAndError: {
+          reducer(_, action: PayloadAction<number, string>) {},
+          prepare: (payload: number) => ({
+            payload,
+            meta: 'meta' as 'meta',
+            error: 'error' as 'error',
+          }),
+        },
+        // case: meta and error marked as "unknown" in reducer
+        testUnknownMetaAndError: {
+          reducer(
+            _,
+            action: PayloadAction<number, string, unknown, unknown>,
+          ) {},
+          prepare: (payload: number) => ({
+            payload,
+            meta: 'meta' as 'meta',
+            error: 'error' as 'error',
+          }),
+        },
+        // case: meta and error are typed in the reducer as returned by prepare
+        testMetaAndError: {
+          reducer(_, action: PayloadAction<number, string, 'meta', 'error'>) {},
+          prepare: (payload: number) => ({
+            payload,
+            meta: 'meta' as 'meta',
+            error: 'error' as 'error',
+          }),
+        },
+        // case: meta is typed differently in the reducer than returned from prepare
+        testErroneousMeta: {
+          reducer(_, action: PayloadAction<number, string, 'meta', 'error'>) {},
+          // @ts-expect-error
+          prepare: (payload: number) => ({
+            payload,
+            meta: 1,
+            error: 'error' as 'error',
+          }),
+        },
+        // case: error is typed differently in the reducer than returned from prepare
+        testErroneousError: {
+          reducer(_, action: PayloadAction<number, string, 'meta', 'error'>) {},
+          // @ts-expect-error
+          prepare: (payload: number) => ({
+            payload,
+            meta: 'meta' as 'meta',
+            error: 1,
+          }),
+        },
+      },
+    })
+  })
+
+  test('returned case reducer has the correct type', () => {
+    const counter = createSlice({
+      name: 'counter',
+      initialState: 0,
+      reducers: {
+        increment(state, action: PayloadAction<number>) {
+          return state + action.payload
+        },
+        decrement: {
+          reducer(state, action: PayloadAction<number>) {
+            return state - action.payload
+          },
+          prepare(amount: number) {
+            return { payload: amount }
+          },
+        },
+      },
+    })
+
+    test('Should match positively', () => {
+      expectTypeOf(counter.caseReducers.increment).toMatchTypeOf<
+        (state: number, action: PayloadAction<number>) => number | void
+      >()
+    })
+
+    test('Should match positively for reducers with prepare callback', () => {
+      expectTypeOf(counter.caseReducers.decrement).toMatchTypeOf<
+        (state: number, action: PayloadAction<number>) => number | void
+      >()
+    })
+
+    test("Should not mismatch the payload if it's a simple reducer", () => {
+      expectTypeOf(counter.caseReducers.increment).not.toMatchTypeOf<
+        (state: number, action: PayloadAction<string>) => number | void
+      >()
+    })
+
+    test("Should not mismatch the payload if it's a reducer with a prepare callback", () => {
+      expectTypeOf(counter.caseReducers.decrement).not.toMatchTypeOf<
+        (state: number, action: PayloadAction<string>) => number | void
+      >()
+    })
+
+    test("Should not include entries that don't exist", () => {
+      expectTypeOf(counter.caseReducers).not.toHaveProperty(
+        'someThingNonExistent',
+      )
+    })
+  })
+
+  test('prepared payload does not match action payload - should cause an error.', () => {
+    const counter = createSlice({
+      name: 'counter',
+      initialState: { counter: 0 },
+      reducers: {
+        increment: {
+          reducer(state, action: PayloadAction<string>) {
+            state.counter += action.payload.length
+          },
+          // @ts-expect-error
+          prepare(x: string) {
+            return {
+              payload: 6,
+            }
+          },
+        },
+      },
+    })
+  })
+
+  test('if no Payload Type is specified, accept any payload', () => {
+    // see https://github.com/reduxjs/redux-toolkit/issues/165
+
+    const initialState = {
+      name: null,
+    }
+
+    const mySlice = createSlice({
+      name: 'name',
+      initialState,
+      reducers: {
+        setName: (state, action) => {
+          state.name = action.payload
+        },
+      },
+    })
+
+    expectTypeOf(
+      mySlice.actions.setName,
+    ).toMatchTypeOf<ActionCreatorWithNonInferrablePayload>()
+
+    const x = mySlice.actions.setName
+
+    mySlice.actions.setName(null)
+    mySlice.actions.setName('asd')
+    mySlice.actions.setName(5)
+  })
+
+  test('actions.x.match()', () => {
+    const mySlice = createSlice({
+      name: 'name',
+      initialState: { name: 'test' },
+      reducers: {
+        setName: (state, action: PayloadAction<string>) => {
+          state.name = action.payload
+        },
+      },
+    })
+
+    const x: Action<string> = {} as any
+    if (mySlice.actions.setName.match(x)) {
+      expectTypeOf(x.type).toEqualTypeOf<'name/setName'>()
+
+      expectTypeOf(x.payload).toBeString()
+    } else {
+      expectTypeOf(x.type).not.toMatchTypeOf<'name/setName'>()
+
+      expectTypeOf(x).not.toHaveProperty('payload')
+    }
+  })
+
+  test('builder callback for extraReducers', () => {
+    createSlice({
+      name: 'test',
+      initialState: 0,
+      reducers: {},
+      extraReducers: (builder) => {
+        expectTypeOf(builder).toEqualTypeOf<ActionReducerMapBuilder<number>>()
+      },
+    })
+  })
+
+  test('wrapping createSlice should be possible', () => {
+    interface GenericState<T> {
+      data?: T
+      status: 'loading' | 'finished' | 'error'
+    }
+
+    const createGenericSlice = <
+      T,
+      Reducers extends SliceCaseReducers<GenericState<T>>,
+    >({
+      name = '',
+      initialState,
+      reducers,
+    }: {
+      name: string
+      initialState: GenericState<T>
+      reducers: ValidateSliceCaseReducers<GenericState<T>, Reducers>
+    }) => {
+      return createSlice({
+        name,
+        initialState,
+        reducers: {
+          start(state) {
+            state.status = 'loading'
+          },
+          success(state: GenericState<T>, action: PayloadAction<T>) {
+            state.data = action.payload
+            state.status = 'finished'
+          },
+          ...reducers,
+        },
+      })
+    }
+
+    const wrappedSlice = createGenericSlice({
+      name: 'test',
+      initialState: { status: 'loading' } as GenericState<string>,
+      reducers: {
+        magic(state) {
+          expectTypeOf(state).toEqualTypeOf<GenericState<string>>()
+
+          expectTypeOf(state).not.toMatchTypeOf<GenericState<number>>()
+
+          state.status = 'finished'
+          state.data = 'hocus pocus'
+        },
+      },
+    })
+
+    expectTypeOf(wrappedSlice.actions.success).toMatchTypeOf<
+      ActionCreatorWithPayload<string>
+    >()
+
+    expectTypeOf(wrappedSlice.actions.magic).toMatchTypeOf<
+      ActionCreatorWithoutPayload<string>
+    >()
+  })
+
+  test('extraReducers', () => {
+    interface GenericState<T> {
+      data: T | null
+    }
+
+    function createDataSlice<
+      T,
+      Reducers extends SliceCaseReducers<GenericState<T>>,
+    >(
+      name: string,
+      reducers: ValidateSliceCaseReducers<GenericState<T>, Reducers>,
+      initialState: GenericState<T>,
+    ) {
+      const doNothing = createAction<undefined>('doNothing')
+      const setData = createAction<T>('setData')
+
+      const slice = createSlice({
+        name,
+        initialState,
+        reducers,
+        extraReducers: (builder) => {
+          builder.addCase(doNothing, (state) => {
+            return { ...state }
+          })
+          builder.addCase(setData, (state, { payload }) => {
+            return {
+              ...state,
+              data: payload,
+            }
+          })
+        },
+      })
+      return { doNothing, setData, slice }
+    }
+  })
+
+  test('slice selectors', () => {
+    const sliceWithoutSelectors = createSlice({
+      name: '',
+      initialState: '',
+      reducers: {},
+    })
+
+    expectTypeOf(sliceWithoutSelectors.selectors).not.toHaveProperty('foo')
+
+    const sliceWithSelectors = createSlice({
+      name: 'counter',
+      initialState: { value: 0 },
+      reducers: {
+        increment: (state) => {
+          state.value += 1
+        },
+      },
+      selectors: {
+        selectValue: (state) => state.value,
+        selectMultiply: (state, multiplier: number) => state.value * multiplier,
+        selectToFixed: Object.assign(
+          (state: { value: number }) => state.value.toFixed(2),
+          { static: true },
+        ),
+      },
+    })
+
+    const rootState = {
+      [sliceWithSelectors.reducerPath]: sliceWithSelectors.getInitialState(),
+    }
+
+    const { selectValue, selectMultiply, selectToFixed } =
+      sliceWithSelectors.selectors
+
+    expectTypeOf(selectValue(rootState)).toBeNumber()
+
+    expectTypeOf(selectMultiply(rootState, 2)).toBeNumber()
+
+    expectTypeOf(selectToFixed(rootState)).toBeString()
+
+    expectTypeOf(selectToFixed.unwrapped.static).toBeBoolean()
+
+    const nestedState = {
+      nested: rootState,
+    }
+
+    const nestedSelectors = sliceWithSelectors.getSelectors(
+      (rootState: typeof nestedState) => rootState.nested.counter,
+    )
+
+    expectTypeOf(nestedSelectors.selectValue(nestedState)).toBeNumber()
+
+    expectTypeOf(nestedSelectors.selectMultiply(nestedState, 2)).toBeNumber()
+
+    expectTypeOf(nestedSelectors.selectToFixed(nestedState)).toBeString()
+  })
+
+  test('reducer callback', () => {
+    interface TestState {
+      foo: string
+    }
+
+    interface TestArg {
+      test: string
+    }
+
+    interface TestReturned {
+      payload: string
+    }
+
+    interface TestReject {
+      cause: string
+    }
+
+    const slice = createSlice({
+      name: 'test',
+      initialState: {} as TestState,
+      reducers: (create) => {
+        const preTypedAsyncThunk = create.asyncThunk.withTypes<{
+          rejectValue: TestReject
+        }>()
+
+        // @ts-expect-error
+        create.asyncThunk<any, any, { state: StoreState }>(() => {})
+
+        // @ts-expect-error
+        create.asyncThunk.withTypes<{
+          rejectValue: string
+          dispatch: StoreDispatch
+        }>()
+
+        return {
+          normalReducer: create.reducer<string>((state, action) => {
+            expectTypeOf(state).toEqualTypeOf<TestState>()
+
+            expectTypeOf(action.payload).toBeString()
+          }),
+          optionalReducer: create.reducer<string | undefined>(
+            (state, action) => {
+              expectTypeOf(state).toEqualTypeOf<TestState>()
+
+              expectTypeOf(action.payload).toEqualTypeOf<string | undefined>()
+            },
+          ),
+          noActionReducer: create.reducer((state) => {
+            expectTypeOf(state).toEqualTypeOf<TestState>()
+          }),
+          preparedReducer: create.preparedReducer(
+            (payload: string) => ({
+              payload,
+              meta: 'meta' as const,
+              error: 'error' as const,
+            }),
+            (state, action) => {
+              expectTypeOf(state).toEqualTypeOf<TestState>()
+
+              expectTypeOf(action.payload).toBeString()
+
+              expectTypeOf(action.meta).toEqualTypeOf<'meta'>()
+
+              expectTypeOf(action.error).toEqualTypeOf<'error'>()
+            },
+          ),
+          testInferVoid: create.asyncThunk(() => {}, {
+            pending(state, action) {
+              expectTypeOf(state).toEqualTypeOf<TestState>()
+
+              expectTypeOf(action.meta.arg).toBeVoid()
+            },
+            fulfilled(state, action) {
+              expectTypeOf(state).toEqualTypeOf<TestState>()
+
+              expectTypeOf(action.meta.arg).toBeVoid()
+
+              expectTypeOf(action.payload).toBeVoid()
+            },
+            rejected(state, action) {
+              expectTypeOf(state).toEqualTypeOf<TestState>()
+
+              expectTypeOf(action.meta.arg).toBeVoid()
+
+              expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+            },
+            settled(state, action) {
+              expectTypeOf(state).toEqualTypeOf<TestState>()
+
+              expectTypeOf(action.meta.arg).toBeVoid()
+
+              if (isRejected(action)) {
+                expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+              } else {
+                expectTypeOf(action.payload).toBeVoid()
+              }
+            },
+          }),
+          testInfer: create.asyncThunk(
+            function payloadCreator(arg: TestArg, api) {
+              return Promise.resolve<TestReturned>({ payload: 'foo' })
+            },
+            {
+              pending(state, action) {
+                expectTypeOf(state).toEqualTypeOf<TestState>()
+
+                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()
+              },
+              fulfilled(state, action) {
+                expectTypeOf(state).toEqualTypeOf<TestState>()
+
+                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()
+
+                expectTypeOf(action.payload).toEqualTypeOf<TestReturned>()
+              },
+              rejected(state, action) {
+                expectTypeOf(state).toEqualTypeOf<TestState>()
+
+                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()
+
+                expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+              },
+              settled(state, action) {
+                expectTypeOf(state).toEqualTypeOf<TestState>()
+
+                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()
+
+                if (isRejected(action)) {
+                  expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+                } else {
+                  expectTypeOf(action.payload).toEqualTypeOf<TestReturned>()
+                }
+              },
+            },
+          ),
+          testExplicitType: create.asyncThunk<
+            TestReturned,
+            TestArg,
+            {
+              rejectValue: TestReject
+            }
+          >(
+            function payloadCreator(arg, api) {
+              // here would be a circular reference
+              expectTypeOf(api.getState()).toBeUnknown()
+              // here would be a circular reference
+              expectTypeOf(api.dispatch).toMatchTypeOf<
+                ThunkDispatch<any, any, any>
+              >()
+
+              // so you need to cast inside instead
+              const getState = api.getState as () => StoreState
+              const dispatch = api.dispatch as StoreDispatch
+
+              expectTypeOf(arg).toEqualTypeOf<TestArg>()
+
+              expectTypeOf(api.rejectWithValue).toMatchTypeOf<
+                (value: TestReject) => any
+              >()
+
+              return Promise.resolve({ payload: 'foo' })
+            },
+            {
+              pending(state, action) {
+                expectTypeOf(state).toEqualTypeOf<TestState>()
+
+                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()
+              },
+              fulfilled(state, action) {
+                expectTypeOf(state).toEqualTypeOf<TestState>()
+
+                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()
+
+                expectTypeOf(action.payload).toEqualTypeOf<TestReturned>()
+              },
+              rejected(state, action) {
+                expectTypeOf(state).toEqualTypeOf<TestState>()
+
+                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()
+
+                expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+
+                expectTypeOf(action.payload).toEqualTypeOf<
+                  TestReject | undefined
+                >()
+              },
+              settled(state, action) {
+                expectTypeOf(state).toEqualTypeOf<TestState>()
+
+                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()
+
+                if (isRejected(action)) {
+                  expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+
+                  expectTypeOf(action.payload).toEqualTypeOf<
+                    TestReject | undefined
+                  >()
+                } else {
+                  expectTypeOf(action.payload).toEqualTypeOf<TestReturned>()
+                }
+              },
+            },
+          ),
+          testPreTyped: preTypedAsyncThunk(
+            function payloadCreator(arg: TestArg, api) {
+              expectTypeOf(api.rejectWithValue).toMatchTypeOf<
+                (value: TestReject) => any
+              >()
+
+              return Promise.resolve<TestReturned>({ payload: 'foo' })
+            },
+            {
+              pending(state, action) {
+                expectTypeOf(state).toEqualTypeOf<TestState>()
+
+                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()
+              },
+              fulfilled(state, action) {
+                expectTypeOf(state).toEqualTypeOf<TestState>()
+
+                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()
+
+                expectTypeOf(action.payload).toEqualTypeOf<TestReturned>()
+              },
+              rejected(state, action) {
+                expectTypeOf(state).toEqualTypeOf<TestState>()
+
+                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()
+
+                expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+
+                expectTypeOf(action.payload).toEqualTypeOf<
+                  TestReject | undefined
+                >()
+              },
+              settled(state, action) {
+                expectTypeOf(state).toEqualTypeOf<TestState>()
+
+                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()
+
+                if (isRejected(action)) {
+                  expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+
+                  expectTypeOf(action.payload).toEqualTypeOf<
+                    TestReject | undefined
+                  >()
+                } else {
+                  expectTypeOf(action.payload).toEqualTypeOf<TestReturned>()
+                }
+              },
+            },
+          ),
+        }
+      },
+    })
+
+    const store = configureStore({ reducer: { test: slice.reducer } })
+
+    type StoreState = ReturnType<typeof store.getState>
+
+    type StoreDispatch = typeof store.dispatch
+
+    expectTypeOf(slice.actions.normalReducer).toMatchTypeOf<
+      PayloadActionCreator<string>
+    >()
+
+    expectTypeOf(slice.actions.normalReducer).toBeCallableWith('')
+
+    expectTypeOf(slice.actions.normalReducer).parameters.not.toMatchTypeOf<[]>()
+
+    expectTypeOf(slice.actions.normalReducer).parameters.not.toMatchTypeOf<
+      [number]
+    >()
+
+    expectTypeOf(slice.actions.optionalReducer).toMatchTypeOf<
+      ActionCreatorWithOptionalPayload<string | undefined>
+    >()
+
+    expectTypeOf(slice.actions.optionalReducer).toBeCallableWith()
+
+    expectTypeOf(slice.actions.optionalReducer).toBeCallableWith('')
+
+    expectTypeOf(slice.actions.optionalReducer).parameter(0).not.toBeNumber()
+
+    expectTypeOf(
+      slice.actions.noActionReducer,
+    ).toMatchTypeOf<ActionCreatorWithoutPayload>()
+
+    expectTypeOf(slice.actions.noActionReducer).toBeCallableWith()
+
+    expectTypeOf(slice.actions.noActionReducer).parameter(0).not.toBeString()
+
+    expectTypeOf(slice.actions.preparedReducer).toEqualTypeOf<
+      ActionCreatorWithPreparedPayload<
+        [string],
+        string,
+        'test/preparedReducer',
+        'error',
+        'meta'
+      >
+    >()
+
+    expectTypeOf(slice.actions.testInferVoid).toEqualTypeOf<
+      AsyncThunk<void, void, {}>
+    >()
+
+    expectTypeOf(slice.actions.testInferVoid).toBeCallableWith()
+
+    expectTypeOf(slice.actions.testInfer).toEqualTypeOf<
+      AsyncThunk<TestReturned, TestArg, {}>
+    >()
+
+    expectTypeOf(slice.actions.testExplicitType).toEqualTypeOf<
+      AsyncThunk<TestReturned, TestArg, { rejectValue: TestReject }>
+    >()
+
+    type TestInferThunk = AsyncThunk<TestReturned, TestArg, {}>
+
+    expectTypeOf(slice.caseReducers.testInfer.pending).toEqualTypeOf<
+      CaseReducer<TestState, ReturnType<TestInferThunk['pending']>>
+    >()
+
+    expectTypeOf(slice.caseReducers.testInfer.fulfilled).toEqualTypeOf<
+      CaseReducer<TestState, ReturnType<TestInferThunk['fulfilled']>>
+    >()
+
+    expectTypeOf(slice.caseReducers.testInfer.rejected).toEqualTypeOf<
+      CaseReducer<TestState, ReturnType<TestInferThunk['rejected']>>
+    >()
+  })
+
+  test('wrapping createSlice should be possible, with callback', () => {
+    interface GenericState<T> {
+      data?: T
+      status: 'loading' | 'finished' | 'error'
+    }
+
+    const createGenericSlice = <
+      T,
+      Reducers extends SliceCaseReducers<GenericState<T>>,
+    >({
+      name = '',
+      initialState,
+      reducers,
+    }: {
+      name: string
+      initialState: GenericState<T>
+      reducers: (create: ReducerCreators<GenericState<T>>) => Reducers
+    }) => {
+      return createSlice({
+        name,
+        initialState,
+        reducers: (create) => ({
+          start: create.reducer((state) => {
+            state.status = 'loading'
+          }),
+          success: create.reducer<T>((state, action) => {
+            state.data = castDraft(action.payload)
+            state.status = 'finished'
+          }),
+          ...reducers(create),
+        }),
+      })
+    }
+
+    const wrappedSlice = createGenericSlice({
+      name: 'test',
+      initialState: { status: 'loading' } as GenericState<string>,
+      reducers: (create) => ({
+        magic: create.reducer((state) => {
+          expectTypeOf(state).toEqualTypeOf<GenericState<string>>()
+
+          expectTypeOf(state).not.toMatchTypeOf<GenericState<number>>()
+
+          state.status = 'finished'
+          state.data = 'hocus pocus'
+        }),
+      }),
+    })
+
+    expectTypeOf(wrappedSlice.actions.success).toMatchTypeOf<
+      ActionCreatorWithPayload<string>
+    >()
+
+    expectTypeOf(wrappedSlice.actions.magic).toMatchTypeOf<
+      ActionCreatorWithoutPayload<string>
+    >()
+  })
+
+  test('selectSlice', () => {
+    expectTypeOf(counterSlice.selectSlice({ counter: 0 })).toBeNumber()
+
+    // We use `not.toEqualTypeOf` instead of `not.toMatchTypeOf`
+    // because `toMatchTypeOf` allows missing properties
+    expectTypeOf(counterSlice.selectSlice).parameter(0).not.toEqualTypeOf<{}>()
+  })
+
+  test('buildCreateSlice', () => {
+    expectTypeOf(buildCreateSlice()).toEqualTypeOf(createSlice)
+
+    buildCreateSlice({
+      // @ts-expect-error not possible to recreate shape because symbol is not exported
+      creators: { asyncThunk: { [Symbol()]: createAsyncThunk } },
+    })
+    buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/createSlice.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/createSlice.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/createSlice.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,987 @@
+import { noop } from '@internal/listenerMiddleware/utils'
+import type { PayloadAction, WithSlice } from '@reduxjs/toolkit'
+import {
+  asyncThunkCreator,
+  buildCreateSlice,
+  combineSlices,
+  configureStore,
+  createAction,
+  createAsyncThunk,
+  createSlice,
+} from '@reduxjs/toolkit'
+
+type CreateSlice = typeof createSlice
+
+describe('createSlice', () => {
+  const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
+
+  beforeEach(() => {
+    vi.clearAllMocks()
+  })
+
+  afterAll(() => {
+    vi.restoreAllMocks()
+  })
+
+  describe('when slice is undefined', () => {
+    it('should throw an error', () => {
+      expect(() =>
+        // @ts-ignore
+        createSlice({
+          reducers: {
+            increment: (state) => state + 1,
+            multiply: (state, action: PayloadAction<number>) =>
+              state * action.payload,
+          },
+          initialState: 0,
+        }),
+      ).toThrowError()
+    })
+  })
+
+  describe('when slice is an empty string', () => {
+    it('should throw an error', () => {
+      expect(() =>
+        createSlice({
+          name: '',
+          reducers: {
+            increment: (state) => state + 1,
+            multiply: (state, action: PayloadAction<number>) =>
+              state * action.payload,
+          },
+          initialState: 0,
+        }),
+      ).toThrowError()
+    })
+  })
+
+  describe('when initial state is undefined', () => {
+    beforeEach(() => {
+      vi.stubEnv('NODE_ENV', 'development')
+    })
+
+    afterEach(() => {
+      vi.unstubAllEnvs()
+    })
+
+    it('should throw an error', () => {
+      createSlice({
+        name: 'test',
+        reducers: {},
+        initialState: undefined,
+      })
+
+      expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+      expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+        'You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`',
+      )
+    })
+  })
+
+  describe('when passing slice', () => {
+    const { actions, reducer, caseReducers } = createSlice({
+      reducers: {
+        increment: (state) => state + 1,
+      },
+      initialState: 0,
+      name: 'cool',
+    })
+
+    it('should create increment action', () => {
+      expect(actions.hasOwnProperty('increment')).toBe(true)
+    })
+
+    it('should have the correct action for increment', () => {
+      expect(actions.increment()).toEqual({
+        type: 'cool/increment',
+        payload: undefined,
+      })
+    })
+
+    it('should return the correct value from reducer', () => {
+      expect(reducer(undefined, actions.increment())).toEqual(1)
+    })
+
+    it('should include the generated case reducers', () => {
+      expect(caseReducers).toBeTruthy()
+      expect(caseReducers.increment).toBeTruthy()
+      expect(typeof caseReducers.increment).toBe('function')
+    })
+
+    it('getInitialState should return the state', () => {
+      const initialState = 42
+      const slice = createSlice({
+        name: 'counter',
+        initialState,
+        reducers: {},
+      })
+
+      expect(slice.getInitialState()).toBe(initialState)
+    })
+
+    it('should allow non-draftable initial state', () => {
+      expect(() =>
+        createSlice({
+          name: 'params',
+          initialState: new URLSearchParams(),
+          reducers: {},
+        }),
+      ).not.toThrowError()
+    })
+  })
+
+  describe('when initialState is a function', () => {
+    const initialState = () => ({ user: '' })
+
+    const { actions, reducer } = createSlice({
+      reducers: {
+        setUserName: (state, action) => {
+          state.user = action.payload
+        },
+      },
+      initialState,
+      name: 'user',
+    })
+
+    it('should set the username', () => {
+      expect(reducer(undefined, actions.setUserName('eric'))).toEqual({
+        user: 'eric',
+      })
+    })
+
+    it('getInitialState should return the state', () => {
+      const initialState = () => 42
+      const slice = createSlice({
+        name: 'counter',
+        initialState,
+        reducers: {},
+      })
+
+      expect(slice.getInitialState()).toBe(42)
+    })
+
+    it('should allow non-draftable initial state', () => {
+      expect(() =>
+        createSlice({
+          name: 'params',
+          initialState: () => new URLSearchParams(),
+          reducers: {},
+        }),
+      ).not.toThrowError()
+    })
+  })
+
+  describe('when mutating state object', () => {
+    const initialState = { user: '' }
+
+    const { actions, reducer } = createSlice({
+      reducers: {
+        setUserName: (state, action) => {
+          state.user = action.payload
+        },
+      },
+      initialState,
+      name: 'user',
+    })
+
+    it('should set the username', () => {
+      expect(reducer(initialState, actions.setUserName('eric'))).toEqual({
+        user: 'eric',
+      })
+    })
+  })
+
+  describe('when passing extra reducers', () => {
+    const addMore = createAction<{ amount: number }>('ADD_MORE')
+
+    const { reducer } = createSlice({
+      name: 'test',
+      reducers: {
+        increment: (state) => state + 1,
+        multiply: (state, action) => state * action.payload,
+      },
+      extraReducers: (builder) => {
+        builder.addCase(
+          addMore,
+          (state, action) => state + action.payload.amount,
+        )
+      },
+
+      initialState: 0,
+    })
+
+    it('should call extra reducers when their actions are dispatched', () => {
+      const result = reducer(10, addMore({ amount: 5 }))
+
+      expect(result).toBe(15)
+    })
+
+    describe('builder callback for extraReducers', () => {
+      const increment = createAction<number, 'increment'>('increment')
+
+      test('can be used with actionCreators', () => {
+        const slice = createSlice({
+          name: 'counter',
+          initialState: 0,
+          reducers: {},
+          extraReducers: (builder) =>
+            builder.addCase(
+              increment,
+              (state, action) => state + action.payload,
+            ),
+        })
+        expect(slice.reducer(0, increment(5))).toBe(5)
+      })
+
+      test('can be used with string action types', () => {
+        const slice = createSlice({
+          name: 'counter',
+          initialState: 0,
+          reducers: {},
+          extraReducers: (builder) =>
+            builder.addCase(
+              'increment',
+              (state, action: { type: 'increment'; payload: number }) =>
+                state + action.payload,
+            ),
+        })
+        expect(slice.reducer(0, increment(5))).toBe(5)
+      })
+
+      test('prevents the same action type from being specified twice', () => {
+        expect(() => {
+          const slice = createSlice({
+            name: 'counter',
+            initialState: 0,
+            reducers: {},
+            extraReducers: (builder) =>
+              builder
+                .addCase('increment', (state) => state + 1)
+                .addCase('increment', (state) => state + 1),
+          })
+          slice.reducer(undefined, { type: 'unrelated' })
+        }).toThrowErrorMatchingInlineSnapshot(
+          `[Error: \`builder.addCase\` cannot be called with two reducers for the same action type 'increment']`,
+        )
+      })
+
+      test('can be used with addAsyncThunk and async thunks', () => {
+        const asyncThunk = createAsyncThunk('test', (n: number) => n)
+        const slice = createSlice({
+          name: 'counter',
+          initialState: {
+            loading: false,
+            errored: false,
+            value: 0,
+          },
+          reducers: {},
+          extraReducers: (builder) =>
+            builder.addAsyncThunk(asyncThunk, {
+              pending(state) {
+                state.loading = true
+              },
+              fulfilled(state, action) {
+                state.value = action.payload
+              },
+              rejected(state) {
+                state.errored = true
+              },
+              settled(state) {
+                state.loading = false
+              },
+            }),
+        })
+        expect(
+          slice.reducer(undefined, asyncThunk.pending('requestId', 5)),
+        ).toEqual({
+          loading: true,
+          errored: false,
+          value: 0,
+        })
+        expect(
+          slice.reducer(undefined, asyncThunk.fulfilled(5, 'requestId', 5)),
+        ).toEqual({
+          loading: false,
+          errored: false,
+          value: 5,
+        })
+        expect(
+          slice.reducer(
+            undefined,
+            asyncThunk.rejected(new Error(), 'requestId', 5),
+          ),
+        ).toEqual({
+          loading: false,
+          errored: true,
+          value: 0,
+        })
+      })
+
+      test('can be used with addMatcher and type guard functions', () => {
+        const slice = createSlice({
+          name: 'counter',
+          initialState: 0,
+          reducers: {},
+          extraReducers: (builder) =>
+            builder.addMatcher(
+              increment.match,
+              (state, action: { type: 'increment'; payload: number }) =>
+                state + action.payload,
+            ),
+        })
+        expect(slice.reducer(0, increment(5))).toBe(5)
+      })
+
+      test('can be used with addDefaultCase', () => {
+        const slice = createSlice({
+          name: 'counter',
+          initialState: 0,
+          reducers: {},
+          extraReducers: (builder) =>
+            builder.addDefaultCase(
+              (state, action) =>
+                state + (action as PayloadAction<number>).payload,
+            ),
+        })
+        expect(slice.reducer(0, increment(5))).toBe(5)
+      })
+
+      // for further tests, see the test of createReducer that goes way more into depth on this
+    })
+  })
+
+  describe('behavior with enhanced case reducers', () => {
+    it('should pass all arguments to the prepare function', () => {
+      const prepare = vi.fn((payload, somethingElse) => ({ payload }))
+
+      const testSlice = createSlice({
+        name: 'test',
+        initialState: 0,
+        reducers: {
+          testReducer: {
+            reducer: (s) => s,
+            prepare,
+          },
+        },
+      })
+
+      expect(testSlice.actions.testReducer('a', 1)).toEqual({
+        type: 'test/testReducer',
+        payload: 'a',
+      })
+      expect(prepare).toHaveBeenCalledWith('a', 1)
+    })
+
+    it('should call the reducer function', () => {
+      const reducer = vi.fn(() => 5)
+
+      const testSlice = createSlice({
+        name: 'test',
+        initialState: 0,
+        reducers: {
+          testReducer: {
+            reducer,
+            prepare: (payload: any) => ({ payload }),
+          },
+        },
+      })
+
+      testSlice.reducer(0, testSlice.actions.testReducer('testPayload'))
+      expect(reducer).toHaveBeenCalledWith(
+        0,
+        expect.objectContaining({ payload: 'testPayload' }),
+      )
+    })
+  })
+
+  describe('circularity', () => {
+    test('extraReducers can reference each other circularly', () => {
+      const first = createSlice({
+        name: 'first',
+        initialState: 'firstInitial',
+        reducers: {
+          something() {
+            return 'firstSomething'
+          },
+        },
+        extraReducers(builder) {
+          // eslint-disable-next-line @typescript-eslint/no-use-before-define
+          builder.addCase(second.actions.other, () => {
+            return 'firstOther'
+          })
+        },
+      })
+      const second = createSlice({
+        name: 'second',
+        initialState: 'secondInitial',
+        reducers: {
+          other() {
+            return 'secondOther'
+          },
+        },
+        extraReducers(builder) {
+          builder.addCase(first.actions.something, () => {
+            return 'secondSomething'
+          })
+        },
+      })
+
+      expect(first.reducer(undefined, { type: 'unrelated' })).toBe(
+        'firstInitial',
+      )
+      expect(first.reducer(undefined, first.actions.something())).toBe(
+        'firstSomething',
+      )
+      expect(first.reducer(undefined, second.actions.other())).toBe(
+        'firstOther',
+      )
+
+      expect(second.reducer(undefined, { type: 'unrelated' })).toBe(
+        'secondInitial',
+      )
+      expect(second.reducer(undefined, first.actions.something())).toBe(
+        'secondSomething',
+      )
+      expect(second.reducer(undefined, second.actions.other())).toBe(
+        'secondOther',
+      )
+    })
+  })
+
+  describe('Deprecation warnings', () => {
+    beforeEach(() => {
+      vi.resetModules()
+    })
+
+    afterEach(() => {
+      vi.unstubAllEnvs()
+    })
+
+    // NOTE: This needs to be in front of the later `createReducer` call to check the one-time warning
+    it('Throws an error if the legacy object notation is used', async () => {
+      const { createSlice } = await import('../createSlice')
+
+      let dummySlice = (createSlice as CreateSlice)({
+        name: 'dummy',
+        initialState: [],
+        reducers: {},
+        extraReducers: {
+          // @ts-ignore
+          a: () => [],
+        },
+      })
+      let reducer: any
+      // Have to trigger the lazy creation
+      const wrapper = () => {
+        reducer = dummySlice.reducer
+        reducer(undefined, { type: 'dummy' })
+      }
+
+      expect(wrapper).toThrowError(
+        /The object notation for `createSlice.extraReducers` has been removed/,
+      )
+
+      dummySlice = (createSlice as CreateSlice)({
+        name: 'dummy',
+        initialState: [],
+        reducers: {},
+        extraReducers: {
+          // @ts-ignore
+          a: () => [],
+        },
+      })
+      expect(wrapper).toThrowError(
+        /The object notation for `createSlice.extraReducers` has been removed/,
+      )
+    })
+
+    // TODO Determine final production behavior here
+    it.todo('Crashes in production', () => {
+      vi.stubEnv('NODE_ENV', 'production')
+
+      const { createSlice } = require('../createSlice')
+
+      const dummySlice = (createSlice as CreateSlice)({
+        name: 'dummy',
+        initialState: [],
+        reducers: {},
+        // @ts-ignore
+        extraReducers: {},
+      })
+      const wrapper = () => {
+        const { reducer } = dummySlice
+        reducer(undefined, { type: 'dummy' })
+      }
+
+      expect(wrapper).toThrowError(
+        /The object notation for `createSlice.extraReducers` has been removed/,
+      )
+
+      vi.unstubAllEnvs()
+    })
+  })
+  describe('slice selectors', () => {
+    const slice = createSlice({
+      name: 'counter',
+      initialState: 42,
+      reducers: {},
+      selectors: {
+        selectSlice: (state) => state,
+        selectMultiple: Object.assign(
+          (state: number, multiplier: number) => state * multiplier,
+          { test: 0 },
+        ),
+      },
+    })
+    it('expects reducer under slice.reducerPath if no selectState callback passed', () => {
+      const testState = {
+        [slice.reducerPath]: slice.getInitialState(),
+      }
+      const { selectSlice, selectMultiple } = slice.selectors
+      expect(selectSlice(testState)).toBe(slice.getInitialState())
+      expect(selectMultiple(testState, 2)).toBe(slice.getInitialState() * 2)
+    })
+    it('allows passing a selector for a custom location', () => {
+      const customState = {
+        number: slice.getInitialState(),
+      }
+      const { selectSlice, selectMultiple } = slice.getSelectors(
+        (state: typeof customState) => state.number,
+      )
+      expect(selectSlice(customState)).toBe(slice.getInitialState())
+      expect(selectMultiple(customState, 2)).toBe(slice.getInitialState() * 2)
+    })
+    it('allows accessing properties on the selector', () => {
+      expect(slice.selectors.selectMultiple.unwrapped.test).toBe(0)
+    })
+    it('has selectSlice attached to slice, which can go without this', () => {
+      const slice = createSlice({
+        name: 'counter',
+        initialState: 42,
+        reducers: {},
+      })
+      const { selectSlice } = slice
+      expect(() => selectSlice({ counter: 42 })).not.toThrow()
+      expect(selectSlice({ counter: 42 })).toBe(42)
+    })
+  })
+  describe('slice injections', () => {
+    it('uses injectInto to inject slice into combined reducer', () => {
+      const slice = createSlice({
+        name: 'counter',
+        initialState: 42,
+        reducers: {
+          increment: (state) => ++state,
+        },
+        selectors: {
+          selectMultiple: (state, multiplier: number) => state * multiplier,
+        },
+      })
+
+      const { increment } = slice.actions
+
+      const combinedReducer = combineSlices({
+        static: slice.reducer,
+      }).withLazyLoadedSlices<WithSlice<typeof slice>>()
+
+      const uninjectedState = combinedReducer(undefined, increment())
+
+      expect(uninjectedState.counter).toBe(undefined)
+
+      const injectedSlice = slice.injectInto(combinedReducer)
+
+      // selector returns initial state if undefined in real state
+      expect(injectedSlice.selectSlice(uninjectedState)).toBe(
+        slice.getInitialState(),
+      )
+      expect(injectedSlice.selectors.selectMultiple({}, 1)).toBe(
+        slice.getInitialState(),
+      )
+      expect(injectedSlice.getSelectors().selectMultiple(undefined, 1)).toBe(
+        slice.getInitialState(),
+      )
+
+      const injectedState = combinedReducer(undefined, increment())
+
+      expect(injectedSlice.selectSlice(injectedState)).toBe(
+        slice.getInitialState() + 1,
+      )
+      expect(injectedSlice.selectors.selectMultiple(injectedState, 1)).toBe(
+        slice.getInitialState() + 1,
+      )
+    })
+    it('allows providing a custom name to inject under', () => {
+      const slice = createSlice({
+        name: 'counter',
+        reducerPath: 'injected',
+        initialState: 42,
+        reducers: {
+          increment: (state) => ++state,
+        },
+        selectors: {
+          selectMultiple: (state, multiplier: number) => state * multiplier,
+        },
+      })
+
+      const { increment } = slice.actions
+
+      const combinedReducer = combineSlices({
+        static: slice.reducer,
+      }).withLazyLoadedSlices<WithSlice<typeof slice> & { injected2: number }>()
+
+      const uninjectedState = combinedReducer(undefined, increment())
+
+      expect(uninjectedState.injected).toBe(undefined)
+
+      const injected = slice.injectInto(combinedReducer)
+
+      const injectedState = combinedReducer(undefined, increment())
+
+      expect(injected.selectSlice(injectedState)).toBe(
+        slice.getInitialState() + 1,
+      )
+      expect(injected.selectors.selectMultiple(injectedState, 2)).toBe(
+        (slice.getInitialState() + 1) * 2,
+      )
+
+      const injected2 = slice.injectInto(combinedReducer, {
+        reducerPath: 'injected2',
+      })
+
+      const injected2State = combinedReducer(undefined, increment())
+
+      expect(injected2.selectSlice(injected2State)).toBe(
+        slice.getInitialState() + 1,
+      )
+      expect(injected2.selectors.selectMultiple(injected2State, 2)).toBe(
+        (slice.getInitialState() + 1) * 2,
+      )
+    })
+    it('avoids incorrectly caching selectors', () => {
+      const slice = createSlice({
+        name: 'counter',
+        reducerPath: 'injected',
+        initialState: 42,
+        reducers: {
+          increment: (state) => ++state,
+        },
+        selectors: {
+          selectMultiple: (state, multiplier: number) => state * multiplier,
+        },
+      })
+      expect(slice.getSelectors()).toBe(slice.getSelectors())
+      const combinedReducer = combineSlices({
+        static: slice.reducer,
+      }).withLazyLoadedSlices<WithSlice<typeof slice>>()
+
+      const injected = slice.injectInto(combinedReducer)
+
+      expect(injected.getSelectors()).not.toBe(slice.getSelectors())
+
+      expect(injected.getSelectors().selectMultiple(undefined, 1)).toBe(42)
+
+      expect(() =>
+        // @ts-expect-error
+        slice.getSelectors().selectMultiple(undefined, 1),
+      ).toThrowErrorMatchingInlineSnapshot(
+        `[Error: selectState returned undefined for an uninjected slice reducer]`,
+      )
+
+      const injected2 = slice.injectInto(combinedReducer, {
+        reducerPath: 'other',
+      })
+
+      // can use same cache for localised selectors
+      expect(injected.getSelectors()).toBe(injected2.getSelectors())
+      // these should be different
+      expect(injected.selectors).not.toBe(injected2.selectors)
+    })
+    it('caches initial states for selectors', () => {
+      const slice = createSlice({
+        name: 'counter',
+        initialState: () => ({ value: 0 }),
+        reducers: {},
+        selectors: {
+          selectObj: (state) => state,
+        },
+      })
+      // not cached
+      expect(slice.getInitialState()).not.toBe(slice.getInitialState())
+      expect(slice.reducer(undefined, { type: 'dummy' })).not.toBe(
+        slice.reducer(undefined, { type: 'dummy' }),
+      )
+
+      const combinedReducer = combineSlices({
+        static: slice.reducer,
+      }).withLazyLoadedSlices<WithSlice<typeof slice>>()
+
+      const injected = slice.injectInto(combinedReducer)
+
+      // still not cached
+      expect(injected.getInitialState()).not.toBe(injected.getInitialState())
+      expect(injected.reducer(undefined, { type: 'dummy' })).not.toBe(
+        injected.reducer(undefined, { type: 'dummy' }),
+      )
+      // cached
+      expect(injected.selectSlice({})).toBe(injected.selectSlice({}))
+      expect(injected.selectors.selectObj({})).toBe(
+        injected.selectors.selectObj({}),
+      )
+    })
+  })
+  describe('reducers definition with asyncThunks', () => {
+    it('is disabled by default', () => {
+      expect(() =>
+        createSlice({
+          name: 'test',
+          initialState: [] as any[],
+          reducers: (create) => ({ thunk: create.asyncThunk(() => {}) }),
+        }),
+      ).toThrowErrorMatchingInlineSnapshot(
+        `[Error: Cannot use \`create.asyncThunk\` in the built-in \`createSlice\`. Use \`buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })\` to create a customised version of \`createSlice\`.]`,
+      )
+    })
+    const createAppSlice = buildCreateSlice({
+      creators: { asyncThunk: asyncThunkCreator },
+    })
+    function pending(state: any[], action: any) {
+      state.push(['pendingReducer', action])
+    }
+    function fulfilled(state: any[], action: any) {
+      state.push(['fulfilledReducer', action])
+    }
+    function rejected(state: any[], action: any) {
+      state.push(['rejectedReducer', action])
+    }
+    function settled(state: any[], action: any) {
+      state.push(['settledReducer', action])
+    }
+
+    test('successful thunk', async () => {
+      const slice = createAppSlice({
+        name: 'test',
+        initialState: [] as any[],
+        reducers: (create) => ({
+          thunkReducers: create.asyncThunk(
+            function payloadCreator(arg: string, api) {
+              return Promise.resolve('resolved payload')
+            },
+            { pending, fulfilled, rejected, settled },
+          ),
+        }),
+      })
+
+      const store = configureStore({
+        reducer: slice.reducer,
+      })
+      await store.dispatch(slice.actions.thunkReducers('test'))
+      expect(store.getState()).toMatchObject([
+        [
+          'pendingReducer',
+          {
+            type: 'test/thunkReducers/pending',
+            payload: undefined,
+          },
+        ],
+        [
+          'fulfilledReducer',
+          {
+            type: 'test/thunkReducers/fulfilled',
+            payload: 'resolved payload',
+          },
+        ],
+        [
+          'settledReducer',
+          {
+            type: 'test/thunkReducers/fulfilled',
+            payload: 'resolved payload',
+          },
+        ],
+      ])
+    })
+
+    test('rejected thunk', async () => {
+      const slice = createAppSlice({
+        name: 'test',
+        initialState: [] as any[],
+        reducers: (create) => ({
+          thunkReducers: create.asyncThunk(
+            // payloadCreator isn't allowed to return never
+            function payloadCreator(arg: string, api): any {
+              throw new Error('')
+            },
+            { pending, fulfilled, rejected, settled },
+          ),
+        }),
+      })
+
+      const store = configureStore({
+        reducer: slice.reducer,
+      })
+      await store.dispatch(slice.actions.thunkReducers('test'))
+      expect(store.getState()).toMatchObject([
+        [
+          'pendingReducer',
+          {
+            type: 'test/thunkReducers/pending',
+            payload: undefined,
+          },
+        ],
+        [
+          'rejectedReducer',
+          {
+            type: 'test/thunkReducers/rejected',
+            payload: undefined,
+          },
+        ],
+        [
+          'settledReducer',
+          {
+            type: 'test/thunkReducers/rejected',
+            payload: undefined,
+          },
+        ],
+      ])
+    })
+
+    test('with options', async () => {
+      const slice = createAppSlice({
+        name: 'test',
+        initialState: [] as any[],
+        reducers: (create) => ({
+          thunkReducers: create.asyncThunk(
+            function payloadCreator(arg: string, api) {
+              return 'should not call this'
+            },
+            {
+              options: {
+                condition() {
+                  return false
+                },
+                dispatchConditionRejection: true,
+              },
+              pending,
+              fulfilled,
+              rejected,
+              settled,
+            },
+          ),
+        }),
+      })
+
+      const store = configureStore({
+        reducer: slice.reducer,
+      })
+      await store.dispatch(slice.actions.thunkReducers('test'))
+      expect(store.getState()).toMatchObject([
+        [
+          'rejectedReducer',
+          {
+            type: 'test/thunkReducers/rejected',
+            payload: undefined,
+            meta: { condition: true },
+          },
+        ],
+        [
+          'settledReducer',
+          {
+            type: 'test/thunkReducers/rejected',
+            payload: undefined,
+            meta: { condition: true },
+          },
+        ],
+      ])
+    })
+
+    test('has caseReducers for the asyncThunk', async () => {
+      const slice = createAppSlice({
+        name: 'test',
+        initialState: [],
+        reducers: (create) => ({
+          thunkReducers: create.asyncThunk(
+            function payloadCreator(arg, api) {
+              return Promise.resolve('resolved payload')
+            },
+            { pending, fulfilled, settled },
+          ),
+        }),
+      })
+
+      expect(slice.caseReducers.thunkReducers.pending).toBe(pending)
+      expect(slice.caseReducers.thunkReducers.fulfilled).toBe(fulfilled)
+      expect(slice.caseReducers.thunkReducers.settled).toBe(settled)
+      // even though it is not defined above, this should at least be a no-op function to match the TypeScript typings
+      // and should be callable as a reducer even if it does nothing
+      expect(() =>
+        slice.caseReducers.thunkReducers.rejected(
+          [],
+          slice.actions.thunkReducers.rejected(
+            new Error('test'),
+            'fakeRequestId',
+          ),
+        ),
+      ).not.toThrow()
+    })
+
+    test('can define reducer with prepare statement using create.preparedReducer', async () => {
+      const slice = createSlice({
+        name: 'test',
+        initialState: [] as any[],
+        reducers: (create) => ({
+          prepared: create.preparedReducer(
+            (p: string, m: number, e: { message: string }) => ({
+              payload: p,
+              meta: m,
+              error: e,
+            }),
+            (state, action) => {
+              state.push(action)
+            },
+          ),
+        }),
+      })
+
+      expect(
+        slice.reducer(
+          [],
+          slice.actions.prepared('test', 1, { message: 'err' }),
+        ),
+      ).toMatchInlineSnapshot(`
+        [
+          {
+            "error": {
+              "message": "err",
+            },
+            "meta": 1,
+            "payload": "test",
+            "type": "test/prepared",
+          },
+        ]
+      `)
+    })
+
+    test('throws an error when invoked with a normal `prepare` object that has not gone through a `create.preparedReducer` call', async () => {
+      expect(() =>
+        createSlice({
+          name: 'test',
+          initialState: [] as any[],
+          reducers: (create) => ({
+            prepared: {
+              prepare: (p: string, m: number, e: { message: string }) => ({
+                payload: p,
+                meta: m,
+                error: e,
+              }),
+              reducer: (state, action) => {
+                state.push(action)
+              },
+            },
+          }),
+        }),
+      ).toThrowErrorMatchingInlineSnapshot(
+        `[Error: Please use the \`create.preparedReducer\` notation for prepared action creators with the \`create\` notation.]`,
+      )
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/getDefaultEnhancers.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/getDefaultEnhancers.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/getDefaultEnhancers.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,143 @@
+import type { StoreEnhancer } from '@reduxjs/toolkit'
+import { configureStore } from '@reduxjs/toolkit'
+
+declare const enhancer1: StoreEnhancer<
+  {
+    has1: true
+  },
+  { stateHas1: true }
+>
+
+declare const enhancer2: StoreEnhancer<
+  {
+    has2: true
+  },
+  { stateHas2: true }
+>
+
+describe('type tests', () => {
+  test('prepend single element', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      enhancers: (gDE) => gDE().prepend(enhancer1),
+    })
+
+    expectTypeOf(store.has1).toEqualTypeOf<true>()
+
+    expectTypeOf(store.getState().stateHas1).toEqualTypeOf<true>()
+
+    expectTypeOf(store).not.toHaveProperty('has2')
+
+    expectTypeOf(store.getState()).not.toHaveProperty('stateHas2')
+  })
+
+  test('prepend multiple (rest)', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      enhancers: (gDE) => gDE().prepend(enhancer1, enhancer2),
+    })
+
+    expectTypeOf(store.has1).toEqualTypeOf<true>()
+
+    expectTypeOf(store.getState().stateHas1).toEqualTypeOf<true>()
+
+    expectTypeOf(store.has2).toEqualTypeOf<true>()
+
+    expectTypeOf(store.getState().stateHas2).toEqualTypeOf<true>()
+
+    expectTypeOf(store).not.toHaveProperty('has3')
+
+    expectTypeOf(store.getState()).not.toHaveProperty('stateHas3')
+  })
+
+  test('prepend multiple (array notation)', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      enhancers: (gDE) => gDE().prepend([enhancer1, enhancer2] as const),
+    })
+
+    expectTypeOf(store.has1).toEqualTypeOf<true>()
+
+    expectTypeOf(store.getState().stateHas1).toEqualTypeOf<true>()
+
+    expectTypeOf(store.has2).toEqualTypeOf<true>()
+
+    expectTypeOf(store.getState().stateHas2).toEqualTypeOf<true>()
+
+    expectTypeOf(store).not.toHaveProperty('has3')
+
+    expectTypeOf(store.getState()).not.toHaveProperty('stateHas3')
+  })
+
+  test('concat single element', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      enhancers: (gDE) => gDE().concat(enhancer1),
+    })
+
+    expectTypeOf(store.has1).toEqualTypeOf<true>()
+
+    expectTypeOf(store.getState().stateHas1).toEqualTypeOf<true>()
+
+    expectTypeOf(store).not.toHaveProperty('has2')
+
+    expectTypeOf(store.getState()).not.toHaveProperty('stateHas2')
+  })
+
+  test('prepend multiple (rest)', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      enhancers: (gDE) => gDE().concat(enhancer1, enhancer2),
+    })
+
+    expectTypeOf(store.has1).toEqualTypeOf<true>()
+
+    expectTypeOf(store.getState().stateHas1).toEqualTypeOf<true>()
+
+    expectTypeOf(store.has2).toEqualTypeOf<true>()
+
+    expectTypeOf(store.getState().stateHas2).toEqualTypeOf<true>()
+
+    expectTypeOf(store).not.toHaveProperty('has3')
+
+    expectTypeOf(store.getState()).not.toHaveProperty('stateHas3')
+  })
+
+  test('concat multiple (array notation)', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      enhancers: (gDE) => gDE().concat([enhancer1, enhancer2] as const),
+    })
+
+    expectTypeOf(store.has1).toEqualTypeOf<true>()
+
+    expectTypeOf(store.getState().stateHas1).toEqualTypeOf<true>()
+
+    expectTypeOf(store.has2).toEqualTypeOf<true>()
+
+    expectTypeOf(store.getState().stateHas2).toEqualTypeOf<true>()
+
+    expectTypeOf(store).not.toHaveProperty('has3')
+
+    expectTypeOf(store.getState()).not.toHaveProperty('stateHas3')
+  })
+
+  test('concat and prepend', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      enhancers: (gDE) => gDE().concat(enhancer1).prepend(enhancer2),
+    })
+
+    expectTypeOf(store.has1).toEqualTypeOf<true>()
+
+    expectTypeOf(store.getState().stateHas1).toEqualTypeOf<true>()
+
+    expectTypeOf(store.has2).toEqualTypeOf<true>()
+
+    expectTypeOf(store.getState().stateHas2).toEqualTypeOf<true>()
+
+    expectTypeOf(store).not.toHaveProperty('has3')
+
+    expectTypeOf(store.getState()).not.toHaveProperty('stateHas3')
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/getDefaultMiddleware.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/getDefaultMiddleware.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/getDefaultMiddleware.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,199 @@
+import { buildGetDefaultMiddleware } from '@internal/getDefaultMiddleware'
+import type {
+  Action,
+  Dispatch,
+  Middleware,
+  ThunkAction,
+  ThunkDispatch,
+  ThunkMiddleware,
+  Tuple,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import { configureStore } from '@reduxjs/toolkit'
+
+declare const middleware1: Middleware<{
+  (_: string): number
+}>
+
+declare const middleware2: Middleware<{
+  (_: number): string
+}>
+
+type ThunkReturn = Promise<'thunk'>
+declare const thunkCreator: () => () => ThunkReturn
+
+const getDefaultMiddleware = buildGetDefaultMiddleware()
+
+describe('type tests', () => {
+  test('prepend single element', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      middleware: (gDM) => gDM().prepend(middleware1),
+    })
+
+    expectTypeOf(store.dispatch('foo')).toBeNumber()
+
+    expectTypeOf(store.dispatch(thunkCreator())).toEqualTypeOf<ThunkReturn>()
+
+    expectTypeOf(store.dispatch('foo')).not.toBeString()
+  })
+
+  test('prepend multiple (rest)', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      middleware: (gDM) => gDM().prepend(middleware1, middleware2),
+    })
+
+    expectTypeOf(store.dispatch('foo')).toBeNumber()
+
+    expectTypeOf(store.dispatch(5)).toBeString()
+
+    expectTypeOf(store.dispatch(thunkCreator())).toEqualTypeOf<ThunkReturn>()
+
+    expectTypeOf(store.dispatch('foo')).not.toBeString()
+  })
+
+  test('prepend multiple (array notation)', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      middleware: (gDM) => gDM().prepend([middleware1, middleware2] as const),
+    })
+
+    expectTypeOf(store.dispatch('foo')).toBeNumber()
+
+    expectTypeOf(store.dispatch(5)).toBeString()
+
+    expectTypeOf(store.dispatch(thunkCreator())).toEqualTypeOf<ThunkReturn>()
+
+    expectTypeOf(store.dispatch('foo')).not.toBeString()
+  })
+
+  test('concat single element', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      middleware: (gDM) => gDM().concat(middleware1),
+    })
+
+    expectTypeOf(store.dispatch('foo')).toBeNumber()
+
+    expectTypeOf(store.dispatch(thunkCreator())).toEqualTypeOf<ThunkReturn>()
+
+    expectTypeOf(store.dispatch('foo')).not.toBeString()
+  })
+
+  test('prepend multiple (rest)', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      middleware: (gDM) => gDM().concat(middleware1, middleware2),
+    })
+
+    expectTypeOf(store.dispatch('foo')).toBeNumber()
+
+    expectTypeOf(store.dispatch(5)).toBeString()
+
+    expectTypeOf(store.dispatch(thunkCreator())).toEqualTypeOf<ThunkReturn>()
+
+    expectTypeOf(store.dispatch('foo')).not.toBeString()
+  })
+
+  test('concat multiple (array notation)', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      middleware: (gDM) => gDM().concat([middleware1, middleware2] as const),
+    })
+
+    expectTypeOf(store.dispatch('foo')).toBeNumber()
+
+    expectTypeOf(store.dispatch(5)).toBeString()
+
+    expectTypeOf(store.dispatch(thunkCreator())).toEqualTypeOf<ThunkReturn>()
+
+    expectTypeOf(store.dispatch('foo')).not.toBeString()
+  })
+
+  test('concat and prepend', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      middleware: (gDM) => gDM().concat(middleware1).prepend(middleware2),
+    })
+
+    expectTypeOf(store.dispatch('foo')).toBeNumber()
+
+    expectTypeOf(store.dispatch(5)).toBeString()
+
+    expectTypeOf(store.dispatch(thunkCreator())).toEqualTypeOf<ThunkReturn>()
+
+    expectTypeOf(store.dispatch('foo')).not.toBeString()
+  })
+
+  test('allows passing options to thunk', () => {
+    const extraArgument = 42 as const
+
+    const m2 = getDefaultMiddleware({
+      thunk: false,
+    })
+
+    expectTypeOf(m2).toMatchTypeOf<Tuple<[]>>()
+
+    const dummyMiddleware: Middleware<
+      {
+        (action: Action<'actionListenerMiddleware/add'>): () => void
+      },
+      { counter: number }
+    > = (storeApi) => (next) => (action) => {
+      return next(action)
+    }
+
+    const dummyMiddleware2: Middleware<{}, { counter: number }> =
+      (storeApi) => (next) => (action) => {}
+
+    const testThunk: ThunkAction<
+      void,
+      { counter: number },
+      number,
+      UnknownAction
+    > = (dispatch, getState, extraArg) => {
+      expect(extraArg).toBe(extraArgument)
+    }
+
+    const reducer = () => ({ counter: 123 })
+
+    const store = configureStore({
+      reducer,
+      middleware: (gDM) => {
+        const middleware = gDM({
+          thunk: { extraArgument },
+          immutableCheck: false,
+          serializableCheck: false,
+          actionCreatorCheck: false,
+        })
+
+        const m3 = middleware.concat(dummyMiddleware, dummyMiddleware2)
+
+        expectTypeOf(m3).toMatchTypeOf<
+          Tuple<
+            [
+              ThunkMiddleware<any, UnknownAction, 42>,
+              Middleware<
+                (action: Action<'actionListenerMiddleware/add'>) => () => void,
+                {
+                  counter: number
+                },
+                Dispatch<UnknownAction>
+              >,
+              Middleware<{}, any, Dispatch<UnknownAction>>,
+            ]
+          >
+        >()
+
+        return m3
+      },
+    })
+
+    expectTypeOf(store.dispatch).toMatchTypeOf<
+      ThunkDispatch<any, 42, UnknownAction> & Dispatch<UnknownAction>
+    >()
+
+    store.dispatch(testThunk)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/getDefaultMiddleware.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/getDefaultMiddleware.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/getDefaultMiddleware.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,317 @@
+import { Tuple } from '@internal/utils'
+import type {
+  Action,
+  Middleware,
+  ThunkAction,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import { configureStore } from '@reduxjs/toolkit'
+import { thunk } from 'redux-thunk'
+import { vi } from 'vitest'
+
+import { buildGetDefaultMiddleware } from '@internal/getDefaultMiddleware'
+
+const getDefaultMiddleware = buildGetDefaultMiddleware()
+
+describe('getDefaultMiddleware', () => {
+  afterEach(() => {
+    vi.unstubAllEnvs()
+  })
+
+  describe('Production behavior', () => {
+    beforeEach(() => {
+      vi.resetModules()
+    })
+
+    it('returns an array with only redux-thunk in production', async () => {
+      vi.stubEnv('NODE_ENV', 'production')
+
+      const { thunk } = await import('redux-thunk')
+      const { buildGetDefaultMiddleware } = await import(
+        '@internal/getDefaultMiddleware'
+      )
+
+      const middleware = buildGetDefaultMiddleware()()
+      expect(middleware).toContain(thunk)
+      expect(middleware.length).toBe(1)
+    })
+  })
+
+  it('returns an array with additional middleware in development', () => {
+    const middleware = getDefaultMiddleware()
+    expect(middleware).toContain(thunk)
+    expect(middleware.length).toBeGreaterThan(1)
+  })
+
+  const defaultMiddleware = getDefaultMiddleware()
+
+  it('removes the thunk middleware if disabled', () => {
+    const middleware = getDefaultMiddleware({ thunk: false })
+    // @ts-ignore
+    expect(middleware.includes(thunk)).toBe(false)
+    expect(middleware.length).toBe(defaultMiddleware.length - 1)
+  })
+
+  it('removes the immutable middleware if disabled', () => {
+    const middleware = getDefaultMiddleware({ immutableCheck: false })
+    expect(middleware.length).toBe(defaultMiddleware.length - 1)
+  })
+
+  it('removes the serializable middleware if disabled', () => {
+    const middleware = getDefaultMiddleware({ serializableCheck: false })
+    expect(middleware.length).toBe(defaultMiddleware.length - 1)
+  })
+
+  it('removes the action creator middleware if disabled', () => {
+    const middleware = getDefaultMiddleware({ actionCreatorCheck: false })
+    expect(middleware.length).toBe(defaultMiddleware.length - 1)
+  })
+
+  it('allows passing options to thunk', () => {
+    const extraArgument = 42 as const
+
+    const m2 = getDefaultMiddleware({
+      thunk: false,
+    })
+
+    const dummyMiddleware: Middleware<
+      {
+        (action: Action<'actionListenerMiddleware/add'>): () => void
+      },
+      { counter: number }
+    > = (storeApi) => (next) => (action) => {
+      return next(action)
+    }
+
+    const dummyMiddleware2: Middleware<{}, { counter: number }> =
+      (storeApi) => (next) => (action) => {}
+
+    const testThunk: ThunkAction<
+      void,
+      { counter: number },
+      number,
+      UnknownAction
+    > = (dispatch, getState, extraArg) => {
+      expect(extraArg).toBe(extraArgument)
+    }
+
+    const reducer = () => ({ counter: 123 })
+
+    const store = configureStore({
+      reducer,
+      middleware: (gDM) => {
+        const middleware = gDM({
+          thunk: { extraArgument },
+          immutableCheck: false,
+          serializableCheck: false,
+          actionCreatorCheck: false,
+        })
+
+        const m3 = middleware.concat(dummyMiddleware, dummyMiddleware2)
+
+        return m3
+      },
+    })
+
+    store.dispatch(testThunk)
+  })
+
+  it('allows passing options to immutableCheck', () => {
+    let immutableCheckWasCalled = false
+
+    const middleware = () =>
+      getDefaultMiddleware({
+        thunk: false,
+        immutableCheck: {
+          isImmutable: () => {
+            immutableCheckWasCalled = true
+            return true
+          },
+        },
+        serializableCheck: false,
+        actionCreatorCheck: false,
+      })
+
+    const reducer = () => ({})
+
+    const store = configureStore({
+      reducer,
+      middleware,
+    })
+
+    expect(immutableCheckWasCalled).toBe(true)
+  })
+
+  it('allows passing options to serializableCheck', () => {
+    let serializableCheckWasCalled = false
+
+    const middleware = () =>
+      getDefaultMiddleware({
+        thunk: false,
+        immutableCheck: false,
+        serializableCheck: {
+          isSerializable: () => {
+            serializableCheckWasCalled = true
+            return true
+          },
+        },
+        actionCreatorCheck: false,
+      })
+
+    const reducer = () => ({})
+
+    const store = configureStore({
+      reducer,
+      middleware,
+    })
+
+    store.dispatch({ type: 'TEST_ACTION' })
+
+    expect(serializableCheckWasCalled).toBe(true)
+  })
+})
+
+it('allows passing options to actionCreatorCheck', () => {
+  let actionCreatorCheckWasCalled = false
+
+  const middleware = () =>
+    getDefaultMiddleware({
+      thunk: false,
+      immutableCheck: false,
+      serializableCheck: false,
+      actionCreatorCheck: {
+        isActionCreator: (action: unknown): action is Function => {
+          actionCreatorCheckWasCalled = true
+          return false
+        },
+      },
+    })
+
+  const reducer = () => ({})
+
+  const store = configureStore({
+    reducer,
+    middleware,
+  })
+
+  store.dispatch({ type: 'TEST_ACTION' })
+
+  expect(actionCreatorCheckWasCalled).toBe(true)
+})
+
+describe('Tuple functionality', () => {
+  const middleware1: Middleware = () => (next) => (action) => next(action)
+  const middleware2: Middleware = () => (next) => (action) => next(action)
+  const defaultMiddleware = getDefaultMiddleware()
+  const originalDefaultMiddleware = [...defaultMiddleware]
+
+  test('allows to prepend a single value', () => {
+    const prepended = defaultMiddleware.prepend(middleware1)
+
+    // value is prepended
+    expect(prepended).toEqual([middleware1, ...defaultMiddleware])
+    // returned value is of correct type
+    expect(prepended).toBeInstanceOf(Tuple)
+    // prepended is a new array
+    expect(prepended).not.toEqual(defaultMiddleware)
+    // defaultMiddleware is not modified
+    expect(defaultMiddleware).toEqual(originalDefaultMiddleware)
+  })
+
+  test('allows to prepend multiple values (array as first argument)', () => {
+    const prepended = defaultMiddleware.prepend([middleware1, middleware2])
+
+    // value is prepended
+    expect(prepended).toEqual([middleware1, middleware2, ...defaultMiddleware])
+    // returned value is of correct type
+    expect(prepended).toBeInstanceOf(Tuple)
+    // prepended is a new array
+    expect(prepended).not.toEqual(defaultMiddleware)
+    // defaultMiddleware is not modified
+    expect(defaultMiddleware).toEqual(originalDefaultMiddleware)
+  })
+
+  test('allows to prepend multiple values (rest)', () => {
+    const prepended = defaultMiddleware.prepend(middleware1, middleware2)
+
+    // value is prepended
+    expect(prepended).toEqual([middleware1, middleware2, ...defaultMiddleware])
+    // returned value is of correct type
+    expect(prepended).toBeInstanceOf(Tuple)
+    // prepended is a new array
+    expect(prepended).not.toEqual(defaultMiddleware)
+    // defaultMiddleware is not modified
+    expect(defaultMiddleware).toEqual(originalDefaultMiddleware)
+  })
+
+  test('allows to concat a single value', () => {
+    const concatenated = defaultMiddleware.concat(middleware1)
+
+    // value is concatenated
+    expect(concatenated).toEqual([...defaultMiddleware, middleware1])
+    // returned value is of correct type
+    expect(concatenated).toBeInstanceOf(Tuple)
+    // concatenated is a new array
+    expect(concatenated).not.toEqual(defaultMiddleware)
+    // defaultMiddleware is not modified
+    expect(defaultMiddleware).toEqual(originalDefaultMiddleware)
+  })
+
+  test('allows to concat multiple values (array as first argument)', () => {
+    const concatenated = defaultMiddleware.concat([middleware1, middleware2])
+
+    // value is concatenated
+    expect(concatenated).toEqual([
+      ...defaultMiddleware,
+      middleware1,
+      middleware2,
+    ])
+    // returned value is of correct type
+    expect(concatenated).toBeInstanceOf(Tuple)
+    // concatenated is a new array
+    expect(concatenated).not.toEqual(defaultMiddleware)
+    // defaultMiddleware is not modified
+    expect(defaultMiddleware).toEqual(originalDefaultMiddleware)
+  })
+
+  test('allows to concat multiple values (rest)', () => {
+    const concatenated = defaultMiddleware.concat(middleware1, middleware2)
+
+    // value is concatenated
+    expect(concatenated).toEqual([
+      ...defaultMiddleware,
+      middleware1,
+      middleware2,
+    ])
+    // returned value is of correct type
+    expect(concatenated).toBeInstanceOf(Tuple)
+    // concatenated is a new array
+    expect(concatenated).not.toEqual(defaultMiddleware)
+    // defaultMiddleware is not modified
+    expect(defaultMiddleware).toEqual(originalDefaultMiddleware)
+  })
+
+  test('allows to concat and then prepend', () => {
+    const concatenated = defaultMiddleware
+      .concat(middleware1)
+      .prepend(middleware2)
+
+    expect(concatenated).toEqual([
+      middleware2,
+      ...defaultMiddleware,
+      middleware1,
+    ])
+  })
+
+  test('allows to prepend and then concat', () => {
+    const concatenated = defaultMiddleware
+      .prepend(middleware2)
+      .concat(middleware1)
+
+    expect(concatenated).toEqual([
+      middleware2,
+      ...defaultMiddleware,
+      middleware1,
+    ])
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/immutableStateInvariantMiddleware.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/immutableStateInvariantMiddleware.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/immutableStateInvariantMiddleware.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,506 @@
+import { trackForMutations } from '@internal/immutableStateInvariantMiddleware'
+import { noop } from '@internal/listenerMiddleware/utils'
+import type {
+  ImmutableStateInvariantMiddlewareOptions,
+  Middleware,
+  MiddlewareAPI,
+  Store,
+} from '@reduxjs/toolkit'
+import {
+  createImmutableStateInvariantMiddleware,
+  isImmutableDefault,
+} from '@reduxjs/toolkit'
+
+type MWNext = Parameters<ReturnType<Middleware>>[0]
+
+describe('createImmutableStateInvariantMiddleware', () => {
+  let state: { foo: { bar: number[]; baz: string } }
+  const getState: Store['getState'] = () => state
+
+  function middleware(options: ImmutableStateInvariantMiddlewareOptions = {}) {
+    return createImmutableStateInvariantMiddleware(options)({
+      getState,
+    } as MiddlewareAPI)
+  }
+
+  beforeEach(() => {
+    state = { foo: { bar: [2, 3, 4], baz: 'baz' } }
+  })
+
+  it('sends the action through the middleware chain', () => {
+    const next: MWNext = vi.fn()
+    const dispatch = middleware()(next)
+    dispatch({ type: 'SOME_ACTION' })
+
+    expect(next).toHaveBeenCalledWith({
+      type: 'SOME_ACTION',
+    })
+  })
+
+  it('throws if mutating inside the dispatch', () => {
+    const next: MWNext = (action) => {
+      state.foo.bar.push(5)
+      return action
+    }
+
+    const dispatch = middleware()(next)
+
+    expect(() => {
+      dispatch({ type: 'SOME_ACTION' })
+    }).toThrow(new RegExp('foo\\.bar\\.3'))
+  })
+
+  it('throws if mutating between dispatches', () => {
+    const next: MWNext = (action) => action
+
+    const dispatch = middleware()(next)
+
+    dispatch({ type: 'SOME_ACTION' })
+    state.foo.bar.push(5)
+    expect(() => {
+      dispatch({ type: 'SOME_OTHER_ACTION' })
+    }).toThrow(new RegExp('foo\\.bar\\.3'))
+  })
+
+  it('does not throw if not mutating inside the dispatch', () => {
+    const next: MWNext = (action) => {
+      state = { ...state, foo: { ...state.foo, baz: 'changed!' } }
+      return action
+    }
+
+    const dispatch = middleware()(next)
+
+    expect(() => {
+      dispatch({ type: 'SOME_ACTION' })
+    }).not.toThrow()
+  })
+
+  it('does not throw if not mutating between dispatches', () => {
+    const next: MWNext = (action) => action
+
+    const dispatch = middleware()(next)
+
+    dispatch({ type: 'SOME_ACTION' })
+    state = { ...state, foo: { ...state.foo, baz: 'changed!' } }
+    expect(() => {
+      dispatch({ type: 'SOME_OTHER_ACTION' })
+    }).not.toThrow()
+  })
+
+  it('works correctly with circular references', () => {
+    const next: MWNext = (action) => action
+
+    const dispatch = middleware()(next)
+
+    let x: any = {}
+    let y: any = {}
+    x.y = y
+    y.x = x
+
+    expect(() => {
+      dispatch({ type: 'SOME_ACTION', x })
+    }).not.toThrow()
+  })
+
+  it('respects "isImmutable" option', function () {
+    const isImmutable = (value: any) => true
+    const next: MWNext = (action) => {
+      state.foo.bar.push(5)
+      return action
+    }
+
+    const dispatch = middleware({ isImmutable })(next)
+
+    expect(() => {
+      dispatch({ type: 'SOME_ACTION' })
+    }).not.toThrow()
+  })
+
+  it('respects "ignoredPaths" option', () => {
+    const next: MWNext = (action) => {
+      state.foo.bar.push(5)
+      return action
+    }
+
+    const dispatch1 = middleware({ ignoredPaths: ['foo.bar'] })(next)
+
+    expect(() => {
+      dispatch1({ type: 'SOME_ACTION' })
+    }).not.toThrow()
+
+    const dispatch2 = middleware({ ignoredPaths: [/^foo/] })(next)
+
+    expect(() => {
+      dispatch2({ type: 'SOME_ACTION' })
+    }).not.toThrow()
+  })
+
+  it('Should print a warning if execution takes too long', () => {
+    state.foo.bar = new Array(10000).fill({ value: 'more' })
+
+    const next: MWNext = (action) => action
+
+    const dispatch = middleware({ warnAfter: 4 })(next)
+
+    const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(noop)
+
+    try {
+      dispatch({ type: 'SOME_ACTION' })
+
+      expect(consoleWarnSpy).toHaveBeenCalledOnce()
+
+      expect(consoleWarnSpy).toHaveBeenLastCalledWith(
+        expect.stringMatching(
+          /^ImmutableStateInvariantMiddleware took \d*ms, which is more than the warning threshold of 4ms./,
+        ),
+      )
+    } finally {
+      consoleWarnSpy.mockRestore()
+    }
+  })
+
+  it('Should not print a warning if "next" takes too long', () => {
+    const next: MWNext = (action) => {
+      const started = Date.now()
+      while (Date.now() - started < 8) {}
+      return action
+    }
+
+    const dispatch = middleware({ warnAfter: 4 })(next)
+
+    const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(noop)
+
+    try {
+      dispatch({ type: 'SOME_ACTION' })
+
+      expect(consoleWarnSpy).not.toHaveBeenCalled()
+    } finally {
+      consoleWarnSpy.mockRestore()
+    }
+  })
+})
+
+describe('trackForMutations', () => {
+  function testCasesForMutation(spec: any) {
+    it('returns true and the mutated path', () => {
+      const state = spec.getState()
+      const options = spec.middlewareOptions || {}
+      const { isImmutable = isImmutableDefault, ignoredPaths } = options
+      const tracker = trackForMutations(isImmutable, ignoredPaths, state)
+      const newState = spec.fn(state)
+
+      expect(tracker.detectMutations()).toEqual({
+        wasMutated: true,
+        path: spec.path.join('.'),
+      })
+    })
+  }
+
+  function testCasesForNonMutation(spec: any) {
+    it('returns false', () => {
+      const state = spec.getState()
+      const options = spec.middlewareOptions || {}
+      const { isImmutable = isImmutableDefault, ignoredPaths } = options
+      const tracker = trackForMutations(isImmutable, ignoredPaths, state)
+      const newState = spec.fn(state)
+
+      expect(tracker.detectMutations()).toEqual({ wasMutated: false })
+    })
+  }
+
+  interface TestConfig {
+    getState: Store['getState']
+    fn: (s: any) => typeof s | object
+    middlewareOptions?: ImmutableStateInvariantMiddlewareOptions
+    path?: string[]
+  }
+
+  const mutations: Record<string, TestConfig> = {
+    'adding to nested array': {
+      getState: () => ({
+        foo: {
+          bar: [2, 3, 4],
+          baz: 'baz',
+        },
+        stuff: [],
+      }),
+      fn: (s) => {
+        s.foo.bar.push(5)
+        return s
+      },
+      path: ['foo', 'bar', '3'],
+    },
+    'adding to nested array and setting new root object': {
+      getState: () => ({
+        foo: {
+          bar: [2, 3, 4],
+          baz: 'baz',
+        },
+        stuff: [],
+      }),
+      fn: (s) => {
+        s.foo.bar.push(5)
+        return { ...s }
+      },
+      path: ['foo', 'bar', '3'],
+    },
+    'changing nested string': {
+      getState: () => ({
+        foo: {
+          bar: [2, 3, 4],
+          baz: 'baz',
+        },
+        stuff: [],
+      }),
+      fn: (s) => {
+        s.foo.baz = 'changed!'
+        return s
+      },
+      path: ['foo', 'baz'],
+    },
+    'removing nested state': {
+      getState: () => ({
+        foo: {
+          bar: [2, 3, 4],
+          baz: 'baz',
+        },
+        stuff: [],
+      }),
+      fn: (s) => {
+        delete s.foo
+        return s
+      },
+      path: ['foo'],
+    },
+    'adding to array': {
+      getState: () => ({
+        foo: {
+          bar: [2, 3, 4],
+          baz: 'baz',
+        },
+        stuff: [],
+      }),
+      fn: (s) => {
+        s.stuff.push(1)
+        return s
+      },
+      path: ['stuff', '0'],
+    },
+    'adding object to array': {
+      getState: () => ({
+        stuff: [],
+      }),
+      fn: (s) => {
+        s.stuff.push({ foo: 1, bar: 2 })
+        return s
+      },
+      path: ['stuff', '0'],
+    },
+    'mutating previous state and returning new state': {
+      getState: () => ({ counter: 0 }),
+      fn: (s) => {
+        s.mutation = true
+        return { ...s, counter: s.counter + 1 }
+      },
+      path: ['mutation'],
+    },
+    'mutating previous state with non immutable type and returning new state': {
+      getState: () => ({ counter: 0 }),
+      fn: (s) => {
+        s.mutation = [1, 2, 3]
+        return { ...s, counter: s.counter + 1 }
+      },
+      path: ['mutation'],
+    },
+    'mutating previous state with non immutable type and returning new state without that property':
+      {
+        getState: () => ({ counter: 0 }),
+        fn: (s) => {
+          s.mutation = [1, 2, 3]
+          return { counter: s.counter + 1 }
+        },
+        path: ['mutation'],
+      },
+    'mutating previous state with non immutable type and returning new simple state':
+      {
+        getState: () => ({ counter: 0 }),
+        fn: (s) => {
+          s.mutation = [1, 2, 3]
+          return 1
+        },
+        path: ['mutation'],
+      },
+    'mutating previous state by deleting property and returning new state without that property':
+      {
+        getState: () => ({ counter: 0, toBeDeleted: true }),
+        fn: (s) => {
+          delete s.toBeDeleted
+          return { counter: s.counter + 1 }
+        },
+        path: ['toBeDeleted'],
+      },
+    'mutating previous state by deleting nested property': {
+      getState: () => ({ nested: { counter: 0, toBeDeleted: true }, foo: 1 }),
+      fn: (s) => {
+        delete s.nested.toBeDeleted
+        return { nested: { counter: s.counter + 1 } }
+      },
+      path: ['nested', 'toBeDeleted'],
+    },
+    'update reference': {
+      getState: () => ({ foo: {} }),
+      fn: (s) => {
+        s.foo = {}
+        return s
+      },
+      path: ['foo'],
+    },
+    'cannot ignore root state': {
+      getState: () => ({ foo: {} }),
+      fn: (s) => {
+        s.foo = {}
+        return s
+      },
+      middlewareOptions: {
+        ignoredPaths: [''],
+      },
+      path: ['foo'],
+    },
+    'catching state mutation in non-ignored branch': {
+      getState: () => ({
+        foo: {
+          bar: [1, 2],
+        },
+        boo: {
+          yah: [1, 2],
+        },
+      }),
+      fn: (s) => {
+        s.foo.bar.push(3)
+        s.boo.yah.push(3)
+        return s
+      },
+      middlewareOptions: {
+        ignoredPaths: ['foo'],
+      },
+      path: ['boo', 'yah', '2'],
+    },
+  }
+
+  Object.keys(mutations).forEach((mutationDesc) => {
+    describe(mutationDesc, () => {
+      testCasesForMutation(mutations[mutationDesc])
+    })
+  })
+
+  const nonMutations: Record<string, TestConfig> = {
+    'not doing anything': {
+      getState: () => ({ a: 1, b: 2 }),
+      fn: (s) => s,
+    },
+    'from undefined to something': {
+      getState: () => undefined,
+      fn: (s) => ({ foo: 'bar' }),
+    },
+    'returning same state': {
+      getState: () => ({
+        foo: {
+          bar: [2, 3, 4],
+          baz: 'baz',
+        },
+        stuff: [],
+      }),
+      fn: (s) => s,
+    },
+    'returning a new state object with nested new string': {
+      getState: () => ({
+        foo: {
+          bar: [2, 3, 4],
+          baz: 'baz',
+        },
+        stuff: [],
+      }),
+      fn: (s) => {
+        return { ...s, foo: { ...s.foo, baz: 'changed!' } }
+      },
+    },
+    'returning a new state object with nested new array': {
+      getState: () => ({
+        foo: {
+          bar: [2, 3, 4],
+          baz: 'baz',
+        },
+        stuff: [],
+      }),
+      fn: (s) => {
+        return { ...s, foo: { ...s.foo, bar: [...s.foo.bar, 5] } }
+      },
+    },
+    'removing nested state': {
+      getState: () => ({
+        foo: {
+          bar: [2, 3, 4],
+          baz: 'baz',
+        },
+        stuff: [],
+      }),
+      fn: (s) => {
+        return { ...s, foo: {} }
+      },
+    },
+    'having a NaN in the state': {
+      getState: () => ({ a: NaN, b: Number.NaN }),
+      fn: (s) => s,
+    },
+    'ignoring branches from mutation detection': {
+      getState: () => ({
+        foo: {
+          bar: 'bar',
+        },
+      }),
+      fn: (s) => {
+        s.foo.bar = 'baz'
+        return s
+      },
+      middlewareOptions: {
+        ignoredPaths: ['foo'],
+      },
+    },
+    'ignoring nested branches from mutation detection': {
+      getState: () => ({
+        foo: {
+          bar: [1, 2],
+          boo: {
+            yah: [1, 2],
+          },
+        },
+      }),
+      fn: (s) => {
+        s.foo.bar.push(3)
+        s.foo.boo.yah.push(3)
+        return s
+      },
+      middlewareOptions: {
+        ignoredPaths: ['foo.bar', 'foo.boo.yah'],
+      },
+    },
+    'ignoring nested array indices from mutation detection': {
+      getState: () => ({
+        stuff: [{ a: 1 }, { a: 2 }],
+      }),
+      fn: (s) => {
+        s.stuff[1].a = 3
+        return s
+      },
+      middlewareOptions: {
+        ignoredPaths: ['stuff.1'],
+      },
+    },
+  }
+
+  Object.keys(nonMutations).forEach((nonMutationDesc) => {
+    describe(nonMutationDesc, () => {
+      testCasesForNonMutation(nonMutations[nonMutationDesc])
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/mapBuilders.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/mapBuilders.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/mapBuilders.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,416 @@
+import type { SerializedError } from '@internal/createAsyncThunk'
+import { createAsyncThunk } from '@internal/createAsyncThunk'
+import { executeReducerBuilderCallback } from '@internal/mapBuilders'
+import type { UnknownAction } from '@reduxjs/toolkit'
+import { createAction } from '@reduxjs/toolkit'
+
+describe('type tests', () => {
+  test('builder callback for actionMap', () => {
+    const increment = createAction<number, 'increment'>('increment')
+
+    const decrement = createAction<number, 'decrement'>('decrement')
+
+    executeReducerBuilderCallback<number>((builder) => {
+      builder.addCase(increment, (state, action) => {
+        expectTypeOf(state).toBeNumber()
+
+        expectTypeOf(action).toEqualTypeOf<{
+          type: 'increment'
+          payload: number
+        }>()
+
+        expectTypeOf(state).not.toBeString()
+
+        expectTypeOf(action).not.toMatchTypeOf<{
+          type: 'increment'
+          payload: string
+        }>()
+
+        expectTypeOf(action).not.toMatchTypeOf<{
+          type: 'decrement'
+          payload: number
+        }>()
+      })
+
+      builder.addCase('increment', (state, action) => {
+        expectTypeOf(state).toBeNumber()
+
+        expectTypeOf(action).toEqualTypeOf<{ type: 'increment' }>()
+
+        expectTypeOf(state).not.toBeString()
+
+        expectTypeOf(action).not.toMatchTypeOf<{ type: 'decrement' }>()
+
+        // this cannot be inferred and has to be manually specified
+        expectTypeOf(action).not.toMatchTypeOf<{
+          type: 'increment'
+          payload: number
+        }>()
+      })
+
+      builder.addCase(
+        increment,
+        (state, action: ReturnType<typeof increment>) => state,
+      )
+
+      // @ts-expect-error
+      builder.addCase(
+        increment,
+        (state, action: ReturnType<typeof decrement>) => state,
+      )
+
+      builder.addCase(
+        'increment',
+        (state, action: ReturnType<typeof increment>) => state,
+      )
+
+      // @ts-expect-error
+      builder.addCase(
+        'decrement',
+        (state, action: ReturnType<typeof increment>) => state,
+      )
+
+      // action type is inferred
+      builder.addMatcher(increment.match, (state, action) => {
+        expectTypeOf(action).toEqualTypeOf<ReturnType<typeof increment>>()
+      })
+
+      test('action type is inferred when type predicate lacks `type` property', () => {
+        type PredicateWithoutTypeProperty = {
+          payload: number
+        }
+
+        builder.addMatcher(
+          (action): action is PredicateWithoutTypeProperty => true,
+          (state, action) => {
+            expectTypeOf(action).toMatchTypeOf<PredicateWithoutTypeProperty>()
+
+            expectTypeOf(action).toMatchTypeOf<UnknownAction>()
+          },
+        )
+      })
+
+      // action type defaults to UnknownAction if no type predicate matcher is passed
+      builder.addMatcher(
+        () => true,
+        (state, action) => {
+          expectTypeOf(action).toMatchTypeOf<UnknownAction>()
+        },
+      )
+
+      // with a boolean checker, action can also be typed by type argument
+      builder.addMatcher<{ foo: boolean }>(
+        () => true,
+        (state, action) => {
+          expectTypeOf(action).toMatchTypeOf<{ foo: boolean }>()
+
+          expectTypeOf(action).toMatchTypeOf<UnknownAction>()
+        },
+      )
+
+      // addCase().addMatcher() is possible, action type inferred correctly
+      builder
+        .addCase(
+          'increment',
+          (state, action: ReturnType<typeof increment>) => state,
+        )
+        .addMatcher(decrement.match, (state, action) => {
+          expectTypeOf(action).toEqualTypeOf<ReturnType<typeof decrement>>()
+        })
+
+      // addCase().addDefaultCase() is possible, action type is UnknownAction
+      builder
+        .addCase(
+          'increment',
+          (state, action: ReturnType<typeof increment>) => state,
+        )
+        .addDefaultCase((state, action) => {
+          expectTypeOf(action).toMatchTypeOf<UnknownAction>()
+        })
+
+      test('addAsyncThunk() should prevent further calls to addCase() ', () => {
+        const asyncThunk = createAsyncThunk('test', () => {})
+        const b = builder.addAsyncThunk(asyncThunk, {
+          pending: () => {},
+          rejected: () => {},
+          fulfilled: () => {},
+          settled: () => {},
+        })
+
+        expectTypeOf(b).not.toHaveProperty('addCase')
+
+        expectTypeOf(b.addAsyncThunk).toBeFunction()
+
+        expectTypeOf(b.addMatcher).toBeCallableWith(increment.match, () => {})
+
+        expectTypeOf(b.addDefaultCase).toBeCallableWith(() => {})
+      })
+
+      test('addMatcher() should prevent further calls to addCase() and addAsyncThunk()', () => {
+        const b = builder.addMatcher(increment.match, () => {})
+
+        expectTypeOf(b).not.toHaveProperty('addCase')
+        expectTypeOf(b).not.toHaveProperty('addAsyncThunk')
+
+        expectTypeOf(b.addMatcher).toBeCallableWith(increment.match, () => {})
+
+        expectTypeOf(b.addDefaultCase).toBeCallableWith(() => {})
+      })
+
+      test('addDefaultCase() should prevent further calls to addCase(), addAsyncThunk(), addMatcher() and addDefaultCase', () => {
+        const b = builder.addDefaultCase(() => {})
+
+        expectTypeOf(b).not.toHaveProperty('addCase')
+
+        expectTypeOf(b).not.toHaveProperty('addAsyncThunk')
+
+        expectTypeOf(b).not.toHaveProperty('addMatcher')
+
+        expectTypeOf(b).not.toHaveProperty('addDefaultCase')
+      })
+
+      describe('`createAsyncThunk` actions work with `mapBuilder`', () => {
+        test('case 1: normal `createAsyncThunk`', () => {
+          const thunk = createAsyncThunk('test', () => {
+            return 'ret' as const
+          })
+          builder.addCase(thunk.pending, (_, action) => {
+            expectTypeOf(action).toMatchTypeOf<{
+              payload: undefined
+              meta: {
+                arg: void
+                requestId: string
+                requestStatus: 'pending'
+              }
+            }>()
+          })
+
+          builder.addCase(thunk.rejected, (_, action) => {
+            expectTypeOf(action).toMatchTypeOf<{
+              payload: unknown
+              error: SerializedError
+              meta: {
+                arg: void
+                requestId: string
+                requestStatus: 'rejected'
+                aborted: boolean
+                condition: boolean
+                rejectedWithValue: boolean
+              }
+            }>()
+          })
+          builder.addCase(thunk.fulfilled, (_, action) => {
+            expectTypeOf(action).toMatchTypeOf<{
+              payload: 'ret'
+              meta: {
+                arg: void
+                requestId: string
+                requestStatus: 'fulfilled'
+              }
+            }>()
+          })
+
+          builder.addAsyncThunk(thunk, {
+            pending(_, action) {
+              expectTypeOf(action).toMatchTypeOf<{
+                payload: undefined
+                meta: {
+                  arg: void
+                  requestId: string
+                  requestStatus: 'pending'
+                }
+              }>()
+            },
+            rejected(_, action) {
+              expectTypeOf(action).toMatchTypeOf<{
+                payload: unknown
+                error: SerializedError
+                meta: {
+                  arg: void
+                  requestId: string
+                  requestStatus: 'rejected'
+                  aborted: boolean
+                  condition: boolean
+                  rejectedWithValue: boolean
+                }
+              }>()
+            },
+            fulfilled(_, action) {
+              expectTypeOf(action).toMatchTypeOf<{
+                payload: 'ret'
+                meta: {
+                  arg: void
+                  requestId: string
+                  requestStatus: 'fulfilled'
+                }
+              }>()
+            },
+            settled(_, action) {
+              expectTypeOf(action).toMatchTypeOf<
+                | {
+                    payload: 'ret'
+                    meta: {
+                      arg: void
+                      requestId: string
+                      requestStatus: 'fulfilled'
+                    }
+                  }
+                | {
+                    payload: unknown
+                    error: SerializedError
+                    meta: {
+                      arg: void
+                      requestId: string
+                      requestStatus: 'rejected'
+                      aborted: boolean
+                      condition: boolean
+                      rejectedWithValue: boolean
+                    }
+                  }
+              >()
+            },
+          })
+        })
+
+        test('case 2: `createAsyncThunk` with `meta`', () => {
+          const thunk = createAsyncThunk<
+            'ret',
+            void,
+            {
+              pendingMeta: { startedTimeStamp: number }
+              fulfilledMeta: {
+                fulfilledTimeStamp: number
+                baseQueryMeta: 'meta!'
+              }
+              rejectedMeta: {
+                baseQueryMeta: 'meta!'
+              }
+            }
+          >(
+            'test',
+            (_, api) => {
+              return api.fulfillWithValue('ret' as const, {
+                fulfilledTimeStamp: 5,
+                baseQueryMeta: 'meta!',
+              })
+            },
+            {
+              getPendingMeta() {
+                return { startedTimeStamp: 0 }
+              },
+            },
+          )
+
+          builder.addCase(thunk.pending, (_, action) => {
+            expectTypeOf(action).toMatchTypeOf<{
+              payload: undefined
+              meta: {
+                arg: void
+                requestId: string
+                requestStatus: 'pending'
+                startedTimeStamp: number
+              }
+            }>()
+          })
+
+          builder.addCase(thunk.rejected, (_, action) => {
+            expectTypeOf(action).toMatchTypeOf<{
+              payload: unknown
+              error: SerializedError
+              meta: {
+                arg: void
+                requestId: string
+                requestStatus: 'rejected'
+                aborted: boolean
+                condition: boolean
+                rejectedWithValue: boolean
+                baseQueryMeta?: 'meta!'
+              }
+            }>()
+
+            if (action.meta.rejectedWithValue) {
+              expectTypeOf(action.meta.baseQueryMeta).toEqualTypeOf<'meta!'>()
+            }
+          })
+          builder.addCase(thunk.fulfilled, (_, action) => {
+            expectTypeOf(action).toMatchTypeOf<{
+              payload: 'ret'
+              meta: {
+                arg: void
+                requestId: string
+                requestStatus: 'fulfilled'
+                baseQueryMeta: 'meta!'
+              }
+            }>()
+          })
+
+          builder.addAsyncThunk(thunk, {
+            pending(_, action) {
+              expectTypeOf(action).toMatchTypeOf<{
+                payload: undefined
+                meta: {
+                  arg: void
+                  requestId: string
+                  requestStatus: 'pending'
+                  startedTimeStamp: number
+                }
+              }>()
+            },
+            rejected(_, action) {
+              expectTypeOf(action).toMatchTypeOf<{
+                payload: unknown
+                error: SerializedError
+                meta: {
+                  arg: void
+                  requestId: string
+                  requestStatus: 'rejected'
+                  aborted: boolean
+                  condition: boolean
+                  rejectedWithValue: boolean
+                  baseQueryMeta?: 'meta!'
+                }
+              }>()
+            },
+            fulfilled(_, action) {
+              expectTypeOf(action).toMatchTypeOf<{
+                payload: 'ret'
+                meta: {
+                  arg: void
+                  requestId: string
+                  requestStatus: 'fulfilled'
+                  baseQueryMeta: 'meta!'
+                }
+              }>()
+            },
+            settled(_, action) {
+              expectTypeOf(action).toMatchTypeOf<
+                | {
+                    payload: 'ret'
+                    meta: {
+                      arg: void
+                      requestId: string
+                      requestStatus: 'fulfilled'
+                      baseQueryMeta: 'meta!'
+                    }
+                  }
+                | {
+                    payload: unknown
+                    error: SerializedError
+                    meta: {
+                      arg: void
+                      requestId: string
+                      requestStatus: 'rejected'
+                      aborted: boolean
+                      condition: boolean
+                      rejectedWithValue: boolean
+                      baseQueryMeta?: 'meta!'
+                    }
+                  }
+              >()
+            },
+          })
+        })
+      })
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/matchers.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/matchers.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/matchers.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,296 @@
+import type { UnknownAction } from 'redux'
+import type { SerializedError } from '../../src'
+import {
+  createAction,
+  createAsyncThunk,
+  isAllOf,
+  isAnyOf,
+  isAsyncThunkAction,
+  isFulfilled,
+  isPending,
+  isRejected,
+  isRejectedWithValue,
+} from '../../src'
+
+const action: UnknownAction = { type: 'foo' }
+
+describe('type tests', () => {
+  describe('isAnyOf', () => {
+    test('isAnyOf correctly narrows types when used with action creators', () => {
+      const actionA = createAction('a', () => {
+        return {
+          payload: {
+            prop1: 1,
+            prop3: 2,
+          },
+        }
+      })
+
+      const actionB = createAction('b', () => {
+        return {
+          payload: {
+            prop1: 1,
+            prop2: 2,
+          },
+        }
+      })
+
+      if (isAnyOf(actionA, actionB)(action)) {
+        expectTypeOf(action.payload).toHaveProperty('prop1')
+
+        expectTypeOf(action.payload).not.toHaveProperty('prop2')
+
+        expectTypeOf(action.payload).not.toHaveProperty('prop3')
+      }
+    })
+
+    test('isAnyOf correctly narrows types when used with async thunks', () => {
+      const asyncThunk1 = createAsyncThunk<{ prop1: number; prop3: number }>(
+        'asyncThunk1',
+
+        async () => {
+          return {
+            prop1: 1,
+            prop3: 3,
+          }
+        },
+      )
+
+      const asyncThunk2 = createAsyncThunk<{ prop1: number; prop2: number }>(
+        'asyncThunk2',
+
+        async () => {
+          return {
+            prop1: 1,
+            prop2: 2,
+          }
+        },
+      )
+
+      if (isAnyOf(asyncThunk1.fulfilled, asyncThunk2.fulfilled)(action)) {
+        expectTypeOf(action.payload).toHaveProperty('prop1')
+
+        expectTypeOf(action.payload).not.toHaveProperty('prop2')
+
+        expectTypeOf(action.payload).not.toHaveProperty('prop3')
+      }
+    })
+
+    test('isAnyOf correctly narrows types when used with type guards', () => {
+      interface ActionA {
+        type: 'a'
+        payload: {
+          prop1: 1
+          prop3: 2
+        }
+      }
+
+      interface ActionB {
+        type: 'b'
+        payload: {
+          prop1: 1
+          prop2: 2
+        }
+      }
+
+      const guardA = (v: any): v is ActionA => {
+        return v.type === 'a'
+      }
+
+      const guardB = (v: any): v is ActionB => {
+        return v.type === 'b'
+      }
+
+      if (isAnyOf(guardA, guardB)(action)) {
+        expectTypeOf(action.payload).toHaveProperty('prop1')
+
+        expectTypeOf(action.payload).not.toHaveProperty('prop2')
+
+        expectTypeOf(action.payload).not.toHaveProperty('prop3')
+      }
+    })
+  })
+
+  describe('isAllOf', () => {
+    interface SpecialAction {
+      payload: {
+        special: boolean
+      }
+    }
+
+    const isSpecialAction = (v: any): v is SpecialAction => {
+      return v.meta.isSpecial
+    }
+
+    test('isAllOf correctly narrows types when used with action creators and type guards', () => {
+      const actionA = createAction('a', () => {
+        return {
+          payload: {
+            prop1: 1,
+            prop3: 2,
+          },
+        }
+      })
+
+      if (isAllOf(actionA, isSpecialAction)(action)) {
+        expectTypeOf(action.payload).toHaveProperty('prop1')
+
+        expectTypeOf(action.payload).not.toHaveProperty('prop2')
+
+        expectTypeOf(action.payload).toHaveProperty('prop3')
+
+        expectTypeOf(action.payload).toHaveProperty('special')
+      }
+    })
+
+    test('isAllOf correctly narrows types when used with async thunks and type guards', () => {
+      const asyncThunk1 = createAsyncThunk<{ prop1: number; prop3: number }>(
+        'asyncThunk1',
+
+        async () => {
+          return {
+            prop1: 1,
+            prop3: 3,
+          }
+        },
+      )
+
+      if (isAllOf(asyncThunk1.fulfilled, isSpecialAction)(action)) {
+        expectTypeOf(action.payload).toHaveProperty('prop1')
+
+        expectTypeOf(action.payload).not.toHaveProperty('prop2')
+
+        expectTypeOf(action.payload).toHaveProperty('prop3')
+
+        expectTypeOf(action.payload).toHaveProperty('special')
+      }
+    })
+
+    test('isAnyOf correctly narrows types when used with type guards', () => {
+      interface ActionA {
+        type: 'a'
+        payload: {
+          prop1: 1
+          prop3: 2
+        }
+      }
+
+      const guardA = (v: any): v is ActionA => {
+        return v.type === 'a'
+      }
+
+      if (isAllOf(guardA, isSpecialAction)(action)) {
+        expectTypeOf(action.payload).toHaveProperty('prop1')
+
+        expectTypeOf(action.payload).not.toHaveProperty('prop2')
+
+        expectTypeOf(action.payload).toHaveProperty('prop3')
+
+        expectTypeOf(action.payload).toHaveProperty('special')
+      }
+    })
+
+    test('isPending correctly narrows types', () => {
+      if (isPending(action)) {
+        expectTypeOf(action.payload).toBeUndefined()
+
+        expectTypeOf(action).not.toHaveProperty('error')
+      }
+
+      const thunk = createAsyncThunk<string>('a', () => 'result')
+
+      if (isPending(thunk)(action)) {
+        expectTypeOf(action.payload).toBeUndefined()
+
+        expectTypeOf(action).not.toHaveProperty('error')
+      }
+    })
+
+    test('isRejected correctly narrows types', () => {
+      if (isRejected(action)) {
+        // might be there if rejected with payload
+        expectTypeOf(action.payload).toBeUnknown()
+
+        expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+      }
+
+      const thunk = createAsyncThunk<string>('a', () => 'result')
+
+      if (isRejected(thunk)(action)) {
+        // might be there if rejected with payload
+        expectTypeOf(action.payload).toBeUnknown()
+
+        expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+      }
+    })
+
+    test('isFulfilled correctly narrows types', () => {
+      if (isFulfilled(action)) {
+        expectTypeOf(action.payload).toBeUnknown()
+
+        expectTypeOf(action).not.toHaveProperty('error')
+      }
+
+      const thunk = createAsyncThunk<string>('a', () => 'result')
+      if (isFulfilled(thunk)(action)) {
+        expectTypeOf(action.payload).toBeString()
+
+        expectTypeOf(action).not.toHaveProperty('error')
+      }
+    })
+
+    test('isAsyncThunkAction correctly narrows types', () => {
+      if (isAsyncThunkAction(action)) {
+        expectTypeOf(action.payload).toBeUnknown()
+
+        // do not expect an error property because pending/fulfilled lack it
+        expectTypeOf(action).not.toHaveProperty('error')
+      }
+
+      const thunk = createAsyncThunk<string>('a', () => 'result')
+      if (isAsyncThunkAction(thunk)(action)) {
+        // we should expect the payload to be available, but of unknown type because the action may be pending/rejected
+        expectTypeOf(action.payload).toBeUnknown()
+
+        // do not expect an error property because pending/fulfilled lack it
+        expectTypeOf(action).not.toHaveProperty('error')
+      }
+    })
+
+    test('isRejectedWithValue correctly narrows types', () => {
+      if (isRejectedWithValue(action)) {
+        expectTypeOf(action.payload).toBeUnknown()
+
+        expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+      }
+
+      const thunk = createAsyncThunk<
+        string,
+        void,
+        { rejectValue: { message: string } }
+      >('a', () => 'result')
+      if (isRejectedWithValue(thunk)(action)) {
+        expectTypeOf(action.payload).toEqualTypeOf({ message: '' as string })
+
+        expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+      }
+    })
+  })
+
+  test('matchersAcceptSpreadArguments', () => {
+    const thunk1 = createAsyncThunk('a', () => 'a')
+    const thunk2 = createAsyncThunk('b', () => 'b')
+    const interestingThunks = [thunk1, thunk2]
+    const interestingPendingThunks = interestingThunks.map(
+      (thunk) => thunk.pending,
+    )
+    const interestingFulfilledThunks = interestingThunks.map(
+      (thunk) => thunk.fulfilled,
+    )
+
+    const isLoading = isAnyOf(...interestingPendingThunks)
+    const isNotLoading = isAnyOf(...interestingFulfilledThunks)
+
+    const isAllLoading = isAllOf(...interestingPendingThunks)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/matchers.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/matchers.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/matchers.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,461 @@
+import { vi } from 'vitest'
+import type { ThunkAction, UnknownAction } from '@reduxjs/toolkit'
+import {
+  isAllOf,
+  isAnyOf,
+  isAsyncThunkAction,
+  isFulfilled,
+  isPending,
+  isRejected,
+  isRejectedWithValue,
+  createAction,
+  createAsyncThunk,
+  createReducer,
+} from '@reduxjs/toolkit'
+
+const thunk: ThunkAction<any, any, any, UnknownAction> = () => {}
+
+describe('isAnyOf', () => {
+  it('returns true only if any matchers match (match function)', () => {
+    const actionA = createAction<string>('a')
+    const actionB = createAction<number>('b')
+
+    const trueAction = {
+      type: 'a',
+      payload: 'payload',
+    }
+
+    expect(isAnyOf(actionA, actionB)(trueAction)).toEqual(true)
+
+    const falseAction = {
+      type: 'c',
+      payload: 'payload',
+    }
+
+    expect(isAnyOf(actionA, actionB)(falseAction)).toEqual(false)
+  })
+
+  it('returns true only if any type guards match', () => {
+    const actionA = createAction<string>('a')
+    const actionB = createAction<number>('b')
+
+    const isActionA = actionA.match
+    const isActionB = actionB.match
+
+    const trueAction = {
+      type: 'a',
+      payload: 'payload',
+    }
+
+    expect(isAnyOf(isActionA, isActionB)(trueAction)).toEqual(true)
+
+    const falseAction = {
+      type: 'c',
+      payload: 'payload',
+    }
+
+    expect(isAnyOf(isActionA, isActionB)(falseAction)).toEqual(false)
+  })
+
+  it('returns true only if any matchers match (thunk action creators)', () => {
+    const thunkA = createAsyncThunk<string>('a', () => {
+      return 'noop'
+    })
+    const thunkB = createAsyncThunk<number>('b', () => {
+      return 0
+    })
+
+    const action = thunkA.fulfilled('fakeRequestId', 'test')
+
+    expect(isAnyOf(thunkA.fulfilled, thunkB.fulfilled)(action)).toEqual(true)
+
+    expect(
+      isAnyOf(thunkA.pending, thunkA.rejected, thunkB.fulfilled)(action),
+    ).toEqual(false)
+  })
+
+  it('works with reducers', () => {
+    const actionA = createAction<string>('a')
+    const actionB = createAction<number>('b')
+
+    const trueAction = {
+      type: 'a',
+      payload: 'payload',
+    }
+
+    const initialState = { value: false }
+
+    const reducer = createReducer(initialState, (builder) => {
+      builder.addMatcher(isAnyOf(actionA, actionB), (state) => {
+        return { ...state, value: true }
+      })
+    })
+
+    expect(reducer(initialState, trueAction)).toEqual({ value: true })
+
+    const falseAction = {
+      type: 'c',
+      payload: 'payload',
+    }
+
+    expect(reducer(initialState, falseAction)).toEqual(initialState)
+  })
+})
+
+describe('isAllOf', () => {
+  it('returns true only if all matchers match', () => {
+    const actionA = createAction<string>('a')
+
+    interface SpecialAction {
+      payload: 'SPECIAL'
+    }
+
+    const isActionSpecial = (action: any): action is SpecialAction => {
+      return action.payload === 'SPECIAL'
+    }
+
+    const trueAction = {
+      type: 'a',
+      payload: 'SPECIAL',
+    }
+
+    expect(isAllOf(actionA, isActionSpecial)(trueAction)).toEqual(true)
+
+    const falseAction = {
+      type: 'a',
+      payload: 'ORDINARY',
+    }
+
+    expect(isAllOf(actionA, isActionSpecial)(falseAction)).toEqual(false)
+
+    const thunkA = createAsyncThunk<string>('a', () => 'result')
+
+    const specialThunkAction = thunkA.fulfilled('SPECIAL', 'fakeRequestId')
+
+    expect(isAllOf(thunkA.fulfilled, isActionSpecial)(specialThunkAction)).toBe(
+      true,
+    )
+
+    const ordinaryThunkAction = thunkA.fulfilled('ORDINARY', 'fakeRequestId')
+
+    expect(
+      isAllOf(thunkA.fulfilled, isActionSpecial)(ordinaryThunkAction),
+    ).toBe(false)
+  })
+})
+
+describe('isPending', () => {
+  test('should return false for a regular action', () => {
+    const action = createAction<string>('action/type')('testPayload')
+
+    expect(isPending()(action)).toBe(false)
+    expect(isPending(action)).toBe(false)
+    expect(isPending(thunk)).toBe(false)
+  })
+
+  test('should return true only for pending async thunk actions', () => {
+    const thunk = createAsyncThunk<string>('a', () => 'result')
+
+    const pendingAction = thunk.pending('fakeRequestId')
+    expect(isPending()(pendingAction)).toBe(true)
+    expect(isPending(pendingAction)).toBe(true)
+
+    const rejectedAction = thunk.rejected(
+      new Error('rejected'),
+      'fakeRequestId',
+    )
+    expect(isPending()(rejectedAction)).toBe(false)
+
+    const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')
+    expect(isPending()(fulfilledAction)).toBe(false)
+  })
+
+  test('should return true only for thunks provided as arguments', () => {
+    const thunkA = createAsyncThunk<string>('a', () => 'result')
+    const thunkB = createAsyncThunk<string>('b', () => 'result')
+    const thunkC = createAsyncThunk<string>('c', () => 'result')
+
+    const matchAC = isPending(thunkA, thunkC)
+    const matchB = isPending(thunkB)
+
+    function testPendingAction(
+      thunk: typeof thunkA | typeof thunkB | typeof thunkC,
+      expected: boolean,
+    ) {
+      const pendingAction = thunk.pending('fakeRequestId')
+      expect(matchAC(pendingAction)).toBe(expected)
+      expect(matchB(pendingAction)).toBe(!expected)
+
+      const rejectedAction = thunk.rejected(
+        new Error('rejected'),
+        'fakeRequestId',
+      )
+      expect(matchAC(rejectedAction)).toBe(false)
+
+      const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')
+      expect(matchAC(fulfilledAction)).toBe(false)
+    }
+
+    testPendingAction(thunkA, true)
+    testPendingAction(thunkC, true)
+    testPendingAction(thunkB, false)
+  })
+})
+
+describe('isRejected', () => {
+  test('should return false for a regular action', () => {
+    const action = createAction<string>('action/type')('testPayload')
+
+    expect(isRejected()(action)).toBe(false)
+    expect(isRejected(action)).toBe(false)
+    expect(isRejected(thunk)).toBe(false)
+  })
+
+  test('should return true only for rejected async thunk actions', () => {
+    const thunk = createAsyncThunk<string>('a', () => 'result')
+
+    const pendingAction = thunk.pending('fakeRequestId')
+    expect(isRejected()(pendingAction)).toBe(false)
+
+    const rejectedAction = thunk.rejected(
+      new Error('rejected'),
+      'fakeRequestId',
+    )
+    expect(isRejected()(rejectedAction)).toBe(true)
+    expect(isRejected(rejectedAction)).toBe(true)
+
+    const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')
+    expect(isRejected()(fulfilledAction)).toBe(false)
+  })
+
+  test('should return true only for thunks provided as arguments', () => {
+    const thunkA = createAsyncThunk<string>('a', () => 'result')
+    const thunkB = createAsyncThunk<string>('b', () => 'result')
+    const thunkC = createAsyncThunk<string>('c', () => 'result')
+
+    const matchAC = isRejected(thunkA, thunkC)
+    const matchB = isRejected(thunkB)
+
+    function testRejectedAction(
+      thunk: typeof thunkA | typeof thunkB | typeof thunkC,
+      expected: boolean,
+    ) {
+      const pendingAction = thunk.pending('fakeRequestId')
+      expect(matchAC(pendingAction)).toBe(false)
+
+      const rejectedAction = thunk.rejected(
+        new Error('rejected'),
+        'fakeRequestId',
+      )
+      expect(matchAC(rejectedAction)).toBe(expected)
+      expect(matchB(rejectedAction)).toBe(!expected)
+
+      const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')
+      expect(matchAC(fulfilledAction)).toBe(false)
+    }
+
+    testRejectedAction(thunkA, true)
+    testRejectedAction(thunkC, true)
+    testRejectedAction(thunkB, false)
+  })
+})
+
+describe('isRejectedWithValue', () => {
+  test('should return false for a regular action', () => {
+    const action = createAction<string>('action/type')('testPayload')
+
+    expect(isRejectedWithValue()(action)).toBe(false)
+    expect(isRejectedWithValue(action)).toBe(false)
+    expect(isRejectedWithValue(thunk)).toBe(false)
+  })
+
+  test('should return true only for rejected-with-value async thunk actions', async () => {
+    const thunk = createAsyncThunk<string>('a', (_, { rejectWithValue }) => {
+      return rejectWithValue('rejectWithValue!')
+    })
+
+    const pendingAction = thunk.pending('fakeRequestId')
+    expect(isRejectedWithValue()(pendingAction)).toBe(false)
+
+    const rejectedAction = thunk.rejected(
+      new Error('rejected'),
+      'fakeRequestId',
+    )
+    expect(isRejectedWithValue()(rejectedAction)).toBe(false)
+
+    const getState = vi.fn(() => ({}))
+    const dispatch = vi.fn((x: any) => x)
+    const extra = {}
+
+    // note: doesn't throw because we don't unwrap it
+    const rejectedWithValueAction = await thunk()(dispatch, getState, extra)
+
+    expect(isRejectedWithValue()(rejectedWithValueAction)).toBe(true)
+
+    const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')
+    expect(isRejectedWithValue()(fulfilledAction)).toBe(false)
+  })
+
+  test('should return true only for thunks provided as arguments', async () => {
+    const payloadCreator = (_: any, { rejectWithValue }: any) => {
+      return rejectWithValue('rejectWithValue!')
+    }
+
+    const thunkA = createAsyncThunk<string>('a', payloadCreator)
+    const thunkB = createAsyncThunk<string>('b', payloadCreator)
+    const thunkC = createAsyncThunk<string>('c', payloadCreator)
+
+    const matchAC = isRejectedWithValue(thunkA, thunkC)
+    const matchB = isRejectedWithValue(thunkB)
+
+    async function testRejectedAction(
+      thunk: typeof thunkA | typeof thunkB | typeof thunkC,
+      expected: boolean,
+    ) {
+      const pendingAction = thunk.pending('fakeRequestId')
+      expect(matchAC(pendingAction)).toBe(false)
+
+      const rejectedAction = thunk.rejected(
+        new Error('rejected'),
+        'fakeRequestId',
+      )
+      // rejected-with-value is a narrower requirement than rejected
+      expect(matchAC(rejectedAction)).toBe(false)
+
+      const getState = vi.fn(() => ({}))
+      const dispatch = vi.fn((x: any) => x)
+      const extra = {}
+
+      // note: doesn't throw because we don't unwrap it
+      const rejectedWithValueAction = await thunk()(dispatch, getState, extra)
+
+      expect(matchAC(rejectedWithValueAction)).toBe(expected)
+      expect(matchB(rejectedWithValueAction)).toBe(!expected)
+
+      const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')
+      expect(matchAC(fulfilledAction)).toBe(false)
+    }
+
+    await testRejectedAction(thunkA, true)
+    await testRejectedAction(thunkC, true)
+    await testRejectedAction(thunkB, false)
+  })
+})
+
+describe('isFulfilled', () => {
+  test('should return false for a regular action', () => {
+    const action = createAction<string>('action/type')('testPayload')
+
+    expect(isFulfilled()(action)).toBe(false)
+    expect(isFulfilled(action)).toBe(false)
+    expect(isFulfilled(thunk)).toBe(false)
+  })
+
+  test('should return true only for fulfilled async thunk actions', () => {
+    const thunk = createAsyncThunk<string>('a', () => 'result')
+
+    const pendingAction = thunk.pending('fakeRequestId')
+    expect(isFulfilled()(pendingAction)).toBe(false)
+
+    const rejectedAction = thunk.rejected(
+      new Error('rejected'),
+      'fakeRequestId',
+    )
+    expect(isFulfilled()(rejectedAction)).toBe(false)
+
+    const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')
+    expect(isFulfilled()(fulfilledAction)).toBe(true)
+    expect(isFulfilled(fulfilledAction)).toBe(true)
+  })
+
+  test('should return true only for thunks provided as arguments', () => {
+    const thunkA = createAsyncThunk<string>('a', () => 'result')
+    const thunkB = createAsyncThunk<string>('b', () => 'result')
+    const thunkC = createAsyncThunk<string>('c', () => 'result')
+
+    const matchAC = isFulfilled(thunkA, thunkC)
+    const matchB = isFulfilled(thunkB)
+
+    function testFulfilledAction(
+      thunk: typeof thunkA | typeof thunkB | typeof thunkC,
+      expected: boolean,
+    ) {
+      const pendingAction = thunk.pending('fakeRequestId')
+      expect(matchAC(pendingAction)).toBe(false)
+
+      const rejectedAction = thunk.rejected(
+        new Error('rejected'),
+        'fakeRequestId',
+      )
+      expect(matchAC(rejectedAction)).toBe(false)
+
+      const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')
+      expect(matchAC(fulfilledAction)).toBe(expected)
+      expect(matchB(fulfilledAction)).toBe(!expected)
+    }
+
+    testFulfilledAction(thunkA, true)
+    testFulfilledAction(thunkC, true)
+    testFulfilledAction(thunkB, false)
+  })
+})
+
+describe('isAsyncThunkAction', () => {
+  test('should return false for a regular action', () => {
+    const action = createAction<string>('action/type')('testPayload')
+
+    expect(isAsyncThunkAction()(action)).toBe(false)
+    expect(isAsyncThunkAction(action)).toBe(false)
+    expect(isAsyncThunkAction(thunk)).toBe(false)
+  })
+
+  test('should return true for any async thunk action if no arguments were provided', () => {
+    const thunk = createAsyncThunk<string>('a', () => 'result')
+    const matcher = isAsyncThunkAction()
+
+    const pendingAction = thunk.pending('fakeRequestId')
+    expect(matcher(pendingAction)).toBe(true)
+
+    const rejectedAction = thunk.rejected(
+      new Error('rejected'),
+      'fakeRequestId',
+    )
+    expect(matcher(rejectedAction)).toBe(true)
+
+    const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')
+    expect(matcher(fulfilledAction)).toBe(true)
+  })
+
+  test('should return true only for thunks provided as arguments', () => {
+    const thunkA = createAsyncThunk<string>('a', () => 'result')
+    const thunkB = createAsyncThunk<string>('b', () => 'result')
+    const thunkC = createAsyncThunk<string>('c', () => 'result')
+
+    const matchAC = isAsyncThunkAction(thunkA, thunkC)
+    const matchB = isAsyncThunkAction(thunkB)
+
+    function testAllActions(
+      thunk: typeof thunkA | typeof thunkB | typeof thunkC,
+      expected: boolean,
+    ) {
+      const pendingAction = thunk.pending('fakeRequestId')
+      expect(matchAC(pendingAction)).toBe(expected)
+      expect(matchB(pendingAction)).toBe(!expected)
+
+      const rejectedAction = thunk.rejected(
+        new Error('rejected'),
+        'fakeRequestId',
+      )
+      expect(matchAC(rejectedAction)).toBe(expected)
+      expect(matchB(rejectedAction)).toBe(!expected)
+
+      const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')
+      expect(matchAC(fulfilledAction)).toBe(expected)
+      expect(matchB(fulfilledAction)).toBe(!expected)
+    }
+
+    testAllActions(thunkA, true)
+    testAllActions(thunkC, true)
+    testAllActions(thunkB, false)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/serializableStateInvariantMiddleware.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/serializableStateInvariantMiddleware.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/serializableStateInvariantMiddleware.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,663 @@
+import { noop } from '@internal/listenerMiddleware/utils'
+import { isNestedFrozen } from '@internal/serializableStateInvariantMiddleware'
+import type { Reducer } from '@reduxjs/toolkit'
+import {
+  configureStore,
+  createNextState,
+  createSerializableStateInvariantMiddleware,
+  findNonSerializableValue,
+  isPlain,
+  Tuple,
+} from '@reduxjs/toolkit'
+
+// Mocking console
+const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
+
+const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(noop)
+
+afterEach(() => {
+  vi.clearAllMocks()
+})
+
+afterAll(() => {
+  vi.restoreAllMocks()
+})
+
+describe('findNonSerializableValue', () => {
+  it('Should return false if no matching values are found', () => {
+    const obj = {
+      a: 42,
+      b: {
+        b1: 'test',
+      },
+      c: [99, { d: 123 }],
+    }
+
+    const result = findNonSerializableValue(obj)
+
+    expect(result).toBe(false)
+  })
+
+  it('Should return a keypath and the value if it finds a non-serializable value', () => {
+    function testFunction() {}
+
+    const obj = {
+      a: 42,
+      b: {
+        b1: testFunction,
+      },
+      c: [99, { d: 123 }],
+    }
+
+    const result = findNonSerializableValue(obj)
+
+    expect(result).toEqual({ keyPath: 'b.b1', value: testFunction })
+  })
+
+  it('Should return the first non-serializable value it finds', () => {
+    const map = new Map()
+    const symbol = Symbol.for('testSymbol')
+
+    const obj = {
+      a: 42,
+      b: {
+        b1: 1,
+      },
+      c: [99, { d: 123 }, map, symbol, 'test'],
+      d: symbol,
+    }
+
+    const result = findNonSerializableValue(obj)
+
+    expect(result).toEqual({ keyPath: 'c.2', value: map })
+  })
+
+  it('Should return a specific value if the root object is non-serializable', () => {
+    const value = new Map()
+    const result = findNonSerializableValue(value)
+
+    expect(result).toEqual({ keyPath: '<root>', value })
+  })
+
+  it('Should accept null as a valid value', () => {
+    const obj = {
+      a: 42,
+      b: {
+        b1: 1,
+      },
+      c: null,
+    }
+
+    const result = findNonSerializableValue(obj)
+
+    expect(result).toEqual(false)
+  })
+})
+
+describe('serializableStateInvariantMiddleware', () => {
+  it('Should log an error when a non-serializable action is dispatched', () => {
+    const reducer: Reducer = (state = 0, _action) => state + 1
+
+    const serializableStateInvariantMiddleware =
+      createSerializableStateInvariantMiddleware()
+
+    const store = configureStore({
+      reducer,
+      middleware: () => new Tuple(serializableStateInvariantMiddleware),
+    })
+
+    const symbol = Symbol.for('SOME_CONSTANT')
+    const dispatchedAction = { type: 'an-action', payload: symbol }
+
+    store.dispatch(dispatchedAction)
+
+    expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+    expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+      `A non-serializable value was detected in an action, in the path: \`payload\`. Value:`,
+      symbol,
+      `\nTake a look at the logic that dispatched this action: `,
+      dispatchedAction,
+      `\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)`,
+      `\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)`,
+    )
+  })
+
+  it('Should log an error when a non-serializable value is in state', () => {
+    const ACTION_TYPE = 'TEST_ACTION'
+
+    const initialState = {
+      a: 0,
+    }
+
+    const badValue = new Map()
+
+    const reducer: Reducer = (state = initialState, action) => {
+      switch (action.type) {
+        case ACTION_TYPE: {
+          return {
+            a: badValue,
+          }
+        }
+        default:
+          return state
+      }
+    }
+
+    const serializableStateInvariantMiddleware =
+      createSerializableStateInvariantMiddleware()
+
+    const store = configureStore({
+      reducer: {
+        testSlice: reducer,
+      },
+      middleware: () => new Tuple(serializableStateInvariantMiddleware),
+    })
+
+    store.dispatch({ type: ACTION_TYPE })
+
+    expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+    expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+      `A non-serializable value was detected in the state, in the path: \`testSlice.a\`. Value:`,
+      badValue,
+      `\nTake a look at the reducer(s) handling this action type: TEST_ACTION.
+(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`,
+    )
+  })
+
+  describe('consumer tolerated structures', () => {
+    const nonSerializableValue = new Map()
+
+    const nestedSerializableObjectWithBadValue = {
+      isSerializable: true,
+      entries: (): [string, any][] => [
+        ['good-string', 'Good!'],
+        ['good-number', 1337],
+        ['bad-map-instance', nonSerializableValue],
+      ],
+    }
+
+    const serializableObject = {
+      isSerializable: true,
+      entries: (): [string, any][] => [
+        ['first', 1],
+        ['second', 'B!'],
+        ['third', nestedSerializableObjectWithBadValue],
+      ],
+    }
+
+    it('Should log an error when a non-serializable value is nested in state', () => {
+      const ACTION_TYPE = 'TEST_ACTION'
+
+      const initialState = {
+        a: 0,
+      }
+
+      const reducer: Reducer = (state = initialState, action) => {
+        switch (action.type) {
+          case ACTION_TYPE: {
+            return {
+              a: serializableObject,
+            }
+          }
+          default:
+            return state
+        }
+      }
+
+      // use default options
+      const serializableStateInvariantMiddleware =
+        createSerializableStateInvariantMiddleware()
+
+      const store = configureStore({
+        reducer: {
+          testSlice: reducer,
+        },
+        middleware: () => new Tuple(serializableStateInvariantMiddleware),
+      })
+
+      store.dispatch({ type: ACTION_TYPE })
+
+      expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+      // since default options are used, the `entries` function in `serializableObject` will cause the error
+      expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+        `A non-serializable value was detected in the state, in the path: \`testSlice.a.entries\`. Value:`,
+        serializableObject.entries,
+        `\nTake a look at the reducer(s) handling this action type: TEST_ACTION.
+(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`,
+      )
+    })
+
+    it('Should use consumer supplied isSerializable and getEntries options to tolerate certain structures', () => {
+      const ACTION_TYPE = 'TEST_ACTION'
+
+      const initialState = {
+        a: 0,
+      }
+
+      const isSerializable = (val: any): boolean =>
+        val.isSerializable || isPlain(val)
+      const getEntries = (val: any): [string, any][] =>
+        val.isSerializable ? val.entries() : Object.entries(val)
+
+      const reducer: Reducer = (state = initialState, action) => {
+        switch (action.type) {
+          case ACTION_TYPE: {
+            return {
+              a: serializableObject,
+            }
+          }
+          default:
+            return state
+        }
+      }
+
+      const serializableStateInvariantMiddleware =
+        createSerializableStateInvariantMiddleware({
+          isSerializable,
+          getEntries,
+        })
+
+      const store = configureStore({
+        reducer: {
+          testSlice: reducer,
+        },
+        middleware: () => new Tuple(serializableStateInvariantMiddleware),
+      })
+
+      store.dispatch({ type: ACTION_TYPE })
+
+      expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+      // error reported is from a nested class instance, rather than the `entries` function `serializableObject`
+      expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+        `A non-serializable value was detected in the state, in the path: \`testSlice.a.third.bad-map-instance\`. Value:`,
+        nonSerializableValue,
+        `\nTake a look at the reducer(s) handling this action type: TEST_ACTION.
+(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`,
+      )
+    })
+  })
+
+  it('Should use the supplied isSerializable function to determine serializability', () => {
+    const ACTION_TYPE = 'TEST_ACTION'
+
+    const initialState = {
+      a: 0,
+    }
+
+    const badValue = new Map()
+
+    const reducer: Reducer = (state = initialState, action) => {
+      switch (action.type) {
+        case ACTION_TYPE: {
+          return {
+            a: badValue,
+          }
+        }
+        default:
+          return state
+      }
+    }
+
+    const serializableStateInvariantMiddleware =
+      createSerializableStateInvariantMiddleware({
+        isSerializable: () => true,
+      })
+
+    const store = configureStore({
+      reducer: {
+        testSlice: reducer,
+      },
+      middleware: () => new Tuple(serializableStateInvariantMiddleware),
+    })
+
+    store.dispatch({ type: ACTION_TYPE })
+
+    // Supplied 'isSerializable' considers all values serializable, hence
+    // no error logging is expected:
+    expect(consoleErrorSpy).not.toHaveBeenCalled()
+  })
+
+  it('should not check serializability for ignored action types', () => {
+    let numTimesCalled = 0
+
+    const serializableStateMiddleware =
+      createSerializableStateInvariantMiddleware({
+        isSerializable: () => {
+          numTimesCalled++
+          return true
+        },
+        ignoredActions: ['IGNORE_ME'],
+      })
+
+    const store = configureStore({
+      reducer: () => ({}),
+      middleware: () => new Tuple(serializableStateMiddleware),
+    })
+
+    expect(numTimesCalled).toBe(0)
+
+    store.dispatch({ type: 'IGNORE_ME' })
+
+    // The state check only calls `isSerializable` once
+    expect(numTimesCalled).toBe(1)
+
+    store.dispatch({ type: 'ANY_OTHER_ACTION' })
+
+    // Action checks call `isSerializable` 2+ times when enabled
+    expect(numTimesCalled).toBeGreaterThanOrEqual(3)
+  })
+
+  describe('ignored action paths', () => {
+    function reducer() {
+      return 0
+    }
+    const nonSerializableValue = new Map()
+
+    it('default value: meta.arg', () => {
+      configureStore({
+        reducer,
+        middleware: () =>
+          new Tuple(createSerializableStateInvariantMiddleware()),
+      }).dispatch({ type: 'test', meta: { arg: nonSerializableValue } })
+
+      expect(consoleErrorSpy).not.toHaveBeenCalled()
+    })
+
+    it('default value can be overridden', () => {
+      configureStore({
+        reducer,
+        middleware: () =>
+          new Tuple(
+            createSerializableStateInvariantMiddleware({
+              ignoredActionPaths: [],
+            }),
+          ),
+      }).dispatch({ type: 'test', meta: { arg: nonSerializableValue } })
+
+      expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+      expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+        `A non-serializable value was detected in an action, in the path: \`meta.arg\`. Value:`,
+        nonSerializableValue,
+        `\nTake a look at the logic that dispatched this action: `,
+        { type: 'test', meta: { arg: nonSerializableValue } },
+        `\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)`,
+        `\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)`,
+      )
+    })
+
+    it('can specify (multiple) different values', () => {
+      configureStore({
+        reducer,
+        middleware: () =>
+          new Tuple(
+            createSerializableStateInvariantMiddleware({
+              ignoredActionPaths: ['payload', 'meta.arg'],
+            }),
+          ),
+      }).dispatch({
+        type: 'test',
+        payload: { arg: nonSerializableValue },
+        meta: { arg: nonSerializableValue },
+      })
+
+      expect(consoleErrorSpy).not.toHaveBeenCalled()
+    })
+
+    it('can specify regexp', () => {
+      configureStore({
+        reducer,
+        middleware: () =>
+          new Tuple(
+            createSerializableStateInvariantMiddleware({
+              ignoredActionPaths: [/^payload\..*$/],
+            }),
+          ),
+      }).dispatch({
+        type: 'test',
+        payload: { arg: nonSerializableValue },
+      })
+
+      expect(consoleErrorSpy).not.toHaveBeenCalled()
+    })
+  })
+
+  it('allows ignoring actions entirely', () => {
+    let numTimesCalled = 0
+
+    const serializableStateMiddleware =
+      createSerializableStateInvariantMiddleware({
+        isSerializable: () => {
+          numTimesCalled++
+          return true
+        },
+        ignoreActions: true,
+      })
+
+    const store = configureStore({
+      reducer: () => ({}),
+      middleware: () => new Tuple(serializableStateMiddleware),
+    })
+
+    expect(numTimesCalled).toBe(0)
+
+    store.dispatch({ type: 'THIS_DOESNT_MATTER' })
+
+    // `isSerializable` is called once for a state check
+    expect(numTimesCalled).toBe(1)
+
+    store.dispatch({ type: 'THIS_DOESNT_MATTER_AGAIN' })
+
+    expect(numTimesCalled).toBe(2)
+  })
+
+  it('should not check serializability for ignored slice names', () => {
+    const ACTION_TYPE = 'TEST_ACTION'
+
+    const initialState = {
+      a: 0,
+    }
+
+    const badValue = new Map()
+
+    const reducer: Reducer = (state = initialState, action) => {
+      switch (action.type) {
+        case ACTION_TYPE: {
+          return {
+            a: badValue,
+            b: {
+              c: badValue,
+              d: badValue,
+            },
+            e: { f: badValue },
+            g: {
+              h: badValue,
+              i: badValue,
+            },
+          }
+        }
+        default:
+          return state
+      }
+    }
+
+    const serializableStateInvariantMiddleware =
+      createSerializableStateInvariantMiddleware({
+        ignoredPaths: [
+          // Test for ignoring a single value
+          'testSlice.a',
+          // Test for ignoring a single nested value
+          'testSlice.b.c',
+          // Test for ignoring an object and its children
+          'testSlice.e',
+          // Test for ignoring based on RegExp
+          /^testSlice\.g\..*$/,
+        ],
+      })
+
+    const store = configureStore({
+      reducer: {
+        testSlice: reducer,
+      },
+      middleware: () => new Tuple(serializableStateInvariantMiddleware),
+    })
+
+    store.dispatch({ type: ACTION_TYPE })
+
+    expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+    // testSlice.b.d was not covered in ignoredPaths, so will still log the error
+    expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+      `A non-serializable value was detected in the state, in the path: \`testSlice.b.d\`. Value:`,
+      badValue,
+      `\nTake a look at the reducer(s) handling this action type: TEST_ACTION.
+(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`,
+    )
+  })
+
+  it('allows ignoring state entirely', () => {
+    const badValue = new Map()
+    let numTimesCalled = 0
+    const reducer = () => badValue
+    const store = configureStore({
+      reducer,
+      middleware: () =>
+        new Tuple(
+          createSerializableStateInvariantMiddleware({
+            isSerializable: () => {
+              numTimesCalled++
+              return true
+            },
+            ignoreState: true,
+          }),
+        ),
+    })
+
+    expect(numTimesCalled).toBe(0)
+
+    store.dispatch({ type: 'test' })
+
+    expect(consoleErrorSpy).not.toHaveBeenCalled()
+
+    // Should be called twice for the action - there is an initial check for early returns, then a second and potentially 3rd for nested properties
+    expect(numTimesCalled).toBe(2)
+  })
+
+  it('never calls isSerializable if both ignoreState and ignoreActions are true', () => {
+    const badValue = new Map()
+    let numTimesCalled = 0
+    const reducer = () => badValue
+    const store = configureStore({
+      reducer,
+      middleware: () =>
+        new Tuple(
+          createSerializableStateInvariantMiddleware({
+            isSerializable: () => {
+              numTimesCalled++
+              return true
+            },
+            ignoreState: true,
+            ignoreActions: true,
+          }),
+        ),
+    })
+
+    expect(numTimesCalled).toBe(0)
+
+    store.dispatch({ type: 'TEST', payload: new Date() })
+    store.dispatch({ type: 'OTHER_THING' })
+
+    expect(numTimesCalled).toBe(0)
+  })
+
+  it('Should print a warning if execution takes too long', () => {
+    const reducer: Reducer = (state = 42, action) => {
+      return state
+    }
+
+    const serializableStateInvariantMiddleware =
+      createSerializableStateInvariantMiddleware({ warnAfter: 4 })
+
+    const store = configureStore({
+      reducer: {
+        testSlice: reducer,
+      },
+      middleware: () => new Tuple(serializableStateInvariantMiddleware),
+    })
+
+    store.dispatch({
+      type: 'SOME_ACTION',
+      payload: new Array(10_000).fill({ value: 'more' }),
+    })
+
+    expect(consoleWarnSpy).toHaveBeenCalledOnce()
+
+    expect(consoleWarnSpy).toHaveBeenLastCalledWith(
+      expect.stringMatching(
+        /^SerializableStateInvariantMiddleware took \d*ms, which is more than the warning threshold of 4ms./,
+      ),
+    )
+  })
+
+  it('Should not print a warning if "reducer" takes too long', () => {
+    const reducer: Reducer = (state = 42, action) => {
+      const started = Date.now()
+      while (Date.now() - started < 8) {}
+      return state
+    }
+
+    const serializableStateInvariantMiddleware =
+      createSerializableStateInvariantMiddleware({ warnAfter: 4 })
+
+    const store = configureStore({
+      reducer: {
+        testSlice: reducer,
+      },
+      middleware: () => new Tuple(serializableStateInvariantMiddleware),
+    })
+
+    store.dispatch({ type: 'SOME_ACTION' })
+
+    expect(consoleErrorSpy).not.toHaveBeenCalled()
+  })
+
+  it('Should cache its results', () => {
+    let numPlainChecks = 0
+    const countPlainChecks = (x: any) => {
+      numPlainChecks++
+      return isPlain(x)
+    }
+
+    const serializableStateInvariantMiddleware =
+      createSerializableStateInvariantMiddleware({
+        isSerializable: countPlainChecks,
+      })
+
+    const store = configureStore({
+      reducer: (state = [], action) => {
+        if (action.type === 'SET_STATE') return action.payload
+        return state
+      },
+      middleware: () => new Tuple(serializableStateInvariantMiddleware),
+    })
+
+    const state = createNextState([], () =>
+      new Array(50).fill(0).map((x, i) => ({ i })),
+    )
+    expect(isNestedFrozen(state)).toBe(true)
+
+    store.dispatch({
+      type: 'SET_STATE',
+      payload: state,
+    })
+    expect(numPlainChecks).toBeGreaterThan(state.length)
+
+    numPlainChecks = 0
+    store.dispatch({ type: 'NOOP' })
+    expect(numPlainChecks).toBeLessThan(10)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/utils/CustomMatchers.d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/utils/CustomMatchers.d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/utils/CustomMatchers.d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,16 @@
+import type { Assertion, AsymmetricMatchersContaining } from 'vitest'
+
+interface CustomMatchers<R = unknown> {
+  toMatchSequence(...matchers: Array<(arg: any) => boolean>): R
+}
+
+declare module 'vitest' {
+  interface Assertion<T = any> extends CustomMatchers<T> {}
+  interface AsymmetricMatchersContaining extends CustomMatchers {}
+}
+
+declare global {
+  namespace jest {
+    interface Matchers<R> extends CustomMatchers<R> {}
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/tests/utils/helpers.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/utils/helpers.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/utils/helpers.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,217 @@
+import type {
+  EnhancedStore,
+  Middleware,
+  Reducer,
+  Store,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import { configureStore } from '@reduxjs/toolkit'
+import { setupListeners } from '@reduxjs/toolkit/query'
+import { useCallback, useEffect, useRef } from 'react'
+
+import { Provider } from 'react-redux'
+
+import { act, cleanup } from '@testing-library/react'
+
+export const ANY = 0 as any
+
+export const DEFAULT_DELAY_MS = 150
+
+export const getSerializedHeaders = (headers: Headers = new Headers()) => {
+  const result: Record<string, string> = {}
+  headers.forEach((val, key) => {
+    result[key] = val
+  })
+  return result
+}
+
+export async function waitMs(time = DEFAULT_DELAY_MS) {
+  const now = Date.now()
+  while (Date.now() < now + time) {
+    await new Promise((res) => process.nextTick(res))
+  }
+}
+
+export function waitForFakeTimer(time = DEFAULT_DELAY_MS) {
+  return new Promise((resolve) => setTimeout(resolve, time))
+}
+
+export function withProvider(store: Store<any>) {
+  return function Wrapper({ children }: any) {
+    return <Provider store={store}>{children}</Provider>
+  }
+}
+
+export const hookWaitFor = async (cb: () => void, time = 2000) => {
+  const startedAt = Date.now()
+
+  while (true) {
+    try {
+      cb()
+      return true
+    } catch (e) {
+      if (Date.now() > startedAt + time) {
+        throw e
+      }
+      await act(async () => {
+        await waitMs(2)
+      })
+    }
+  }
+}
+export const fakeTimerWaitFor = async (cb: () => void, time = 2000) => {
+  const startedAt = Date.now()
+
+  while (true) {
+    try {
+      cb()
+      return true
+    } catch (e) {
+      if (Date.now() > startedAt + time) {
+        throw e
+      }
+      await act(async () => {
+        await vi.advanceTimersByTimeAsync(2)
+      })
+    }
+  }
+}
+
+export const useRenderCounter = () => {
+  const countRef = useRef(0)
+
+  useEffect(() => {
+    countRef.current += 1
+  })
+
+  useEffect(() => {
+    return () => {
+      countRef.current = 0
+    }
+  }, [])
+
+  return useCallback(() => countRef.current, [])
+}
+
+expect.extend({
+  toMatchSequence(
+    _actions: UnknownAction[],
+    ...matchers: Array<(arg: any) => boolean>
+  ) {
+    const actions = _actions.concat()
+    actions.shift() // remove INIT
+
+    for (let i = 0; i < matchers.length; i++) {
+      if (!matchers[i](actions[i])) {
+        return {
+          message: () =>
+            `Action ${actions[i].type} does not match sequence at position ${i}.
+All actions:
+${actions.map((a) => a.type).join('\n')}`,
+          pass: false,
+        }
+      }
+    }
+    return {
+      message: () => `All actions match the sequence.`,
+      pass: true,
+    }
+  },
+})
+
+export const actionsReducer = {
+  actions: (state: UnknownAction[] = [], action: UnknownAction) => {
+    // As of 2.0-beta.4, we are going to ignore all `subscriptionsUpdated` actions in tests
+    if (action.type.includes('subscriptionsUpdated')) {
+      return state
+    }
+
+    return [...state, action]
+  },
+}
+
+export function setupApiStore<
+  A extends {
+    reducerPath: 'api'
+    reducer: Reducer<any, any>
+    middleware: Middleware
+    util: { resetApiState(): any }
+  },
+  R extends Record<string, Reducer<any, any>> = Record<never, never>,
+>(
+  api: A,
+  extraReducers?: R,
+  options: {
+    withoutListeners?: boolean
+    withoutTestLifecycles?: boolean
+    middleware?: {
+      prepend?: Middleware[]
+      concat?: Middleware[]
+    }
+  } = {},
+) {
+  const { middleware } = options
+  const getStore = () =>
+    configureStore({
+      reducer: { api: api.reducer, ...extraReducers },
+      middleware: (gdm) => {
+        const tempMiddleware = gdm({
+          serializableCheck: false,
+          immutableCheck: false,
+        }).concat(api.middleware)
+
+        return tempMiddleware
+          .concat(middleware?.concat ?? [])
+          .prepend(middleware?.prepend ?? []) as typeof tempMiddleware
+      },
+      enhancers: (gde) =>
+        gde({
+          autoBatch: false,
+        }),
+    })
+
+  type State = {
+    api: ReturnType<A['reducer']>
+  } & {
+    [K in keyof R]: ReturnType<R[K]>
+  }
+  type StoreType = EnhancedStore<
+    {
+      api: ReturnType<A['reducer']>
+    } & {
+      [K in keyof R]: ReturnType<R[K]>
+    },
+    UnknownAction,
+    ReturnType<typeof getStore> extends EnhancedStore<any, any, infer M>
+      ? M
+      : never
+  >
+
+  const initialStore = getStore() as StoreType
+  const refObj = {
+    api,
+    store: initialStore,
+    wrapper: withProvider(initialStore),
+  }
+  let cleanupListeners: () => void
+
+  if (!options.withoutTestLifecycles) {
+    beforeEach(() => {
+      const store = getStore() as StoreType
+      refObj.store = store
+      refObj.wrapper = withProvider(store)
+      if (!options.withoutListeners) {
+        cleanupListeners = setupListeners(store.dispatch)
+      }
+    })
+    afterEach(() => {
+      cleanup()
+      if (!options.withoutListeners) {
+        cleanupListeners()
+      }
+      refObj.store.dispatch(api.util.resetApiState())
+    })
+  }
+
+  return refObj
+}
Index: node_modules/@reduxjs/toolkit/src/tsHelpers.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tsHelpers.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tsHelpers.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,223 @@
+import type { Middleware, StoreEnhancer } from 'redux'
+import type { Tuple } from './utils'
+
+export function safeAssign<T extends object>(
+  target: T,
+  ...args: Array<Partial<NoInfer<T>>>
+) {
+  Object.assign(target, ...args)
+}
+
+/**
+ * return True if T is `any`, otherwise return False
+ * taken from https://github.com/joonhocho/tsdef
+ *
+ * @internal
+ */
+export type IsAny<T, True, False = never> =
+  // test if we are going the left AND right path in the condition
+  true | false extends (T extends never ? true : false) ? True : False
+
+export type CastAny<T, CastTo> = IsAny<T, CastTo, T>
+
+/**
+ * return True if T is `unknown`, otherwise return False
+ * taken from https://github.com/joonhocho/tsdef
+ *
+ * @internal
+ */
+export type IsUnknown<T, True, False = never> = unknown extends T
+  ? IsAny<T, False, True>
+  : False
+
+export type FallbackIfUnknown<T, Fallback> = IsUnknown<T, Fallback, T>
+
+/**
+ * @internal
+ */
+export type IfMaybeUndefined<P, True, False> = [undefined] extends [P]
+  ? True
+  : False
+
+/**
+ * @internal
+ */
+export type IfVoid<P, True, False> = [void] extends [P] ? True : False
+
+/**
+ * @internal
+ */
+export type IsEmptyObj<T, True, False = never> = T extends any
+  ? keyof T extends never
+    ? IsUnknown<T, False, IfMaybeUndefined<T, False, IfVoid<T, False, True>>>
+    : False
+  : never
+
+/**
+ * returns True if TS version is above 3.5, False if below.
+ * uses feature detection to detect TS version >= 3.5
+ * * versions below 3.5 will return `{}` for unresolvable interference
+ * * versions above will return `unknown`
+ *
+ * @internal
+ */
+export type AtLeastTS35<True, False> = [True, False][IsUnknown<
+  ReturnType<<T>() => T>,
+  0,
+  1
+>]
+
+/**
+ * @internal
+ */
+export type IsUnknownOrNonInferrable<T, True, False> = AtLeastTS35<
+  IsUnknown<T, True, False>,
+  IsEmptyObj<T, True, IsUnknown<T, True, False>>
+>
+
+/**
+ * Convert a Union type `(A|B)` to an intersection type `(A&B)`
+ */
+export type UnionToIntersection<U> = (
+  U extends any ? (k: U) => void : never
+) extends (k: infer I) => void
+  ? I
+  : never
+
+// Appears to have a convenient side effect of ignoring `never` even if that's not what you specified
+export type ExcludeFromTuple<T, E, Acc extends unknown[] = []> = T extends [
+  infer Head,
+  ...infer Tail,
+]
+  ? ExcludeFromTuple<Tail, E, [...Acc, ...([Head] extends [E] ? [] : [Head])]>
+  : Acc
+
+type ExtractDispatchFromMiddlewareTuple<
+  MiddlewareTuple extends readonly any[],
+  Acc extends {},
+> = MiddlewareTuple extends [infer Head, ...infer Tail]
+  ? ExtractDispatchFromMiddlewareTuple<
+      Tail,
+      Acc & (Head extends Middleware<infer D> ? IsAny<D, {}, D> : {})
+    >
+  : Acc
+
+export type ExtractDispatchExtensions<M> =
+  M extends Tuple<infer MiddlewareTuple>
+    ? ExtractDispatchFromMiddlewareTuple<MiddlewareTuple, {}>
+    : M extends ReadonlyArray<Middleware>
+      ? ExtractDispatchFromMiddlewareTuple<[...M], {}>
+      : never
+
+type ExtractStoreExtensionsFromEnhancerTuple<
+  EnhancerTuple extends readonly any[],
+  Acc extends {},
+> = EnhancerTuple extends [infer Head, ...infer Tail]
+  ? ExtractStoreExtensionsFromEnhancerTuple<
+      Tail,
+      Acc & (Head extends StoreEnhancer<infer Ext> ? IsAny<Ext, {}, Ext> : {})
+    >
+  : Acc
+
+export type ExtractStoreExtensions<E> =
+  E extends Tuple<infer EnhancerTuple>
+    ? ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple, {}>
+    : E extends ReadonlyArray<StoreEnhancer>
+      ? UnionToIntersection<
+          E[number] extends StoreEnhancer<infer Ext>
+            ? Ext extends {}
+              ? IsAny<Ext, {}, Ext>
+              : {}
+            : {}
+        >
+      : never
+
+type ExtractStateExtensionsFromEnhancerTuple<
+  EnhancerTuple extends readonly any[],
+  Acc extends {},
+> = EnhancerTuple extends [infer Head, ...infer Tail]
+  ? ExtractStateExtensionsFromEnhancerTuple<
+      Tail,
+      Acc &
+        (Head extends StoreEnhancer<any, infer StateExt>
+          ? IsAny<StateExt, {}, StateExt>
+          : {})
+    >
+  : Acc
+
+export type ExtractStateExtensions<E> =
+  E extends Tuple<infer EnhancerTuple>
+    ? ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple, {}>
+    : E extends ReadonlyArray<StoreEnhancer>
+      ? UnionToIntersection<
+          E[number] extends StoreEnhancer<any, infer StateExt>
+            ? StateExt extends {}
+              ? IsAny<StateExt, {}, StateExt>
+              : {}
+            : {}
+        >
+      : never
+
+/**
+ * Helper type. Passes T out again, but boxes it in a way that it cannot
+ * "widen" the type by accident if it is a generic that should be inferred
+ * from elsewhere.
+ *
+ * @internal
+ */
+export type NoInfer<T> = [T][T extends any ? 0 : never]
+
+export type NonUndefined<T> = T extends undefined ? never : T
+
+export type WithRequiredProp<T, K extends keyof T> = Omit<T, K> &
+  Required<Pick<T, K>>
+
+export type WithOptionalProp<T, K extends keyof T> = Omit<T, K> &
+  Partial<Pick<T, K>>
+
+export interface TypeGuard<T> {
+  (value: any): value is T
+}
+
+export interface HasMatchFunction<T> {
+  match: TypeGuard<T>
+}
+
+export const hasMatchFunction = <T>(
+  v: Matcher<T>,
+): v is HasMatchFunction<T> => {
+  return v && typeof (v as HasMatchFunction<T>).match === 'function'
+}
+
+/** @public */
+export type Matcher<T> = HasMatchFunction<T> | TypeGuard<T>
+
+/** @public */
+export type ActionFromMatcher<M extends Matcher<any>> =
+  M extends Matcher<infer T> ? T : never
+
+export type Id<T> = { [K in keyof T]: T[K] } & {}
+
+export type Tail<T extends any[]> = T extends [any, ...infer Tail]
+  ? Tail
+  : never
+
+export type UnknownIfNonSpecific<T> = {} extends T ? unknown : T
+
+/**
+ * A Promise that will never reject.
+ * @see https://github.com/reduxjs/redux-toolkit/issues/4101
+ */
+export type SafePromise<T> = Promise<T> & {
+  __linterBrands: 'SafePromise'
+}
+
+/**
+ * Properly wraps a Promise as a {@link SafePromise} with .catch(fallback).
+ */
+export function asSafePromise<Resolved, Rejected>(
+  promise: Promise<Resolved>,
+  fallback: (error: unknown) => Rejected,
+) {
+  return promise.catch(fallback) as SafePromise<Resolved | Rejected>
+}
Index: node_modules/@reduxjs/toolkit/src/uncheckedindexed.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/uncheckedindexed.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/uncheckedindexed.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,16 @@
+// inlined from https://github.com/EskiMojo14/uncheckedindexed
+// relies on remaining as a TS file, not .d.ts
+type IfMaybeUndefined<T, True, False> = [undefined] extends [T] ? True : False
+
+const testAccess = ({} as Record<string, 0>)['a']
+
+export type IfUncheckedIndexedAccess<True, False> = IfMaybeUndefined<
+  typeof testAccess,
+  True,
+  False
+>
+
+export type UncheckedIndexedAccess<T> = IfUncheckedIndexedAccess<
+  T | undefined,
+  T
+>
Index: node_modules/@reduxjs/toolkit/src/utils.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/utils.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/utils.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,125 @@
+import { createNextState, isDraftable } from './immerImports'
+
+export function getTimeMeasureUtils(maxDelay: number, fnName: string) {
+  let elapsed = 0
+  return {
+    measureTime<T>(fn: () => T): T {
+      const started = Date.now()
+      try {
+        return fn()
+      } finally {
+        const finished = Date.now()
+        elapsed += finished - started
+      }
+    },
+    warnIfExceeded() {
+      if (elapsed > maxDelay) {
+        console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms. 
+If your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.
+It is disabled in production builds, so you don't need to worry about that.`)
+      }
+    },
+  }
+}
+
+export function delay(ms: number) {
+  return new Promise((resolve) => setTimeout(resolve, ms))
+}
+
+export class Tuple<Items extends ReadonlyArray<unknown> = []> extends Array<
+  Items[number]
+> {
+  constructor(length: number)
+  constructor(...items: Items)
+  constructor(...items: any[]) {
+    super(...items)
+    Object.setPrototypeOf(this, Tuple.prototype)
+  }
+
+  static override get [Symbol.species]() {
+    return Tuple as any
+  }
+
+  override concat<AdditionalItems extends ReadonlyArray<unknown>>(
+    items: Tuple<AdditionalItems>,
+  ): Tuple<[...Items, ...AdditionalItems]>
+  override concat<AdditionalItems extends ReadonlyArray<unknown>>(
+    items: AdditionalItems,
+  ): Tuple<[...Items, ...AdditionalItems]>
+  override concat<AdditionalItems extends ReadonlyArray<unknown>>(
+    ...items: AdditionalItems
+  ): Tuple<[...Items, ...AdditionalItems]>
+  override concat(...arr: any[]) {
+    return super.concat.apply(this, arr)
+  }
+
+  prepend<AdditionalItems extends ReadonlyArray<unknown>>(
+    items: Tuple<AdditionalItems>,
+  ): Tuple<[...AdditionalItems, ...Items]>
+  prepend<AdditionalItems extends ReadonlyArray<unknown>>(
+    items: AdditionalItems,
+  ): Tuple<[...AdditionalItems, ...Items]>
+  prepend<AdditionalItems extends ReadonlyArray<unknown>>(
+    ...items: AdditionalItems
+  ): Tuple<[...AdditionalItems, ...Items]>
+  prepend(...arr: any[]) {
+    if (arr.length === 1 && Array.isArray(arr[0])) {
+      return new Tuple(...arr[0].concat(this))
+    }
+    return new Tuple(...arr.concat(this))
+  }
+}
+
+export function freezeDraftable<T>(val: T) {
+  return isDraftable(val) ? createNextState(val, () => {}) : val
+}
+
+export function getOrInsert<K extends object, V>(
+  map: WeakMap<K, V>,
+  key: K,
+  value: V,
+): V
+export function getOrInsert<K, V>(map: Map<K, V>, key: K, value: V): V
+export function getOrInsert<K extends object, V>(
+  map: Map<K, V> | WeakMap<K, V>,
+  key: K,
+  value: V,
+): V {
+  if (map.has(key)) return map.get(key) as V
+
+  return map.set(key, value).get(key) as V
+}
+
+export function getOrInsertComputed<K extends object, V>(
+  map: WeakMap<K, V>,
+  key: K,
+  compute: (key: K) => V,
+): V
+export function getOrInsertComputed<K, V>(
+  map: Map<K, V>,
+  key: K,
+  compute: (key: K) => V,
+): V
+export function getOrInsertComputed<K extends object, V>(
+  map: Map<K, V> | WeakMap<K, V>,
+  key: K,
+  compute: (key: K) => V,
+): V {
+  if (map.has(key)) return map.get(key) as V
+
+  return map.set(key, compute(key)).get(key) as V
+}
+
+export function promiseWithResolvers<T>(): {
+  promise: Promise<T>
+  resolve: (value: T | PromiseLike<T>) => void
+  reject: (reason?: any) => void
+} {
+  let resolve: any
+  let reject: any
+  const promise = new Promise<T>((res, rej) => {
+    resolve = res
+    reject = rej
+  })
+  return { promise, resolve, reject }
+}
