{"version":3,"sources":["../../../src/query/index.ts","../../../src/query/core/apiState.ts","../../../src/index.ts","../../../src/createDraftSafeSelector.ts","../../../src/configureStore.ts","../../../src/devtoolsExtension.ts","../../../src/getDefaultMiddleware.ts","../../../src/createAction.ts","../../../src/tsHelpers.ts","../../../src/actionCreatorInvariantMiddleware.ts","../../../src/utils.ts","../../../src/immutableStateInvariantMiddleware.ts","../../../src/serializableStateInvariantMiddleware.ts","../../../src/autoBatchEnhancer.ts","../../../src/getDefaultEnhancers.ts","../../../src/createReducer.ts","../../../src/mapBuilders.ts","../../../src/matchers.ts","../../../src/nanoid.ts","../../../src/createAsyncThunk.ts","../../../src/createSlice.ts","../../../src/entities/entity_state.ts","../../../src/entities/state_selectors.ts","../../../src/entities/state_adapter.ts","../../../src/entities/utils.ts","../../../src/entities/unsorted_state_adapter.ts","../../../src/entities/sorted_state_adapter.ts","../../../src/entities/create_adapter.ts","../../../src/listenerMiddleware/index.ts","../../../src/listenerMiddleware/exceptions.ts","../../../src/listenerMiddleware/utils.ts","../../../src/listenerMiddleware/task.ts","../../../src/dynamicMiddleware/index.ts","../../../src/combineSlices.ts","../../../src/formatProdErrorMessage.ts","../../../src/query/utils/copyWithStructuralSharing.ts","../../../src/query/utils/countObjectKeys.ts","../../../src/query/utils/flatten.ts","../../../src/query/utils/isAbsoluteUrl.ts","../../../src/query/utils/isDocumentVisible.ts","../../../src/query/utils/isNotNullish.ts","../../../src/query/utils/isOnline.ts","../../../src/query/utils/joinUrls.ts","../../../src/query/utils/getOrInsert.ts","../../../src/query/fetchBaseQuery.ts","../../../src/query/HandledError.ts","../../../src/query/retry.ts","../../../src/query/core/setupListeners.ts","../../../src/query/endpointDefinitions.ts","../../../src/query/core/buildThunks.ts","../../../src/query/core/buildInitiate.ts","../../../src/query/standardSchema.ts","../../../src/query/core/buildSlice.ts","../../../src/query/core/buildSelectors.ts","../../../src/query/defaultSerializeQueryArgs.ts","../../../src/query/createApi.ts","../../../src/query/fakeBaseQuery.ts","../../../src/query/core/module.ts","../../../src/query/tsHelpers.ts","../../../src/query/core/buildMiddleware/batchActions.ts","../../../src/query/core/buildMiddleware/cacheCollection.ts","../../../src/query/core/buildMiddleware/cacheLifecycle.ts","../../../src/query/core/buildMiddleware/devMiddleware.ts","../../../src/query/core/buildMiddleware/invalidationByTags.ts","../../../src/query/core/buildMiddleware/polling.ts","../../../src/query/core/buildMiddleware/queryLifecycle.ts","../../../src/query/core/buildMiddleware/windowEventHandling.ts","../../../src/query/core/buildMiddleware/index.ts","../../../src/query/core/index.ts"],"sourcesContent":["// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from '@reduxjs/toolkit';\nexport type { CombinedState, QueryCacheKey, QueryKeys, QuerySubState, RootState, SubscriptionOptions } from './core/apiState';\nexport { QueryStatus } from './core/apiState';\nexport type { Api, ApiContext, Module } from './apiTypes';\nexport type { BaseQueryApi, BaseQueryArg, BaseQueryEnhancer, BaseQueryError, BaseQueryExtraOptions, BaseQueryFn, BaseQueryMeta, BaseQueryResult, QueryReturnValue } from './baseQueryTypes';\nexport 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 } from './endpointDefinitions';\nexport { fetchBaseQuery } from './fetchBaseQuery';\nexport type { FetchBaseQueryArgs, FetchBaseQueryError, FetchBaseQueryMeta, FetchArgs } from './fetchBaseQuery';\nexport { retry } from './retry';\nexport type { RetryOptions } from './retry';\nexport { setupListeners } from './core/setupListeners';\nexport { skipToken } from './core/buildSelectors';\nexport type { QueryResultSelectorResult, MutationResultSelectorResult, SkipToken } from './core/buildSelectors';\nexport type { QueryActionCreatorResult, MutationActionCreatorResult, StartQueryActionCreatorOptions } from './core/buildInitiate';\nexport type { CreateApi, CreateApiOptions } from './createApi';\nexport { buildCreateApi } from './createApi';\nexport { _NEVER, fakeBaseQuery } from './fakeBaseQuery';\nexport { copyWithStructuralSharing } from './utils/copyWithStructuralSharing';\nexport { createApi, coreModule, coreModuleName } from './core/index';\nexport type { InfiniteData, InfiniteQueryActionCreatorResult, InfiniteQueryConfigOptions, InfiniteQueryResultSelectorResult, InfiniteQuerySubState, TypedMutationOnQueryStarted, TypedQueryOnQueryStarted } from './core/index';\nexport type { ApiEndpointMutation, ApiEndpointQuery, ApiEndpointInfiniteQuery, ApiModules, CoreModule, PrefetchOptions } from './core/module';\nexport { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs';\nexport type { SerializeQueryArgs } from './defaultSerializeQueryArgs';\nexport type { Id as TSHelpersId, NoInfer as TSHelpersNoInfer, Override as TSHelpersOverride } from './tsHelpers';\nexport { NamedSchemaError } from './standardSchema';","import type { SerializedError } from '@reduxjs/toolkit';\nimport type { BaseQueryError } from '../baseQueryTypes';\nimport type { BaseEndpointDefinition, EndpointDefinitions, FullTagDescription, InfiniteQueryDefinition, MutationDefinition, PageParamFrom, QueryArgFromAnyQuery, QueryDefinition, ResultTypeFrom } from '../endpointDefinitions';\nimport type { Id, WithRequiredProp } from '../tsHelpers';\nexport type QueryCacheKey = string & {\n  _type: 'queryCacheKey';\n};\nexport type QuerySubstateIdentifier = {\n  queryCacheKey: QueryCacheKey;\n};\nexport type MutationSubstateIdentifier = {\n  requestId: string;\n  fixedCacheKey?: string;\n} | {\n  requestId?: string;\n  fixedCacheKey: string;\n};\nexport type RefetchConfigOptions = {\n  refetchOnMountOrArgChange: boolean | number;\n  refetchOnReconnect: boolean;\n  refetchOnFocus: boolean;\n};\nexport type InfiniteQueryConfigOptions<DataType, PageParam, QueryArg> = {\n  /**\n   * The initial page parameter to use for the first page fetch.\n   */\n  initialPageParam: PageParam;\n  /**\n   * This function is required to automatically get the next cursor for infinite queries.\n   * The result will also be used to determine the value of `hasNextPage`.\n   */\n  getNextPageParam: (lastPage: DataType, allPages: Array<DataType>, lastPageParam: PageParam, allPageParams: Array<PageParam>, queryArg: QueryArg) => PageParam | undefined | null;\n  /**\n   * This function can be set to automatically get the previous cursor for infinite queries.\n   * The result will also be used to determine the value of `hasPreviousPage`.\n   */\n  getPreviousPageParam?: (firstPage: DataType, allPages: Array<DataType>, firstPageParam: PageParam, allPageParams: Array<PageParam>, queryArg: QueryArg) => PageParam | undefined | null;\n  /**\n   * If specified, only keep this many pages in cache at once.\n   * If additional pages are fetched, older pages in the other\n   * direction will be dropped from the cache.\n   */\n  maxPages?: number;\n};\nexport type InfiniteData<DataType, PageParam> = {\n  pages: Array<DataType>;\n  pageParams: Array<PageParam>;\n};\n\n/**\n * Strings describing the query state at any given time.\n */\nexport enum QueryStatus {\n  uninitialized = 'uninitialized',\n  pending = 'pending',\n  fulfilled = 'fulfilled',\n  rejected = 'rejected',\n}\nexport type RequestStatusFlags = {\n  status: QueryStatus.uninitialized;\n  isUninitialized: true;\n  isLoading: false;\n  isSuccess: false;\n  isError: false;\n} | {\n  status: QueryStatus.pending;\n  isUninitialized: false;\n  isLoading: true;\n  isSuccess: false;\n  isError: false;\n} | {\n  status: QueryStatus.fulfilled;\n  isUninitialized: false;\n  isLoading: false;\n  isSuccess: true;\n  isError: false;\n} | {\n  status: QueryStatus.rejected;\n  isUninitialized: false;\n  isLoading: false;\n  isSuccess: false;\n  isError: true;\n};\nexport function getRequestStatusFlags(status: QueryStatus): RequestStatusFlags {\n  return {\n    status,\n    isUninitialized: status === QueryStatus.uninitialized,\n    isLoading: status === QueryStatus.pending,\n    isSuccess: status === QueryStatus.fulfilled,\n    isError: status === QueryStatus.rejected\n  } as any;\n}\n\n/**\n * @public\n */\nexport type SubscriptionOptions = {\n  /**\n   * How frequently to automatically re-fetch data (in milliseconds). Defaults to `0` (off).\n   */\n  pollingInterval?: number;\n  /**\n   *  Defaults to 'false'. This setting allows you to control whether RTK Query will continue polling if the window is not focused.\n   *\n   *  If pollingInterval is not set or set to 0, this **will not be evaluated** until pollingInterval is greater than 0.\n   *\n   *  Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  skipPollingIfUnfocused?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnReconnect?: boolean;\n  /**\n   * 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.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnFocus?: boolean;\n};\nexport type Subscribers = {\n  [requestId: string]: SubscriptionOptions;\n};\nexport type QueryKeys<Definitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any> ? K : never }[keyof Definitions];\nexport type InfiniteQueryKeys<Definitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends InfiniteQueryDefinition<any, any, any, any, any> ? K : never }[keyof Definitions];\nexport type MutationKeys<Definitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends MutationDefinition<any, any, any, any> ? K : never }[keyof Definitions];\ntype BaseQuerySubState<D extends BaseEndpointDefinition<any, any, any, any>, DataType = ResultTypeFrom<D>> = {\n  /**\n   * The argument originally passed into the hook or `initiate` action call\n   */\n  originalArgs: QueryArgFromAnyQuery<D>;\n  /**\n   * A unique ID associated with the request\n   */\n  requestId: string;\n  /**\n   * The received data from the query\n   */\n  data?: DataType;\n  /**\n   * The received error if applicable\n   */\n  error?: SerializedError | (D extends QueryDefinition<any, infer BaseQuery, any, any> ? BaseQueryError<BaseQuery> : never);\n  /**\n   * The name of the endpoint associated with the query\n   */\n  endpointName: string;\n  /**\n   * Time that the latest query started\n   */\n  startedTimeStamp: number;\n  /**\n   * Time that the latest query was fulfilled\n   */\n  fulfilledTimeStamp?: number;\n};\nexport type QuerySubState<D extends BaseEndpointDefinition<any, any, any, any>, DataType = ResultTypeFrom<D>> = Id<({\n  status: QueryStatus.fulfilled;\n} & WithRequiredProp<BaseQuerySubState<D, DataType>, 'data' | 'fulfilledTimeStamp'> & {\n  error: undefined;\n}) | ({\n  status: QueryStatus.pending;\n} & BaseQuerySubState<D, DataType>) | ({\n  status: QueryStatus.rejected;\n} & WithRequiredProp<BaseQuerySubState<D, DataType>, 'error'>) | {\n  status: QueryStatus.uninitialized;\n  originalArgs?: undefined;\n  data?: undefined;\n  error?: undefined;\n  requestId?: undefined;\n  endpointName?: string;\n  startedTimeStamp?: undefined;\n  fulfilledTimeStamp?: undefined;\n}>;\nexport type InfiniteQueryDirection = 'forward' | 'backward';\nexport type InfiniteQuerySubState<D extends BaseEndpointDefinition<any, any, any, any>> = D extends InfiniteQueryDefinition<any, any, any, any, any> ? QuerySubState<D, InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>> & {\n  direction?: InfiniteQueryDirection;\n} : never;\ntype BaseMutationSubState<D extends BaseEndpointDefinition<any, any, any, any>> = {\n  requestId: string;\n  data?: ResultTypeFrom<D>;\n  error?: SerializedError | (D extends MutationDefinition<any, infer BaseQuery, any, any> ? BaseQueryError<BaseQuery> : never);\n  endpointName: string;\n  startedTimeStamp: number;\n  fulfilledTimeStamp?: number;\n};\nexport type MutationSubState<D extends BaseEndpointDefinition<any, any, any, any>> = (({\n  status: QueryStatus.fulfilled;\n} & WithRequiredProp<BaseMutationSubState<D>, 'data' | 'fulfilledTimeStamp'>) & {\n  error: undefined;\n}) | (({\n  status: QueryStatus.pending;\n} & BaseMutationSubState<D>) & {\n  data?: undefined;\n}) | ({\n  status: QueryStatus.rejected;\n} & WithRequiredProp<BaseMutationSubState<D>, 'error'>) | {\n  requestId?: undefined;\n  status: QueryStatus.uninitialized;\n  data?: undefined;\n  error?: undefined;\n  endpointName?: string;\n  startedTimeStamp?: undefined;\n  fulfilledTimeStamp?: undefined;\n};\nexport type CombinedState<D extends EndpointDefinitions, E extends string, ReducerPath extends string> = {\n  queries: QueryState<D>;\n  mutations: MutationState<D>;\n  provided: InvalidationState<E>;\n  subscriptions: SubscriptionState;\n  config: ConfigState<ReducerPath>;\n};\nexport type InvalidationState<TagTypes extends string> = {\n  tags: { [_ in TagTypes]: {\n    [id: string]: Array<QueryCacheKey>;\n    [id: number]: Array<QueryCacheKey>;\n  } };\n  keys: Record<QueryCacheKey, Array<FullTagDescription<any>>>;\n};\nexport type QueryState<D extends EndpointDefinitions> = {\n  [queryCacheKey: string]: QuerySubState<D[string]> | InfiniteQuerySubState<D[string]> | undefined;\n};\nexport type SubscriptionState = {\n  [queryCacheKey: string]: Subscribers | undefined;\n};\nexport type ConfigState<ReducerPath> = RefetchConfigOptions & {\n  reducerPath: ReducerPath;\n  online: boolean;\n  focused: boolean;\n  middlewareRegistered: boolean | 'conflict';\n} & ModifiableConfigState;\nexport type ModifiableConfigState = {\n  keepUnusedDataFor: number;\n  invalidationBehavior: 'delayed' | 'immediately';\n} & RefetchConfigOptions;\nexport type MutationState<D extends EndpointDefinitions> = {\n  [requestId: string]: MutationSubState<D[string]> | undefined;\n};\nexport type RootState<Definitions extends EndpointDefinitions, TagTypes extends string, ReducerPath extends string> = { [P in ReducerPath]: CombinedState<Definitions, TagTypes, P> };","// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from './formatProdErrorMessage';\nexport * from 'redux';\nexport { produce as createNextState, current, freeze, original, isDraft } from 'immer';\nexport type { Draft } from 'immer';\nexport { createSelector, createSelectorCreator, lruMemoize, weakMapMemoize } from 'reselect';\nexport type { Selector, OutputSelector } from 'reselect';\nexport { createDraftSafeSelector, createDraftSafeSelectorCreator } from './createDraftSafeSelector';\nexport type { ThunkAction, ThunkDispatch, ThunkMiddleware } from 'redux-thunk';\nexport {\n// js\nconfigureStore } from './configureStore';\nexport type {\n// types\nConfigureStoreOptions, EnhancedStore } from './configureStore';\nexport type { DevToolsEnhancerOptions } from './devtoolsExtension';\nexport {\n// js\ncreateAction, isActionCreator, isFSA as isFluxStandardAction } from './createAction';\nexport type {\n// types\nPayloadAction, PayloadActionCreator, ActionCreatorWithNonInferrablePayload, ActionCreatorWithOptionalPayload, ActionCreatorWithPayload, ActionCreatorWithoutPayload, ActionCreatorWithPreparedPayload, PrepareAction } from './createAction';\nexport {\n// js\ncreateReducer } from './createReducer';\nexport type {\n// types\nActions, CaseReducer, CaseReducers } from './createReducer';\nexport {\n// js\ncreateSlice, buildCreateSlice, asyncThunkCreator, ReducerType } from './createSlice';\nexport type {\n// types\nCreateSliceOptions, Slice, CaseReducerActions, SliceCaseReducers, ValidateSliceCaseReducers, CaseReducerWithPrepare, ReducerCreators, SliceSelectors } from './createSlice';\nexport type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware';\nexport { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware';\nexport {\n// js\ncreateImmutableStateInvariantMiddleware, isImmutableDefault } from './immutableStateInvariantMiddleware';\nexport type {\n// types\nImmutableStateInvariantMiddlewareOptions } from './immutableStateInvariantMiddleware';\nexport {\n// js\ncreateSerializableStateInvariantMiddleware, findNonSerializableValue, isPlain } from './serializableStateInvariantMiddleware';\nexport type {\n// types\nSerializableStateInvariantMiddlewareOptions } from './serializableStateInvariantMiddleware';\nexport type {\n// types\nActionReducerMapBuilder } from './mapBuilders';\nexport { Tuple } from './utils';\nexport { createEntityAdapter } from './entities/create_adapter';\nexport type { EntityState, EntityAdapter, EntitySelectors, EntityStateAdapter, EntityId, Update, IdSelector, Comparer } from './entities/models';\nexport { createAsyncThunk, unwrapResult, miniSerializeError } from './createAsyncThunk';\nexport type { AsyncThunk, AsyncThunkOptions, AsyncThunkAction, AsyncThunkPayloadCreatorReturnValue, AsyncThunkPayloadCreator, GetState, GetThunkAPI, SerializedError, CreateAsyncThunkFunction } from './createAsyncThunk';\nexport {\n// js\nisAllOf, isAnyOf, isPending, isRejected, isFulfilled, isAsyncThunkAction, isRejectedWithValue } from './matchers';\nexport type {\n// types\nActionMatchingAllOf, ActionMatchingAnyOf } from './matchers';\nexport { nanoid } from './nanoid';\nexport 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';\nexport type { AnyListenerPredicate } from './listenerMiddleware/types';\nexport { createListenerMiddleware, addListener, removeListener, clearAllListeners, TaskAbortError } from './listenerMiddleware/index';\nexport type { AddMiddleware, DynamicDispatch, DynamicMiddlewareInstance, GetDispatchType as GetDispatch, MiddlewareApiConfig } from './dynamicMiddleware/types';\nexport { createDynamicMiddleware } from './dynamicMiddleware/index';\nexport { SHOULD_AUTOBATCH, prepareAutoBatched, autoBatchEnhancer } from './autoBatchEnhancer';\nexport type { AutoBatchOptions } from './autoBatchEnhancer';\nexport { combineSlices } from './combineSlices';\nexport type { CombinedSliceReducer, WithSlice } from './combineSlices';\nexport type { ExtractDispatchExtensions as TSHelpersExtractDispatchExtensions, SafePromise } from './tsHelpers';\nexport { formatProdErrorMessage } from './formatProdErrorMessage';","import { current, isDraft } from 'immer';\nimport { createSelectorCreator, weakMapMemoize } from 'reselect';\nexport const createDraftSafeSelectorCreator: typeof createSelectorCreator = (...args: unknown[]) => {\n  const createSelector = (createSelectorCreator as any)(...args);\n  const createDraftSafeSelector = Object.assign((...args: unknown[]) => {\n    const selector = createSelector(...args);\n    const wrappedSelector = (value: unknown, ...rest: unknown[]) => selector(isDraft(value) ? current(value) : value, ...rest);\n    Object.assign(wrappedSelector, selector);\n    return wrappedSelector as any;\n  }, {\n    withTypes: () => createDraftSafeSelector\n  });\n  return createDraftSafeSelector;\n};\n\n/**\n * \"Draft-Safe\" version of `reselect`'s `createSelector`:\n * If an `immer`-drafted object is passed into the resulting selector's first argument,\n * the selector will act on the current draft value, instead of returning a cached value\n * that might be possibly outdated if the draft has been modified since.\n * @public\n */\nexport const createDraftSafeSelector = /* @__PURE__ */\ncreateDraftSafeSelectorCreator(weakMapMemoize);","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3, formatProdErrorMessage as _formatProdErrorMessage4, formatProdErrorMessage as _formatProdErrorMessage5, formatProdErrorMessage as _formatProdErrorMessage6, formatProdErrorMessage as _formatProdErrorMessage7, formatProdErrorMessage as _formatProdErrorMessage8 } from \"@reduxjs/toolkit\";\nimport type { Reducer, ReducersMapObject, Middleware, Action, StoreEnhancer, Store, UnknownAction } from 'redux';\nimport { applyMiddleware, createStore, compose, combineReducers, isPlainObject } from 'redux';\nimport type { DevToolsEnhancerOptions as DevToolsOptions } from './devtoolsExtension';\nimport { composeWithDevTools } from './devtoolsExtension';\nimport type { ThunkMiddlewareFor, GetDefaultMiddleware } from './getDefaultMiddleware';\nimport { buildGetDefaultMiddleware } from './getDefaultMiddleware';\nimport type { ExtractDispatchExtensions, ExtractStoreExtensions, ExtractStateExtensions, UnknownIfNonSpecific } from './tsHelpers';\nimport type { Tuple } from './utils';\nimport type { GetDefaultEnhancers } from './getDefaultEnhancers';\nimport { buildGetDefaultEnhancers } from './getDefaultEnhancers';\n\n/**\n * Options for `configureStore()`.\n *\n * @public\n */\nexport interface ConfigureStoreOptions<S = any, A extends Action = UnknownAction, M extends Tuple<Middlewares<S>> = Tuple<Middlewares<S>>, E extends Tuple<Enhancers> = Tuple<Enhancers>, P = S> {\n  /**\n   * A single reducer function that will be used as the root reducer, or an\n   * object of slice reducers that will be passed to `combineReducers()`.\n   */\n  reducer: Reducer<S, A, P> | ReducersMapObject<S, A, P>;\n\n  /**\n   * An array of Redux middleware to install, or a callback receiving `getDefaultMiddleware` and returning a Tuple of middleware.\n   * If not supplied, defaults to the set of middleware returned by `getDefaultMiddleware()`.\n   *\n   * @example `middleware: (gDM) => gDM().concat(logger, apiMiddleware, yourCustomMiddleware)`\n   * @see https://redux-toolkit.js.org/api/getDefaultMiddleware#intended-usage\n   */\n  middleware?: (getDefaultMiddleware: GetDefaultMiddleware<S>) => M;\n\n  /**\n   * Whether to enable Redux DevTools integration. Defaults to `true`.\n   *\n   * Additional configuration can be done by passing Redux DevTools options\n   */\n  devTools?: boolean | DevToolsOptions;\n\n  /**\n   * Whether to check for duplicate middleware instances. Defaults to `true`.\n   */\n  duplicateMiddlewareCheck?: boolean;\n\n  /**\n   * The initial state, same as Redux's createStore.\n   * You may optionally specify it to hydrate the state\n   * from the server in universal apps, or to restore a previously serialized\n   * user session. If you use `combineReducers()` to produce the root reducer\n   * function (either directly or indirectly by passing an object as `reducer`),\n   * this must be an object with the same shape as the reducer map keys.\n   */\n  // we infer here, and instead complain if the reducer doesn't match\n  preloadedState?: P;\n\n  /**\n   * The store enhancers to apply. See Redux's `createStore()`.\n   * All enhancers will be included before the DevTools Extension enhancer.\n   * If you need to customize the order of enhancers, supply a callback\n   * function that will receive a `getDefaultEnhancers` function that returns a Tuple,\n   * and should return a Tuple of enhancers (such as `getDefaultEnhancers().concat(offline)`).\n   * If you only need to add middleware, you can use the `middleware` parameter instead.\n   */\n  enhancers?: (getDefaultEnhancers: GetDefaultEnhancers<M>) => E;\n}\nexport type Middlewares<S> = ReadonlyArray<Middleware<{}, S>>;\ntype Enhancers = ReadonlyArray<StoreEnhancer>;\n\n/**\n * A Redux store returned by `configureStore()`. Supports dispatching\n * side-effectful _thunks_ in addition to plain actions.\n *\n * @public\n */\nexport type EnhancedStore<S = any, A extends Action = UnknownAction, E extends Enhancers = Enhancers> = ExtractStoreExtensions<E> & Store<S, A, UnknownIfNonSpecific<ExtractStateExtensions<E>>>;\n\n/**\n * A friendly abstraction over the standard Redux `createStore()` function.\n *\n * @param options The store configuration.\n * @returns A configured Redux store.\n *\n * @public\n */\nexport function configureStore<S = any, A extends Action = UnknownAction, M extends Tuple<Middlewares<S>> = Tuple<[ThunkMiddlewareFor<S>]>, E extends Tuple<Enhancers> = Tuple<[StoreEnhancer<{\n  dispatch: ExtractDispatchExtensions<M>;\n}>, StoreEnhancer]>, P = S>(options: ConfigureStoreOptions<S, A, M, E, P>): EnhancedStore<S, A, E> {\n  const getDefaultMiddleware = buildGetDefaultMiddleware<S>();\n  const {\n    reducer = undefined,\n    middleware,\n    devTools = true,\n    duplicateMiddlewareCheck = true,\n    preloadedState = undefined,\n    enhancers = undefined\n  } = options || {};\n  let rootReducer: Reducer<S, A, P>;\n  if (typeof reducer === 'function') {\n    rootReducer = reducer;\n  } else if (isPlainObject(reducer)) {\n    rootReducer = combineReducers(reducer) as unknown as Reducer<S, A, P>;\n  } else {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(1) : '`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers');\n  }\n  if (process.env.NODE_ENV !== 'production' && middleware && typeof middleware !== 'function') {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(2) : '`middleware` field must be a callback');\n  }\n  let finalMiddleware: Tuple<Middlewares<S>>;\n  if (typeof middleware === 'function') {\n    finalMiddleware = middleware(getDefaultMiddleware);\n    if (process.env.NODE_ENV !== 'production' && !Array.isArray(finalMiddleware)) {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(3) : 'when using a middleware builder function, an array of middleware must be returned');\n    }\n  } else {\n    finalMiddleware = getDefaultMiddleware();\n  }\n  if (process.env.NODE_ENV !== 'production' && finalMiddleware.some((item: any) => typeof item !== 'function')) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage4(4) : 'each middleware provided to configureStore must be a function');\n  }\n  if (process.env.NODE_ENV !== 'production' && duplicateMiddlewareCheck) {\n    let middlewareReferences = new Set<Middleware<any, S>>();\n    finalMiddleware.forEach(middleware => {\n      if (middlewareReferences.has(middleware)) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage5(42) : 'Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.');\n      }\n      middlewareReferences.add(middleware);\n    });\n  }\n  let finalCompose = compose;\n  if (devTools) {\n    finalCompose = composeWithDevTools({\n      // Enable capture of stack traces for dispatched Redux actions\n      trace: process.env.NODE_ENV !== 'production',\n      ...(typeof devTools === 'object' && devTools)\n    });\n  }\n  const middlewareEnhancer = applyMiddleware(...finalMiddleware);\n  const getDefaultEnhancers = buildGetDefaultEnhancers<M>(middlewareEnhancer);\n  if (process.env.NODE_ENV !== 'production' && enhancers && typeof enhancers !== 'function') {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage6(5) : '`enhancers` field must be a callback');\n  }\n  let storeEnhancers = typeof enhancers === 'function' ? enhancers(getDefaultEnhancers) : getDefaultEnhancers();\n  if (process.env.NODE_ENV !== 'production' && !Array.isArray(storeEnhancers)) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage7(6) : '`enhancers` callback must return an array');\n  }\n  if (process.env.NODE_ENV !== 'production' && storeEnhancers.some((item: any) => typeof item !== 'function')) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage8(7) : 'each enhancer provided to configureStore must be a function');\n  }\n  if (process.env.NODE_ENV !== 'production' && finalMiddleware.length && !storeEnhancers.includes(middlewareEnhancer)) {\n    console.error('middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`');\n  }\n  const composedEnhancer: StoreEnhancer<any> = finalCompose(...storeEnhancers);\n  return createStore(rootReducer, preloadedState as P, composedEnhancer);\n}","import type { Action, ActionCreator, StoreEnhancer } from 'redux';\nimport { compose } from 'redux';\n\n/**\n * @public\n */\nexport interface DevToolsEnhancerOptions {\n  /**\n   * the instance name to be showed on the monitor page. Default value is `document.title`.\n   * If not specified and there's no document title, it will consist of `tabId` and `instanceId`.\n   */\n  name?: string;\n  /**\n   * action creators functions to be available in the Dispatcher.\n   */\n  actionCreators?: ActionCreator<any>[] | {\n    [key: string]: ActionCreator<any>;\n  };\n  /**\n   * if more than one action is dispatched in the indicated interval, all new actions will be collected and sent at once.\n   * It is the joint between performance and speed. When set to `0`, all actions will be sent instantly.\n   * Set it to a higher value when experiencing perf issues (also `maxAge` to a lower value).\n   *\n   * @default 500 ms.\n   */\n  latency?: number;\n  /**\n   * (> 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.\n   *\n   * @default 50\n   */\n  maxAge?: number;\n  /**\n   * 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\n   * were to pass an object and specify `options` as a boolean. Giving an object allows fine-grained customization using the `replacer` and `reviver`\n   * functions.\n   */\n  serialize?: boolean | {\n    /**\n     * - `undefined` - will use regular `JSON.stringify` to send data (it's the fast mode).\n     * - `false` - will handle also circular references.\n     * - `true` - will handle also date, regex, undefined, error objects, symbols, maps, sets and functions.\n     * - object, which contains `date`, `regex`, `undefined`, `error`, `symbol`, `map`, `set` and `function` keys.\n     *   For each of them you can indicate if to include (by setting as `true`).\n     *   For `function` key you can also specify a custom function which handles serialization.\n     *   See [`jsan`](https://github.com/kolodny/jsan) for more details.\n     */\n    options?: undefined | boolean | {\n      date?: true;\n      regex?: true;\n      undefined?: true;\n      error?: true;\n      symbol?: true;\n      map?: true;\n      set?: true;\n      function?: true | ((fn: (...args: any[]) => any) => string);\n    };\n    /**\n     * [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.\n     * In addition, you can specify a data type by adding a [`__serializedType__`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/helpers/index.js#L4)\n     * key. So you can deserialize it back while importing or persisting data.\n     * 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):\n     */\n    replacer?: (key: string, value: unknown) => any;\n    /**\n     * [JSON `reviver` function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter)\n     * used for parsing the imported actions and states. See [`remotedev-serialize`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/immutable/serialize.js#L8-L41)\n     * as an example on how to serialize special data types and get them back.\n     */\n    reviver?: (key: string, value: unknown) => any;\n    /**\n     * Automatically serialize/deserialize immutablejs via [remotedev-serialize](https://github.com/zalmoxisus/remotedev-serialize).\n     * Just pass the Immutable library. It will support all ImmutableJS structures. You can even export them into a file and get them back.\n     * The only exception is `Record` class, for which you should pass this in addition the references to your classes in `refs`.\n     */\n    immutable?: any;\n    /**\n     * ImmutableJS `Record` classes used to make possible restore its instances back when importing, persisting...\n     */\n    refs?: any;\n  };\n  /**\n   * function which takes `action` object and id number as arguments, and should return `action` object back.\n   */\n  actionSanitizer?: <A extends Action>(action: A, id: number) => A;\n  /**\n   * function which takes `state` object and index as arguments, and should return `state` object back.\n   */\n  stateSanitizer?: <S>(state: S, index: number) => S;\n  /**\n   * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).\n   * If `actionsAllowlist` specified, `actionsDenylist` is ignored.\n   */\n  actionsDenylist?: string | string[];\n  /**\n   * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).\n   * If `actionsAllowlist` specified, `actionsDenylist` is ignored.\n   */\n  actionsAllowlist?: string | string[];\n  /**\n   * 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.\n   * Use it as a more advanced version of `actionsDenylist`/`actionsAllowlist` parameters.\n   */\n  predicate?: <S, A extends Action>(state: S, action: A) => boolean;\n  /**\n   * if specified as `false`, it will not record the changes till clicking on `Start recording` button.\n   * Available only for Redux enhancer, for others use `autoPause`.\n   *\n   * @default true\n   */\n  shouldRecordChanges?: boolean;\n  /**\n   * if specified, whenever clicking on `Pause recording` button and there are actions in the history log, will add this action type.\n   * If not specified, will commit when paused. Available only for Redux enhancer.\n   *\n   * @default \"@@PAUSED\"\"\n   */\n  pauseActionType?: string;\n  /**\n   * auto pauses when the extension’s window is not opened, and so has zero impact on your app when not in use.\n   * Not available for Redux enhancer (as it already does it but storing the data to be sent).\n   *\n   * @default false\n   */\n  autoPause?: boolean;\n  /**\n   * if specified as `true`, it will not allow any non-monitor actions to be dispatched till clicking on `Unlock changes` button.\n   * Available only for Redux enhancer.\n   *\n   * @default false\n   */\n  shouldStartLocked?: boolean;\n  /**\n   * if set to `false`, will not recompute the states on hot reloading (or on replacing the reducers). Available only for Redux enhancer.\n   *\n   * @default true\n   */\n  shouldHotReload?: boolean;\n  /**\n   * 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.\n   *\n   * @default false\n   */\n  shouldCatchErrors?: boolean;\n  /**\n   * If you want to restrict the extension, specify the features you allow.\n   * If not specified, all of the features are enabled. When set as an object, only those included as `true` will be allowed.\n   * 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.\n   * Otherwise, you'll get/set the data right from the monitor part.\n   */\n  features?: {\n    /**\n     * start/pause recording of dispatched actions\n     */\n    pause?: boolean;\n    /**\n     * lock/unlock dispatching actions and side effects\n     */\n    lock?: boolean;\n    /**\n     * persist states on page reloading\n     */\n    persist?: boolean;\n    /**\n     * export history of actions in a file\n     */\n    export?: boolean | 'custom';\n    /**\n     * import history of actions from a file\n     */\n    import?: boolean | 'custom';\n    /**\n     * jump back and forth (time travelling)\n     */\n    jump?: boolean;\n    /**\n     * skip (cancel) actions\n     */\n    skip?: boolean;\n    /**\n     * drag and drop actions in the history list\n     */\n    reorder?: boolean;\n    /**\n     * dispatch custom actions or action creators\n     */\n    dispatch?: boolean;\n    /**\n     * generate tests for the selected actions\n     */\n    test?: boolean;\n  };\n  /**\n   * Set to true or a stacktrace-returning function to record call stack traces for dispatched actions.\n   * Defaults to false.\n   */\n  trace?: boolean | (<A extends Action>(action: A) => string);\n  /**\n   * The maximum number of stack trace entries to record per action. Defaults to 10.\n   */\n  traceLimit?: number;\n}\ntype Compose = typeof compose;\ninterface ComposeWithDevTools {\n  (options: DevToolsEnhancerOptions): Compose;\n  <StoreExt extends {}>(...funcs: StoreEnhancer<StoreExt>[]): StoreEnhancer<StoreExt>;\n}\n\n/**\n * @public\n */\nexport const composeWithDevTools: ComposeWithDevTools = typeof window !== 'undefined' && (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function () {\n  if (arguments.length === 0) return undefined;\n  if (typeof arguments[0] === 'object') return compose;\n  return compose.apply(null, arguments as any as Function[]);\n};\n\n/**\n * @public\n */\nexport const devToolsEnhancer: {\n  (options: DevToolsEnhancerOptions): StoreEnhancer<any>;\n} = typeof window !== 'undefined' && (window as any).__REDUX_DEVTOOLS_EXTENSION__ ? (window as any).__REDUX_DEVTOOLS_EXTENSION__ : function () {\n  return function (noop) {\n    return noop;\n  };\n};","import type { Middleware, UnknownAction } from 'redux';\nimport type { ThunkMiddleware } from 'redux-thunk';\nimport { thunk as thunkMiddleware, withExtraArgument } from 'redux-thunk';\nimport type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware';\nimport { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware';\nimport type { ImmutableStateInvariantMiddlewareOptions } from './immutableStateInvariantMiddleware';\n/* PROD_START_REMOVE_UMD */\nimport { createImmutableStateInvariantMiddleware } from './immutableStateInvariantMiddleware';\n/* PROD_STOP_REMOVE_UMD */\n\nimport type { SerializableStateInvariantMiddlewareOptions } from './serializableStateInvariantMiddleware';\nimport { createSerializableStateInvariantMiddleware } from './serializableStateInvariantMiddleware';\nimport type { ExcludeFromTuple } from './tsHelpers';\nimport { Tuple } from './utils';\nfunction isBoolean(x: any): x is boolean {\n  return typeof x === 'boolean';\n}\ninterface ThunkOptions<E = any> {\n  extraArgument: E;\n}\ninterface GetDefaultMiddlewareOptions {\n  thunk?: boolean | ThunkOptions;\n  immutableCheck?: boolean | ImmutableStateInvariantMiddlewareOptions;\n  serializableCheck?: boolean | SerializableStateInvariantMiddlewareOptions;\n  actionCreatorCheck?: boolean | ActionCreatorInvariantMiddlewareOptions;\n}\nexport type ThunkMiddlewareFor<S, O extends GetDefaultMiddlewareOptions = {}> = O extends {\n  thunk: false;\n} ? never : O extends {\n  thunk: {\n    extraArgument: infer E;\n  };\n} ? ThunkMiddleware<S, UnknownAction, E> : ThunkMiddleware<S, UnknownAction>;\nexport type GetDefaultMiddleware<S = any> = <O extends GetDefaultMiddlewareOptions = {\n  thunk: true;\n  immutableCheck: true;\n  serializableCheck: true;\n  actionCreatorCheck: true;\n}>(options?: O) => Tuple<ExcludeFromTuple<[ThunkMiddlewareFor<S, O>], never>>;\nexport const buildGetDefaultMiddleware = <S = any,>(): GetDefaultMiddleware<S> => function getDefaultMiddleware(options) {\n  const {\n    thunk = true,\n    immutableCheck = true,\n    serializableCheck = true,\n    actionCreatorCheck = true\n  } = options ?? {};\n  let middlewareArray = new Tuple<Middleware[]>();\n  if (thunk) {\n    if (isBoolean(thunk)) {\n      middlewareArray.push(thunkMiddleware);\n    } else {\n      middlewareArray.push(withExtraArgument(thunk.extraArgument));\n    }\n  }\n  if (process.env.NODE_ENV !== 'production') {\n    if (immutableCheck) {\n      /* PROD_START_REMOVE_UMD */\n      let immutableOptions: ImmutableStateInvariantMiddlewareOptions = {};\n      if (!isBoolean(immutableCheck)) {\n        immutableOptions = immutableCheck;\n      }\n      middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));\n      /* PROD_STOP_REMOVE_UMD */\n    }\n    if (serializableCheck) {\n      let serializableOptions: SerializableStateInvariantMiddlewareOptions = {};\n      if (!isBoolean(serializableCheck)) {\n        serializableOptions = serializableCheck;\n      }\n      middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));\n    }\n    if (actionCreatorCheck) {\n      let actionCreatorOptions: ActionCreatorInvariantMiddlewareOptions = {};\n      if (!isBoolean(actionCreatorCheck)) {\n        actionCreatorOptions = actionCreatorCheck;\n      }\n      middlewareArray.unshift(createActionCreatorInvariantMiddleware(actionCreatorOptions));\n    }\n  }\n  return middlewareArray as any;\n};","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport { isAction } from 'redux';\nimport type { IsUnknownOrNonInferrable, IfMaybeUndefined, IfVoid, IsAny } from './tsHelpers';\nimport { hasMatchFunction } from './tsHelpers';\n\n/**\n * An action with a string type and an associated payload. This is the\n * type of action returned by `createAction()` action creators.\n *\n * @template P The type of the action's payload.\n * @template T the type used for the action type.\n * @template M The type of the action's meta (optional)\n * @template E The type of the action's error (optional)\n *\n * @public\n */\nexport type PayloadAction<P = void, T extends string = string, M = never, E = never> = {\n  payload: P;\n  type: T;\n} & ([M] extends [never] ? {} : {\n  meta: M;\n}) & ([E] extends [never] ? {} : {\n  error: E;\n});\n\n/**\n * A \"prepare\" method to be used as the second parameter of `createAction`.\n * Takes any number of arguments and returns a Flux Standard Action without\n * type (will be added later) that *must* contain a payload (might be undefined).\n *\n * @public\n */\nexport type PrepareAction<P> = ((...args: any[]) => {\n  payload: P;\n}) | ((...args: any[]) => {\n  payload: P;\n  meta: any;\n}) | ((...args: any[]) => {\n  payload: P;\n  error: any;\n}) | ((...args: any[]) => {\n  payload: P;\n  meta: any;\n  error: any;\n});\n\n/**\n * Internal version of `ActionCreatorWithPreparedPayload`. Not to be used externally.\n *\n * @internal\n */\nexport type _ActionCreatorWithPreparedPayload<PA extends PrepareAction<any> | void, T extends string = string> = PA extends PrepareAction<infer P> ? ActionCreatorWithPreparedPayload<Parameters<PA>, P, T, ReturnType<PA> extends {\n  error: infer E;\n} ? E : never, ReturnType<PA> extends {\n  meta: infer M;\n} ? M : never> : void;\n\n/**\n * Basic type for all action creators.\n *\n * @inheritdoc {redux#ActionCreator}\n */\nexport type BaseActionCreator<P, T extends string, M = never, E = never> = {\n  type: T;\n  match: (action: unknown) => action is PayloadAction<P, T, M, E>;\n};\n\n/**\n * An action creator that takes multiple arguments that are passed\n * to a `PrepareAction` method to create the final Action.\n * @typeParam Args arguments for the action creator function\n * @typeParam P `payload` type\n * @typeParam T `type` name\n * @typeParam E optional `error` type\n * @typeParam M optional `meta` type\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithPreparedPayload<Args extends unknown[], P, T extends string = string, E = never, M = never> extends BaseActionCreator<P, T, M, E> {\n  /**\n   * Calling this {@link redux#ActionCreator} with `Args` will return\n   * an Action with a payload of type `P` and (depending on the `PrepareAction`\n   * method used) a `meta`- and `error` property of types `M` and `E` respectively.\n   */\n  (...args: Args): PayloadAction<P, T, M, E>;\n}\n\n/**\n * An action creator of type `T` that takes an optional payload of type `P`.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithOptionalPayload<P, T extends string = string> extends BaseActionCreator<P, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} with an argument will\n   * return a {@link PayloadAction} of type `T` with a payload of `P`.\n   * Calling it without an argument will return a PayloadAction with a payload of `undefined`.\n   */\n  (payload?: P): PayloadAction<P, T>;\n}\n\n/**\n * An action creator of type `T` that takes no payload.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithoutPayload<T extends string = string> extends BaseActionCreator<undefined, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} will\n   * return a {@link PayloadAction} of type `T` with a payload of `undefined`\n   */\n  (noArgument: void): PayloadAction<undefined, T>;\n}\n\n/**\n * An action creator of type `T` that requires a payload of type P.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithPayload<P, T extends string = string> extends BaseActionCreator<P, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} with an argument will\n   * return a {@link PayloadAction} of type `T` with a payload of `P`\n   */\n  (payload: P): PayloadAction<P, T>;\n}\n\n/**\n * An action creator of type `T` whose `payload` type could not be inferred. Accepts everything as `payload`.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithNonInferrablePayload<T extends string = string> extends BaseActionCreator<unknown, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} with an argument will\n   * return a {@link PayloadAction} of type `T` with a payload\n   * of exactly the type of the argument.\n   */\n  <PT extends unknown>(payload: PT): PayloadAction<PT, T>;\n}\n\n/**\n * An action creator that produces actions with a `payload` attribute.\n *\n * @typeParam P the `payload` type\n * @typeParam T the `type` of the resulting action\n * @typeParam PA if the resulting action is preprocessed by a `prepare` method, the signature of said method.\n *\n * @public\n */\nexport type PayloadActionCreator<P = void, T extends string = string, PA extends PrepareAction<P> | void = void> = IfPrepareActionMethodProvided<PA, _ActionCreatorWithPreparedPayload<PA, T>,\n// else\nIsAny<P, ActionCreatorWithPayload<any, T>, IsUnknownOrNonInferrable<P, ActionCreatorWithNonInferrablePayload<T>,\n// else\nIfVoid<P, ActionCreatorWithoutPayload<T>,\n// else\nIfMaybeUndefined<P, ActionCreatorWithOptionalPayload<P, T>,\n// else\nActionCreatorWithPayload<P, T>>>>>>;\n\n/**\n * A utility function to create an action creator for the given action type\n * string. The action creator accepts a single argument, which will be included\n * in the action object as a field called payload. The action creator function\n * will also have its toString() overridden so that it returns the action type.\n *\n * @param type The action type to use for created actions.\n * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.\n *                If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.\n *\n * @public\n */\nexport function createAction<P = void, T extends string = string>(type: T): PayloadActionCreator<P, T>;\n\n/**\n * A utility function to create an action creator for the given action type\n * string. The action creator accepts a single argument, which will be included\n * in the action object as a field called payload. The action creator function\n * will also have its toString() overridden so that it returns the action type.\n *\n * @param type The action type to use for created actions.\n * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.\n *                If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.\n *\n * @public\n */\nexport function createAction<PA extends PrepareAction<any>, T extends string = string>(type: T, prepareAction: PA): PayloadActionCreator<ReturnType<PA>['payload'], T, PA>;\nexport function createAction(type: string, prepareAction?: Function): any {\n  function actionCreator(...args: any[]) {\n    if (prepareAction) {\n      let prepared = prepareAction(...args);\n      if (!prepared) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(0) : 'prepareAction did not return an object');\n      }\n      return {\n        type,\n        payload: prepared.payload,\n        ...('meta' in prepared && {\n          meta: prepared.meta\n        }),\n        ...('error' in prepared && {\n          error: prepared.error\n        })\n      };\n    }\n    return {\n      type,\n      payload: args[0]\n    };\n  }\n  actionCreator.toString = () => `${type}`;\n  actionCreator.type = type;\n  actionCreator.match = (action: unknown): action is PayloadAction => isAction(action) && action.type === type;\n  return actionCreator;\n}\n\n/**\n * Returns true if value is an RTK-like action creator, with a static type property and match method.\n */\nexport function isActionCreator(action: unknown): action is BaseActionCreator<unknown, string> & Function {\n  return typeof action === 'function' && 'type' in action &&\n  // hasMatchFunction only wants Matchers but I don't see the point in rewriting it\n  hasMatchFunction(action as any);\n}\n\n/**\n * Returns true if value is an action with a string type and valid Flux Standard Action keys.\n */\nexport function isFSA(action: unknown): action is {\n  type: string;\n  payload?: unknown;\n  error?: unknown;\n  meta?: unknown;\n} {\n  return isAction(action) && Object.keys(action).every(isValidKey);\n}\nfunction isValidKey(key: string) {\n  return ['type', 'payload', 'error', 'meta'].indexOf(key) > -1;\n}\n\n// helper types for more readable typings\n\ntype IfPrepareActionMethodProvided<PA extends PrepareAction<any> | void, True, False> = PA extends ((...args: any[]) => any) ? True : False;","import type { Middleware, StoreEnhancer } from 'redux';\nimport type { Tuple } from './utils';\nexport function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>) {\n  Object.assign(target, ...args);\n}\n\n/**\n * return True if T is `any`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsAny<T, True, False = never> =\n// test if we are going the left AND right path in the condition\ntrue | false extends (T extends never ? true : false) ? True : False;\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>;\n\n/**\n * return True if T is `unknown`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsUnknown<T, True, False = never> = unknown extends T ? IsAny<T, False, True> : False;\nexport type FallbackIfUnknown<T, Fallback> = IsUnknown<T, Fallback, T>;\n\n/**\n * @internal\n */\nexport type IfMaybeUndefined<P, True, False> = [undefined] extends [P] ? True : False;\n\n/**\n * @internal\n */\nexport type IfVoid<P, True, False> = [void] extends [P] ? True : False;\n\n/**\n * @internal\n */\nexport 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;\n\n/**\n * returns True if TS version is above 3.5, False if below.\n * uses feature detection to detect TS version >= 3.5\n * * versions below 3.5 will return `{}` for unresolvable interference\n * * versions above will return `unknown`\n *\n * @internal\n */\nexport type AtLeastTS35<True, False> = [True, False][IsUnknown<ReturnType<<T>() => T>, 0, 1>];\n\n/**\n * @internal\n */\nexport type IsUnknownOrNonInferrable<T, True, False> = AtLeastTS35<IsUnknown<T, True, False>, IsEmptyObj<T, True, IsUnknown<T, True, False>>>;\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;\n\n// Appears to have a convenient side effect of ignoring `never` even if that's not what you specified\nexport type ExcludeFromTuple<T, E, Acc extends unknown[] = []> = T extends [infer Head, ...infer Tail] ? ExcludeFromTuple<Tail, E, [...Acc, ...([Head] extends [E] ? [] : [Head])]> : Acc;\ntype 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;\nexport type ExtractDispatchExtensions<M> = M extends Tuple<infer MiddlewareTuple> ? ExtractDispatchFromMiddlewareTuple<MiddlewareTuple, {}> : M extends ReadonlyArray<Middleware> ? ExtractDispatchFromMiddlewareTuple<[...M], {}> : never;\ntype 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;\nexport 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;\ntype 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;\nexport 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;\n\n/**\n * Helper type. Passes T out again, but boxes it in a way that it cannot\n * \"widen\" the type by accident if it is a generic that should be inferred\n * from elsewhere.\n *\n * @internal\n */\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\nexport type NonUndefined<T> = T extends undefined ? never : T;\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\nexport type WithOptionalProp<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;\nexport interface TypeGuard<T> {\n  (value: any): value is T;\n}\nexport interface HasMatchFunction<T> {\n  match: TypeGuard<T>;\n}\nexport const hasMatchFunction = <T,>(v: Matcher<T>): v is HasMatchFunction<T> => {\n  return v && typeof (v as HasMatchFunction<T>).match === 'function';\n};\n\n/** @public */\nexport type Matcher<T> = HasMatchFunction<T> | TypeGuard<T>;\n\n/** @public */\nexport type ActionFromMatcher<M extends Matcher<any>> = M extends Matcher<infer T> ? T : never;\nexport type Id<T> = { [K in keyof T]: T[K] } & {};\nexport type Tail<T extends any[]> = T extends [any, ...infer Tail] ? Tail : never;\nexport type UnknownIfNonSpecific<T> = {} extends T ? unknown : T;\n\n/**\n * A Promise that will never reject.\n * @see https://github.com/reduxjs/redux-toolkit/issues/4101\n */\nexport type SafePromise<T> = Promise<T> & {\n  __linterBrands: 'SafePromise';\n};\n\n/**\n * Properly wraps a Promise as a {@link SafePromise} with .catch(fallback).\n */\nexport function asSafePromise<Resolved, Rejected>(promise: Promise<Resolved>, fallback: (error: unknown) => Rejected) {\n  return promise.catch(fallback) as SafePromise<Resolved | Rejected>;\n}","import type { Middleware } from 'redux';\nimport { isActionCreator as isRTKAction } from './createAction';\nexport interface ActionCreatorInvariantMiddlewareOptions {\n  /**\n   * The function to identify whether a value is an action creator.\n   * The default checks for a function with a static type property and match method.\n   */\n  isActionCreator?: (action: unknown) => action is Function & {\n    type?: unknown;\n  };\n}\nexport function getMessage(type?: unknown) {\n  const splitType = type ? `${type}`.split('/') : [];\n  const actionName = splitType[splitType.length - 1] || 'actionCreator';\n  return `Detected an action creator with type \"${type || 'unknown'}\" being dispatched. \nMake 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.`;\n}\nexport function createActionCreatorInvariantMiddleware(options: ActionCreatorInvariantMiddlewareOptions = {}): Middleware {\n  if (process.env.NODE_ENV === 'production') {\n    return () => next => action => next(action);\n  }\n  const {\n    isActionCreator = isRTKAction\n  } = options;\n  return () => next => action => {\n    if (isActionCreator(action)) {\n      console.warn(getMessage(action.type));\n    }\n    return next(action);\n  };\n}","import { produce as createNextState, isDraftable } from 'immer';\nexport function getTimeMeasureUtils(maxDelay: number, fnName: string) {\n  let elapsed = 0;\n  return {\n    measureTime<T>(fn: () => T): T {\n      const started = Date.now();\n      try {\n        return fn();\n      } finally {\n        const finished = Date.now();\n        elapsed += finished - started;\n      }\n    },\n    warnIfExceeded() {\n      if (elapsed > maxDelay) {\n        console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms. \nIf 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.\nIt is disabled in production builds, so you don't need to worry about that.`);\n      }\n    }\n  };\n}\nexport function delay(ms: number) {\n  return new Promise(resolve => setTimeout(resolve, ms));\n}\nexport class Tuple<Items extends ReadonlyArray<unknown> = []> extends Array<Items[number]> {\n  constructor(length: number);\n  constructor(...items: Items);\n  constructor(...items: any[]) {\n    super(...items);\n    Object.setPrototypeOf(this, Tuple.prototype);\n  }\n  static override get [Symbol.species]() {\n    return Tuple as any;\n  }\n  override concat<AdditionalItems extends ReadonlyArray<unknown>>(items: Tuple<AdditionalItems>): Tuple<[...Items, ...AdditionalItems]>;\n  override concat<AdditionalItems extends ReadonlyArray<unknown>>(items: AdditionalItems): Tuple<[...Items, ...AdditionalItems]>;\n  override concat<AdditionalItems extends ReadonlyArray<unknown>>(...items: AdditionalItems): Tuple<[...Items, ...AdditionalItems]>;\n  override concat(...arr: any[]) {\n    return super.concat.apply(this, arr);\n  }\n  prepend<AdditionalItems extends ReadonlyArray<unknown>>(items: Tuple<AdditionalItems>): Tuple<[...AdditionalItems, ...Items]>;\n  prepend<AdditionalItems extends ReadonlyArray<unknown>>(items: AdditionalItems): Tuple<[...AdditionalItems, ...Items]>;\n  prepend<AdditionalItems extends ReadonlyArray<unknown>>(...items: AdditionalItems): Tuple<[...AdditionalItems, ...Items]>;\n  prepend(...arr: any[]) {\n    if (arr.length === 1 && Array.isArray(arr[0])) {\n      return new Tuple(...arr[0].concat(this));\n    }\n    return new Tuple(...arr.concat(this));\n  }\n}\nexport function freezeDraftable<T>(val: T) {\n  return isDraftable(val) ? createNextState(val, () => {}) : val;\n}\nexport function getOrInsert<K extends object, V>(map: WeakMap<K, V>, key: K, value: V): V;\nexport function getOrInsert<K, V>(map: Map<K, V>, key: K, value: V): V;\nexport function getOrInsert<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, value: V): V {\n  if (map.has(key)) return map.get(key) as V;\n  return map.set(key, value).get(key) as V;\n}\nexport function getOrInsertComputed<K extends object, V>(map: WeakMap<K, V>, key: K, compute: (key: K) => V): V;\nexport function getOrInsertComputed<K, V>(map: Map<K, V>, key: K, compute: (key: K) => V): V;\nexport function getOrInsertComputed<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, compute: (key: K) => V): V {\n  if (map.has(key)) return map.get(key) as V;\n  return map.set(key, compute(key)).get(key) as V;\n}\nexport function promiseWithResolvers<T>(): {\n  promise: Promise<T>;\n  resolve: (value: T | PromiseLike<T>) => void;\n  reject: (reason?: any) => void;\n} {\n  let resolve: any;\n  let reject: any;\n  const promise = new Promise<T>((res, rej) => {\n    resolve = res;\n    reject = rej;\n  });\n  return {\n    promise,\n    resolve,\n    reject\n  };\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2 } from \"@reduxjs/toolkit\";\nimport type { Middleware } from 'redux';\nimport type { IgnorePaths } from './serializableStateInvariantMiddleware';\nimport { getTimeMeasureUtils } from './utils';\ntype EntryProcessor = (key: string, value: any) => any;\n\n/**\n * The default `isImmutable` function.\n *\n * @public\n */\nexport function isImmutableDefault(value: unknown): boolean {\n  return typeof value !== 'object' || value == null || Object.isFrozen(value);\n}\nexport function trackForMutations(isImmutable: IsImmutableFunc, ignorePaths: IgnorePaths | undefined, obj: any) {\n  const trackedProperties = trackProperties(isImmutable, ignorePaths, obj);\n  return {\n    detectMutations() {\n      return detectMutations(isImmutable, ignorePaths, trackedProperties, obj);\n    }\n  };\n}\ninterface TrackedProperty {\n  value: any;\n  children: Record<string, any>;\n}\nfunction trackProperties(isImmutable: IsImmutableFunc, ignorePaths: IgnorePaths = [], obj: Record<string, any>, path: string = '', checkedObjects: Set<Record<string, any>> = new Set()) {\n  const tracked: Partial<TrackedProperty> = {\n    value: obj\n  };\n  if (!isImmutable(obj) && !checkedObjects.has(obj)) {\n    checkedObjects.add(obj);\n    tracked.children = {};\n    for (const key in obj) {\n      const childPath = path ? path + '.' + key : key;\n      if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) {\n        continue;\n      }\n      tracked.children[key] = trackProperties(isImmutable, ignorePaths, obj[key], childPath);\n    }\n  }\n  return tracked as TrackedProperty;\n}\nfunction detectMutations(isImmutable: IsImmutableFunc, ignoredPaths: IgnorePaths = [], trackedProperty: TrackedProperty, obj: any, sameParentRef: boolean = false, path: string = ''): {\n  wasMutated: boolean;\n  path?: string;\n} {\n  const prevObj = trackedProperty ? trackedProperty.value : undefined;\n  const sameRef = prevObj === obj;\n  if (sameParentRef && !sameRef && !Number.isNaN(obj)) {\n    return {\n      wasMutated: true,\n      path\n    };\n  }\n  if (isImmutable(prevObj) || isImmutable(obj)) {\n    return {\n      wasMutated: false\n    };\n  }\n\n  // Gather all keys from prev (tracked) and after objs\n  const keysToDetect: Record<string, boolean> = {};\n  for (let key in trackedProperty.children) {\n    keysToDetect[key] = true;\n  }\n  for (let key in obj) {\n    keysToDetect[key] = true;\n  }\n  const hasIgnoredPaths = ignoredPaths.length > 0;\n  for (let key in keysToDetect) {\n    const nestedPath = path ? path + '.' + key : key;\n    if (hasIgnoredPaths) {\n      const hasMatches = ignoredPaths.some(ignored => {\n        if (ignored instanceof RegExp) {\n          return ignored.test(nestedPath);\n        }\n        return nestedPath === ignored;\n      });\n      if (hasMatches) {\n        continue;\n      }\n    }\n    const result = detectMutations(isImmutable, ignoredPaths, trackedProperty.children[key], obj[key], sameRef, nestedPath);\n    if (result.wasMutated) {\n      return result;\n    }\n  }\n  return {\n    wasMutated: false\n  };\n}\ntype IsImmutableFunc = (value: any) => boolean;\n\n/**\n * Options for `createImmutableStateInvariantMiddleware()`.\n *\n * @public\n */\nexport interface ImmutableStateInvariantMiddlewareOptions {\n  /**\n    Callback function to check if a value is considered to be immutable.\n    This function is applied recursively to every value contained in the state.\n    The default implementation will return true for primitive types\n    (like numbers, strings, booleans, null and undefined).\n   */\n  isImmutable?: IsImmutableFunc;\n  /**\n    An array of dot-separated path strings that match named nodes from\n    the root state to ignore when checking for immutability.\n    Defaults to undefined\n   */\n  ignoredPaths?: IgnorePaths;\n  /** Print a warning if checks take longer than N ms. Default: 32ms */\n  warnAfter?: number;\n}\n\n/**\n * Creates a middleware that checks whether any state was mutated in between\n * dispatches or during a dispatch. If any mutations are detected, an error is\n * thrown.\n *\n * @param options Middleware options.\n *\n * @public\n */\nexport function createImmutableStateInvariantMiddleware(options: ImmutableStateInvariantMiddlewareOptions = {}): Middleware {\n  if (process.env.NODE_ENV === 'production') {\n    return () => next => action => next(action);\n  } else {\n    function stringify(obj: any, serializer?: EntryProcessor, indent?: string | number, decycler?: EntryProcessor): string {\n      return JSON.stringify(obj, getSerialize(serializer, decycler), indent);\n    }\n    function getSerialize(serializer?: EntryProcessor, decycler?: EntryProcessor): EntryProcessor {\n      let stack: any[] = [],\n        keys: any[] = [];\n      if (!decycler) decycler = function (_: string, value: any) {\n        if (stack[0] === value) return '[Circular ~]';\n        return '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']';\n      };\n      return function (this: any, key: string, value: any) {\n        if (stack.length > 0) {\n          var thisPos = stack.indexOf(this);\n          ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);\n          ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);\n          if (~stack.indexOf(value)) value = decycler!.call(this, key, value);\n        } else stack.push(value);\n        return serializer == null ? value : serializer.call(this, key, value);\n      };\n    }\n    let {\n      isImmutable = isImmutableDefault,\n      ignoredPaths,\n      warnAfter = 32\n    } = options;\n    const track = trackForMutations.bind(null, isImmutable, ignoredPaths);\n    return ({\n      getState\n    }) => {\n      let state = getState();\n      let tracker = track(state);\n      let result;\n      return next => action => {\n        const measureUtils = getTimeMeasureUtils(warnAfter, 'ImmutableStateInvariantMiddleware');\n        measureUtils.measureTime(() => {\n          state = getState();\n          result = tracker.detectMutations();\n          // Track before potentially not meeting the invariant\n          tracker = track(state);\n          if (result.wasMutated) {\n            throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(19) : `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)`);\n          }\n        });\n        const dispatchedAction = next(action);\n        measureUtils.measureTime(() => {\n          state = getState();\n          result = tracker.detectMutations();\n          // Track before potentially not meeting the invariant\n          tracker = track(state);\n          if (result.wasMutated) {\n            throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(20) : `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)`);\n          }\n        });\n        measureUtils.warnIfExceeded();\n        return dispatchedAction;\n      };\n    };\n  }\n}","import type { Middleware } from 'redux';\nimport { isAction, isPlainObject } from 'redux';\nimport { getTimeMeasureUtils } from './utils';\n\n/**\n * Returns true if the passed value is \"plain\", i.e. a value that is either\n * directly JSON-serializable (boolean, number, string, array, plain object)\n * or `undefined`.\n *\n * @param val The value to check.\n *\n * @public\n */\nexport function isPlain(val: any) {\n  const type = typeof val;\n  return val == null || type === 'string' || type === 'boolean' || type === 'number' || Array.isArray(val) || isPlainObject(val);\n}\ninterface NonSerializableValue {\n  keyPath: string;\n  value: unknown;\n}\nexport type IgnorePaths = readonly (string | RegExp)[];\n\n/**\n * @public\n */\nexport function findNonSerializableValue(value: unknown, path: string = '', isSerializable: (value: unknown) => boolean = isPlain, getEntries?: (value: unknown) => [string, any][], ignoredPaths: IgnorePaths = [], cache?: WeakSet<object>): NonSerializableValue | false {\n  let foundNestedSerializable: NonSerializableValue | false;\n  if (!isSerializable(value)) {\n    return {\n      keyPath: path || '<root>',\n      value: value\n    };\n  }\n  if (typeof value !== 'object' || value === null) {\n    return false;\n  }\n  if (cache?.has(value)) return false;\n  const entries = getEntries != null ? getEntries(value) : Object.entries(value);\n  const hasIgnoredPaths = ignoredPaths.length > 0;\n  for (const [key, nestedValue] of entries) {\n    const nestedPath = path ? path + '.' + key : key;\n    if (hasIgnoredPaths) {\n      const hasMatches = ignoredPaths.some(ignored => {\n        if (ignored instanceof RegExp) {\n          return ignored.test(nestedPath);\n        }\n        return nestedPath === ignored;\n      });\n      if (hasMatches) {\n        continue;\n      }\n    }\n    if (!isSerializable(nestedValue)) {\n      return {\n        keyPath: nestedPath,\n        value: nestedValue\n      };\n    }\n    if (typeof nestedValue === 'object') {\n      foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths, cache);\n      if (foundNestedSerializable) {\n        return foundNestedSerializable;\n      }\n    }\n  }\n  if (cache && isNestedFrozen(value)) cache.add(value);\n  return false;\n}\nexport function isNestedFrozen(value: object) {\n  if (!Object.isFrozen(value)) return false;\n  for (const nestedValue of Object.values(value)) {\n    if (typeof nestedValue !== 'object' || nestedValue === null) continue;\n    if (!isNestedFrozen(nestedValue)) return false;\n  }\n  return true;\n}\n\n/**\n * Options for `createSerializableStateInvariantMiddleware()`.\n *\n * @public\n */\nexport interface SerializableStateInvariantMiddlewareOptions {\n  /**\n   * The function to check if a value is considered serializable. This\n   * function is applied recursively to every value contained in the\n   * state. Defaults to `isPlain()`.\n   */\n  isSerializable?: (value: any) => boolean;\n  /**\n   * The function that will be used to retrieve entries from each\n   * value.  If unspecified, `Object.entries` will be used. Defaults\n   * to `undefined`.\n   */\n  getEntries?: (value: any) => [string, any][];\n\n  /**\n   * An array of action types to ignore when checking for serializability.\n   * Defaults to []\n   */\n  ignoredActions?: string[];\n\n  /**\n   * An array of dot-separated path strings or regular expressions to ignore\n   * when checking for serializability, Defaults to\n   * ['meta.arg', 'meta.baseQueryMeta']\n   */\n  ignoredActionPaths?: (string | RegExp)[];\n\n  /**\n   * An array of dot-separated path strings or regular expressions to ignore\n   * when checking for serializability, Defaults to []\n   */\n  ignoredPaths?: (string | RegExp)[];\n  /**\n   * Execution time warning threshold. If the middleware takes longer\n   * than `warnAfter` ms, a warning will be displayed in the console.\n   * Defaults to 32ms.\n   */\n  warnAfter?: number;\n\n  /**\n   * Opt out of checking state. When set to `true`, other state-related params will be ignored.\n   */\n  ignoreState?: boolean;\n\n  /**\n   * Opt out of checking actions. When set to `true`, other action-related params will be ignored.\n   */\n  ignoreActions?: boolean;\n\n  /**\n   * Opt out of caching the results. The cache uses a WeakSet and speeds up repeated checking processes.\n   * The cache is automatically disabled if no browser support for WeakSet is present.\n   */\n  disableCache?: boolean;\n}\n\n/**\n * Creates a middleware that, after every state change, checks if the new\n * state is serializable. If a non-serializable value is found within the\n * state, an error is printed to the console.\n *\n * @param options Middleware options.\n *\n * @public\n */\nexport function createSerializableStateInvariantMiddleware(options: SerializableStateInvariantMiddlewareOptions = {}): Middleware {\n  if (process.env.NODE_ENV === 'production') {\n    return () => next => action => next(action);\n  } else {\n    const {\n      isSerializable = isPlain,\n      getEntries,\n      ignoredActions = [],\n      ignoredActionPaths = ['meta.arg', 'meta.baseQueryMeta'],\n      ignoredPaths = [],\n      warnAfter = 32,\n      ignoreState = false,\n      ignoreActions = false,\n      disableCache = false\n    } = options;\n    const cache: WeakSet<object> | undefined = !disableCache && WeakSet ? new WeakSet() : undefined;\n    return storeAPI => next => action => {\n      if (!isAction(action)) {\n        return next(action);\n      }\n      const result = next(action);\n      const measureUtils = getTimeMeasureUtils(warnAfter, 'SerializableStateInvariantMiddleware');\n      if (!ignoreActions && !(ignoredActions.length && ignoredActions.indexOf(action.type as any) !== -1)) {\n        measureUtils.measureTime(() => {\n          const foundActionNonSerializableValue = findNonSerializableValue(action, '', isSerializable, getEntries, ignoredActionPaths, cache);\n          if (foundActionNonSerializableValue) {\n            const {\n              keyPath,\n              value\n            } = foundActionNonSerializableValue;\n            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)');\n          }\n        });\n      }\n      if (!ignoreState) {\n        measureUtils.measureTime(() => {\n          const state = storeAPI.getState();\n          const foundStateNonSerializableValue = findNonSerializableValue(state, '', isSerializable, getEntries, ignoredPaths, cache);\n          if (foundStateNonSerializableValue) {\n            const {\n              keyPath,\n              value\n            } = foundStateNonSerializableValue;\n            console.error(`A non-serializable value was detected in the state, in the path: \\`${keyPath}\\`. Value:`, value, `\nTake a look at the reducer(s) handling this action type: ${action.type}.\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`);\n          }\n        });\n        measureUtils.warnIfExceeded();\n      }\n      return result;\n    };\n  }\n}","import type { StoreEnhancer } from 'redux';\nexport const SHOULD_AUTOBATCH = 'RTK_autoBatch';\nexport const prepareAutoBatched = <T,>() => (payload: T): {\n  payload: T;\n  meta: unknown;\n} => ({\n  payload,\n  meta: {\n    [SHOULD_AUTOBATCH]: true\n  }\n});\nconst createQueueWithTimer = (timeout: number) => {\n  return (notify: () => void) => {\n    setTimeout(notify, timeout);\n  };\n};\nexport type AutoBatchOptions = {\n  type: 'tick';\n} | {\n  type: 'timer';\n  timeout: number;\n} | {\n  type: 'raf';\n} | {\n  type: 'callback';\n  queueNotification: (notify: () => void) => void;\n};\n\n/**\n * A Redux store enhancer that watches for \"low-priority\" actions, and delays\n * notifying subscribers until either the queued callback executes or the\n * next \"standard-priority\" action is dispatched.\n *\n * This allows dispatching multiple \"low-priority\" actions in a row with only\n * a single subscriber notification to the UI after the sequence of actions\n * is finished, thus improving UI re-render performance.\n *\n * Watches for actions with the `action.meta[SHOULD_AUTOBATCH]` attribute.\n * This can be added to `action.meta` manually, or by using the\n * `prepareAutoBatched` helper.\n *\n * By default, it will queue a notification for the end of the event loop tick.\n * However, you can pass several other options to configure the behavior:\n * - `{type: 'tick'}`: queues using `queueMicrotask`\n * - `{type: 'timer', timeout: number}`: queues using `setTimeout`\n * - `{type: 'raf'}`: queues using `requestAnimationFrame` (default)\n * - `{type: 'callback', queueNotification: (notify: () => void) => void}`: lets you provide your own callback\n *\n *\n */\nexport const autoBatchEnhancer = (options: AutoBatchOptions = {\n  type: 'raf'\n}): StoreEnhancer => next => (...args) => {\n  const store = next(...args);\n  let notifying = true;\n  let shouldNotifyAtEndOfTick = false;\n  let notificationQueued = false;\n  const listeners = new Set<() => void>();\n  const queueCallback = options.type === 'tick' ? queueMicrotask : options.type === 'raf' ?\n  // requestAnimationFrame won't exist in SSR environments. Fall back to a vague approximation just to keep from erroring.\n  typeof window !== 'undefined' && window.requestAnimationFrame ? window.requestAnimationFrame : createQueueWithTimer(10) : options.type === 'callback' ? options.queueNotification : createQueueWithTimer(options.timeout);\n  const notifyListeners = () => {\n    // We're running at the end of the event loop tick.\n    // Run the real listener callbacks to actually update the UI.\n    notificationQueued = false;\n    if (shouldNotifyAtEndOfTick) {\n      shouldNotifyAtEndOfTick = false;\n      listeners.forEach(l => l());\n    }\n  };\n  return Object.assign({}, store, {\n    // Override the base `store.subscribe` method to keep original listeners\n    // from running if we're delaying notifications\n    subscribe(listener: () => void) {\n      // Each wrapped listener will only call the real listener if\n      // the `notifying` flag is currently active when it's called.\n      // This lets the base store work as normal, while the actual UI\n      // update becomes controlled by this enhancer.\n      const wrappedListener: typeof listener = () => notifying && listener();\n      const unsubscribe = store.subscribe(wrappedListener);\n      listeners.add(listener);\n      return () => {\n        unsubscribe();\n        listeners.delete(listener);\n      };\n    },\n    // Override the base `store.dispatch` method so that we can check actions\n    // for the `shouldAutoBatch` flag and determine if batching is active\n    dispatch(action: any) {\n      try {\n        // If the action does _not_ have the `shouldAutoBatch` flag,\n        // we resume/continue normal notify-after-each-dispatch behavior\n        notifying = !action?.meta?.[SHOULD_AUTOBATCH];\n        // If a `notifyListeners` microtask was queued, you can't cancel it.\n        // Instead, we set a flag so that it's a no-op when it does run\n        shouldNotifyAtEndOfTick = !notifying;\n        if (shouldNotifyAtEndOfTick) {\n          // We've seen at least 1 action with `SHOULD_AUTOBATCH`. Try to queue\n          // a microtask to notify listeners at the end of the event loop tick.\n          // Make sure we only enqueue this _once_ per tick.\n          if (!notificationQueued) {\n            notificationQueued = true;\n            queueCallback(notifyListeners);\n          }\n        }\n        // Go ahead and process the action as usual, including reducers.\n        // If normal notification behavior is enabled, the store will notify\n        // all of its own listeners, and the wrapper callbacks above will\n        // see `notifying` is true and pass on to the real listener callbacks.\n        // If we're \"batching\" behavior, then the wrapped callbacks will\n        // bail out, causing the base store notification behavior to be no-ops.\n        return store.dispatch(action);\n      } finally {\n        // Assume we're back to normal behavior after each action\n        notifying = true;\n      }\n    }\n  });\n};","import type { StoreEnhancer } from 'redux';\nimport type { AutoBatchOptions } from './autoBatchEnhancer';\nimport { autoBatchEnhancer } from './autoBatchEnhancer';\nimport { Tuple } from './utils';\nimport type { Middlewares } from './configureStore';\nimport type { ExtractDispatchExtensions } from './tsHelpers';\ntype GetDefaultEnhancersOptions = {\n  autoBatch?: boolean | AutoBatchOptions;\n};\nexport type GetDefaultEnhancers<M extends Middlewares<any>> = (options?: GetDefaultEnhancersOptions) => Tuple<[StoreEnhancer<{\n  dispatch: ExtractDispatchExtensions<M>;\n}>]>;\nexport const buildGetDefaultEnhancers = <M extends Middlewares<any>,>(middlewareEnhancer: StoreEnhancer<{\n  dispatch: ExtractDispatchExtensions<M>;\n}>): GetDefaultEnhancers<M> => function getDefaultEnhancers(options) {\n  const {\n    autoBatch = true\n  } = options ?? {};\n  let enhancerArray = new Tuple<StoreEnhancer[]>(middlewareEnhancer);\n  if (autoBatch) {\n    enhancerArray.push(autoBatchEnhancer(typeof autoBatch === 'object' ? autoBatch : undefined));\n  }\n  return enhancerArray as any;\n};","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { Draft } from 'immer';\nimport { produce as createNextState, isDraft, isDraftable } from 'immer';\nimport type { Action, Reducer, UnknownAction } from 'redux';\nimport type { ActionReducerMapBuilder } from './mapBuilders';\nimport { executeReducerBuilderCallback } from './mapBuilders';\nimport type { NoInfer, TypeGuard } from './tsHelpers';\nimport { freezeDraftable } from './utils';\n\n/**\n * Defines a mapping from action types to corresponding action object shapes.\n *\n * @deprecated This should not be used manually - it is only used for internal\n *             inference purposes and should not have any further value.\n *             It might be removed in the future.\n * @public\n */\nexport type Actions<T extends keyof any = string> = Record<T, Action>;\nexport type ActionMatcherDescription<S, A extends Action> = {\n  matcher: TypeGuard<A>;\n  reducer: CaseReducer<S, NoInfer<A>>;\n};\nexport type ReadonlyActionMatcherDescriptionCollection<S> = ReadonlyArray<ActionMatcherDescription<S, any>>;\nexport type ActionMatcherDescriptionCollection<S> = Array<ActionMatcherDescription<S, any>>;\n\n/**\n * A *case reducer* is a reducer function for a specific action type. Case\n * reducers can be composed to full reducers using `createReducer()`.\n *\n * Unlike a normal Redux reducer, a case reducer is never called with an\n * `undefined` state to determine the initial state. Instead, the initial\n * state is explicitly specified as an argument to `createReducer()`.\n *\n * In addition, a case reducer can choose to mutate the passed-in `state`\n * value directly instead of returning a new state. This does not actually\n * cause the store state to be mutated directly; instead, thanks to\n * [immer](https://github.com/mweststrate/immer), the mutations are\n * translated to copy operations that result in a new state.\n *\n * @public\n */\nexport type CaseReducer<S = any, A extends Action = UnknownAction> = (state: Draft<S>, action: A) => NoInfer<S> | void | Draft<NoInfer<S>>;\n\n/**\n * A mapping from action types to case reducers for `createReducer()`.\n *\n * @deprecated This should not be used manually - it is only used\n *             for internal inference purposes and using it manually\n *             would lead to type erasure.\n *             It might be removed in the future.\n * @public\n */\nexport type CaseReducers<S, AS extends Actions> = { [T in keyof AS]: AS[T] extends Action ? CaseReducer<S, AS[T]> : void };\nexport type NotFunction<T> = T extends Function ? never : T;\nfunction isStateFunction<S>(x: unknown): x is () => S {\n  return typeof x === 'function';\n}\nexport type ReducerWithInitialState<S extends NotFunction<any>> = Reducer<S> & {\n  getInitialState: () => S;\n};\n\n/**\n * A utility function that allows defining a reducer as a mapping from action\n * type to *case reducer* functions that handle these action types. The\n * reducer's initial state is passed as the first argument.\n *\n * @remarks\n * The body of every case reducer is implicitly wrapped with a call to\n * `produce()` from the [immer](https://github.com/mweststrate/immer) library.\n * This means that rather than returning a new state object, you can also\n * mutate the passed-in state object directly; these mutations will then be\n * automatically and efficiently translated into copies, giving you both\n * convenience and immutability.\n *\n * @overloadSummary\n * This function accepts a callback that receives a `builder` object as its argument.\n * That builder provides `addCase`, `addMatcher` and `addDefaultCase` functions that may be\n * called to define what actions this reducer will handle.\n *\n * @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`.\n * @param builderCallback - `(builder: Builder) => void` A callback that receives a *builder* object to define\n *   case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.\n * @example\n```ts\nimport {\n  createAction,\n  createReducer,\n  UnknownAction,\n  PayloadAction,\n} from \"@reduxjs/toolkit\";\n\nconst increment = createAction<number>(\"increment\");\nconst decrement = createAction<number>(\"decrement\");\n\nfunction isActionWithNumberPayload(\n  action: UnknownAction\n): action is PayloadAction<number> {\n  return typeof action.payload === \"number\";\n}\n\nconst reducer = createReducer(\n  {\n    counter: 0,\n    sumOfNumberPayloads: 0,\n    unhandledActions: 0,\n  },\n  (builder) => {\n    builder\n      .addCase(increment, (state, action) => {\n        // action is inferred correctly here\n        state.counter += action.payload;\n      })\n      // You can chain calls, or have separate `builder.addCase()` lines each time\n      .addCase(decrement, (state, action) => {\n        state.counter -= action.payload;\n      })\n      // You can apply a \"matcher function\" to incoming actions\n      .addMatcher(isActionWithNumberPayload, (state, action) => {})\n      // and provide a default case if no other handlers matched\n      .addDefaultCase((state, action) => {});\n  }\n);\n```\n * @public\n */\nexport function createReducer<S extends NotFunction<any>>(initialState: S | (() => S), mapOrBuilderCallback: (builder: ActionReducerMapBuilder<S>) => void): ReducerWithInitialState<S> {\n  if (process.env.NODE_ENV !== 'production') {\n    if (typeof mapOrBuilderCallback === 'object') {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(8) : \"The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer\");\n    }\n  }\n  let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] = executeReducerBuilderCallback(mapOrBuilderCallback);\n\n  // Ensure the initial state gets frozen either way (if draftable)\n  let getInitialState: () => S;\n  if (isStateFunction(initialState)) {\n    getInitialState = () => freezeDraftable(initialState());\n  } else {\n    const frozenInitialState = freezeDraftable(initialState);\n    getInitialState = () => frozenInitialState;\n  }\n  function reducer(state = getInitialState(), action: any): S {\n    let caseReducers = [actionsMap[action.type], ...finalActionMatchers.filter(({\n      matcher\n    }) => matcher(action)).map(({\n      reducer\n    }) => reducer)];\n    if (caseReducers.filter(cr => !!cr).length === 0) {\n      caseReducers = [finalDefaultCaseReducer];\n    }\n    return caseReducers.reduce((previousState, caseReducer): S => {\n      if (caseReducer) {\n        if (isDraft(previousState)) {\n          // If it's already a draft, we must already be inside a `createNextState` call,\n          // likely because this is being wrapped in `createReducer`, `createSlice`, or nested\n          // inside an existing draft. It's safe to just pass the draft to the mutator.\n          const draft = previousState as Draft<S>; // We can assume this is already a draft\n          const result = caseReducer(draft, action);\n          if (result === undefined) {\n            return previousState;\n          }\n          return result as S;\n        } else if (!isDraftable(previousState)) {\n          // If state is not draftable (ex: a primitive, such as 0), we want to directly\n          // return the caseReducer func and not wrap it with produce.\n          const result = caseReducer(previousState as any, action);\n          if (result === undefined) {\n            if (previousState === null) {\n              return previousState;\n            }\n            throw Error('A case reducer on a non-draftable value must not return undefined');\n          }\n          return result as S;\n        } else {\n          // @ts-ignore createNextState() produces an Immutable<Draft<S>> rather\n          // than an Immutable<S>, and TypeScript cannot find out how to reconcile\n          // these two types.\n          return createNextState(previousState, (draft: Draft<S>) => {\n            return caseReducer(draft, action);\n          });\n        }\n      }\n      return previousState;\n    }, state);\n  }\n  reducer.getInitialState = getInitialState;\n  return reducer as ReducerWithInitialState<S>;\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3, formatProdErrorMessage as _formatProdErrorMessage4, formatProdErrorMessage as _formatProdErrorMessage5, formatProdErrorMessage as _formatProdErrorMessage6 } from \"@reduxjs/toolkit\";\nimport type { Action } from 'redux';\nimport type { CaseReducer, CaseReducers, ActionMatcherDescriptionCollection } from './createReducer';\nimport type { TypeGuard } from './tsHelpers';\nexport type TypedActionCreator<Type extends string> = {\n  (...args: any[]): Action<Type>;\n  type: Type;\n};\n\n/**\n * A builder for an action <-> reducer map.\n *\n * @public\n */\nexport interface ActionReducerMapBuilder<State> {\n  /**\n   * Adds a case reducer to handle a single exact action type.\n   * @remarks\n   * All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.\n   * @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.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<ActionCreator extends TypedActionCreator<string>>(actionCreator: ActionCreator, reducer: CaseReducer<State, ReturnType<ActionCreator>>): ActionReducerMapBuilder<State>;\n  /**\n   * Adds a case reducer to handle a single exact action type.\n   * @remarks\n   * All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.\n   * @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.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<Type extends string, A extends Action<Type>>(type: Type, reducer: CaseReducer<State, A>): ActionReducerMapBuilder<State>;\n\n  /**\n   * Allows you to match your incoming actions against your own filter function instead of only the `action.type` property.\n   * @remarks\n   * If multiple matcher reducers match, all of them will be executed in the order\n   * they were defined in - even if a case reducer already matched.\n   * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and before any calls to `builder.addDefaultCase`.\n   * @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)\n   *   function\n   * @param reducer - The actual case reducer function.\n   *\n   * @example\n  ```ts\n  import {\n  createAction,\n  createReducer,\n  AsyncThunk,\n  UnknownAction,\n  } from \"@reduxjs/toolkit\";\n  type GenericAsyncThunk = AsyncThunk<unknown, unknown, any>;\n  type PendingAction = ReturnType<GenericAsyncThunk[\"pending\"]>;\n  type RejectedAction = ReturnType<GenericAsyncThunk[\"rejected\"]>;\n  type FulfilledAction = ReturnType<GenericAsyncThunk[\"fulfilled\"]>;\n  const initialState: Record<string, string> = {};\n  const resetAction = createAction(\"reset-tracked-loading-state\");\n  function isPendingAction(action: UnknownAction): action is PendingAction {\n  return typeof action.type === \"string\" && action.type.endsWith(\"/pending\");\n  }\n  const reducer = createReducer(initialState, (builder) => {\n  builder\n    .addCase(resetAction, () => initialState)\n    // matcher can be defined outside as a type predicate function\n    .addMatcher(isPendingAction, (state, action) => {\n      state[action.meta.requestId] = \"pending\";\n    })\n    .addMatcher(\n      // matcher can be defined inline as a type predicate function\n      (action): action is RejectedAction => action.type.endsWith(\"/rejected\"),\n      (state, action) => {\n        state[action.meta.requestId] = \"rejected\";\n      }\n    )\n    // matcher can just return boolean and the matcher can receive a generic argument\n    .addMatcher<FulfilledAction>(\n      (action) => action.type.endsWith(\"/fulfilled\"),\n      (state, action) => {\n        state[action.meta.requestId] = \"fulfilled\";\n      }\n    );\n  });\n  ```\n   */\n  addMatcher<A>(matcher: TypeGuard<A> | ((action: any) => boolean), reducer: CaseReducer<State, A extends Action ? A : A & Action>): Omit<ActionReducerMapBuilder<State>, 'addCase'>;\n\n  /**\n   * Adds a \"default case\" reducer that is executed if no case reducer and no matcher\n   * reducer was executed for this action.\n   * @param reducer - The fallback \"default case\" reducer function.\n   *\n   * @example\n  ```ts\n  import { createReducer } from '@reduxjs/toolkit'\n  const initialState = { otherActions: 0 }\n  const reducer = createReducer(initialState, builder => {\n  builder\n    // .addCase(...)\n    // .addMatcher(...)\n    .addDefaultCase((state, action) => {\n      state.otherActions++\n    })\n  })\n  ```\n   */\n  addDefaultCase(reducer: CaseReducer<State, Action>): {};\n}\nexport function executeReducerBuilderCallback<S>(builderCallback: (builder: ActionReducerMapBuilder<S>) => void): [CaseReducers<S, any>, ActionMatcherDescriptionCollection<S>, CaseReducer<S, Action> | undefined] {\n  const actionsMap: CaseReducers<S, any> = {};\n  const actionMatchers: ActionMatcherDescriptionCollection<S> = [];\n  let defaultCaseReducer: CaseReducer<S, Action> | undefined;\n  const builder = {\n    addCase(typeOrActionCreator: string | TypedActionCreator<any>, reducer: CaseReducer<S>) {\n      if (process.env.NODE_ENV !== 'production') {\n        /*\n         to keep the definition by the user in line with actual behavior,\n         we enforce `addCase` to always be called before calling `addMatcher`\n         as matching cases take precedence over matchers\n         */\n        if (actionMatchers.length > 0) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(26) : '`builder.addCase` should only be called before calling `builder.addMatcher`');\n        }\n        if (defaultCaseReducer) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(27) : '`builder.addCase` should only be called before calling `builder.addDefaultCase`');\n        }\n      }\n      const type = typeof typeOrActionCreator === 'string' ? typeOrActionCreator : typeOrActionCreator.type;\n      if (!type) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(28) : '`builder.addCase` cannot be called with an empty action type');\n      }\n      if (type in actionsMap) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage4(29) : '`builder.addCase` cannot be called with two reducers for the same action type ' + `'${type}'`);\n      }\n      actionsMap[type] = reducer;\n      return builder;\n    },\n    addMatcher<A>(matcher: TypeGuard<A>, reducer: CaseReducer<S, A extends Action ? A : A & Action>) {\n      if (process.env.NODE_ENV !== 'production') {\n        if (defaultCaseReducer) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage5(30) : '`builder.addMatcher` should only be called before calling `builder.addDefaultCase`');\n        }\n      }\n      actionMatchers.push({\n        matcher,\n        reducer\n      });\n      return builder;\n    },\n    addDefaultCase(reducer: CaseReducer<S, Action>) {\n      if (process.env.NODE_ENV !== 'production') {\n        if (defaultCaseReducer) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage6(31) : '`builder.addDefaultCase` can only be called once');\n        }\n      }\n      defaultCaseReducer = reducer;\n      return builder;\n    }\n  };\n  builderCallback(builder);\n  return [actionsMap, actionMatchers, defaultCaseReducer];\n}","import type { ActionFromMatcher, Matcher, UnionToIntersection } from './tsHelpers';\nimport { hasMatchFunction } from './tsHelpers';\nimport type { AsyncThunk, AsyncThunkFulfilledActionCreator, AsyncThunkPendingActionCreator, AsyncThunkRejectedActionCreator } from './createAsyncThunk';\n\n/** @public */\nexport type ActionMatchingAnyOf<Matchers extends Matcher<any>[]> = ActionFromMatcher<Matchers[number]>;\n\n/** @public */\nexport type ActionMatchingAllOf<Matchers extends Matcher<any>[]> = UnionToIntersection<ActionMatchingAnyOf<Matchers>>;\nconst matches = (matcher: Matcher<any>, action: any) => {\n  if (hasMatchFunction(matcher)) {\n    return matcher.match(action);\n  } else {\n    return matcher(action);\n  }\n};\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action matches any one of the supplied type guards or action\n * creators.\n *\n * @param matchers The type guards or action creators to match against.\n *\n * @public\n */\nexport function isAnyOf<Matchers extends Matcher<any>[]>(...matchers: Matchers) {\n  return (action: any): action is ActionMatchingAnyOf<Matchers> => {\n    return matchers.some(matcher => matches(matcher, action));\n  };\n}\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action matches all of the supplied type guards or action\n * creators.\n *\n * @param matchers The type guards or action creators to match against.\n *\n * @public\n */\nexport function isAllOf<Matchers extends Matcher<any>[]>(...matchers: Matchers) {\n  return (action: any): action is ActionMatchingAllOf<Matchers> => {\n    return matchers.every(matcher => matches(matcher, action));\n  };\n}\n\n/**\n * @param action A redux action\n * @param validStatus An array of valid meta.requestStatus values\n *\n * @internal\n */\nexport function hasExpectedRequestMetadata(action: any, validStatus: readonly string[]) {\n  if (!action || !action.meta) return false;\n  const hasValidRequestId = typeof action.meta.requestId === 'string';\n  const hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;\n  return hasValidRequestId && hasValidRequestStatus;\n}\nfunction isAsyncThunkArray(a: [any] | AnyAsyncThunk[]): a is AnyAsyncThunk[] {\n  return typeof a[0] === 'function' && 'pending' in a[0] && 'fulfilled' in a[0] && 'rejected' in a[0];\n}\nexport type UnknownAsyncThunkPendingAction = ReturnType<AsyncThunkPendingActionCreator<unknown>>;\nexport type PendingActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['pending']>;\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is pending.\n *\n * @public\n */\nexport function isPending(): (action: any) => action is UnknownAsyncThunkPendingAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is pending.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isPending<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is PendingActionFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a pending thunk action\n * @public\n */\nexport function isPending(action: any): action is UnknownAsyncThunkPendingAction;\nexport function isPending<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['pending']);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isPending()(asyncThunks[0]);\n  }\n  return isAnyOf(...asyncThunks.map(asyncThunk => asyncThunk.pending));\n}\nexport type UnknownAsyncThunkRejectedAction = ReturnType<AsyncThunkRejectedActionCreator<unknown, unknown>>;\nexport type RejectedActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['rejected']>;\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is rejected.\n *\n * @public\n */\nexport function isRejected(): (action: any) => action is UnknownAsyncThunkRejectedAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is rejected.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isRejected<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is RejectedActionFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a rejected thunk action\n * @public\n */\nexport function isRejected(action: any): action is UnknownAsyncThunkRejectedAction;\nexport function isRejected<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['rejected']);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isRejected()(asyncThunks[0]);\n  }\n  return isAnyOf(...asyncThunks.map(asyncThunk => asyncThunk.rejected));\n}\nexport type UnknownAsyncThunkRejectedWithValueAction = ReturnType<AsyncThunkRejectedActionCreator<unknown, unknown>>;\nexport type RejectedWithValueActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['rejected']> & (T extends AsyncThunk<any, any, {\n  rejectValue: infer RejectedValue;\n}> ? {\n  payload: RejectedValue;\n} : unknown);\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is rejected with value.\n *\n * @public\n */\nexport function isRejectedWithValue(): (action: any) => action is UnknownAsyncThunkRejectedAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is rejected with value.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isRejectedWithValue<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is RejectedWithValueActionFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a rejected thunk action with value\n * @public\n */\nexport function isRejectedWithValue(action: any): action is UnknownAsyncThunkRejectedAction;\nexport function isRejectedWithValue<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  const hasFlag = (action: any): action is any => {\n    return action && action.meta && action.meta.rejectedWithValue;\n  };\n  if (asyncThunks.length === 0) {\n    return isAllOf(isRejected(...asyncThunks), hasFlag);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isRejectedWithValue()(asyncThunks[0]);\n  }\n  return isAllOf(isRejected(...asyncThunks), hasFlag);\n}\nexport type UnknownAsyncThunkFulfilledAction = ReturnType<AsyncThunkFulfilledActionCreator<unknown, unknown>>;\nexport type FulfilledActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['fulfilled']>;\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is fulfilled.\n *\n * @public\n */\nexport function isFulfilled(): (action: any) => action is UnknownAsyncThunkFulfilledAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is fulfilled.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isFulfilled<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is FulfilledActionFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a fulfilled thunk action\n * @public\n */\nexport function isFulfilled(action: any): action is UnknownAsyncThunkFulfilledAction;\nexport function isFulfilled<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['fulfilled']);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isFulfilled()(asyncThunks[0]);\n  }\n  return isAnyOf(...asyncThunks.map(asyncThunk => asyncThunk.fulfilled));\n}\nexport type UnknownAsyncThunkAction = UnknownAsyncThunkPendingAction | UnknownAsyncThunkRejectedAction | UnknownAsyncThunkFulfilledAction;\nexport type AnyAsyncThunk = {\n  pending: {\n    match: (action: any) => action is any;\n  };\n  fulfilled: {\n    match: (action: any) => action is any;\n  };\n  rejected: {\n    match: (action: any) => action is any;\n  };\n};\nexport type ActionsFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['pending']> | ActionFromMatcher<T['fulfilled']> | ActionFromMatcher<T['rejected']>;\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator.\n *\n * @public\n */\nexport function isAsyncThunkAction(): (action: any) => action is UnknownAsyncThunkAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isAsyncThunkAction<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is ActionsFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a thunk action\n * @public\n */\nexport function isAsyncThunkAction(action: any): action is UnknownAsyncThunkAction;\nexport function isAsyncThunkAction<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['pending', 'fulfilled', 'rejected']);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isAsyncThunkAction()(asyncThunks[0]);\n  }\n  return isAnyOf(...asyncThunks.flatMap(asyncThunk => [asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled]));\n}","// Borrowed from https://github.com/ai/nanoid/blob/3.0.2/non-secure/index.js\n// This alphabet uses `A-Za-z0-9_-` symbols. A genetic algorithm helped\n// optimize the gzip compression for this alphabet.\nlet urlAlphabet = 'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW';\n\n/**\r\n *\r\n * @public\r\n */\nexport let nanoid = (size = 21) => {\n  let id = '';\n  // A compact alternative for `for (var i = 0; i < step; i++)`.\n  let i = size;\n  while (i--) {\n    // `| 0` is more compact and faster than `Math.floor()`.\n    id += urlAlphabet[Math.random() * 64 | 0];\n  }\n  return id;\n};","import type { Dispatch, UnknownAction } from 'redux';\nimport type { ThunkDispatch } from 'redux-thunk';\nimport type { ActionCreatorWithPreparedPayload } from './createAction';\nimport { createAction } from './createAction';\nimport { isAnyOf } from './matchers';\nimport { nanoid } from './nanoid';\nimport type { FallbackIfUnknown, Id, IsAny, IsUnknown, SafePromise } from './tsHelpers';\nexport type BaseThunkAPI<S, E, D extends Dispatch = Dispatch, RejectedValue = unknown, RejectedMeta = unknown, FulfilledMeta = unknown> = {\n  dispatch: D;\n  getState: () => S;\n  extra: E;\n  requestId: string;\n  signal: AbortSignal;\n  abort: (reason?: string) => void;\n  rejectWithValue: IsUnknown<RejectedMeta, (value: RejectedValue) => RejectWithValue<RejectedValue, RejectedMeta>, (value: RejectedValue, meta: RejectedMeta) => RejectWithValue<RejectedValue, RejectedMeta>>;\n  fulfillWithValue: IsUnknown<FulfilledMeta, <FulfilledValue>(value: FulfilledValue) => FulfilledValue, <FulfilledValue>(value: FulfilledValue, meta: FulfilledMeta) => FulfillWithMeta<FulfilledValue, FulfilledMeta>>;\n};\n\n/**\n * @public\n */\nexport interface SerializedError {\n  name?: string;\n  message?: string;\n  stack?: string;\n  code?: string;\n}\nconst commonProperties: Array<keyof SerializedError> = ['name', 'message', 'stack', 'code'];\nclass RejectWithValue<Payload, RejectedMeta> {\n  /*\n  type-only property to distinguish between RejectWithValue and FulfillWithMeta\n  does not exist at runtime\n  */\n  private readonly _type!: 'RejectWithValue';\n  constructor(public readonly payload: Payload, public readonly meta: RejectedMeta) {}\n}\nclass FulfillWithMeta<Payload, FulfilledMeta> {\n  /*\n  type-only property to distinguish between RejectWithValue and FulfillWithMeta\n  does not exist at runtime\n  */\n  private readonly _type!: 'FulfillWithMeta';\n  constructor(public readonly payload: Payload, public readonly meta: FulfilledMeta) {}\n}\n\n/**\n * Serializes an error into a plain object.\n * Reworked from https://github.com/sindresorhus/serialize-error\n *\n * @public\n */\nexport const miniSerializeError = (value: any): SerializedError => {\n  if (typeof value === 'object' && value !== null) {\n    const simpleError: SerializedError = {};\n    for (const property of commonProperties) {\n      if (typeof value[property] === 'string') {\n        simpleError[property] = value[property];\n      }\n    }\n    return simpleError;\n  }\n  return {\n    message: String(value)\n  };\n};\nexport type AsyncThunkConfig = {\n  state?: unknown;\n  dispatch?: ThunkDispatch<unknown, unknown, UnknownAction>;\n  extra?: unknown;\n  rejectValue?: unknown;\n  serializedErrorType?: unknown;\n  pendingMeta?: unknown;\n  fulfilledMeta?: unknown;\n  rejectedMeta?: unknown;\n};\nexport type GetState<ThunkApiConfig> = ThunkApiConfig extends {\n  state: infer State;\n} ? State : unknown;\ntype GetExtra<ThunkApiConfig> = ThunkApiConfig extends {\n  extra: infer Extra;\n} ? Extra : unknown;\ntype GetDispatch<ThunkApiConfig> = ThunkApiConfig extends {\n  dispatch: infer Dispatch;\n} ? FallbackIfUnknown<Dispatch, ThunkDispatch<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, UnknownAction>> : ThunkDispatch<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, UnknownAction>;\nexport type GetThunkAPI<ThunkApiConfig> = BaseThunkAPI<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, GetDispatch<ThunkApiConfig>, GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig>, GetFulfilledMeta<ThunkApiConfig>>;\ntype GetRejectValue<ThunkApiConfig> = ThunkApiConfig extends {\n  rejectValue: infer RejectValue;\n} ? RejectValue : unknown;\ntype GetPendingMeta<ThunkApiConfig> = ThunkApiConfig extends {\n  pendingMeta: infer PendingMeta;\n} ? PendingMeta : unknown;\ntype GetFulfilledMeta<ThunkApiConfig> = ThunkApiConfig extends {\n  fulfilledMeta: infer FulfilledMeta;\n} ? FulfilledMeta : unknown;\ntype GetRejectedMeta<ThunkApiConfig> = ThunkApiConfig extends {\n  rejectedMeta: infer RejectedMeta;\n} ? RejectedMeta : unknown;\ntype GetSerializedErrorType<ThunkApiConfig> = ThunkApiConfig extends {\n  serializedErrorType: infer GetSerializedErrorType;\n} ? GetSerializedErrorType : SerializedError;\ntype MaybePromise<T> = T | Promise<T> | (T extends any ? Promise<T> : never);\n\n/**\n * A type describing the return value of the `payloadCreator` argument to `createAsyncThunk`.\n * Might be useful for wrapping `createAsyncThunk` in custom abstractions.\n *\n * @public\n */\nexport type AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig extends AsyncThunkConfig> = MaybePromise<IsUnknown<GetFulfilledMeta<ThunkApiConfig>, Returned, FulfillWithMeta<Returned, GetFulfilledMeta<ThunkApiConfig>>> | RejectWithValue<GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig>>>;\n/**\n * A type describing the `payloadCreator` argument to `createAsyncThunk`.\n * Might be useful for wrapping `createAsyncThunk` in custom abstractions.\n *\n * @public\n */\nexport type AsyncThunkPayloadCreator<Returned, ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = (arg: ThunkArg, thunkAPI: GetThunkAPI<ThunkApiConfig>) => AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig>;\n\n/**\n * A ThunkAction created by `createAsyncThunk`.\n * Dispatching it returns a Promise for either a\n * fulfilled or rejected action.\n * Also, the returned value contains an `abort()` method\n * that allows the asyncAction to be cancelled from the outside.\n *\n * @public\n */\nexport 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>>> & {\n  abort: (reason?: string) => void;\n  requestId: string;\n  arg: ThunkArg;\n  unwrap: () => Promise<Returned>;\n};\n\n/**\n * Config provided when calling the async thunk action creator.\n */\nexport interface AsyncThunkDispatchConfig {\n  /**\n   * An external `AbortSignal` that will be tracked by the internal `AbortSignal`.\n   */\n  signal?: AbortSignal;\n}\ntype AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = IsAny<ThunkArg,\n// any handling\n(arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,\n// unknown handling\nunknown extends ThunkArg ? (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument not specified or specified as void or undefined\n: [ThunkArg] extends [void] | [undefined] ? (arg?: undefined, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains void\n: [void] extends [ThunkArg] // make optional\n? (arg?: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains undefined\n: [undefined] extends [ThunkArg] ? WithStrictNullChecks<\n// with strict nullChecks: make optional\n(arg?: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,\n// without strict null checks this will match everything, so don't make it optional\n(arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>> // default case: normal argument\n: (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>>;\n\n/**\n * Options object for `createAsyncThunk`.\n *\n * @public\n */\nexport type AsyncThunkOptions<ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = {\n  /**\n   * A method to control whether the asyncThunk should be executed. Has access to the\n   * `arg`, `api.getState()` and `api.extra` arguments.\n   *\n   * @returns `false` if it should be skipped\n   */\n  condition?(arg: ThunkArg, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): MaybePromise<boolean | undefined>;\n  /**\n   * If `condition` returns `false`, the asyncThunk will be skipped.\n   * This option allows you to control whether a `rejected` action with `meta.condition == false`\n   * will be dispatched or not.\n   *\n   * @default `false`\n   */\n  dispatchConditionRejection?: boolean;\n  serializeError?: (x: unknown) => GetSerializedErrorType<ThunkApiConfig>;\n\n  /**\n   * A function to use when generating the `requestId` for the request sequence.\n   *\n   * @default `nanoid`\n   */\n  idGenerator?: (arg: ThunkArg) => string;\n} & IsUnknown<GetPendingMeta<ThunkApiConfig>, {\n  /**\n   * A method to generate additional properties to be added to `meta` of the pending action.\n   *\n   * Using this optional overload will not modify the types correctly, this overload is only in place to support JavaScript users.\n   * Please use the `ThunkApiConfig` parameter `pendingMeta` to get access to a correctly typed overload\n   */\n  getPendingMeta?(base: {\n    arg: ThunkArg;\n    requestId: string;\n  }, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): GetPendingMeta<ThunkApiConfig>;\n}, {\n  /**\n   * A method to generate additional properties to be added to `meta` of the pending action.\n   */\n  getPendingMeta(base: {\n    arg: ThunkArg;\n    requestId: string;\n  }, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): GetPendingMeta<ThunkApiConfig>;\n}>;\nexport type AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[string, ThunkArg, GetPendingMeta<ThunkApiConfig>?], undefined, string, never, {\n  arg: ThunkArg;\n  requestId: string;\n  requestStatus: 'pending';\n} & GetPendingMeta<ThunkApiConfig>>;\nexport type AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[Error | null, string, ThunkArg, GetRejectValue<ThunkApiConfig>?, GetRejectedMeta<ThunkApiConfig>?], GetRejectValue<ThunkApiConfig> | undefined, string, GetSerializedErrorType<ThunkApiConfig>, {\n  arg: ThunkArg;\n  requestId: string;\n  requestStatus: 'rejected';\n  aborted: boolean;\n  condition: boolean;\n} & (({\n  rejectedWithValue: false;\n} & { [K in keyof GetRejectedMeta<ThunkApiConfig>]?: undefined }) | ({\n  rejectedWithValue: true;\n} & GetRejectedMeta<ThunkApiConfig>))>;\nexport type AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[Returned, string, ThunkArg, GetFulfilledMeta<ThunkApiConfig>?], Returned, string, never, {\n  arg: ThunkArg;\n  requestId: string;\n  requestStatus: 'fulfilled';\n} & GetFulfilledMeta<ThunkApiConfig>>;\n\n/**\n * A type describing the return value of `createAsyncThunk`.\n * Might be useful for wrapping `createAsyncThunk` in custom abstractions.\n *\n * @public\n */\nexport type AsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig> & {\n  pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig>;\n  rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>;\n  fulfilled: AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>;\n  // matchSettled?\n  settled: (action: any) => action is ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig> | AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>>;\n  typePrefix: string;\n};\nexport type OverrideThunkApiConfigs<OldConfig, NewConfig> = Id<NewConfig & Omit<OldConfig, keyof NewConfig>>;\nexport type CreateAsyncThunkFunction<CurriedThunkApiConfig extends AsyncThunkConfig> = {\n  /**\n   *\n   * @param typePrefix\n   * @param payloadCreator\n   * @param options\n   *\n   * @public\n   */\n  // separate signature without `AsyncThunkConfig` for better inference\n  <Returned, ThunkArg = void>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, CurriedThunkApiConfig>, options?: AsyncThunkOptions<ThunkArg, CurriedThunkApiConfig>): AsyncThunk<Returned, ThunkArg, CurriedThunkApiConfig>;\n\n  /**\n   *\n   * @param typePrefix\n   * @param payloadCreator\n   * @param options\n   *\n   * @public\n   */\n  <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>>;\n};\ntype CreateAsyncThunk<CurriedThunkApiConfig extends AsyncThunkConfig> = CreateAsyncThunkFunction<CurriedThunkApiConfig> & {\n  withTypes<ThunkApiConfig extends AsyncThunkConfig>(): CreateAsyncThunk<OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;\n};\nconst externalAbortMessage = 'External signal was aborted';\nexport const createAsyncThunk = /* @__PURE__ */(() => {\n  function createAsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>, options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>): AsyncThunk<Returned, ThunkArg, ThunkApiConfig> {\n    type RejectedValue = GetRejectValue<ThunkApiConfig>;\n    type PendingMeta = GetPendingMeta<ThunkApiConfig>;\n    type FulfilledMeta = GetFulfilledMeta<ThunkApiConfig>;\n    type RejectedMeta = GetRejectedMeta<ThunkApiConfig>;\n    const fulfilled: AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig> = createAction(typePrefix + '/fulfilled', (payload: Returned, requestId: string, arg: ThunkArg, meta?: FulfilledMeta) => ({\n      payload,\n      meta: {\n        ...(meta as any || {}),\n        arg,\n        requestId,\n        requestStatus: 'fulfilled' as const\n      }\n    }));\n    const pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig> = createAction(typePrefix + '/pending', (requestId: string, arg: ThunkArg, meta?: PendingMeta) => ({\n      payload: undefined,\n      meta: {\n        ...(meta as any || {}),\n        arg,\n        requestId,\n        requestStatus: 'pending' as const\n      }\n    }));\n    const rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig> = createAction(typePrefix + '/rejected', (error: Error | null, requestId: string, arg: ThunkArg, payload?: RejectedValue, meta?: RejectedMeta) => ({\n      payload,\n      error: (options && options.serializeError || miniSerializeError)(error || 'Rejected') as GetSerializedErrorType<ThunkApiConfig>,\n      meta: {\n        ...(meta as any || {}),\n        arg,\n        requestId,\n        rejectedWithValue: !!payload,\n        requestStatus: 'rejected' as const,\n        aborted: error?.name === 'AbortError',\n        condition: error?.name === 'ConditionError'\n      }\n    }));\n    function actionCreator(arg: ThunkArg, {\n      signal\n    }: AsyncThunkDispatchConfig = {}): AsyncThunkAction<Returned, ThunkArg, Required<ThunkApiConfig>> {\n      return (dispatch, getState, extra) => {\n        const requestId = options?.idGenerator ? options.idGenerator(arg) : nanoid();\n        const abortController = new AbortController();\n        let abortHandler: (() => void) | undefined;\n        let abortReason: string | undefined;\n        function abort(reason?: string) {\n          abortReason = reason;\n          abortController.abort();\n        }\n        if (signal) {\n          if (signal.aborted) {\n            abort(externalAbortMessage);\n          } else {\n            signal.addEventListener('abort', () => abort(externalAbortMessage), {\n              once: true\n            });\n          }\n        }\n        const promise = async function () {\n          let finalAction: ReturnType<typeof fulfilled | typeof rejected>;\n          try {\n            let conditionResult = options?.condition?.(arg, {\n              getState,\n              extra\n            });\n            if (isThenable(conditionResult)) {\n              conditionResult = await conditionResult;\n            }\n            if (conditionResult === false || abortController.signal.aborted) {\n              // eslint-disable-next-line no-throw-literal\n              throw {\n                name: 'ConditionError',\n                message: 'Aborted due to condition callback returning false.'\n              };\n            }\n            const abortedPromise = new Promise<never>((_, reject) => {\n              abortHandler = () => {\n                reject({\n                  name: 'AbortError',\n                  message: abortReason || 'Aborted'\n                });\n              };\n              abortController.signal.addEventListener('abort', abortHandler);\n            });\n            dispatch(pending(requestId, arg, options?.getPendingMeta?.({\n              requestId,\n              arg\n            }, {\n              getState,\n              extra\n            })) as any);\n            finalAction = await Promise.race([abortedPromise, Promise.resolve(payloadCreator(arg, {\n              dispatch,\n              getState,\n              extra,\n              requestId,\n              signal: abortController.signal,\n              abort,\n              rejectWithValue: ((value: RejectedValue, meta?: RejectedMeta) => {\n                return new RejectWithValue(value, meta);\n              }) as any,\n              fulfillWithValue: ((value: unknown, meta?: FulfilledMeta) => {\n                return new FulfillWithMeta(value, meta);\n              }) as any\n            })).then(result => {\n              if (result instanceof RejectWithValue) {\n                throw result;\n              }\n              if (result instanceof FulfillWithMeta) {\n                return fulfilled(result.payload, requestId, arg, result.meta);\n              }\n              return fulfilled(result as any, requestId, arg);\n            })]);\n          } catch (err) {\n            finalAction = err instanceof RejectWithValue ? rejected(null, requestId, arg, err.payload, err.meta) : rejected(err as any, requestId, arg);\n          } finally {\n            if (abortHandler) {\n              abortController.signal.removeEventListener('abort', abortHandler);\n            }\n          }\n          // We dispatch the result action _after_ the catch, to avoid having any errors\n          // here get swallowed by the try/catch block,\n          // per https://twitter.com/dan_abramov/status/770914221638942720\n          // and https://github.com/reduxjs/redux-toolkit/blob/e85eb17b39a2118d859f7b7746e0f3fee523e089/docs/tutorials/advanced-tutorial.md#async-error-handling-logic-in-thunks\n\n          const skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && (finalAction as any).meta.condition;\n          if (!skipDispatch) {\n            dispatch(finalAction as any);\n          }\n          return finalAction;\n        }();\n        return Object.assign(promise as SafePromise<any>, {\n          abort,\n          requestId,\n          arg,\n          unwrap() {\n            return promise.then<any>(unwrapResult);\n          }\n        });\n      };\n    }\n    return Object.assign(actionCreator as AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig>, {\n      pending,\n      rejected,\n      fulfilled,\n      settled: isAnyOf(rejected, fulfilled),\n      typePrefix\n    });\n  }\n  createAsyncThunk.withTypes = () => createAsyncThunk;\n  return createAsyncThunk as CreateAsyncThunk<AsyncThunkConfig>;\n})();\ninterface UnwrappableAction {\n  payload: any;\n  meta?: any;\n  error?: any;\n}\ntype UnwrappedActionPayload<T extends UnwrappableAction> = Exclude<T, {\n  error: any;\n}>['payload'];\n\n/**\n * @public\n */\nexport function unwrapResult<R extends UnwrappableAction>(action: R): UnwrappedActionPayload<R> {\n  if (action.meta && action.meta.rejectedWithValue) {\n    throw action.payload;\n  }\n  if (action.error) {\n    throw action.error;\n  }\n  return action.payload;\n}\ntype WithStrictNullChecks<True, False> = undefined extends boolean ? False : True;\nfunction isThenable(value: any): value is PromiseLike<any> {\n  return value !== null && typeof value === 'object' && typeof value.then === 'function';\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3, formatProdErrorMessage as _formatProdErrorMessage4, formatProdErrorMessage as _formatProdErrorMessage5, formatProdErrorMessage as _formatProdErrorMessage6, formatProdErrorMessage as _formatProdErrorMessage7, formatProdErrorMessage as _formatProdErrorMessage8 } from \"@reduxjs/toolkit\";\nimport type { Action, Reducer, UnknownAction } from 'redux';\nimport type { Selector } from 'reselect';\nimport type { InjectConfig } from './combineSlices';\nimport type { ActionCreatorWithoutPayload, PayloadAction, PayloadActionCreator, PrepareAction, _ActionCreatorWithPreparedPayload } from './createAction';\nimport { createAction } from './createAction';\nimport type { AsyncThunk, AsyncThunkConfig, AsyncThunkOptions, AsyncThunkPayloadCreator, OverrideThunkApiConfigs } from './createAsyncThunk';\nimport { createAsyncThunk as _createAsyncThunk } from './createAsyncThunk';\nimport type { ActionMatcherDescriptionCollection, CaseReducer, ReducerWithInitialState } from './createReducer';\nimport { createReducer } from './createReducer';\nimport type { ActionReducerMapBuilder, TypedActionCreator } from './mapBuilders';\nimport { executeReducerBuilderCallback } from './mapBuilders';\nimport type { Id, TypeGuard } from './tsHelpers';\nimport { getOrInsertComputed } from './utils';\nconst asyncThunkSymbol = /* @__PURE__ */Symbol.for('rtk-slice-createasyncthunk');\n// type is annotated because it's too long to infer\nexport const asyncThunkCreator: {\n  [asyncThunkSymbol]: typeof _createAsyncThunk;\n} = {\n  [asyncThunkSymbol]: _createAsyncThunk\n};\ntype InjectIntoConfig<NewReducerPath extends string> = InjectConfig & {\n  reducerPath?: NewReducerPath;\n};\n\n/**\n * The return value of `createSlice`\n *\n * @public\n */\nexport interface Slice<State = any, CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> {\n  /**\n   * The slice name.\n   */\n  name: Name;\n\n  /**\n   *  The slice reducer path.\n   */\n  reducerPath: ReducerPath;\n\n  /**\n   * The slice's reducer.\n   */\n  reducer: Reducer<State>;\n\n  /**\n   * Action creators for the types of actions that are handled by the slice\n   * reducer.\n   */\n  actions: CaseReducerActions<CaseReducers, Name>;\n\n  /**\n   * The individual case reducer functions that were passed in the `reducers` parameter.\n   * This enables reuse and testing if they were defined inline when calling `createSlice`.\n   */\n  caseReducers: SliceDefinedCaseReducers<CaseReducers>;\n\n  /**\n   * Provides access to the initial state value given to the slice.\n   * If a lazy state initializer was provided, it will be called and a fresh value returned.\n   */\n  getInitialState: () => State;\n\n  /**\n   * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)\n   */\n  getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State>>;\n\n  /**\n   * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)\n   */\n  getSelectors<RootState>(selectState: (rootState: RootState) => State): Id<SliceDefinedSelectors<State, Selectors, RootState>>;\n\n  /**\n   * Selectors that assume the slice's state is `rootState[slice.reducerPath]` (which is usually the case)\n   *\n   * Equivalent to `slice.getSelectors((state: RootState) => state[slice.reducerPath])`.\n   */\n  get selectors(): Id<SliceDefinedSelectors<State, Selectors, { [K in ReducerPath]: State }>>;\n\n  /**\n   * Inject slice into provided reducer (return value from `combineSlices`), and return injected slice.\n   */\n  injectInto<NewReducerPath extends string = ReducerPath>(this: this, injectable: {\n    inject: (slice: {\n      reducerPath: string;\n      reducer: Reducer;\n    }, config?: InjectConfig) => void;\n  }, config?: InjectIntoConfig<NewReducerPath>): InjectedSlice<State, CaseReducers, Name, NewReducerPath, Selectors>;\n\n  /**\n   * Select the slice state, using the slice's current reducerPath.\n   *\n   * Will throw an error if slice is not found.\n   */\n  selectSlice(state: { [K in ReducerPath]: State }): State;\n}\n\n/**\n * A slice after being called with `injectInto(reducer)`.\n *\n * Selectors can now be called with an `undefined` value, in which case they use the slice's initial state.\n */\ntype 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'> & {\n  /**\n   * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)\n   */\n  getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State | undefined>>;\n\n  /**\n   * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)\n   */\n  getSelectors<RootState>(selectState: (rootState: RootState) => State | undefined): Id<SliceDefinedSelectors<State, Selectors, RootState>>;\n\n  /**\n   * Selectors that assume the slice's state is `rootState[slice.name]` (which is usually the case)\n   *\n   * Equivalent to `slice.getSelectors((state: RootState) => state[slice.name])`.\n   */\n  get selectors(): Id<SliceDefinedSelectors<State, Selectors, { [K in ReducerPath]?: State | undefined }>>;\n\n  /**\n   * Select the slice state, using the slice's current reducerPath.\n   *\n   * Returns initial state if slice is not found.\n   */\n  selectSlice(state: { [K in ReducerPath]?: State | undefined }): State;\n};\n\n/**\n * Options for `createSlice()`.\n *\n * @public\n */\nexport interface CreateSliceOptions<State = any, CR extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> {\n  /**\n   * The slice's name. Used to namespace the generated action types.\n   */\n  name: Name;\n\n  /**\n   * The slice's reducer path. Used when injecting into a combined slice reducer.\n   */\n  reducerPath?: ReducerPath;\n\n  /**\n   * 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`.\n   */\n  initialState: State | (() => State);\n\n  /**\n   * A mapping from action types to action-type-specific *case reducer*\n   * functions. For every action type, a matching action creator will be\n   * generated using `createAction()`.\n   */\n  reducers: ValidateSliceCaseReducers<State, CR> | ((creators: ReducerCreators<State>) => CR);\n\n  /**\n   * A callback that receives a *builder* object to define\n   * case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.\n   *\n   *\n   * @example\n  ```ts\n  import { createAction, createSlice, Action } from '@reduxjs/toolkit'\n  const incrementBy = createAction<number>('incrementBy')\n  const decrement = createAction('decrement')\n  interface RejectedAction extends Action {\n  error: Error\n  }\n  function isRejectedAction(action: Action): action is RejectedAction {\n  return action.type.endsWith('rejected')\n  }\n  createSlice({\n  name: 'counter',\n  initialState: 0,\n  reducers: {},\n  extraReducers: builder => {\n    builder\n      .addCase(incrementBy, (state, action) => {\n        // action is inferred correctly here if using TS\n      })\n      // You can chain calls, or have separate `builder.addCase()` lines each time\n      .addCase(decrement, (state, action) => {})\n      // You can match a range of action types\n      .addMatcher(\n        isRejectedAction,\n        // `action` will be inferred as a RejectedAction due to isRejectedAction being defined as a type guard\n        (state, action) => {}\n      )\n      // and provide a default case if no other handlers matched\n      .addDefaultCase((state, action) => {})\n    }\n  })\n  ```\n   */\n  extraReducers?: (builder: ActionReducerMapBuilder<State>) => void;\n\n  /**\n   * A map of selectors that receive the slice's state and any additional arguments, and return a result.\n   */\n  selectors?: Selectors;\n}\nexport enum ReducerType {\n  reducer = 'reducer',\n  reducerWithPrepare = 'reducerWithPrepare',\n  asyncThunk = 'asyncThunk',\n}\ntype ReducerDefinition<T extends ReducerType = ReducerType> = {\n  _reducerDefinitionType: T;\n};\nexport type CaseReducerDefinition<S = any, A extends Action = UnknownAction> = CaseReducer<S, A> & ReducerDefinition<ReducerType.reducer>;\n\n/**\n * A CaseReducer with a `prepare` method.\n *\n * @public\n */\nexport type CaseReducerWithPrepare<State, Action extends PayloadAction> = {\n  reducer: CaseReducer<State, Action>;\n  prepare: PrepareAction<Action['payload']>;\n};\nexport interface CaseReducerWithPrepareDefinition<State, Action extends PayloadAction> extends CaseReducerWithPrepare<State, Action>, ReducerDefinition<ReducerType.reducerWithPrepare> {}\ntype AsyncThunkSliceReducerConfig<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = {\n  pending?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['pending']>>;\n  rejected?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected']>>;\n  fulfilled?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['fulfilled']>>;\n  settled?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected' | 'fulfilled']>>;\n  options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>;\n};\ntype AsyncThunkSliceReducerDefinition<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig> & ReducerDefinition<ReducerType.asyncThunk> & {\n  payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>;\n};\n\n/**\n * Providing these as part of the config would cause circular types, so we disallow passing them\n */\ntype PreventCircular<ThunkApiConfig> = { [K in keyof ThunkApiConfig]: K extends 'state' | 'dispatch' ? never : ThunkApiConfig[K] };\ninterface AsyncThunkCreator<State, CurriedThunkApiConfig extends PreventCircular<AsyncThunkConfig> = PreventCircular<AsyncThunkConfig>> {\n  <Returned, ThunkArg = void>(payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, CurriedThunkApiConfig>, config?: AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, CurriedThunkApiConfig>): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, CurriedThunkApiConfig>;\n  <Returned, ThunkArg, ThunkApiConfig extends PreventCircular<AsyncThunkConfig> = {}>(payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>, config?: AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig>): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, ThunkApiConfig>;\n  withTypes<ThunkApiConfig extends PreventCircular<AsyncThunkConfig>>(): AsyncThunkCreator<State, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;\n}\nexport interface ReducerCreators<State> {\n  reducer(caseReducer: CaseReducer<State, PayloadAction>): CaseReducerDefinition<State, PayloadAction>;\n  reducer<Payload>(caseReducer: CaseReducer<State, PayloadAction<Payload>>): CaseReducerDefinition<State, PayloadAction<Payload>>;\n  asyncThunk: AsyncThunkCreator<State>;\n  preparedReducer<Prepare extends PrepareAction<any>>(prepare: Prepare, reducer: CaseReducer<State, ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>>): {\n    _reducerDefinitionType: ReducerType.reducerWithPrepare;\n    prepare: Prepare;\n    reducer: CaseReducer<State, ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>>;\n  };\n}\n\n/**\n * The type describing a slice's `reducers` option.\n *\n * @public\n */\nexport type SliceCaseReducers<State> = Record<string, ReducerDefinition> | Record<string, CaseReducer<State, PayloadAction<any>> | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>>;\n\n/**\n * The type describing a slice's `selectors` option.\n */\nexport type SliceSelectors<State> = {\n  [K: string]: (sliceState: State, ...args: any[]) => any;\n};\ntype SliceActionType<SliceName extends string, ActionName extends keyof any> = ActionName extends string | number ? `${SliceName}/${ActionName}` : string;\n\n/**\n * Derives the slice's `actions` property from the `reducers` options\n *\n * @public\n */\nexport type CaseReducerActions<CaseReducers extends SliceCaseReducers<any>, SliceName extends string> = { [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition ? Definition extends {\n  prepare: any;\n} ? ActionCreatorForCaseReducerWithPrepare<Definition, SliceActionType<SliceName, Type>> : Definition extends AsyncThunkSliceReducerDefinition<any, infer ThunkArg, infer Returned, infer ThunkApiConfig> ? AsyncThunk<Returned, ThunkArg, ThunkApiConfig> : Definition extends {\n  reducer: any;\n} ? ActionCreatorForCaseReducer<Definition['reducer'], SliceActionType<SliceName, Type>> : ActionCreatorForCaseReducer<Definition, SliceActionType<SliceName, Type>> : never };\n\n/**\n * Get a `PayloadActionCreator` type for a passed `CaseReducerWithPrepare`\n *\n * @internal\n */\ntype ActionCreatorForCaseReducerWithPrepare<CR extends {\n  prepare: any;\n}, Type extends string> = _ActionCreatorWithPreparedPayload<CR['prepare'], Type>;\n\n/**\n * Get a `PayloadActionCreator` type for a passed `CaseReducer`\n *\n * @internal\n */\ntype ActionCreatorForCaseReducer<CR, Type extends string> = CR extends ((state: any, action: infer Action) => any) ? Action extends {\n  payload: infer P;\n} ? PayloadActionCreator<P, Type> : ActionCreatorWithoutPayload<Type> : ActionCreatorWithoutPayload<Type>;\n\n/**\n * Extracts the CaseReducers out of a `reducers` object, even if they are\n * tested into a `CaseReducerWithPrepare`.\n *\n * @internal\n */\ntype 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 {\n  reducer: infer Reducer;\n} ? Reducer : Definition : never };\ntype RemappedSelector<S extends Selector, NewState> = S extends Selector<any, infer R, infer P> ? Selector<NewState, R, P> & {\n  unwrapped: S;\n} : never;\n\n/**\n * Extracts the final selector type from the `selectors` object.\n *\n * Removes the `string` index signature from the default value.\n */\ntype SliceDefinedSelectors<State, Selectors extends SliceSelectors<State>, RootState> = { [K in keyof Selectors as string extends K ? never : K]: RemappedSelector<Selectors[K], RootState> };\n\n/**\n * Used on a SliceCaseReducers object.\n * Ensures that if a CaseReducer is a `CaseReducerWithPrepare`, that\n * the `reducer` and the `prepare` function use the same type of `payload`.\n *\n * Might do additional such checks in the future.\n *\n * This type is only ever useful if you want to write your own wrapper around\n * `createSlice`. Please don't use it otherwise!\n *\n * @public\n */\nexport type ValidateSliceCaseReducers<S, ACR extends SliceCaseReducers<S>> = ACR & { [T in keyof ACR]: ACR[T] extends {\n  reducer(s: S, action?: infer A): any;\n} ? {\n  prepare(...a: never[]): Omit<A, 'type'>;\n} : {} };\nfunction getType(slice: string, actionKey: string): string {\n  return `${slice}/${actionKey}`;\n}\ninterface BuildCreateSliceConfig {\n  creators?: {\n    asyncThunk?: typeof asyncThunkCreator;\n  };\n}\nexport function buildCreateSlice({\n  creators\n}: BuildCreateSliceConfig = {}) {\n  const cAT = creators?.asyncThunk?.[asyncThunkSymbol];\n  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> {\n    const {\n      name,\n      reducerPath = name as unknown as ReducerPath\n    } = options;\n    if (!name) {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(11) : '`name` is a required option for createSlice');\n    }\n    if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n      if (options.initialState === undefined) {\n        console.error('You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`');\n      }\n    }\n    const reducers = (typeof options.reducers === 'function' ? options.reducers(buildReducerCreators<State>()) : options.reducers) || {};\n    const reducerNames = Object.keys(reducers);\n    const context: ReducerHandlingContext<State> = {\n      sliceCaseReducersByName: {},\n      sliceCaseReducersByType: {},\n      actionCreators: {},\n      sliceMatchers: []\n    };\n    const contextMethods: ReducerHandlingContextMethods<State> = {\n      addCase(typeOrActionCreator: string | TypedActionCreator<any>, reducer: CaseReducer<State>) {\n        const type = typeof typeOrActionCreator === 'string' ? typeOrActionCreator : typeOrActionCreator.type;\n        if (!type) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(12) : '`context.addCase` cannot be called with an empty action type');\n        }\n        if (type in context.sliceCaseReducersByType) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(13) : '`context.addCase` cannot be called with two reducers for the same action type: ' + type);\n        }\n        context.sliceCaseReducersByType[type] = reducer;\n        return contextMethods;\n      },\n      addMatcher(matcher, reducer) {\n        context.sliceMatchers.push({\n          matcher,\n          reducer\n        });\n        return contextMethods;\n      },\n      exposeAction(name, actionCreator) {\n        context.actionCreators[name] = actionCreator;\n        return contextMethods;\n      },\n      exposeCaseReducer(name, reducer) {\n        context.sliceCaseReducersByName[name] = reducer;\n        return contextMethods;\n      }\n    };\n    reducerNames.forEach(reducerName => {\n      const reducerDefinition = reducers[reducerName];\n      const reducerDetails: ReducerDetails = {\n        reducerName,\n        type: getType(name, reducerName),\n        createNotation: typeof options.reducers === 'function'\n      };\n      if (isAsyncThunkSliceReducerDefinition<State>(reducerDefinition)) {\n        handleThunkCaseReducerDefinition(reducerDetails, reducerDefinition, contextMethods, cAT);\n      } else {\n        handleNormalReducerDefinition<State>(reducerDetails, reducerDefinition as any, contextMethods);\n      }\n    });\n    function buildReducer() {\n      if (process.env.NODE_ENV !== 'production') {\n        if (typeof options.extraReducers === 'object') {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage4(14) : \"The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice\");\n        }\n      }\n      const [extraReducers = {}, actionMatchers = [], defaultCaseReducer = undefined] = typeof options.extraReducers === 'function' ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers];\n      const finalCaseReducers = {\n        ...extraReducers,\n        ...context.sliceCaseReducersByType\n      };\n      return createReducer(options.initialState, builder => {\n        for (let key in finalCaseReducers) {\n          builder.addCase(key, finalCaseReducers[key] as CaseReducer<any>);\n        }\n        for (let sM of context.sliceMatchers) {\n          builder.addMatcher(sM.matcher, sM.reducer);\n        }\n        for (let m of actionMatchers) {\n          builder.addMatcher(m.matcher, m.reducer);\n        }\n        if (defaultCaseReducer) {\n          builder.addDefaultCase(defaultCaseReducer);\n        }\n      });\n    }\n    const selectSelf = (state: State) => state;\n    const injectedSelectorCache = new Map<boolean, WeakMap<(rootState: any) => State | undefined, Record<string, (rootState: any) => any>>>();\n    const injectedStateCache = new WeakMap<(rootState: any) => State, State>();\n    let _reducer: ReducerWithInitialState<State>;\n    function reducer(state: State | undefined, action: UnknownAction) {\n      if (!_reducer) _reducer = buildReducer();\n      return _reducer(state, action);\n    }\n    function getInitialState() {\n      if (!_reducer) _reducer = buildReducer();\n      return _reducer.getInitialState();\n    }\n    function makeSelectorProps<CurrentReducerPath extends string = ReducerPath>(reducerPath: CurrentReducerPath, injected = false): Pick<Slice<State, CaseReducers, Name, CurrentReducerPath, Selectors>, 'getSelectors' | 'selectors' | 'selectSlice' | 'reducerPath'> {\n      function selectSlice(state: { [K in CurrentReducerPath]: State }) {\n        let sliceState = state[reducerPath];\n        if (typeof sliceState === 'undefined') {\n          if (injected) {\n            sliceState = getOrInsertComputed(injectedStateCache, selectSlice, getInitialState);\n          } else if (process.env.NODE_ENV !== 'production') {\n            throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage5(15) : 'selectSlice returned undefined for an uninjected slice reducer');\n          }\n        }\n        return sliceState;\n      }\n      function getSelectors(selectState: (rootState: any) => State = selectSelf) {\n        const selectorCache = getOrInsertComputed(injectedSelectorCache, injected, () => new WeakMap());\n        return getOrInsertComputed(selectorCache, selectState, () => {\n          const map: Record<string, Selector<any, any>> = {};\n          for (const [name, selector] of Object.entries(options.selectors ?? {})) {\n            map[name] = wrapSelector(selector, selectState, () => getOrInsertComputed(injectedStateCache, selectState, getInitialState), injected);\n          }\n          return map;\n        }) as any;\n      }\n      return {\n        reducerPath,\n        getSelectors,\n        get selectors() {\n          return getSelectors(selectSlice);\n        },\n        selectSlice\n      };\n    }\n    const slice: Slice<State, CaseReducers, Name, ReducerPath, Selectors> = {\n      name,\n      reducer,\n      actions: context.actionCreators as any,\n      caseReducers: context.sliceCaseReducersByName as any,\n      getInitialState,\n      ...makeSelectorProps(reducerPath),\n      injectInto(injectable, {\n        reducerPath: pathOpt,\n        ...config\n      } = {}) {\n        const newReducerPath = pathOpt ?? reducerPath;\n        injectable.inject({\n          reducerPath: newReducerPath,\n          reducer\n        }, config);\n        return {\n          ...slice,\n          ...makeSelectorProps(newReducerPath, true)\n        } as any;\n      }\n    };\n    return slice;\n  };\n}\nfunction wrapSelector<State, NewState, S extends Selector<State>>(selector: S, selectState: Selector<NewState, State>, getInitialState: () => State, injected?: boolean) {\n  function wrapper(rootState: NewState, ...args: any[]) {\n    let sliceState = selectState(rootState);\n    if (typeof sliceState === 'undefined') {\n      if (injected) {\n        sliceState = getInitialState();\n      } else if (process.env.NODE_ENV !== 'production') {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage6(16) : 'selectState returned undefined for an uninjected slice reducer');\n      }\n    }\n    return selector(sliceState, ...args);\n  }\n  wrapper.unwrapped = selector;\n  return wrapper as RemappedSelector<S, NewState>;\n}\n\n/**\n * A function that accepts an initial state, an object full of reducer\n * functions, and a \"slice name\", and automatically generates\n * action creators and action types that correspond to the\n * reducers and state.\n *\n * @public\n */\nexport const createSlice = /* @__PURE__ */buildCreateSlice();\ninterface ReducerHandlingContext<State> {\n  sliceCaseReducersByName: Record<string, CaseReducer<State, any> | Pick<AsyncThunkSliceReducerDefinition<State, any, any, any>, 'fulfilled' | 'rejected' | 'pending' | 'settled'>>;\n  sliceCaseReducersByType: Record<string, CaseReducer<State, any>>;\n  sliceMatchers: ActionMatcherDescriptionCollection<State>;\n  actionCreators: Record<string, Function>;\n}\ninterface ReducerHandlingContextMethods<State> {\n  /**\n   * Adds a case reducer to handle a single action type.\n   * @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.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<ActionCreator extends TypedActionCreator<string>>(actionCreator: ActionCreator, reducer: CaseReducer<State, ReturnType<ActionCreator>>): ReducerHandlingContextMethods<State>;\n  /**\n   * Adds a case reducer to handle a single action type.\n   * @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.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<Type extends string, A extends Action<Type>>(type: Type, reducer: CaseReducer<State, A>): ReducerHandlingContextMethods<State>;\n\n  /**\n   * Allows you to match incoming actions against your own filter function instead of only the `action.type` property.\n   * @remarks\n   * If multiple matcher reducers match, all of them will be executed in the order\n   * they were defined in - even if a case reducer already matched.\n   * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and before any calls to `builder.addDefaultCase`.\n   * @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)\n   *   function\n   * @param reducer - The actual case reducer function.\n   *\n   */\n  addMatcher<A>(matcher: TypeGuard<A>, reducer: CaseReducer<State, A extends Action ? A : A & Action>): ReducerHandlingContextMethods<State>;\n  /**\n   * Add an action to be exposed under the final `slice.actions` key.\n   * @param name The key to be exposed as.\n   * @param actionCreator The action to expose.\n   * @example\n   * context.exposeAction(\"addPost\", createAction<Post>(\"addPost\"));\n   *\n   * export const { addPost } = slice.actions\n   *\n   * dispatch(addPost(post))\n   */\n  exposeAction(name: string, actionCreator: Function): ReducerHandlingContextMethods<State>;\n  /**\n   * Add a case reducer to be exposed under the final `slice.caseReducers` key.\n   * @param name The key to be exposed as.\n   * @param reducer The reducer to expose.\n   * @example\n   * context.exposeCaseReducer(\"addPost\", (state, action: PayloadAction<Post>) => {\n   *   state.push(action.payload)\n   * })\n   *\n   * slice.caseReducers.addPost([], addPost(post))\n   */\n  exposeCaseReducer(name: string, reducer: CaseReducer<State, any> | Pick<AsyncThunkSliceReducerDefinition<State, any, any, any>, 'fulfilled' | 'rejected' | 'pending' | 'settled'>): ReducerHandlingContextMethods<State>;\n}\ninterface ReducerDetails {\n  /** The key the reducer was defined under */\n  reducerName: string;\n  /** The predefined action type, i.e. `${slice.name}/${reducerName}` */\n  type: string;\n  /** Whether create. notation was used when defining reducers */\n  createNotation: boolean;\n}\nfunction buildReducerCreators<State>(): ReducerCreators<State> {\n  function asyncThunk(payloadCreator: AsyncThunkPayloadCreator<any, any>, config: AsyncThunkSliceReducerConfig<State, any>): AsyncThunkSliceReducerDefinition<State, any> {\n    return {\n      _reducerDefinitionType: ReducerType.asyncThunk,\n      payloadCreator,\n      ...config\n    };\n  }\n  asyncThunk.withTypes = () => asyncThunk;\n  return {\n    reducer(caseReducer: CaseReducer<State, any>) {\n      return Object.assign({\n        // hack so the wrapping function has the same name as the original\n        // we need to create a wrapper so the `reducerDefinitionType` is not assigned to the original\n        [caseReducer.name](...args: Parameters<typeof caseReducer>) {\n          return caseReducer(...args);\n        }\n      }[caseReducer.name], {\n        _reducerDefinitionType: ReducerType.reducer\n      } as const);\n    },\n    preparedReducer(prepare, reducer) {\n      return {\n        _reducerDefinitionType: ReducerType.reducerWithPrepare,\n        prepare,\n        reducer\n      };\n    },\n    asyncThunk: asyncThunk as any\n  };\n}\nfunction handleNormalReducerDefinition<State>({\n  type,\n  reducerName,\n  createNotation\n}: ReducerDetails, maybeReducerWithPrepare: CaseReducer<State, {\n  payload: any;\n  type: string;\n}> | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>, context: ReducerHandlingContextMethods<State>) {\n  let caseReducer: CaseReducer<State, any>;\n  let prepareCallback: PrepareAction<any> | undefined;\n  if ('reducer' in maybeReducerWithPrepare) {\n    if (createNotation && !isCaseReducerWithPrepareDefinition(maybeReducerWithPrepare)) {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage7(17) : 'Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.');\n    }\n    caseReducer = maybeReducerWithPrepare.reducer;\n    prepareCallback = maybeReducerWithPrepare.prepare;\n  } else {\n    caseReducer = maybeReducerWithPrepare;\n  }\n  context.addCase(type, caseReducer).exposeCaseReducer(reducerName, caseReducer).exposeAction(reducerName, prepareCallback ? createAction(type, prepareCallback) : createAction(type));\n}\nfunction isAsyncThunkSliceReducerDefinition<State>(reducerDefinition: any): reducerDefinition is AsyncThunkSliceReducerDefinition<State, any, any, any> {\n  return reducerDefinition._reducerDefinitionType === ReducerType.asyncThunk;\n}\nfunction isCaseReducerWithPrepareDefinition<State>(reducerDefinition: any): reducerDefinition is CaseReducerWithPrepareDefinition<State, any> {\n  return reducerDefinition._reducerDefinitionType === ReducerType.reducerWithPrepare;\n}\nfunction handleThunkCaseReducerDefinition<State>({\n  type,\n  reducerName\n}: ReducerDetails, reducerDefinition: AsyncThunkSliceReducerDefinition<State, any, any, any>, context: ReducerHandlingContextMethods<State>, cAT: typeof _createAsyncThunk | undefined) {\n  if (!cAT) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage8(18) : 'Cannot use `create.asyncThunk` in the built-in `createSlice`. ' + 'Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.');\n  }\n  const {\n    payloadCreator,\n    fulfilled,\n    pending,\n    rejected,\n    settled,\n    options\n  } = reducerDefinition;\n  const thunk = cAT(type, payloadCreator, options as any);\n  context.exposeAction(reducerName, thunk);\n  if (fulfilled) {\n    context.addCase(thunk.fulfilled, fulfilled);\n  }\n  if (pending) {\n    context.addCase(thunk.pending, pending);\n  }\n  if (rejected) {\n    context.addCase(thunk.rejected, rejected);\n  }\n  if (settled) {\n    context.addMatcher(thunk.settled, settled);\n  }\n  context.exposeCaseReducer(reducerName, {\n    fulfilled: fulfilled || noop,\n    pending: pending || noop,\n    rejected: rejected || noop,\n    settled: settled || noop\n  });\n}\nfunction noop() {}","import type { EntityId, EntityState, EntityStateAdapter, EntityStateFactory } from './models';\nexport function getInitialEntityState<T, Id extends EntityId>(): EntityState<T, Id> {\n  return {\n    ids: [],\n    entities: {} as Record<Id, T>\n  };\n}\nexport function createInitialStateFactory<T, Id extends EntityId>(stateAdapter: EntityStateAdapter<T, Id>): EntityStateFactory<T, Id> {\n  function getInitialState(state?: undefined, entities?: readonly T[] | Record<Id, T>): EntityState<T, Id>;\n  function getInitialState<S extends object>(additionalState: S, entities?: readonly T[] | Record<Id, T>): EntityState<T, Id> & S;\n  function getInitialState(additionalState: any = {}, entities?: readonly T[] | Record<Id, T>): any {\n    const state = Object.assign(getInitialEntityState(), additionalState);\n    return entities ? stateAdapter.setAll(state, entities) : state;\n  }\n  return {\n    getInitialState\n  };\n}","import type { CreateSelectorFunction, Selector } from 'reselect';\nimport { createDraftSafeSelector } from '../createDraftSafeSelector';\nimport type { EntityId, EntitySelectors, EntityState } from './models';\ntype AnyFunction = (...args: any) => any;\ntype AnyCreateSelectorFunction = CreateSelectorFunction<<F extends AnyFunction>(f: F) => F, <F extends AnyFunction>(f: F) => F>;\nexport type GetSelectorsOptions = {\n  createSelector?: AnyCreateSelectorFunction;\n};\nexport function createSelectorsFactory<T, Id extends EntityId>() {\n  function getSelectors(selectState?: undefined, options?: GetSelectorsOptions): EntitySelectors<T, EntityState<T, Id>, Id>;\n  function getSelectors<V>(selectState: (state: V) => EntityState<T, Id>, options?: GetSelectorsOptions): EntitySelectors<T, V, Id>;\n  function getSelectors<V>(selectState?: (state: V) => EntityState<T, Id>, options: GetSelectorsOptions = {}): EntitySelectors<T, any, Id> {\n    const {\n      createSelector = createDraftSafeSelector as AnyCreateSelectorFunction\n    } = options;\n    const selectIds = (state: EntityState<T, Id>) => state.ids;\n    const selectEntities = (state: EntityState<T, Id>) => state.entities;\n    const selectAll = createSelector(selectIds, selectEntities, (ids, entities): T[] => ids.map(id => entities[id]!));\n    const selectId = (_: unknown, id: Id) => id;\n    const selectById = (entities: Record<Id, T>, id: Id) => entities[id];\n    const selectTotal = createSelector(selectIds, ids => ids.length);\n    if (!selectState) {\n      return {\n        selectIds,\n        selectEntities,\n        selectAll,\n        selectTotal,\n        selectById: createSelector(selectEntities, selectId, selectById)\n      };\n    }\n    const selectGlobalizedEntities = createSelector(selectState as Selector<V, EntityState<T, Id>>, selectEntities);\n    return {\n      selectIds: createSelector(selectState, selectIds),\n      selectEntities: selectGlobalizedEntities,\n      selectAll: createSelector(selectState, selectAll),\n      selectTotal: createSelector(selectState, selectTotal),\n      selectById: createSelector(selectGlobalizedEntities, selectId, selectById)\n    };\n  }\n  return {\n    getSelectors\n  };\n}","import { produce as createNextState, isDraft } from 'immer';\nimport type { Draft } from 'immer';\nimport type { EntityId, DraftableEntityState, PreventAny } from './models';\nimport type { PayloadAction } from '../createAction';\nimport { isFSA } from '../createAction';\nexport const isDraftTyped = isDraft as <T>(value: T | Draft<T>) => value is Draft<T>;\nexport function createSingleArgumentStateOperator<T, Id extends EntityId>(mutator: (state: DraftableEntityState<T, Id>) => void) {\n  const operator = createStateOperator((_: undefined, state: DraftableEntityState<T, Id>) => mutator(state));\n  return function operation<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>): S {\n    return operator(state as S, undefined);\n  };\n}\nexport function createStateOperator<T, Id extends EntityId, R>(mutator: (arg: R, state: DraftableEntityState<T, Id>) => void) {\n  return function operation<S extends DraftableEntityState<T, Id>>(state: S, arg: R | PayloadAction<R>): S {\n    function isPayloadActionArgument(arg: R | PayloadAction<R>): arg is PayloadAction<R> {\n      return isFSA(arg);\n    }\n    const runMutator = (draft: DraftableEntityState<T, Id>) => {\n      if (isPayloadActionArgument(arg)) {\n        mutator(arg.payload, draft);\n      } else {\n        mutator(arg, draft);\n      }\n    };\n    if (isDraftTyped<DraftableEntityState<T, Id>>(state)) {\n      // we must already be inside a `createNextState` call, likely because\n      // this is being wrapped in `createReducer` or `createSlice`.\n      // It's safe to just pass the draft to the mutator.\n      runMutator(state);\n\n      // since it's a draft, we'll just return it\n      return state;\n    }\n    return createNextState(state, runMutator);\n  };\n}","import type { Draft } from 'immer';\nimport { current, isDraft } from 'immer';\nimport type { DraftableEntityState, EntityId, IdSelector, Update } from './models';\nexport function selectIdValue<T, Id extends EntityId>(entity: T, selectId: IdSelector<T, Id>) {\n  const key = selectId(entity);\n  if (process.env.NODE_ENV !== 'production' && key === undefined) {\n    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());\n  }\n  return key;\n}\nexport function ensureEntitiesArray<T, Id extends EntityId>(entities: readonly T[] | Record<Id, T>): readonly T[] {\n  if (!Array.isArray(entities)) {\n    entities = Object.values(entities);\n  }\n  return entities;\n}\nexport function getCurrent<T>(value: T | Draft<T>): T {\n  return (isDraft(value) ? current(value) : value) as T;\n}\nexport 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[]] {\n  newEntities = ensureEntitiesArray(newEntities);\n  const existingIdsArray = getCurrent(state.ids);\n  const existingIds = new Set<Id>(existingIdsArray);\n  const added: T[] = [];\n  const addedIds = new Set<Id>([]);\n  const updated: Update<T, Id>[] = [];\n  for (const entity of newEntities) {\n    const id = selectIdValue(entity, selectId);\n    if (existingIds.has(id) || addedIds.has(id)) {\n      updated.push({\n        id,\n        changes: entity\n      });\n    } else {\n      addedIds.add(id);\n      added.push(entity);\n    }\n  }\n  return [added, updated, existingIdsArray];\n}","import type { Draft } from 'immer';\nimport type { EntityStateAdapter, IdSelector, Update, EntityId, DraftableEntityState } from './models';\nimport { createStateOperator, createSingleArgumentStateOperator } from './state_adapter';\nimport { selectIdValue, ensureEntitiesArray, splitAddedUpdatedEntities } from './utils';\nexport function createUnsortedStateAdapter<T, Id extends EntityId>(selectId: IdSelector<T, Id>): EntityStateAdapter<T, Id> {\n  type R = DraftableEntityState<T, Id>;\n  function addOneMutably(entity: T, state: R): void {\n    const key = selectIdValue(entity, selectId);\n    if (key in state.entities) {\n      return;\n    }\n    state.ids.push(key as Id & Draft<Id>);\n    (state.entities as Record<Id, T>)[key] = entity;\n  }\n  function addManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    for (const entity of newEntities) {\n      addOneMutably(entity, state);\n    }\n  }\n  function setOneMutably(entity: T, state: R): void {\n    const key = selectIdValue(entity, selectId);\n    if (!(key in state.entities)) {\n      state.ids.push(key as Id & Draft<Id>);\n    }\n    ;\n    (state.entities as Record<Id, T>)[key] = entity;\n  }\n  function setManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    for (const entity of newEntities) {\n      setOneMutably(entity, state);\n    }\n  }\n  function setAllMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    state.ids = [];\n    state.entities = {} as Record<Id, T>;\n    addManyMutably(newEntities, state);\n  }\n  function removeOneMutably(key: Id, state: R): void {\n    return removeManyMutably([key], state);\n  }\n  function removeManyMutably(keys: readonly Id[], state: R): void {\n    let didMutate = false;\n    keys.forEach(key => {\n      if (key in state.entities) {\n        delete (state.entities as Record<Id, T>)[key];\n        didMutate = true;\n      }\n    });\n    if (didMutate) {\n      state.ids = (state.ids as Id[]).filter(id => id in state.entities) as Id[] | Draft<Id[]>;\n    }\n  }\n  function removeAllMutably(state: R): void {\n    Object.assign(state, {\n      ids: [],\n      entities: {}\n    });\n  }\n  function takeNewKey(keys: {\n    [id: string]: Id;\n  }, update: Update<T, Id>, state: R): boolean {\n    const original: T | undefined = (state.entities as Record<Id, T>)[update.id];\n    if (original === undefined) {\n      return false;\n    }\n    const updated: T = Object.assign({}, original, update.changes);\n    const newKey = selectIdValue(updated, selectId);\n    const hasNewKey = newKey !== update.id;\n    if (hasNewKey) {\n      keys[update.id] = newKey;\n      delete (state.entities as Record<Id, T>)[update.id];\n    }\n    ;\n    (state.entities as Record<Id, T>)[newKey] = updated;\n    return hasNewKey;\n  }\n  function updateOneMutably(update: Update<T, Id>, state: R): void {\n    return updateManyMutably([update], state);\n  }\n  function updateManyMutably(updates: ReadonlyArray<Update<T, Id>>, state: R): void {\n    const newKeys: {\n      [id: string]: Id;\n    } = {};\n    const updatesPerEntity: {\n      [id: string]: Update<T, Id>;\n    } = {};\n    updates.forEach(update => {\n      // Only apply updates to entities that currently exist\n      if (update.id in state.entities) {\n        // If there are multiple updates to one entity, merge them together\n        updatesPerEntity[update.id] = {\n          id: update.id,\n          // Spreads ignore falsy values, so this works even if there isn't\n          // an existing update already at this key\n          changes: {\n            ...updatesPerEntity[update.id]?.changes,\n            ...update.changes\n          }\n        };\n      }\n    });\n    updates = Object.values(updatesPerEntity);\n    const didMutateEntities = updates.length > 0;\n    if (didMutateEntities) {\n      const didMutateIds = updates.filter(update => takeNewKey(newKeys, update, state)).length > 0;\n      if (didMutateIds) {\n        state.ids = Object.values(state.entities).map(e => selectIdValue(e as T, selectId));\n      }\n    }\n  }\n  function upsertOneMutably(entity: T, state: R): void {\n    return upsertManyMutably([entity], state);\n  }\n  function upsertManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    const [added, updated] = splitAddedUpdatedEntities<T, Id>(newEntities, selectId, state);\n    addManyMutably(added, state);\n    updateManyMutably(updated, state);\n  }\n  return {\n    removeAll: createSingleArgumentStateOperator(removeAllMutably),\n    addOne: createStateOperator(addOneMutably),\n    addMany: createStateOperator(addManyMutably),\n    setOne: createStateOperator(setOneMutably),\n    setMany: createStateOperator(setManyMutably),\n    setAll: createStateOperator(setAllMutably),\n    updateOne: createStateOperator(updateOneMutably),\n    updateMany: createStateOperator(updateManyMutably),\n    upsertOne: createStateOperator(upsertOneMutably),\n    upsertMany: createStateOperator(upsertManyMutably),\n    removeOne: createStateOperator(removeOneMutably),\n    removeMany: createStateOperator(removeManyMutably)\n  };\n}","import type { IdSelector, Comparer, EntityStateAdapter, Update, EntityId, DraftableEntityState } from './models';\nimport { createStateOperator } from './state_adapter';\nimport { createUnsortedStateAdapter } from './unsorted_state_adapter';\nimport { selectIdValue, ensureEntitiesArray, splitAddedUpdatedEntities, getCurrent } from './utils';\n\n// Borrowed from Replay\nexport function findInsertIndex<T>(sortedItems: T[], item: T, comparisonFunction: Comparer<T>): number {\n  let lowIndex = 0;\n  let highIndex = sortedItems.length;\n  while (lowIndex < highIndex) {\n    let middleIndex = lowIndex + highIndex >>> 1;\n    const currentItem = sortedItems[middleIndex];\n    const res = comparisonFunction(item, currentItem);\n    if (res >= 0) {\n      lowIndex = middleIndex + 1;\n    } else {\n      highIndex = middleIndex;\n    }\n  }\n  return lowIndex;\n}\nexport function insert<T>(sortedItems: T[], item: T, comparisonFunction: Comparer<T>): T[] {\n  const insertAtIndex = findInsertIndex(sortedItems, item, comparisonFunction);\n  sortedItems.splice(insertAtIndex, 0, item);\n  return sortedItems;\n}\nexport function createSortedStateAdapter<T, Id extends EntityId>(selectId: IdSelector<T, Id>, comparer: Comparer<T>): EntityStateAdapter<T, Id> {\n  type R = DraftableEntityState<T, Id>;\n  const {\n    removeOne,\n    removeMany,\n    removeAll\n  } = createUnsortedStateAdapter(selectId);\n  function addOneMutably(entity: T, state: R): void {\n    return addManyMutably([entity], state);\n  }\n  function addManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R, existingIds?: Id[]): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    const existingKeys = new Set<Id>(existingIds ?? getCurrent(state.ids));\n    const models = newEntities.filter(model => !existingKeys.has(selectIdValue(model, selectId)));\n    if (models.length !== 0) {\n      mergeFunction(state, models);\n    }\n  }\n  function setOneMutably(entity: T, state: R): void {\n    return setManyMutably([entity], state);\n  }\n  function setManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    if (newEntities.length !== 0) {\n      for (const item of newEntities) {\n        delete (state.entities as Record<Id, T>)[selectId(item)];\n      }\n      mergeFunction(state, newEntities);\n    }\n  }\n  function setAllMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    state.entities = {} as Record<Id, T>;\n    state.ids = [];\n    addManyMutably(newEntities, state, []);\n  }\n  function updateOneMutably(update: Update<T, Id>, state: R): void {\n    return updateManyMutably([update], state);\n  }\n  function updateManyMutably(updates: ReadonlyArray<Update<T, Id>>, state: R): void {\n    let appliedUpdates = false;\n    let replacedIds = false;\n    for (let update of updates) {\n      const entity: T | undefined = (state.entities as Record<Id, T>)[update.id];\n      if (!entity) {\n        continue;\n      }\n      appliedUpdates = true;\n      Object.assign(entity, update.changes);\n      const newId = selectId(entity);\n      if (update.id !== newId) {\n        // We do support the case where updates can change an item's ID.\n        // This makes things trickier - go ahead and swap the IDs in state now.\n        replacedIds = true;\n        delete (state.entities as Record<Id, T>)[update.id];\n        const oldIndex = (state.ids as Id[]).indexOf(update.id);\n        state.ids[oldIndex] = newId;\n        (state.entities as Record<Id, T>)[newId] = entity;\n      }\n    }\n    if (appliedUpdates) {\n      mergeFunction(state, [], appliedUpdates, replacedIds);\n    }\n  }\n  function upsertOneMutably(entity: T, state: R): void {\n    return upsertManyMutably([entity], state);\n  }\n  function upsertManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    const [added, updated, existingIdsArray] = splitAddedUpdatedEntities<T, Id>(newEntities, selectId, state);\n    if (added.length) {\n      addManyMutably(added, state, existingIdsArray);\n    }\n    if (updated.length) {\n      updateManyMutably(updated, state);\n    }\n  }\n  function areArraysEqual(a: readonly unknown[], b: readonly unknown[]) {\n    if (a.length !== b.length) {\n      return false;\n    }\n    for (let i = 0; i < a.length; i++) {\n      if (a[i] === b[i]) {\n        continue;\n      }\n      return false;\n    }\n    return true;\n  }\n  type MergeFunction = (state: R, addedItems: readonly T[], appliedUpdates?: boolean, replacedIds?: boolean) => void;\n  const mergeFunction: MergeFunction = (state, addedItems, appliedUpdates, replacedIds) => {\n    const currentEntities = getCurrent(state.entities);\n    const currentIds = getCurrent(state.ids);\n    const stateEntities = state.entities as Record<Id, T>;\n    let ids: Iterable<Id> = currentIds;\n    if (replacedIds) {\n      ids = new Set(currentIds);\n    }\n    let sortedEntities: T[] = [];\n    for (const id of ids) {\n      const entity = currentEntities[id];\n      if (entity) {\n        sortedEntities.push(entity);\n      }\n    }\n    const wasPreviouslyEmpty = sortedEntities.length === 0;\n\n    // Insert/overwrite all new/updated\n    for (const item of addedItems) {\n      stateEntities[selectId(item)] = item;\n      if (!wasPreviouslyEmpty) {\n        // Binary search insertion generally requires fewer comparisons\n        insert(sortedEntities, item, comparer);\n      }\n    }\n    if (wasPreviouslyEmpty) {\n      // All we have is the incoming values, sort them\n      sortedEntities = addedItems.slice().sort(comparer);\n    } else if (appliedUpdates) {\n      // We should have a _mostly_-sorted array already\n      sortedEntities.sort(comparer);\n    }\n    const newSortedIds = sortedEntities.map(selectId);\n    if (!areArraysEqual(currentIds, newSortedIds)) {\n      state.ids = newSortedIds;\n    }\n  };\n  return {\n    removeOne,\n    removeMany,\n    removeAll,\n    addOne: createStateOperator(addOneMutably),\n    updateOne: createStateOperator(updateOneMutably),\n    upsertOne: createStateOperator(upsertOneMutably),\n    setOne: createStateOperator(setOneMutably),\n    setMany: createStateOperator(setManyMutably),\n    setAll: createStateOperator(setAllMutably),\n    addMany: createStateOperator(addManyMutably),\n    updateMany: createStateOperator(updateManyMutably),\n    upsertMany: createStateOperator(upsertManyMutably)\n  };\n}","import type { EntityAdapter, EntityId, EntityAdapterOptions } from './models';\nimport { createInitialStateFactory } from './entity_state';\nimport { createSelectorsFactory } from './state_selectors';\nimport { createSortedStateAdapter } from './sorted_state_adapter';\nimport { createUnsortedStateAdapter } from './unsorted_state_adapter';\nimport type { WithRequiredProp } from '../tsHelpers';\nexport function createEntityAdapter<T, Id extends EntityId>(options: WithRequiredProp<EntityAdapterOptions<T, Id>, 'selectId'>): EntityAdapter<T, Id>;\nexport function createEntityAdapter<T extends {\n  id: EntityId;\n}>(options?: Omit<EntityAdapterOptions<T, T['id']>, 'selectId'>): EntityAdapter<T, T['id']>;\n\n/**\n *\n * @param options\n *\n * @public\n */\nexport function createEntityAdapter<T>(options: EntityAdapterOptions<T, EntityId> = {}): EntityAdapter<T, EntityId> {\n  const {\n    selectId,\n    sortComparer\n  }: Required<EntityAdapterOptions<T, EntityId>> = {\n    sortComparer: false,\n    selectId: (instance: any) => instance.id,\n    ...options\n  };\n  const stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);\n  const stateFactory = createInitialStateFactory(stateAdapter);\n  const selectorsFactory = createSelectorsFactory<T, EntityId>();\n  return {\n    selectId,\n    sortComparer,\n    ...stateFactory,\n    ...selectorsFactory,\n    ...stateAdapter\n  };\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3 } from \"@reduxjs/toolkit\";\nimport type { Action, Dispatch, MiddlewareAPI, UnknownAction } from 'redux';\nimport { isAction } from 'redux';\nimport type { ThunkDispatch } from 'redux-thunk';\nimport { createAction } from '../createAction';\nimport { nanoid } from '../nanoid';\nimport { TaskAbortError, listenerCancelled, listenerCompleted, taskCancelled, taskCompleted } from './exceptions';\nimport { createDelay, createPause, raceWithSignal, runTask, validateActive } from './task';\nimport type { AbortSignalWithReason, AddListenerOverloads, AnyListenerPredicate, CreateListenerMiddlewareOptions, FallbackAddListenerOptions, ForkOptions, ForkedTask, ForkedTaskExecutor, ListenerEntry, ListenerErrorHandler, ListenerErrorInfo, ListenerMiddleware, ListenerMiddlewareInstance, TakePattern, TaskResult, TypedAddListener, TypedCreateListenerEntry, TypedRemoveListener, UnsubscribeListener, UnsubscribeListenerOptions } from './types';\nimport { abortControllerWithReason, addAbortSignalListener, assertFunction, catchRejection, noop } from './utils';\nexport { TaskAbortError } from './exceptions';\nexport type { AsyncTaskExecutor, CreateListenerMiddlewareOptions, ForkedTask, ForkedTaskAPI, ForkedTaskExecutor, ListenerEffect, ListenerEffectAPI, ListenerErrorHandler, ListenerMiddleware, ListenerMiddlewareInstance, SyncTaskExecutor, TaskCancelled, TaskRejected, TaskResolved, TaskResult, TypedAddListener, TypedRemoveListener, TypedStartListening, TypedStopListening, UnsubscribeListener, UnsubscribeListenerOptions } from './types';\n\n//Overly-aggressive byte-shaving\nconst {\n  assign\n} = Object;\n/**\n * @internal\n */\nconst INTERNAL_NIL_TOKEN = {} as const;\nconst alm = 'listenerMiddleware' as const;\nconst createFork = (parentAbortSignal: AbortSignalWithReason<unknown>, parentBlockingPromises: Promise<any>[]) => {\n  const linkControllers = (controller: AbortController) => addAbortSignalListener(parentAbortSignal, () => abortControllerWithReason(controller, parentAbortSignal.reason));\n  return <T,>(taskExecutor: ForkedTaskExecutor<T>, opts?: ForkOptions): ForkedTask<T> => {\n    assertFunction(taskExecutor, 'taskExecutor');\n    const childAbortController = new AbortController();\n    linkControllers(childAbortController);\n    const result = runTask<T>(async (): Promise<T> => {\n      validateActive(parentAbortSignal);\n      validateActive(childAbortController.signal);\n      const result = (await taskExecutor({\n        pause: createPause(childAbortController.signal),\n        delay: createDelay(childAbortController.signal),\n        signal: childAbortController.signal\n      })) as T;\n      validateActive(childAbortController.signal);\n      return result;\n    }, () => abortControllerWithReason(childAbortController, taskCompleted));\n    if (opts?.autoJoin) {\n      parentBlockingPromises.push(result.catch(noop));\n    }\n    return {\n      result: createPause<TaskResult<T>>(parentAbortSignal)(result),\n      cancel() {\n        abortControllerWithReason(childAbortController, taskCancelled);\n      }\n    };\n  };\n};\nconst createTakePattern = <S,>(startListening: AddListenerOverloads<UnsubscribeListener, S, Dispatch>, signal: AbortSignal): TakePattern<S> => {\n  /**\n   * A function that takes a ListenerPredicate and an optional timeout,\n   * and resolves when either the predicate returns `true` based on an action\n   * state combination or when the timeout expires.\n   * If the parent listener is canceled while waiting, this will throw a\n   * TaskAbortError.\n   */\n  const take = async <P extends AnyListenerPredicate<S>,>(predicate: P, timeout: number | undefined) => {\n    validateActive(signal);\n\n    // Placeholder unsubscribe function until the listener is added\n    let unsubscribe: UnsubscribeListener = () => {};\n    const tuplePromise = new Promise<[Action, S, S]>((resolve, reject) => {\n      // Inside the Promise, we synchronously add the listener.\n      let stopListening = startListening({\n        predicate: predicate as any,\n        effect: (action, listenerApi): void => {\n          // One-shot listener that cleans up as soon as the predicate passes\n          listenerApi.unsubscribe();\n          // Resolve the promise with the same arguments the predicate saw\n          resolve([action, listenerApi.getState(), listenerApi.getOriginalState()]);\n        }\n      });\n      unsubscribe = () => {\n        stopListening();\n        reject();\n      };\n    });\n    const promises: (Promise<null> | Promise<[Action, S, S]>)[] = [tuplePromise];\n    if (timeout != null) {\n      promises.push(new Promise<null>(resolve => setTimeout(resolve, timeout, null)));\n    }\n    try {\n      const output = await raceWithSignal(signal, Promise.race(promises));\n      validateActive(signal);\n      return output;\n    } finally {\n      // Always clean up the listener\n      unsubscribe();\n    }\n  };\n  return ((predicate: AnyListenerPredicate<S>, timeout: number | undefined) => catchRejection(take(predicate, timeout))) as TakePattern<S>;\n};\nconst getListenerEntryPropsFrom = (options: FallbackAddListenerOptions) => {\n  let {\n    type,\n    actionCreator,\n    matcher,\n    predicate,\n    effect\n  } = options;\n  if (type) {\n    predicate = createAction(type).match;\n  } else if (actionCreator) {\n    type = actionCreator!.type;\n    predicate = actionCreator.match;\n  } else if (matcher) {\n    predicate = matcher;\n  } else if (predicate) {\n    // pass\n  } else {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(21) : 'Creating or removing a listener requires one of the known fields for matching an action');\n  }\n  assertFunction(effect, 'options.listener');\n  return {\n    predicate,\n    type,\n    effect\n  };\n};\n\n/** Accepts the possible options for creating a listener, and returns a formatted listener entry */\nexport const createListenerEntry: TypedCreateListenerEntry<unknown> = /* @__PURE__ */assign((options: FallbackAddListenerOptions) => {\n  const {\n    type,\n    predicate,\n    effect\n  } = getListenerEntryPropsFrom(options);\n  const entry: ListenerEntry<unknown> = {\n    id: nanoid(),\n    effect,\n    type,\n    predicate,\n    pending: new Set<AbortController>(),\n    unsubscribe: () => {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(22) : 'Unsubscribe not initialized');\n    }\n  };\n  return entry;\n}, {\n  withTypes: () => createListenerEntry\n}) as unknown as TypedCreateListenerEntry<unknown>;\nconst findListenerEntry = (listenerMap: Map<string, ListenerEntry>, options: FallbackAddListenerOptions) => {\n  const {\n    type,\n    effect,\n    predicate\n  } = getListenerEntryPropsFrom(options);\n  return Array.from(listenerMap.values()).find(entry => {\n    const matchPredicateOrType = typeof type === 'string' ? entry.type === type : entry.predicate === predicate;\n    return matchPredicateOrType && entry.effect === effect;\n  });\n};\nconst cancelActiveListeners = (entry: ListenerEntry<unknown, Dispatch<UnknownAction>>) => {\n  entry.pending.forEach(controller => {\n    abortControllerWithReason(controller, listenerCancelled);\n  });\n};\nconst createClearListenerMiddleware = (listenerMap: Map<string, ListenerEntry>) => {\n  return () => {\n    listenerMap.forEach(cancelActiveListeners);\n    listenerMap.clear();\n  };\n};\n\n/**\n * Safely reports errors to the `errorHandler` provided.\n * Errors that occur inside `errorHandler` are notified in a new task.\n * Inspired by [rxjs reportUnhandledError](https://github.com/ReactiveX/rxjs/blob/6fafcf53dc9e557439b25debaeadfd224b245a66/src/internal/util/reportUnhandledError.ts)\n * @param errorHandler\n * @param errorToNotify\n */\nconst safelyNotifyError = (errorHandler: ListenerErrorHandler, errorToNotify: unknown, errorInfo: ListenerErrorInfo): void => {\n  try {\n    errorHandler(errorToNotify, errorInfo);\n  } catch (errorHandlerError) {\n    // We cannot let an error raised here block the listener queue.\n    // The error raised here will be picked up by `window.onerror`, `process.on('error')` etc...\n    setTimeout(() => {\n      throw errorHandlerError;\n    }, 0);\n  }\n};\n\n/**\n * @public\n */\nexport const addListener = /* @__PURE__ */assign(/* @__PURE__ */createAction(`${alm}/add`), {\n  withTypes: () => addListener\n}) as unknown as TypedAddListener<unknown>;\n\n/**\n * @public\n */\nexport const clearAllListeners = /* @__PURE__ */createAction(`${alm}/removeAll`);\n\n/**\n * @public\n */\nexport const removeListener = /* @__PURE__ */assign(/* @__PURE__ */createAction(`${alm}/remove`), {\n  withTypes: () => removeListener\n}) as unknown as TypedRemoveListener<unknown>;\nconst defaultErrorHandler: ListenerErrorHandler = (...args: unknown[]) => {\n  console.error(`${alm}/error`, ...args);\n};\n\n/**\n * @public\n */\nexport const createListenerMiddleware = <StateType = unknown, DispatchType extends Dispatch<Action> = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown>(middlewareOptions: CreateListenerMiddlewareOptions<ExtraArgument> = {}) => {\n  const listenerMap = new Map<string, ListenerEntry>();\n  const {\n    extra,\n    onError = defaultErrorHandler\n  } = middlewareOptions;\n  assertFunction(onError, 'onError');\n  const insertEntry = (entry: ListenerEntry) => {\n    entry.unsubscribe = () => listenerMap.delete(entry.id);\n    listenerMap.set(entry.id, entry);\n    return (cancelOptions?: UnsubscribeListenerOptions) => {\n      entry.unsubscribe();\n      if (cancelOptions?.cancelActive) {\n        cancelActiveListeners(entry);\n      }\n    };\n  };\n  const startListening = ((options: FallbackAddListenerOptions) => {\n    const entry = findListenerEntry(listenerMap, options) ?? createListenerEntry(options as any);\n    return insertEntry(entry);\n  }) as AddListenerOverloads<any>;\n  assign(startListening, {\n    withTypes: () => startListening\n  });\n  const stopListening = (options: FallbackAddListenerOptions & UnsubscribeListenerOptions): boolean => {\n    const entry = findListenerEntry(listenerMap, options);\n    if (entry) {\n      entry.unsubscribe();\n      if (options.cancelActive) {\n        cancelActiveListeners(entry);\n      }\n    }\n    return !!entry;\n  };\n  assign(stopListening, {\n    withTypes: () => stopListening\n  });\n  const notifyListener = async (entry: ListenerEntry<unknown, Dispatch<UnknownAction>>, action: unknown, api: MiddlewareAPI, getOriginalState: () => StateType) => {\n    const internalTaskController = new AbortController();\n    const take = createTakePattern(startListening as AddListenerOverloads<any>, internalTaskController.signal);\n    const autoJoinPromises: Promise<any>[] = [];\n    try {\n      entry.pending.add(internalTaskController);\n      await Promise.resolve(entry.effect(action,\n      // Use assign() rather than ... to avoid extra helper functions added to bundle\n      assign({}, api, {\n        getOriginalState,\n        condition: (predicate: AnyListenerPredicate<any>, timeout?: number) => take(predicate, timeout).then(Boolean),\n        take,\n        delay: createDelay(internalTaskController.signal),\n        pause: createPause<any>(internalTaskController.signal),\n        extra,\n        signal: internalTaskController.signal,\n        fork: createFork(internalTaskController.signal, autoJoinPromises),\n        unsubscribe: entry.unsubscribe,\n        subscribe: () => {\n          listenerMap.set(entry.id, entry);\n        },\n        cancelActiveListeners: () => {\n          entry.pending.forEach((controller, _, set) => {\n            if (controller !== internalTaskController) {\n              abortControllerWithReason(controller, listenerCancelled);\n              set.delete(controller);\n            }\n          });\n        },\n        cancel: () => {\n          abortControllerWithReason(internalTaskController, listenerCancelled);\n          entry.pending.delete(internalTaskController);\n        },\n        throwIfCancelled: () => {\n          validateActive(internalTaskController.signal);\n        }\n      })));\n    } catch (listenerError) {\n      if (!(listenerError instanceof TaskAbortError)) {\n        safelyNotifyError(onError, listenerError, {\n          raisedBy: 'effect'\n        });\n      }\n    } finally {\n      await Promise.all(autoJoinPromises);\n      abortControllerWithReason(internalTaskController, listenerCompleted); // Notify that the task has completed\n      entry.pending.delete(internalTaskController);\n    }\n  };\n  const clearListenerMiddleware = createClearListenerMiddleware(listenerMap);\n  const middleware: ListenerMiddleware<StateType, DispatchType, ExtraArgument> = api => next => action => {\n    if (!isAction(action)) {\n      // we only want to notify listeners for action objects\n      return next(action);\n    }\n    if (addListener.match(action)) {\n      return startListening(action.payload as any);\n    }\n    if (clearAllListeners.match(action)) {\n      clearListenerMiddleware();\n      return;\n    }\n    if (removeListener.match(action)) {\n      return stopListening(action.payload);\n    }\n\n    // Need to get this state _before_ the reducer processes the action\n    let originalState: StateType | typeof INTERNAL_NIL_TOKEN = api.getState();\n\n    // `getOriginalState` can only be called synchronously.\n    // @see https://github.com/reduxjs/redux-toolkit/discussions/1648#discussioncomment-1932820\n    const getOriginalState = (): StateType => {\n      if (originalState === INTERNAL_NIL_TOKEN) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(23) : `${alm}: getOriginalState can only be called synchronously`);\n      }\n      return originalState as StateType;\n    };\n    let result: unknown;\n    try {\n      // Actually forward the action to the reducer before we handle listeners\n      result = next(action);\n      if (listenerMap.size > 0) {\n        const currentState = api.getState();\n        // Work around ESBuild+TS transpilation issue\n        const listenerEntries = Array.from(listenerMap.values());\n        for (const entry of listenerEntries) {\n          let runListener = false;\n          try {\n            runListener = entry.predicate(action, currentState, originalState);\n          } catch (predicateError) {\n            runListener = false;\n            safelyNotifyError(onError, predicateError, {\n              raisedBy: 'predicate'\n            });\n          }\n          if (!runListener) {\n            continue;\n          }\n          notifyListener(entry, action, api, getOriginalState);\n        }\n      }\n    } finally {\n      // Remove `originalState` store from this scope.\n      originalState = INTERNAL_NIL_TOKEN;\n    }\n    return result;\n  };\n  return {\n    middleware,\n    startListening,\n    stopListening,\n    clearListeners: clearListenerMiddleware\n  } as ListenerMiddlewareInstance<StateType, DispatchType, ExtraArgument>;\n};","import type { SerializedError } from '@reduxjs/toolkit';\nconst task = 'task';\nconst listener = 'listener';\nconst completed = 'completed';\nconst cancelled = 'cancelled';\n\n/* TaskAbortError error codes  */\nexport const taskCancelled = `task-${cancelled}` as const;\nexport const taskCompleted = `task-${completed}` as const;\nexport const listenerCancelled = `${listener}-${cancelled}` as const;\nexport const listenerCompleted = `${listener}-${completed}` as const;\nexport class TaskAbortError implements SerializedError {\n  name = 'TaskAbortError';\n  message: string;\n  constructor(public code: string | undefined) {\n    this.message = `${task} ${cancelled} (reason: ${code})`;\n  }\n}","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { AbortSignalWithReason } from './types';\nexport const assertFunction: (func: unknown, expected: string) => asserts func is (...args: unknown[]) => unknown = (func: unknown, expected: string) => {\n  if (typeof func !== 'function') {\n    throw new TypeError(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(32) : `${expected} is not a function`);\n  }\n};\nexport const noop = () => {};\nexport const catchRejection = <T,>(promise: Promise<T>, onError = noop): Promise<T> => {\n  promise.catch(onError);\n  return promise;\n};\nexport const addAbortSignalListener = (abortSignal: AbortSignal, callback: (evt: Event) => void) => {\n  abortSignal.addEventListener('abort', callback, {\n    once: true\n  });\n  return () => abortSignal.removeEventListener('abort', callback);\n};\n\n/**\n * Calls `abortController.abort(reason)` and patches `signal.reason`.\n * if it is not supported.\n *\n * At the time of writing `signal.reason` is available in FF chrome, edge node 17 and deno.\n * @param abortController\n * @param reason\n * @returns\n * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/reason\n */\nexport const abortControllerWithReason = <T,>(abortController: AbortController, reason: T): void => {\n  type Consumer<T> = (val: T) => void;\n  const signal = abortController.signal as AbortSignalWithReason<T>;\n  if (signal.aborted) {\n    return;\n  }\n\n  // Patch `reason` if necessary.\n  // - We use defineProperty here because reason is a getter of `AbortSignal.__proto__`.\n  // - We need to patch 'reason' before calling `.abort()` because listeners to the 'abort'\n  // event are are notified immediately.\n  if (!('reason' in signal)) {\n    Object.defineProperty(signal, 'reason', {\n      enumerable: true,\n      value: reason,\n      configurable: true,\n      writable: true\n    });\n  }\n  ;\n  (abortController.abort as Consumer<typeof reason>)(reason);\n};","import { TaskAbortError } from './exceptions';\nimport type { AbortSignalWithReason, TaskResult } from './types';\nimport { addAbortSignalListener, catchRejection, noop } from './utils';\n\n/**\n * Synchronously raises {@link TaskAbortError} if the task tied to the input `signal` has been cancelled.\n * @param signal\n * @param reason\n * @see {TaskAbortError}\n */\nexport const validateActive = (signal: AbortSignal): void => {\n  if (signal.aborted) {\n    const {\n      reason\n    } = signal as AbortSignalWithReason<string>;\n    throw new TaskAbortError(reason);\n  }\n};\n\n/**\n * Generates a race between the promise(s) and the AbortSignal\n * This avoids `Promise.race()`-related memory leaks:\n * https://github.com/nodejs/node/issues/17469#issuecomment-349794909\n */\nexport function raceWithSignal<T>(signal: AbortSignalWithReason<string>, promise: Promise<T>): Promise<T> {\n  let cleanup = noop;\n  return new Promise<T>((resolve, reject) => {\n    const notifyRejection = () => reject(new TaskAbortError(signal.reason));\n    if (signal.aborted) {\n      notifyRejection();\n      return;\n    }\n    cleanup = addAbortSignalListener(signal, notifyRejection);\n    promise.finally(() => cleanup()).then(resolve, reject);\n  }).finally(() => {\n    // after this point, replace `cleanup` with a noop, so there is no reference to `signal` any more\n    cleanup = noop;\n  });\n}\n\n/**\n * Runs a task and returns promise that resolves to {@link TaskResult}.\n * Second argument is an optional `cleanUp` function that always runs after task.\n *\n * **Note:** `runTask` runs the executor in the next microtask.\n * @returns\n */\nexport const runTask = async <T,>(task: () => Promise<T>, cleanUp?: () => void): Promise<TaskResult<T>> => {\n  try {\n    await Promise.resolve();\n    const value = await task();\n    return {\n      status: 'ok',\n      value\n    };\n  } catch (error: any) {\n    return {\n      status: error instanceof TaskAbortError ? 'cancelled' : 'rejected',\n      error\n    };\n  } finally {\n    cleanUp?.();\n  }\n};\n\n/**\n * Given an input `AbortSignal` and a promise returns another promise that resolves\n * as soon the input promise is provided or rejects as soon as\n * `AbortSignal.abort` is `true`.\n * @param signal\n * @returns\n */\nexport const createPause = <T,>(signal: AbortSignal) => {\n  return (promise: Promise<T>): Promise<T> => {\n    return catchRejection(raceWithSignal(signal, promise).then(output => {\n      validateActive(signal);\n      return output;\n    }));\n  };\n};\n\n/**\n * Given an input `AbortSignal` and `timeoutMs` returns a promise that resolves\n * after `timeoutMs` or rejects as soon as `AbortSignal.abort` is `true`.\n * @param signal\n * @returns\n */\nexport const createDelay = (signal: AbortSignal) => {\n  const pause = createPause<void>(signal);\n  return (timeoutMs: number): Promise<void> => {\n    return pause(new Promise<void>(resolve => setTimeout(resolve, timeoutMs)));\n  };\n};","import type { Dispatch, Middleware, UnknownAction } from 'redux';\nimport { compose } from 'redux';\nimport { createAction } from '../createAction';\nimport { isAllOf } from '../matchers';\nimport { nanoid } from '../nanoid';\nimport { getOrInsertComputed } from '../utils';\nimport type { AddMiddleware, DynamicMiddleware, DynamicMiddlewareInstance, MiddlewareEntry, WithMiddleware } from './types';\nexport type { DynamicMiddlewareInstance, GetDispatchType as GetDispatch, MiddlewareApiConfig } from './types';\nconst createMiddlewareEntry = <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>(middleware: Middleware<any, State, DispatchType>): MiddlewareEntry<State, DispatchType> => ({\n  middleware,\n  applied: new Map()\n});\nconst matchInstance = (instanceId: string) => (action: any): action is {\n  meta: {\n    instanceId: string;\n  };\n} => action?.meta?.instanceId === instanceId;\nexport const createDynamicMiddleware = <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>(): DynamicMiddlewareInstance<State, DispatchType> => {\n  const instanceId = nanoid();\n  const middlewareMap = new Map<Middleware<any, State, DispatchType>, MiddlewareEntry<State, DispatchType>>();\n  const withMiddleware = Object.assign(createAction('dynamicMiddleware/add', (...middlewares: Middleware<any, State, DispatchType>[]) => ({\n    payload: middlewares,\n    meta: {\n      instanceId\n    }\n  })), {\n    withTypes: () => withMiddleware\n  }) as WithMiddleware<State, DispatchType>;\n  const addMiddleware = Object.assign(function addMiddleware(...middlewares: Middleware<any, State, DispatchType>[]) {\n    middlewares.forEach(middleware => {\n      getOrInsertComputed(middlewareMap, middleware, createMiddlewareEntry);\n    });\n  }, {\n    withTypes: () => addMiddleware\n  }) as AddMiddleware<State, DispatchType>;\n  const getFinalMiddleware: Middleware<{}, State, DispatchType> = api => {\n    const appliedMiddleware = Array.from(middlewareMap.values()).map(entry => getOrInsertComputed(entry.applied, api, entry.middleware));\n    return compose(...appliedMiddleware);\n  };\n  const isWithMiddleware = isAllOf(withMiddleware, matchInstance(instanceId));\n  const middleware: DynamicMiddleware<State, DispatchType> = api => next => action => {\n    if (isWithMiddleware(action)) {\n      addMiddleware(...action.payload);\n      return api.dispatch;\n    }\n    return getFinalMiddleware(api)(next)(action);\n  };\n  return {\n    middleware,\n    addMiddleware,\n    withMiddleware,\n    instanceId\n  };\n};","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2 } from \"@reduxjs/toolkit\";\nimport type { Reducer, StateFromReducersMapObject, UnknownAction } from 'redux';\nimport { combineReducers } from 'redux';\nimport { nanoid } from './nanoid';\nimport type { Id, NonUndefined, Tail, UnionToIntersection, WithOptionalProp } from './tsHelpers';\nimport { getOrInsertComputed } from './utils';\ntype SliceLike<ReducerPath extends string, State> = {\n  reducerPath: ReducerPath;\n  reducer: Reducer<State>;\n};\ntype AnySliceLike = SliceLike<string, any>;\ntype SliceLikeReducerPath<A extends AnySliceLike> = A extends SliceLike<infer ReducerPath, any> ? ReducerPath : never;\ntype SliceLikeState<A extends AnySliceLike> = A extends SliceLike<any, infer State> ? State : never;\nexport type WithSlice<A extends AnySliceLike> = { [Path in SliceLikeReducerPath<A>]: SliceLikeState<A> };\ntype ReducerMap = Record<string, Reducer>;\ntype ExistingSliceLike<DeclaredState> = { [ReducerPath in keyof DeclaredState]: SliceLike<ReducerPath & string, NonUndefined<DeclaredState[ReducerPath]>> }[keyof DeclaredState];\nexport type InjectConfig = {\n  /**\n   * 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.\n   */\n  overrideExisting?: boolean;\n};\n\n/**\n * A reducer that allows for slices/reducers to be injected after initialisation.\n */\nexport interface CombinedSliceReducer<InitialState, DeclaredState = InitialState> extends Reducer<DeclaredState, UnknownAction, Partial<DeclaredState>> {\n  /**\n   * Provide a type for slices that will be injected lazily.\n   *\n   * One way to do this would be with interface merging:\n   * ```ts\n   *\n   * export interface LazyLoadedSlices {}\n   *\n   * export const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();\n   *\n   * // elsewhere\n   *\n   * declare module './reducer' {\n   *   export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}\n   * }\n   *\n   * const withBoolean = rootReducer.inject(booleanSlice);\n   *\n   * // elsewhere again\n   *\n   * declare module './reducer' {\n   *   export interface LazyLoadedSlices {\n   *     customName: CustomState\n   *   }\n   * }\n   *\n   * const withCustom = rootReducer.inject({ reducerPath: \"customName\", reducer: customSlice.reducer })\n   * ```\n   */\n  withLazyLoadedSlices<Lazy = {}>(): CombinedSliceReducer<InitialState, Id<DeclaredState & Partial<Lazy>>>;\n\n  /**\n   * Inject a slice.\n   *\n   * Accepts an individual slice, RTKQ API instance, or a \"slice-like\" { reducerPath, reducer } object.\n   *\n   * ```ts\n   * rootReducer.inject(booleanSlice)\n   * rootReducer.inject(baseApi)\n   * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })\n   * ```\n   *\n   */\n  inject<Sl extends Id<ExistingSliceLike<DeclaredState>>>(slice: Sl, config?: InjectConfig): CombinedSliceReducer<InitialState, Id<DeclaredState & WithSlice<Sl>>>;\n\n  /**\n   * Inject a slice.\n   *\n   * Accepts an individual slice, RTKQ API instance, or a \"slice-like\" { reducerPath, reducer } object.\n   *\n   * ```ts\n   * rootReducer.inject(booleanSlice)\n   * rootReducer.inject(baseApi)\n   * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })\n   * ```\n   *\n   */\n  inject<ReducerPath extends string, State>(slice: SliceLike<ReducerPath, State & (ReducerPath extends keyof DeclaredState ? never : State)>, config?: InjectConfig): CombinedSliceReducer<InitialState, Id<DeclaredState & WithSlice<SliceLike<ReducerPath, State>>>>;\n\n  /**\n   * Create a selector that guarantees that the slices injected will have a defined value when selector is run.\n   *\n   * ```ts\n   * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;\n   * //                                                                ^? boolean | undefined\n   *\n   * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {\n   *   // if action hasn't been dispatched since slice was injected, this would usually be undefined\n   *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined\n   *   return state.boolean;\n   *   //           ^? boolean\n   * })\n   * ```\n   *\n   * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.\n   *\n   * ```ts\n   *\n   * export interface LazyLoadedSlices {};\n   *\n   * export const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();\n   *\n   * export const rootReducer = combineSlices({ inner: innerReducer });\n   *\n   * export type RootState = ReturnType<typeof rootReducer>;\n   *\n   * // elsewhere\n   *\n   * declare module \"./reducer.ts\" {\n   *  export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}\n   * }\n   *\n   * const withBool = innerReducer.inject(booleanSlice);\n   *\n   * const selectBoolean = withBool.selector(\n   *   (state) => state.boolean,\n   *   (rootState: RootState) => state.inner\n   * );\n   * //    now expects to be passed RootState instead of innerReducer state\n   *\n   * ```\n   *\n   * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)\n   *\n   * ```ts\n   * const injectedReducer = rootReducer.inject(booleanSlice);\n   * const selectBoolean = injectedReducer.selector((state) => {\n   *   console.log(injectedReducer.selector.original(state).boolean) // possibly undefined\n   *   return state.boolean\n   * })\n   * ```\n   */\n  selector: {\n    /**\n     * Create a selector that guarantees that the slices injected will have a defined value when selector is run.\n     *\n     * ```ts\n     * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;\n     * //                                                                ^? boolean | undefined\n     *\n     * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {\n     *   // if action hasn't been dispatched since slice was injected, this would usually be undefined\n     *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined\n     *   return state.boolean;\n     *   //           ^? boolean\n     * })\n     * ```\n     *\n     * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)\n     *\n     * ```ts\n     * const injectedReducer = rootReducer.inject(booleanSlice);\n     * const selectBoolean = injectedReducer.selector((state) => {\n     *   console.log(injectedReducer.selector.original(state).boolean) // undefined\n     *   return state.boolean\n     * })\n     * ```\n     */\n    <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>;\n\n    /**\n     * Create a selector that guarantees that the slices injected will have a defined value when selector is run.\n     *\n     * ```ts\n     * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;\n     * //                                                                ^? boolean | undefined\n     *\n     * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {\n     *   // if action hasn't been dispatched since slice was injected, this would usually be undefined\n     *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined\n     *   return state.boolean;\n     *   //           ^? boolean\n     * })\n     * ```\n     *\n     * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.\n     *\n     * ```ts\n     *\n     * interface LazyLoadedSlices {};\n     *\n     * const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();\n     *\n     * const rootReducer = combineSlices({ inner: innerReducer });\n     *\n     * type RootState = ReturnType<typeof rootReducer>;\n     *\n     * // elsewhere\n     *\n     * declare module \"./reducer.ts\" {\n     *  interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}\n     * }\n     *\n     * const withBool = innerReducer.inject(booleanSlice);\n     *\n     * const selectBoolean = withBool.selector(\n     *   (state) => state.boolean,\n     *   (rootState: RootState) => state.inner\n     * );\n     * //    now expects to be passed RootState instead of innerReducer state\n     *\n     * ```\n     *\n     * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)\n     *\n     * ```ts\n     * const injectedReducer = rootReducer.inject(booleanSlice);\n     * const selectBoolean = injectedReducer.selector((state) => {\n     *   console.log(injectedReducer.selector.original(state).boolean) // possibly undefined\n     *   return state.boolean\n     * })\n     * ```\n     */\n    <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>;\n    /**\n     * Returns the unproxied state. Useful for debugging.\n     * @param state state Proxy, that ensures injected reducers have value\n     * @returns original, unproxied state\n     * @throws if value passed is not a state Proxy\n     */\n    original: (state: DeclaredState) => InitialState & Partial<DeclaredState>;\n  };\n}\ntype InitialState<Slices extends Array<AnySliceLike | ReducerMap>> = UnionToIntersection<Slices[number] extends infer Slice ? Slice extends AnySliceLike ? WithSlice<Slice> : StateFromReducersMapObject<Slice> : never>;\nconst isSliceLike = (maybeSliceLike: AnySliceLike | ReducerMap): maybeSliceLike is AnySliceLike => 'reducerPath' in maybeSliceLike && typeof maybeSliceLike.reducerPath === 'string';\nconst getReducers = (slices: Array<AnySliceLike | ReducerMap>) => slices.flatMap(sliceOrMap => isSliceLike(sliceOrMap) ? [[sliceOrMap.reducerPath, sliceOrMap.reducer] as const] : Object.entries(sliceOrMap));\nconst ORIGINAL_STATE = Symbol.for('rtk-state-proxy-original');\nconst isStateProxy = (value: any) => !!value && !!value[ORIGINAL_STATE];\nconst stateProxyMap = new WeakMap<object, object>();\nconst createStateProxy = <State extends object,>(state: State, reducerMap: Partial<Record<PropertyKey, Reducer>>, initialStateCache: Record<PropertyKey, unknown>) => getOrInsertComputed(stateProxyMap, state, () => new Proxy(state, {\n  get: (target, prop, receiver) => {\n    if (prop === ORIGINAL_STATE) return target;\n    const result = Reflect.get(target, prop, receiver);\n    if (typeof result === 'undefined') {\n      const cached = initialStateCache[prop];\n      if (typeof cached !== 'undefined') return cached;\n      const reducer = reducerMap[prop];\n      if (reducer) {\n        // ensure action type is random, to prevent reducer treating it differently\n        const reducerResult = reducer(undefined, {\n          type: nanoid()\n        });\n        if (typeof reducerResult === 'undefined') {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(24) : `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.`);\n        }\n        initialStateCache[prop] = reducerResult;\n        return reducerResult;\n      }\n    }\n    return result;\n  }\n})) as State;\nconst original = (state: any) => {\n  if (!isStateProxy(state)) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(25) : 'original must be used on state Proxy');\n  }\n  return state[ORIGINAL_STATE];\n};\nconst emptyObject = {};\nconst noopReducer: Reducer<Record<string, any>> = (state = emptyObject) => state;\nexport function combineSlices<Slices extends Array<AnySliceLike | ReducerMap>>(...slices: Slices): CombinedSliceReducer<Id<InitialState<Slices>>> {\n  const reducerMap = Object.fromEntries<Reducer>(getReducers(slices));\n  const getReducer = () => Object.keys(reducerMap).length ? combineReducers(reducerMap) : noopReducer;\n  let reducer = getReducer();\n  function combinedReducer(state: Record<string, unknown>, action: UnknownAction) {\n    return reducer(state, action);\n  }\n  combinedReducer.withLazyLoadedSlices = () => combinedReducer;\n  const initialStateCache: Record<PropertyKey, unknown> = {};\n  const inject = (slice: AnySliceLike, config: InjectConfig = {}): typeof combinedReducer => {\n    const {\n      reducerPath,\n      reducer: reducerToInject\n    } = slice;\n    const currentReducer = reducerMap[reducerPath];\n    if (!config.overrideExisting && currentReducer && currentReducer !== reducerToInject) {\n      if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n        console.error(`called \\`inject\\` to override already-existing reducer ${reducerPath} without specifying \\`overrideExisting: true\\``);\n      }\n      return combinedReducer;\n    }\n    if (config.overrideExisting && currentReducer !== reducerToInject) {\n      delete initialStateCache[reducerPath];\n    }\n    reducerMap[reducerPath] = reducerToInject;\n    reducer = getReducer();\n    return combinedReducer;\n  };\n  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) {\n    return function selector(state: State, ...args: Args) {\n      return selectorFn(createStateProxy(selectState ? selectState(state as any, ...args) : state, reducerMap, initialStateCache), ...args);\n    };\n  }, {\n    original\n  });\n  return Object.assign(combinedReducer, {\n    inject,\n    selector\n  }) as any;\n}","/**\n * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js\n *\n * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes\n * during build.\n * @param {number} code\n */\nexport function formatProdErrorMessage(code: number) {\n  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. ';\n}","import { isPlainObject as _iPO } from '../core/rtkImports';\n\n// remove type guard\nconst isPlainObject: (_: any) => boolean = _iPO;\nexport function copyWithStructuralSharing<T>(oldObj: any, newObj: T): T;\nexport function copyWithStructuralSharing(oldObj: any, newObj: any): any {\n  if (oldObj === newObj || !(isPlainObject(oldObj) && isPlainObject(newObj) || Array.isArray(oldObj) && Array.isArray(newObj))) {\n    return newObj;\n  }\n  const newKeys = Object.keys(newObj);\n  const oldKeys = Object.keys(oldObj);\n  let isSameObject = newKeys.length === oldKeys.length;\n  const mergeObj: any = Array.isArray(newObj) ? [] : {};\n  for (const key of newKeys) {\n    mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key]);\n    if (isSameObject) isSameObject = oldObj[key] === mergeObj[key];\n  }\n  return isSameObject ? oldObj : mergeObj;\n}","// Fast method for counting an object's keys\n// without resorting to `Object.keys(obj).length\n// Will this make a big difference in perf? Probably not\n// But we can save a few allocations.\n\nexport function countObjectKeys(obj: Record<any, any>) {\n  let count = 0;\n  for (const _key in obj) {\n    count++;\n  }\n  return count;\n}","/**\r\n * Alternative to `Array.flat(1)`\r\n * @param arr An array like [1,2,3,[1,2]]\r\n * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat\r\n */\nexport const flatten = (arr: readonly any[]) => [].concat(...arr);","/**\r\n * If either :// or // is present consider it to be an absolute url\r\n *\r\n * @param url string\r\n */\n\nexport function isAbsoluteUrl(url: string) {\n  return new RegExp(`(^|:)//`).test(url);\n}","/**\r\n * Assumes true for a non-browser env, otherwise makes a best effort\r\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState\r\n */\nexport function isDocumentVisible(): boolean {\n  // `document` may not exist in non-browser envs (like RN)\n  if (typeof document === 'undefined') {\n    return true;\n  }\n  // Match true for visible, prerender, undefined\n  return document.visibilityState !== 'hidden';\n}","export function isNotNullish<T>(v: T | null | undefined): v is T {\n  return v != null;\n}","/**\n * Assumes a browser is online if `undefined`, otherwise makes a best effort\n * @link https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine\n */\nexport function isOnline() {\n  // We set the default config value in the store, so we'd need to check for this in a SSR env\n  return typeof navigator === 'undefined' ? true : navigator.onLine === undefined ? true : navigator.onLine;\n}","import { isAbsoluteUrl } from './isAbsoluteUrl';\nconst withoutTrailingSlash = (url: string) => url.replace(/\\/$/, '');\nconst withoutLeadingSlash = (url: string) => url.replace(/^\\//, '');\nexport function joinUrls(base: string | undefined, url: string | undefined): string {\n  if (!base) {\n    return url!;\n  }\n  if (!url) {\n    return base;\n  }\n  if (isAbsoluteUrl(url)) {\n    return url;\n  }\n  const delimiter = base.endsWith('/') || !url.startsWith('?') ? '/' : '';\n  base = withoutTrailingSlash(base);\n  url = withoutLeadingSlash(url);\n  return `${base}${delimiter}${url}`;\n}","export function getOrInsert<K extends object, V>(map: WeakMap<K, V>, key: K, value: V): V;\nexport function getOrInsert<K, V>(map: Map<K, V>, key: K, value: V): V;\nexport function getOrInsert<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, value: V): V {\n  if (map.has(key)) return map.get(key) as V;\n  return map.set(key, value).get(key) as V;\n}","import { joinUrls } from './utils';\nimport { isPlainObject } from './core/rtkImports';\nimport type { BaseQueryApi, BaseQueryFn } from './baseQueryTypes';\nimport type { MaybePromise, Override } from './tsHelpers';\nexport type ResponseHandler = 'content-type' | 'json' | 'text' | ((response: Response) => Promise<any>);\ntype CustomRequestInit = Override<RequestInit, {\n  headers?: Headers | string[][] | Record<string, string | undefined> | undefined;\n}>;\nexport interface FetchArgs extends CustomRequestInit {\n  url: string;\n  params?: Record<string, any>;\n  body?: any;\n  responseHandler?: ResponseHandler;\n  validateStatus?: (response: Response, body: any) => boolean;\n  /**\n   * A number in milliseconds that represents that maximum time a request can take before timing out.\n   */\n  timeout?: number;\n}\n\n/**\n * A mini-wrapper that passes arguments straight through to\n * {@link [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)}.\n * Avoids storing `fetch` in a closure, in order to permit mocking/monkey-patching.\n */\nconst defaultFetchFn: typeof fetch = (...args) => fetch(...args);\nconst defaultValidateStatus = (response: Response) => response.status >= 200 && response.status <= 299;\nconst defaultIsJsonContentType = (headers: Headers) => /*applicat*//ion\\/(vnd\\.api\\+)?json/.test(headers.get('content-type') || '');\nexport type FetchBaseQueryError = {\n  /**\n   * * `number`:\n   *   HTTP status code\n   */\n  status: number;\n  data: unknown;\n} | {\n  /**\n   * * `\"FETCH_ERROR\"`:\n   *   An error that occurred during execution of `fetch` or the `fetchFn` callback option\n   **/\n  status: 'FETCH_ERROR';\n  data?: undefined;\n  error: string;\n} | {\n  /**\n   * * `\"PARSING_ERROR\"`:\n   *   An error happened during parsing.\n   *   Most likely a non-JSON-response was returned with the default `responseHandler` \"JSON\",\n   *   or an error occurred while executing a custom `responseHandler`.\n   **/\n  status: 'PARSING_ERROR';\n  originalStatus: number;\n  data: string;\n  error: string;\n} | {\n  /**\n   * * `\"TIMEOUT_ERROR\"`:\n   *   Request timed out\n   **/\n  status: 'TIMEOUT_ERROR';\n  data?: undefined;\n  error: string;\n} | {\n  /**\n   * * `\"CUSTOM_ERROR\"`:\n   *   A custom error type that you can return from your `queryFn` where another error might not make sense.\n   **/\n  status: 'CUSTOM_ERROR';\n  data?: unknown;\n  error: string;\n};\nfunction stripUndefined(obj: any) {\n  if (!isPlainObject(obj)) {\n    return obj;\n  }\n  const copy: Record<string, any> = {\n    ...obj\n  };\n  for (const [k, v] of Object.entries(copy)) {\n    if (v === undefined) delete copy[k];\n  }\n  return copy;\n}\nexport type FetchBaseQueryArgs = {\n  baseUrl?: string;\n  prepareHeaders?: (headers: Headers, api: Pick<BaseQueryApi, 'getState' | 'extra' | 'endpoint' | 'type' | 'forced'> & {\n    arg: string | FetchArgs;\n    extraOptions: unknown;\n  }) => MaybePromise<Headers | void>;\n  fetchFn?: (input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>;\n  paramsSerializer?: (params: Record<string, any>) => string;\n  /**\n   * 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\n   * in a predicate function for your given api to get the same automatic stringifying behavior\n   * @example\n   * ```ts\n   * const isJsonContentType = (headers: Headers) => [\"application/vnd.api+json\", \"application/json\", \"application/vnd.hal+json\"].includes(headers.get(\"content-type\")?.trim());\n   * ```\n   */\n  isJsonContentType?: (headers: Headers) => boolean;\n  /**\n   * Defaults to `application/json`;\n   */\n  jsonContentType?: string;\n\n  /**\n   * Custom replacer function used when calling `JSON.stringify()`;\n   */\n  jsonReplacer?: (this: any, key: string, value: any) => any;\n} & RequestInit & Pick<FetchArgs, 'responseHandler' | 'validateStatus' | 'timeout'>;\nexport type FetchBaseQueryMeta = {\n  request: Request;\n  response?: Response;\n};\n\n/**\n * This is a very small wrapper around fetch that aims to simplify requests.\n *\n * @example\n * ```ts\n * const baseQuery = fetchBaseQuery({\n *   baseUrl: 'https://api.your-really-great-app.com/v1/',\n *   prepareHeaders: (headers, { getState }) => {\n *     const token = (getState() as RootState).auth.token;\n *     // If we have a token set in state, let's assume that we should be passing it.\n *     if (token) {\n *       headers.set('authorization', `Bearer ${token}`);\n *     }\n *     return headers;\n *   },\n * })\n * ```\n *\n * @param {string} baseUrl\n * The base URL for an API service.\n * Typically in the format of https://example.com/\n *\n * @param {(headers: Headers, api: { getState: () => unknown; arg: string | FetchArgs; extra: unknown; endpoint: string; type: 'query' | 'mutation'; forced: boolean; }) => Headers} prepareHeaders\n * An optional function that can be used to inject headers on requests.\n * Provides a Headers object, most of the `BaseQueryApi` (`dispatch` is not available), and the arg passed into the query function.\n * Useful for setting authentication or headers that need to be set conditionally.\n *\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Headers\n *\n * @param {(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>} fetchFn\n * Accepts a custom `fetch` function if you do not want to use the default on the window.\n * Useful in SSR environments if you need to use a library such as `isomorphic-fetch` or `cross-fetch`\n *\n * @param {(params: Record<string, unknown>) => string} paramsSerializer\n * An optional function that can be used to stringify querystring parameters.\n *\n * @param {(headers: Headers) => boolean} isJsonContentType\n * An optional predicate function to determine if `JSON.stringify()` should be called on the `body` arg of `FetchArgs`\n *\n * @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`.\n *\n * @param {(this: any, key: string, value: any) => any} jsonReplacer Custom replacer function used when calling `JSON.stringify()`.\n *\n * @param {number} timeout\n * A number in milliseconds that represents the maximum time a request can take before timing out.\n */\n\nexport function fetchBaseQuery({\n  baseUrl,\n  prepareHeaders = x => x,\n  fetchFn = defaultFetchFn,\n  paramsSerializer,\n  isJsonContentType = defaultIsJsonContentType,\n  jsonContentType = 'application/json',\n  jsonReplacer,\n  timeout: defaultTimeout,\n  responseHandler: globalResponseHandler,\n  validateStatus: globalValidateStatus,\n  ...baseFetchOptions\n}: FetchBaseQueryArgs = {}): BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta> {\n  if (typeof fetch === 'undefined' && fetchFn === defaultFetchFn) {\n    console.warn('Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.');\n  }\n  return async (arg, api, extraOptions) => {\n    const {\n      getState,\n      extra,\n      endpoint,\n      forced,\n      type\n    } = api;\n    let meta: FetchBaseQueryMeta | undefined;\n    let {\n      url,\n      headers = new Headers(baseFetchOptions.headers),\n      params = undefined,\n      responseHandler = globalResponseHandler ?? 'json' as const,\n      validateStatus = globalValidateStatus ?? defaultValidateStatus,\n      timeout = defaultTimeout,\n      ...rest\n    } = typeof arg == 'string' ? {\n      url: arg\n    } : arg;\n    let abortController: AbortController | undefined,\n      signal = api.signal;\n    if (timeout) {\n      abortController = new AbortController();\n      api.signal.addEventListener('abort', abortController.abort);\n      signal = abortController.signal;\n    }\n    let config: RequestInit = {\n      ...baseFetchOptions,\n      signal,\n      ...rest\n    };\n    headers = new Headers(stripUndefined(headers));\n    config.headers = (await prepareHeaders(headers, {\n      getState,\n      arg,\n      extra,\n      endpoint,\n      forced,\n      type,\n      extraOptions\n    })) || headers;\n\n    // Only set the content-type to json if appropriate. Will not be true for FormData, ArrayBuffer, Blob, etc.\n    const isJsonifiable = (body: any) => typeof body === 'object' && (isPlainObject(body) || Array.isArray(body) || typeof body.toJSON === 'function');\n    if (!config.headers.has('content-type') && isJsonifiable(config.body)) {\n      config.headers.set('content-type', jsonContentType);\n    }\n    if (isJsonifiable(config.body) && isJsonContentType(config.headers)) {\n      config.body = JSON.stringify(config.body, jsonReplacer);\n    }\n    if (params) {\n      const divider = ~url.indexOf('?') ? '&' : '?';\n      const query = paramsSerializer ? paramsSerializer(params) : new URLSearchParams(stripUndefined(params));\n      url += divider + query;\n    }\n    url = joinUrls(baseUrl, url);\n    const request = new Request(url, config);\n    const requestClone = new Request(url, config);\n    meta = {\n      request: requestClone\n    };\n    let response,\n      timedOut = false,\n      timeoutId = abortController && setTimeout(() => {\n        timedOut = true;\n        abortController!.abort();\n      }, timeout);\n    try {\n      response = await fetchFn(request);\n    } catch (e) {\n      return {\n        error: {\n          status: timedOut ? 'TIMEOUT_ERROR' : 'FETCH_ERROR',\n          error: String(e)\n        },\n        meta\n      };\n    } finally {\n      if (timeoutId) clearTimeout(timeoutId);\n      abortController?.signal.removeEventListener('abort', abortController.abort);\n    }\n    const responseClone = response.clone();\n    meta.response = responseClone;\n    let resultData: any;\n    let responseText: string = '';\n    try {\n      let handleResponseError;\n      await Promise.all([handleResponse(response, responseHandler).then(r => resultData = r, e => handleResponseError = e),\n      // see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182\n      // we *have* to \"use up\" both streams at the same time or they will stop running in node-fetch scenarios\n      responseClone.text().then(r => responseText = r, () => {})]);\n      if (handleResponseError) throw handleResponseError;\n    } catch (e) {\n      return {\n        error: {\n          status: 'PARSING_ERROR',\n          originalStatus: response.status,\n          data: responseText,\n          error: String(e)\n        },\n        meta\n      };\n    }\n    return validateStatus(response, resultData) ? {\n      data: resultData,\n      meta\n    } : {\n      error: {\n        status: response.status,\n        data: resultData\n      },\n      meta\n    };\n  };\n  async function handleResponse(response: Response, responseHandler: ResponseHandler) {\n    if (typeof responseHandler === 'function') {\n      return responseHandler(response);\n    }\n    if (responseHandler === 'content-type') {\n      responseHandler = isJsonContentType(response.headers) ? 'json' : 'text';\n    }\n    if (responseHandler === 'json') {\n      const text = await response.text();\n      return text.length ? JSON.parse(text) : null;\n    }\n    return response.text();\n  }\n}","export class HandledError {\n  constructor(public readonly value: any, public readonly meta: any = undefined) {}\n}","import type { BaseQueryApi, BaseQueryArg, BaseQueryEnhancer, BaseQueryError, BaseQueryExtraOptions, BaseQueryFn, BaseQueryMeta } from './baseQueryTypes';\nimport type { FetchBaseQueryError } from './fetchBaseQuery';\nimport { HandledError } from './HandledError';\n\n/**\n * Exponential backoff based on the attempt number.\n *\n * @remarks\n * 1. 600ms * random(0.4, 1.4)\n * 2. 1200ms * random(0.4, 1.4)\n * 3. 2400ms * random(0.4, 1.4)\n * 4. 4800ms * random(0.4, 1.4)\n * 5. 9600ms * random(0.4, 1.4)\n *\n * @param attempt - Current attempt\n * @param maxRetries - Maximum number of retries\n */\nasync function defaultBackoff(attempt: number = 0, maxRetries: number = 5) {\n  const attempts = Math.min(attempt, maxRetries);\n  const timeout = ~~((Math.random() + 0.4) * (300 << attempts)); // Force a positive int in the case we make this an option\n  await new Promise(resolve => setTimeout((res: any) => resolve(res), timeout));\n}\ntype RetryConditionFunction = (error: BaseQueryError<BaseQueryFn>, args: BaseQueryArg<BaseQueryFn>, extraArgs: {\n  attempt: number;\n  baseQueryApi: BaseQueryApi;\n  extraOptions: BaseQueryExtraOptions<BaseQueryFn> & RetryOptions;\n}) => boolean;\nexport type RetryOptions = {\n  /**\n   * Function used to determine delay between retries\n   */\n  backoff?: (attempt: number, maxRetries: number) => Promise<void>;\n} & ({\n  /**\n   * How many times the query will be retried (default: 5)\n   */\n  maxRetries?: number;\n  retryCondition?: undefined;\n} | {\n  /**\n   * Callback to determine if a retry should be attempted.\n   * Return `true` for another retry and `false` to quit trying prematurely.\n   */\n  retryCondition?: RetryConditionFunction;\n  maxRetries?: undefined;\n});\nfunction fail<BaseQuery extends BaseQueryFn = BaseQueryFn>(error: BaseQueryError<BaseQuery>, meta?: BaseQueryMeta<BaseQuery>): never {\n  throw Object.assign(new HandledError({\n    error,\n    meta\n  }), {\n    throwImmediately: true\n  });\n}\nconst EMPTY_OPTIONS = {};\nconst retryWithBackoff: BaseQueryEnhancer<unknown, RetryOptions, RetryOptions | void> = (baseQuery, defaultOptions) => async (args, api, extraOptions) => {\n  // We need to figure out `maxRetries` before we define `defaultRetryCondition.\n  // This is probably goofy, but ought to work.\n  // Put our defaults in one array, filter out undefineds, grab the last value.\n  const possibleMaxRetries: number[] = [5, (defaultOptions as any || EMPTY_OPTIONS).maxRetries, (extraOptions as any || EMPTY_OPTIONS).maxRetries].filter(x => x !== undefined);\n  const [maxRetries] = possibleMaxRetries.slice(-1);\n  const defaultRetryCondition: RetryConditionFunction = (_, __, {\n    attempt\n  }) => attempt <= maxRetries;\n  const options: {\n    maxRetries: number;\n    backoff: typeof defaultBackoff;\n    retryCondition: typeof defaultRetryCondition;\n  } = {\n    maxRetries,\n    backoff: defaultBackoff,\n    retryCondition: defaultRetryCondition,\n    ...defaultOptions,\n    ...extraOptions\n  };\n  let retry = 0;\n  while (true) {\n    try {\n      const result = await baseQuery(args, api, extraOptions);\n      // baseQueries _should_ return an error property, so we should check for that and throw it to continue retrying\n      if (result.error) {\n        throw new HandledError(result);\n      }\n      return result;\n    } catch (e: any) {\n      retry++;\n      if (e.throwImmediately) {\n        if (e instanceof HandledError) {\n          return e.value;\n        }\n\n        // We don't know what this is, so we have to rethrow it\n        throw e;\n      }\n      if (e instanceof HandledError && !options.retryCondition(e.value.error as FetchBaseQueryError, args, {\n        attempt: retry,\n        baseQueryApi: api,\n        extraOptions\n      })) {\n        return e.value;\n      }\n      await options.backoff(retry, options.maxRetries);\n    }\n  }\n};\n\n/**\n * A utility that can wrap `baseQuery` in the API definition to provide retries with a basic exponential backoff.\n *\n * @example\n *\n * ```ts\n * // codeblock-meta title=\"Retry every request 5 times by default\"\n * import { createApi, fetchBaseQuery, retry } from '@reduxjs/toolkit/query/react'\n * interface Post {\n *   id: number\n *   name: string\n * }\n * type PostsResponse = Post[]\n *\n * // maxRetries: 5 is the default, and can be omitted. Shown for documentation purposes.\n * const staggeredBaseQuery = retry(fetchBaseQuery({ baseUrl: '/' }), { maxRetries: 5 });\n * export const api = createApi({\n *   baseQuery: staggeredBaseQuery,\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsResponse, void>({\n *       query: () => ({ url: 'posts' }),\n *     }),\n *     getPost: build.query<PostsResponse, string>({\n *       query: (id) => ({ url: `post/${id}` }),\n *       extraOptions: { maxRetries: 8 }, // You can override the retry behavior on each endpoint\n *     }),\n *   }),\n * });\n *\n * export const { useGetPostsQuery, useGetPostQuery } = api;\n * ```\n */\nexport const retry = /* @__PURE__ */Object.assign(retryWithBackoff, {\n  fail\n});","import type { ThunkDispatch, ActionCreatorWithoutPayload // Workaround for API-Extractor\n} from '@reduxjs/toolkit';\nimport { createAction } from './rtkImports';\nexport const onFocus = /* @__PURE__ */createAction('__rtkq/focused');\nexport const onFocusLost = /* @__PURE__ */createAction('__rtkq/unfocused');\nexport const onOnline = /* @__PURE__ */createAction('__rtkq/online');\nexport const onOffline = /* @__PURE__ */createAction('__rtkq/offline');\nlet initialized = false;\n\n/**\n * A utility used to enable `refetchOnMount` and `refetchOnReconnect` behaviors.\n * It requires the dispatch method from your store.\n * Calling `setupListeners(store.dispatch)` will configure listeners with the recommended defaults,\n * but you have the option of providing a callback for more granular control.\n *\n * @example\n * ```ts\n * setupListeners(store.dispatch)\n * ```\n *\n * @param dispatch - The dispatch method from your store\n * @param customHandler - An optional callback for more granular control over listener behavior\n * @returns Return value of the handler.\n * The default handler returns an `unsubscribe` method that can be called to remove the listeners.\n */\nexport function setupListeners(dispatch: ThunkDispatch<any, any, any>, customHandler?: (dispatch: ThunkDispatch<any, any, any>, actions: {\n  onFocus: typeof onFocus;\n  onFocusLost: typeof onFocusLost;\n  onOnline: typeof onOnline;\n  onOffline: typeof onOffline;\n}) => () => void) {\n  function defaultHandler() {\n    const handleFocus = () => dispatch(onFocus());\n    const handleFocusLost = () => dispatch(onFocusLost());\n    const handleOnline = () => dispatch(onOnline());\n    const handleOffline = () => dispatch(onOffline());\n    const handleVisibilityChange = () => {\n      if (window.document.visibilityState === 'visible') {\n        handleFocus();\n      } else {\n        handleFocusLost();\n      }\n    };\n    if (!initialized) {\n      if (typeof window !== 'undefined' && window.addEventListener) {\n        // Handle focus events\n        window.addEventListener('visibilitychange', handleVisibilityChange, false);\n        window.addEventListener('focus', handleFocus, false);\n\n        // Handle connection events\n        window.addEventListener('online', handleOnline, false);\n        window.addEventListener('offline', handleOffline, false);\n        initialized = true;\n      }\n    }\n    const unsubscribe = () => {\n      window.removeEventListener('focus', handleFocus);\n      window.removeEventListener('visibilitychange', handleVisibilityChange);\n      window.removeEventListener('online', handleOnline);\n      window.removeEventListener('offline', handleOffline);\n      initialized = false;\n    };\n    return unsubscribe;\n  }\n  return customHandler ? customHandler(dispatch, {\n    onFocus,\n    onFocusLost,\n    onOffline,\n    onOnline\n  }) : defaultHandler();\n}","import type { Api } from '@reduxjs/toolkit/query';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { BaseQueryApi, BaseQueryArg, BaseQueryError, BaseQueryExtraOptions, BaseQueryFn, BaseQueryMeta, BaseQueryResult, QueryReturnValue } from './baseQueryTypes';\nimport type { CacheCollectionQueryExtraOptions } from './core/buildMiddleware/cacheCollection';\nimport type { CacheLifecycleInfiniteQueryExtraOptions, CacheLifecycleMutationExtraOptions, CacheLifecycleQueryExtraOptions } from './core/buildMiddleware/cacheLifecycle';\nimport type { QueryLifecycleInfiniteQueryExtraOptions, QueryLifecycleMutationExtraOptions, QueryLifecycleQueryExtraOptions } from './core/buildMiddleware/queryLifecycle';\nimport type { InfiniteData, InfiniteQueryConfigOptions, QuerySubState, RootState } from './core/index';\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport type { NEVER } from './fakeBaseQuery';\nimport type { CastAny, HasRequiredProps, MaybePromise, NonUndefined, OmitFromUnion, UnwrapPromise } from './tsHelpers';\nimport { isNotNullish } from './utils';\nimport type { NamedSchemaError } from './standardSchema';\nconst rawResultType = /* @__PURE__ */Symbol();\nconst resultType = /* @__PURE__ */Symbol();\nconst baseQuery = /* @__PURE__ */Symbol();\nexport interface SchemaFailureInfo {\n  endpoint: string;\n  arg: any;\n  type: 'query' | 'mutation';\n  queryCacheKey?: string;\n}\nexport type SchemaFailureHandler = (error: NamedSchemaError, info: SchemaFailureInfo) => void;\nexport type SchemaFailureConverter<BaseQuery extends BaseQueryFn> = (error: NamedSchemaError, info: SchemaFailureInfo) => BaseQueryError<BaseQuery>;\nexport type EndpointDefinitionWithQuery<QueryArg, BaseQuery extends BaseQueryFn, ResultType, RawResultType extends BaseQueryResult<BaseQuery>> = {\n  /**\n   * `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.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"query example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Post'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       // highlight-start\n   *       query: () => 'posts',\n   *       // highlight-end\n   *     }),\n   *     addPost: build.mutation<Post, Partial<Post>>({\n   *      // highlight-start\n   *      query: (body) => ({\n   *        url: `posts`,\n   *        method: 'POST',\n   *        body,\n   *      }),\n   *      // highlight-end\n   *      invalidatesTags: [{ type: 'Post', id: 'LIST' }],\n   *    }),\n   *   })\n   * })\n   * ```\n   */\n  query(arg: QueryArg): BaseQueryArg<BaseQuery>;\n  queryFn?: never;\n  /**\n   * A function to manipulate the data returned by a query or mutation.\n   */\n  transformResponse?(baseQueryReturnValue: RawResultType, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): ResultType | Promise<ResultType>;\n  /**\n   * A function to manipulate the data returned by a failed query or mutation.\n   */\n  transformErrorResponse?(baseQueryReturnValue: BaseQueryError<BaseQuery>, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): unknown;\n\n  /**\n   * A schema for the result *before* it's passed to `transformResponse`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const postSchema = v.object({ id: v.number(), name: v.string() })\n   * type Post = v.InferOutput<typeof postSchema>\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPostName: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       rawResponseSchema: postSchema,\n   *       transformResponse: (post) => post.name,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  rawResponseSchema?: StandardSchemaV1<RawResultType>;\n\n  /**\n   * A schema for the error object returned by the `query` or `queryFn`, *before* it's passed to `transformErrorResponse`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import {customBaseQuery, baseQueryErrorSchema} from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       rawErrorResponseSchema: baseQueryErrorSchema,\n   *       transformErrorResponse: (error) => error.data,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  rawErrorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>;\n};\nexport type EndpointDefinitionWithQueryFn<QueryArg, BaseQuery extends BaseQueryFn, ResultType> = {\n  /**\n   * Can be used in place of `query` as an inline function that bypasses `baseQuery` completely for the endpoint.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Basic queryFn example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *     }),\n   *     flipCoin: build.query<'heads' | 'tails', void>({\n   *       // highlight-start\n   *       queryFn(arg, queryApi, extraOptions, baseQuery) {\n   *         const randomVal = Math.random()\n   *         if (randomVal < 0.45) {\n   *           return { data: 'heads' }\n   *         }\n   *         if (randomVal < 0.9) {\n   *           return { data: 'tails' }\n   *         }\n   *         return { error: { status: 500, statusText: 'Internal Server Error', data: \"Coin landed on its edge!\" } }\n   *       }\n   *       // highlight-end\n   *     })\n   *   })\n   * })\n   * ```\n   */\n  queryFn(arg: QueryArg, api: BaseQueryApi, extraOptions: BaseQueryExtraOptions<BaseQuery>, baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>): MaybePromise<QueryReturnValue<ResultType, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>>;\n  query?: never;\n  transformResponse?: never;\n  transformErrorResponse?: never;\n  rawResponseSchema?: never;\n  rawErrorResponseSchema?: never;\n};\ntype BaseEndpointTypes<QueryArg, BaseQuery extends BaseQueryFn, ResultType> = {\n  QueryArg: QueryArg;\n  BaseQuery: BaseQuery;\n  ResultType: ResultType;\n};\ninterface CommonEndpointDefinition<QueryArg, BaseQuery extends BaseQueryFn, ResultType> {\n  /**\n   * A schema for the arguments to be passed to the `query` or `queryFn`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       argSchema: v.object({ id: v.number() }),\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  argSchema?: StandardSchemaV1<QueryArg>;\n\n  /**\n   * A schema for the result (including `transformResponse` if provided).\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const postSchema = v.object({ id: v.number(), name: v.string() })\n   * type Post = v.InferOutput<typeof postSchema>\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: postSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  responseSchema?: StandardSchemaV1<ResultType>;\n\n  /**\n   * A schema for the error object returned by the `query` or `queryFn` (including `transformErrorResponse` if provided).\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import { customBaseQuery, baseQueryErrorSchema } from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       errorResponseSchema: baseQueryErrorSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  errorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>;\n\n  /**\n   * A schema for the `meta` property returned by the `query` or `queryFn`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import { customBaseQuery, baseQueryMetaSchema } from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       metaSchema: baseQueryMetaSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  metaSchema?: StandardSchemaV1<BaseQueryMeta<BaseQuery>>;\n\n  /**\n   * Defaults to `true`.\n   *\n   * Most apps should leave this setting on. The only time it can be a performance issue\n   * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and\n   * you're unable to paginate it.\n   *\n   * For details of how this works, please see the below. When it is set to `false`,\n   * every request will cause subscribed components to rerender, even when the data has not changed.\n   *\n   * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing\n   */\n  structuralSharing?: boolean;\n\n  /**\n   * A function that is called when a schema validation fails.\n   *\n   * 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).\n   *\n   * `NamedSchemaError` has the following properties:\n   * - `issues`: an array of issues that caused the validation to fail\n   * - `value`: the value that was passed to the schema\n   * - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       onSchemaFailure: (error, info) => {\n   *         console.error(error, info)\n   *       },\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  onSchemaFailure?: SchemaFailureHandler;\n\n  /**\n   * Convert a schema validation failure into an error shape matching base query errors.\n   *\n   * When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *       catchSchemaFailure: (error, info) => ({\n   *         status: \"CUSTOM_ERROR\",\n   *         error: error.schemaName + \" failed validation\",\n   *         data: error.issues,\n   *       }),\n   *     }),\n   *   }),\n   * })\n   * ```\n   */\n  catchSchemaFailure?: SchemaFailureConverter<BaseQuery>;\n\n  /**\n   * Defaults to `false`.\n   *\n   * If set to `true`, will skip schema validation for this endpoint.\n   * Overrides the global setting.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *       skipSchemaValidation: process.env.NODE_ENV === \"test\", // skip schema validation in tests, since we'll be mocking the response\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  skipSchemaValidation?: boolean;\n}\nexport 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> & {\n  /* phantom type */\n  [rawResultType]?: RawResultType;\n  /* phantom type */\n  [resultType]?: ResultType;\n  /* phantom type */\n  [baseQuery]?: BaseQuery;\n} & HasRequiredProps<BaseQueryExtraOptions<BaseQuery>, {\n  extraOptions: BaseQueryExtraOptions<BaseQuery>;\n}, {\n  extraOptions?: BaseQueryExtraOptions<BaseQuery>;\n}>;\nexport enum DefinitionType {\n  query = 'query',\n  mutation = 'mutation',\n  infinitequery = 'infinitequery',\n}\ntype TagDescriptionArray<TagTypes extends string> = ReadonlyArray<TagDescription<TagTypes> | undefined | null>;\nexport type GetResultDescriptionFn<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = (result: ResultType | undefined, error: ErrorType | undefined, arg: QueryArg, meta: MetaType) => TagDescriptionArray<TagTypes>;\nexport type FullTagDescription<TagType> = {\n  type: TagType;\n  id?: number | string;\n};\nexport type TagDescription<TagType> = TagType | FullTagDescription<TagType>;\n\n/**\n * @public\n */\nexport type ResultDescription<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = TagDescriptionArray<TagTypes> | GetResultDescriptionFn<TagTypes, ResultType, QueryArg, ErrorType, MetaType>;\ntype QueryTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n   * ```\n   */\n  QueryDefinition: QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\n\n/**\n * @public\n */\nexport interface QueryExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> extends CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {\n  type: DefinitionType.query;\n\n  /**\n   * Used by `query` endpoints. Determines which 'tag' is attached to the cached data returned by the query.\n   * Expects an array of tag type strings, an array of objects of tag types with ids, or a function that returns such an array.\n   * 1.  `['Post']` - equivalent to `2`\n   * 2.  `[{ type: 'Post' }]` - equivalent to `1`\n   * 3.  `[{ type: 'Post', id: 1 }]`\n   * 4.  `(result, error, arg) => ['Post']` - equivalent to `5`\n   * 5.  `(result, error, arg) => [{ type: 'Post' }]` - equivalent to `4`\n   * 6.  `(result, error, arg) => [{ type: 'Post', id: 1 }]`\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"providesTags example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Posts'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       // highlight-start\n   *       providesTags: (result) =>\n   *         result\n   *           ? [\n   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n   *               { type: 'Posts', id: 'LIST' },\n   *             ]\n   *           : [{ type: 'Posts', id: 'LIST' }],\n   *       // highlight-end\n   *     })\n   *   })\n   * })\n   * ```\n   */\n  providesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A query should not invalidate tags in the cache.\n   */\n  invalidatesTags?: never;\n\n  /**\n   * Can be provided to return a custom cache key value based on the query arguments.\n   *\n   * 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.\n   *\n   * 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.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * interface MyApiClient {\n   *   fetchPost: (id: string) => Promise<Post>\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    // Example: an endpoint with an API client passed in as an argument,\n   *    // but only the item ID should be used as the cache key\n   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({\n   *      queryFn: async ({ id, client }) => {\n   *        const post = await client.fetchPost(id)\n   *        return { data: post }\n   *      },\n   *      // highlight-start\n   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n   *        const { id } = queryArgs\n   *        // This can return a string, an object, a number, or a boolean.\n   *        // If it returns an object, number or boolean, that value\n   *        // will be serialized automatically via `defaultSerializeQueryArgs`\n   *        return { id } // omit `client` from the cache key\n   *\n   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n   *        // return defaultSerializeQueryArgs({\n   *        //   endpointName,\n   *        //   queryArgs: { id },\n   *        //   endpointDefinition\n   *        // })\n   *        // Or  create and return a string yourself:\n   *        // return `getPost(${id})`\n   *      },\n   *      // highlight-end\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;\n\n  /**\n   * Can be provided to merge an incoming response value into the current cache data.\n   * If supplied, no automatic structural sharing will be applied - it's up to\n   * you to update the cache appropriately.\n   *\n   * Since RTKQ normally replaces cache entries with the new response, you will usually\n   * need to use this with the `serializeQueryArgs` or `forceRefetch` options to keep\n   * an existing cache entry so that it can be updated.\n   *\n   * Since this is wrapped with Immer, you may either mutate the `currentCacheValue` directly,\n   * or return a new value, but _not_ both at once.\n   *\n   * Will only be called if the existing `currentCacheData` is _not_ `undefined` - on first response,\n   * the cache entry will just save the response data directly.\n   *\n   * Useful if you don't want a new request to completely override the current cache value,\n   * maybe because you have manually updated it from another source and don't want those\n   * updates to get lost.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"merge: pagination\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    listItems: build.query<string[], number>({\n   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,\n   *     // Only have one cache entry because the arg always maps to one string\n   *     serializeQueryArgs: ({ endpointName }) => {\n   *       return endpointName\n   *      },\n   *      // Always merge incoming data to the cache entry\n   *      merge: (currentCache, newItems) => {\n   *        currentCache.push(...newItems)\n   *      },\n   *      // Refetch when the page arg changes\n   *      forceRefetch({ currentArg, previousArg }) {\n   *        return currentArg !== previousArg\n   *      },\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  merge?(currentCacheData: ResultType, responseData: ResultType, otherArgs: {\n    arg: QueryArg;\n    baseQueryMeta: BaseQueryMeta<BaseQuery>;\n    requestId: string;\n    fulfilledTimeStamp: number;\n  }): ResultType | void;\n\n  /**\n   * Check to see if the endpoint should force a refetch in cases where it normally wouldn't.\n   * This is primarily useful for \"infinite scroll\" / pagination use cases where\n   * RTKQ is keeping a single cache entry that is added to over time, in combination\n   * with `serializeQueryArgs` returning a fixed cache key and a `merge` callback\n   * set to add incoming data to the cache entry each time.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"forceRefresh: pagination\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    listItems: build.query<string[], number>({\n   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,\n   *     // Only have one cache entry because the arg always maps to one string\n   *     serializeQueryArgs: ({ endpointName }) => {\n   *       return endpointName\n   *      },\n   *      // Always merge incoming data to the cache entry\n   *      merge: (currentCache, newItems) => {\n   *        currentCache.push(...newItems)\n   *      },\n   *      // Refetch when the page arg changes\n   *      forceRefetch({ currentArg, previousArg }) {\n   *        return currentArg !== previousArg\n   *      },\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  forceRefetch?(params: {\n    currentArg: QueryArg | undefined;\n    previousArg: QueryArg | undefined;\n    state: RootState<any, any, string>;\n    endpointState?: QuerySubState<any>;\n  }): boolean;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: QueryTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n}\nexport 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>;\nexport type InfiniteQueryTypes<QueryArg, PageParam, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n   * ```\n   */\n  InfiniteQueryDefinition: InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\nexport interface InfiniteQueryExtraOptions<TagTypes extends string, ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> extends CacheLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {\n  type: DefinitionType.infinitequery;\n  providesTags?: ResultDescription<TagTypes, InfiniteData<ResultType, PageParam>, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A query should not invalidate tags in the cache.\n   */\n  invalidatesTags?: never;\n\n  /**\n   * Required options to configure the infinite query behavior.\n   * `initialPageParam` and `getNextPageParam` are required, to\n   * ensure the infinite query can properly fetch the next page of data.\n   * `initialPageParam` may be specified when using the\n   * endpoint, to override the default value.\n   * `maxPages` and `getPreviousPageParam` are both optional.\n   * \n   * @example\n   * \n   * ```ts\n   * // codeblock-meta title=\"infiniteQueryOptions example\"\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * \n   * type Pokemon = {\n   *   id: string\n   *   name: string\n   * }\n   * \n   * const pokemonApi = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n   *   endpoints: (build) => ({\n   *     getInfinitePokemonWithMax: build.infiniteQuery<Pokemon[], string, number>({\n   *       infiniteQueryOptions: {\n   *         initialPageParam: 0,\n   *         maxPages: 3,\n   *         getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) =>\n   *           lastPageParam + 1,\n   *         getPreviousPageParam: (\n   *           firstPage,\n   *           allPages,\n   *           firstPageParam,\n   *           allPageParams,\n   *         ) => {\n   *           return firstPageParam > 0 ? firstPageParam - 1 : undefined\n   *         },\n   *       },\n   *       query({pageParam}) {\n   *         return `https://example.com/listItems?page=${pageParam}`\n   *       },\n   *     }),\n   *   }),\n   * })\n   \n   * ```\n   */\n  infiniteQueryOptions: InfiniteQueryConfigOptions<ResultType, PageParam, QueryArg>;\n\n  /**\n   * Can be provided to return a custom cache key value based on the query arguments.\n   *\n   * 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.\n   *\n   * 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.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * interface MyApiClient {\n   *   fetchPost: (id: string) => Promise<Post>\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    // Example: an endpoint with an API client passed in as an argument,\n   *    // but only the item ID should be used as the cache key\n   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({\n   *      queryFn: async ({ id, client }) => {\n   *        const post = await client.fetchPost(id)\n   *        return { data: post }\n   *      },\n   *      // highlight-start\n   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n   *        const { id } = queryArgs\n   *        // This can return a string, an object, a number, or a boolean.\n   *        // If it returns an object, number or boolean, that value\n   *        // will be serialized automatically via `defaultSerializeQueryArgs`\n   *        return { id } // omit `client` from the cache key\n   *\n   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n   *        // return defaultSerializeQueryArgs({\n   *        //   endpointName,\n   *        //   queryArgs: { id },\n   *        //   endpointDefinition\n   *        // })\n   *        // Or  create and return a string yourself:\n   *        // return `getPost(${id})`\n   *      },\n   *      // highlight-end\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: InfiniteQueryTypes<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath>;\n}\nexport type InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> =\n// Infinite query endpoints receive `{queryArg, pageParam}`\nBaseEndpointDefinition<InfiniteQueryCombinedArg<QueryArg, PageParam>, BaseQuery, ResultType, RawResultType> & InfiniteQueryExtraOptions<TagTypes, ResultType, QueryArg, PageParam, BaseQuery, ReducerPath>;\ntype MutationTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseMutation<typeof api.endpoints.query.Types.MutationDefinition> = ...\n   * ```\n   */\n  MutationDefinition: MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\n\n/**\n * @public\n */\nexport interface MutationExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> extends CacheLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath> {\n  type: DefinitionType.mutation;\n\n  /**\n   * Used by `mutation` endpoints. Determines which cached data should be either re-fetched or removed from the cache.\n   * Expects the same shapes as `providesTags`.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"invalidatesTags example\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Posts'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       providesTags: (result) =>\n   *         result\n   *           ? [\n   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n   *               { type: 'Posts', id: 'LIST' },\n   *             ]\n   *           : [{ type: 'Posts', id: 'LIST' }],\n   *     }),\n   *     addPost: build.mutation<Post, Partial<Post>>({\n   *       query(body) {\n   *         return {\n   *           url: `posts`,\n   *           method: 'POST',\n   *           body,\n   *         }\n   *       },\n   *       // highlight-start\n   *       invalidatesTags: [{ type: 'Posts', id: 'LIST' }],\n   *       // highlight-end\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  invalidatesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A mutation should not provide tags to the cache.\n   */\n  providesTags?: never;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: MutationTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n}\nexport 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>;\nexport 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>;\nexport type EndpointDefinitions = Record<string, EndpointDefinition<any, any, any, any, any, any, any>>;\nexport function isQueryDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is QueryDefinition<any, any, any, any, any, any> {\n  return e.type === DefinitionType.query;\n}\nexport function isMutationDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is MutationDefinition<any, any, any, any, any, any> {\n  return e.type === DefinitionType.mutation;\n}\nexport function isInfiniteQueryDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is InfiniteQueryDefinition<any, any, any, any, any, any, any> {\n  return e.type === DefinitionType.infinitequery;\n}\nexport function isAnyQueryDefinition(e: EndpointDefinition<any, any, any, any>): e is QueryDefinition<any, any, any, any> | InfiniteQueryDefinition<any, any, any, any, any> {\n  return isQueryDefinition(e) || isInfiniteQueryDefinition(e);\n}\nexport type EndpointBuilder<BaseQuery extends BaseQueryFn, TagTypes extends string, ReducerPath extends string> = {\n  /**\n   * An endpoint definition that retrieves data, and may provide tags to the cache.\n   *\n   * @example\n   * ```js\n   * // codeblock-meta title=\"Example of all query endpoint options\"\n   * const api = createApi({\n   *  baseQuery,\n   *  endpoints: (build) => ({\n   *    getPost: build.query({\n   *      query: (id) => ({ url: `post/${id}` }),\n   *      // Pick out data and prevent nested properties in a hook or selector\n   *      transformResponse: (response) => response.data,\n   *      // Pick out error and prevent nested properties in a hook or selector\n   *      transformErrorResponse: (response) => response.error,\n   *      // `result` is the server response\n   *      providesTags: (result, error, id) => [{ type: 'Post', id }],\n   *      // trigger side effects or optimistic updates\n   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry, updateCachedData }) {},\n   *      // handle subscriptions etc\n   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry, updateCachedData }) {},\n   *    }),\n   *  }),\n   *});\n   *```\n   */\n  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>;\n\n  /**\n   * An endpoint definition that alters data on the server or will possibly invalidate the cache.\n   *\n   * @example\n   * ```js\n   * // codeblock-meta title=\"Example of all mutation endpoint options\"\n   * const api = createApi({\n   *   baseQuery,\n   *   endpoints: (build) => ({\n   *     updatePost: build.mutation({\n   *       query: ({ id, ...patch }) => ({ url: `post/${id}`, method: 'PATCH', body: patch }),\n   *       // Pick out data and prevent nested properties in a hook or selector\n   *       transformResponse: (response) => response.data,\n   *       // Pick out error and prevent nested properties in a hook or selector\n   *       transformErrorResponse: (response) => response.error,\n   *       // `result` is the server response\n   *       invalidatesTags: (result, error, id) => [{ type: 'Post', id }],\n   *      // trigger side effects or optimistic updates\n   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry }) {},\n   *      // handle subscriptions etc\n   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry }) {},\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  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>;\n  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>;\n};\nexport type AssertTagTypes = <T extends FullTagDescription<string>>(t: T) => T;\nexport 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>[] {\n  if (isFunction(description)) {\n    return description(result as ResultType, error as undefined, queryArg, meta as MetaType).filter(isNotNullish).map(expandTagDescription).map(assertTagTypes);\n  }\n  if (Array.isArray(description)) {\n    return description.map(expandTagDescription).map(assertTagTypes);\n  }\n  return [];\n}\nfunction isFunction<T>(t: T): t is Extract<T, Function> {\n  return typeof t === 'function';\n}\nexport function expandTagDescription(description: TagDescription<string>): FullTagDescription<string> {\n  return typeof description === 'string' ? {\n    type: description\n  } : description;\n}\nexport type QueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<infer QA, any, any, any> ? QA : never;\n\n// Just extracting `QueryArg` from `BaseEndpointDefinition`\n// doesn't sufficiently match here.\n// We need to explicitly match against `InfiniteQueryDefinition`\nexport type InfiniteQueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends InfiniteQueryDefinition<infer QA, any, any, any, any, any, any> ? QA : never;\nexport 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;\nexport type ResultTypeFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<any, any, infer RT, any> ? RT : unknown;\nexport 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;\nexport 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;\nexport 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;\nexport type InfiniteQueryCombinedArg<QueryArg, PageParam> = {\n  queryArg: QueryArg;\n  pageParam: PageParam;\n};\nexport type TagTypesFromApi<T> = T extends Api<any, any, any, infer TagTypes> ? TagTypes : never;\nexport type DefinitionsFromApi<T> = T extends Api<any, infer Definitions, any, any> ? Definitions : never;\nexport type TransformedResponse<NewDefinitions extends EndpointDefinitions, K, ResultType> = K extends keyof NewDefinitions ? NewDefinitions[K]['transformResponse'] extends undefined ? ResultType : UnwrapPromise<ReturnType<NonUndefined<NewDefinitions[K]['transformResponse']>>> : ResultType;\nexport 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;\nexport 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 };","import type { AsyncThunk, AsyncThunkPayloadCreator, Draft, ThunkAction, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport type { Patch } from 'immer';\nimport { isDraftable, produceWithPatches } from 'immer';\nimport type { Api, ApiContext } from '../apiTypes';\nimport type { BaseQueryError, BaseQueryFn, QueryReturnValue } from '../baseQueryTypes';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { AssertTagTypes, EndpointDefinition, EndpointDefinitions, InfiniteQueryArgFrom, InfiniteQueryCombinedArg, InfiniteQueryDefinition, MutationDefinition, PageParamFrom, QueryArgFrom, QueryDefinition, ResultDescription, ResultTypeFrom, SchemaFailureConverter, SchemaFailureHandler, SchemaFailureInfo } from '../endpointDefinitions';\nimport { calculateProvidedBy, isInfiniteQueryDefinition, isQueryDefinition } from '../endpointDefinitions';\nimport { HandledError } from '../HandledError';\nimport type { UnwrapPromise } from '../tsHelpers';\nimport type { RootState, QueryKeys, QuerySubstateIdentifier, InfiniteData, InfiniteQueryConfigOptions, QueryCacheKey, InfiniteQueryDirection, InfiniteQueryKeys } from './apiState';\nimport { QueryStatus } from './apiState';\nimport type { InfiniteQueryActionCreatorResult, QueryActionCreatorResult, StartInfiniteQueryActionCreatorOptions, StartQueryActionCreatorOptions } from './buildInitiate';\nimport { forceQueryFnSymbol, isUpsertQuery } from './buildInitiate';\nimport type { AllSelectors } from './buildSelectors';\nimport type { ApiEndpointQuery, PrefetchOptions } from './module';\nimport { createAsyncThunk, isAllOf, isFulfilled, isPending, isRejected, isRejectedWithValue, SHOULD_AUTOBATCH } from './rtkImports';\nimport { parseWithSchema, NamedSchemaError } from '../standardSchema';\nexport type BuildThunksApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>> = Matchers<QueryThunk, Definition>;\nexport type BuildThunksApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = Matchers<InfiniteQueryThunk<any>, Definition>;\nexport type BuildThunksApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>> = Matchers<MutationThunk, Definition>;\ntype 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 & {\n  originalArgs: QueryArg;\n}, ATConfig & {\n  rejectValue: BaseQueryError<BaseQueryFn>;\n}> : 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 & {\n  originalArgs: QueryArg;\n}, ATConfig & {\n  rejectValue: BaseQueryError<BaseQueryFn>;\n}> : never : never;\nexport type PendingAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['pending']>;\nexport type FulfilledAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['fulfilled']>;\nexport type RejectedAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['rejected']>;\nexport type Matcher<M> = (value: any) => value is M;\nexport interface Matchers<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> {\n  matchPending: Matcher<PendingAction<Thunk, Definition>>;\n  matchFulfilled: Matcher<FulfilledAction<Thunk, Definition>>;\n  matchRejected: Matcher<RejectedAction<Thunk, Definition>>;\n}\nexport type QueryThunkArg = QuerySubstateIdentifier & StartQueryActionCreatorOptions & {\n  type: 'query';\n  originalArgs: unknown;\n  endpointName: string;\n};\nexport type InfiniteQueryThunkArg<D extends InfiniteQueryDefinition<any, any, any, any, any>> = QuerySubstateIdentifier & StartInfiniteQueryActionCreatorOptions<D> & {\n  type: `query`;\n  originalArgs: unknown;\n  endpointName: string;\n  param: unknown;\n  direction?: InfiniteQueryDirection;\n};\ntype MutationThunkArg = {\n  type: 'mutation';\n  originalArgs: unknown;\n  endpointName: string;\n  track?: boolean;\n  fixedCacheKey?: string;\n};\nexport type ThunkResult = unknown;\nexport type ThunkApiMetaConfig = {\n  pendingMeta: {\n    startedTimeStamp: number;\n    [SHOULD_AUTOBATCH]: true;\n  };\n  fulfilledMeta: {\n    fulfilledTimeStamp: number;\n    baseQueryMeta: unknown;\n    [SHOULD_AUTOBATCH]: true;\n  };\n  rejectedMeta: {\n    baseQueryMeta: unknown;\n    [SHOULD_AUTOBATCH]: true;\n  };\n};\nexport type QueryThunk = AsyncThunk<ThunkResult, QueryThunkArg, ThunkApiMetaConfig>;\nexport type InfiniteQueryThunk<D extends InfiniteQueryDefinition<any, any, any, any, any>> = AsyncThunk<ThunkResult, InfiniteQueryThunkArg<D>, ThunkApiMetaConfig>;\nexport type MutationThunk = AsyncThunk<ThunkResult, MutationThunkArg, ThunkApiMetaConfig>;\nfunction defaultTransformResponse(baseQueryReturnValue: unknown) {\n  return baseQueryReturnValue;\n}\nexport type MaybeDrafted<T> = T | Draft<T>;\nexport type Recipe<T> = (data: MaybeDrafted<T>) => void | MaybeDrafted<T>;\nexport type UpsertRecipe<T> = (data: MaybeDrafted<T> | undefined) => void | MaybeDrafted<T>;\nexport 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>;\nexport type AllQueryKeys<Definitions extends EndpointDefinitions> = QueryKeys<Definitions> | InfiniteQueryKeys<Definitions>;\nexport 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;\nexport 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;\nexport 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>;\nexport 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>;\nexport 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>;\n\n/**\n * An object returned from dispatching a `api.util.updateQueryData` call.\n */\nexport type PatchCollection = {\n  /**\n   * An `immer` Patch describing the cache update.\n   */\n  patches: Patch[];\n  /**\n   * An `immer` Patch to revert the cache update.\n   */\n  inversePatches: Patch[];\n  /**\n   * A function that will undo the cache update.\n   */\n  undo: () => void;\n};\ntype TransformCallback = (baseQueryReturnValue: unknown, meta: unknown, arg: unknown) => any;\nexport const addShouldAutoBatch = <T extends Record<string, any>,>(arg: T = {} as T): T & {\n  [SHOULD_AUTOBATCH]: true;\n} => {\n  return {\n    ...arg,\n    [SHOULD_AUTOBATCH]: true\n  };\n};\nexport function buildThunks<BaseQuery extends BaseQueryFn, ReducerPath extends string, Definitions extends EndpointDefinitions>({\n  reducerPath,\n  baseQuery,\n  context: {\n    endpointDefinitions\n  },\n  serializeQueryArgs,\n  api,\n  assertTagType,\n  selectors,\n  onSchemaFailure,\n  catchSchemaFailure: globalCatchSchemaFailure,\n  skipSchemaValidation: globalSkipSchemaValidation\n}: {\n  baseQuery: BaseQuery;\n  reducerPath: ReducerPath;\n  context: ApiContext<Definitions>;\n  serializeQueryArgs: InternalSerializeQueryArgs;\n  api: Api<BaseQuery, Definitions, ReducerPath, any>;\n  assertTagType: AssertTagTypes;\n  selectors: AllSelectors;\n  onSchemaFailure: SchemaFailureHandler | undefined;\n  catchSchemaFailure: SchemaFailureConverter<BaseQuery> | undefined;\n  skipSchemaValidation: boolean | undefined;\n}) {\n  type State = RootState<any, string, ReducerPath>;\n  const patchQueryData: PatchQueryDataThunk<EndpointDefinitions, State> = (endpointName, arg, patches, updateProvided) => (dispatch, getState) => {\n    const endpointDefinition = endpointDefinitions[endpointName];\n    const queryCacheKey = serializeQueryArgs({\n      queryArgs: arg,\n      endpointDefinition,\n      endpointName\n    });\n    dispatch(api.internalActions.queryResultPatched({\n      queryCacheKey,\n      patches\n    }));\n    if (!updateProvided) {\n      return;\n    }\n    const newValue = api.endpoints[endpointName].select(arg)(\n    // Work around TS 4.1 mismatch\n    getState() as RootState<any, any, any>);\n    const providedTags = calculateProvidedBy(endpointDefinition.providesTags, newValue.data, undefined, arg, {}, assertTagType);\n    dispatch(api.internalActions.updateProvidedBy([{\n      queryCacheKey,\n      providedTags\n    }]));\n  };\n  function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {\n    const newItems = [item, ...items];\n    return max && newItems.length > max ? newItems.slice(0, -1) : newItems;\n  }\n  function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {\n    const newItems = [...items, item];\n    return max && newItems.length > max ? newItems.slice(1) : newItems;\n  }\n  const updateQueryData: UpdateQueryDataThunk<EndpointDefinitions, State> = (endpointName, arg, updateRecipe, updateProvided = true) => (dispatch, getState) => {\n    const endpointDefinition = api.endpoints[endpointName];\n    const currentState = endpointDefinition.select(arg)(\n    // Work around TS 4.1 mismatch\n    getState() as RootState<any, any, any>);\n    const ret: PatchCollection = {\n      patches: [],\n      inversePatches: [],\n      undo: () => dispatch(api.util.patchQueryData(endpointName, arg, ret.inversePatches, updateProvided))\n    };\n    if (currentState.status === QueryStatus.uninitialized) {\n      return ret;\n    }\n    let newValue;\n    if ('data' in currentState) {\n      if (isDraftable(currentState.data)) {\n        const [value, patches, inversePatches] = produceWithPatches(currentState.data, updateRecipe);\n        ret.patches.push(...patches);\n        ret.inversePatches.push(...inversePatches);\n        newValue = value;\n      } else {\n        newValue = updateRecipe(currentState.data);\n        ret.patches.push({\n          op: 'replace',\n          path: [],\n          value: newValue\n        });\n        ret.inversePatches.push({\n          op: 'replace',\n          path: [],\n          value: currentState.data\n        });\n      }\n    }\n    if (ret.patches.length === 0) {\n      return ret;\n    }\n    dispatch(api.util.patchQueryData(endpointName, arg, ret.patches, updateProvided));\n    return ret;\n  };\n  const upsertQueryData: UpsertQueryDataThunk<Definitions, State> = (endpointName, arg, value) => dispatch => {\n    type EndpointName = typeof endpointName;\n    const res = dispatch((api.endpoints[endpointName] as ApiEndpointQuery<QueryDefinition<any, any, any, any, any>, Definitions>).initiate(arg, {\n      subscribe: false,\n      forceRefetch: true,\n      [forceQueryFnSymbol]: () => ({\n        data: value\n      })\n    })) as UpsertThunkResult<Definitions, EndpointName>;\n    return res;\n  };\n  const getTransformCallbackForEndpoint = (endpointDefinition: EndpointDefinition<any, any, any, any>, transformFieldName: 'transformResponse' | 'transformErrorResponse'): TransformCallback => {\n    return endpointDefinition.query && endpointDefinition[transformFieldName] ? endpointDefinition[transformFieldName]! as TransformCallback : defaultTransformResponse;\n  };\n\n  // The generic async payload function for all of our thunks\n  const executeEndpoint: AsyncThunkPayloadCreator<ThunkResult, QueryThunkArg | MutationThunkArg | InfiniteQueryThunkArg<any>, ThunkApiMetaConfig & {\n    state: RootState<any, string, ReducerPath>;\n  }> = async (arg, {\n    signal,\n    abort,\n    rejectWithValue,\n    fulfillWithValue,\n    dispatch,\n    getState,\n    extra\n  }) => {\n    const endpointDefinition = endpointDefinitions[arg.endpointName];\n    const {\n      metaSchema,\n      skipSchemaValidation = globalSkipSchemaValidation\n    } = endpointDefinition;\n    try {\n      let transformResponse = getTransformCallbackForEndpoint(endpointDefinition, 'transformResponse');\n      const baseQueryApi = {\n        signal,\n        abort,\n        dispatch,\n        getState,\n        extra,\n        endpoint: arg.endpointName,\n        type: arg.type,\n        forced: arg.type === 'query' ? isForcedQuery(arg, getState()) : undefined,\n        queryCacheKey: arg.type === 'query' ? arg.queryCacheKey : undefined\n      };\n      const forceQueryFn = arg.type === 'query' ? arg[forceQueryFnSymbol] : undefined;\n      let finalQueryReturnValue: QueryReturnValue;\n\n      // Infinite query wrapper, which executes the request and returns\n      // the InfiniteData `{pages, pageParams}` structure\n      const fetchPage = async (data: InfiniteData<unknown, unknown>, param: unknown, maxPages: number, previous?: boolean): Promise<QueryReturnValue> => {\n        // This should handle cases where there is no `getPrevPageParam`,\n        // or `getPPP` returned nullish\n        if (param == null && data.pages.length) {\n          return Promise.resolve({\n            data\n          });\n        }\n        const finalQueryArg: InfiniteQueryCombinedArg<any, any> = {\n          queryArg: arg.originalArgs,\n          pageParam: param\n        };\n        const pageResponse = await executeRequest(finalQueryArg);\n        const addTo = previous ? addToStart : addToEnd;\n        return {\n          data: {\n            pages: addTo(data.pages, pageResponse.data, maxPages),\n            pageParams: addTo(data.pageParams, param, maxPages)\n          },\n          meta: pageResponse.meta\n        };\n      };\n\n      // Wrapper for executing either `query` or `queryFn`,\n      // and handling any errors\n      async function executeRequest(finalQueryArg: unknown): Promise<QueryReturnValue> {\n        let result: QueryReturnValue;\n        const {\n          extraOptions,\n          argSchema,\n          rawResponseSchema,\n          responseSchema\n        } = endpointDefinition;\n        if (argSchema && !skipSchemaValidation) {\n          finalQueryArg = await parseWithSchema(argSchema, finalQueryArg, 'argSchema', {} // we don't have a meta yet, so we can't pass it\n          );\n        }\n        if (forceQueryFn) {\n          // upsertQueryData relies on this to pass in the user-provided value\n          result = forceQueryFn();\n        } else if (endpointDefinition.query) {\n          result = await baseQuery(endpointDefinition.query(finalQueryArg as any), baseQueryApi, extraOptions as any);\n        } else {\n          result = await endpointDefinition.queryFn(finalQueryArg as any, baseQueryApi, extraOptions as any, arg => baseQuery(arg, baseQueryApi, extraOptions as any));\n        }\n        if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n          const what = endpointDefinition.query ? '`baseQuery`' : '`queryFn`';\n          let err: undefined | string;\n          if (!result) {\n            err = `${what} did not return anything.`;\n          } else if (typeof result !== 'object') {\n            err = `${what} did not return an object.`;\n          } else if (result.error && result.data) {\n            err = `${what} returned an object containing both \\`error\\` and \\`result\\`.`;\n          } else if (result.error === undefined && result.data === undefined) {\n            err = `${what} returned an object containing neither a valid \\`error\\` and \\`result\\`. At least one of them should not be \\`undefined\\``;\n          } else {\n            for (const key of Object.keys(result)) {\n              if (key !== 'error' && key !== 'data' && key !== 'meta') {\n                err = `The object returned by ${what} has the unknown property ${key}.`;\n                break;\n              }\n            }\n          }\n          if (err) {\n            console.error(`Error encountered handling the endpoint ${arg.endpointName}.\n                  ${err}\n                  It needs to return an object with either the shape \\`{ data: <value> }\\` or \\`{ error: <value> }\\` that may contain an optional \\`meta\\` property.\n                  Object returned was:`, result);\n          }\n        }\n        if (result.error) throw new HandledError(result.error, result.meta);\n        let {\n          data\n        } = result;\n        if (rawResponseSchema && !skipSchemaValidation) {\n          data = await parseWithSchema(rawResponseSchema, result.data, 'rawResponseSchema', result.meta);\n        }\n        let transformedResponse = await transformResponse(data, result.meta, finalQueryArg);\n        if (responseSchema && !skipSchemaValidation) {\n          transformedResponse = await parseWithSchema(responseSchema, transformedResponse, 'responseSchema', result.meta);\n        }\n        return {\n          ...result,\n          data: transformedResponse\n        };\n      }\n      if (arg.type === 'query' && 'infiniteQueryOptions' in endpointDefinition) {\n        // This is an infinite query endpoint\n        const {\n          infiniteQueryOptions\n        } = endpointDefinition;\n\n        // Runtime checks should guarantee this is a positive number if provided\n        const {\n          maxPages = Infinity\n        } = infiniteQueryOptions;\n        let result: QueryReturnValue;\n\n        // Start by looking up the existing InfiniteData value from state,\n        // falling back to an empty value if it doesn't exist yet\n        const blankData = {\n          pages: [],\n          pageParams: []\n        };\n        const cachedData = selectors.selectQueryEntry(getState(), arg.queryCacheKey)?.data as InfiniteData<unknown, unknown> | undefined;\n\n        // When the arg changes or the user forces a refetch,\n        // we don't include the `direction` flag. This lets us distinguish\n        // between actually refetching with a forced query, vs just fetching\n        // the next page.\n        const isForcedQueryNeedingRefetch =\n        // arg.forceRefetch\n        isForcedQuery(arg, getState()) && !(arg as InfiniteQueryThunkArg<any>).direction;\n        const existingData = (isForcedQueryNeedingRefetch || !cachedData ? blankData : cachedData) as InfiniteData<unknown, unknown>;\n\n        // If the thunk specified a direction and we do have at least one page,\n        // fetch the next or previous page\n        if ('direction' in arg && arg.direction && existingData.pages.length) {\n          const previous = arg.direction === 'backward';\n          const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;\n          const param = pageParamFn(infiniteQueryOptions, existingData, arg.originalArgs);\n          result = await fetchPage(existingData, param, maxPages, previous);\n        } else {\n          // Otherwise, fetch the first page and then any remaining pages\n\n          const {\n            initialPageParam = infiniteQueryOptions.initialPageParam\n          } = arg as InfiniteQueryThunkArg<any>;\n\n          // If we're doing a refetch, we should start from\n          // the first page we have cached.\n          // Otherwise, we should start from the initialPageParam\n          const cachedPageParams = cachedData?.pageParams ?? [];\n          const firstPageParam = cachedPageParams[0] ?? initialPageParam;\n          const totalPages = cachedPageParams.length;\n\n          // Fetch first page\n          result = await fetchPage(existingData, firstPageParam, maxPages);\n          if (forceQueryFn) {\n            // HACK `upsertQueryData` expects the user to pass in the `{pages, pageParams}` structure,\n            // but `fetchPage` treats that as `pages[0]`. We have to manually un-nest it.\n            result = {\n              data: (result.data as InfiniteData<unknown, unknown>).pages[0]\n            } as QueryReturnValue;\n          }\n\n          // Fetch remaining pages\n          for (let i = 1; i < totalPages; i++) {\n            const param = getNextPageParam(infiniteQueryOptions, result.data as InfiniteData<unknown, unknown>, arg.originalArgs);\n            result = await fetchPage(result.data as InfiniteData<unknown, unknown>, param, maxPages);\n          }\n        }\n        finalQueryReturnValue = result;\n      } else {\n        // Non-infinite endpoint. Just run the one request.\n        finalQueryReturnValue = await executeRequest(arg.originalArgs);\n      }\n      if (metaSchema && !skipSchemaValidation && finalQueryReturnValue.meta) {\n        finalQueryReturnValue.meta = await parseWithSchema(metaSchema, finalQueryReturnValue.meta, 'metaSchema', finalQueryReturnValue.meta);\n      }\n\n      // console.log('Final result: ', transformedData)\n      return fulfillWithValue(finalQueryReturnValue.data, addShouldAutoBatch({\n        fulfilledTimeStamp: Date.now(),\n        baseQueryMeta: finalQueryReturnValue.meta\n      }));\n    } catch (error) {\n      let caughtError = error;\n      if (caughtError instanceof HandledError) {\n        let transformErrorResponse = getTransformCallbackForEndpoint(endpointDefinition, 'transformErrorResponse');\n        const {\n          rawErrorResponseSchema,\n          errorResponseSchema\n        } = endpointDefinition;\n        let {\n          value,\n          meta\n        } = caughtError;\n        try {\n          if (rawErrorResponseSchema && !skipSchemaValidation) {\n            value = await parseWithSchema(rawErrorResponseSchema, value, 'rawErrorResponseSchema', meta);\n          }\n          if (metaSchema && !skipSchemaValidation) {\n            meta = await parseWithSchema(metaSchema, meta, 'metaSchema', meta);\n          }\n          let transformedErrorResponse = await transformErrorResponse(value, meta, arg.originalArgs);\n          if (errorResponseSchema && !skipSchemaValidation) {\n            transformedErrorResponse = await parseWithSchema(errorResponseSchema, transformedErrorResponse, 'errorResponseSchema', meta);\n          }\n          return rejectWithValue(transformedErrorResponse, addShouldAutoBatch({\n            baseQueryMeta: meta\n          }));\n        } catch (e) {\n          caughtError = e;\n        }\n      }\n      try {\n        if (caughtError instanceof NamedSchemaError) {\n          const info: SchemaFailureInfo = {\n            endpoint: arg.endpointName,\n            arg: arg.originalArgs,\n            type: arg.type,\n            queryCacheKey: arg.type === 'query' ? arg.queryCacheKey : undefined\n          };\n          endpointDefinition.onSchemaFailure?.(caughtError, info);\n          onSchemaFailure?.(caughtError, info);\n          const {\n            catchSchemaFailure = globalCatchSchemaFailure\n          } = endpointDefinition;\n          if (catchSchemaFailure) {\n            return rejectWithValue(catchSchemaFailure(caughtError, info), addShouldAutoBatch({\n              baseQueryMeta: caughtError._bqMeta\n            }));\n          }\n        }\n      } catch (e) {\n        caughtError = e;\n      }\n      if (typeof process !== 'undefined' && process.env.NODE_ENV !== 'production') {\n        console.error(`An unhandled error occurred processing a request for the endpoint \"${arg.endpointName}\".\nIn the case of an unhandled error, no tags will be \"provided\" or \"invalidated\".`, caughtError);\n      } else {\n        console.error(caughtError);\n      }\n      throw caughtError;\n    }\n  };\n  function isForcedQuery(arg: QueryThunkArg, state: RootState<any, string, ReducerPath>) {\n    const requestState = selectors.selectQueryEntry(state, arg.queryCacheKey);\n    const baseFetchOnMountOrArgChange = selectors.selectConfig(state).refetchOnMountOrArgChange;\n    const fulfilledVal = requestState?.fulfilledTimeStamp;\n    const refetchVal = arg.forceRefetch ?? (arg.subscribe && baseFetchOnMountOrArgChange);\n    if (refetchVal) {\n      // Return if it's true or compare the dates because it must be a number\n      return refetchVal === true || (Number(new Date()) - Number(fulfilledVal)) / 1000 >= refetchVal;\n    }\n    return false;\n  }\n  const createQueryThunk = <ThunkArgType extends QueryThunkArg | InfiniteQueryThunkArg<any>,>() => {\n    const generatedQueryThunk = createAsyncThunk<ThunkResult, ThunkArgType, ThunkApiMetaConfig & {\n      state: RootState<any, string, ReducerPath>;\n    }>(`${reducerPath}/executeQuery`, executeEndpoint, {\n      getPendingMeta({\n        arg\n      }) {\n        const endpointDefinition = endpointDefinitions[arg.endpointName];\n        return addShouldAutoBatch({\n          startedTimeStamp: Date.now(),\n          ...(isInfiniteQueryDefinition(endpointDefinition) ? {\n            direction: (arg as InfiniteQueryThunkArg<any>).direction\n          } : {})\n        });\n      },\n      condition(queryThunkArg, {\n        getState\n      }) {\n        const state = getState();\n        const requestState = selectors.selectQueryEntry(state, queryThunkArg.queryCacheKey);\n        const fulfilledVal = requestState?.fulfilledTimeStamp;\n        const currentArg = queryThunkArg.originalArgs;\n        const previousArg = requestState?.originalArgs;\n        const endpointDefinition = endpointDefinitions[queryThunkArg.endpointName];\n        const direction = (queryThunkArg as InfiniteQueryThunkArg<any>).direction;\n\n        // Order of these checks matters.\n        // In order for `upsertQueryData` to successfully run while an existing request is in flight,\n        /// we have to check for that first, otherwise `queryThunk` will bail out and not run at all.\n        if (isUpsertQuery(queryThunkArg)) {\n          return true;\n        }\n\n        // Don't retry a request that's currently in-flight\n        if (requestState?.status === 'pending') {\n          return false;\n        }\n\n        // if this is forced, continue\n        if (isForcedQuery(queryThunkArg, state)) {\n          return true;\n        }\n        if (isQueryDefinition(endpointDefinition) && endpointDefinition?.forceRefetch?.({\n          currentArg,\n          previousArg,\n          endpointState: requestState,\n          state\n        })) {\n          return true;\n        }\n\n        // Pull from the cache unless we explicitly force refetch or qualify based on time\n        if (fulfilledVal && !direction) {\n          // Value is cached and we didn't specify to refresh, skip it.\n          return false;\n        }\n        return true;\n      },\n      dispatchConditionRejection: true\n    });\n    return generatedQueryThunk;\n  };\n  const queryThunk = createQueryThunk<QueryThunkArg>();\n  const infiniteQueryThunk = createQueryThunk<InfiniteQueryThunkArg<any>>();\n  const mutationThunk = createAsyncThunk<ThunkResult, MutationThunkArg, ThunkApiMetaConfig & {\n    state: RootState<any, string, ReducerPath>;\n  }>(`${reducerPath}/executeMutation`, executeEndpoint, {\n    getPendingMeta() {\n      return addShouldAutoBatch({\n        startedTimeStamp: Date.now()\n      });\n    }\n  });\n  const hasTheForce = (options: any): options is {\n    force: boolean;\n  } => 'force' in options;\n  const hasMaxAge = (options: any): options is {\n    ifOlderThan: false | number;\n  } => 'ifOlderThan' in options;\n  const prefetch = <EndpointName extends QueryKeys<Definitions>,>(endpointName: EndpointName, arg: any, options: PrefetchOptions): ThunkAction<void, any, any, UnknownAction> => (dispatch: ThunkDispatch<any, any, any>, getState: () => any) => {\n    const force = hasTheForce(options) && options.force;\n    const maxAge = hasMaxAge(options) && options.ifOlderThan;\n    const queryAction = (force: boolean = true) => {\n      const options = {\n        forceRefetch: force,\n        isPrefetch: true\n      };\n      return (api.endpoints[endpointName] as ApiEndpointQuery<any, any>).initiate(arg, options);\n    };\n    const latestStateValue = (api.endpoints[endpointName] as ApiEndpointQuery<any, any>).select(arg)(getState());\n    if (force) {\n      dispatch(queryAction());\n    } else if (maxAge) {\n      const lastFulfilledTs = latestStateValue?.fulfilledTimeStamp;\n      if (!lastFulfilledTs) {\n        dispatch(queryAction());\n        return;\n      }\n      const shouldRetrigger = (Number(new Date()) - Number(new Date(lastFulfilledTs))) / 1000 >= maxAge;\n      if (shouldRetrigger) {\n        dispatch(queryAction());\n      }\n    } else {\n      // If prefetching with no options, just let it try\n      dispatch(queryAction(false));\n    }\n  };\n  function matchesEndpoint(endpointName: string) {\n    return (action: any): action is UnknownAction => action?.meta?.arg?.endpointName === endpointName;\n  }\n  function buildMatchThunkActions<Thunk extends AsyncThunk<any, QueryThunkArg, ThunkApiMetaConfig> | AsyncThunk<any, MutationThunkArg, ThunkApiMetaConfig>>(thunk: Thunk, endpointName: string) {\n    return {\n      matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)),\n      matchFulfilled: isAllOf(isFulfilled(thunk), matchesEndpoint(endpointName)),\n      matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpointName))\n    } as Matchers<Thunk, any>;\n  }\n  return {\n    queryThunk,\n    mutationThunk,\n    infiniteQueryThunk,\n    prefetch,\n    updateQueryData,\n    upsertQueryData,\n    patchQueryData,\n    buildMatchThunkActions\n  };\n}\nexport function getNextPageParam(options: InfiniteQueryConfigOptions<unknown, unknown, unknown>, {\n  pages,\n  pageParams\n}: InfiniteData<unknown, unknown>, queryArg: unknown): unknown | undefined {\n  const lastIndex = pages.length - 1;\n  return options.getNextPageParam(pages[lastIndex], pages, pageParams[lastIndex], pageParams, queryArg);\n}\nexport function getPreviousPageParam(options: InfiniteQueryConfigOptions<unknown, unknown, unknown>, {\n  pages,\n  pageParams\n}: InfiniteData<unknown, unknown>, queryArg: unknown): unknown | undefined {\n  return options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams, queryArg);\n}\nexport function calculateProvidedByThunk(action: UnwrapPromise<ReturnType<ReturnType<QueryThunk>> | ReturnType<ReturnType<MutationThunk>> | ReturnType<ReturnType<InfiniteQueryThunk<any>>>>, type: 'providesTags' | 'invalidatesTags', endpointDefinitions: EndpointDefinitions, assertTagType: AssertTagTypes) {\n  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);\n}","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { AsyncThunkAction, SafePromise, SerializedError, ThunkAction, UnknownAction } from '@reduxjs/toolkit';\nimport type { Dispatch } from 'redux';\nimport { asSafePromise } from '../../tsHelpers';\nimport type { Api, ApiContext } from '../apiTypes';\nimport type { BaseQueryError, QueryReturnValue } from '../baseQueryTypes';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport { isQueryDefinition, type EndpointDefinition, type EndpointDefinitions, type InfiniteQueryArgFrom, type InfiniteQueryDefinition, type MutationDefinition, type PageParamFrom, type QueryArgFrom, type QueryDefinition, type ResultTypeFrom } from '../endpointDefinitions';\nimport { countObjectKeys, getOrInsert, isNotNullish } from '../utils';\nimport type { InfiniteData, InfiniteQueryConfigOptions, InfiniteQueryDirection, SubscriptionOptions } from './apiState';\nimport type { InfiniteQueryResultSelectorResult, QueryResultSelectorResult } from './buildSelectors';\nimport type { InfiniteQueryThunk, InfiniteQueryThunkArg, MutationThunk, QueryThunk, QueryThunkArg, ThunkApiMetaConfig } from './buildThunks';\nimport type { ApiEndpointQuery } from './module';\nexport type BuildInitiateApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>> = {\n  initiate: StartQueryActionCreator<Definition>;\n};\nexport type BuildInitiateApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = {\n  initiate: StartInfiniteQueryActionCreator<Definition>;\n};\nexport type BuildInitiateApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>> = {\n  initiate: StartMutationActionCreator<Definition>;\n};\nexport const forceQueryFnSymbol = Symbol('forceQueryFn');\nexport const isUpsertQuery = (arg: QueryThunkArg) => typeof arg[forceQueryFnSymbol] === 'function';\nexport type StartQueryActionCreatorOptions = {\n  subscribe?: boolean;\n  forceRefetch?: boolean | number;\n  subscriptionOptions?: SubscriptionOptions;\n  [forceQueryFnSymbol]?: () => QueryReturnValue;\n};\nexport type StartInfiniteQueryActionCreatorOptions<D extends InfiniteQueryDefinition<any, any, any, any, any>> = StartQueryActionCreatorOptions & {\n  direction?: InfiniteQueryDirection;\n  param?: unknown;\n} & Partial<Pick<Partial<InfiniteQueryConfigOptions<ResultTypeFrom<D>, PageParamFrom<D>, InfiniteQueryArgFrom<D>>>, 'initialPageParam'>>;\ntype AnyQueryActionCreator<D extends EndpointDefinition<any, any, any, any>> = (arg: any, options?: StartQueryActionCreatorOptions) => ThunkAction<AnyActionCreatorResult, any, any, UnknownAction>;\ntype StartQueryActionCreator<D extends QueryDefinition<any, any, any, any, any>> = (arg: QueryArgFrom<D>, options?: StartQueryActionCreatorOptions) => ThunkAction<QueryActionCreatorResult<D>, any, any, UnknownAction>;\nexport type StartInfiniteQueryActionCreator<D extends InfiniteQueryDefinition<any, any, any, any, any>> = (arg: InfiniteQueryArgFrom<D>, options?: StartInfiniteQueryActionCreatorOptions<D>) => ThunkAction<InfiniteQueryActionCreatorResult<D>, any, any, UnknownAction>;\ntype QueryActionCreatorFields = {\n  requestId: string;\n  subscriptionOptions: SubscriptionOptions | undefined;\n  abort(): void;\n  unsubscribe(): void;\n  updateSubscriptionOptions(options: SubscriptionOptions): void;\n  queryCacheKey: string;\n};\ntype AnyActionCreatorResult = SafePromise<any> & QueryActionCreatorFields & {\n  arg: any;\n  unwrap(): Promise<any>;\n  refetch(): AnyActionCreatorResult;\n};\nexport type QueryActionCreatorResult<D extends QueryDefinition<any, any, any, any>> = SafePromise<QueryResultSelectorResult<D>> & QueryActionCreatorFields & {\n  arg: QueryArgFrom<D>;\n  unwrap(): Promise<ResultTypeFrom<D>>;\n  refetch(): QueryActionCreatorResult<D>;\n};\nexport type InfiniteQueryActionCreatorResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = SafePromise<InfiniteQueryResultSelectorResult<D>> & QueryActionCreatorFields & {\n  arg: InfiniteQueryArgFrom<D>;\n  unwrap(): Promise<InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>>;\n  refetch(): InfiniteQueryActionCreatorResult<D>;\n};\ntype StartMutationActionCreator<D extends MutationDefinition<any, any, any, any>> = (arg: QueryArgFrom<D>, options?: {\n  /**\n   * If this mutation should be tracked in the store.\n   * If you just want to manually trigger this mutation using `dispatch` and don't care about the\n   * result, state & potential errors being held in store, you can set this to false.\n   * (defaults to `true`)\n   */\n  track?: boolean;\n  fixedCacheKey?: string;\n}) => ThunkAction<MutationActionCreatorResult<D>, any, any, UnknownAction>;\nexport type MutationActionCreatorResult<D extends MutationDefinition<any, any, any, any>> = SafePromise<{\n  data: ResultTypeFrom<D>;\n  error?: undefined;\n} | {\n  data?: undefined;\n  error: Exclude<BaseQueryError<D extends MutationDefinition<any, infer BaseQuery, any, any> ? BaseQuery : never>, undefined> | SerializedError;\n}> & {\n  /** @internal */\n  arg: {\n    /**\n     * The name of the given endpoint for the mutation\n     */\n    endpointName: string;\n    /**\n     * The original arguments supplied to the mutation call\n     */\n    originalArgs: QueryArgFrom<D>;\n    /**\n     * Whether the mutation is being tracked in the store.\n     */\n    track?: boolean;\n    fixedCacheKey?: string;\n  };\n  /**\n   * A unique string generated for the request sequence\n   */\n  requestId: string;\n\n  /**\n   * A method to cancel the mutation promise. Note that this is not intended to prevent the mutation\n   * that was fired off from reaching the server, but only to assist in handling the response.\n   *\n   * Calling `abort()` prior to the promise resolving will force it to reach the error state with\n   * the serialized error:\n   * `{ name: 'AbortError', message: 'Aborted' }`\n   *\n   * @example\n   * ```ts\n   * const [updateUser] = useUpdateUserMutation();\n   *\n   * useEffect(() => {\n   *   const promise = updateUser(id);\n   *   promise\n   *     .unwrap()\n   *     .catch((err) => {\n   *       if (err.name === 'AbortError') return;\n   *       // else handle the unexpected error\n   *     })\n   *\n   *   return () => {\n   *     promise.abort();\n   *   }\n   * }, [id, updateUser])\n   * ```\n   */\n  abort(): void;\n  /**\n   * Unwraps a mutation call to provide the raw response/error.\n   *\n   * @remarks\n   * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap\"\n   * addPost({ id: 1, name: 'Example' })\n   *   .unwrap()\n   *   .then((payload) => console.log('fulfilled', payload))\n   *   .catch((error) => console.error('rejected', error));\n   * ```\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap with async await\"\n   * try {\n   *   const payload = await addPost({ id: 1, name: 'Example' }).unwrap();\n   *   console.log('fulfilled', payload)\n   * } catch (error) {\n   *   console.error('rejected', error);\n   * }\n   * ```\n   */\n  unwrap(): Promise<ResultTypeFrom<D>>;\n  /**\n   * A method to manually unsubscribe from the mutation call, meaning it will be removed from cache after the usual caching grace period.\n   The value returned by the hook will reset to `isUninitialized` afterwards.\n   */\n  reset(): void;\n};\nexport function buildInitiate({\n  serializeQueryArgs,\n  queryThunk,\n  infiniteQueryThunk,\n  mutationThunk,\n  api,\n  context\n}: {\n  serializeQueryArgs: InternalSerializeQueryArgs;\n  queryThunk: QueryThunk;\n  infiniteQueryThunk: InfiniteQueryThunk<any>;\n  mutationThunk: MutationThunk;\n  api: Api<any, EndpointDefinitions, any, any>;\n  context: ApiContext<EndpointDefinitions>;\n}) {\n  const runningQueries: Map<Dispatch, Record<string, QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any> | undefined>> = new Map();\n  const runningMutations: Map<Dispatch, Record<string, MutationActionCreatorResult<any> | undefined>> = new Map();\n  const {\n    unsubscribeQueryResult,\n    removeMutationResult,\n    updateSubscriptionOptions\n  } = api.internalActions;\n  return {\n    buildInitiateQuery,\n    buildInitiateInfiniteQuery,\n    buildInitiateMutation,\n    getRunningQueryThunk,\n    getRunningMutationThunk,\n    getRunningQueriesThunk,\n    getRunningMutationsThunk\n  };\n  function getRunningQueryThunk(endpointName: string, queryArgs: any) {\n    return (dispatch: Dispatch) => {\n      const endpointDefinition = context.endpointDefinitions[endpointName];\n      const queryCacheKey = serializeQueryArgs({\n        queryArgs,\n        endpointDefinition,\n        endpointName\n      });\n      return runningQueries.get(dispatch)?.[queryCacheKey] as QueryActionCreatorResult<never> | InfiniteQueryActionCreatorResult<never> | undefined;\n    };\n  }\n  function getRunningMutationThunk(\n  /**\n   * this is only here to allow TS to infer the result type by input value\n   * we could use it to validate the result, but it's probably not necessary\n   */\n  _endpointName: string, fixedCacheKeyOrRequestId: string) {\n    return (dispatch: Dispatch) => {\n      return runningMutations.get(dispatch)?.[fixedCacheKeyOrRequestId] as MutationActionCreatorResult<never> | undefined;\n    };\n  }\n  function getRunningQueriesThunk() {\n    return (dispatch: Dispatch) => Object.values(runningQueries.get(dispatch) || {}).filter(isNotNullish);\n  }\n  function getRunningMutationsThunk() {\n    return (dispatch: Dispatch) => Object.values(runningMutations.get(dispatch) || {}).filter(isNotNullish);\n  }\n  function middlewareWarning(dispatch: Dispatch) {\n    if (process.env.NODE_ENV !== 'production') {\n      if ((middlewareWarning as any).triggered) return;\n      const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());\n      (middlewareWarning as any).triggered = true;\n\n      // The RTKQ middleware should return the internal state object,\n      // but it should _not_ be the action object.\n      if (typeof returnedValue !== 'object' || typeof returnedValue?.type === 'string') {\n        // Otherwise, must not have been added\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(34) : `Warning: Middleware for RTK-Query API at reducerPath \"${api.reducerPath}\" has not been added to the store.\nYou must add the middleware for RTK-Query to function correctly!`);\n      }\n    }\n  }\n  function buildInitiateAnyQuery<T extends 'query' | 'infiniteQuery'>(endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any> | InfiniteQueryDefinition<any, any, any, any, any>) {\n    const queryAction: AnyQueryActionCreator<any> = (arg, {\n      subscribe = true,\n      forceRefetch,\n      subscriptionOptions,\n      [forceQueryFnSymbol]: forceQueryFn,\n      ...rest\n    } = {}) => (dispatch, getState) => {\n      const queryCacheKey = serializeQueryArgs({\n        queryArgs: arg,\n        endpointDefinition,\n        endpointName\n      });\n      let thunk: AsyncThunkAction<unknown, QueryThunkArg, ThunkApiMetaConfig>;\n      const commonThunkArgs = {\n        ...rest,\n        type: 'query' as const,\n        subscribe,\n        forceRefetch: forceRefetch,\n        subscriptionOptions,\n        endpointName,\n        originalArgs: arg,\n        queryCacheKey,\n        [forceQueryFnSymbol]: forceQueryFn\n      };\n      if (isQueryDefinition(endpointDefinition)) {\n        thunk = queryThunk(commonThunkArgs);\n      } else {\n        const {\n          direction,\n          initialPageParam\n        } = rest as Pick<InfiniteQueryThunkArg<any>, 'direction' | 'initialPageParam'>;\n        thunk = infiniteQueryThunk({\n          ...(commonThunkArgs as InfiniteQueryThunkArg<any>),\n          // Supply these even if undefined. This helps with a field existence\n          // check over in `buildSlice.ts`\n          direction,\n          initialPageParam\n        });\n      }\n      const selector = (api.endpoints[endpointName] as ApiEndpointQuery<any, any>).select(arg);\n      const thunkResult = dispatch(thunk);\n      const stateAfter = selector(getState());\n      middlewareWarning(dispatch);\n      const {\n        requestId,\n        abort\n      } = thunkResult;\n      const skippedSynchronously = stateAfter.requestId !== requestId;\n      const runningQuery = runningQueries.get(dispatch)?.[queryCacheKey];\n      const selectFromState = () => selector(getState());\n      const statePromise: AnyActionCreatorResult = Object.assign((forceQueryFn ?\n      // a query has been forced (upsertQueryData)\n      // -> we want to resolve it once data has been written with the data that will be written\n      thunkResult.then(selectFromState) : skippedSynchronously && !runningQuery ?\n      // a query has been skipped due to a condition and we do not have any currently running query\n      // -> we want to resolve it immediately with the current data\n      Promise.resolve(stateAfter) :\n      // query just started or one is already in flight\n      // -> wait for the running query, then resolve with data from after that\n      Promise.all([runningQuery, thunkResult]).then(selectFromState)) as SafePromise<any>, {\n        arg,\n        requestId,\n        subscriptionOptions,\n        queryCacheKey,\n        abort,\n        async unwrap() {\n          const result = await statePromise;\n          if (result.isError) {\n            throw result.error;\n          }\n          return result.data;\n        },\n        refetch: () => dispatch(queryAction(arg, {\n          subscribe: false,\n          forceRefetch: true\n        })),\n        unsubscribe() {\n          if (subscribe) dispatch(unsubscribeQueryResult({\n            queryCacheKey,\n            requestId\n          }));\n        },\n        updateSubscriptionOptions(options: SubscriptionOptions) {\n          statePromise.subscriptionOptions = options;\n          dispatch(updateSubscriptionOptions({\n            endpointName,\n            requestId,\n            queryCacheKey,\n            options\n          }));\n        }\n      });\n      if (!runningQuery && !skippedSynchronously && !forceQueryFn) {\n        const running = getOrInsert(runningQueries, dispatch, {});\n        running[queryCacheKey] = statePromise;\n        statePromise.then(() => {\n          delete running[queryCacheKey];\n          if (!countObjectKeys(running)) {\n            runningQueries.delete(dispatch);\n          }\n        });\n      }\n      return statePromise;\n    };\n    return queryAction;\n  }\n  function buildInitiateQuery(endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any>) {\n    const queryAction: StartQueryActionCreator<any> = buildInitiateAnyQuery(endpointName, endpointDefinition);\n    return queryAction;\n  }\n  function buildInitiateInfiniteQuery(endpointName: string, endpointDefinition: InfiniteQueryDefinition<any, any, any, any, any>) {\n    const infiniteQueryAction: StartInfiniteQueryActionCreator<any> = buildInitiateAnyQuery(endpointName, endpointDefinition);\n    return infiniteQueryAction;\n  }\n  function buildInitiateMutation(endpointName: string): StartMutationActionCreator<any> {\n    return (arg, {\n      track = true,\n      fixedCacheKey\n    } = {}) => (dispatch, getState) => {\n      const thunk = mutationThunk({\n        type: 'mutation',\n        endpointName,\n        originalArgs: arg,\n        track,\n        fixedCacheKey\n      });\n      const thunkResult = dispatch(thunk);\n      middlewareWarning(dispatch);\n      const {\n        requestId,\n        abort,\n        unwrap\n      } = thunkResult;\n      const returnValuePromise = asSafePromise(thunkResult.unwrap().then(data => ({\n        data\n      })), error => ({\n        error\n      }));\n      const reset = () => {\n        dispatch(removeMutationResult({\n          requestId,\n          fixedCacheKey\n        }));\n      };\n      const ret = Object.assign(returnValuePromise, {\n        arg: thunkResult.arg,\n        requestId,\n        abort,\n        unwrap,\n        reset\n      });\n      const running = runningMutations.get(dispatch) || {};\n      runningMutations.set(dispatch, running);\n      running[requestId] = ret;\n      ret.then(() => {\n        delete running[requestId];\n        if (!countObjectKeys(running)) {\n          runningMutations.delete(dispatch);\n        }\n      });\n      if (fixedCacheKey) {\n        running[fixedCacheKey] = ret;\n        ret.then(() => {\n          if (running[fixedCacheKey] === ret) {\n            delete running[fixedCacheKey];\n            if (!countObjectKeys(running)) {\n              runningMutations.delete(dispatch);\n            }\n          }\n        });\n      }\n      return ret;\n    };\n  }\n}","import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { SchemaError } from '@standard-schema/utils';\nexport class NamedSchemaError extends SchemaError {\n  constructor(issues: readonly StandardSchemaV1.Issue[], public readonly value: any, public readonly schemaName: string, public readonly _bqMeta: any) {\n    super(issues);\n  }\n}\nexport async function parseWithSchema<Schema extends StandardSchemaV1>(schema: Schema, data: unknown, schemaName: string, bqMeta: any): Promise<StandardSchemaV1.InferOutput<Schema>> {\n  const result = await schema['~standard'].validate(data);\n  if (result.issues) {\n    throw new NamedSchemaError(result.issues, data, schemaName, bqMeta);\n  }\n  return result.value;\n}","import type { PayloadAction } from '@reduxjs/toolkit';\nimport { combineReducers, createAction, createSlice, isAnyOf, isFulfilled, isRejectedWithValue, createNextState, prepareAutoBatched, SHOULD_AUTOBATCH, nanoid } from './rtkImports';\nimport type { QuerySubstateIdentifier, QuerySubState, MutationSubstateIdentifier, MutationSubState, MutationState, QueryState, InvalidationState, Subscribers, QueryCacheKey, SubscriptionState, ConfigState, InfiniteQuerySubState, InfiniteQueryDirection } from './apiState';\nimport { QueryStatus } from './apiState';\nimport type { AllQueryKeys, QueryArgFromAnyQueryDefinition, DataFromAnyQueryDefinition, InfiniteQueryThunk, MutationThunk, QueryThunk, QueryThunkArg } from './buildThunks';\nimport { calculateProvidedByThunk } from './buildThunks';\nimport { isInfiniteQueryDefinition, type AssertTagTypes, type EndpointDefinitions, type FullTagDescription, type QueryDefinition } from '../endpointDefinitions';\nimport type { Patch } from 'immer';\nimport { isDraft } from 'immer';\nimport { applyPatches, original } from 'immer';\nimport { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners';\nimport { isDocumentVisible, isOnline, copyWithStructuralSharing } from '../utils';\nimport type { ApiContext } from '../apiTypes';\nimport { isUpsertQuery } from './buildInitiate';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { UnwrapPromise } from '../tsHelpers';\n\n/**\n * A typesafe single entry to be upserted into the cache\n */\nexport type NormalizedQueryUpsertEntry<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = {\n  endpointName: EndpointName;\n  arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>;\n  value: DataFromAnyQueryDefinition<Definitions, EndpointName>;\n};\n\n/**\n * The internal version that is not typesafe since we can't carry the generics through `createSlice`\n */\ntype NormalizedQueryUpsertEntryPayload = {\n  endpointName: string;\n  arg: unknown;\n  value: unknown;\n};\nexport type ProcessedQueryUpsertEntry = {\n  queryDescription: QueryThunkArg;\n  value: unknown;\n};\n\n/**\n * A typesafe representation of a util action creator that accepts cache entry descriptions to upsert\n */\nexport type UpsertEntries<Definitions extends EndpointDefinitions> = (<EndpointNames extends Array<AllQueryKeys<Definitions>>>(entries: [...{ [I in keyof EndpointNames]: NormalizedQueryUpsertEntry<Definitions, EndpointNames[I]> }]) => PayloadAction<NormalizedQueryUpsertEntryPayload[]>) & {\n  match: (action: unknown) => action is PayloadAction<NormalizedQueryUpsertEntryPayload[]>;\n};\nfunction updateQuerySubstateIfExists(state: QueryState<any>, queryCacheKey: QueryCacheKey, update: (substate: QuerySubState<any> | InfiniteQuerySubState<any>) => void) {\n  const substate = state[queryCacheKey];\n  if (substate) {\n    update(substate);\n  }\n}\nexport function getMutationCacheKey(id: MutationSubstateIdentifier | {\n  requestId: string;\n  arg: {\n    fixedCacheKey?: string | undefined;\n  };\n}): string;\nexport function getMutationCacheKey(id: {\n  fixedCacheKey?: string;\n  requestId?: string;\n}): string | undefined;\nexport function getMutationCacheKey(id: {\n  fixedCacheKey?: string;\n  requestId?: string;\n} | MutationSubstateIdentifier | {\n  requestId: string;\n  arg: {\n    fixedCacheKey?: string | undefined;\n  };\n}): string | undefined {\n  return ('arg' in id ? id.arg.fixedCacheKey : id.fixedCacheKey) ?? id.requestId;\n}\nfunction updateMutationSubstateIfExists(state: MutationState<any>, id: MutationSubstateIdentifier | {\n  requestId: string;\n  arg: {\n    fixedCacheKey?: string | undefined;\n  };\n}, update: (substate: MutationSubState<any>) => void) {\n  const substate = state[getMutationCacheKey(id)];\n  if (substate) {\n    update(substate);\n  }\n}\nconst initialState = {} as any;\nexport function buildSlice({\n  reducerPath,\n  queryThunk,\n  mutationThunk,\n  serializeQueryArgs,\n  context: {\n    endpointDefinitions: definitions,\n    apiUid,\n    extractRehydrationInfo,\n    hasRehydrationInfo\n  },\n  assertTagType,\n  config\n}: {\n  reducerPath: string;\n  queryThunk: QueryThunk;\n  infiniteQueryThunk: InfiniteQueryThunk<any>;\n  mutationThunk: MutationThunk;\n  serializeQueryArgs: InternalSerializeQueryArgs;\n  context: ApiContext<EndpointDefinitions>;\n  assertTagType: AssertTagTypes;\n  config: Omit<ConfigState<string>, 'online' | 'focused' | 'middlewareRegistered'>;\n}) {\n  const resetApiState = createAction(`${reducerPath}/resetApiState`);\n  function writePendingCacheEntry(draft: QueryState<any>, arg: QueryThunkArg, upserting: boolean, meta: {\n    arg: QueryThunkArg;\n    requestId: string;\n    // requestStatus: 'pending'\n  } & {\n    startedTimeStamp: number;\n  }) {\n    draft[arg.queryCacheKey] ??= {\n      status: QueryStatus.uninitialized,\n      endpointName: arg.endpointName\n    };\n    updateQuerySubstateIfExists(draft, arg.queryCacheKey, substate => {\n      substate.status = QueryStatus.pending;\n      substate.requestId = upserting && substate.requestId ?\n      // for `upsertQuery` **updates**, keep the current `requestId`\n      substate.requestId :\n      // for normal queries or `upsertQuery` **inserts** always update the `requestId`\n      meta.requestId;\n      if (arg.originalArgs !== undefined) {\n        substate.originalArgs = arg.originalArgs;\n      }\n      substate.startedTimeStamp = meta.startedTimeStamp;\n      const endpointDefinition = definitions[meta.arg.endpointName];\n      if (isInfiniteQueryDefinition(endpointDefinition) && 'direction' in arg) {\n        ;\n        (substate as InfiniteQuerySubState<any>).direction = arg.direction as InfiniteQueryDirection;\n      }\n    });\n  }\n  function writeFulfilledCacheEntry(draft: QueryState<any>, meta: {\n    arg: QueryThunkArg;\n    requestId: string;\n  } & {\n    fulfilledTimeStamp: number;\n    baseQueryMeta: unknown;\n  }, payload: unknown, upserting: boolean) {\n    updateQuerySubstateIfExists(draft, meta.arg.queryCacheKey, substate => {\n      if (substate.requestId !== meta.requestId && !upserting) return;\n      const {\n        merge\n      } = definitions[meta.arg.endpointName] as QueryDefinition<any, any, any, any>;\n      substate.status = QueryStatus.fulfilled;\n      if (merge) {\n        if (substate.data !== undefined) {\n          const {\n            fulfilledTimeStamp,\n            arg,\n            baseQueryMeta,\n            requestId\n          } = meta;\n          // There's existing cache data. Let the user merge it in themselves.\n          // We're already inside an Immer-powered reducer, and the user could just mutate `substate.data`\n          // themselves inside of `merge()`. But, they might also want to return a new value.\n          // Try to let Immer figure that part out, save the result, and assign it to `substate.data`.\n          let newData = createNextState(substate.data, draftSubstateData => {\n            // As usual with Immer, you can mutate _or_ return inside here, but not both\n            return merge(draftSubstateData, payload, {\n              arg: arg.originalArgs,\n              baseQueryMeta,\n              fulfilledTimeStamp,\n              requestId\n            });\n          });\n          substate.data = newData;\n        } else {\n          // Presumably a fresh request. Just cache the response data.\n          substate.data = payload;\n        }\n      } else {\n        // Assign or safely update the cache data.\n        substate.data = definitions[meta.arg.endpointName].structuralSharing ?? true ? copyWithStructuralSharing(isDraft(substate.data) ? original(substate.data) : substate.data, payload) : payload;\n      }\n      delete substate.error;\n      substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;\n    });\n  }\n  const querySlice = createSlice({\n    name: `${reducerPath}/queries`,\n    initialState: initialState as QueryState<any>,\n    reducers: {\n      removeQueryResult: {\n        reducer(draft, {\n          payload: {\n            queryCacheKey\n          }\n        }: PayloadAction<QuerySubstateIdentifier>) {\n          delete draft[queryCacheKey];\n        },\n        prepare: prepareAutoBatched<QuerySubstateIdentifier>()\n      },\n      cacheEntriesUpserted: {\n        reducer(draft, action: PayloadAction<ProcessedQueryUpsertEntry[], string, {\n          RTK_autoBatch: boolean;\n          requestId: string;\n          timestamp: number;\n        }>) {\n          for (const entry of action.payload) {\n            const {\n              queryDescription: arg,\n              value\n            } = entry;\n            writePendingCacheEntry(draft, arg, true, {\n              arg,\n              requestId: action.meta.requestId,\n              startedTimeStamp: action.meta.timestamp\n            });\n            writeFulfilledCacheEntry(draft, {\n              arg,\n              requestId: action.meta.requestId,\n              fulfilledTimeStamp: action.meta.timestamp,\n              baseQueryMeta: {}\n            }, value,\n            // We know we're upserting here\n            true);\n          }\n        },\n        prepare: (payload: NormalizedQueryUpsertEntryPayload[]) => {\n          const queryDescriptions: ProcessedQueryUpsertEntry[] = payload.map(entry => {\n            const {\n              endpointName,\n              arg,\n              value\n            } = entry;\n            const endpointDefinition = definitions[endpointName];\n            const queryDescription: QueryThunkArg = {\n              type: 'query',\n              endpointName: endpointName,\n              originalArgs: entry.arg,\n              queryCacheKey: serializeQueryArgs({\n                queryArgs: arg,\n                endpointDefinition,\n                endpointName\n              })\n            };\n            return {\n              queryDescription,\n              value\n            };\n          });\n          const result = {\n            payload: queryDescriptions,\n            meta: {\n              [SHOULD_AUTOBATCH]: true,\n              requestId: nanoid(),\n              timestamp: Date.now()\n            }\n          };\n          return result;\n        }\n      },\n      queryResultPatched: {\n        reducer(draft, {\n          payload: {\n            queryCacheKey,\n            patches\n          }\n        }: PayloadAction<QuerySubstateIdentifier & {\n          patches: readonly Patch[];\n        }>) {\n          updateQuerySubstateIfExists(draft, queryCacheKey, substate => {\n            substate.data = applyPatches(substate.data as any, patches.concat());\n          });\n        },\n        prepare: prepareAutoBatched<QuerySubstateIdentifier & {\n          patches: readonly Patch[];\n        }>()\n      }\n    },\n    extraReducers(builder) {\n      builder.addCase(queryThunk.pending, (draft, {\n        meta,\n        meta: {\n          arg\n        }\n      }) => {\n        const upserting = isUpsertQuery(arg);\n        writePendingCacheEntry(draft, arg, upserting, meta);\n      }).addCase(queryThunk.fulfilled, (draft, {\n        meta,\n        payload\n      }) => {\n        const upserting = isUpsertQuery(meta.arg);\n        writeFulfilledCacheEntry(draft, meta, payload, upserting);\n      }).addCase(queryThunk.rejected, (draft, {\n        meta: {\n          condition,\n          arg,\n          requestId\n        },\n        error,\n        payload\n      }) => {\n        updateQuerySubstateIfExists(draft, arg.queryCacheKey, substate => {\n          if (condition) {\n            // request was aborted due to condition (another query already running)\n          } else {\n            // request failed\n            if (substate.requestId !== requestId) return;\n            substate.status = QueryStatus.rejected;\n            substate.error = (payload ?? error) as any;\n          }\n        });\n      }).addMatcher(hasRehydrationInfo, (draft, action) => {\n        const {\n          queries\n        } = extractRehydrationInfo(action)!;\n        for (const [key, entry] of Object.entries(queries)) {\n          if (\n          // do not rehydrate entries that were currently in flight.\n          entry?.status === QueryStatus.fulfilled || entry?.status === QueryStatus.rejected) {\n            draft[key] = entry;\n          }\n        }\n      });\n    }\n  });\n  const mutationSlice = createSlice({\n    name: `${reducerPath}/mutations`,\n    initialState: initialState as MutationState<any>,\n    reducers: {\n      removeMutationResult: {\n        reducer(draft, {\n          payload\n        }: PayloadAction<MutationSubstateIdentifier>) {\n          const cacheKey = getMutationCacheKey(payload);\n          if (cacheKey in draft) {\n            delete draft[cacheKey];\n          }\n        },\n        prepare: prepareAutoBatched<MutationSubstateIdentifier>()\n      }\n    },\n    extraReducers(builder) {\n      builder.addCase(mutationThunk.pending, (draft, {\n        meta,\n        meta: {\n          requestId,\n          arg,\n          startedTimeStamp\n        }\n      }) => {\n        if (!arg.track) return;\n        draft[getMutationCacheKey(meta)] = {\n          requestId,\n          status: QueryStatus.pending,\n          endpointName: arg.endpointName,\n          startedTimeStamp\n        };\n      }).addCase(mutationThunk.fulfilled, (draft, {\n        payload,\n        meta\n      }) => {\n        if (!meta.arg.track) return;\n        updateMutationSubstateIfExists(draft, meta, substate => {\n          if (substate.requestId !== meta.requestId) return;\n          substate.status = QueryStatus.fulfilled;\n          substate.data = payload;\n          substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;\n        });\n      }).addCase(mutationThunk.rejected, (draft, {\n        payload,\n        error,\n        meta\n      }) => {\n        if (!meta.arg.track) return;\n        updateMutationSubstateIfExists(draft, meta, substate => {\n          if (substate.requestId !== meta.requestId) return;\n          substate.status = QueryStatus.rejected;\n          substate.error = (payload ?? error) as any;\n        });\n      }).addMatcher(hasRehydrationInfo, (draft, action) => {\n        const {\n          mutations\n        } = extractRehydrationInfo(action)!;\n        for (const [key, entry] of Object.entries(mutations)) {\n          if (\n          // do not rehydrate entries that were currently in flight.\n          (entry?.status === QueryStatus.fulfilled || entry?.status === QueryStatus.rejected) &&\n          // only rehydrate endpoints that were persisted using a `fixedCacheKey`\n          key !== entry?.requestId) {\n            draft[key] = entry;\n          }\n        }\n      });\n    }\n  });\n  type CalculateProvidedByAction = UnwrapPromise<ReturnType<ReturnType<QueryThunk>> | ReturnType<ReturnType<InfiniteQueryThunk<any>>>>;\n  const initialInvalidationState: InvalidationState<string> = {\n    tags: {},\n    keys: {}\n  };\n  const invalidationSlice = createSlice({\n    name: `${reducerPath}/invalidation`,\n    initialState: initialInvalidationState,\n    reducers: {\n      updateProvidedBy: {\n        reducer(draft, action: PayloadAction<Array<{\n          queryCacheKey: QueryCacheKey;\n          providedTags: readonly FullTagDescription<string>[];\n        }>>) {\n          for (const {\n            queryCacheKey,\n            providedTags\n          } of action.payload) {\n            removeCacheKeyFromTags(draft, queryCacheKey);\n            for (const {\n              type,\n              id\n            } of providedTags) {\n              const subscribedQueries = (draft.tags[type] ??= {})[id || '__internal_without_id'] ??= [];\n              const alreadySubscribed = subscribedQueries.includes(queryCacheKey);\n              if (!alreadySubscribed) {\n                subscribedQueries.push(queryCacheKey);\n              }\n            }\n\n            // Remove readonly from the providedTags array\n            draft.keys[queryCacheKey] = providedTags as FullTagDescription<string>[];\n          }\n        },\n        prepare: prepareAutoBatched<Array<{\n          queryCacheKey: QueryCacheKey;\n          providedTags: readonly FullTagDescription<string>[];\n        }>>()\n      }\n    },\n    extraReducers(builder) {\n      builder.addCase(querySlice.actions.removeQueryResult, (draft, {\n        payload: {\n          queryCacheKey\n        }\n      }) => {\n        removeCacheKeyFromTags(draft, queryCacheKey);\n      }).addMatcher(hasRehydrationInfo, (draft, action) => {\n        const {\n          provided\n        } = extractRehydrationInfo(action)!;\n        for (const [type, incomingTags] of Object.entries(provided)) {\n          for (const [id, cacheKeys] of Object.entries(incomingTags)) {\n            const subscribedQueries = (draft.tags[type] ??= {})[id || '__internal_without_id'] ??= [];\n            for (const queryCacheKey of cacheKeys) {\n              const alreadySubscribed = subscribedQueries.includes(queryCacheKey);\n              if (!alreadySubscribed) {\n                subscribedQueries.push(queryCacheKey);\n              }\n            }\n          }\n        }\n      }).addMatcher(isAnyOf(isFulfilled(queryThunk), isRejectedWithValue(queryThunk)), (draft, action) => {\n        writeProvidedTagsForQueries(draft, [action]);\n      }).addMatcher(querySlice.actions.cacheEntriesUpserted.match, (draft, action) => {\n        const mockActions: CalculateProvidedByAction[] = action.payload.map(({\n          queryDescription,\n          value\n        }) => {\n          return {\n            type: 'UNKNOWN',\n            payload: value,\n            meta: {\n              requestStatus: 'fulfilled',\n              requestId: 'UNKNOWN',\n              arg: queryDescription\n            }\n          };\n        });\n        writeProvidedTagsForQueries(draft, mockActions);\n      });\n    }\n  });\n  function removeCacheKeyFromTags(draft: InvalidationState<any>, queryCacheKey: QueryCacheKey) {\n    const existingTags = draft.keys[queryCacheKey] ?? [];\n\n    // Delete this cache key from any existing tags that may have provided it\n    for (const tag of existingTags) {\n      const tagType = tag.type;\n      const tagId = tag.id ?? '__internal_without_id';\n      const tagSubscriptions = draft.tags[tagType]?.[tagId];\n      if (tagSubscriptions) {\n        draft.tags[tagType][tagId] = tagSubscriptions.filter(qc => qc !== queryCacheKey);\n      }\n    }\n    delete draft.keys[queryCacheKey];\n  }\n  function writeProvidedTagsForQueries(draft: InvalidationState<string>, actions: CalculateProvidedByAction[]) {\n    const providedByEntries = actions.map(action => {\n      const providedTags = calculateProvidedByThunk(action, 'providesTags', definitions, assertTagType);\n      const {\n        queryCacheKey\n      } = action.meta.arg;\n      return {\n        queryCacheKey,\n        providedTags\n      };\n    });\n    invalidationSlice.caseReducers.updateProvidedBy(draft, invalidationSlice.actions.updateProvidedBy(providedByEntries));\n  }\n\n  // Dummy slice to generate actions\n  const subscriptionSlice = createSlice({\n    name: `${reducerPath}/subscriptions`,\n    initialState: initialState as SubscriptionState,\n    reducers: {\n      updateSubscriptionOptions(d, a: PayloadAction<{\n        endpointName: string;\n        requestId: string;\n        options: Subscribers[number];\n      } & QuerySubstateIdentifier>) {\n        // Dummy\n      },\n      unsubscribeQueryResult(d, a: PayloadAction<{\n        requestId: string;\n      } & QuerySubstateIdentifier>) {\n        // Dummy\n      },\n      internal_getRTKQSubscriptions() {}\n    }\n  });\n  const internalSubscriptionsSlice = createSlice({\n    name: `${reducerPath}/internalSubscriptions`,\n    initialState: initialState as SubscriptionState,\n    reducers: {\n      subscriptionsUpdated: {\n        reducer(state, action: PayloadAction<Patch[]>) {\n          return applyPatches(state, action.payload);\n        },\n        prepare: prepareAutoBatched<Patch[]>()\n      }\n    }\n  });\n  const configSlice = createSlice({\n    name: `${reducerPath}/config`,\n    initialState: {\n      online: isOnline(),\n      focused: isDocumentVisible(),\n      middlewareRegistered: false,\n      ...config\n    } as ConfigState<string>,\n    reducers: {\n      middlewareRegistered(state, {\n        payload\n      }: PayloadAction<string>) {\n        state.middlewareRegistered = state.middlewareRegistered === 'conflict' || apiUid !== payload ? 'conflict' : true;\n      }\n    },\n    extraReducers: builder => {\n      builder.addCase(onOnline, state => {\n        state.online = true;\n      }).addCase(onOffline, state => {\n        state.online = false;\n      }).addCase(onFocus, state => {\n        state.focused = true;\n      }).addCase(onFocusLost, state => {\n        state.focused = false;\n      })\n      // update the state to be a new object to be picked up as a \"state change\"\n      // by redux-persist's `autoMergeLevel2`\n      .addMatcher(hasRehydrationInfo, draft => ({\n        ...draft\n      }));\n    }\n  });\n  const combinedReducer = combineReducers({\n    queries: querySlice.reducer,\n    mutations: mutationSlice.reducer,\n    provided: invalidationSlice.reducer,\n    subscriptions: internalSubscriptionsSlice.reducer,\n    config: configSlice.reducer\n  });\n  const reducer: typeof combinedReducer = (state, action) => combinedReducer(resetApiState.match(action) ? undefined : state, action);\n  const actions = {\n    ...configSlice.actions,\n    ...querySlice.actions,\n    ...subscriptionSlice.actions,\n    ...internalSubscriptionsSlice.actions,\n    ...mutationSlice.actions,\n    ...invalidationSlice.actions,\n    resetApiState\n  };\n  return {\n    reducer,\n    actions\n  };\n}\nexport type SliceActions = ReturnType<typeof buildSlice>['actions'];","import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { EndpointDefinition, EndpointDefinitions, InfiniteQueryArgFrom, InfiniteQueryDefinition, MutationDefinition, QueryArgFrom, QueryArgFromAnyQuery, QueryDefinition, ReducerPathFrom, TagDescription, TagTypesFrom } from '../endpointDefinitions';\nimport { expandTagDescription } from '../endpointDefinitions';\nimport { flatten, isNotNullish } from '../utils';\nimport type { InfiniteData, InfiniteQueryConfigOptions, InfiniteQuerySubState, MutationSubState, QueryCacheKey, QueryKeys, QueryState, QuerySubState, RequestStatusFlags, RootState as _RootState } from './apiState';\nimport { QueryStatus, getRequestStatusFlags } from './apiState';\nimport { getMutationCacheKey } from './buildSlice';\nimport type { createSelector as _createSelector } from './rtkImports';\nimport { createNextState } from './rtkImports';\nimport { type AllQueryKeys, getNextPageParam, getPreviousPageParam } from './buildThunks';\nexport type SkipToken = typeof skipToken;\n/**\n * Can be passed into `useQuery`, `useQueryState` or `useQuerySubscription`\n * instead of the query argument to get the same effect as if setting\n * `skip: true` in the query options.\n *\n * Useful for scenarios where a query should be skipped when `arg` is `undefined`\n * and TypeScript complains about it because `arg` is not allowed to be passed\n * in as `undefined`, such as\n *\n * ```ts\n * // codeblock-meta title=\"will error if the query argument is not allowed to be undefined\" no-transpile\n * useSomeQuery(arg, { skip: !!arg })\n * ```\n *\n * ```ts\n * // codeblock-meta title=\"using skipToken instead\" no-transpile\n * useSomeQuery(arg ?? skipToken)\n * ```\n *\n * If passed directly into a query or mutation selector, that selector will always\n * return an uninitialized state.\n */\nexport const skipToken = /* @__PURE__ */Symbol.for('RTKQ/skipToken');\nexport type BuildSelectorsApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {\n  select: QueryResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;\n};\nexport type BuildSelectorsApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {\n  select: InfiniteQueryResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;\n};\nexport type BuildSelectorsApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {\n  select: MutationResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;\n};\ntype QueryResultSelectorFactory<Definition extends QueryDefinition<any, any, any, any>, RootState> = (queryArg: QueryArgFrom<Definition> | SkipToken) => (state: RootState) => QueryResultSelectorResult<Definition>;\nexport type QueryResultSelectorResult<Definition extends QueryDefinition<any, any, any, any>> = QuerySubState<Definition> & RequestStatusFlags;\ntype InfiniteQueryResultSelectorFactory<Definition extends InfiniteQueryDefinition<any, any, any, any, any>, RootState> = (queryArg: InfiniteQueryArgFrom<Definition> | SkipToken) => (state: RootState) => InfiniteQueryResultSelectorResult<Definition>;\nexport type InfiniteQueryResultFlags = {\n  hasNextPage: boolean;\n  hasPreviousPage: boolean;\n  isFetchingNextPage: boolean;\n  isFetchingPreviousPage: boolean;\n  isFetchNextPageError: boolean;\n  isFetchPreviousPageError: boolean;\n};\nexport type InfiniteQueryResultSelectorResult<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = InfiniteQuerySubState<Definition> & RequestStatusFlags & InfiniteQueryResultFlags;\ntype MutationResultSelectorFactory<Definition extends MutationDefinition<any, any, any, any>, RootState> = (requestId: string | {\n  requestId: string | undefined;\n  fixedCacheKey: string | undefined;\n} | SkipToken) => (state: RootState) => MutationResultSelectorResult<Definition>;\nexport type MutationResultSelectorResult<Definition extends MutationDefinition<any, any, any, any>> = MutationSubState<Definition> & RequestStatusFlags;\nconst initialSubState: QuerySubState<any> = {\n  status: QueryStatus.uninitialized as const\n};\n\n// abuse immer to freeze default states\nconst defaultQuerySubState = /* @__PURE__ */createNextState(initialSubState, () => {});\nconst defaultMutationSubState = /* @__PURE__ */createNextState(initialSubState as MutationSubState<any>, () => {});\nexport type AllSelectors = ReturnType<typeof buildSelectors>;\nexport function buildSelectors<Definitions extends EndpointDefinitions, ReducerPath extends string>({\n  serializeQueryArgs,\n  reducerPath,\n  createSelector\n}: {\n  serializeQueryArgs: InternalSerializeQueryArgs;\n  reducerPath: ReducerPath;\n  createSelector: typeof _createSelector;\n}) {\n  type RootState = _RootState<Definitions, string, string>;\n  const selectSkippedQuery = (state: RootState) => defaultQuerySubState;\n  const selectSkippedMutation = (state: RootState) => defaultMutationSubState;\n  return {\n    buildQuerySelector,\n    buildInfiniteQuerySelector,\n    buildMutationSelector,\n    selectInvalidatedBy,\n    selectCachedArgsForQuery,\n    selectApiState,\n    selectQueries,\n    selectMutations,\n    selectQueryEntry,\n    selectConfig\n  };\n  function withRequestFlags<T extends {\n    status: QueryStatus;\n  }>(substate: T): T & RequestStatusFlags {\n    return {\n      ...substate,\n      ...getRequestStatusFlags(substate.status)\n    };\n  }\n  function selectApiState(rootState: RootState) {\n    const state = rootState[reducerPath];\n    if (process.env.NODE_ENV !== 'production') {\n      if (!state) {\n        if ((selectApiState as any).triggered) return state;\n        (selectApiState as any).triggered = true;\n        console.error(`Error: No data found at \\`state.${reducerPath}\\`. Did you forget to add the reducer to the store?`);\n      }\n    }\n    return state;\n  }\n  function selectQueries(rootState: RootState) {\n    return selectApiState(rootState)?.queries;\n  }\n  function selectQueryEntry(rootState: RootState, cacheKey: QueryCacheKey) {\n    return selectQueries(rootState)?.[cacheKey];\n  }\n  function selectMutations(rootState: RootState) {\n    return selectApiState(rootState)?.mutations;\n  }\n  function selectConfig(rootState: RootState) {\n    return selectApiState(rootState)?.config;\n  }\n  function buildAnyQuerySelector(endpointName: string, endpointDefinition: EndpointDefinition<any, any, any, any>, combiner: <T extends {\n    status: QueryStatus;\n  }>(substate: T) => T & RequestStatusFlags) {\n    return (queryArgs: any) => {\n      // Avoid calling serializeQueryArgs if the arg is skipToken\n      if (queryArgs === skipToken) {\n        return createSelector(selectSkippedQuery, combiner);\n      }\n      const serializedArgs = serializeQueryArgs({\n        queryArgs,\n        endpointDefinition,\n        endpointName\n      });\n      const selectQuerySubstate = (state: RootState) => selectQueryEntry(state, serializedArgs) ?? defaultQuerySubState;\n      return createSelector(selectQuerySubstate, combiner);\n    };\n  }\n  function buildQuerySelector(endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any>) {\n    return buildAnyQuerySelector(endpointName, endpointDefinition, withRequestFlags) as QueryResultSelectorFactory<any, RootState>;\n  }\n  function buildInfiniteQuerySelector(endpointName: string, endpointDefinition: InfiniteQueryDefinition<any, any, any, any, any>) {\n    const {\n      infiniteQueryOptions\n    } = endpointDefinition;\n    function withInfiniteQueryResultFlags<T extends {\n      status: QueryStatus;\n    }>(substate: T): T & RequestStatusFlags & InfiniteQueryResultFlags {\n      const stateWithRequestFlags = {\n        ...(substate as InfiniteQuerySubState<any>),\n        ...getRequestStatusFlags(substate.status)\n      };\n      const {\n        isLoading,\n        isError,\n        direction\n      } = stateWithRequestFlags;\n      const isForward = direction === 'forward';\n      const isBackward = direction === 'backward';\n      return {\n        ...stateWithRequestFlags,\n        hasNextPage: getHasNextPage(infiniteQueryOptions, stateWithRequestFlags.data, stateWithRequestFlags.originalArgs),\n        hasPreviousPage: getHasPreviousPage(infiniteQueryOptions, stateWithRequestFlags.data, stateWithRequestFlags.originalArgs),\n        isFetchingNextPage: isLoading && isForward,\n        isFetchingPreviousPage: isLoading && isBackward,\n        isFetchNextPageError: isError && isForward,\n        isFetchPreviousPageError: isError && isBackward\n      };\n    }\n    return buildAnyQuerySelector(endpointName, endpointDefinition, withInfiniteQueryResultFlags) as unknown as InfiniteQueryResultSelectorFactory<any, RootState>;\n  }\n  function buildMutationSelector() {\n    return (id => {\n      let mutationId: string | typeof skipToken;\n      if (typeof id === 'object') {\n        mutationId = getMutationCacheKey(id) ?? skipToken;\n      } else {\n        mutationId = id;\n      }\n      const selectMutationSubstate = (state: RootState) => selectApiState(state)?.mutations?.[mutationId as string] ?? defaultMutationSubState;\n      const finalSelectMutationSubstate = mutationId === skipToken ? selectSkippedMutation : selectMutationSubstate;\n      return createSelector(finalSelectMutationSubstate, withRequestFlags);\n    }) as MutationResultSelectorFactory<any, RootState>;\n  }\n  function selectInvalidatedBy(state: RootState, tags: ReadonlyArray<TagDescription<string> | null | undefined>): Array<{\n    endpointName: string;\n    originalArgs: any;\n    queryCacheKey: QueryCacheKey;\n  }> {\n    const apiState = state[reducerPath];\n    const toInvalidate = new Set<QueryCacheKey>();\n    for (const tag of tags.filter(isNotNullish).map(expandTagDescription)) {\n      const provided = apiState.provided.tags[tag.type];\n      if (!provided) {\n        continue;\n      }\n      let invalidateSubscriptions = (tag.id !== undefined ?\n      // id given: invalidate all queries that provide this type & id\n      provided[tag.id] :\n      // no id: invalidate all queries that provide this type\n      flatten(Object.values(provided))) ?? [];\n      for (const invalidate of invalidateSubscriptions) {\n        toInvalidate.add(invalidate);\n      }\n    }\n    return flatten(Array.from(toInvalidate.values()).map(queryCacheKey => {\n      const querySubState = apiState.queries[queryCacheKey];\n      return querySubState ? [{\n        queryCacheKey,\n        endpointName: querySubState.endpointName!,\n        originalArgs: querySubState.originalArgs\n      }] : [];\n    }));\n  }\n  function selectCachedArgsForQuery<QueryName extends AllQueryKeys<Definitions>>(state: RootState, queryName: QueryName): Array<QueryArgFromAnyQuery<Definitions[QueryName]>> {\n    return Object.values(selectQueries(state) as QueryState<any>).filter((entry): entry is Exclude<QuerySubState<Definitions[QueryName]>, {\n      status: QueryStatus.uninitialized;\n    }> => entry?.endpointName === queryName && entry.status !== QueryStatus.uninitialized).map(entry => entry.originalArgs);\n  }\n  function getHasNextPage(options: InfiniteQueryConfigOptions<any, any, any>, data?: InfiniteData<unknown, unknown>, queryArg?: unknown): boolean {\n    if (!data) return false;\n    return getNextPageParam(options, data, queryArg) != null;\n  }\n  function getHasPreviousPage(options: InfiniteQueryConfigOptions<any, any, any>, data?: InfiniteData<unknown, unknown>, queryArg?: unknown): boolean {\n    if (!data || !options.getPreviousPageParam) return false;\n    return getPreviousPageParam(options, data, queryArg) != null;\n  }\n}","import type { QueryCacheKey } from './core/apiState';\nimport type { EndpointDefinition } from './endpointDefinitions';\nimport { isPlainObject } from './core/rtkImports';\nconst cache: WeakMap<any, string> | undefined = WeakMap ? new WeakMap() : undefined;\nexport const defaultSerializeQueryArgs: SerializeQueryArgs<any> = ({\n  endpointName,\n  queryArgs\n}) => {\n  let serialized = '';\n  const cached = cache?.get(queryArgs);\n  if (typeof cached === 'string') {\n    serialized = cached;\n  } else {\n    const stringified = JSON.stringify(queryArgs, (key, value) => {\n      // Handle bigints\n      value = typeof value === 'bigint' ? {\n        $bigint: value.toString()\n      } : value;\n      // Sort the object keys before stringifying, to prevent useQuery({ a: 1, b: 2 }) having a different cache key than useQuery({ b: 2, a: 1 })\n      value = isPlainObject(value) ? Object.keys(value).sort().reduce<any>((acc, key) => {\n        acc[key] = (value as any)[key];\n        return acc;\n      }, {}) : value;\n      return value;\n    });\n    if (isPlainObject(queryArgs)) {\n      cache?.set(queryArgs, stringified);\n    }\n    serialized = stringified;\n  }\n  return `${endpointName}(${serialized})`;\n};\nexport type SerializeQueryArgs<QueryArgs, ReturnType = string> = (_: {\n  queryArgs: QueryArgs;\n  endpointDefinition: EndpointDefinition<any, any, any, any>;\n  endpointName: string;\n}) => ReturnType;\nexport type InternalSerializeQueryArgs = (_: {\n  queryArgs: any;\n  endpointDefinition: EndpointDefinition<any, any, any, any>;\n  endpointName: string;\n}) => QueryCacheKey;","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3 } from \"@reduxjs/toolkit\";\nimport type { Api, ApiContext, Module, ModuleName } from './apiTypes';\nimport type { CombinedState } from './core/apiState';\nimport type { BaseQueryArg, BaseQueryFn } from './baseQueryTypes';\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport type { EndpointBuilder, EndpointDefinitions, SchemaFailureConverter, SchemaFailureHandler } from './endpointDefinitions';\nimport { DefinitionType, isInfiniteQueryDefinition, isQueryDefinition } from './endpointDefinitions';\nimport { nanoid } from './core/rtkImports';\nimport type { UnknownAction } from '@reduxjs/toolkit';\nimport type { NoInfer } from './tsHelpers';\nimport { weakMapMemoize } from 'reselect';\nexport interface CreateApiOptions<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', TagTypes extends string = never> {\n  /**\n   * 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.\n   *\n   * @example\n   *\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   *\n   * const api = createApi({\n   *   // highlight-start\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   // highlight-end\n   *   endpoints: (build) => ({\n   *     // ...endpoints\n   *   }),\n   * })\n   * ```\n   */\n  baseQuery: BaseQuery;\n  /**\n   * 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).\n   *\n   * @example\n   *\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   // highlight-start\n   *   tagTypes: ['Post', 'User'],\n   *   // highlight-end\n   *   endpoints: (build) => ({\n   *     // ...endpoints\n   *   }),\n   * })\n   * ```\n   */\n  tagTypes?: readonly TagTypes[];\n  /**\n   * 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'`.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"apis.js\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query';\n   *\n   * const apiOne = createApi({\n   *   // highlight-start\n   *   reducerPath: 'apiOne',\n   *   // highlight-end\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (builder) => ({\n   *     // ...endpoints\n   *   }),\n   * });\n   *\n   * const apiTwo = createApi({\n   *   // highlight-start\n   *   reducerPath: 'apiTwo',\n   *   // highlight-end\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (builder) => ({\n   *     // ...endpoints\n   *   }),\n   * });\n   * ```\n   */\n  reducerPath?: ReducerPath;\n  /**\n   * Accepts a custom function if you have a need to change the creation of cache keys for any reason.\n   */\n  serializeQueryArgs?: SerializeQueryArgs<unknown>;\n  /**\n   * 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).\n   */\n  endpoints(build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>): Definitions;\n  /**\n   * 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.\n   *\n   * ```ts\n   * // codeblock-meta title=\"keepUnusedDataFor example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       // highlight-start\n   *       keepUnusedDataFor: 5\n   *       // highlight-end\n   *     })\n   *   })\n   * })\n   * ```\n   */\n  keepUnusedDataFor?: number;\n  /**\n   * 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.\n   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.\n   * - `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.\n   * - `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.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   */\n  refetchOnMountOrArgChange?: boolean | number;\n  /**\n   * 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.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnFocus?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnReconnect?: boolean;\n  /**\n   * Defaults to `'delayed'`. This setting allows you to control when tags are invalidated after a mutation.\n   *\n   * - `'immediately'`: Queries are invalidated instantly after the mutation finished, even if they are running.\n   *   If the query provides tags that were invalidated while it ran, it won't be re-fetched.\n   * - `'delayed'`: Invalidation only happens after all queries and mutations are settled.\n   *   This ensures that queries are always invalidated correctly and automatically \"batches\" invalidations of concurrent mutations.\n   *   Note that if you constantly have some queries (or mutations) running, this can delay tag invalidations indefinitely.\n   */\n  invalidationBehavior?: 'delayed' | 'immediately';\n  /**\n   * A function that is passed every dispatched action. If this returns something other than `undefined`,\n   * that return value will be used to rehydrate fulfilled & errored queries.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"next-redux-wrapper rehydration example\"\n   * import type { Action, PayloadAction } from '@reduxjs/toolkit'\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import { HYDRATE } from 'next-redux-wrapper'\n   *\n   * type RootState = any; // normally inferred from state\n   *\n   * function isHydrateAction(action: Action): action is PayloadAction<RootState> {\n   *   return action.type === HYDRATE\n   * }\n   *\n   * export const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   // highlight-start\n   *   extractRehydrationInfo(action, { reducerPath }): any {\n   *     if (isHydrateAction(action)) {\n   *       return action.payload[reducerPath]\n   *     }\n   *   },\n   *   // highlight-end\n   *   endpoints: (build) => ({\n   *     // omitted\n   *   }),\n   * })\n   * ```\n   */\n  extractRehydrationInfo?: (action: UnknownAction, {\n    reducerPath\n  }: {\n    reducerPath: ReducerPath;\n  }) => undefined | CombinedState<NoInfer<Definitions>, NoInfer<TagTypes>, NoInfer<ReducerPath>>;\n\n  /**\n   * A function that is called when a schema validation fails.\n   *\n   * 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).\n   *\n   * `NamedSchemaError` has the following properties:\n   * - `issues`: an array of issues that caused the validation to fail\n   * - `value`: the value that was passed to the schema\n   * - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *     }),\n   *   }),\n   *   onSchemaFailure: (error, info) => {\n   *     console.error(error, info)\n   *   },\n   * })\n   * ```\n   */\n  onSchemaFailure?: SchemaFailureHandler;\n\n  /**\n   * Convert a schema validation failure into an error shape matching base query errors.\n   *\n   * When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *     }),\n   *   }),\n   *   catchSchemaFailure: (error, info) => ({\n   *     status: \"CUSTOM_ERROR\",\n   *     error: error.schemaName + \" failed validation\",\n   *     data: error.issues,\n   *   }),\n   * })\n   * ```\n   */\n  catchSchemaFailure?: SchemaFailureConverter<BaseQuery>;\n\n  /**\n   * Defaults to `false`.\n   *\n   * If set to `true`, will skip schema validation for all endpoints, unless overridden by the endpoint.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   skipSchemaValidation: process.env.NODE_ENV === \"test\", // skip schema validation in tests, since we'll be mocking the response\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  skipSchemaValidation?: boolean;\n}\nexport type CreateApi<Modules extends ModuleName> = {\n  /**\n   * Creates a service to use in your application. Contains only the basic redux logic (the core module).\n   *\n   * @link https://redux-toolkit.js.org/rtk-query/api/createApi\n   */\n  <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>;\n};\n\n/**\n * Builds a `createApi` method based on the provided `modules`.\n *\n * @link https://redux-toolkit.js.org/rtk-query/usage/customizing-create-api\n *\n * @example\n * ```ts\n * const MyContext = React.createContext<ReactReduxContextValue | null>(null);\n * const customCreateApi = buildCreateApi(\n *   coreModule(),\n *   reactHooksModule({\n *     hooks: {\n *       useDispatch: createDispatchHook(MyContext),\n *       useSelector: createSelectorHook(MyContext),\n *       useStore: createStoreHook(MyContext)\n *     }\n *   })\n * );\n * ```\n *\n * @param modules - A variable number of modules that customize how the `createApi` method handles endpoints\n * @returns A `createApi` method using the provided `modules`.\n */\nexport function buildCreateApi<Modules extends [Module<any>, ...Module<any>[]]>(...modules: Modules): CreateApi<Modules[number]['name']> {\n  return function baseCreateApi(options) {\n    const extractRehydrationInfo = weakMapMemoize((action: UnknownAction) => options.extractRehydrationInfo?.(action, {\n      reducerPath: (options.reducerPath ?? 'api') as any\n    }));\n    const optionsWithDefaults: CreateApiOptions<any, any, any, any> = {\n      reducerPath: 'api',\n      keepUnusedDataFor: 60,\n      refetchOnMountOrArgChange: false,\n      refetchOnFocus: false,\n      refetchOnReconnect: false,\n      invalidationBehavior: 'delayed',\n      ...options,\n      extractRehydrationInfo,\n      serializeQueryArgs(queryArgsApi) {\n        let finalSerializeQueryArgs = defaultSerializeQueryArgs;\n        if ('serializeQueryArgs' in queryArgsApi.endpointDefinition) {\n          const endpointSQA = queryArgsApi.endpointDefinition.serializeQueryArgs!;\n          finalSerializeQueryArgs = queryArgsApi => {\n            const initialResult = endpointSQA(queryArgsApi);\n            if (typeof initialResult === 'string') {\n              // If the user function returned a string, use it as-is\n              return initialResult;\n            } else {\n              // Assume they returned an object (such as a subset of the original\n              // query args) or a primitive, and serialize it ourselves\n              return defaultSerializeQueryArgs({\n                ...queryArgsApi,\n                queryArgs: initialResult\n              });\n            }\n          };\n        } else if (options.serializeQueryArgs) {\n          finalSerializeQueryArgs = options.serializeQueryArgs;\n        }\n        return finalSerializeQueryArgs(queryArgsApi);\n      },\n      tagTypes: [...(options.tagTypes || [])]\n    };\n    const context: ApiContext<EndpointDefinitions> = {\n      endpointDefinitions: {},\n      batch(fn) {\n        // placeholder \"batch\" method to be overridden by plugins, for example with React.unstable_batchedUpdate\n        fn();\n      },\n      apiUid: nanoid(),\n      extractRehydrationInfo,\n      hasRehydrationInfo: weakMapMemoize(action => extractRehydrationInfo(action) != null)\n    };\n    const api = {\n      injectEndpoints,\n      enhanceEndpoints({\n        addTagTypes,\n        endpoints\n      }) {\n        if (addTagTypes) {\n          for (const eT of addTagTypes) {\n            if (!optionsWithDefaults.tagTypes!.includes(eT as any)) {\n              ;\n              (optionsWithDefaults.tagTypes as any[]).push(eT);\n            }\n          }\n        }\n        if (endpoints) {\n          for (const [endpointName, partialDefinition] of Object.entries(endpoints)) {\n            if (typeof partialDefinition === 'function') {\n              partialDefinition(context.endpointDefinitions[endpointName]);\n            } else {\n              Object.assign(context.endpointDefinitions[endpointName] || {}, partialDefinition);\n            }\n          }\n        }\n        return api;\n      }\n    } as Api<BaseQueryFn, {}, string, string, Modules[number]['name']>;\n    const initializedModules = modules.map(m => m.init(api as any, optionsWithDefaults as any, context));\n    function injectEndpoints(inject: Parameters<typeof api.injectEndpoints>[0]) {\n      const evaluatedEndpoints = inject.endpoints({\n        query: x => ({\n          ...x,\n          type: DefinitionType.query\n        }) as any,\n        mutation: x => ({\n          ...x,\n          type: DefinitionType.mutation\n        }) as any,\n        infiniteQuery: x => ({\n          ...x,\n          type: DefinitionType.infinitequery\n        }) as any\n      });\n      for (const [endpointName, definition] of Object.entries(evaluatedEndpoints)) {\n        if (inject.overrideExisting !== true && endpointName in context.endpointDefinitions) {\n          if (inject.overrideExisting === 'throw') {\n            throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(39) : `called \\`injectEndpoints\\` to override already-existing endpointName ${endpointName} without specifying \\`overrideExisting: true\\``);\n          } else if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n            console.error(`called \\`injectEndpoints\\` to override already-existing endpointName ${endpointName} without specifying \\`overrideExisting: true\\``);\n          }\n          continue;\n        }\n        if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n          if (isInfiniteQueryDefinition(definition)) {\n            const {\n              infiniteQueryOptions\n            } = definition;\n            const {\n              maxPages,\n              getPreviousPageParam\n            } = infiniteQueryOptions;\n            if (typeof maxPages === 'number') {\n              if (maxPages < 1) {\n                throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(40) : `maxPages for endpoint '${endpointName}' must be a number greater than 0`);\n              }\n              if (typeof getPreviousPageParam !== 'function') {\n                throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(41) : `getPreviousPageParam for endpoint '${endpointName}' must be a function if maxPages is used`);\n              }\n            }\n          }\n        }\n        context.endpointDefinitions[endpointName] = definition;\n        for (const m of initializedModules) {\n          m.injectEndpoint(endpointName, definition);\n        }\n      }\n      return api as any;\n    }\n    return api.injectEndpoints({\n      endpoints: options.endpoints as any\n    });\n  };\n}","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { BaseQueryFn } from './baseQueryTypes';\nexport const _NEVER = /* @__PURE__ */Symbol();\nexport type NEVER = typeof _NEVER;\n\n/**\n * Creates a \"fake\" baseQuery to be used if your api *only* uses the `queryFn` definition syntax.\n * This also allows you to specify a specific error type to be shared by all your `queryFn` definitions.\n */\nexport function fakeBaseQuery<ErrorType>(): BaseQueryFn<void, NEVER, ErrorType, {}> {\n  return function () {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(33) : 'When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.');\n  };\n}","/**\n * Note: this file should import all other files for type discovery and declaration merging\n */\nimport type { ActionCreatorWithPayload, Middleware, Reducer, ThunkAction, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport { enablePatches } from 'immer';\nimport type { Api, Module } from '../apiTypes';\nimport type { BaseQueryFn } from '../baseQueryTypes';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { AssertTagTypes, EndpointDefinitions, InfiniteQueryDefinition, MutationDefinition, QueryArgFrom, QueryArgFromAnyQuery, QueryDefinition, TagDescription } from '../endpointDefinitions';\nimport { isInfiniteQueryDefinition, isMutationDefinition, isQueryDefinition } from '../endpointDefinitions';\nimport { assertCast, safeAssign } from '../tsHelpers';\nimport type { CombinedState, MutationKeys, QueryKeys, RootState } from './apiState';\nimport type { BuildInitiateApiEndpointMutation, BuildInitiateApiEndpointQuery, MutationActionCreatorResult, QueryActionCreatorResult, InfiniteQueryActionCreatorResult, BuildInitiateApiEndpointInfiniteQuery } from './buildInitiate';\nimport { buildInitiate } from './buildInitiate';\nimport type { ReferenceCacheCollection, ReferenceCacheLifecycle, ReferenceQueryLifecycle } from './buildMiddleware';\nimport { buildMiddleware } from './buildMiddleware';\nimport type { BuildSelectorsApiEndpointInfiniteQuery, BuildSelectorsApiEndpointMutation, BuildSelectorsApiEndpointQuery } from './buildSelectors';\nimport { buildSelectors } from './buildSelectors';\nimport type { SliceActions, UpsertEntries } from './buildSlice';\nimport { buildSlice } from './buildSlice';\nimport type { AllQueryKeys, BuildThunksApiEndpointInfiniteQuery, BuildThunksApiEndpointMutation, BuildThunksApiEndpointQuery, PatchQueryDataThunk, QueryArgFromAnyQueryDefinition, UpdateQueryDataThunk, UpsertQueryDataThunk } from './buildThunks';\nimport { buildThunks } from './buildThunks';\nimport { createSelector as _createSelector } from './rtkImports';\nimport { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners';\n\n/**\n * `ifOlderThan` - (default: `false` | `number`) - _number is value in seconds_\n * - If specified, it will only run the query if the difference between `new Date()` and the last `fulfilledTimeStamp` is greater than the given value\n *\n * @overloadSummary\n * `force`\n * - 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.\n */\nexport type PrefetchOptions = {\n  ifOlderThan?: false | number;\n} | {\n  force?: boolean;\n};\nexport const coreModuleName = /* @__PURE__ */Symbol();\nexport type CoreModule = typeof coreModuleName | ReferenceCacheLifecycle | ReferenceQueryLifecycle | ReferenceCacheCollection;\nexport type ThunkWithReturnValue<T> = ThunkAction<T, any, any, UnknownAction>;\nexport interface ApiModules<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nBaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string> {\n  [coreModuleName]: {\n    /**\n     * This api's reducer should be mounted at `store[api.reducerPath]`.\n     *\n     * @example\n     * ```ts\n     * configureStore({\n     *   reducer: {\n     *     [api.reducerPath]: api.reducer,\n     *   },\n     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\n     * })\n     * ```\n     */\n    reducerPath: ReducerPath;\n    /**\n     * Internal actions not part of the public API. Note: These are subject to change at any given time.\n     */\n    internalActions: InternalActions;\n    /**\n     *  A standard redux reducer that enables core functionality. Make sure it's included in your store.\n     *\n     * @example\n     * ```ts\n     * configureStore({\n     *   reducer: {\n     *     [api.reducerPath]: api.reducer,\n     *   },\n     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\n     * })\n     * ```\n     */\n    reducer: Reducer<CombinedState<Definitions, TagTypes, ReducerPath>, UnknownAction>;\n    /**\n     * 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.\n     *\n     * @example\n     * ```ts\n     * configureStore({\n     *   reducer: {\n     *     [api.reducerPath]: api.reducer,\n     *   },\n     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\n     * })\n     * ```\n     */\n    middleware: Middleware<{}, RootState<Definitions, string, ReducerPath>, ThunkDispatch<any, any, UnknownAction>>;\n    /**\n     * A collection of utility thunks for various situations.\n     */\n    util: {\n      /**\n       * A thunk that (if dispatched) will return a specific running query, identified\n       * by `endpointName` and `arg`.\n       * If that query is not running, dispatching the thunk will result in `undefined`.\n       *\n       * Can be used to await a specific query triggered in any way,\n       * including via hook calls or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningQueryThunk<EndpointName extends AllQueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>): ThunkWithReturnValue<QueryActionCreatorResult<Definitions[EndpointName] & {\n        type: 'query';\n      }> | InfiniteQueryActionCreatorResult<Definitions[EndpointName] & {\n        type: 'infinitequery';\n      }> | undefined>;\n\n      /**\n       * A thunk that (if dispatched) will return a specific running mutation, identified\n       * by `endpointName` and `fixedCacheKey` or `requestId`.\n       * If that mutation is not running, dispatching the thunk will result in `undefined`.\n       *\n       * Can be used to await a specific mutation triggered in any way,\n       * including via hook trigger functions or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningMutationThunk<EndpointName extends MutationKeys<Definitions>>(endpointName: EndpointName, fixedCacheKeyOrRequestId: string): ThunkWithReturnValue<MutationActionCreatorResult<Definitions[EndpointName] & {\n        type: 'mutation';\n      }> | undefined>;\n\n      /**\n       * A thunk that (if dispatched) will return all running queries.\n       *\n       * Useful for SSR scenarios to await all running queries triggered in any way,\n       * including via hook calls or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningQueriesThunk(): ThunkWithReturnValue<Array<QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>>>;\n\n      /**\n       * A thunk that (if dispatched) will return all running mutations.\n       *\n       * Useful for SSR scenarios to await all running mutations triggered in any way,\n       * including via hook calls or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningMutationsThunk(): ThunkWithReturnValue<Array<MutationActionCreatorResult<any>>>;\n\n      /**\n       * A Redux thunk that can be used to manually trigger pre-fetching of data.\n       *\n       * 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.\n       *\n       * 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.\n       *\n       * @example\n       *\n       * ```ts no-transpile\n       * dispatch(api.util.prefetch('getPosts', undefined, { force: true }))\n       * ```\n       */\n      prefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFrom<Definitions[EndpointName]>, options: PrefetchOptions): ThunkAction<void, any, any, UnknownAction>;\n      /**\n       * 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.\n       *\n       * 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.\n       *\n       * 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).\n       *\n       * 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.\n       *\n       * 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.\n       *\n       * @example\n       *\n       * ```ts\n       * const patchCollection = dispatch(\n       *   api.util.updateQueryData('getPosts', undefined, (draftPosts) => {\n       *     draftPosts.push({ id: 1, name: 'Teddy' })\n       *   })\n       * )\n       * ```\n       */\n      updateQueryData: UpdateQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;\n\n      /**\n       * A Redux thunk action creator that, when dispatched, acts as an artificial API request to upsert a value into the cache.\n       *\n       * 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.\n       *\n       * 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.\n       *\n       * The thunk executes _asynchronously_, and returns a promise that resolves when the store has been updated.\n       *\n       * 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.\n       *\n       * @example\n       *\n       * ```ts\n       * await dispatch(\n       *   api.util.upsertQueryData('getPost', {id: 1}, {id: 1, text: \"Hello!\"})\n       * )\n       * ```\n       */\n      upsertQueryData: UpsertQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;\n      /**\n       * 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.\n       *\n       * 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`.\n       *\n       * 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.\n       *\n       * 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.\n       *\n       * @example\n       * ```ts\n       * const patchCollection = dispatch(\n       *   api.util.updateQueryData('getPosts', undefined, (draftPosts) => {\n       *     draftPosts.push({ id: 1, name: 'Teddy' })\n       *   })\n       * )\n       *\n       * // later\n       * dispatch(\n       *   api.util.patchQueryData('getPosts', undefined, patchCollection.inversePatches)\n       * )\n       *\n       * // or\n       * patchCollection.undo()\n       * ```\n       */\n      patchQueryData: PatchQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;\n\n      /**\n       * 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'.\n       *\n       * @example\n       *\n       * ```ts\n       * dispatch(api.util.resetApiState())\n       * ```\n       */\n      resetApiState: SliceActions['resetApiState'];\n      upsertQueryEntries: UpsertEntries<Definitions>;\n\n      /**\n       * A Redux action creator that can be used to manually invalidate cache tags for [automated re-fetching](../../usage/automated-refetching.mdx).\n       *\n       * 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.\n       *\n       * 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.\n       *\n       * 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:\n       *\n       * - `[TagType]`\n       * - `[{ type: TagType }]`\n       * - `[{ type: TagType, id: number | string }]`\n       *\n       * @example\n       *\n       * ```ts\n       * dispatch(api.util.invalidateTags(['Post']))\n       * dispatch(api.util.invalidateTags([{ type: 'Post', id: 1 }]))\n       * dispatch(\n       *   api.util.invalidateTags([\n       *     { type: 'Post', id: 1 },\n       *     { type: 'Post', id: 'LIST' },\n       *   ])\n       * )\n       * ```\n       */\n      invalidateTags: ActionCreatorWithPayload<Array<TagDescription<TagTypes> | null | undefined>, string>;\n\n      /**\n       * A function to select all `{ endpointName, originalArgs, queryCacheKey }` combinations that would be invalidated by a specific set of tags.\n       *\n       * 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.\n       */\n      selectInvalidatedBy: (state: RootState<Definitions, string, ReducerPath>, tags: ReadonlyArray<TagDescription<TagTypes> | null | undefined>) => Array<{\n        endpointName: string;\n        originalArgs: any;\n        queryCacheKey: string;\n      }>;\n\n      /**\n       * A function to select all arguments currently cached for a given endpoint.\n       *\n       * 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.\n       */\n      selectCachedArgsForQuery: <QueryName extends AllQueryKeys<Definitions>>(state: RootState<Definitions, string, ReducerPath>, queryName: QueryName) => Array<QueryArgFromAnyQuery<Definitions[QueryName]>>;\n    };\n    /**\n     * Endpoints based on the input endpoints provided to `createApi`, containing `select` and `action matchers`.\n     */\n    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 };\n  };\n}\nexport interface ApiEndpointQuery<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinition extends QueryDefinition<any, any, any, any, any>,\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinitions extends EndpointDefinitions> extends BuildThunksApiEndpointQuery<Definition>, BuildInitiateApiEndpointQuery<Definition>, BuildSelectorsApiEndpointQuery<Definition, Definitions> {\n  name: string;\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types: NonNullable<Definition['Types']>;\n}\nexport interface ApiEndpointInfiniteQuery<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinition extends InfiniteQueryDefinition<any, any, any, any, any>,\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinitions extends EndpointDefinitions> extends BuildThunksApiEndpointInfiniteQuery<Definition>, BuildInitiateApiEndpointInfiniteQuery<Definition>, BuildSelectorsApiEndpointInfiniteQuery<Definition, Definitions> {\n  name: string;\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types: NonNullable<Definition['Types']>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface ApiEndpointMutation<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinition extends MutationDefinition<any, any, any, any, any>,\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinitions extends EndpointDefinitions> extends BuildThunksApiEndpointMutation<Definition>, BuildInitiateApiEndpointMutation<Definition>, BuildSelectorsApiEndpointMutation<Definition, Definitions> {\n  name: string;\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types: NonNullable<Definition['Types']>;\n}\nexport type ListenerActions = {\n  /**\n   * Will cause the RTK Query middleware to trigger any refetchOnReconnect-related behavior\n   * @link https://redux-toolkit.js.org/rtk-query/api/setupListeners\n   */\n  onOnline: typeof onOnline;\n  onOffline: typeof onOffline;\n  /**\n   * Will cause the RTK Query middleware to trigger any refetchOnFocus-related behavior\n   * @link https://redux-toolkit.js.org/rtk-query/api/setupListeners\n   */\n  onFocus: typeof onFocus;\n  onFocusLost: typeof onFocusLost;\n};\nexport type InternalActions = SliceActions & ListenerActions;\nexport interface CoreModuleOptions {\n  /**\n   * A selector creator (usually from `reselect`, or matching the same signature)\n   */\n  createSelector?: typeof _createSelector;\n}\n\n/**\n * Creates a module containing the basic redux logic for use with `buildCreateApi`.\n *\n * @example\n * ```ts\n * const createBaseApi = buildCreateApi(coreModule());\n * ```\n */\nexport const coreModule = ({\n  createSelector = _createSelector\n}: CoreModuleOptions = {}): Module<CoreModule> => ({\n  name: coreModuleName,\n  init(api, {\n    baseQuery,\n    tagTypes,\n    reducerPath,\n    serializeQueryArgs,\n    keepUnusedDataFor,\n    refetchOnMountOrArgChange,\n    refetchOnFocus,\n    refetchOnReconnect,\n    invalidationBehavior,\n    onSchemaFailure,\n    catchSchemaFailure,\n    skipSchemaValidation\n  }, context) {\n    enablePatches();\n    assertCast<InternalSerializeQueryArgs>(serializeQueryArgs);\n    const assertTagType: AssertTagTypes = tag => {\n      if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n        if (!tagTypes.includes(tag.type as any)) {\n          console.error(`Tag type '${tag.type}' was used, but not specified in \\`tagTypes\\`!`);\n        }\n      }\n      return tag;\n    };\n    Object.assign(api, {\n      reducerPath,\n      endpoints: {},\n      internalActions: {\n        onOnline,\n        onOffline,\n        onFocus,\n        onFocusLost\n      },\n      util: {}\n    });\n    const selectors = buildSelectors({\n      serializeQueryArgs: serializeQueryArgs as any,\n      reducerPath,\n      createSelector\n    });\n    const {\n      selectInvalidatedBy,\n      selectCachedArgsForQuery,\n      buildQuerySelector,\n      buildInfiniteQuerySelector,\n      buildMutationSelector\n    } = selectors;\n    safeAssign(api.util, {\n      selectInvalidatedBy,\n      selectCachedArgsForQuery\n    });\n    const {\n      queryThunk,\n      infiniteQueryThunk,\n      mutationThunk,\n      patchQueryData,\n      updateQueryData,\n      upsertQueryData,\n      prefetch,\n      buildMatchThunkActions\n    } = buildThunks({\n      baseQuery,\n      reducerPath,\n      context,\n      api,\n      serializeQueryArgs,\n      assertTagType,\n      selectors,\n      onSchemaFailure,\n      catchSchemaFailure,\n      skipSchemaValidation\n    });\n    const {\n      reducer,\n      actions: sliceActions\n    } = buildSlice({\n      context,\n      queryThunk,\n      infiniteQueryThunk,\n      mutationThunk,\n      serializeQueryArgs,\n      reducerPath,\n      assertTagType,\n      config: {\n        refetchOnFocus,\n        refetchOnReconnect,\n        refetchOnMountOrArgChange,\n        keepUnusedDataFor,\n        reducerPath,\n        invalidationBehavior\n      }\n    });\n    safeAssign(api.util, {\n      patchQueryData,\n      updateQueryData,\n      upsertQueryData,\n      prefetch,\n      resetApiState: sliceActions.resetApiState,\n      upsertQueryEntries: sliceActions.cacheEntriesUpserted as any\n    });\n    safeAssign(api.internalActions, sliceActions);\n    const {\n      middleware,\n      actions: middlewareActions\n    } = buildMiddleware({\n      reducerPath,\n      context,\n      queryThunk,\n      mutationThunk,\n      infiniteQueryThunk,\n      api,\n      assertTagType,\n      selectors\n    });\n    safeAssign(api.util, middlewareActions);\n    safeAssign(api, {\n      reducer: reducer as any,\n      middleware\n    });\n    const {\n      buildInitiateQuery,\n      buildInitiateInfiniteQuery,\n      buildInitiateMutation,\n      getRunningMutationThunk,\n      getRunningMutationsThunk,\n      getRunningQueriesThunk,\n      getRunningQueryThunk\n    } = buildInitiate({\n      queryThunk,\n      mutationThunk,\n      infiniteQueryThunk,\n      api,\n      serializeQueryArgs: serializeQueryArgs as any,\n      context\n    });\n    safeAssign(api.util, {\n      getRunningMutationThunk,\n      getRunningMutationsThunk,\n      getRunningQueryThunk,\n      getRunningQueriesThunk\n    });\n    return {\n      name: coreModuleName,\n      injectEndpoint(endpointName, definition) {\n        const anyApi = api as any as Api<any, Record<string, any>, string, string, CoreModule>;\n        const endpoint = anyApi.endpoints[endpointName] ??= {} as any;\n        if (isQueryDefinition(definition)) {\n          safeAssign(endpoint, {\n            name: endpointName,\n            select: buildQuerySelector(endpointName, definition),\n            initiate: buildInitiateQuery(endpointName, definition)\n          }, buildMatchThunkActions(queryThunk, endpointName));\n        }\n        if (isMutationDefinition(definition)) {\n          safeAssign(endpoint, {\n            name: endpointName,\n            select: buildMutationSelector(),\n            initiate: buildInitiateMutation(endpointName)\n          }, buildMatchThunkActions(mutationThunk, endpointName));\n        }\n        if (isInfiniteQueryDefinition(definition)) {\n          safeAssign(endpoint, {\n            name: endpointName,\n            select: buildInfiniteQuerySelector(endpointName, definition),\n            initiate: buildInitiateInfiniteQuery(endpointName, definition)\n          }, buildMatchThunkActions(queryThunk, endpointName));\n        }\n      }\n    };\n  }\n});","export type Id<T> = { [K in keyof T]: T[K] } & {};\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\nexport type Override<T1, T2> = T2 extends any ? Omit<T1, keyof T2> & T2 : never;\nexport function assertCast<T>(v: any): asserts v is T {}\nexport function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>): T {\n  return Object.assign(target, ...args);\n}\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;\nexport type NonOptionalKeys<T> = { [K in keyof T]-?: undefined extends T[K] ? never : K }[keyof T];\nexport type HasRequiredProps<T, True, False> = NonOptionalKeys<T> extends never ? False : True;\nexport type OptionalIfAllPropsOptional<T> = HasRequiredProps<T, T, T | never>;\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\nexport type NonUndefined<T> = T extends undefined ? never : T;\nexport type UnwrapPromise<T> = T extends PromiseLike<infer V> ? V : T;\nexport type MaybePromise<T> = T | PromiseLike<T>;\nexport type OmitFromUnion<T, K extends keyof T> = T extends any ? Omit<T, K> : never;\nexport type IsAny<T, True, False = never> = true | false extends (T extends never ? true : false) ? True : False;\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>;","import type { InternalHandlerBuilder, SubscriptionSelectors } from './types';\nimport type { SubscriptionState } from '../apiState';\nimport { produceWithPatches } from 'immer';\nimport type { Action } from '@reduxjs/toolkit';\nimport { countObjectKeys } from '../../utils/countObjectKeys';\nexport const buildBatchedActionsHandler: InternalHandlerBuilder<[actionShouldContinue: boolean, returnValue: SubscriptionSelectors | boolean]> = ({\n  api,\n  queryThunk,\n  internalState\n}) => {\n  const subscriptionsPrefix = `${api.reducerPath}/subscriptions`;\n  let previousSubscriptions: SubscriptionState = null as unknown as SubscriptionState;\n  let updateSyncTimer: ReturnType<typeof window.setTimeout> | null = null;\n  const {\n    updateSubscriptionOptions,\n    unsubscribeQueryResult\n  } = api.internalActions;\n\n  // Actually intentionally mutate the subscriptions state used in the middleware\n  // This is done to speed up perf when loading many components\n  const actuallyMutateSubscriptions = (mutableState: SubscriptionState, action: Action) => {\n    if (updateSubscriptionOptions.match(action)) {\n      const {\n        queryCacheKey,\n        requestId,\n        options\n      } = action.payload;\n      if (mutableState?.[queryCacheKey]?.[requestId]) {\n        mutableState[queryCacheKey]![requestId] = options;\n      }\n      return true;\n    }\n    if (unsubscribeQueryResult.match(action)) {\n      const {\n        queryCacheKey,\n        requestId\n      } = action.payload;\n      if (mutableState[queryCacheKey]) {\n        delete mutableState[queryCacheKey]![requestId];\n      }\n      return true;\n    }\n    if (api.internalActions.removeQueryResult.match(action)) {\n      delete mutableState[action.payload.queryCacheKey];\n      return true;\n    }\n    if (queryThunk.pending.match(action)) {\n      const {\n        meta: {\n          arg,\n          requestId\n        }\n      } = action;\n      const substate = mutableState[arg.queryCacheKey] ??= {};\n      substate[`${requestId}_running`] = {};\n      if (arg.subscribe) {\n        substate[requestId] = arg.subscriptionOptions ?? substate[requestId] ?? {};\n      }\n      return true;\n    }\n    let mutated = false;\n    if (queryThunk.fulfilled.match(action) || queryThunk.rejected.match(action)) {\n      const state = mutableState[action.meta.arg.queryCacheKey] || {};\n      const key = `${action.meta.requestId}_running`;\n      mutated ||= !!state[key];\n      delete state[key];\n    }\n    if (queryThunk.rejected.match(action)) {\n      const {\n        meta: {\n          condition,\n          arg,\n          requestId\n        }\n      } = action;\n      if (condition && arg.subscribe) {\n        const substate = mutableState[arg.queryCacheKey] ??= {};\n        substate[requestId] = arg.subscriptionOptions ?? substate[requestId] ?? {};\n        mutated = true;\n      }\n    }\n    return mutated;\n  };\n  const getSubscriptions = () => internalState.currentSubscriptions;\n  const getSubscriptionCount = (queryCacheKey: string) => {\n    const subscriptions = getSubscriptions();\n    const subscriptionsForQueryArg = subscriptions[queryCacheKey] ?? {};\n    return countObjectKeys(subscriptionsForQueryArg);\n  };\n  const isRequestSubscribed = (queryCacheKey: string, requestId: string) => {\n    const subscriptions = getSubscriptions();\n    return !!subscriptions?.[queryCacheKey]?.[requestId];\n  };\n  const subscriptionSelectors: SubscriptionSelectors = {\n    getSubscriptions,\n    getSubscriptionCount,\n    isRequestSubscribed\n  };\n  return (action, mwApi): [actionShouldContinue: boolean, result: SubscriptionSelectors | boolean] => {\n    if (!previousSubscriptions) {\n      // Initialize it the first time this handler runs\n      previousSubscriptions = JSON.parse(JSON.stringify(internalState.currentSubscriptions));\n    }\n    if (api.util.resetApiState.match(action)) {\n      previousSubscriptions = internalState.currentSubscriptions = {};\n      updateSyncTimer = null;\n      return [true, false];\n    }\n\n    // Intercept requests by hooks to see if they're subscribed\n    // We return the internal state reference so that hooks\n    // can do their own checks to see if they're still active.\n    // It's stupid and hacky, but it does cut down on some dispatch calls.\n    if (api.internalActions.internal_getRTKQSubscriptions.match(action)) {\n      return [false, subscriptionSelectors];\n    }\n\n    // Update subscription data based on this action\n    const didMutate = actuallyMutateSubscriptions(internalState.currentSubscriptions, action);\n    let actionShouldContinue = true;\n    if (didMutate) {\n      if (!updateSyncTimer) {\n        // We only use the subscription state for the Redux DevTools at this point,\n        // as the real data is kept here in the middleware.\n        // Given that, we can throttle synchronizing this state significantly to\n        // save on overall perf.\n        // In 1.9, it was updated in a microtask, but now we do it at most every 500ms.\n        updateSyncTimer = setTimeout(() => {\n          // Deep clone the current subscription data\n          const newSubscriptions: SubscriptionState = JSON.parse(JSON.stringify(internalState.currentSubscriptions));\n          // Figure out a smaller diff between original and current\n          const [, patches] = produceWithPatches(previousSubscriptions, () => newSubscriptions);\n\n          // Sync the store state for visibility\n          mwApi.next(api.internalActions.subscriptionsUpdated(patches));\n          // Save the cloned state for later reference\n          previousSubscriptions = newSubscriptions;\n          updateSyncTimer = null;\n        }, 500);\n      }\n      const isSubscriptionSliceAction = typeof action.type == 'string' && !!action.type.startsWith(subscriptionsPrefix);\n      const isAdditionalSubscriptionAction = queryThunk.rejected.match(action) && action.meta.condition && !!action.meta.arg.subscribe;\n      actionShouldContinue = !isSubscriptionSliceAction && !isAdditionalSubscriptionAction;\n    }\n    return [actionShouldContinue, false];\n  };\n};","import type { QueryDefinition } from '../../endpointDefinitions';\nimport type { ConfigState, QueryCacheKey } from '../apiState';\nimport { isAnyOf } from '../rtkImports';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, QueryStateMeta, SubMiddlewareApi, TimeoutId } from './types';\nexport type ReferenceCacheCollection = never;\nfunction isObjectEmpty(obj: Record<any, any>) {\n  // Apparently a for..in loop is faster than `Object.keys()` here:\n  // https://stackoverflow.com/a/59787784/62937\n  for (const k in obj) {\n    // If there is at least one key, it's not empty\n    return false;\n  }\n  return true;\n}\nexport type CacheCollectionQueryExtraOptions = {\n  /**\n   * Overrides the api-wide definition of `keepUnusedDataFor` for this endpoint only. _(This value is in seconds.)_\n   *\n   * 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.\n   */\n  keepUnusedDataFor?: number;\n};\n\n// Per https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value , browsers store\n// `setTimeout()` timer values in a 32-bit int. If we pass a value in that's larger than that,\n// it wraps and ends up executing immediately.\n// Our `keepUnusedDataFor` values are in seconds, so adjust the numbers here accordingly.\nexport const THIRTY_TWO_BIT_MAX_INT = 2_147_483_647;\nexport const THIRTY_TWO_BIT_MAX_TIMER_SECONDS = 2_147_483_647 / 1_000 - 1;\nexport const buildCacheCollectionHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  api,\n  queryThunk,\n  context,\n  internalState,\n  selectors: {\n    selectQueryEntry,\n    selectConfig\n  }\n}) => {\n  const {\n    removeQueryResult,\n    unsubscribeQueryResult,\n    cacheEntriesUpserted\n  } = api.internalActions;\n  const canTriggerUnsubscribe = isAnyOf(unsubscribeQueryResult.match, queryThunk.fulfilled, queryThunk.rejected, cacheEntriesUpserted.match);\n  function anySubscriptionsRemainingForKey(queryCacheKey: string) {\n    const subscriptions = internalState.currentSubscriptions[queryCacheKey];\n    return !!subscriptions && !isObjectEmpty(subscriptions);\n  }\n  const currentRemovalTimeouts: QueryStateMeta<TimeoutId> = {};\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi, internalState) => {\n    const state = mwApi.getState();\n    const config = selectConfig(state);\n    if (canTriggerUnsubscribe(action)) {\n      let queryCacheKeys: QueryCacheKey[];\n      if (cacheEntriesUpserted.match(action)) {\n        queryCacheKeys = action.payload.map(entry => entry.queryDescription.queryCacheKey);\n      } else {\n        const {\n          queryCacheKey\n        } = unsubscribeQueryResult.match(action) ? action.payload : action.meta.arg;\n        queryCacheKeys = [queryCacheKey];\n      }\n      handleUnsubscribeMany(queryCacheKeys, mwApi, config);\n    }\n    if (api.util.resetApiState.match(action)) {\n      for (const [key, timeout] of Object.entries(currentRemovalTimeouts)) {\n        if (timeout) clearTimeout(timeout);\n        delete currentRemovalTimeouts[key];\n      }\n    }\n    if (context.hasRehydrationInfo(action)) {\n      const {\n        queries\n      } = context.extractRehydrationInfo(action)!;\n      // Gotcha:\n      // If rehydrating before the endpoint has been injected,the global `keepUnusedDataFor`\n      // will be used instead of the endpoint-specific one.\n      handleUnsubscribeMany(Object.keys(queries) as QueryCacheKey[], mwApi, config);\n    }\n  };\n  function handleUnsubscribeMany(cacheKeys: QueryCacheKey[], api: SubMiddlewareApi, config: ConfigState<string>) {\n    const state = api.getState();\n    for (const queryCacheKey of cacheKeys) {\n      const entry = selectQueryEntry(state, queryCacheKey);\n      handleUnsubscribe(queryCacheKey, entry?.endpointName, api, config);\n    }\n  }\n  function handleUnsubscribe(queryCacheKey: QueryCacheKey, endpointName: string | undefined, api: SubMiddlewareApi, config: ConfigState<string>) {\n    const endpointDefinition = context.endpointDefinitions[endpointName!] as QueryDefinition<any, any, any, any>;\n    const keepUnusedDataFor = endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor;\n    if (keepUnusedDataFor === Infinity) {\n      // Hey, user said keep this forever!\n      return;\n    }\n    // Prevent `setTimeout` timers from overflowing a 32-bit internal int, by\n    // clamping the max value to be at most 1000ms less than the 32-bit max.\n    // Look, a 24.8-day keepalive ought to be enough for anybody, right? :)\n    // Also avoid negative values too.\n    const finalKeepUnusedDataFor = Math.max(0, Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS));\n    if (!anySubscriptionsRemainingForKey(queryCacheKey)) {\n      const currentTimeout = currentRemovalTimeouts[queryCacheKey];\n      if (currentTimeout) {\n        clearTimeout(currentTimeout);\n      }\n      currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {\n        if (!anySubscriptionsRemainingForKey(queryCacheKey)) {\n          api.dispatch(removeQueryResult({\n            queryCacheKey\n          }));\n        }\n        delete currentRemovalTimeouts![queryCacheKey];\n      }, finalKeepUnusedDataFor * 1000);\n    }\n  }\n  return handler;\n};","import type { ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport type { BaseQueryFn, BaseQueryMeta, BaseQueryResult } from '../../baseQueryTypes';\nimport type { BaseEndpointDefinition } from '../../endpointDefinitions';\nimport { DefinitionType, isAnyQueryDefinition } from '../../endpointDefinitions';\nimport type { QueryCacheKey, RootState } from '../apiState';\nimport type { MutationResultSelectorResult, QueryResultSelectorResult } from '../buildSelectors';\nimport { getMutationCacheKey } from '../buildSlice';\nimport type { PatchCollection, Recipe } from '../buildThunks';\nimport { isAsyncThunkAction, isFulfilled } from '../rtkImports';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, PromiseWithKnownReason, SubMiddlewareApi } from './types';\nexport type ReferenceCacheLifecycle = never;\nexport interface QueryBaseLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends LifecycleApi<ReducerPath> {\n  /**\n   * Gets the current value of this cache entry.\n   */\n  getCacheEntry(): QueryResultSelectorResult<{\n    type: DefinitionType.query;\n  } & BaseEndpointDefinition<QueryArg, BaseQuery, ResultType, BaseQueryResult<BaseQuery>>>;\n  /**\n   * Updates the current cache entry value.\n   * For documentation see `api.util.updateQueryData`.\n   */\n  updateCachedData(updateRecipe: Recipe<ResultType>): PatchCollection;\n}\nexport type MutationBaseLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = LifecycleApi<ReducerPath> & {\n  /**\n   * Gets the current value of this cache entry.\n   */\n  getCacheEntry(): MutationResultSelectorResult<{\n    type: DefinitionType.mutation;\n  } & BaseEndpointDefinition<QueryArg, BaseQuery, ResultType, BaseQueryResult<BaseQuery>>>;\n};\ntype LifecycleApi<ReducerPath extends string = string> = {\n  /**\n   * The dispatch method for the store\n   */\n  dispatch: ThunkDispatch<any, any, UnknownAction>;\n  /**\n   * A method to get the current state\n   */\n  getState(): RootState<any, any, ReducerPath>;\n  /**\n   * `extra` as provided as `thunk.extraArgument` to the `configureStore` `getDefaultMiddleware` option.\n   */\n  extra: unknown;\n  /**\n   * A unique ID generated for the mutation\n   */\n  requestId: string;\n};\ntype CacheLifecyclePromises<ResultType = unknown, MetaType = unknown> = {\n  /**\n   * Promise that will resolve with the first value for this cache key.\n   * This allows you to `await` until an actual value is in cache.\n   *\n   * If the cache entry is removed from the cache before any value has ever\n   * been resolved, this Promise will reject with\n   * `new Error('Promise never resolved before cacheEntryRemoved.')`\n   * to prevent memory leaks.\n   * You can just re-throw that error (or not handle it at all) -\n   * it will be caught outside of `cacheEntryAdded`.\n   *\n   * If you don't interact with this promise, it will not throw.\n   */\n  cacheDataLoaded: PromiseWithKnownReason<{\n    /**\n     * The (transformed) query result.\n     */\n    data: ResultType;\n    /**\n     * The `meta` returned by the `baseQuery`\n     */\n    meta: MetaType;\n  }, typeof neverResolvedError>;\n  /**\n   * Promise that allows you to wait for the point in time when the cache entry\n   * has been removed from the cache, by not being used/subscribed to any more\n   * in the application for too long or by dispatching `api.util.resetApiState`.\n   */\n  cacheEntryRemoved: Promise<void>;\n};\nexport interface QueryCacheLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>> {}\nexport type MutationCacheLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> & CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>>;\nexport type CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n  onCacheEntryAdded?(arg: QueryArg, api: QueryCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nexport type CacheLifecycleInfiniteQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>;\nexport type CacheLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n  onCacheEntryAdded?(arg: QueryArg, api: MutationCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nconst neverResolvedError = new Error('Promise never resolved before cacheEntryRemoved.') as Error & {\n  message: 'Promise never resolved before cacheEntryRemoved.';\n};\nexport const buildCacheLifecycleHandler: InternalHandlerBuilder = ({\n  api,\n  reducerPath,\n  context,\n  queryThunk,\n  mutationThunk,\n  internalState,\n  selectors: {\n    selectQueryEntry,\n    selectApiState\n  }\n}) => {\n  const isQueryThunk = isAsyncThunkAction(queryThunk);\n  const isMutationThunk = isAsyncThunkAction(mutationThunk);\n  const isFulfilledThunk = isFulfilled(queryThunk, mutationThunk);\n  type CacheLifecycle = {\n    valueResolved?(value: {\n      data: unknown;\n      meta: unknown;\n    }): unknown;\n    cacheEntryRemoved(): void;\n  };\n  const lifecycleMap: Record<string, CacheLifecycle> = {};\n  function resolveLifecycleEntry(cacheKey: string, data: unknown, meta: unknown) {\n    const lifecycle = lifecycleMap[cacheKey];\n    if (lifecycle?.valueResolved) {\n      lifecycle.valueResolved({\n        data,\n        meta\n      });\n      delete lifecycle.valueResolved;\n    }\n  }\n  function removeLifecycleEntry(cacheKey: string) {\n    const lifecycle = lifecycleMap[cacheKey];\n    if (lifecycle) {\n      delete lifecycleMap[cacheKey];\n      lifecycle.cacheEntryRemoved();\n    }\n  }\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi, stateBefore) => {\n    const cacheKey = getCacheKey(action) as QueryCacheKey;\n    function checkForNewCacheKey(endpointName: string, cacheKey: QueryCacheKey, requestId: string, originalArgs: unknown) {\n      const oldEntry = selectQueryEntry(stateBefore, cacheKey);\n      const newEntry = selectQueryEntry(mwApi.getState(), cacheKey);\n      if (!oldEntry && newEntry) {\n        handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId);\n      }\n    }\n    if (queryThunk.pending.match(action)) {\n      checkForNewCacheKey(action.meta.arg.endpointName, cacheKey, action.meta.requestId, action.meta.arg.originalArgs);\n    } else if (api.internalActions.cacheEntriesUpserted.match(action)) {\n      for (const {\n        queryDescription,\n        value\n      } of action.payload) {\n        const {\n          endpointName,\n          originalArgs,\n          queryCacheKey\n        } = queryDescription;\n        checkForNewCacheKey(endpointName, queryCacheKey, action.meta.requestId, originalArgs);\n        resolveLifecycleEntry(queryCacheKey, value, {});\n      }\n    } else if (mutationThunk.pending.match(action)) {\n      const state = mwApi.getState()[reducerPath].mutations[cacheKey];\n      if (state) {\n        handleNewKey(action.meta.arg.endpointName, action.meta.arg.originalArgs, cacheKey, mwApi, action.meta.requestId);\n      }\n    } else if (isFulfilledThunk(action)) {\n      resolveLifecycleEntry(cacheKey, action.payload, action.meta.baseQueryMeta);\n    } else if (api.internalActions.removeQueryResult.match(action) || api.internalActions.removeMutationResult.match(action)) {\n      removeLifecycleEntry(cacheKey);\n    } else if (api.util.resetApiState.match(action)) {\n      for (const cacheKey of Object.keys(lifecycleMap)) {\n        removeLifecycleEntry(cacheKey);\n      }\n    }\n  };\n  function getCacheKey(action: any) {\n    if (isQueryThunk(action)) return action.meta.arg.queryCacheKey;\n    if (isMutationThunk(action)) {\n      return action.meta.arg.fixedCacheKey ?? action.meta.requestId;\n    }\n    if (api.internalActions.removeQueryResult.match(action)) return action.payload.queryCacheKey;\n    if (api.internalActions.removeMutationResult.match(action)) return getMutationCacheKey(action.payload);\n    return '';\n  }\n  function handleNewKey(endpointName: string, originalArgs: any, queryCacheKey: string, mwApi: SubMiddlewareApi, requestId: string) {\n    const endpointDefinition = context.endpointDefinitions[endpointName];\n    const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded;\n    if (!onCacheEntryAdded) return;\n    const lifecycle = {} as CacheLifecycle;\n    const cacheEntryRemoved = new Promise<void>(resolve => {\n      lifecycle.cacheEntryRemoved = resolve;\n    });\n    const cacheDataLoaded: PromiseWithKnownReason<{\n      data: unknown;\n      meta: unknown;\n    }, typeof neverResolvedError> = Promise.race([new Promise<{\n      data: unknown;\n      meta: unknown;\n    }>(resolve => {\n      lifecycle.valueResolved = resolve;\n    }), cacheEntryRemoved.then(() => {\n      throw neverResolvedError;\n    })]);\n    // prevent uncaught promise rejections from happening.\n    // if the original promise is used in any way, that will create a new promise that will throw again\n    cacheDataLoaded.catch(() => {});\n    lifecycleMap[queryCacheKey] = lifecycle;\n    const selector = (api.endpoints[endpointName] as any).select(isAnyQueryDefinition(endpointDefinition) ? originalArgs : queryCacheKey);\n    const extra = mwApi.dispatch((_, __, extra) => extra);\n    const lifecycleApi = {\n      ...mwApi,\n      getCacheEntry: () => selector(mwApi.getState()),\n      requestId,\n      extra,\n      updateCachedData: (isAnyQueryDefinition(endpointDefinition) ? (updateRecipe: Recipe<any>) => mwApi.dispatch(api.util.updateQueryData(endpointName as never, originalArgs as never, updateRecipe)) : undefined) as any,\n      cacheDataLoaded,\n      cacheEntryRemoved\n    };\n    const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi as any);\n    // if a `neverResolvedError` was thrown, but not handled in the running handler, do not let it leak out further\n    Promise.resolve(runningHandler).catch(e => {\n      if (e === neverResolvedError) return;\n      throw e;\n    });\n  }\n  return handler;\n};","import type { InternalHandlerBuilder } from './types';\nexport const buildDevCheckHandler: InternalHandlerBuilder = ({\n  api,\n  context: {\n    apiUid\n  },\n  reducerPath\n}) => {\n  return (action, mwApi) => {\n    if (api.util.resetApiState.match(action)) {\n      // dispatch after api reset\n      mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));\n    }\n    if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n      if (api.internalActions.middlewareRegistered.match(action) && action.payload === apiUid && mwApi.getState()[reducerPath]?.config?.middlewareRegistered === 'conflict') {\n        console.warn(`There is a mismatch between slice and middleware for the reducerPath \"${reducerPath}\".\nYou can only have one api per reducer path, this will lead to crashes in various situations!${reducerPath === 'api' ? `\nIf you have multiple apis, you *have* to specify the reducerPath option when using createApi!` : ''}`);\n      }\n    }\n  };\n};","import { isAnyOf, isFulfilled, isRejected, isRejectedWithValue } from '../rtkImports';\nimport type { EndpointDefinitions, FullTagDescription } from '../../endpointDefinitions';\nimport { calculateProvidedBy } from '../../endpointDefinitions';\nimport type { CombinedState, QueryCacheKey } from '../apiState';\nimport { QueryStatus } from '../apiState';\nimport { calculateProvidedByThunk } from '../buildThunks';\nimport type { SubMiddlewareApi, InternalHandlerBuilder, ApiMiddlewareInternalHandler, InternalMiddlewareState } from './types';\nimport { countObjectKeys } from '../../utils/countObjectKeys';\nexport const buildInvalidationByTagsHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  context,\n  context: {\n    endpointDefinitions\n  },\n  mutationThunk,\n  queryThunk,\n  api,\n  assertTagType,\n  refetchQuery,\n  internalState\n}) => {\n  const {\n    removeQueryResult\n  } = api.internalActions;\n  const isThunkActionWithTags = isAnyOf(isFulfilled(mutationThunk), isRejectedWithValue(mutationThunk));\n  const isQueryEnd = isAnyOf(isFulfilled(mutationThunk, queryThunk), isRejected(mutationThunk, queryThunk));\n  let pendingTagInvalidations: FullTagDescription<string>[] = [];\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (isThunkActionWithTags(action)) {\n      invalidateTags(calculateProvidedByThunk(action, 'invalidatesTags', endpointDefinitions, assertTagType), mwApi);\n    } else if (isQueryEnd(action)) {\n      invalidateTags([], mwApi);\n    } else if (api.util.invalidateTags.match(action)) {\n      invalidateTags(calculateProvidedBy(action.payload, undefined, undefined, undefined, undefined, assertTagType), mwApi);\n    }\n  };\n  function hasPendingRequests(state: CombinedState<EndpointDefinitions, string, string>) {\n    const {\n      queries,\n      mutations\n    } = state;\n    for (const cacheRecord of [queries, mutations]) {\n      for (const key in cacheRecord) {\n        if (cacheRecord[key]?.status === QueryStatus.pending) return true;\n      }\n    }\n    return false;\n  }\n  function invalidateTags(newTags: readonly FullTagDescription<string>[], mwApi: SubMiddlewareApi) {\n    const rootState = mwApi.getState();\n    const state = rootState[reducerPath];\n    pendingTagInvalidations.push(...newTags);\n    if (state.config.invalidationBehavior === 'delayed' && hasPendingRequests(state)) {\n      return;\n    }\n    const tags = pendingTagInvalidations;\n    pendingTagInvalidations = [];\n    if (tags.length === 0) return;\n    const toInvalidate = api.util.selectInvalidatedBy(rootState, tags);\n    context.batch(() => {\n      const valuesArray = Array.from(toInvalidate.values());\n      for (const {\n        queryCacheKey\n      } of valuesArray) {\n        const querySubState = state.queries[queryCacheKey];\n        const subscriptionSubState = internalState.currentSubscriptions[queryCacheKey] ?? {};\n        if (querySubState) {\n          if (countObjectKeys(subscriptionSubState) === 0) {\n            mwApi.dispatch(removeQueryResult({\n              queryCacheKey: queryCacheKey as QueryCacheKey\n            }));\n          } else if (querySubState.status !== QueryStatus.uninitialized) {\n            mwApi.dispatch(refetchQuery(querySubState));\n          }\n        }\n      }\n    });\n  }\n  return handler;\n};","import type { QueryCacheKey, QuerySubstateIdentifier, Subscribers } from '../apiState';\nimport { QueryStatus } from '../apiState';\nimport type { QueryStateMeta, SubMiddlewareApi, TimeoutId, InternalHandlerBuilder, ApiMiddlewareInternalHandler, InternalMiddlewareState } from './types';\nexport const buildPollingHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  queryThunk,\n  api,\n  refetchQuery,\n  internalState\n}) => {\n  const currentPolls: QueryStateMeta<{\n    nextPollTimestamp: number;\n    timeout?: TimeoutId;\n    pollingInterval: number;\n  }> = {};\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (api.internalActions.updateSubscriptionOptions.match(action) || api.internalActions.unsubscribeQueryResult.match(action)) {\n      updatePollingInterval(action.payload, mwApi);\n    }\n    if (queryThunk.pending.match(action) || queryThunk.rejected.match(action) && action.meta.condition) {\n      updatePollingInterval(action.meta.arg, mwApi);\n    }\n    if (queryThunk.fulfilled.match(action) || queryThunk.rejected.match(action) && !action.meta.condition) {\n      startNextPoll(action.meta.arg, mwApi);\n    }\n    if (api.util.resetApiState.match(action)) {\n      clearPolls();\n    }\n  };\n  function getCacheEntrySubscriptions(queryCacheKey: QueryCacheKey, api: SubMiddlewareApi) {\n    const state = api.getState()[reducerPath];\n    const querySubState = state.queries[queryCacheKey];\n    const subscriptions = internalState.currentSubscriptions[queryCacheKey];\n    if (!querySubState || querySubState.status === QueryStatus.uninitialized) return;\n    return subscriptions;\n  }\n  function startNextPoll({\n    queryCacheKey\n  }: QuerySubstateIdentifier, api: SubMiddlewareApi) {\n    const state = api.getState()[reducerPath];\n    const querySubState = state.queries[queryCacheKey];\n    const subscriptions = internalState.currentSubscriptions[queryCacheKey];\n    if (!querySubState || querySubState.status === QueryStatus.uninitialized) return;\n    const {\n      lowestPollingInterval,\n      skipPollingIfUnfocused\n    } = findLowestPollingInterval(subscriptions);\n    if (!Number.isFinite(lowestPollingInterval)) return;\n    const currentPoll = currentPolls[queryCacheKey];\n    if (currentPoll?.timeout) {\n      clearTimeout(currentPoll.timeout);\n      currentPoll.timeout = undefined;\n    }\n    const nextPollTimestamp = Date.now() + lowestPollingInterval;\n    currentPolls[queryCacheKey] = {\n      nextPollTimestamp,\n      pollingInterval: lowestPollingInterval,\n      timeout: setTimeout(() => {\n        if (state.config.focused || !skipPollingIfUnfocused) {\n          api.dispatch(refetchQuery(querySubState));\n        }\n        startNextPoll({\n          queryCacheKey\n        }, api);\n      }, lowestPollingInterval)\n    };\n  }\n  function updatePollingInterval({\n    queryCacheKey\n  }: QuerySubstateIdentifier, api: SubMiddlewareApi) {\n    const state = api.getState()[reducerPath];\n    const querySubState = state.queries[queryCacheKey];\n    const subscriptions = internalState.currentSubscriptions[queryCacheKey];\n    if (!querySubState || querySubState.status === QueryStatus.uninitialized) {\n      return;\n    }\n    const {\n      lowestPollingInterval\n    } = findLowestPollingInterval(subscriptions);\n    if (!Number.isFinite(lowestPollingInterval)) {\n      cleanupPollForKey(queryCacheKey);\n      return;\n    }\n    const currentPoll = currentPolls[queryCacheKey];\n    const nextPollTimestamp = Date.now() + lowestPollingInterval;\n    if (!currentPoll || nextPollTimestamp < currentPoll.nextPollTimestamp) {\n      startNextPoll({\n        queryCacheKey\n      }, api);\n    }\n  }\n  function cleanupPollForKey(key: string) {\n    const existingPoll = currentPolls[key];\n    if (existingPoll?.timeout) {\n      clearTimeout(existingPoll.timeout);\n    }\n    delete currentPolls[key];\n  }\n  function clearPolls() {\n    for (const key of Object.keys(currentPolls)) {\n      cleanupPollForKey(key);\n    }\n  }\n  function findLowestPollingInterval(subscribers: Subscribers = {}) {\n    let skipPollingIfUnfocused: boolean | undefined = false;\n    let lowestPollingInterval = Number.POSITIVE_INFINITY;\n    for (let key in subscribers) {\n      if (!!subscribers[key].pollingInterval) {\n        lowestPollingInterval = Math.min(subscribers[key].pollingInterval!, lowestPollingInterval);\n        skipPollingIfUnfocused = subscribers[key].skipPollingIfUnfocused || skipPollingIfUnfocused;\n      }\n    }\n    return {\n      lowestPollingInterval,\n      skipPollingIfUnfocused\n    };\n  }\n  return handler;\n};","import type { BaseQueryError, BaseQueryFn, BaseQueryMeta } from '../../baseQueryTypes';\nimport { DefinitionType, isAnyQueryDefinition } from '../../endpointDefinitions';\nimport type { Recipe } from '../buildThunks';\nimport { isFulfilled, isPending, isRejected } from '../rtkImports';\nimport type { MutationBaseLifecycleApi, QueryBaseLifecycleApi } from './cacheLifecycle';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, PromiseConstructorWithKnownReason, PromiseWithKnownReason } from './types';\nexport type ReferenceQueryLifecycle = never;\ntype QueryLifecyclePromises<ResultType, BaseQuery extends BaseQueryFn> = {\n  /**\n   * Promise that will resolve with the (transformed) query result.\n   *\n   * If the query fails, this promise will reject with the error.\n   *\n   * This allows you to `await` for the query to finish.\n   *\n   * If you don't interact with this promise, it will not throw.\n   */\n  queryFulfilled: PromiseWithKnownReason<{\n    /**\n     * The (transformed) query result.\n     */\n    data: ResultType;\n    /**\n     * The `meta` returned by the `baseQuery`\n     */\n    meta: BaseQueryMeta<BaseQuery>;\n  }, QueryFulfilledRejectionReason<BaseQuery>>;\n};\ntype QueryFulfilledRejectionReason<BaseQuery extends BaseQueryFn> = {\n  error: BaseQueryError<BaseQuery>;\n  /**\n   * If this is `false`, that means this error was returned from the `baseQuery` or `queryFn` in a controlled manner.\n   */\n  isUnhandledError: false;\n  /**\n   * The `meta` returned by the `baseQuery`\n   */\n  meta: BaseQueryMeta<BaseQuery>;\n} | {\n  error: unknown;\n  meta?: undefined;\n  /**\n   * 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.\n   * There can not be made any assumption about the shape of `error`.\n   */\n  isUnhandledError: true;\n};\nexport type QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n  /**\n   * 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).\n   *\n   * Can be used to perform side-effects throughout the lifecycle of the query.\n   *\n   * @example\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   * import { messageCreated } from './notificationsSlice\n   * export interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({\n   *     baseUrl: '/',\n   *   }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, number>({\n   *       query: (id) => `post/${id}`,\n   *       async onQueryStarted(id, { dispatch, queryFulfilled }) {\n   *         // `onStart` side-effect\n   *         dispatch(messageCreated('Fetching posts...'))\n   *         try {\n   *           const { data } = await queryFulfilled\n   *           // `onSuccess` side-effect\n   *           dispatch(messageCreated('Posts received!'))\n   *         } catch (err) {\n   *           // `onError` side-effect\n   *           dispatch(messageCreated('Error fetching posts!'))\n   *         }\n   *       }\n   *     }),\n   *   }),\n   * })\n   * ```\n   */\n  onQueryStarted?(queryArgument: QueryArg, queryLifeCycleApi: QueryLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nexport type QueryLifecycleInfiniteQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>;\nexport type QueryLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n  /**\n   * 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).\n   *\n   * Can be used for `optimistic updates`.\n   *\n   * @example\n   *\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   * export interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({\n   *     baseUrl: '/',\n   *   }),\n   *   tagTypes: ['Post'],\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, number>({\n   *       query: (id) => `post/${id}`,\n   *       providesTags: ['Post'],\n   *     }),\n   *     updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({\n   *       query: ({ id, ...patch }) => ({\n   *         url: `post/${id}`,\n   *         method: 'PATCH',\n   *         body: patch,\n   *       }),\n   *       invalidatesTags: ['Post'],\n   *       async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {\n   *         const patchResult = dispatch(\n   *           api.util.updateQueryData('getPost', id, (draft) => {\n   *             Object.assign(draft, patch)\n   *           })\n   *         )\n   *         try {\n   *           await queryFulfilled\n   *         } catch {\n   *           patchResult.undo()\n   *         }\n   *       },\n   *     }),\n   *   }),\n   * })\n   * ```\n   */\n  onQueryStarted?(queryArgument: QueryArg, mutationLifeCycleApi: MutationLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nexport interface QueryLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, QueryLifecyclePromises<ResultType, BaseQuery> {}\nexport type MutationLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> & QueryLifecyclePromises<ResultType, BaseQuery>;\n\n/**\n * Provides a way to define a strongly-typed version of\n * {@linkcode QueryLifecycleQueryExtraOptions.onQueryStarted | onQueryStarted}\n * for a specific query.\n *\n * @example\n * <caption>#### __Create and reuse a strongly-typed `onQueryStarted` function__</caption>\n *\n * ```ts\n * import type { TypedQueryOnQueryStarted } from '@reduxjs/toolkit/query'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n *\n * type Post = {\n *   id: number\n *   title: string\n *   userId: number\n * }\n *\n * type PostsApiResponse = {\n *   posts: Post[]\n *   total: number\n *   skip: number\n *   limit: number\n * }\n *\n * type QueryArgument = number | undefined\n *\n * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>\n *\n * const baseApiSlice = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),\n *   reducerPath: 'postsApi',\n *   tagTypes: ['Posts'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsApiResponse, void>({\n *       query: () => `/posts`,\n *     }),\n *\n *     getPostById: build.query<Post, QueryArgument>({\n *       query: (postId) => `/posts/${postId}`,\n *     }),\n *   }),\n * })\n *\n * const updatePostOnFulfilled: TypedQueryOnQueryStarted<\n *   PostsApiResponse,\n *   QueryArgument,\n *   BaseQueryFunction,\n *   'postsApi'\n * > = async (queryArgument, { dispatch, queryFulfilled }) => {\n *   const result = await queryFulfilled\n *\n *   const { posts } = result.data\n *\n *   // Pre-fill the individual post entries with the results\n *   // from the list endpoint query\n *   dispatch(\n *     baseApiSlice.util.upsertQueryEntries(\n *       posts.map((post) => ({\n *         endpointName: 'getPostById',\n *         arg: post.id,\n *         value: post,\n *       })),\n *     ),\n *   )\n * }\n *\n * export const extendedApiSlice = baseApiSlice.injectEndpoints({\n *   endpoints: (build) => ({\n *     getPostsByUserId: build.query<PostsApiResponse, QueryArgument>({\n *       query: (userId) => `/posts/user/${userId}`,\n *\n *       onQueryStarted: updatePostOnFulfilled,\n *     }),\n *   }),\n * })\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArgumentType - The type of the argument passed into the query.\n * @template BaseQueryFunctionType - The type of the base query function being used.\n * @template ReducerPath - The type representing the `reducerPath` for the API slice.\n *\n * @since 2.4.0\n * @public\n */\nexport type TypedQueryOnQueryStarted<ResultType, QueryArgumentType, BaseQueryFunctionType extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleQueryExtraOptions<ResultType, QueryArgumentType, BaseQueryFunctionType, ReducerPath>['onQueryStarted'];\n\n/**\n * Provides a way to define a strongly-typed version of\n * {@linkcode QueryLifecycleMutationExtraOptions.onQueryStarted | onQueryStarted}\n * for a specific mutation.\n *\n * @example\n * <caption>#### __Create and reuse a strongly-typed `onQueryStarted` function__</caption>\n *\n * ```ts\n * import type { TypedMutationOnQueryStarted } from '@reduxjs/toolkit/query'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n *\n * type Post = {\n *   id: number\n *   title: string\n *   userId: number\n * }\n *\n * type PostsApiResponse = {\n *   posts: Post[]\n *   total: number\n *   skip: number\n *   limit: number\n * }\n *\n * type QueryArgument = Pick<Post, 'id'> & Partial<Post>\n *\n * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>\n *\n * const baseApiSlice = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),\n *   reducerPath: 'postsApi',\n *   tagTypes: ['Posts'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsApiResponse, void>({\n *       query: () => `/posts`,\n *     }),\n *\n *     getPostById: build.query<Post, number>({\n *       query: (postId) => `/posts/${postId}`,\n *     }),\n *   }),\n * })\n *\n * const updatePostOnFulfilled: TypedMutationOnQueryStarted<\n *   Post,\n *   QueryArgument,\n *   BaseQueryFunction,\n *   'postsApi'\n * > = async ({ id, ...patch }, { dispatch, queryFulfilled }) => {\n *   const patchCollection = dispatch(\n *     baseApiSlice.util.updateQueryData('getPostById', id, (draftPost) => {\n *       Object.assign(draftPost, patch)\n *     }),\n *   )\n *\n *   try {\n *     await queryFulfilled\n *   } catch {\n *     patchCollection.undo()\n *   }\n * }\n *\n * export const extendedApiSlice = baseApiSlice.injectEndpoints({\n *   endpoints: (build) => ({\n *     addPost: build.mutation<Post, Omit<QueryArgument, 'id'>>({\n *       query: (body) => ({\n *         url: `posts/add`,\n *         method: 'POST',\n *         body,\n *       }),\n *\n *       onQueryStarted: updatePostOnFulfilled,\n *     }),\n *\n *     updatePost: build.mutation<Post, QueryArgument>({\n *       query: ({ id, ...patch }) => ({\n *         url: `post/${id}`,\n *         method: 'PATCH',\n *         body: patch,\n *       }),\n *\n *       onQueryStarted: updatePostOnFulfilled,\n *     }),\n *   }),\n * })\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArgumentType - The type of the argument passed into the query.\n * @template BaseQueryFunctionType - The type of the base query function being used.\n * @template ReducerPath - The type representing the `reducerPath` for the API slice.\n *\n * @since 2.4.0\n * @public\n */\nexport type TypedMutationOnQueryStarted<ResultType, QueryArgumentType, BaseQueryFunctionType extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleMutationExtraOptions<ResultType, QueryArgumentType, BaseQueryFunctionType, ReducerPath>['onQueryStarted'];\nexport const buildQueryLifecycleHandler: InternalHandlerBuilder = ({\n  api,\n  context,\n  queryThunk,\n  mutationThunk\n}) => {\n  const isPendingThunk = isPending(queryThunk, mutationThunk);\n  const isRejectedThunk = isRejected(queryThunk, mutationThunk);\n  const isFullfilledThunk = isFulfilled(queryThunk, mutationThunk);\n  type CacheLifecycle = {\n    resolve(value: {\n      data: unknown;\n      meta: unknown;\n    }): unknown;\n    reject(value: QueryFulfilledRejectionReason<any>): unknown;\n  };\n  const lifecycleMap: Record<string, CacheLifecycle> = {};\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (isPendingThunk(action)) {\n      const {\n        requestId,\n        arg: {\n          endpointName,\n          originalArgs\n        }\n      } = action.meta;\n      const endpointDefinition = context.endpointDefinitions[endpointName];\n      const onQueryStarted = endpointDefinition?.onQueryStarted;\n      if (onQueryStarted) {\n        const lifecycle = {} as CacheLifecycle;\n        const queryFulfilled = new (Promise as PromiseConstructorWithKnownReason)<{\n          data: unknown;\n          meta: unknown;\n        }, QueryFulfilledRejectionReason<any>>((resolve, reject) => {\n          lifecycle.resolve = resolve;\n          lifecycle.reject = reject;\n        });\n        // prevent uncaught promise rejections from happening.\n        // if the original promise is used in any way, that will create a new promise that will throw again\n        queryFulfilled.catch(() => {});\n        lifecycleMap[requestId] = lifecycle;\n        const selector = (api.endpoints[endpointName] as any).select(isAnyQueryDefinition(endpointDefinition) ? originalArgs : requestId);\n        const extra = mwApi.dispatch((_, __, extra) => extra);\n        const lifecycleApi = {\n          ...mwApi,\n          getCacheEntry: () => selector(mwApi.getState()),\n          requestId,\n          extra,\n          updateCachedData: (isAnyQueryDefinition(endpointDefinition) ? (updateRecipe: Recipe<any>) => mwApi.dispatch(api.util.updateQueryData(endpointName as never, originalArgs as never, updateRecipe)) : undefined) as any,\n          queryFulfilled\n        };\n        onQueryStarted(originalArgs, lifecycleApi as any);\n      }\n    } else if (isFullfilledThunk(action)) {\n      const {\n        requestId,\n        baseQueryMeta\n      } = action.meta;\n      lifecycleMap[requestId]?.resolve({\n        data: action.payload,\n        meta: baseQueryMeta\n      });\n      delete lifecycleMap[requestId];\n    } else if (isRejectedThunk(action)) {\n      const {\n        requestId,\n        rejectedWithValue,\n        baseQueryMeta\n      } = action.meta;\n      lifecycleMap[requestId]?.reject({\n        error: action.payload ?? action.error,\n        isUnhandledError: !rejectedWithValue,\n        meta: baseQueryMeta as any\n      });\n      delete lifecycleMap[requestId];\n    }\n  };\n  return handler;\n};","import { QueryStatus } from '../apiState';\nimport type { QueryCacheKey } from '../apiState';\nimport { onFocus, onOnline } from '../setupListeners';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, SubMiddlewareApi } from './types';\nimport { countObjectKeys } from '../../utils/countObjectKeys';\nexport const buildWindowEventHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  context,\n  api,\n  refetchQuery,\n  internalState\n}) => {\n  const {\n    removeQueryResult\n  } = api.internalActions;\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (onFocus.match(action)) {\n      refetchValidQueries(mwApi, 'refetchOnFocus');\n    }\n    if (onOnline.match(action)) {\n      refetchValidQueries(mwApi, 'refetchOnReconnect');\n    }\n  };\n  function refetchValidQueries(api: SubMiddlewareApi, type: 'refetchOnFocus' | 'refetchOnReconnect') {\n    const state = api.getState()[reducerPath];\n    const queries = state.queries;\n    const subscriptions = internalState.currentSubscriptions;\n    context.batch(() => {\n      for (const queryCacheKey of Object.keys(subscriptions)) {\n        const querySubState = queries[queryCacheKey];\n        const subscriptionSubState = subscriptions[queryCacheKey];\n        if (!subscriptionSubState || !querySubState) continue;\n        const shouldRefetch = Object.values(subscriptionSubState).some(sub => sub[type] === true) || Object.values(subscriptionSubState).every(sub => sub[type] === undefined) && state.config[type];\n        if (shouldRefetch) {\n          if (countObjectKeys(subscriptionSubState) === 0) {\n            api.dispatch(removeQueryResult({\n              queryCacheKey: queryCacheKey as QueryCacheKey\n            }));\n          } else if (querySubState.status !== QueryStatus.uninitialized) {\n            api.dispatch(refetchQuery(querySubState));\n          }\n        }\n      }\n    });\n  }\n  return handler;\n};","import type { Action, Middleware, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport type { EndpointDefinitions, FullTagDescription } from '../../endpointDefinitions';\nimport type { QueryStatus, QuerySubState, RootState } from '../apiState';\nimport type { QueryThunkArg } from '../buildThunks';\nimport { createAction, isAction } from '../rtkImports';\nimport { buildBatchedActionsHandler } from './batchActions';\nimport { buildCacheCollectionHandler } from './cacheCollection';\nimport { buildCacheLifecycleHandler } from './cacheLifecycle';\nimport { buildDevCheckHandler } from './devMiddleware';\nimport { buildInvalidationByTagsHandler } from './invalidationByTags';\nimport { buildPollingHandler } from './polling';\nimport { buildQueryLifecycleHandler } from './queryLifecycle';\nimport type { BuildMiddlewareInput, InternalHandlerBuilder, InternalMiddlewareState } from './types';\nimport { buildWindowEventHandler } from './windowEventHandling';\nimport type { ApiEndpointQuery } from '../module';\nexport type { ReferenceCacheCollection } from './cacheCollection';\nexport type { MutationCacheLifecycleApi, QueryCacheLifecycleApi, ReferenceCacheLifecycle } from './cacheLifecycle';\nexport type { MutationLifecycleApi, QueryLifecycleApi, ReferenceQueryLifecycle, TypedMutationOnQueryStarted, TypedQueryOnQueryStarted } from './queryLifecycle';\nexport type { SubscriptionSelectors } from './types';\nexport function buildMiddleware<Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string>(input: BuildMiddlewareInput<Definitions, ReducerPath, TagTypes>) {\n  const {\n    reducerPath,\n    queryThunk,\n    api,\n    context\n  } = input;\n  const {\n    apiUid\n  } = context;\n  const actions = {\n    invalidateTags: createAction<Array<TagTypes | FullTagDescription<TagTypes> | null | undefined>>(`${reducerPath}/invalidateTags`)\n  };\n  const isThisApiSliceAction = (action: Action) => action.type.startsWith(`${reducerPath}/`);\n  const handlerBuilders: InternalHandlerBuilder[] = [buildDevCheckHandler, buildCacheCollectionHandler, buildInvalidationByTagsHandler, buildPollingHandler, buildCacheLifecycleHandler, buildQueryLifecycleHandler];\n  const middleware: Middleware<{}, RootState<Definitions, string, ReducerPath>, ThunkDispatch<any, any, UnknownAction>> = mwApi => {\n    let initialized = false;\n    const internalState: InternalMiddlewareState = {\n      currentSubscriptions: {}\n    };\n    const builderArgs = {\n      ...(input as any as BuildMiddlewareInput<EndpointDefinitions, string, string>),\n      internalState,\n      refetchQuery,\n      isThisApiSliceAction\n    };\n    const handlers = handlerBuilders.map(build => build(builderArgs));\n    const batchedActionsHandler = buildBatchedActionsHandler(builderArgs);\n    const windowEventsHandler = buildWindowEventHandler(builderArgs);\n    return next => {\n      return action => {\n        if (!isAction(action)) {\n          return next(action);\n        }\n        if (!initialized) {\n          initialized = true;\n          // dispatch before any other action\n          mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));\n        }\n        const mwApiWithNext = {\n          ...mwApi,\n          next\n        };\n        const stateBefore = mwApi.getState();\n        const [actionShouldContinue, internalProbeResult] = batchedActionsHandler(action, mwApiWithNext, stateBefore);\n        let res: any;\n        if (actionShouldContinue) {\n          res = next(action);\n        } else {\n          res = internalProbeResult;\n        }\n        if (!!mwApi.getState()[reducerPath]) {\n          // Only run these checks if the middleware is registered okay\n\n          // This looks for actions that aren't specific to the API slice\n          windowEventsHandler(action, mwApiWithNext, stateBefore);\n          if (isThisApiSliceAction(action) || context.hasRehydrationInfo(action)) {\n            // Only run these additional checks if the actions are part of the API slice,\n            // or the action has hydration-related data\n            for (const handler of handlers) {\n              handler(action, mwApiWithNext, stateBefore);\n            }\n          }\n        }\n        return res;\n      };\n    };\n  };\n  return {\n    middleware,\n    actions\n  };\n  function refetchQuery(querySubState: Exclude<QuerySubState<any>, {\n    status: QueryStatus.uninitialized;\n  }>) {\n    return (input.api.endpoints[querySubState.endpointName] as ApiEndpointQuery<any, any>).initiate(querySubState.originalArgs as any, {\n      subscribe: false,\n      forceRefetch: true\n    });\n  }\n}","import { buildCreateApi } from '../createApi';\nimport { coreModule } from './module';\nexport const createApi = /* @__PURE__ */buildCreateApi(coreModule());\nexport { QueryStatus } from './apiState';\nexport type { CombinedState, InfiniteData, InfiniteQueryConfigOptions, InfiniteQuerySubState, MutationKeys, QueryCacheKey, QueryKeys, QuerySubState, RootState, SubscriptionOptions } from './apiState';\nexport type { InfiniteQueryActionCreatorResult, MutationActionCreatorResult, QueryActionCreatorResult, StartQueryActionCreatorOptions } from './buildInitiate';\nexport type { MutationCacheLifecycleApi, MutationLifecycleApi, QueryCacheLifecycleApi, QueryLifecycleApi, SubscriptionSelectors, TypedMutationOnQueryStarted, TypedQueryOnQueryStarted } from './buildMiddleware/index';\nexport { skipToken } from './buildSelectors';\nexport type { InfiniteQueryResultSelectorResult, MutationResultSelectorResult, QueryResultSelectorResult, SkipToken } from './buildSelectors';\nexport type { SliceActions } from './buildSlice';\nexport type { PatchQueryDataThunk, UpdateQueryDataThunk, UpsertQueryDataThunk } from './buildThunks';\nexport { coreModuleName } from './module';\nexport type { ApiEndpointInfiniteQuery, ApiEndpointMutation, ApiEndpointQuery, CoreModule, InternalActions, PrefetchOptions, ThunkWithReturnValue } from './module';\nexport { setupListeners } from './setupListeners';\nexport { buildCreateApi, coreModule };"],"mappings":"2eAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,sBAAAE,GAAA,gBAAAC,GAAA,WAAAC,GAAA,mBAAAC,GAAA,8BAAAC,GAAA,eAAAC,GAAA,mBAAAC,GAAA,cAAAC,GAAA,8BAAAC,GAAA,kBAAAC,GAAA,mBAAAC,GAAA,UAAAC,GAAA,mBAAAC,GAAA,cAAAC,KAAA,eAAAC,GAAAhB,ICoDO,IAAKiB,QACVA,EAAA,cAAgB,gBAChBA,EAAA,QAAU,UACVA,EAAA,UAAY,YACZA,EAAA,SAAW,WAJDA,QAAA,IA+BL,SAASC,GAAsBC,EAAyC,CAC7E,MAAO,CACL,OAAAA,EACA,gBAAiBA,IAAW,gBAC5B,UAAWA,IAAW,UACtB,UAAWA,IAAW,YACtB,QAASA,IAAW,UACtB,CACF,CC3FA,IAAAC,EAAA,GAAAC,GAAAD,EAAA,iBAAAE,GAAA,qBAAAC,GAAA,mBAAAC,GAAA,UAAAC,GAAA,gBAAAC,GAAA,sBAAAC,GAAA,sBAAAC,GAAA,qBAAAC,GAAA,sBAAAC,GAAA,kBAAAC,GAAA,mBAAAC,GAAA,iBAAAC,EAAA,2CAAAC,GAAA,qBAAAC,GAAA,4BAAAC,GAAA,mCAAAC,GAAA,4BAAAC,GAAA,wBAAAC,GAAA,4CAAAC,GAAA,6BAAAC,GAAA,gDAAAC,GAAA,uIAAAC,GAAA,gBAAAC,GAAA,mDAAAC,GAAA,2BAAAC,EAAA,wCAAAC,GAAA,YAAAC,GAAA,YAAAC,EAAA,uBAAAC,GAAA,+CAAAC,GAAA,gBAAAC,EAAA,uBAAAC,GAAA,cAAAC,GAAA,YAAAC,GAAA,eAAAC,GAAA,wBAAAC,GAAA,oDAAAC,GAAA,WAAAC,GAAA,+CAAAC,GAAA,mBAAAC,GAAA,iBAAAC,GAAA,u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EACD,OAAAc,GAAW3B,EAAI,KAAM,CACnB,wBAAA8C,EACA,yBAAAC,GACA,qBAAAE,EACA,uBAAAD,CACF,CAAC,EACM,CACL,KAAMnD,GACN,eAAesD,EAAcC,EAAY,CACvC,IAAMC,EAASrD,EACTsD,EAAWD,EAAO,UAAUF,CAAY,IAAM,CAAC,EACjDI,GAAkBH,CAAU,GAC9BzB,GAAW2B,EAAU,CACnB,KAAMH,EACN,OAAQ3B,EAAmB2B,EAAcC,CAAU,EACnD,SAAUT,EAAmBQ,EAAcC,CAAU,CACvD,EAAGjB,EAAuBP,EAAYuB,CAAY,CAAC,EAEjDK,GAAqBJ,CAAU,GACjCzB,GAAW2B,EAAU,CACnB,KAAMH,EACN,OAAQzB,EAAsB,EAC9B,SAAUmB,EAAsBM,CAAY,CAC9C,EAAGhB,EAAuBL,EAAeqB,CAAY,CAAC,EAEpDM,GAA0BL,CAAU,GACtCzB,GAAW2B,EAAU,CACnB,KAAMH,EACN,OAAQ1B,EAA2B0B,EAAcC,CAAU,EAC3D,SAAUR,EAA2BO,EAAcC,CAAU,CAC/D,EAAGjB,EAAuBP,EAAYuB,CAAY,CAAC,CAEvD,CACF,CACF,CACF,GWnhBO,IAAMO,GAA2BC,GAAeC,GAAW,CAAC","names":["query_exports","__export","NamedSchemaError","QueryStatus","_NEVER","buildCreateApi","copyWithStructuralSharing","coreModule","coreModuleName","createApi","defaultSerializeQueryArgs","fakeBaseQuery","fetchBaseQuery","retry","setupListeners","skipToken","__toCommonJS","QueryStatus","getRequestStatusFlags","status","src_exports","__export","ReducerType","SHOULD_AUTOBATCH","TaskAbortError","Tuple","addListener","asyncThunkCreator","autoBatchEnhancer","buildCreateSlice","clearAllListeners","combineSlices","configureStore","createAction","createActionCreatorInvariantMiddleware","createAsyncThunk","createDraftSafeSelector","createDraftSafeSelectorCreator","createDynamicMiddleware","createEntityAdapter","createImmutableStateInvariantMiddleware","createListenerMiddleware","createReducer","createSerializableStateInvariantMiddleware","createSlice","findNonSerializableValue","formatProdErrorMessage","isActionCreator","isAllOf","isAnyOf","isAsyncThunkAction","isFSA","isFulfilled","isImmutableDefault","isPending","isPlain","isRejected","isRejectedWithValue","miniSerializeError","nanoid","prepareAutoBatched","removeListener","unwrapResult","__reExport","import_immer","import_reselect","import_immer","import_reselect","createDraftSafeSelectorCreator","args","createSelector","createDraftSafeSelector","selector","wrappedSelector","value","rest","import_redux","import_redux","composeWithDevTools","devToolsEnhancer","noop","import_redux_thunk","import_redux","hasMatchFunction","v","asSafePromise","promise","fallback","createAction","type","prepareAction","actionCreator","args","prepared","formatProdErrorMessage","action","isActionCreator","hasMatchFunction","isFSA","isValidKey","key","getMessage","type","splitType","actionName","createActionCreatorInvariantMiddleware","options","next","action","import_immer","Tuple","_Tuple","items","arr","freezeDraftable","val","createNextState","getOrInsertComputed","map","key","compute","isImmutableDefault","value","createImmutableStateInvariantMiddleware","options","next","action","stringify","getSerialize","import_redux","isPlain","val","type","findNonSerializableValue","value","path","isSerializable","getEntries","ignoredPaths","cache","foundNestedSerializable","entries","hasIgnoredPaths","key","nestedValue","nestedPath","ignored","isNestedFrozen","createSerializableStateInvariantMiddleware","options","next","action","isBoolean","x","buildGetDefaultMiddleware","options","thunk","immutableCheck","serializableCheck","actionCreatorCheck","middlewareArray","Tuple","thunkMiddleware","SHOULD_AUTOBATCH","prepareAutoBatched","payload","createQueueWithTimer","timeout","notify","autoBatchEnhancer","options","next","args","store","notifying","shouldNotifyAtEndOfTick","notificationQueued","listeners","queueCallback","notifyListeners","l","listener","wrappedListener","unsubscribe","action","buildGetDefaultEnhancers","middlewareEnhancer","options","autoBatch","enhancerArray","Tuple","autoBatchEnhancer","configureStore","options","getDefaultMiddleware","buildGetDefaultMiddleware","reducer","middleware","devTools","duplicateMiddlewareCheck","preloadedState","enhancers","rootReducer","formatProdErrorMessage","finalMiddleware","finalCompose","composeWithDevTools","middlewareEnhancer","getDefaultEnhancers","buildGetDefaultEnhancers","storeEnhancers","composedEnhancer","import_immer","executeReducerBuilderCallback","builderCallback","actionsMap","actionMatchers","defaultCaseReducer","builder","typeOrActionCreator","reducer","type","formatProdErrorMessage","matcher","isStateFunction","x","createReducer","initialState","mapOrBuilderCallback","actionsMap","finalActionMatchers","finalDefaultCaseReducer","executeReducerBuilderCallback","getInitialState","freezeDraftable","frozenInitialState","reducer","state","action","caseReducers","matcher","cr","previousState","caseReducer","result","createNextState","draft","matches","matcher","action","hasMatchFunction","isAnyOf","matchers","isAllOf","hasExpectedRequestMetadata","validStatus","hasValidRequestId","hasValidRequestStatus","isAsyncThunkArray","a","isPending","asyncThunks","asyncThunk","isRejected","isRejectedWithValue","hasFlag","isFulfilled","isAsyncThunkAction","urlAlphabet","nanoid","size","id","i","commonProperties","RejectWithValue","payload","meta","FulfillWithMeta","miniSerializeError","value","simpleError","property","externalAbortMessage","createAsyncThunk","typePrefix","payloadCreator","options","fulfilled","createAction","requestId","arg","pending","rejected","error","actionCreator","signal","dispatch","getState","extra","nanoid","abortController","abortHandler","abortReason","abort","reason","promise","finalAction","conditionResult","isThenable","abortedPromise","_","reject","result","err","unwrapResult","isAnyOf","action","asyncThunkSymbol","asyncThunkCreator","createAsyncThunk","ReducerType","getType","slice","actionKey","buildCreateSlice","creators","cAT","options","name","reducerPath","formatProdErrorMessage","reducers","buildReducerCreators","reducerNames","context","contextMethods","typeOrActionCreator","reducer","type","matcher","actionCreator","reducerName","reducerDefinition","reducerDetails","isAsyncThunkSliceReducerDefinition","handleThunkCaseReducerDefinition","handleNormalReducerDefinition","buildReducer","extraReducers","actionMatchers","defaultCaseReducer","executeReducerBuilderCallback","finalCaseReducers","createReducer","builder","key","sM","m","selectSelf","state","injectedSelectorCache","injectedStateCache","_reducer","action","getInitialState","makeSelectorProps","injected","selectSlice","sliceState","getOrInsertComputed","getSelectors","selectState","selectorCache","map","selector","wrapSelector","injectable","pathOpt","config","newReducerPath","wrapper","rootState","args","createSlice","asyncThunk","payloadCreator","caseReducer","prepare","createNotation","maybeReducerWithPrepare","prepareCallback","isCaseReducerWithPrepareDefinition","createAction","fulfilled","pending","rejected","settled","thunk","noop","getInitialEntityState","createInitialStateFactory","stateAdapter","getInitialState","additionalState","entities","state","createSelectorsFactory","getSelectors","selectState","options","createSelector","createDraftSafeSelector","selectIds","state","selectEntities","selectAll","ids","entities","id","selectId","_","selectById","selectTotal","selectGlobalizedEntities","import_immer","isDraftTyped","createSingleArgumentStateOperator","mutator","operator","createStateOperator","_","state","arg","isPayloadActionArgument","isFSA","runMutator","draft","createNextState","import_immer","selectIdValue","entity","selectId","ensureEntitiesArray","entities","getCurrent","value","splitAddedUpdatedEntities","newEntities","state","existingIdsArray","existingIds","added","addedIds","updated","id","createUnsortedStateAdapter","selectId","addOneMutably","entity","state","key","selectIdValue","addManyMutably","newEntities","ensureEntitiesArray","setOneMutably","setManyMutably","setAllMutably","removeOneMutably","removeManyMutably","keys","didMutate","id","removeAllMutably","takeNewKey","update","original","updated","newKey","hasNewKey","updateOneMutably","updateManyMutably","updates","newKeys","updatesPerEntity","e","upsertOneMutably","upsertManyMutably","added","splitAddedUpdatedEntities","createSingleArgumentStateOperator","createStateOperator","findInsertIndex","sortedItems","item","comparisonFunction","lowIndex","highIndex","middleIndex","currentItem","insert","insertAtIndex","createSortedStateAdapter","selectId","comparer","removeOne","removeMany","removeAll","createUnsortedStateAdapter","addOneMutably","entity","state","addManyMutably","newEntities","existingIds","ensureEntitiesArray","existingKeys","getCurrent","models","model","selectIdValue","mergeFunction","setOneMutably","setManyMutably","setAllMutably","updateOneMutably","update","updateManyMutably","updates","appliedUpdates","replacedIds","newId","oldIndex","upsertOneMutably","upsertManyMutably","added","updated","existingIdsArray","splitAddedUpdatedEntities","areArraysEqual","a","b","i","addedItems","currentEntities","currentIds","stateEntities","ids","sortedEntities","id","wasPreviouslyEmpty","newSortedIds","createStateOperator","createEntityAdapter","options","selectId","sortComparer","instance","stateAdapter","createSortedStateAdapter","createUnsortedStateAdapter","stateFactory","createInitialStateFactory","selectorsFactory","createSelectorsFactory","import_redux","task","listener","completed","cancelled","taskCancelled","taskCompleted","listenerCancelled","listenerCompleted","TaskAbortError","code","assertFunction","func","expected","formatProdErrorMessage","noop","catchRejection","promise","onError","addAbortSignalListener","abortSignal","callback","abortControllerWithReason","abortController","reason","signal","validateActive","signal","reason","TaskAbortError","raceWithSignal","promise","cleanup","noop","resolve","reject","notifyRejection","addAbortSignalListener","runTask","task","cleanUp","error","createPause","catchRejection","output","createDelay","pause","timeoutMs","assign","INTERNAL_NIL_TOKEN","alm","createFork","parentAbortSignal","parentBlockingPromises","linkControllers","controller","addAbortSignalListener","abortControllerWithReason","taskExecutor","opts","assertFunction","childAbortController","result","runTask","validateActive","createPause","createDelay","taskCompleted","noop","taskCancelled","createTakePattern","startListening","signal","take","predicate","timeout","unsubscribe","promises","resolve","reject","stopListening","action","listenerApi","output","raceWithSignal","catchRejection","getListenerEntryPropsFrom","options","type","actionCreator","matcher","effect","createAction","formatProdErrorMessage","createListenerEntry","nanoid","findListenerEntry","listenerMap","entry","cancelActiveListeners","listenerCancelled","createClearListenerMiddleware","safelyNotifyError","errorHandler","errorToNotify","errorInfo","errorHandlerError","addListener","clearAllListeners","removeListener","defaultErrorHandler","args","createListenerMiddleware","middlewareOptions","extra","onError","insertEntry","cancelOptions","notifyListener","api","getOriginalState","internalTaskController","autoJoinPromises","_","set","listenerError","TaskAbortError","listenerCompleted","clearListenerMiddleware","next","originalState","currentState","listenerEntries","runListener","predicateError","import_redux","createMiddlewareEntry","middleware","matchInstance","instanceId","action","createDynamicMiddleware","nanoid","middlewareMap","withMiddleware","createAction","middlewares","addMiddleware","getOrInsertComputed","getFinalMiddleware","api","appliedMiddleware","entry","isWithMiddleware","isAllOf","next","import_redux","isSliceLike","maybeSliceLike","getReducers","slices","sliceOrMap","ORIGINAL_STATE","isStateProxy","value","stateProxyMap","createStateProxy","state","reducerMap","initialStateCache","getOrInsertComputed","target","prop","receiver","result","cached","reducer","reducerResult","nanoid","formatProdErrorMessage","original","emptyObject","noopReducer","combineSlices","getReducer","combinedReducer","action","inject","slice","config","reducerPath","reducerToInject","currentReducer","selector","selectorFn","selectState","args","formatProdErrorMessage","code","isPlainObject","copyWithStructuralSharing","oldObj","newObj","newKeys","oldKeys","isSameObject","mergeObj","key","countObjectKeys","obj","count","_key","flatten","arr","isAbsoluteUrl","url","isDocumentVisible","isNotNullish","v","isOnline","withoutTrailingSlash","url","withoutLeadingSlash","joinUrls","base","isAbsoluteUrl","delimiter","getOrInsert","map","key","value","defaultFetchFn","args","defaultValidateStatus","response","defaultIsJsonContentType","headers","stripUndefined","obj","copy","k","v","fetchBaseQuery","baseUrl","prepareHeaders","x","fetchFn","paramsSerializer","isJsonContentType","jsonContentType","jsonReplacer","defaultTimeout","globalResponseHandler","globalValidateStatus","baseFetchOptions","arg","api","extraOptions","getState","extra","endpoint","forced","type","meta","url","params","responseHandler","validateStatus","timeout","rest","abortController","signal","config","isJsonifiable","body","divider","query","joinUrls","request","timedOut","timeoutId","e","responseClone","resultData","responseText","handleResponseError","handleResponse","r","text","HandledError","value","meta","defaultBackoff","attempt","maxRetries","attempts","timeout","resolve","res","fail","error","meta","HandledError","EMPTY_OPTIONS","retryWithBackoff","baseQuery","defaultOptions","args","api","extraOptions","possibleMaxRetries","x","options","_","__","retry","result","e","onFocus","createAction","onFocusLost","onOnline","onOffline","initialized","setupListeners","dispatch","customHandler","defaultHandler","handleFocus","handleFocusLost","handleOnline","handleOffline","handleVisibilityChange","isQueryDefinition","isMutationDefinition","isInfiniteQueryDefinition","isAnyQueryDefinition","calculateProvidedBy","description","result","error","queryArg","meta","assertTagTypes","isFunction","isNotNullish","expandTagDescription","t","import_immer","forceQueryFnSymbol","isUpsertQuery","arg","buildInitiate","serializeQueryArgs","queryThunk","infiniteQueryThunk","mutationThunk","api","context","runningQueries","runningMutations","unsubscribeQueryResult","removeMutationResult","updateSubscriptionOptions","buildInitiateQuery","buildInitiateInfiniteQuery","buildInitiateMutation","getRunningQueryThunk","getRunningMutationThunk","getRunningQueriesThunk","getRunningMutationsThunk","endpointName","queryArgs","dispatch","endpointDefinition","queryCacheKey","_endpointName","fixedCacheKeyOrRequestId","isNotNullish","middlewareWarning","buildInitiateAnyQuery","queryAction","subscribe","forceRefetch","subscriptionOptions","forceQueryFn","rest","getState","thunk","commonThunkArgs","isQueryDefinition","direction","initialPageParam","selector","thunkResult","stateAfter","requestId","abort","skippedSynchronously","runningQuery","selectFromState","statePromise","result","options","running","getOrInsert","countObjectKeys","track","fixedCacheKey","unwrap","returnValuePromise","asSafePromise","data","error","reset","ret","import_utils","NamedSchemaError","issues","value","schemaName","_bqMeta","parseWithSchema","schema","data","bqMeta","result","defaultTransformResponse","baseQueryReturnValue","addShouldAutoBatch","arg","SHOULD_AUTOBATCH","buildThunks","reducerPath","baseQuery","endpointDefinitions","serializeQueryArgs","api","assertTagType","selectors","onSchemaFailure","globalCatchSchemaFailure","globalSkipSchemaValidation","patchQueryData","endpointName","patches","updateProvided","dispatch","getState","endpointDefinition","queryCacheKey","newValue","providedTags","calculateProvidedBy","addToStart","items","item","max","newItems","addToEnd","updateQueryData","updateRecipe","currentState","ret","value","inversePatches","upsertQueryData","forceQueryFnSymbol","getTransformCallbackForEndpoint","transformFieldName","executeEndpoint","signal","abort","rejectWithValue","fulfillWithValue","extra","metaSchema","skipSchemaValidation","transformResponse","baseQueryApi","isForcedQuery","forceQueryFn","finalQueryReturnValue","fetchPage","data","param","maxPages","previous","finalQueryArg","pageResponse","executeRequest","addTo","result","extraOptions","argSchema","rawResponseSchema","responseSchema","parseWithSchema","HandledError","transformedResponse","infiniteQueryOptions","blankData","cachedData","existingData","getPreviousPageParam","getNextPageParam","initialPageParam","cachedPageParams","firstPageParam","totalPages","i","error","caughtError","transformErrorResponse","rawErrorResponseSchema","errorResponseSchema","meta","transformedErrorResponse","e","NamedSchemaError","info","catchSchemaFailure","state","requestState","baseFetchOnMountOrArgChange","fulfilledVal","refetchVal","createQueryThunk","createAsyncThunk","isInfiniteQueryDefinition","queryThunkArg","currentArg","previousArg","direction","isUpsertQuery","isQueryDefinition","queryThunk","infiniteQueryThunk","mutationThunk","hasTheForce","options","hasMaxAge","prefetch","force","maxAge","queryAction","latestStateValue","lastFulfilledTs","matchesEndpoint","action","buildMatchThunkActions","thunk","isAllOf","isPending","isFulfilled","isRejected","pages","pageParams","queryArg","lastIndex","calculateProvidedByThunk","type","isRejectedWithValue","import_immer","updateQuerySubstateIfExists","state","queryCacheKey","update","substate","getMutationCacheKey","id","updateMutationSubstateIfExists","initialState","buildSlice","reducerPath","queryThunk","mutationThunk","serializeQueryArgs","definitions","apiUid","extractRehydrationInfo","hasRehydrationInfo","assertTagType","config","resetApiState","createAction","writePendingCacheEntry","draft","arg","upserting","meta","endpointDefinition","isInfiniteQueryDefinition","writeFulfilledCacheEntry","payload","merge","fulfilledTimeStamp","baseQueryMeta","requestId","newData","draftSubstateData","copyWithStructuralSharing","querySlice","createSlice","prepareAutoBatched","action","entry","value","endpointName","SHOULD_AUTOBATCH","nanoid","patches","builder","isUpsertQuery","condition","error","queries","key","mutationSlice","cacheKey","startedTimeStamp","mutations","initialInvalidationState","invalidationSlice","providedTags","removeCacheKeyFromTags","type","subscribedQueries","provided","incomingTags","cacheKeys","isAnyOf","isFulfilled","isRejectedWithValue","writeProvidedTagsForQueries","mockActions","queryDescription","existingTags","tag","tagType","tagId","tagSubscriptions","qc","actions","providedByEntries","calculateProvidedByThunk","subscriptionSlice","d","a","internalSubscriptionsSlice","configSlice","isOnline","isDocumentVisible","onOnline","onOffline","onFocus","onFocusLost","combinedReducer","reducer","skipToken","initialSubState","defaultQuerySubState","defaultMutationSubState","buildSelectors","serializeQueryArgs","reducerPath","createSelector","selectSkippedQuery","state","selectSkippedMutation","buildQuerySelector","buildInfiniteQuerySelector","buildMutationSelector","selectInvalidatedBy","selectCachedArgsForQuery","selectApiState","selectQueries","selectMutations","selectQueryEntry","selectConfig","withRequestFlags","substate","getRequestStatusFlags","rootState","cacheKey","buildAnyQuerySelector","endpointName","endpointDefinition","combiner","queryArgs","serializedArgs","infiniteQueryOptions","withInfiniteQueryResultFlags","stateWithRequestFlags","isLoading","isError","direction","isForward","isBackward","getHasNextPage","getHasPreviousPage","id","mutationId","getMutationCacheKey","tags","apiState","toInvalidate","tag","isNotNullish","expandTagDescription","provided","invalidateSubscriptions","flatten","invalidate","queryCacheKey","querySubState","queryName","entry","options","data","queryArg","getNextPageParam","getPreviousPageParam","cache","defaultSerializeQueryArgs","endpointName","queryArgs","serialized","cached","stringified","key","value","acc","import_reselect","buildCreateApi","modules","options","extractRehydrationInfo","action","optionsWithDefaults","queryArgsApi","finalSerializeQueryArgs","defaultSerializeQueryArgs","endpointSQA","initialResult","context","fn","nanoid","api","injectEndpoints","addTagTypes","endpoints","eT","endpointName","partialDefinition","initializedModules","inject","evaluatedEndpoints","x","definition","formatProdErrorMessage","m","_NEVER","fakeBaseQuery","formatProdErrorMessage","import_immer","safeAssign","target","args","import_immer","buildBatchedActionsHandler","api","queryThunk","internalState","subscriptionsPrefix","previousSubscriptions","updateSyncTimer","updateSubscriptionOptions","unsubscribeQueryResult","actuallyMutateSubscriptions","mutableState","action","queryCacheKey","requestId","options","arg","substate","mutated","state","key","condition","getSubscriptions","subscriptionSelectors","subscriptionsForQueryArg","countObjectKeys","mwApi","didMutate","actionShouldContinue","newSubscriptions","patches","isSubscriptionSliceAction","isAdditionalSubscriptionAction","isObjectEmpty","obj","k","THIRTY_TWO_BIT_MAX_TIMER_SECONDS","buildCacheCollectionHandler","reducerPath","api","queryThunk","context","internalState","selectQueryEntry","selectConfig","removeQueryResult","unsubscribeQueryResult","cacheEntriesUpserted","canTriggerUnsubscribe","isAnyOf","anySubscriptionsRemainingForKey","queryCacheKey","subscriptions","isObjectEmpty","currentRemovalTimeouts","handler","action","mwApi","state","config","queryCacheKeys","entry","handleUnsubscribeMany","key","timeout","queries","cacheKeys","handleUnsubscribe","endpointName","keepUnusedDataFor","finalKeepUnusedDataFor","currentTimeout","neverResolvedError","buildCacheLifecycleHandler","api","reducerPath","context","queryThunk","mutationThunk","internalState","selectQueryEntry","selectApiState","isQueryThunk","isAsyncThunkAction","isMutationThunk","isFulfilledThunk","isFulfilled","lifecycleMap","resolveLifecycleEntry","cacheKey","data","meta","lifecycle","removeLifecycleEntry","handler","action","mwApi","stateBefore","getCacheKey","checkForNewCacheKey","endpointName","requestId","originalArgs","oldEntry","newEntry","handleNewKey","queryDescription","value","queryCacheKey","getMutationCacheKey","endpointDefinition","onCacheEntryAdded","cacheEntryRemoved","resolve","cacheDataLoaded","selector","isAnyQueryDefinition","extra","_","__","lifecycleApi","updateRecipe","runningHandler","e","buildDevCheckHandler","api","apiUid","reducerPath","action","mwApi","buildInvalidationByTagsHandler","reducerPath","context","endpointDefinitions","mutationThunk","queryThunk","api","assertTagType","refetchQuery","internalState","removeQueryResult","isThunkActionWithTags","isAnyOf","isFulfilled","isRejectedWithValue","isQueryEnd","isRejected","pendingTagInvalidations","handler","action","mwApi","invalidateTags","calculateProvidedByThunk","calculateProvidedBy","hasPendingRequests","state","queries","mutations","cacheRecord","key","newTags","rootState","tags","toInvalidate","valuesArray","queryCacheKey","querySubState","subscriptionSubState","countObjectKeys","buildPollingHandler","reducerPath","queryThunk","api","refetchQuery","internalState","currentPolls","handler","action","mwApi","updatePollingInterval","startNextPoll","clearPolls","getCacheEntrySubscriptions","queryCacheKey","querySubState","subscriptions","state","lowestPollingInterval","skipPollingIfUnfocused","findLowestPollingInterval","currentPoll","nextPollTimestamp","cleanupPollForKey","key","existingPoll","subscribers","buildQueryLifecycleHandler","api","context","queryThunk","mutationThunk","isPendingThunk","isPending","isRejectedThunk","isRejected","isFullfilledThunk","isFulfilled","lifecycleMap","action","mwApi","requestId","endpointName","originalArgs","endpointDefinition","onQueryStarted","lifecycle","queryFulfilled","resolve","reject","selector","isAnyQueryDefinition","extra","_","__","lifecycleApi","updateRecipe","baseQueryMeta","rejectedWithValue","buildWindowEventHandler","reducerPath","context","api","refetchQuery","internalState","removeQueryResult","handler","action","mwApi","onFocus","refetchValidQueries","onOnline","type","state","queries","subscriptions","queryCacheKey","querySubState","subscriptionSubState","sub","countObjectKeys","buildMiddleware","input","reducerPath","queryThunk","api","context","apiUid","actions","createAction","isThisApiSliceAction","action","handlerBuilders","buildDevCheckHandler","buildCacheCollectionHandler","buildInvalidationByTagsHandler","buildPollingHandler","buildCacheLifecycleHandler","buildQueryLifecycleHandler","mwApi","initialized","builderArgs","refetchQuery","handlers","build","batchedActionsHandler","buildBatchedActionsHandler","windowEventsHandler","buildWindowEventHandler","next","mwApiWithNext","stateBefore","actionShouldContinue","internalProbeResult","res","handler","querySubState","coreModuleName","coreModule","createSelector","api","baseQuery","tagTypes","reducerPath","serializeQueryArgs","keepUnusedDataFor","refetchOnMountOrArgChange","refetchOnFocus","refetchOnReconnect","invalidationBehavior","onSchemaFailure","catchSchemaFailure","skipSchemaValidation","context","assertTagType","tag","onOnline","onOffline","onFocus","onFocusLost","selectors","buildSelectors","selectInvalidatedBy","selectCachedArgsForQuery","buildQuerySelector","buildInfiniteQuerySelector","buildMutationSelector","safeAssign","queryThunk","infiniteQueryThunk","mutationThunk","patchQueryData","updateQueryData","upsertQueryData","prefetch","buildMatchThunkActions","buildThunks","reducer","sliceActions","buildSlice","middleware","middlewareActions","buildMiddleware","buildInitiateQuery","buildInitiateInfiniteQuery","buildInitiateMutation","getRunningMutationThunk","getRunningMutationsThunk","getRunningQueriesThunk","getRunningQueryThunk","buildInitiate","endpointName","definition","anyApi","endpoint","isQueryDefinition","isMutationDefinition","isInfiniteQueryDefinition","createApi","buildCreateApi","coreModule"]}