amis-rpc-design/node_modules/@reduxjs/toolkit/dist/query/rtk-query.modern.production.min.js.map
2023-10-07 19:42:30 +08:00

2 lines
259 KiB
Plaintext

{"version":3,"names":["QueryStatus","QueryStatus2","flatten","arr","concat","_iPO","isPlainObject","copyWithStructuralSharing","oldObj","newObj","Array","isArray","newKeys","Object","keys","oldKeys","isSameObject","length","mergeObj","key","isPlainObject2","defaultFetchFn","args","fetch","defaultValidateStatus","response","status","defaultIsJsonContentType","headers","test","get","stripUndefined","obj","copy","__spreadValues","k","v","entries","fetchBaseQuery","_a","_b","baseUrl","prepareHeaders","x","fetchFn","paramsSerializer","isJsonContentType","jsonContentType","jsonReplacer","timeout","defaultTimeout","responseHandler","globalResponseHandler","validateStatus","globalValidateStatus","baseFetchOptions","__objRest","console","warn","async","arg","api","signal","getState","extra","endpoint","forced","type","meta","_a2","url","Headers","params","rest","config","__spreadProps","isJsonifiable","body","toJSON","has","set","JSON","stringify","divider","indexOf","URLSearchParams","base","RegExp","isAbsoluteUrl","delimiter","endsWith","startsWith","replace","withoutTrailingSlash","withoutLeadingSlash","joinUrls","request","Request","timedOut","timeoutId","setTimeout","abort","e","error","String","clearTimeout","responseClone","clone","resultData","responseText","handleResponseError","Promise","all","handleResponse","then","r","text","originalStatus","data","parse","HandledError","constructor","value","this","defaultBackoff","attempt","maxRetries","attempts","Math","min","random","resolve","res","EMPTY_OPTIONS","retry","assign","baseQuery","defaultOptions","extraOptions","possibleMaxRetries","filter","slice","options","backoff","retryCondition","_","__","retry2","result","throwImmediately","baseQueryApi","fail","createAction","DefinitionType","DefinitionType2","onFocus","onFocusLost","onOnline","onOffline","initialized","setupListeners","dispatch","customHandler","handleFocus","handleOnline","handleOffline","handleVisibilityChange","window","document","visibilityState","addEventListener","removeEventListener","defaultHandler","createNextState2","createSelector","isQueryDefinition","query","calculateProvidedBy","description","queryArg","assertTagTypes","map","expandTagDescription","combineReducers","createAction2","createSlice","isAnyOf","isFulfilled2","isRejectedWithValue2","createNextState","prepareAutoBatched","isNotNullish","forceQueryFnSymbol","Symbol","isUpsertQuery","isAllOf","isFulfilled","isPending","isRejected","isRejectedWithValue","isDraftable","produceWithPatches","createAsyncThunk","SHOULD_AUTOBATCH","defaultTransformResponse","baseQueryReturnValue","calculateProvidedByThunk","action","endpointDefinitions","assertTagType","endpointName","payload","originalArgs","baseQueryMeta","isDraft","applyPatches","original","updateQuerySubstateIfExists","state","queryCacheKey","update","substate","getMutationCacheKey","id","fixedCacheKey","requestId","updateMutationSubstateIfExists","initialState","skipToken","for","skipSelector","initialSubState","uninitialized","defaultQuerySubState","defaultMutationSubState","isPlainObject3","cache","WeakMap","defaultSerializeQueryArgs","queryArgs","serialized","cached","stringified","sort","reduce","acc","key2","nanoid","defaultMemoize","buildCreateApi","modules","extractRehydrationInfo","call","reducerPath","optionsWithDefaults","keepUnusedDataFor","refetchOnMountOrArgChange","refetchOnFocus","refetchOnReconnect","serializeQueryArgs","queryArgsApi","finalSerializeQueryArgs","endpointDefinition","endpointSQA","queryArgsApi2","initialResult","tagTypes","context","batch","fn","apiUid","hasRehydrationInfo","injectEndpoints","inject","evaluatedEndpoints","endpoints","mutation","definition","overrideExisting","m","initializedModules","injectEndpoint","enhanceEndpoints","addTagTypes","eT","includes","push","partialDefinition","init","fakeBaseQuery","Error","createAction3","buildCacheCollectionHandler","internalState","removeQueryResult","unsubscribeQueryResult","internalActions","anySubscriptionsRemainingForKey","subscriptions","currentSubscriptions","isObjectEmpty","currentRemovalTimeouts","handleUnsubscribe","api2","Infinity","finalKeepUnusedDataFor","max","currentTimeout","mwApi","internalState2","match","queries","util","resetApiState","queryState","isAnyOf2","isFulfilled3","isRejectedWithValue3","buildInvalidationByTagsHandler","mutationThunk","refetchQuery","isThunkActionWithTags","invalidateTags","tags","rootState","toInvalidate","selectInvalidatedBy","valuesArray","from","values","querySubState","subscriptionSubState","buildPollingHandler","queryThunk","currentPolls","startNextPoll","lowestPollingInterval","findLowestPollingInterval","Number","isFinite","currentPoll","nextPollTimestamp","Date","now","currentInterval","pollingInterval","updatePollingInterval","cleanupPollForKey","existingPoll","subscribers","POSITIVE_INFINITY","updateSubscriptionOptions","pending","rejected","condition","fulfilled","clearPolls","isAsyncThunkAction","isFulfilled4","neverResolvedError","buildCacheLifecycleHandler","isQueryThunk","isMutationThunk","isFulfilledThunk","lifecycleMap","handleNewKey","onCacheEntryAdded","lifecycle","cacheEntryRemoved","cacheDataLoaded","race","valueResolved","catch","selector","select","extra2","lifecycleApi","getCacheEntry","updateCachedData","updateRecipe","updateQueryData","runningHandler","stateBefore","cacheKey","removeMutationResult","getCacheKey","oldState","mutations","cacheKey2","isPending2","isRejected2","isFulfilled5","promise","buildQueryLifecycleHandler","isPendingThunk","isRejectedThunk","isFullfilledThunk","_c","onQueryStarted","queryFulfilled","reject","rejectedWithValue","isUnhandledError","buildDevCheckHandler","middlewareRegistered","produceWithPatches2","queueMicrotaskShim","queueMicrotask","bind","global","globalThis","cb","err","safeAssign","target","enablePatches","coreModuleName","coreModule","name","tag","patchQueryData","upsertQueryData","prefetch","buildMatchThunkActions","executeEndpoint","rejectWithValue","fulfillWithValue","transformResponse","isForcedQuery","forceQueryFn","queryFn","arg2","fulfilledTimeStamp","catchedError","transformErrorResponse","_d","requestState","baseFetchOnMountOrArgChange","fulfilledVal","refetchVal","forceRefetch","subscribe","matchesEndpoint","getPendingMeta","startedTimeStamp","queryThunkArgs","currentArg","previousArg","endpointState","dispatchConditionRejection","force","hasTheForce","maxAge","hasMaxAge","ifOlderThan","queryAction","force2","initiate","latestStateValue","lastFulfilledTs","updateProvided","currentState","newValue","ret","patches","inversePatches","undo","op","path","queryResultPatched","providedTags","providesTags","updateProvidedBy","thunk","matchPending","matchFulfilled","matchRejected","buildThunks","reducer","actions","sliceActions","definitions","querySlice","reducers","draft","prepare","extraReducers","builder","addCase","upserting","merge","newData","draftSubstateData","structuralSharing","addMatcher","entry","mutationSlice","track","invalidationSlice","tagTypeSubscriptions","idSubscriptions","foundAt","splice","subscribedQueries","provided","incomingTags","cacheKeys","caseReducers","subscriptionSlice","d","a","internal_probeSubscription","internalSubscriptionsSlice","subscriptionsUpdated","configSlice","online","navigator","onLine","focused","combinedReducer","unsubscribeMutationResult","buildSlice","middleware","middlewareActions","input","handlerBuilders","initialized2","builderArgs","handlers","build","batchedActionsHandler","subscriptionsPrefix","previousSubscriptions","dispatchQueued","didMutate","mutableState","_e","_f","_g","_h","_i","subscriptionOptions","actuallyMutateSubscriptions","newSubscriptions","next","isSubscriptionSliceAction","isAdditionalSubscriptionAction","buildBatchedActionsHandler","windowEventsHandler","refetchValidQueries","some","sub","every","buildWindowEventHandler","mwApiWithNext","actionShouldContinue","hasSubscription","isThisApiSliceAction","handler","override","buildMiddleware","buildQuerySelector","buildMutationSelector","selectSkippedQuery","selectSkippedMutation","serializedArgs","selectInternalState","withRequestFlags","mutationId","apiState","Set","invalidateSubscriptions","invalidate","add","isUninitialized","isLoading","isSuccess","isError","buildSelectors","buildInitiateQuery","buildInitiateMutation","getRunningMutationThunk","getRunningMutationsThunk","getRunningQueriesThunk","getRunningQueryThunk","getRunningOperationPromises","removalWarning","runningQueries","Map","runningMutations","thunkResult","stateAfter","skippedSynchronously","runningQuery","selectFromState","statePromise","refetch","unsubscribe","running","delete","unwrap","returnValuePromise","reset","_endpointName","fixedCacheKeyOrRequestId","extract","flatMap","queriesForStore","buildInitiate","getRunningOperationPromise","anyApi","createApi"],"sources":["../../src/query/core/apiState.ts","../../src/query/utils/flatten.ts","../../src/query/utils/copyWithStructuralSharing.ts","../../src/query/fetchBaseQuery.ts","../../src/query/utils/joinUrls.ts","../../src/query/utils/isAbsoluteUrl.ts","../../src/query/HandledError.ts","../../src/query/retry.ts","../../src/query/core/setupListeners.ts","../../src/query/endpointDefinitions.ts","../../src/query/core/buildSelectors.ts","../../src/query/core/buildSlice.ts","../../src/query/utils/isNotNullish.ts","../../src/query/core/buildInitiate.ts","../../src/query/core/buildThunks.ts","../../src/query/defaultSerializeQueryArgs.ts","../../src/query/createApi.ts","../../src/query/fakeBaseQuery.ts","../../src/query/core/buildMiddleware/index.ts","../../src/query/core/buildMiddleware/cacheCollection.ts","../../src/query/core/buildMiddleware/invalidationByTags.ts","../../src/query/core/buildMiddleware/polling.ts","../../src/query/core/buildMiddleware/cacheLifecycle.ts","../../src/query/core/buildMiddleware/queryLifecycle.ts","../../src/query/core/buildMiddleware/batchActions.ts","../../src/query/core/buildMiddleware/devMiddleware.ts","../../src/query/tsHelpers.ts","../../src/query/core/module.ts","../../src/query/utils/isOnline.ts","../../src/query/utils/isDocumentVisible.ts","../../src/query/core/buildMiddleware/windowEventHandling.ts","../../src/query/core/index.ts"],"sourcesContent":["import type { SerializedError } from '@reduxjs/toolkit'\r\nimport type { BaseQueryError } from '../baseQueryTypes'\r\nimport type {\r\n QueryDefinition,\r\n MutationDefinition,\r\n EndpointDefinitions,\r\n BaseEndpointDefinition,\r\n ResultTypeFrom,\r\n QueryArgFrom,\r\n} from '../endpointDefinitions'\r\nimport type { Id, WithRequiredProp } from '../tsHelpers'\r\n\r\nexport type QueryCacheKey = string & { _type: 'queryCacheKey' }\r\nexport type QuerySubstateIdentifier = { queryCacheKey: QueryCacheKey }\r\nexport type MutationSubstateIdentifier =\r\n | {\r\n requestId: string\r\n fixedCacheKey?: string\r\n }\r\n | {\r\n requestId?: string\r\n fixedCacheKey: string\r\n }\r\n\r\nexport type RefetchConfigOptions = {\r\n refetchOnMountOrArgChange: boolean | number\r\n refetchOnReconnect: boolean\r\n refetchOnFocus: boolean\r\n}\r\n\r\n/**\r\n * Strings describing the query state at any given time.\r\n */\r\nexport enum QueryStatus {\r\n uninitialized = 'uninitialized',\r\n pending = 'pending',\r\n fulfilled = 'fulfilled',\r\n rejected = 'rejected',\r\n}\r\n\r\nexport type RequestStatusFlags =\r\n | {\r\n status: QueryStatus.uninitialized\r\n isUninitialized: true\r\n isLoading: false\r\n isSuccess: false\r\n isError: false\r\n }\r\n | {\r\n status: QueryStatus.pending\r\n isUninitialized: false\r\n isLoading: true\r\n isSuccess: false\r\n isError: false\r\n }\r\n | {\r\n status: QueryStatus.fulfilled\r\n isUninitialized: false\r\n isLoading: false\r\n isSuccess: true\r\n isError: false\r\n }\r\n | {\r\n status: QueryStatus.rejected\r\n isUninitialized: false\r\n isLoading: false\r\n isSuccess: false\r\n isError: true\r\n }\r\n\r\nexport function getRequestStatusFlags(status: QueryStatus): RequestStatusFlags {\r\n return {\r\n status,\r\n isUninitialized: status === QueryStatus.uninitialized,\r\n isLoading: status === QueryStatus.pending,\r\n isSuccess: status === QueryStatus.fulfilled,\r\n isError: status === QueryStatus.rejected,\r\n } as any\r\n}\r\n\r\nexport type SubscriptionOptions = {\r\n /**\r\n * How frequently to automatically re-fetch data (in milliseconds). Defaults to `0` (off).\r\n */\r\n pollingInterval?: number\r\n /**\r\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.\r\n *\r\n * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\r\n *\r\n * Note: requires [`setupListeners`](./setupListeners) to have been called.\r\n */\r\n refetchOnReconnect?: boolean\r\n /**\r\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.\r\n *\r\n * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\r\n *\r\n * Note: requires [`setupListeners`](./setupListeners) to have been called.\r\n */\r\n refetchOnFocus?: boolean\r\n}\r\nexport type Subscribers = { [requestId: string]: SubscriptionOptions }\r\nexport type QueryKeys<Definitions extends EndpointDefinitions> = {\r\n [K in keyof Definitions]: Definitions[K] extends QueryDefinition<\r\n any,\r\n any,\r\n any,\r\n any\r\n >\r\n ? K\r\n : never\r\n}[keyof Definitions]\r\nexport type MutationKeys<Definitions extends EndpointDefinitions> = {\r\n [K in keyof Definitions]: Definitions[K] extends MutationDefinition<\r\n any,\r\n any,\r\n any,\r\n any\r\n >\r\n ? K\r\n : never\r\n}[keyof Definitions]\r\n\r\ntype BaseQuerySubState<D extends BaseEndpointDefinition<any, any, any>> = {\r\n /**\r\n * The argument originally passed into the hook or `initiate` action call\r\n */\r\n originalArgs: QueryArgFrom<D>\r\n /**\r\n * A unique ID associated with the request\r\n */\r\n requestId: string\r\n /**\r\n * The received data from the query\r\n */\r\n data?: ResultTypeFrom<D>\r\n /**\r\n * The received error if applicable\r\n */\r\n error?:\r\n | SerializedError\r\n | (D extends QueryDefinition<any, infer BaseQuery, any, any>\r\n ? BaseQueryError<BaseQuery>\r\n : never)\r\n /**\r\n * The name of the endpoint associated with the query\r\n */\r\n endpointName: string\r\n /**\r\n * Time that the latest query started\r\n */\r\n startedTimeStamp: number\r\n /**\r\n * Time that the latest query was fulfilled\r\n */\r\n fulfilledTimeStamp?: number\r\n}\r\n\r\nexport type QuerySubState<D extends BaseEndpointDefinition<any, any, any>> = Id<\r\n | ({\r\n status: QueryStatus.fulfilled\r\n } & WithRequiredProp<\r\n BaseQuerySubState<D>,\r\n 'data' | 'fulfilledTimeStamp'\r\n > & { error: undefined })\r\n | ({\r\n status: QueryStatus.pending\r\n } & BaseQuerySubState<D>)\r\n | ({\r\n status: QueryStatus.rejected\r\n } & WithRequiredProp<BaseQuerySubState<D>, 'error'>)\r\n | {\r\n status: QueryStatus.uninitialized\r\n originalArgs?: undefined\r\n data?: undefined\r\n error?: undefined\r\n requestId?: undefined\r\n endpointName?: string\r\n startedTimeStamp?: undefined\r\n fulfilledTimeStamp?: undefined\r\n }\r\n>\r\n\r\ntype BaseMutationSubState<D extends BaseEndpointDefinition<any, any, any>> = {\r\n requestId: string\r\n data?: ResultTypeFrom<D>\r\n error?:\r\n | SerializedError\r\n | (D extends MutationDefinition<any, infer BaseQuery, any, any>\r\n ? BaseQueryError<BaseQuery>\r\n : never)\r\n endpointName: string\r\n startedTimeStamp: number\r\n fulfilledTimeStamp?: number\r\n}\r\n\r\nexport type MutationSubState<D extends BaseEndpointDefinition<any, any, any>> =\r\n | (({\r\n status: QueryStatus.fulfilled\r\n } & WithRequiredProp<\r\n BaseMutationSubState<D>,\r\n 'data' | 'fulfilledTimeStamp'\r\n >) & { error: undefined })\r\n | (({\r\n status: QueryStatus.pending\r\n } & BaseMutationSubState<D>) & { data?: undefined })\r\n | ({\r\n status: QueryStatus.rejected\r\n } & WithRequiredProp<BaseMutationSubState<D>, 'error'>)\r\n | {\r\n requestId?: undefined\r\n status: QueryStatus.uninitialized\r\n data?: undefined\r\n error?: undefined\r\n endpointName?: string\r\n startedTimeStamp?: undefined\r\n fulfilledTimeStamp?: undefined\r\n }\r\n\r\nexport type CombinedState<\r\n D extends EndpointDefinitions,\r\n E extends string,\r\n ReducerPath extends string\r\n> = {\r\n queries: QueryState<D>\r\n mutations: MutationState<D>\r\n provided: InvalidationState<E>\r\n subscriptions: SubscriptionState\r\n config: ConfigState<ReducerPath>\r\n}\r\n\r\nexport type InvalidationState<TagTypes extends string> = {\r\n [_ in TagTypes]: {\r\n [id: string]: Array<QueryCacheKey>\r\n [id: number]: Array<QueryCacheKey>\r\n }\r\n}\r\n\r\nexport type QueryState<D extends EndpointDefinitions> = {\r\n [queryCacheKey: string]: QuerySubState<D[string]> | undefined\r\n}\r\n\r\nexport type SubscriptionState = {\r\n [queryCacheKey: string]: Subscribers | undefined\r\n}\r\n\r\nexport type ConfigState<ReducerPath> = RefetchConfigOptions & {\r\n reducerPath: ReducerPath\r\n online: boolean\r\n focused: boolean\r\n middlewareRegistered: boolean | 'conflict'\r\n} & ModifiableConfigState\r\n\r\nexport type ModifiableConfigState = {\r\n keepUnusedDataFor: number\r\n} & RefetchConfigOptions\r\n\r\nexport type MutationState<D extends EndpointDefinitions> = {\r\n [requestId: string]: MutationSubState<D[string]> | undefined\r\n}\r\n\r\nexport type RootState<\r\n Definitions extends EndpointDefinitions,\r\n TagTypes extends string,\r\n ReducerPath extends string\r\n> = {\r\n [P in ReducerPath]: CombinedState<Definitions, TagTypes, P>\r\n}\r\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 */\r\nexport const flatten = (arr: readonly any[]) => [].concat(...arr)\r\n","import { isPlainObject as _iPO } from '@reduxjs/toolkit'\r\n\r\n// remove type guard\r\nconst isPlainObject: (_: any) => boolean = _iPO\r\n\r\nexport function copyWithStructuralSharing<T>(oldObj: any, newObj: T): T\r\nexport function copyWithStructuralSharing(oldObj: any, newObj: any): any {\r\n if (\r\n oldObj === newObj ||\r\n !(\r\n (isPlainObject(oldObj) && isPlainObject(newObj)) ||\r\n (Array.isArray(oldObj) && Array.isArray(newObj))\r\n )\r\n ) {\r\n return newObj\r\n }\r\n const newKeys = Object.keys(newObj)\r\n const oldKeys = Object.keys(oldObj)\r\n\r\n let isSameObject = newKeys.length === oldKeys.length\r\n const mergeObj: any = Array.isArray(newObj) ? [] : {}\r\n for (const key of newKeys) {\r\n mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key])\r\n if (isSameObject) isSameObject = oldObj[key] === mergeObj[key]\r\n }\r\n return isSameObject ? oldObj : mergeObj\r\n}\r\n","import { joinUrls } from './utils'\r\nimport { isPlainObject } from '@reduxjs/toolkit'\r\nimport type { BaseQueryApi, BaseQueryFn } from './baseQueryTypes'\r\nimport type { MaybePromise, Override } from './tsHelpers'\r\n\r\nexport type ResponseHandler =\r\n | 'content-type'\r\n | 'json'\r\n | 'text'\r\n | ((response: Response) => Promise<any>)\r\n\r\ntype CustomRequestInit = Override<\r\n RequestInit,\r\n {\r\n headers?:\r\n | Headers\r\n | string[][]\r\n | Record<string, string | undefined>\r\n | undefined\r\n }\r\n>\r\n\r\nexport interface FetchArgs extends CustomRequestInit {\r\n url: string\r\n params?: Record<string, any>\r\n body?: any\r\n responseHandler?: ResponseHandler\r\n validateStatus?: (response: Response, body: any) => boolean\r\n /**\r\n * A number in milliseconds that represents that maximum time a request can take before timing out.\r\n */\r\n timeout?: number\r\n}\r\n\r\n/**\r\n * A mini-wrapper that passes arguments straight through to\r\n * {@link [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)}.\r\n * Avoids storing `fetch` in a closure, in order to permit mocking/monkey-patching.\r\n */\r\nconst defaultFetchFn: typeof fetch = (...args) => fetch(...args)\r\n\r\nconst defaultValidateStatus = (response: Response) =>\r\n response.status >= 200 && response.status <= 299\r\n\r\nconst defaultIsJsonContentType = (headers: Headers) =>\r\n /*applicat*/ /ion\\/(vnd\\.api\\+)?json/.test(headers.get('content-type') || '')\r\n\r\nexport type FetchBaseQueryError =\r\n | {\r\n /**\r\n * * `number`:\r\n * HTTP status code\r\n */\r\n status: number\r\n data: unknown\r\n }\r\n | {\r\n /**\r\n * * `\"FETCH_ERROR\"`:\r\n * An error that occurred during execution of `fetch` or the `fetchFn` callback option\r\n **/\r\n status: 'FETCH_ERROR'\r\n data?: undefined\r\n error: string\r\n }\r\n | {\r\n /**\r\n * * `\"PARSING_ERROR\"`:\r\n * An error happened during parsing.\r\n * Most likely a non-JSON-response was returned with the default `responseHandler` \"JSON\",\r\n * or an error occurred while executing a custom `responseHandler`.\r\n **/\r\n status: 'PARSING_ERROR'\r\n originalStatus: number\r\n data: string\r\n error: string\r\n }\r\n | {\r\n /**\r\n * * `\"TIMEOUT_ERROR\"`:\r\n * Request timed out\r\n **/\r\n status: 'TIMEOUT_ERROR'\r\n data?: undefined\r\n error: string\r\n }\r\n | {\r\n /**\r\n * * `\"CUSTOM_ERROR\"`:\r\n * A custom error type that you can return from your `queryFn` where another error might not make sense.\r\n **/\r\n status: 'CUSTOM_ERROR'\r\n data?: unknown\r\n error: string\r\n }\r\n\r\nfunction stripUndefined(obj: any) {\r\n if (!isPlainObject(obj)) {\r\n return obj\r\n }\r\n const copy: Record<string, any> = { ...obj }\r\n for (const [k, v] of Object.entries(copy)) {\r\n if (v === undefined) delete copy[k]\r\n }\r\n return copy\r\n}\r\n\r\nexport type FetchBaseQueryArgs = {\r\n baseUrl?: string\r\n prepareHeaders?: (\r\n headers: Headers,\r\n api: Pick<\r\n BaseQueryApi,\r\n 'getState' | 'extra' | 'endpoint' | 'type' | 'forced'\r\n >\r\n ) => MaybePromise<Headers | void>\r\n fetchFn?: (\r\n input: RequestInfo,\r\n init?: RequestInit | undefined\r\n ) => Promise<Response>\r\n paramsSerializer?: (params: Record<string, any>) => string\r\n /**\r\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\r\n * in a predicate function for your given api to get the same automatic stringifying behavior\r\n * @example\r\n * ```ts\r\n * const isJsonContentType = (headers: Headers) => [\"application/vnd.api+json\", \"application/json\", \"application/vnd.hal+json\"].includes(headers.get(\"content-type\")?.trim());\r\n * ```\r\n */\r\n isJsonContentType?: (headers: Headers) => boolean\r\n /**\r\n * Defaults to `application/json`;\r\n */\r\n jsonContentType?: string\r\n\r\n /**\r\n * Custom replacer function used when calling `JSON.stringify()`;\r\n */\r\n jsonReplacer?: (this: any, key: string, value: any) => any\r\n} & RequestInit &\r\n Pick<FetchArgs, 'responseHandler' | 'validateStatus' | 'timeout'>\r\n\r\nexport type FetchBaseQueryMeta = { request: Request; response?: Response }\r\n\r\n/**\r\n * This is a very small wrapper around fetch that aims to simplify requests.\r\n *\r\n * @example\r\n * ```ts\r\n * const baseQuery = fetchBaseQuery({\r\n * baseUrl: 'https://api.your-really-great-app.com/v1/',\r\n * prepareHeaders: (headers, { getState }) => {\r\n * const token = (getState() as RootState).auth.token;\r\n * // If we have a token set in state, let's assume that we should be passing it.\r\n * if (token) {\r\n * headers.set('authorization', `Bearer ${token}`);\r\n * }\r\n * return headers;\r\n * },\r\n * })\r\n * ```\r\n *\r\n * @param {string} baseUrl\r\n * The base URL for an API service.\r\n * Typically in the format of https://example.com/\r\n *\r\n * @param {(headers: Headers, api: { getState: () => unknown; extra: unknown; endpoint: string; type: 'query' | 'mutation'; forced: boolean; }) => Headers} prepareHeaders\r\n * An optional function that can be used to inject headers on requests.\r\n * Provides a Headers object, as well as most of the `BaseQueryApi` (`dispatch` is not available).\r\n * Useful for setting authentication or headers that need to be set conditionally.\r\n *\r\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Headers\r\n *\r\n * @param {(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>} fetchFn\r\n * Accepts a custom `fetch` function if you do not want to use the default on the window.\r\n * Useful in SSR environments if you need to use a library such as `isomorphic-fetch` or `cross-fetch`\r\n *\r\n * @param {(params: Record<string, unknown>) => string} paramsSerializer\r\n * An optional function that can be used to stringify querystring parameters.\r\n *\r\n * @param {(headers: Headers) => boolean} isJsonContentType\r\n * An optional predicate function to determine if `JSON.stringify()` should be called on the `body` arg of `FetchArgs`\r\n *\r\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`.\r\n *\r\n * @param {(this: any, key: string, value: any) => any} jsonReplacer Custom replacer function used when calling `JSON.stringify()`.\r\n *\r\n * @param {number} timeout\r\n * A number in milliseconds that represents the maximum time a request can take before timing out.\r\n */\r\nexport function fetchBaseQuery({\r\n baseUrl,\r\n prepareHeaders = (x) => x,\r\n fetchFn = defaultFetchFn,\r\n paramsSerializer,\r\n isJsonContentType = defaultIsJsonContentType,\r\n jsonContentType = 'application/json',\r\n jsonReplacer,\r\n timeout: defaultTimeout,\r\n responseHandler: globalResponseHandler,\r\n validateStatus: globalValidateStatus,\r\n ...baseFetchOptions\r\n}: FetchBaseQueryArgs = {}): BaseQueryFn<\r\n string | FetchArgs,\r\n unknown,\r\n FetchBaseQueryError,\r\n {},\r\n FetchBaseQueryMeta\r\n> {\r\n if (typeof fetch === 'undefined' && fetchFn === defaultFetchFn) {\r\n console.warn(\r\n 'Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.'\r\n )\r\n }\r\n return async (arg, api) => {\r\n const { signal, getState, extra, endpoint, forced, type } = api\r\n let meta: FetchBaseQueryMeta | undefined\r\n let {\r\n url,\r\n headers = new Headers(baseFetchOptions.headers),\r\n params = undefined,\r\n responseHandler = globalResponseHandler ?? ('json' as const),\r\n validateStatus = globalValidateStatus ?? defaultValidateStatus,\r\n timeout = defaultTimeout,\r\n ...rest\r\n } = typeof arg == 'string' ? { url: arg } : arg\r\n let config: RequestInit = {\r\n ...baseFetchOptions,\r\n signal,\r\n ...rest,\r\n }\r\n\r\n headers = new Headers(stripUndefined(headers))\r\n config.headers =\r\n (await prepareHeaders(headers, {\r\n getState,\r\n extra,\r\n endpoint,\r\n forced,\r\n type,\r\n })) || headers\r\n\r\n // Only set the content-type to json if appropriate. Will not be true for FormData, ArrayBuffer, Blob, etc.\r\n const isJsonifiable = (body: any) =>\r\n typeof body === 'object' &&\r\n (isPlainObject(body) ||\r\n Array.isArray(body) ||\r\n typeof body.toJSON === 'function')\r\n\r\n if (!config.headers.has('content-type') && isJsonifiable(config.body)) {\r\n config.headers.set('content-type', jsonContentType)\r\n }\r\n\r\n if (isJsonifiable(config.body) && isJsonContentType(config.headers)) {\r\n config.body = JSON.stringify(config.body, jsonReplacer)\r\n }\r\n\r\n if (params) {\r\n const divider = ~url.indexOf('?') ? '&' : '?'\r\n const query = paramsSerializer\r\n ? paramsSerializer(params)\r\n : new URLSearchParams(stripUndefined(params))\r\n url += divider + query\r\n }\r\n\r\n url = joinUrls(baseUrl, url)\r\n\r\n const request = new Request(url, config)\r\n const requestClone = new Request(url, config)\r\n meta = { request: requestClone }\r\n\r\n let response,\r\n timedOut = false,\r\n timeoutId =\r\n timeout &&\r\n setTimeout(() => {\r\n timedOut = true\r\n api.abort()\r\n }, timeout)\r\n try {\r\n response = await fetchFn(request)\r\n } catch (e) {\r\n return {\r\n error: {\r\n status: timedOut ? 'TIMEOUT_ERROR' : 'FETCH_ERROR',\r\n error: String(e),\r\n },\r\n meta,\r\n }\r\n } finally {\r\n if (timeoutId) clearTimeout(timeoutId)\r\n }\r\n const responseClone = response.clone()\r\n\r\n meta.response = responseClone\r\n\r\n let resultData: any\r\n let responseText: string = ''\r\n try {\r\n let handleResponseError\r\n await Promise.all([\r\n handleResponse(response, responseHandler).then(\r\n (r) => (resultData = r),\r\n (e) => (handleResponseError = e)\r\n ),\r\n // see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182\r\n // we *have* to \"use up\" both streams at the same time or they will stop running in node-fetch scenarios\r\n responseClone.text().then(\r\n (r) => (responseText = r),\r\n () => {}\r\n ),\r\n ])\r\n if (handleResponseError) throw handleResponseError\r\n } catch (e) {\r\n return {\r\n error: {\r\n status: 'PARSING_ERROR',\r\n originalStatus: response.status,\r\n data: responseText,\r\n error: String(e),\r\n },\r\n meta,\r\n }\r\n }\r\n\r\n return validateStatus(response, resultData)\r\n ? {\r\n data: resultData,\r\n meta,\r\n }\r\n : {\r\n error: {\r\n status: response.status,\r\n data: resultData,\r\n },\r\n meta,\r\n }\r\n }\r\n\r\n async function handleResponse(\r\n response: Response,\r\n responseHandler: ResponseHandler\r\n ) {\r\n if (typeof responseHandler === 'function') {\r\n return responseHandler(response)\r\n }\r\n\r\n if (responseHandler === 'content-type') {\r\n responseHandler = isJsonContentType(response.headers) ? 'json' : 'text'\r\n }\r\n\r\n if (responseHandler === 'json') {\r\n const text = await response.text()\r\n return text.length ? JSON.parse(text) : null\r\n }\r\n\r\n return response.text()\r\n }\r\n}\r\n","import { isAbsoluteUrl } from './isAbsoluteUrl'\r\n\r\nconst withoutTrailingSlash = (url: string) => url.replace(/\\/$/, '')\r\nconst withoutLeadingSlash = (url: string) => url.replace(/^\\//, '')\r\n\r\nexport function joinUrls(\r\n base: string | undefined,\r\n url: string | undefined\r\n): string {\r\n if (!base) {\r\n return url!\r\n }\r\n if (!url) {\r\n return base\r\n }\r\n\r\n if (isAbsoluteUrl(url)) {\r\n return url\r\n }\r\n\r\n const delimiter = base.endsWith('/') || !url.startsWith('?') ? '/' : ''\r\n base = withoutTrailingSlash(base)\r\n url = withoutLeadingSlash(url)\r\n\r\n return `${base}${delimiter}${url}`;\r\n}\r\n","/**\r\n * If either :// or // is present consider it to be an absolute url\r\n *\r\n * @param url string\r\n */\r\n\r\nexport function isAbsoluteUrl(url: string) {\r\n return new RegExp(`(^|:)//`).test(url)\r\n}\r\n","export class HandledError {\r\n constructor(\r\n public readonly value: any,\r\n public readonly meta: any = undefined\r\n ) {}\r\n}\r\n","import type {\r\n BaseQueryApi,\r\n BaseQueryArg,\r\n BaseQueryEnhancer,\r\n BaseQueryExtraOptions,\r\n BaseQueryFn,\r\n} from './baseQueryTypes'\r\nimport type { FetchBaseQueryError } from './fetchBaseQuery'\r\nimport { HandledError } from './HandledError'\r\n\r\n/**\r\n * Exponential backoff based on the attempt number.\r\n *\r\n * @remarks\r\n * 1. 600ms * random(0.4, 1.4)\r\n * 2. 1200ms * random(0.4, 1.4)\r\n * 3. 2400ms * random(0.4, 1.4)\r\n * 4. 4800ms * random(0.4, 1.4)\r\n * 5. 9600ms * random(0.4, 1.4)\r\n *\r\n * @param attempt - Current attempt\r\n * @param maxRetries - Maximum number of retries\r\n */\r\nasync function defaultBackoff(attempt: number = 0, maxRetries: number = 5) {\r\n const attempts = Math.min(attempt, maxRetries)\r\n\r\n const timeout = ~~((Math.random() + 0.4) * (300 << attempts)) // Force a positive int in the case we make this an option\r\n await new Promise((resolve) =>\r\n setTimeout((res: any) => resolve(res), timeout)\r\n )\r\n}\r\n\r\ntype RetryConditionFunction = (\r\n error: FetchBaseQueryError,\r\n args: BaseQueryArg<BaseQueryFn>,\r\n extraArgs: {\r\n attempt: number\r\n baseQueryApi: BaseQueryApi\r\n extraOptions: BaseQueryExtraOptions<BaseQueryFn> & RetryOptions\r\n }\r\n) => boolean\r\n\r\nexport type RetryOptions = {\r\n /**\r\n * Function used to determine delay between retries\r\n */\r\n backoff?: (attempt: number, maxRetries: number) => Promise<void>\r\n} & (\r\n | {\r\n /**\r\n * How many times the query will be retried (default: 5)\r\n */\r\n maxRetries?: number\r\n retryCondition?: undefined\r\n }\r\n | {\r\n /**\r\n * Callback to determine if a retry should be attempted.\r\n * Return `true` for another retry and `false` to quit trying prematurely.\r\n */\r\n retryCondition?: RetryConditionFunction\r\n maxRetries?: undefined\r\n }\r\n)\r\n\r\nfunction fail(e: any): never {\r\n throw Object.assign(new HandledError({ error: e }), {\r\n throwImmediately: true,\r\n })\r\n}\r\n\r\nconst EMPTY_OPTIONS = {}\r\n\r\nconst retryWithBackoff: BaseQueryEnhancer<\r\n unknown,\r\n RetryOptions,\r\n RetryOptions | void\r\n> = (baseQuery, defaultOptions) => async (args, api, extraOptions) => {\r\n // We need to figure out `maxRetries` before we define `defaultRetryCondition.\r\n // This is probably goofy, but ought to work.\r\n // Put our defaults in one array, filter out undefineds, grab the last value.\r\n const possibleMaxRetries: number[] = [\r\n 5,\r\n ((defaultOptions as any) || EMPTY_OPTIONS).maxRetries,\r\n ((extraOptions as any) || EMPTY_OPTIONS).maxRetries,\r\n ].filter(x => x !== undefined)\r\n const [maxRetries] = possibleMaxRetries.slice(-1)\r\n\r\n const defaultRetryCondition: RetryConditionFunction = (_, __, { attempt }) =>\r\n attempt <= maxRetries\r\n\r\n const options: {\r\n maxRetries: number\r\n backoff: typeof defaultBackoff\r\n retryCondition: typeof defaultRetryCondition\r\n } = {\r\n maxRetries,\r\n backoff: defaultBackoff,\r\n retryCondition: defaultRetryCondition,\r\n ...defaultOptions,\r\n ...extraOptions,\r\n }\r\n let retry = 0\r\n\r\n while (true) {\r\n try {\r\n const result = await baseQuery(args, api, extraOptions)\r\n // baseQueries _should_ return an error property, so we should check for that and throw it to continue retrying\r\n if (result.error) {\r\n throw new HandledError(result)\r\n }\r\n return result\r\n } catch (e: any) {\r\n retry++\r\n\r\n if (e.throwImmediately) {\r\n if (e instanceof HandledError) {\r\n return e.value\r\n }\r\n\r\n // We don't know what this is, so we have to rethrow it\r\n throw e\r\n }\r\n\r\n if (\r\n e instanceof HandledError &&\r\n !options.retryCondition(e.value.error as FetchBaseQueryError, args, {\r\n attempt: retry,\r\n baseQueryApi: api,\r\n extraOptions,\r\n })\r\n ) {\r\n return e.value\r\n }\r\n await options.backoff(retry, options.maxRetries)\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * A utility that can wrap `baseQuery` in the API definition to provide retries with a basic exponential backoff.\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * // codeblock-meta title=\"Retry every request 5 times by default\"\r\n * import { createApi, fetchBaseQuery, retry } from '@reduxjs/toolkit/query/react'\r\n * interface Post {\r\n * id: number\r\n * name: string\r\n * }\r\n * type PostsResponse = Post[]\r\n *\r\n * // maxRetries: 5 is the default, and can be omitted. Shown for documentation purposes.\r\n * const staggeredBaseQuery = retry(fetchBaseQuery({ baseUrl: '/' }), { maxRetries: 5 });\r\n * export const api = createApi({\r\n * baseQuery: staggeredBaseQuery,\r\n * endpoints: (build) => ({\r\n * getPosts: build.query<PostsResponse, void>({\r\n * query: () => ({ url: 'posts' }),\r\n * }),\r\n * getPost: build.query<PostsResponse, string>({\r\n * query: (id) => ({ url: `post/${id}` }),\r\n * extraOptions: { maxRetries: 8 }, // You can override the retry behavior on each endpoint\r\n * }),\r\n * }),\r\n * });\r\n *\r\n * export const { useGetPostsQuery, useGetPostQuery } = api;\r\n * ```\r\n */\r\nexport const retry = /* @__PURE__ */ Object.assign(retryWithBackoff, { fail })\r\n","import type {\r\n ThunkDispatch,\r\n ActionCreatorWithoutPayload, // Workaround for API-Extractor\r\n} from '@reduxjs/toolkit'\r\nimport { createAction } from '@reduxjs/toolkit'\r\n\r\nexport const onFocus = /* @__PURE__ */ createAction('__rtkq/focused')\r\nexport const onFocusLost = /* @__PURE__ */ createAction('__rtkq/unfocused')\r\nexport const onOnline = /* @__PURE__ */ createAction('__rtkq/online')\r\nexport const onOffline = /* @__PURE__ */ createAction('__rtkq/offline')\r\n\r\nlet initialized = false\r\n\r\n/**\r\n * A utility used to enable `refetchOnMount` and `refetchOnReconnect` behaviors.\r\n * It requires the dispatch method from your store.\r\n * Calling `setupListeners(store.dispatch)` will configure listeners with the recommended defaults,\r\n * but you have the option of providing a callback for more granular control.\r\n *\r\n * @example\r\n * ```ts\r\n * setupListeners(store.dispatch)\r\n * ```\r\n *\r\n * @param dispatch - The dispatch method from your store\r\n * @param customHandler - An optional callback for more granular control over listener behavior\r\n * @returns Return value of the handler.\r\n * The default handler returns an `unsubscribe` method that can be called to remove the listeners.\r\n */\r\nexport function setupListeners(\r\n dispatch: ThunkDispatch<any, any, any>,\r\n customHandler?: (\r\n dispatch: ThunkDispatch<any, any, any>,\r\n actions: {\r\n onFocus: typeof onFocus\r\n onFocusLost: typeof onFocusLost\r\n onOnline: typeof onOnline\r\n onOffline: typeof onOffline\r\n }\r\n ) => () => void\r\n) {\r\n function defaultHandler() {\r\n const handleFocus = () => dispatch(onFocus())\r\n const handleFocusLost = () => dispatch(onFocusLost())\r\n const handleOnline = () => dispatch(onOnline())\r\n const handleOffline = () => dispatch(onOffline())\r\n const handleVisibilityChange = () => {\r\n if (window.document.visibilityState === 'visible') {\r\n handleFocus()\r\n } else {\r\n handleFocusLost()\r\n }\r\n }\r\n\r\n if (!initialized) {\r\n if (typeof window !== 'undefined' && window.addEventListener) {\r\n // Handle focus events\r\n window.addEventListener(\r\n 'visibilitychange',\r\n handleVisibilityChange,\r\n false\r\n )\r\n window.addEventListener('focus', handleFocus, false)\r\n\r\n // Handle connection events\r\n window.addEventListener('online', handleOnline, false)\r\n window.addEventListener('offline', handleOffline, false)\r\n initialized = true\r\n }\r\n }\r\n const unsubscribe = () => {\r\n window.removeEventListener('focus', handleFocus)\r\n window.removeEventListener('visibilitychange', handleVisibilityChange)\r\n window.removeEventListener('online', handleOnline)\r\n window.removeEventListener('offline', handleOffline)\r\n initialized = false\r\n }\r\n return unsubscribe\r\n }\r\n\r\n return customHandler\r\n ? customHandler(dispatch, { onFocus, onFocusLost, onOffline, onOnline })\r\n : defaultHandler()\r\n}\r\n","import type { AnyAction, ThunkDispatch } from '@reduxjs/toolkit'\r\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs'\r\nimport type { QuerySubState, RootState } from './core/apiState'\r\nimport type {\r\n BaseQueryExtraOptions,\r\n BaseQueryFn,\r\n BaseQueryResult,\r\n BaseQueryArg,\r\n BaseQueryApi,\r\n QueryReturnValue,\r\n BaseQueryError,\r\n BaseQueryMeta,\r\n} from './baseQueryTypes'\r\nimport type {\r\n HasRequiredProps,\r\n MaybePromise,\r\n OmitFromUnion,\r\n CastAny,\r\n NonUndefined,\r\n UnwrapPromise,\r\n} from './tsHelpers'\r\nimport type { NEVER } from './fakeBaseQuery'\r\nimport type { Api } from '@reduxjs/toolkit/query'\r\n\r\nconst resultType = /* @__PURE__ */ Symbol()\r\nconst baseQuery = /* @__PURE__ */ Symbol()\r\n\r\ninterface EndpointDefinitionWithQuery<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ResultType\r\n> {\r\n /**\r\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.\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * // codeblock-meta title=\"query example\"\r\n *\r\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\r\n * interface Post {\r\n * id: number\r\n * name: string\r\n * }\r\n * type PostsResponse = Post[]\r\n *\r\n * const api = createApi({\r\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\r\n * tagTypes: ['Post'],\r\n * endpoints: (build) => ({\r\n * getPosts: build.query<PostsResponse, void>({\r\n * // highlight-start\r\n * query: () => 'posts',\r\n * // highlight-end\r\n * }),\r\n * addPost: build.mutation<Post, Partial<Post>>({\r\n * // highlight-start\r\n * query: (body) => ({\r\n * url: `posts`,\r\n * method: 'POST',\r\n * body,\r\n * }),\r\n * // highlight-end\r\n * invalidatesTags: [{ type: 'Post', id: 'LIST' }],\r\n * }),\r\n * })\r\n * })\r\n * ```\r\n */\r\n query(arg: QueryArg): BaseQueryArg<BaseQuery>\r\n queryFn?: never\r\n /**\r\n * A function to manipulate the data returned by a query or mutation.\r\n */\r\n transformResponse?(\r\n baseQueryReturnValue: BaseQueryResult<BaseQuery>,\r\n meta: BaseQueryMeta<BaseQuery>,\r\n arg: QueryArg\r\n ): ResultType | Promise<ResultType>\r\n /**\r\n * A function to manipulate the data returned by a failed query or mutation.\r\n */\r\n transformErrorResponse?(\r\n baseQueryReturnValue: BaseQueryError<BaseQuery>,\r\n meta: BaseQueryMeta<BaseQuery>,\r\n arg: QueryArg\r\n ): unknown\r\n /**\r\n * Defaults to `true`.\r\n *\r\n * Most apps should leave this setting on. The only time it can be a performance issue\r\n * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and\r\n * you're unable to paginate it.\r\n *\r\n * For details of how this works, please see the below. When it is set to `false`,\r\n * every request will cause subscribed components to rerender, even when the data has not changed.\r\n *\r\n * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing\r\n */\r\n structuralSharing?: boolean\r\n}\r\n\r\ninterface EndpointDefinitionWithQueryFn<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ResultType\r\n> {\r\n /**\r\n * Can be used in place of `query` as an inline function that bypasses `baseQuery` completely for the endpoint.\r\n *\r\n * @example\r\n * ```ts\r\n * // codeblock-meta title=\"Basic queryFn example\"\r\n *\r\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\r\n * interface Post {\r\n * id: number\r\n * name: string\r\n * }\r\n * type PostsResponse = Post[]\r\n *\r\n * const api = createApi({\r\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\r\n * endpoints: (build) => ({\r\n * getPosts: build.query<PostsResponse, void>({\r\n * query: () => 'posts',\r\n * }),\r\n * flipCoin: build.query<'heads' | 'tails', void>({\r\n * // highlight-start\r\n * queryFn(arg, queryApi, extraOptions, baseQuery) {\r\n * const randomVal = Math.random()\r\n * if (randomVal < 0.45) {\r\n * return { data: 'heads' }\r\n * }\r\n * if (randomVal < 0.9) {\r\n * return { data: 'tails' }\r\n * }\r\n * return { error: { status: 500, statusText: 'Internal Server Error', data: \"Coin landed on it's edge!\" } }\r\n * }\r\n * // highlight-end\r\n * })\r\n * })\r\n * })\r\n * ```\r\n */\r\n queryFn(\r\n arg: QueryArg,\r\n api: BaseQueryApi,\r\n extraOptions: BaseQueryExtraOptions<BaseQuery>,\r\n baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>\r\n ): MaybePromise<QueryReturnValue<ResultType, BaseQueryError<BaseQuery>>>\r\n query?: never\r\n transformResponse?: never\r\n transformErrorResponse?: never\r\n /**\r\n * Defaults to `true`.\r\n *\r\n * Most apps should leave this setting on. The only time it can be a performance issue\r\n * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and\r\n * you're unable to paginate it.\r\n *\r\n * For details of how this works, please see the below. When it is set to `false`,\r\n * every request will cause subscribed components to rerender, even when the data has not changed.\r\n *\r\n * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing\r\n */\r\n structuralSharing?: boolean\r\n}\r\n\r\nexport interface BaseEndpointTypes<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ResultType\r\n> {\r\n QueryArg: QueryArg\r\n BaseQuery: BaseQuery\r\n ResultType: ResultType\r\n}\r\n\r\nexport type BaseEndpointDefinition<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ResultType\r\n> = (\r\n | ([CastAny<BaseQueryResult<BaseQuery>, {}>] extends [NEVER]\r\n ? never\r\n : EndpointDefinitionWithQuery<QueryArg, BaseQuery, ResultType>)\r\n | EndpointDefinitionWithQueryFn<QueryArg, BaseQuery, ResultType>\r\n) & {\r\n /* phantom type */\r\n [resultType]?: ResultType\r\n /* phantom type */\r\n [baseQuery]?: BaseQuery\r\n} & HasRequiredProps<\r\n BaseQueryExtraOptions<BaseQuery>,\r\n { extraOptions: BaseQueryExtraOptions<BaseQuery> },\r\n { extraOptions?: BaseQueryExtraOptions<BaseQuery> }\r\n >\r\n\r\nexport enum DefinitionType {\r\n query = 'query',\r\n mutation = 'mutation',\r\n}\r\n\r\nexport type GetResultDescriptionFn<\r\n TagTypes extends string,\r\n ResultType,\r\n QueryArg,\r\n ErrorType,\r\n MetaType\r\n> = (\r\n result: ResultType | undefined,\r\n error: ErrorType | undefined,\r\n arg: QueryArg,\r\n meta: MetaType\r\n) => ReadonlyArray<TagDescription<TagTypes>>\r\n\r\nexport type FullTagDescription<TagType> = {\r\n type: TagType\r\n id?: number | string\r\n}\r\nexport type TagDescription<TagType> = TagType | FullTagDescription<TagType>\r\nexport type ResultDescription<\r\n TagTypes extends string,\r\n ResultType,\r\n QueryArg,\r\n ErrorType,\r\n MetaType\r\n> =\r\n | ReadonlyArray<TagDescription<TagTypes>>\r\n | GetResultDescriptionFn<TagTypes, ResultType, QueryArg, ErrorType, MetaType>\r\n\r\n/** @deprecated please use `onQueryStarted` instead */\r\nexport interface QueryApi<ReducerPath extends string, Context extends {}> {\r\n /** @deprecated please use `onQueryStarted` instead */\r\n dispatch: ThunkDispatch<any, any, AnyAction>\r\n /** @deprecated please use `onQueryStarted` instead */\r\n getState(): RootState<any, any, ReducerPath>\r\n /** @deprecated please use `onQueryStarted` instead */\r\n extra: unknown\r\n /** @deprecated please use `onQueryStarted` instead */\r\n requestId: string\r\n /** @deprecated please use `onQueryStarted` instead */\r\n context: Context\r\n}\r\n\r\nexport interface QueryTypes<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n TagTypes extends string,\r\n ResultType,\r\n ReducerPath extends string = string\r\n> extends BaseEndpointTypes<QueryArg, BaseQuery, ResultType> {\r\n /**\r\n * The endpoint definition type. To be used with some internal generic types.\r\n * @example\r\n * ```ts\r\n * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\r\n * ```\r\n */\r\n QueryDefinition: QueryDefinition<\r\n QueryArg,\r\n BaseQuery,\r\n TagTypes,\r\n ResultType,\r\n ReducerPath\r\n >\r\n TagTypes: TagTypes\r\n ReducerPath: ReducerPath\r\n}\r\n\r\nexport interface QueryExtraOptions<\r\n TagTypes extends string,\r\n ResultType,\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ReducerPath extends string = string\r\n> {\r\n type: DefinitionType.query\r\n /**\r\n * Used by `query` endpoints. Determines which 'tag' is attached to the cached data returned by the query.\r\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.\r\n * 1. `['Post']` - equivalent to `2`\r\n * 2. `[{ type: 'Post' }]` - equivalent to `1`\r\n * 3. `[{ type: 'Post', id: 1 }]`\r\n * 4. `(result, error, arg) => ['Post']` - equivalent to `5`\r\n * 5. `(result, error, arg) => [{ type: 'Post' }]` - equivalent to `4`\r\n * 6. `(result, error, arg) => [{ type: 'Post', id: 1 }]`\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * // codeblock-meta title=\"providesTags example\"\r\n *\r\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\r\n * interface Post {\r\n * id: number\r\n * name: string\r\n * }\r\n * type PostsResponse = Post[]\r\n *\r\n * const api = createApi({\r\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\r\n * tagTypes: ['Posts'],\r\n * endpoints: (build) => ({\r\n * getPosts: build.query<PostsResponse, void>({\r\n * query: () => 'posts',\r\n * // highlight-start\r\n * providesTags: (result) =>\r\n * result\r\n * ? [\r\n * ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\r\n * { type: 'Posts', id: 'LIST' },\r\n * ]\r\n * : [{ type: 'Posts', id: 'LIST' }],\r\n * // highlight-end\r\n * })\r\n * })\r\n * })\r\n * ```\r\n */\r\n providesTags?: ResultDescription<\r\n TagTypes,\r\n ResultType,\r\n QueryArg,\r\n BaseQueryError<BaseQuery>,\r\n BaseQueryMeta<BaseQuery>\r\n >\r\n /**\r\n * Not to be used. A query should not invalidate tags in the cache.\r\n */\r\n invalidatesTags?: never\r\n\r\n /**\r\n * Can be provided to return a custom cache key value based on the query arguments.\r\n *\r\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.\r\n *\r\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.\r\n *\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\r\n *\r\n * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\r\n * interface Post {\r\n * id: number\r\n * name: string\r\n * }\r\n *\r\n * interface MyApiClient {\r\n * fetchPost: (id: string) => Promise<Post>\r\n * }\r\n *\r\n * createApi({\r\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\r\n * endpoints: (build) => ({\r\n * // Example: an endpoint with an API client passed in as an argument,\r\n * // but only the item ID should be used as the cache key\r\n * getPost: build.query<Post, { id: string; client: MyApiClient }>({\r\n * queryFn: async ({ id, client }) => {\r\n * const post = await client.fetchPost(id)\r\n * return { data: post }\r\n * },\r\n * // highlight-start\r\n * serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\r\n * const { id } = queryArgs\r\n * // This can return a string, an object, a number, or a boolean.\r\n * // If it returns an object, number or boolean, that value\r\n * // will be serialized automatically via `defaultSerializeQueryArgs`\r\n * return { id } // omit `client` from the cache key\r\n *\r\n * // Alternately, you can use `defaultSerializeQueryArgs` yourself:\r\n * // return defaultSerializeQueryArgs({\r\n * // endpointName,\r\n * // queryArgs: { id },\r\n * // endpointDefinition\r\n * // })\r\n * // Or create and return a string yourself:\r\n * // return `getPost(${id})`\r\n * },\r\n * // highlight-end\r\n * }),\r\n * }),\r\n *})\r\n * ```\r\n */\r\n serializeQueryArgs?: SerializeQueryArgs<\r\n QueryArg,\r\n string | number | boolean | Record<any, any>\r\n >\r\n\r\n /**\r\n * Can be provided to merge an incoming response value into the current cache data.\r\n * If supplied, no automatic structural sharing will be applied - it's up to\r\n * you to update the cache appropriately.\r\n *\r\n * Since RTKQ normally replaces cache entries with the new response, you will usually\r\n * need to use this with the `serializeQueryArgs` or `forceRefetch` options to keep\r\n * an existing cache entry so that it can be updated.\r\n *\r\n * Since this is wrapped with Immer, you may either mutate the `currentCacheValue` directly,\r\n * or return a new value, but _not_ both at once.\r\n *\r\n * Will only be called if the existing `currentCacheData` is _not_ `undefined` - on first response,\r\n * the cache entry will just save the response data directly.\r\n *\r\n * Useful if you don't want a new request to completely override the current cache value,\r\n * maybe because you have manually updated it from another source and don't want those\r\n * updates to get lost.\r\n *\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * // codeblock-meta title=\"merge: pagination\"\r\n *\r\n * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\r\n * interface Post {\r\n * id: number\r\n * name: string\r\n * }\r\n *\r\n * createApi({\r\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\r\n * endpoints: (build) => ({\r\n * listItems: build.query<string[], number>({\r\n * query: (pageNumber) => `/listItems?page=${pageNumber}`,\r\n * // Only have one cache entry because the arg always maps to one string\r\n * serializeQueryArgs: ({ endpointName }) => {\r\n * return endpointName\r\n * },\r\n * // Always merge incoming data to the cache entry\r\n * merge: (currentCache, newItems) => {\r\n * currentCache.push(...newItems)\r\n * },\r\n * // Refetch when the page arg changes\r\n * forceRefetch({ currentArg, previousArg }) {\r\n * return currentArg !== previousArg\r\n * },\r\n * }),\r\n * }),\r\n *})\r\n * ```\r\n */\r\n merge?(\r\n currentCacheData: ResultType,\r\n responseData: ResultType,\r\n otherArgs: {\r\n arg: QueryArg\r\n baseQueryMeta: BaseQueryMeta<BaseQuery>\r\n requestId: string\r\n fulfilledTimeStamp: number\r\n }\r\n ): ResultType | void\r\n\r\n /**\r\n * Check to see if the endpoint should force a refetch in cases where it normally wouldn't.\r\n * This is primarily useful for \"infinite scroll\" / pagination use cases where\r\n * RTKQ is keeping a single cache entry that is added to over time, in combination\r\n * with `serializeQueryArgs` returning a fixed cache key and a `merge` callback\r\n * set to add incoming data to the cache entry each time.\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * // codeblock-meta title=\"forceRefresh: pagination\"\r\n *\r\n * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\r\n * interface Post {\r\n * id: number\r\n * name: string\r\n * }\r\n *\r\n * createApi({\r\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\r\n * endpoints: (build) => ({\r\n * listItems: build.query<string[], number>({\r\n * query: (pageNumber) => `/listItems?page=${pageNumber}`,\r\n * // Only have one cache entry because the arg always maps to one string\r\n * serializeQueryArgs: ({ endpointName }) => {\r\n * return endpointName\r\n * },\r\n * // Always merge incoming data to the cache entry\r\n * merge: (currentCache, newItems) => {\r\n * currentCache.push(...newItems)\r\n * },\r\n * // Refetch when the page arg changes\r\n * forceRefetch({ currentArg, previousArg }) {\r\n * return currentArg !== previousArg\r\n * },\r\n * }),\r\n * }),\r\n *})\r\n * ```\r\n */\r\n forceRefetch?(params: {\r\n currentArg: QueryArg | undefined\r\n previousArg: QueryArg | undefined\r\n state: RootState<any, any, string>\r\n endpointState?: QuerySubState<any>\r\n }): boolean\r\n\r\n /**\r\n * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\r\n */\r\n Types?: QueryTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>\r\n}\r\n\r\nexport type QueryDefinition<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n TagTypes extends string,\r\n ResultType,\r\n ReducerPath extends string = string\r\n> = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType> &\r\n QueryExtraOptions<TagTypes, ResultType, QueryArg, BaseQuery, ReducerPath>\r\n\r\nexport interface MutationTypes<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n TagTypes extends string,\r\n ResultType,\r\n ReducerPath extends string = string\r\n> extends BaseEndpointTypes<QueryArg, BaseQuery, ResultType> {\r\n /**\r\n * The endpoint definition type. To be used with some internal generic types.\r\n * @example\r\n * ```ts\r\n * const useMyWrappedHook: UseMutation<typeof api.endpoints.query.Types.MutationDefinition> = ...\r\n * ```\r\n */\r\n MutationDefinition: MutationDefinition<\r\n QueryArg,\r\n BaseQuery,\r\n TagTypes,\r\n ResultType,\r\n ReducerPath\r\n >\r\n TagTypes: TagTypes\r\n ReducerPath: ReducerPath\r\n}\r\n\r\nexport interface MutationExtraOptions<\r\n TagTypes extends string,\r\n ResultType,\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ReducerPath extends string = string\r\n> {\r\n type: DefinitionType.mutation\r\n /**\r\n * Used by `mutation` endpoints. Determines which cached data should be either re-fetched or removed from the cache.\r\n * Expects the same shapes as `providesTags`.\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * // codeblock-meta title=\"invalidatesTags example\"\r\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\r\n * interface Post {\r\n * id: number\r\n * name: string\r\n * }\r\n * type PostsResponse = Post[]\r\n *\r\n * const api = createApi({\r\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\r\n * tagTypes: ['Posts'],\r\n * endpoints: (build) => ({\r\n * getPosts: build.query<PostsResponse, void>({\r\n * query: () => 'posts',\r\n * providesTags: (result) =>\r\n * result\r\n * ? [\r\n * ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\r\n * { type: 'Posts', id: 'LIST' },\r\n * ]\r\n * : [{ type: 'Posts', id: 'LIST' }],\r\n * }),\r\n * addPost: build.mutation<Post, Partial<Post>>({\r\n * query(body) {\r\n * return {\r\n * url: `posts`,\r\n * method: 'POST',\r\n * body,\r\n * }\r\n * },\r\n * // highlight-start\r\n * invalidatesTags: [{ type: 'Posts', id: 'LIST' }],\r\n * // highlight-end\r\n * }),\r\n * })\r\n * })\r\n * ```\r\n */\r\n invalidatesTags?: ResultDescription<\r\n TagTypes,\r\n ResultType,\r\n QueryArg,\r\n BaseQueryError<BaseQuery>,\r\n BaseQueryMeta<BaseQuery>\r\n >\r\n /**\r\n * Not to be used. A mutation should not provide tags to the cache.\r\n */\r\n providesTags?: never\r\n\r\n /**\r\n * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\r\n */\r\n Types?: MutationTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>\r\n}\r\n\r\nexport type MutationDefinition<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n TagTypes extends string,\r\n ResultType,\r\n ReducerPath extends string = string\r\n> = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType> &\r\n MutationExtraOptions<TagTypes, ResultType, QueryArg, BaseQuery, ReducerPath>\r\n\r\nexport type EndpointDefinition<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n TagTypes extends string,\r\n ResultType,\r\n ReducerPath extends string = string\r\n> =\r\n | QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>\r\n | MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>\r\n\r\nexport type EndpointDefinitions = Record<\r\n string,\r\n EndpointDefinition<any, any, any, any>\r\n>\r\n\r\nexport function isQueryDefinition(\r\n e: EndpointDefinition<any, any, any, any>\r\n): e is QueryDefinition<any, any, any, any> {\r\n return e.type === DefinitionType.query\r\n}\r\n\r\nexport function isMutationDefinition(\r\n e: EndpointDefinition<any, any, any, any>\r\n): e is MutationDefinition<any, any, any, any> {\r\n return e.type === DefinitionType.mutation\r\n}\r\n\r\nexport type EndpointBuilder<\r\n BaseQuery extends BaseQueryFn,\r\n TagTypes extends string,\r\n ReducerPath extends string\r\n> = {\r\n /**\r\n * An endpoint definition that retrieves data, and may provide tags to the cache.\r\n *\r\n * @example\r\n * ```js\r\n * // codeblock-meta title=\"Example of all query endpoint options\"\r\n * const api = createApi({\r\n * baseQuery,\r\n * endpoints: (build) => ({\r\n * getPost: build.query({\r\n * query: (id) => ({ url: `post/${id}` }),\r\n * // Pick out data and prevent nested properties in a hook or selector\r\n * transformResponse: (response) => response.data,\r\n * // Pick out error and prevent nested properties in a hook or selector\r\n * transformErrorResponse: (response) => response.error,\r\n * // `result` is the server response\r\n * providesTags: (result, error, id) => [{ type: 'Post', id }],\r\n * // trigger side effects or optimistic updates\r\n * onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry, updateCachedData }) {},\r\n * // handle subscriptions etc\r\n * onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry, updateCachedData }) {},\r\n * }),\r\n * }),\r\n *});\r\n *```\r\n */\r\n query<ResultType, QueryArg>(\r\n definition: OmitFromUnion<\r\n QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>,\r\n 'type'\r\n >\r\n ): QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>\r\n /**\r\n * An endpoint definition that alters data on the server or will possibly invalidate the cache.\r\n *\r\n * @example\r\n * ```js\r\n * // codeblock-meta title=\"Example of all mutation endpoint options\"\r\n * const api = createApi({\r\n * baseQuery,\r\n * endpoints: (build) => ({\r\n * updatePost: build.mutation({\r\n * query: ({ id, ...patch }) => ({ url: `post/${id}`, method: 'PATCH', body: patch }),\r\n * // Pick out data and prevent nested properties in a hook or selector\r\n * transformResponse: (response) => response.data,\r\n * // Pick out error and prevent nested properties in a hook or selector\r\n * transformErrorResponse: (response) => response.error,\r\n * // `result` is the server response\r\n * invalidatesTags: (result, error, id) => [{ type: 'Post', id }],\r\n * // trigger side effects or optimistic updates\r\n * onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry }) {},\r\n * // handle subscriptions etc\r\n * onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry }) {},\r\n * }),\r\n * }),\r\n * });\r\n * ```\r\n */\r\n mutation<ResultType, QueryArg>(\r\n definition: OmitFromUnion<\r\n MutationDefinition<\r\n QueryArg,\r\n BaseQuery,\r\n TagTypes,\r\n ResultType,\r\n ReducerPath\r\n >,\r\n 'type'\r\n >\r\n ): MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>\r\n}\r\n\r\nexport type AssertTagTypes = <T extends FullTagDescription<string>>(t: T) => T\r\n\r\nexport function calculateProvidedBy<ResultType, QueryArg, ErrorType, MetaType>(\r\n description:\r\n | ResultDescription<string, ResultType, QueryArg, ErrorType, MetaType>\r\n | undefined,\r\n result: ResultType | undefined,\r\n error: ErrorType | undefined,\r\n queryArg: QueryArg,\r\n meta: MetaType | undefined,\r\n assertTagTypes: AssertTagTypes\r\n): readonly FullTagDescription<string>[] {\r\n if (isFunction(description)) {\r\n return description(\r\n result as ResultType,\r\n error as undefined,\r\n queryArg,\r\n meta as MetaType\r\n )\r\n .map(expandTagDescription)\r\n .map(assertTagTypes)\r\n }\r\n if (Array.isArray(description)) {\r\n return description.map(expandTagDescription).map(assertTagTypes)\r\n }\r\n return []\r\n}\r\n\r\nfunction isFunction<T>(t: T): t is Extract<T, Function> {\r\n return typeof t === 'function'\r\n}\r\n\r\nexport function expandTagDescription(\r\n description: TagDescription<string>\r\n): FullTagDescription<string> {\r\n return typeof description === 'string' ? { type: description } : description\r\n}\r\n\r\nexport type QueryArgFrom<D extends BaseEndpointDefinition<any, any, any>> =\r\n D extends BaseEndpointDefinition<infer QA, any, any> ? QA : unknown\r\nexport type ResultTypeFrom<D extends BaseEndpointDefinition<any, any, any>> =\r\n D extends BaseEndpointDefinition<any, any, infer RT> ? RT : unknown\r\n\r\nexport type ReducerPathFrom<\r\n D extends EndpointDefinition<any, any, any, any, any>\r\n> = D extends EndpointDefinition<any, any, any, any, infer RP> ? RP : unknown\r\n\r\nexport type TagTypesFrom<D extends EndpointDefinition<any, any, any, any>> =\r\n D extends EndpointDefinition<any, any, infer RP, any> ? RP : unknown\r\n\r\nexport type TagTypesFromApi<T> = T extends Api<any, any, any, infer TagTypes>\r\n ? TagTypes\r\n : never\r\n\r\nexport type DefinitionsFromApi<T> = T extends Api<\r\n any,\r\n infer Definitions,\r\n any,\r\n any\r\n>\r\n ? Definitions\r\n : never\r\n\r\nexport type TransformedResponse<\r\n NewDefinitions extends EndpointDefinitions,\r\n K,\r\n ResultType\r\n> = K extends keyof NewDefinitions\r\n ? NewDefinitions[K]['transformResponse'] extends undefined\r\n ? ResultType\r\n : UnwrapPromise<\r\n ReturnType<NonUndefined<NewDefinitions[K]['transformResponse']>>\r\n >\r\n : ResultType\r\n\r\nexport type OverrideResultType<Definition, NewResultType> =\r\n Definition extends QueryDefinition<\r\n infer QueryArg,\r\n infer BaseQuery,\r\n infer TagTypes,\r\n any,\r\n infer ReducerPath\r\n >\r\n ? QueryDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath>\r\n : Definition extends MutationDefinition<\r\n infer QueryArg,\r\n infer BaseQuery,\r\n infer TagTypes,\r\n any,\r\n infer ReducerPath\r\n >\r\n ? MutationDefinition<\r\n QueryArg,\r\n BaseQuery,\r\n TagTypes,\r\n NewResultType,\r\n ReducerPath\r\n >\r\n : never\r\n\r\nexport type UpdateDefinitions<\r\n Definitions extends EndpointDefinitions,\r\n NewTagTypes extends string,\r\n NewDefinitions extends EndpointDefinitions\r\n> = {\r\n [K in keyof Definitions]: Definitions[K] extends QueryDefinition<\r\n infer QueryArg,\r\n infer BaseQuery,\r\n any,\r\n infer ResultType,\r\n infer ReducerPath\r\n >\r\n ? QueryDefinition<\r\n QueryArg,\r\n BaseQuery,\r\n NewTagTypes,\r\n TransformedResponse<NewDefinitions, K, ResultType>,\r\n ReducerPath\r\n >\r\n : Definitions[K] extends MutationDefinition<\r\n infer QueryArg,\r\n infer BaseQuery,\r\n any,\r\n infer ResultType,\r\n infer ReducerPath\r\n >\r\n ? MutationDefinition<\r\n QueryArg,\r\n BaseQuery,\r\n NewTagTypes,\r\n TransformedResponse<NewDefinitions, K, ResultType>,\r\n ReducerPath\r\n >\r\n : never\r\n}\r\n","import { createNextState, createSelector } from '@reduxjs/toolkit'\r\nimport type {\r\n MutationSubState,\r\n QuerySubState,\r\n RootState as _RootState,\r\n RequestStatusFlags,\r\n QueryCacheKey,\r\n} from './apiState'\r\nimport { QueryStatus, getRequestStatusFlags } from './apiState'\r\nimport type {\r\n EndpointDefinitions,\r\n QueryDefinition,\r\n MutationDefinition,\r\n QueryArgFrom,\r\n TagTypesFrom,\r\n ReducerPathFrom,\r\n TagDescription,\r\n} from '../endpointDefinitions'\r\nimport { expandTagDescription } from '../endpointDefinitions'\r\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'\r\nimport { getMutationCacheKey } from './buildSlice'\r\nimport { flatten } from '../utils'\r\n\r\nexport type SkipToken = typeof skipToken\r\n/**\r\n * Can be passed into `useQuery`, `useQueryState` or `useQuerySubscription`\r\n * instead of the query argument to get the same effect as if setting\r\n * `skip: true` in the query options.\r\n *\r\n * Useful for scenarios where a query should be skipped when `arg` is `undefined`\r\n * and TypeScript complains about it because `arg` is not allowed to be passed\r\n * in as `undefined`, such as\r\n *\r\n * ```ts\r\n * // codeblock-meta title=\"will error if the query argument is not allowed to be undefined\" no-transpile\r\n * useSomeQuery(arg, { skip: !!arg })\r\n * ```\r\n *\r\n * ```ts\r\n * // codeblock-meta title=\"using skipToken instead\" no-transpile\r\n * useSomeQuery(arg ?? skipToken)\r\n * ```\r\n *\r\n * If passed directly into a query or mutation selector, that selector will always\r\n * return an uninitialized state.\r\n */\r\nexport const skipToken = /* @__PURE__ */ Symbol.for('RTKQ/skipToken')\r\n/** @deprecated renamed to `skipToken` */\r\nexport const skipSelector = skipToken\r\n\r\ndeclare module './module' {\r\n export interface ApiEndpointQuery<\r\n Definition extends QueryDefinition<any, any, any, any, any>,\r\n Definitions extends EndpointDefinitions\r\n > {\r\n select: QueryResultSelectorFactory<\r\n Definition,\r\n _RootState<\r\n Definitions,\r\n TagTypesFrom<Definition>,\r\n ReducerPathFrom<Definition>\r\n >\r\n >\r\n }\r\n\r\n export interface ApiEndpointMutation<\r\n Definition extends MutationDefinition<any, any, any, any, any>,\r\n Definitions extends EndpointDefinitions\r\n > {\r\n select: MutationResultSelectorFactory<\r\n Definition,\r\n _RootState<\r\n Definitions,\r\n TagTypesFrom<Definition>,\r\n ReducerPathFrom<Definition>\r\n >\r\n >\r\n }\r\n}\r\n\r\ntype QueryResultSelectorFactory<\r\n Definition extends QueryDefinition<any, any, any, any>,\r\n RootState\r\n> = (\r\n queryArg: QueryArgFrom<Definition> | SkipToken\r\n) => (state: RootState) => QueryResultSelectorResult<Definition>\r\n\r\nexport type QueryResultSelectorResult<\r\n Definition extends QueryDefinition<any, any, any, any>\r\n> = QuerySubState<Definition> & RequestStatusFlags\r\n\r\ntype MutationResultSelectorFactory<\r\n Definition extends MutationDefinition<any, any, any, any>,\r\n RootState\r\n> = (\r\n requestId:\r\n | string\r\n | { requestId: string | undefined; fixedCacheKey: string | undefined }\r\n | SkipToken\r\n) => (state: RootState) => MutationResultSelectorResult<Definition>\r\n\r\nexport type MutationResultSelectorResult<\r\n Definition extends MutationDefinition<any, any, any, any>\r\n> = MutationSubState<Definition> & RequestStatusFlags\r\n\r\nconst initialSubState: QuerySubState<any> = {\r\n status: QueryStatus.uninitialized as const,\r\n}\r\n\r\n// abuse immer to freeze default states\r\nconst defaultQuerySubState = /* @__PURE__ */ createNextState(\r\n initialSubState,\r\n () => {}\r\n)\r\nconst defaultMutationSubState = /* @__PURE__ */ createNextState(\r\n initialSubState as MutationSubState<any>,\r\n () => {}\r\n)\r\n\r\nexport function buildSelectors<\r\n Definitions extends EndpointDefinitions,\r\n ReducerPath extends string\r\n>({\r\n serializeQueryArgs,\r\n reducerPath,\r\n}: {\r\n serializeQueryArgs: InternalSerializeQueryArgs\r\n reducerPath: ReducerPath\r\n}) {\r\n type RootState = _RootState<Definitions, string, string>\r\n\r\n const selectSkippedQuery = (state: RootState) => defaultQuerySubState\r\n const selectSkippedMutation = (state: RootState) => defaultMutationSubState\r\n\r\n return { buildQuerySelector, buildMutationSelector, selectInvalidatedBy }\r\n\r\n function withRequestFlags<T extends { status: QueryStatus }>(\r\n substate: T\r\n ): T & RequestStatusFlags {\r\n return {\r\n ...substate,\r\n ...getRequestStatusFlags(substate.status),\r\n }\r\n }\r\n\r\n function selectInternalState(rootState: RootState) {\r\n const state = rootState[reducerPath]\r\n if (process.env.NODE_ENV !== 'production') {\r\n if (!state) {\r\n if ((selectInternalState as any).triggered) return state\r\n ;(selectInternalState as any).triggered = true\r\n console.error(\r\n `Error: No data found at \\`state.${reducerPath}\\`. Did you forget to add the reducer to the store?`\r\n )\r\n }\r\n }\r\n return state\r\n }\r\n\r\n function buildQuerySelector(\r\n endpointName: string,\r\n endpointDefinition: QueryDefinition<any, any, any, any>\r\n ) {\r\n return ((queryArgs: any) => {\r\n const serializedArgs = serializeQueryArgs({\r\n queryArgs,\r\n endpointDefinition,\r\n endpointName,\r\n })\r\n const selectQuerySubstate = (state: RootState) =>\r\n selectInternalState(state)?.queries?.[serializedArgs] ??\r\n defaultQuerySubState\r\n const finalSelectQuerySubState =\r\n queryArgs === skipToken ? selectSkippedQuery : selectQuerySubstate\r\n\r\n return createSelector(finalSelectQuerySubState, withRequestFlags)\r\n }) as QueryResultSelectorFactory<any, RootState>\r\n }\r\n\r\n function buildMutationSelector() {\r\n return ((id) => {\r\n let mutationId: string | typeof skipToken\r\n if (typeof id === 'object') {\r\n mutationId = getMutationCacheKey(id) ?? skipToken\r\n } else {\r\n mutationId = id\r\n }\r\n const selectMutationSubstate = (state: RootState) =>\r\n selectInternalState(state)?.mutations?.[mutationId as string] ??\r\n defaultMutationSubState\r\n const finalSelectMutationSubstate =\r\n mutationId === skipToken\r\n ? selectSkippedMutation\r\n : selectMutationSubstate\r\n\r\n return createSelector(finalSelectMutationSubstate, withRequestFlags)\r\n }) as MutationResultSelectorFactory<any, RootState>\r\n }\r\n\r\n function selectInvalidatedBy(\r\n state: RootState,\r\n tags: ReadonlyArray<TagDescription<string>>\r\n ): Array<{\r\n endpointName: string\r\n originalArgs: any\r\n queryCacheKey: QueryCacheKey\r\n }> {\r\n const apiState = state[reducerPath]\r\n const toInvalidate = new Set<QueryCacheKey>()\r\n for (const tag of tags.map(expandTagDescription)) {\r\n const provided = apiState.provided[tag.type]\r\n if (!provided) {\r\n continue\r\n }\r\n\r\n let invalidateSubscriptions =\r\n (tag.id !== undefined\r\n ? // id given: invalidate all queries that provide this type & id\r\n provided[tag.id]\r\n : // no id: invalidate all queries that provide this type\r\n flatten(Object.values(provided))) ?? []\r\n\r\n for (const invalidate of invalidateSubscriptions) {\r\n toInvalidate.add(invalidate)\r\n }\r\n }\r\n\r\n return flatten(\r\n Array.from(toInvalidate.values()).map((queryCacheKey) => {\r\n const querySubState = apiState.queries[queryCacheKey]\r\n return querySubState\r\n ? [\r\n {\r\n queryCacheKey,\r\n endpointName: querySubState.endpointName!,\r\n originalArgs: querySubState.originalArgs,\r\n },\r\n ]\r\n : []\r\n })\r\n )\r\n }\r\n}\r\n","import type { AnyAction, PayloadAction } from '@reduxjs/toolkit'\r\nimport {\r\n combineReducers,\r\n createAction,\r\n createSlice,\r\n isAnyOf,\r\n isFulfilled,\r\n isRejectedWithValue,\r\n createNextState,\r\n prepareAutoBatched,\r\n} from '@reduxjs/toolkit'\r\nimport type {\r\n CombinedState as CombinedQueryState,\r\n QuerySubstateIdentifier,\r\n QuerySubState,\r\n MutationSubstateIdentifier,\r\n MutationSubState,\r\n MutationState,\r\n QueryState,\r\n InvalidationState,\r\n Subscribers,\r\n QueryCacheKey,\r\n SubscriptionState,\r\n ConfigState,\r\n} from './apiState'\r\nimport { QueryStatus } from './apiState'\r\nimport type { MutationThunk, QueryThunk, RejectedAction } from './buildThunks'\r\nimport { calculateProvidedByThunk } from './buildThunks'\r\nimport type {\r\n AssertTagTypes,\r\n EndpointDefinitions,\r\n FullTagDescription,\r\n QueryDefinition,\r\n} from '../endpointDefinitions'\r\nimport type { Patch } from 'immer'\r\nimport { isDraft } from 'immer'\r\nimport { applyPatches, original } from 'immer'\r\nimport { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners'\r\nimport {\r\n isDocumentVisible,\r\n isOnline,\r\n copyWithStructuralSharing,\r\n} from '../utils'\r\nimport type { ApiContext } from '../apiTypes'\r\nimport { isUpsertQuery } from './buildInitiate'\r\n\r\nfunction updateQuerySubstateIfExists(\r\n state: QueryState<any>,\r\n queryCacheKey: QueryCacheKey,\r\n update: (substate: QuerySubState<any>) => void\r\n) {\r\n const substate = state[queryCacheKey]\r\n if (substate) {\r\n update(substate)\r\n }\r\n}\r\n\r\nexport function getMutationCacheKey(\r\n id:\r\n | MutationSubstateIdentifier\r\n | { requestId: string; arg: { fixedCacheKey?: string | undefined } }\r\n): string\r\nexport function getMutationCacheKey(id: {\r\n fixedCacheKey?: string\r\n requestId?: string\r\n}): string | undefined\r\n\r\nexport function getMutationCacheKey(\r\n id:\r\n | { fixedCacheKey?: string; requestId?: string }\r\n | MutationSubstateIdentifier\r\n | { requestId: string; arg: { fixedCacheKey?: string | undefined } }\r\n): string | undefined {\r\n return ('arg' in id ? id.arg.fixedCacheKey : id.fixedCacheKey) ?? id.requestId\r\n}\r\n\r\nfunction updateMutationSubstateIfExists(\r\n state: MutationState<any>,\r\n id:\r\n | MutationSubstateIdentifier\r\n | { requestId: string; arg: { fixedCacheKey?: string | undefined } },\r\n update: (substate: MutationSubState<any>) => void\r\n) {\r\n const substate = state[getMutationCacheKey(id)]\r\n if (substate) {\r\n update(substate)\r\n }\r\n}\r\n\r\nconst initialState = {} as any\r\n\r\nexport function buildSlice({\r\n reducerPath,\r\n queryThunk,\r\n mutationThunk,\r\n context: {\r\n endpointDefinitions: definitions,\r\n apiUid,\r\n extractRehydrationInfo,\r\n hasRehydrationInfo,\r\n },\r\n assertTagType,\r\n config,\r\n}: {\r\n reducerPath: string\r\n queryThunk: QueryThunk\r\n mutationThunk: MutationThunk\r\n context: ApiContext<EndpointDefinitions>\r\n assertTagType: AssertTagTypes\r\n config: Omit<\r\n ConfigState<string>,\r\n 'online' | 'focused' | 'middlewareRegistered'\r\n >\r\n}) {\r\n const resetApiState = createAction(`${reducerPath}/resetApiState`)\r\n const querySlice = createSlice({\r\n name: `${reducerPath}/queries`,\r\n initialState: initialState as QueryState<any>,\r\n reducers: {\r\n removeQueryResult: {\r\n reducer(\r\n draft,\r\n { payload: { queryCacheKey } }: PayloadAction<QuerySubstateIdentifier>\r\n ) {\r\n delete draft[queryCacheKey]\r\n },\r\n prepare: prepareAutoBatched<QuerySubstateIdentifier>(),\r\n },\r\n queryResultPatched: {\r\n reducer(\r\n draft,\r\n {\r\n payload: { queryCacheKey, patches },\r\n }: PayloadAction<\r\n QuerySubstateIdentifier & { patches: readonly Patch[] }\r\n >\r\n ) {\r\n updateQuerySubstateIfExists(draft, queryCacheKey, (substate) => {\r\n substate.data = applyPatches(substate.data as any, patches.concat())\r\n })\r\n },\r\n prepare: prepareAutoBatched<\r\n QuerySubstateIdentifier & { patches: readonly Patch[] }\r\n >(),\r\n },\r\n },\r\n extraReducers(builder) {\r\n builder\r\n .addCase(queryThunk.pending, (draft, { meta, meta: { arg } }) => {\r\n const upserting = isUpsertQuery(arg)\r\n if (arg.subscribe || upserting) {\r\n // only initialize substate if we want to subscribe to it\r\n draft[arg.queryCacheKey] ??= {\r\n status: QueryStatus.uninitialized,\r\n endpointName: arg.endpointName,\r\n }\r\n }\r\n\r\n updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {\r\n substate.status = QueryStatus.pending\r\n\r\n substate.requestId =\r\n upserting && substate.requestId\r\n ? // for `upsertQuery` **updates**, keep the current `requestId`\r\n substate.requestId\r\n : // for normal queries or `upsertQuery` **inserts** always update the `requestId`\r\n meta.requestId\r\n if (arg.originalArgs !== undefined) {\r\n substate.originalArgs = arg.originalArgs\r\n }\r\n substate.startedTimeStamp = meta.startedTimeStamp\r\n })\r\n })\r\n .addCase(queryThunk.fulfilled, (draft, { meta, payload }) => {\r\n updateQuerySubstateIfExists(\r\n draft,\r\n meta.arg.queryCacheKey,\r\n (substate) => {\r\n if (\r\n substate.requestId !== meta.requestId &&\r\n !isUpsertQuery(meta.arg)\r\n )\r\n return\r\n const { merge } = definitions[\r\n meta.arg.endpointName\r\n ] as QueryDefinition<any, any, any, any>\r\n substate.status = QueryStatus.fulfilled\r\n\r\n if (merge) {\r\n if (substate.data !== undefined) {\r\n const { fulfilledTimeStamp, arg, baseQueryMeta, requestId } =\r\n meta\r\n // There's existing cache data. Let the user merge it in themselves.\r\n // We're already inside an Immer-powered reducer, and the user could just mutate `substate.data`\r\n // themselves inside of `merge()`. But, they might also want to return a new value.\r\n // Try to let Immer figure that part out, save the result, and assign it to `substate.data`.\r\n let newData = createNextState(\r\n substate.data,\r\n (draftSubstateData) => {\r\n // As usual with Immer, you can mutate _or_ return inside here, but not both\r\n return merge(draftSubstateData, payload, {\r\n arg: arg.originalArgs,\r\n baseQueryMeta,\r\n fulfilledTimeStamp,\r\n requestId,\r\n })\r\n }\r\n )\r\n substate.data = newData\r\n } else {\r\n // Presumably a fresh request. Just cache the response data.\r\n substate.data = payload\r\n }\r\n } else {\r\n // Assign or safely update the cache data.\r\n substate.data =\r\n definitions[meta.arg.endpointName].structuralSharing ?? true\r\n ? copyWithStructuralSharing(\r\n isDraft(substate.data)\r\n ? original(substate.data)\r\n : substate.data,\r\n payload\r\n )\r\n : payload\r\n }\r\n\r\n delete substate.error\r\n substate.fulfilledTimeStamp = meta.fulfilledTimeStamp\r\n }\r\n )\r\n })\r\n .addCase(\r\n queryThunk.rejected,\r\n (draft, { meta: { condition, arg, requestId }, error, payload }) => {\r\n updateQuerySubstateIfExists(\r\n draft,\r\n arg.queryCacheKey,\r\n (substate) => {\r\n if (condition) {\r\n // request was aborted due to condition (another query already running)\r\n } else {\r\n // request failed\r\n if (substate.requestId !== requestId) return\r\n substate.status = QueryStatus.rejected\r\n substate.error = (payload ?? error) as any\r\n }\r\n }\r\n )\r\n }\r\n )\r\n .addMatcher(hasRehydrationInfo, (draft, action) => {\r\n const { queries } = extractRehydrationInfo(action)!\r\n for (const [key, entry] of Object.entries(queries)) {\r\n if (\r\n // do not rehydrate entries that were currently in flight.\r\n entry?.status === QueryStatus.fulfilled ||\r\n entry?.status === QueryStatus.rejected\r\n ) {\r\n draft[key] = entry\r\n }\r\n }\r\n })\r\n },\r\n })\r\n const mutationSlice = createSlice({\r\n name: `${reducerPath}/mutations`,\r\n initialState: initialState as MutationState<any>,\r\n reducers: {\r\n removeMutationResult: {\r\n reducer(draft, { payload }: PayloadAction<MutationSubstateIdentifier>) {\r\n const cacheKey = getMutationCacheKey(payload)\r\n if (cacheKey in draft) {\r\n delete draft[cacheKey]\r\n }\r\n },\r\n prepare: prepareAutoBatched<MutationSubstateIdentifier>(),\r\n },\r\n },\r\n extraReducers(builder) {\r\n builder\r\n .addCase(\r\n mutationThunk.pending,\r\n (draft, { meta, meta: { requestId, arg, startedTimeStamp } }) => {\r\n if (!arg.track) return\r\n\r\n draft[getMutationCacheKey(meta)] = {\r\n requestId,\r\n status: QueryStatus.pending,\r\n endpointName: arg.endpointName,\r\n startedTimeStamp,\r\n }\r\n }\r\n )\r\n .addCase(mutationThunk.fulfilled, (draft, { payload, meta }) => {\r\n if (!meta.arg.track) return\r\n\r\n updateMutationSubstateIfExists(draft, meta, (substate) => {\r\n if (substate.requestId !== meta.requestId) return\r\n substate.status = QueryStatus.fulfilled\r\n substate.data = payload\r\n substate.fulfilledTimeStamp = meta.fulfilledTimeStamp\r\n })\r\n })\r\n .addCase(mutationThunk.rejected, (draft, { payload, error, meta }) => {\r\n if (!meta.arg.track) return\r\n\r\n updateMutationSubstateIfExists(draft, meta, (substate) => {\r\n if (substate.requestId !== meta.requestId) return\r\n\r\n substate.status = QueryStatus.rejected\r\n substate.error = (payload ?? error) as any\r\n })\r\n })\r\n .addMatcher(hasRehydrationInfo, (draft, action) => {\r\n const { mutations } = extractRehydrationInfo(action)!\r\n for (const [key, entry] of Object.entries(mutations)) {\r\n if (\r\n // do not rehydrate entries that were currently in flight.\r\n (entry?.status === QueryStatus.fulfilled ||\r\n entry?.status === QueryStatus.rejected) &&\r\n // only rehydrate endpoints that were persisted using a `fixedCacheKey`\r\n key !== entry?.requestId\r\n ) {\r\n draft[key] = entry\r\n }\r\n }\r\n })\r\n },\r\n })\r\n\r\n const invalidationSlice = createSlice({\r\n name: `${reducerPath}/invalidation`,\r\n initialState: initialState as InvalidationState<string>,\r\n reducers: {\r\n updateProvidedBy: {\r\n reducer(\r\n draft,\r\n action: PayloadAction<{\r\n queryCacheKey: QueryCacheKey\r\n providedTags: readonly FullTagDescription<string>[]\r\n }>\r\n ) {\r\n const { queryCacheKey, providedTags } = action.payload\r\n\r\n for (const tagTypeSubscriptions of Object.values(draft)) {\r\n for (const idSubscriptions of Object.values(tagTypeSubscriptions)) {\r\n const foundAt = idSubscriptions.indexOf(queryCacheKey)\r\n if (foundAt !== -1) {\r\n idSubscriptions.splice(foundAt, 1)\r\n }\r\n }\r\n }\r\n\r\n for (const { type, id } of providedTags) {\r\n const subscribedQueries = ((draft[type] ??= {})[\r\n id || '__internal_without_id'\r\n ] ??= [])\r\n const alreadySubscribed = subscribedQueries.includes(queryCacheKey)\r\n if (!alreadySubscribed) {\r\n subscribedQueries.push(queryCacheKey)\r\n }\r\n }\r\n },\r\n prepare: prepareAutoBatched<{\r\n queryCacheKey: QueryCacheKey\r\n providedTags: readonly FullTagDescription<string>[]\r\n }>(),\r\n },\r\n },\r\n extraReducers(builder) {\r\n builder\r\n .addCase(\r\n querySlice.actions.removeQueryResult,\r\n (draft, { payload: { queryCacheKey } }) => {\r\n for (const tagTypeSubscriptions of Object.values(draft)) {\r\n for (const idSubscriptions of Object.values(\r\n tagTypeSubscriptions\r\n )) {\r\n const foundAt = idSubscriptions.indexOf(queryCacheKey)\r\n if (foundAt !== -1) {\r\n idSubscriptions.splice(foundAt, 1)\r\n }\r\n }\r\n }\r\n }\r\n )\r\n .addMatcher(hasRehydrationInfo, (draft, action) => {\r\n const { provided } = extractRehydrationInfo(action)!\r\n for (const [type, incomingTags] of Object.entries(provided)) {\r\n for (const [id, cacheKeys] of Object.entries(incomingTags)) {\r\n const subscribedQueries = ((draft[type] ??= {})[\r\n id || '__internal_without_id'\r\n ] ??= [])\r\n for (const queryCacheKey of cacheKeys) {\r\n const alreadySubscribed =\r\n subscribedQueries.includes(queryCacheKey)\r\n if (!alreadySubscribed) {\r\n subscribedQueries.push(queryCacheKey)\r\n }\r\n }\r\n }\r\n }\r\n })\r\n .addMatcher(\r\n isAnyOf(isFulfilled(queryThunk), isRejectedWithValue(queryThunk)),\r\n (draft, action) => {\r\n const providedTags = calculateProvidedByThunk(\r\n action,\r\n 'providesTags',\r\n definitions,\r\n assertTagType\r\n )\r\n const { queryCacheKey } = action.meta.arg\r\n\r\n invalidationSlice.caseReducers.updateProvidedBy(\r\n draft,\r\n invalidationSlice.actions.updateProvidedBy({\r\n queryCacheKey,\r\n providedTags,\r\n })\r\n )\r\n }\r\n )\r\n },\r\n })\r\n\r\n // Dummy slice to generate actions\r\n const subscriptionSlice = createSlice({\r\n name: `${reducerPath}/subscriptions`,\r\n initialState: initialState as SubscriptionState,\r\n reducers: {\r\n updateSubscriptionOptions(\r\n d,\r\n a: PayloadAction<\r\n {\r\n endpointName: string\r\n requestId: string\r\n options: Subscribers[number]\r\n } & QuerySubstateIdentifier\r\n >\r\n ) {\r\n // Dummy\r\n },\r\n unsubscribeQueryResult(\r\n d,\r\n a: PayloadAction<{ requestId: string } & QuerySubstateIdentifier>\r\n ) {\r\n // Dummy\r\n },\r\n internal_probeSubscription(\r\n d,\r\n a: PayloadAction<{ queryCacheKey: string; requestId: string }>\r\n ) {\r\n // dummy\r\n },\r\n },\r\n })\r\n\r\n const internalSubscriptionsSlice = createSlice({\r\n name: `${reducerPath}/internalSubscriptions`,\r\n initialState: initialState as SubscriptionState,\r\n reducers: {\r\n subscriptionsUpdated: {\r\n reducer(state, action: PayloadAction<Patch[]>) {\r\n return applyPatches(state, action.payload)\r\n },\r\n prepare: prepareAutoBatched<Patch[]>(),\r\n },\r\n },\r\n })\r\n\r\n const configSlice = createSlice({\r\n name: `${reducerPath}/config`,\r\n initialState: {\r\n online: isOnline(),\r\n focused: isDocumentVisible(),\r\n middlewareRegistered: false,\r\n ...config,\r\n } as ConfigState<string>,\r\n reducers: {\r\n middlewareRegistered(state, { payload }: PayloadAction<string>) {\r\n state.middlewareRegistered =\r\n state.middlewareRegistered === 'conflict' || apiUid !== payload\r\n ? 'conflict'\r\n : true\r\n },\r\n },\r\n extraReducers: (builder) => {\r\n builder\r\n .addCase(onOnline, (state) => {\r\n state.online = true\r\n })\r\n .addCase(onOffline, (state) => {\r\n state.online = false\r\n })\r\n .addCase(onFocus, (state) => {\r\n state.focused = true\r\n })\r\n .addCase(onFocusLost, (state) => {\r\n state.focused = false\r\n })\r\n // update the state to be a new object to be picked up as a \"state change\"\r\n // by redux-persist's `autoMergeLevel2`\r\n .addMatcher(hasRehydrationInfo, (draft) => ({ ...draft }))\r\n },\r\n })\r\n\r\n const combinedReducer = combineReducers<\r\n CombinedQueryState<any, string, string>\r\n >({\r\n queries: querySlice.reducer,\r\n mutations: mutationSlice.reducer,\r\n provided: invalidationSlice.reducer,\r\n subscriptions: internalSubscriptionsSlice.reducer,\r\n config: configSlice.reducer,\r\n })\r\n\r\n const reducer: typeof combinedReducer = (state, action) =>\r\n combinedReducer(resetApiState.match(action) ? undefined : state, action)\r\n\r\n const actions = {\r\n ...configSlice.actions,\r\n ...querySlice.actions,\r\n ...subscriptionSlice.actions,\r\n ...internalSubscriptionsSlice.actions,\r\n ...mutationSlice.actions,\r\n ...invalidationSlice.actions,\r\n /** @deprecated has been renamed to `removeMutationResult` */\r\n unsubscribeMutationResult: mutationSlice.actions.removeMutationResult,\r\n resetApiState,\r\n }\r\n\r\n return { reducer, actions }\r\n}\r\nexport type SliceActions = ReturnType<typeof buildSlice>['actions']\r\n","export function isNotNullish<T>(v: T | null | undefined): v is T {\r\n return v != null\r\n}\r\n","import type {\r\n EndpointDefinitions,\r\n QueryDefinition,\r\n MutationDefinition,\r\n QueryArgFrom,\r\n ResultTypeFrom,\r\n} from '../endpointDefinitions'\r\nimport { DefinitionType, isQueryDefinition } from '../endpointDefinitions'\r\nimport type { QueryThunk, MutationThunk, QueryThunkArg } from './buildThunks'\r\nimport type { AnyAction, ThunkAction, SerializedError } from '@reduxjs/toolkit'\r\nimport type { SubscriptionOptions, RootState } from './apiState'\r\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'\r\nimport type { Api, ApiContext } from '../apiTypes'\r\nimport type { ApiEndpointQuery } from './module'\r\nimport type { BaseQueryError, QueryReturnValue } from '../baseQueryTypes'\r\nimport type { QueryResultSelectorResult } from './buildSelectors'\r\nimport type { Dispatch } from 'redux'\r\nimport { isNotNullish } from '../utils/isNotNullish'\r\n\r\ndeclare module './module' {\r\n export interface ApiEndpointQuery<\r\n Definition extends QueryDefinition<any, any, any, any, any>,\r\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\r\n Definitions extends EndpointDefinitions\r\n > {\r\n initiate: StartQueryActionCreator<Definition>\r\n }\r\n\r\n export interface ApiEndpointMutation<\r\n Definition extends MutationDefinition<any, any, any, any, any>,\r\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\r\n Definitions extends EndpointDefinitions\r\n > {\r\n initiate: StartMutationActionCreator<Definition>\r\n }\r\n}\r\n\r\nexport const forceQueryFnSymbol = Symbol('forceQueryFn')\r\nexport const isUpsertQuery = (arg: QueryThunkArg) =>\r\n typeof arg[forceQueryFnSymbol] === 'function'\r\n\r\nexport interface StartQueryActionCreatorOptions {\r\n subscribe?: boolean\r\n forceRefetch?: boolean | number\r\n subscriptionOptions?: SubscriptionOptions\r\n [forceQueryFnSymbol]?: () => QueryReturnValue\r\n}\r\n\r\ntype StartQueryActionCreator<\r\n D extends QueryDefinition<any, any, any, any, any>\r\n> = (\r\n arg: QueryArgFrom<D>,\r\n options?: StartQueryActionCreatorOptions\r\n) => ThunkAction<QueryActionCreatorResult<D>, any, any, AnyAction>\r\n\r\nexport type QueryActionCreatorResult<\r\n D extends QueryDefinition<any, any, any, any>\r\n> = Promise<QueryResultSelectorResult<D>> & {\r\n arg: QueryArgFrom<D>\r\n requestId: string\r\n subscriptionOptions: SubscriptionOptions | undefined\r\n abort(): void\r\n unwrap(): Promise<ResultTypeFrom<D>>\r\n unsubscribe(): void\r\n refetch(): QueryActionCreatorResult<D>\r\n updateSubscriptionOptions(options: SubscriptionOptions): void\r\n queryCacheKey: string\r\n}\r\n\r\ntype StartMutationActionCreator<\r\n D extends MutationDefinition<any, any, any, any>\r\n> = (\r\n arg: QueryArgFrom<D>,\r\n options?: {\r\n /**\r\n * If this mutation should be tracked in the store.\r\n * If you just want to manually trigger this mutation using `dispatch` and don't care about the\r\n * result, state & potential errors being held in store, you can set this to false.\r\n * (defaults to `true`)\r\n */\r\n track?: boolean\r\n fixedCacheKey?: string\r\n }\r\n) => ThunkAction<MutationActionCreatorResult<D>, any, any, AnyAction>\r\n\r\nexport type MutationActionCreatorResult<\r\n D extends MutationDefinition<any, any, any, any>\r\n> = Promise<\r\n | { data: ResultTypeFrom<D> }\r\n | {\r\n error:\r\n | Exclude<\r\n BaseQueryError<\r\n D extends MutationDefinition<any, infer BaseQuery, any, any>\r\n ? BaseQuery\r\n : never\r\n >,\r\n undefined\r\n >\r\n | SerializedError\r\n }\r\n> & {\r\n /** @internal */\r\n arg: {\r\n /**\r\n * The name of the given endpoint for the mutation\r\n */\r\n endpointName: string\r\n /**\r\n * The original arguments supplied to the mutation call\r\n */\r\n originalArgs: QueryArgFrom<D>\r\n /**\r\n * Whether the mutation is being tracked in the store.\r\n */\r\n track?: boolean\r\n fixedCacheKey?: string\r\n }\r\n /**\r\n * A unique string generated for the request sequence\r\n */\r\n requestId: string\r\n\r\n /**\r\n * A method to cancel the mutation promise. Note that this is not intended to prevent the mutation\r\n * that was fired off from reaching the server, but only to assist in handling the response.\r\n *\r\n * Calling `abort()` prior to the promise resolving will force it to reach the error state with\r\n * the serialized error:\r\n * `{ name: 'AbortError', message: 'Aborted' }`\r\n *\r\n * @example\r\n * ```ts\r\n * const [updateUser] = useUpdateUserMutation();\r\n *\r\n * useEffect(() => {\r\n * const promise = updateUser(id);\r\n * promise\r\n * .unwrap()\r\n * .catch((err) => {\r\n * if (err.name === 'AbortError') return;\r\n * // else handle the unexpected error\r\n * })\r\n *\r\n * return () => {\r\n * promise.abort();\r\n * }\r\n * }, [id, updateUser])\r\n * ```\r\n */\r\n abort(): void\r\n /**\r\n * Unwraps a mutation call to provide the raw response/error.\r\n *\r\n * @remarks\r\n * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().\r\n *\r\n * @example\r\n * ```ts\r\n * // codeblock-meta title=\"Using .unwrap\"\r\n * addPost({ id: 1, name: 'Example' })\r\n * .unwrap()\r\n * .then((payload) => console.log('fulfilled', payload))\r\n * .catch((error) => console.error('rejected', error));\r\n * ```\r\n *\r\n * @example\r\n * ```ts\r\n * // codeblock-meta title=\"Using .unwrap with async await\"\r\n * try {\r\n * const payload = await addPost({ id: 1, name: 'Example' }).unwrap();\r\n * console.log('fulfilled', payload)\r\n * } catch (error) {\r\n * console.error('rejected', error);\r\n * }\r\n * ```\r\n */\r\n unwrap(): Promise<ResultTypeFrom<D>>\r\n /**\r\n * A method to manually unsubscribe from the mutation call, meaning it will be removed from cache after the usual caching grace period.\r\n The value returned by the hook will reset to `isUninitialized` afterwards.\r\n */\r\n reset(): void\r\n /** @deprecated has been renamed to `reset` */\r\n unsubscribe(): void\r\n}\r\n\r\nexport function buildInitiate({\r\n serializeQueryArgs,\r\n queryThunk,\r\n mutationThunk,\r\n api,\r\n context,\r\n}: {\r\n serializeQueryArgs: InternalSerializeQueryArgs\r\n queryThunk: QueryThunk\r\n mutationThunk: MutationThunk\r\n api: Api<any, EndpointDefinitions, any, any>\r\n context: ApiContext<EndpointDefinitions>\r\n}) {\r\n const runningQueries: Map<\r\n Dispatch,\r\n Record<string, QueryActionCreatorResult<any> | undefined>\r\n > = new Map()\r\n const runningMutations: Map<\r\n Dispatch,\r\n Record<string, MutationActionCreatorResult<any> | undefined>\r\n > = new Map()\r\n\r\n const {\r\n unsubscribeQueryResult,\r\n removeMutationResult,\r\n updateSubscriptionOptions,\r\n } = api.internalActions\r\n return {\r\n buildInitiateQuery,\r\n buildInitiateMutation,\r\n getRunningQueryThunk,\r\n getRunningMutationThunk,\r\n getRunningQueriesThunk,\r\n getRunningMutationsThunk,\r\n getRunningOperationPromises,\r\n removalWarning,\r\n }\r\n\r\n /** @deprecated to be removed in 2.0 */\r\n function removalWarning(): never {\r\n throw new Error(\r\n `This method had to be removed due to a conceptual bug in RTK.\r\n Please see https://github.com/reduxjs/redux-toolkit/pull/2481 for details.\r\n See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for new guidance on SSR.`\r\n )\r\n }\r\n\r\n /** @deprecated to be removed in 2.0 */\r\n function getRunningOperationPromises() {\r\n if (\r\n typeof process !== 'undefined' &&\r\n process.env.NODE_ENV === 'development'\r\n ) {\r\n removalWarning()\r\n } else {\r\n const extract = <T>(\r\n v: Map<Dispatch<AnyAction>, Record<string, T | undefined>>\r\n ) =>\r\n Array.from(v.values()).flatMap((queriesForStore) =>\r\n queriesForStore ? Object.values(queriesForStore) : []\r\n )\r\n return [...extract(runningQueries), ...extract(runningMutations)].filter(\r\n isNotNullish\r\n )\r\n }\r\n }\r\n\r\n function getRunningQueryThunk(endpointName: string, queryArgs: any) {\r\n return (dispatch: Dispatch) => {\r\n const endpointDefinition = context.endpointDefinitions[endpointName]\r\n const queryCacheKey = serializeQueryArgs({\r\n queryArgs,\r\n endpointDefinition,\r\n endpointName,\r\n })\r\n return runningQueries.get(dispatch)?.[queryCacheKey] as\r\n | QueryActionCreatorResult<never>\r\n | undefined\r\n }\r\n }\r\n\r\n function getRunningMutationThunk(\r\n /**\r\n * this is only here to allow TS to infer the result type by input value\r\n * we could use it to validate the result, but it's probably not necessary\r\n */\r\n _endpointName: string,\r\n fixedCacheKeyOrRequestId: string\r\n ) {\r\n return (dispatch: Dispatch) => {\r\n return runningMutations.get(dispatch)?.[fixedCacheKeyOrRequestId] as\r\n | MutationActionCreatorResult<never>\r\n | undefined\r\n }\r\n }\r\n\r\n function getRunningQueriesThunk() {\r\n return (dispatch: Dispatch) =>\r\n Object.values(runningQueries.get(dispatch) || {}).filter(isNotNullish)\r\n }\r\n\r\n function getRunningMutationsThunk() {\r\n return (dispatch: Dispatch) =>\r\n Object.values(runningMutations.get(dispatch) || {}).filter(isNotNullish)\r\n }\r\n\r\n function middlewareWarning(dispatch: Dispatch) {\r\n if (process.env.NODE_ENV !== 'production') {\r\n if ((middlewareWarning as any).triggered) return\r\n const registered:\r\n | ReturnType<typeof api.internalActions.internal_probeSubscription>\r\n | boolean = dispatch(\r\n api.internalActions.internal_probeSubscription({\r\n queryCacheKey: 'DOES_NOT_EXIST',\r\n requestId: 'DUMMY_REQUEST_ID',\r\n })\r\n )\r\n\r\n ;(middlewareWarning as any).triggered = true\r\n\r\n // The RTKQ middleware _should_ always return a boolean for `probeSubscription`\r\n if (typeof registered !== 'boolean') {\r\n // Otherwise, must not have been added\r\n throw new Error(\r\n `Warning: Middleware for RTK-Query API at reducerPath \"${api.reducerPath}\" has not been added to the store.\r\nYou must add the middleware for RTK-Query to function correctly!`\r\n )\r\n }\r\n }\r\n }\r\n\r\n function buildInitiateQuery(\r\n endpointName: string,\r\n endpointDefinition: QueryDefinition<any, any, any, any>\r\n ) {\r\n const queryAction: StartQueryActionCreator<any> =\r\n (\r\n arg,\r\n {\r\n subscribe = true,\r\n forceRefetch,\r\n subscriptionOptions,\r\n [forceQueryFnSymbol]: forceQueryFn,\r\n } = {}\r\n ) =>\r\n (dispatch, getState) => {\r\n const queryCacheKey = serializeQueryArgs({\r\n queryArgs: arg,\r\n endpointDefinition,\r\n endpointName,\r\n })\r\n\r\n const thunk = queryThunk({\r\n type: 'query',\r\n subscribe,\r\n forceRefetch: forceRefetch,\r\n subscriptionOptions,\r\n endpointName,\r\n originalArgs: arg,\r\n queryCacheKey,\r\n [forceQueryFnSymbol]: forceQueryFn,\r\n })\r\n const selector = (\r\n api.endpoints[endpointName] as ApiEndpointQuery<any, any>\r\n ).select(arg)\r\n\r\n const thunkResult = dispatch(thunk)\r\n const stateAfter = selector(getState())\r\n\r\n middlewareWarning(dispatch)\r\n\r\n const { requestId, abort } = thunkResult\r\n\r\n const skippedSynchronously = stateAfter.requestId !== requestId\r\n\r\n const runningQuery = runningQueries.get(dispatch)?.[queryCacheKey]\r\n const selectFromState = () => selector(getState())\r\n\r\n const statePromise: QueryActionCreatorResult<any> = Object.assign(\r\n forceQueryFn\r\n ? // a query has been forced (upsertQueryData)\r\n // -> we want to resolve it once data has been written with the data that will be written\r\n thunkResult.then(selectFromState)\r\n : skippedSynchronously && !runningQuery\r\n ? // a query has been skipped due to a condition and we do not have any currently running query\r\n // -> we want to resolve it immediately with the current data\r\n Promise.resolve(stateAfter)\r\n : // query just started or one is already in flight\r\n // -> wait for the running query, then resolve with data from after that\r\n Promise.all([runningQuery, thunkResult]).then(selectFromState),\r\n {\r\n arg,\r\n requestId,\r\n subscriptionOptions,\r\n queryCacheKey,\r\n abort,\r\n async unwrap() {\r\n const result = await statePromise\r\n\r\n if (result.isError) {\r\n throw result.error\r\n }\r\n\r\n return result.data\r\n },\r\n refetch: () =>\r\n dispatch(\r\n queryAction(arg, { subscribe: false, forceRefetch: true })\r\n ),\r\n unsubscribe() {\r\n if (subscribe)\r\n dispatch(\r\n unsubscribeQueryResult({\r\n queryCacheKey,\r\n requestId,\r\n })\r\n )\r\n },\r\n updateSubscriptionOptions(options: SubscriptionOptions) {\r\n statePromise.subscriptionOptions = options\r\n dispatch(\r\n updateSubscriptionOptions({\r\n endpointName,\r\n requestId,\r\n queryCacheKey,\r\n options,\r\n })\r\n )\r\n },\r\n }\r\n )\r\n\r\n if (!runningQuery && !skippedSynchronously && !forceQueryFn) {\r\n const running = runningQueries.get(dispatch) || {}\r\n running[queryCacheKey] = statePromise\r\n runningQueries.set(dispatch, running)\r\n\r\n statePromise.then(() => {\r\n delete running[queryCacheKey]\r\n if (!Object.keys(running).length) {\r\n runningQueries.delete(dispatch)\r\n }\r\n })\r\n }\r\n\r\n return statePromise\r\n }\r\n return queryAction\r\n }\r\n\r\n function buildInitiateMutation(\r\n endpointName: string\r\n ): StartMutationActionCreator<any> {\r\n return (arg, { track = true, fixedCacheKey } = {}) =>\r\n (dispatch, getState) => {\r\n const thunk = mutationThunk({\r\n type: 'mutation',\r\n endpointName,\r\n originalArgs: arg,\r\n track,\r\n fixedCacheKey,\r\n })\r\n const thunkResult = dispatch(thunk)\r\n middlewareWarning(dispatch)\r\n const { requestId, abort, unwrap } = thunkResult\r\n const returnValuePromise = thunkResult\r\n .unwrap()\r\n .then((data) => ({ data }))\r\n .catch((error) => ({ error }))\r\n\r\n const reset = () => {\r\n dispatch(removeMutationResult({ requestId, fixedCacheKey }))\r\n }\r\n\r\n const ret = Object.assign(returnValuePromise, {\r\n arg: thunkResult.arg,\r\n requestId,\r\n abort,\r\n unwrap,\r\n unsubscribe: reset,\r\n reset,\r\n })\r\n\r\n const running = runningMutations.get(dispatch) || {}\r\n runningMutations.set(dispatch, running)\r\n running[requestId] = ret\r\n ret.then(() => {\r\n delete running[requestId]\r\n if (!Object.keys(running).length) {\r\n runningMutations.delete(dispatch)\r\n }\r\n })\r\n if (fixedCacheKey) {\r\n running[fixedCacheKey] = ret\r\n ret.then(() => {\r\n if (running[fixedCacheKey] === ret) {\r\n delete running[fixedCacheKey]\r\n if (!Object.keys(running).length) {\r\n runningMutations.delete(dispatch)\r\n }\r\n }\r\n })\r\n }\r\n\r\n return ret\r\n }\r\n }\r\n}\r\n","import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'\r\nimport type { Api, ApiContext } from '../apiTypes'\r\nimport type {\r\n BaseQueryFn,\r\n BaseQueryError,\r\n QueryReturnValue,\r\n} from '../baseQueryTypes'\r\nimport type { RootState, QueryKeys, QuerySubstateIdentifier } from './apiState'\r\nimport { QueryStatus } from './apiState'\r\nimport type {\r\n StartQueryActionCreatorOptions,\r\n QueryActionCreatorResult,\r\n} from './buildInitiate'\r\nimport { forceQueryFnSymbol, isUpsertQuery } from './buildInitiate'\r\nimport type {\r\n AssertTagTypes,\r\n EndpointDefinition,\r\n EndpointDefinitions,\r\n MutationDefinition,\r\n QueryArgFrom,\r\n QueryDefinition,\r\n ResultTypeFrom,\r\n FullTagDescription,\r\n} from '../endpointDefinitions'\r\nimport { isQueryDefinition } from '../endpointDefinitions'\r\nimport { calculateProvidedBy } from '../endpointDefinitions'\r\nimport type { AsyncThunkPayloadCreator, Draft } from '@reduxjs/toolkit'\r\nimport {\r\n isAllOf,\r\n isFulfilled,\r\n isPending,\r\n isRejected,\r\n isRejectedWithValue,\r\n} from '@reduxjs/toolkit'\r\nimport type { Patch } from 'immer'\r\nimport { isDraftable, produceWithPatches } from 'immer'\r\nimport type {\r\n AnyAction,\r\n ThunkAction,\r\n ThunkDispatch,\r\n AsyncThunk,\r\n} from '@reduxjs/toolkit'\r\nimport { createAsyncThunk, SHOULD_AUTOBATCH } from '@reduxjs/toolkit'\r\n\r\nimport { HandledError } from '../HandledError'\r\n\r\nimport type { ApiEndpointQuery, PrefetchOptions } from './module'\r\nimport type { UnwrapPromise } from '../tsHelpers'\r\n\r\ndeclare module './module' {\r\n export interface ApiEndpointQuery<\r\n Definition extends QueryDefinition<any, any, any, any, any>,\r\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\r\n Definitions extends EndpointDefinitions\r\n > extends Matchers<QueryThunk, Definition> {}\r\n\r\n export interface ApiEndpointMutation<\r\n Definition extends MutationDefinition<any, any, any, any, any>,\r\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\r\n Definitions extends EndpointDefinitions\r\n > extends Matchers<MutationThunk, Definition> {}\r\n}\r\n\r\ntype EndpointThunk<\r\n Thunk extends QueryThunk | MutationThunk,\r\n Definition extends EndpointDefinition<any, any, any, any>\r\n> = Definition extends EndpointDefinition<\r\n infer QueryArg,\r\n infer BaseQueryFn,\r\n any,\r\n infer ResultType\r\n>\r\n ? Thunk extends AsyncThunk<unknown, infer ATArg, infer ATConfig>\r\n ? AsyncThunk<\r\n ResultType,\r\n ATArg & { originalArgs: QueryArg },\r\n ATConfig & { rejectValue: BaseQueryError<BaseQueryFn> }\r\n >\r\n : never\r\n : never\r\n\r\nexport type PendingAction<\r\n Thunk extends QueryThunk | MutationThunk,\r\n Definition extends EndpointDefinition<any, any, any, any>\r\n> = ReturnType<EndpointThunk<Thunk, Definition>['pending']>\r\n\r\nexport type FulfilledAction<\r\n Thunk extends QueryThunk | MutationThunk,\r\n Definition extends EndpointDefinition<any, any, any, any>\r\n> = ReturnType<EndpointThunk<Thunk, Definition>['fulfilled']>\r\n\r\nexport type RejectedAction<\r\n Thunk extends QueryThunk | MutationThunk,\r\n Definition extends EndpointDefinition<any, any, any, any>\r\n> = ReturnType<EndpointThunk<Thunk, Definition>['rejected']>\r\n\r\nexport type Matcher<M> = (value: any) => value is M\r\n\r\nexport interface Matchers<\r\n Thunk extends QueryThunk | MutationThunk,\r\n Definition extends EndpointDefinition<any, any, any, any>\r\n> {\r\n matchPending: Matcher<PendingAction<Thunk, Definition>>\r\n matchFulfilled: Matcher<FulfilledAction<Thunk, Definition>>\r\n matchRejected: Matcher<RejectedAction<Thunk, Definition>>\r\n}\r\n\r\nexport interface QueryThunkArg\r\n extends QuerySubstateIdentifier,\r\n StartQueryActionCreatorOptions {\r\n type: 'query'\r\n originalArgs: unknown\r\n endpointName: string\r\n}\r\n\r\nexport interface MutationThunkArg {\r\n type: 'mutation'\r\n originalArgs: unknown\r\n endpointName: string\r\n track?: boolean\r\n fixedCacheKey?: string\r\n}\r\n\r\nexport type ThunkResult = unknown\r\n\r\nexport type ThunkApiMetaConfig = {\r\n pendingMeta: {\r\n startedTimeStamp: number\r\n [SHOULD_AUTOBATCH]: true\r\n }\r\n fulfilledMeta: {\r\n fulfilledTimeStamp: number\r\n baseQueryMeta: unknown\r\n [SHOULD_AUTOBATCH]: true\r\n }\r\n rejectedMeta: {\r\n baseQueryMeta: unknown\r\n [SHOULD_AUTOBATCH]: true\r\n }\r\n}\r\nexport type QueryThunk = AsyncThunk<\r\n ThunkResult,\r\n QueryThunkArg,\r\n ThunkApiMetaConfig\r\n>\r\nexport type MutationThunk = AsyncThunk<\r\n ThunkResult,\r\n MutationThunkArg,\r\n ThunkApiMetaConfig\r\n>\r\n\r\nfunction defaultTransformResponse(baseQueryReturnValue: unknown) {\r\n return baseQueryReturnValue\r\n}\r\n\r\nexport type MaybeDrafted<T> = T | Draft<T>\r\nexport type Recipe<T> = (data: MaybeDrafted<T>) => void | MaybeDrafted<T>\r\nexport type UpsertRecipe<T> = (\r\n data: MaybeDrafted<T> | undefined\r\n) => void | MaybeDrafted<T>\r\n\r\nexport type PatchQueryDataThunk<\r\n Definitions extends EndpointDefinitions,\r\n PartialState\r\n> = <EndpointName extends QueryKeys<Definitions>>(\r\n endpointName: EndpointName,\r\n args: QueryArgFrom<Definitions[EndpointName]>,\r\n patches: readonly Patch[],\r\n updateProvided?: boolean\r\n) => ThunkAction<void, PartialState, any, AnyAction>\r\n\r\nexport type UpdateQueryDataThunk<\r\n Definitions extends EndpointDefinitions,\r\n PartialState\r\n> = <EndpointName extends QueryKeys<Definitions>>(\r\n endpointName: EndpointName,\r\n args: QueryArgFrom<Definitions[EndpointName]>,\r\n updateRecipe: Recipe<ResultTypeFrom<Definitions[EndpointName]>>,\r\n updateProvided?: boolean\r\n) => ThunkAction<PatchCollection, PartialState, any, AnyAction>\r\n\r\nexport type UpsertQueryDataThunk<\r\n Definitions extends EndpointDefinitions,\r\n PartialState\r\n> = <EndpointName extends QueryKeys<Definitions>>(\r\n endpointName: EndpointName,\r\n args: QueryArgFrom<Definitions[EndpointName]>,\r\n value: ResultTypeFrom<Definitions[EndpointName]>\r\n) => ThunkAction<\r\n QueryActionCreatorResult<\r\n Definitions[EndpointName] extends QueryDefinition<any, any, any, any>\r\n ? Definitions[EndpointName]\r\n : never\r\n >,\r\n PartialState,\r\n any,\r\n AnyAction\r\n>\r\n\r\n/**\r\n * An object returned from dispatching a `api.util.updateQueryData` call.\r\n */\r\nexport type PatchCollection = {\r\n /**\r\n * An `immer` Patch describing the cache update.\r\n */\r\n patches: Patch[]\r\n /**\r\n * An `immer` Patch to revert the cache update.\r\n */\r\n inversePatches: Patch[]\r\n /**\r\n * A function that will undo the cache update.\r\n */\r\n undo: () => void\r\n}\r\n\r\nexport function buildThunks<\r\n BaseQuery extends BaseQueryFn,\r\n ReducerPath extends string,\r\n Definitions extends EndpointDefinitions\r\n>({\r\n reducerPath,\r\n baseQuery,\r\n context: { endpointDefinitions },\r\n serializeQueryArgs,\r\n api,\r\n assertTagType,\r\n}: {\r\n baseQuery: BaseQuery\r\n reducerPath: ReducerPath\r\n context: ApiContext<Definitions>\r\n serializeQueryArgs: InternalSerializeQueryArgs\r\n api: Api<BaseQuery, Definitions, ReducerPath, any>\r\n assertTagType: AssertTagTypes\r\n}) {\r\n type State = RootState<any, string, ReducerPath>\r\n\r\n const patchQueryData: PatchQueryDataThunk<EndpointDefinitions, State> =\r\n (endpointName, args, patches, updateProvided) => (dispatch, getState) => {\r\n const endpointDefinition = endpointDefinitions[endpointName]\r\n\r\n const queryCacheKey = serializeQueryArgs({\r\n queryArgs: args,\r\n endpointDefinition,\r\n endpointName,\r\n })\r\n\r\n dispatch(\r\n api.internalActions.queryResultPatched({ queryCacheKey, patches })\r\n )\r\n\r\n if (!updateProvided) {\r\n return\r\n }\r\n\r\n const newValue = api.endpoints[endpointName].select(args)(\r\n // Work around TS 4.1 mismatch\r\n getState() as RootState<any, any, any>\r\n )\r\n\r\n const providedTags = calculateProvidedBy(\r\n endpointDefinition.providesTags,\r\n newValue.data,\r\n undefined,\r\n args,\r\n {},\r\n assertTagType\r\n )\r\n\r\n dispatch(\r\n api.internalActions.updateProvidedBy({ queryCacheKey, providedTags })\r\n )\r\n }\r\n\r\n const updateQueryData: UpdateQueryDataThunk<EndpointDefinitions, State> =\r\n (endpointName, args, updateRecipe, updateProvided = true) =>\r\n (dispatch, getState) => {\r\n const endpointDefinition = api.endpoints[endpointName]\r\n\r\n const currentState = endpointDefinition.select(args)(\r\n // Work around TS 4.1 mismatch\r\n getState() as RootState<any, any, any>\r\n )\r\n\r\n let ret: PatchCollection = {\r\n patches: [],\r\n inversePatches: [],\r\n undo: () =>\r\n dispatch(\r\n api.util.patchQueryData(\r\n endpointName,\r\n args,\r\n ret.inversePatches,\r\n updateProvided\r\n )\r\n ),\r\n }\r\n if (currentState.status === QueryStatus.uninitialized) {\r\n return ret\r\n }\r\n let newValue\r\n if ('data' in currentState) {\r\n if (isDraftable(currentState.data)) {\r\n const [value, patches, inversePatches] = produceWithPatches(\r\n currentState.data,\r\n updateRecipe\r\n )\r\n ret.patches.push(...patches)\r\n ret.inversePatches.push(...inversePatches)\r\n newValue = value\r\n } else {\r\n newValue = updateRecipe(currentState.data)\r\n ret.patches.push({ op: 'replace', path: [], value: newValue })\r\n ret.inversePatches.push({\r\n op: 'replace',\r\n path: [],\r\n value: currentState.data,\r\n })\r\n }\r\n }\r\n\r\n dispatch(\r\n api.util.patchQueryData(endpointName, args, ret.patches, updateProvided)\r\n )\r\n\r\n return ret\r\n }\r\n\r\n const upsertQueryData: UpsertQueryDataThunk<Definitions, State> =\r\n (endpointName, args, value) => (dispatch) => {\r\n return dispatch(\r\n (\r\n api.endpoints[endpointName] as ApiEndpointQuery<\r\n QueryDefinition<any, any, any, any, any>,\r\n Definitions\r\n >\r\n ).initiate(args, {\r\n subscribe: false,\r\n forceRefetch: true,\r\n [forceQueryFnSymbol]: () => ({\r\n data: value,\r\n }),\r\n })\r\n )\r\n }\r\n\r\n const executeEndpoint: AsyncThunkPayloadCreator<\r\n ThunkResult,\r\n QueryThunkArg | MutationThunkArg,\r\n ThunkApiMetaConfig & { state: RootState<any, string, ReducerPath> }\r\n > = async (\r\n arg,\r\n {\r\n signal,\r\n abort,\r\n rejectWithValue,\r\n fulfillWithValue,\r\n dispatch,\r\n getState,\r\n extra,\r\n }\r\n ) => {\r\n const endpointDefinition = endpointDefinitions[arg.endpointName]\r\n\r\n try {\r\n let transformResponse: (\r\n baseQueryReturnValue: any,\r\n meta: any,\r\n arg: any\r\n ) => any = defaultTransformResponse\r\n let result: QueryReturnValue\r\n const baseQueryApi = {\r\n signal,\r\n abort,\r\n dispatch,\r\n getState,\r\n extra,\r\n endpoint: arg.endpointName,\r\n type: arg.type,\r\n forced:\r\n arg.type === 'query' ? isForcedQuery(arg, getState()) : undefined,\r\n }\r\n\r\n const forceQueryFn =\r\n arg.type === 'query' ? arg[forceQueryFnSymbol] : undefined\r\n if (forceQueryFn) {\r\n result = forceQueryFn()\r\n } else if (endpointDefinition.query) {\r\n result = await baseQuery(\r\n endpointDefinition.query(arg.originalArgs),\r\n baseQueryApi,\r\n endpointDefinition.extraOptions as any\r\n )\r\n\r\n if (endpointDefinition.transformResponse) {\r\n transformResponse = endpointDefinition.transformResponse\r\n }\r\n } else {\r\n result = await endpointDefinition.queryFn(\r\n arg.originalArgs,\r\n baseQueryApi,\r\n endpointDefinition.extraOptions as any,\r\n (arg) =>\r\n baseQuery(arg, baseQueryApi, endpointDefinition.extraOptions as any)\r\n )\r\n }\r\n if (\r\n typeof process !== 'undefined' &&\r\n process.env.NODE_ENV === 'development'\r\n ) {\r\n const what = endpointDefinition.query ? '`baseQuery`' : '`queryFn`'\r\n let err: undefined | string\r\n if (!result) {\r\n err = `${what} did not return anything.`\r\n } else if (typeof result !== 'object') {\r\n err = `${what} did not return an object.`\r\n } else if (result.error && result.data) {\r\n err = `${what} returned an object containing both \\`error\\` and \\`result\\`.`\r\n } else if (result.error === undefined && result.data === undefined) {\r\n err = `${what} returned an object containing neither a valid \\`error\\` and \\`result\\`. At least one of them should not be \\`undefined\\``\r\n } else {\r\n for (const key of Object.keys(result)) {\r\n if (key !== 'error' && key !== 'data' && key !== 'meta') {\r\n err = `The object returned by ${what} has the unknown property ${key}.`\r\n break\r\n }\r\n }\r\n }\r\n if (err) {\r\n console.error(\r\n `Error encountered handling the endpoint ${arg.endpointName}.\r\n ${err}\r\n It needs to return an object with either the shape \\`{ data: <value> }\\` or \\`{ error: <value> }\\` that may contain an optional \\`meta\\` property.\r\n Object returned was:`,\r\n result\r\n )\r\n }\r\n }\r\n\r\n if (result.error) throw new HandledError(result.error, result.meta)\r\n\r\n return fulfillWithValue(\r\n await transformResponse(result.data, result.meta, arg.originalArgs),\r\n {\r\n fulfilledTimeStamp: Date.now(),\r\n baseQueryMeta: result.meta,\r\n [SHOULD_AUTOBATCH]: true,\r\n }\r\n )\r\n } catch (error) {\r\n let catchedError = error\r\n if (catchedError instanceof HandledError) {\r\n let transformErrorResponse: (\r\n baseQueryReturnValue: any,\r\n meta: any,\r\n arg: any\r\n ) => any = defaultTransformResponse\r\n\r\n if (\r\n endpointDefinition.query &&\r\n endpointDefinition.transformErrorResponse\r\n ) {\r\n transformErrorResponse = endpointDefinition.transformErrorResponse\r\n }\r\n try {\r\n return rejectWithValue(\r\n await transformErrorResponse(\r\n catchedError.value,\r\n catchedError.meta,\r\n arg.originalArgs\r\n ),\r\n { baseQueryMeta: catchedError.meta, [SHOULD_AUTOBATCH]: true }\r\n )\r\n } catch (e) {\r\n catchedError = e\r\n }\r\n }\r\n if (\r\n typeof process !== 'undefined' &&\r\n process.env.NODE_ENV !== 'production'\r\n ) {\r\n console.error(\r\n `An unhandled error occurred processing a request for the endpoint \"${arg.endpointName}\".\r\nIn the case of an unhandled error, no tags will be \"provided\" or \"invalidated\".`,\r\n catchedError\r\n )\r\n } else {\r\n console.error(catchedError)\r\n }\r\n throw catchedError\r\n }\r\n }\r\n\r\n function isForcedQuery(\r\n arg: QueryThunkArg,\r\n state: RootState<any, string, ReducerPath>\r\n ) {\r\n const requestState = state[reducerPath]?.queries?.[arg.queryCacheKey]\r\n const baseFetchOnMountOrArgChange =\r\n state[reducerPath]?.config.refetchOnMountOrArgChange\r\n\r\n const fulfilledVal = requestState?.fulfilledTimeStamp\r\n const refetchVal =\r\n arg.forceRefetch ?? (arg.subscribe && baseFetchOnMountOrArgChange)\r\n\r\n if (refetchVal) {\r\n // Return if its true or compare the dates because it must be a number\r\n return (\r\n refetchVal === true ||\r\n (Number(new Date()) - Number(fulfilledVal)) / 1000 >= refetchVal\r\n )\r\n }\r\n return false\r\n }\r\n\r\n const queryThunk = createAsyncThunk<\r\n ThunkResult,\r\n QueryThunkArg,\r\n ThunkApiMetaConfig & { state: RootState<any, string, ReducerPath> }\r\n >(`${reducerPath}/executeQuery`, executeEndpoint, {\r\n getPendingMeta() {\r\n return { startedTimeStamp: Date.now(), [SHOULD_AUTOBATCH]: true }\r\n },\r\n condition(queryThunkArgs, { getState }) {\r\n const state = getState()\r\n\r\n const requestState =\r\n state[reducerPath]?.queries?.[queryThunkArgs.queryCacheKey]\r\n const fulfilledVal = requestState?.fulfilledTimeStamp\r\n const currentArg = queryThunkArgs.originalArgs\r\n const previousArg = requestState?.originalArgs\r\n const endpointDefinition =\r\n endpointDefinitions[queryThunkArgs.endpointName]\r\n\r\n // Order of these checks matters.\r\n // In order for `upsertQueryData` to successfully run while an existing request is in flight,\r\n /// we have to check for that first, otherwise `queryThunk` will bail out and not run at all.\r\n if (isUpsertQuery(queryThunkArgs)) {\r\n return true\r\n }\r\n\r\n // Don't retry a request that's currently in-flight\r\n if (requestState?.status === 'pending') {\r\n return false\r\n }\r\n\r\n // if this is forced, continue\r\n if (isForcedQuery(queryThunkArgs, state)) {\r\n return true\r\n }\r\n\r\n if (\r\n isQueryDefinition(endpointDefinition) &&\r\n endpointDefinition?.forceRefetch?.({\r\n currentArg,\r\n previousArg,\r\n endpointState: requestState,\r\n state,\r\n })\r\n ) {\r\n return true\r\n }\r\n\r\n // Pull from the cache unless we explicitly force refetch or qualify based on time\r\n if (fulfilledVal) {\r\n // Value is cached and we didn't specify to refresh, skip it.\r\n return false\r\n }\r\n\r\n return true\r\n },\r\n dispatchConditionRejection: true,\r\n })\r\n\r\n const mutationThunk = createAsyncThunk<\r\n ThunkResult,\r\n MutationThunkArg,\r\n ThunkApiMetaConfig & { state: RootState<any, string, ReducerPath> }\r\n >(`${reducerPath}/executeMutation`, executeEndpoint, {\r\n getPendingMeta() {\r\n return { startedTimeStamp: Date.now(), [SHOULD_AUTOBATCH]: true }\r\n },\r\n })\r\n\r\n const hasTheForce = (options: any): options is { force: boolean } =>\r\n 'force' in options\r\n const hasMaxAge = (\r\n options: any\r\n ): options is { ifOlderThan: false | number } => 'ifOlderThan' in options\r\n\r\n const prefetch =\r\n <EndpointName extends QueryKeys<Definitions>>(\r\n endpointName: EndpointName,\r\n arg: any,\r\n options: PrefetchOptions\r\n ): ThunkAction<void, any, any, AnyAction> =>\r\n (dispatch: ThunkDispatch<any, any, any>, getState: () => any) => {\r\n const force = hasTheForce(options) && options.force\r\n const maxAge = hasMaxAge(options) && options.ifOlderThan\r\n\r\n const queryAction = (force: boolean = true) =>\r\n (api.endpoints[endpointName] as ApiEndpointQuery<any, any>).initiate(\r\n arg,\r\n { forceRefetch: force }\r\n )\r\n const latestStateValue = (\r\n api.endpoints[endpointName] as ApiEndpointQuery<any, any>\r\n ).select(arg)(getState())\r\n\r\n if (force) {\r\n dispatch(queryAction())\r\n } else if (maxAge) {\r\n const lastFulfilledTs = latestStateValue?.fulfilledTimeStamp\r\n if (!lastFulfilledTs) {\r\n dispatch(queryAction())\r\n return\r\n }\r\n const shouldRetrigger =\r\n (Number(new Date()) - Number(new Date(lastFulfilledTs))) / 1000 >=\r\n maxAge\r\n if (shouldRetrigger) {\r\n dispatch(queryAction())\r\n }\r\n } else {\r\n // If prefetching with no options, just let it try\r\n dispatch(queryAction(false))\r\n }\r\n }\r\n\r\n function matchesEndpoint(endpointName: string) {\r\n return (action: any): action is AnyAction =>\r\n action?.meta?.arg?.endpointName === endpointName\r\n }\r\n\r\n function buildMatchThunkActions<\r\n Thunk extends\r\n | AsyncThunk<any, QueryThunkArg, ThunkApiMetaConfig>\r\n | AsyncThunk<any, MutationThunkArg, ThunkApiMetaConfig>\r\n >(thunk: Thunk, endpointName: string) {\r\n return {\r\n matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)),\r\n matchFulfilled: isAllOf(\r\n isFulfilled(thunk),\r\n matchesEndpoint(endpointName)\r\n ),\r\n matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpointName)),\r\n } as Matchers<Thunk, any>\r\n }\r\n\r\n return {\r\n queryThunk,\r\n mutationThunk,\r\n prefetch,\r\n updateQueryData,\r\n upsertQueryData,\r\n patchQueryData,\r\n buildMatchThunkActions,\r\n }\r\n}\r\n\r\nexport function calculateProvidedByThunk(\r\n action: UnwrapPromise<\r\n ReturnType<ReturnType<QueryThunk>> | ReturnType<ReturnType<MutationThunk>>\r\n >,\r\n type: 'providesTags' | 'invalidatesTags',\r\n endpointDefinitions: EndpointDefinitions,\r\n assertTagType: AssertTagTypes\r\n) {\r\n return calculateProvidedBy(\r\n endpointDefinitions[action.meta.arg.endpointName][type],\r\n isFulfilled(action) ? action.payload : undefined,\r\n isRejectedWithValue(action) ? action.payload : undefined,\r\n action.meta.arg.originalArgs,\r\n 'baseQueryMeta' in action.meta ? action.meta.baseQueryMeta : undefined,\r\n assertTagType\r\n )\r\n}\r\n","import type { QueryCacheKey } from './core/apiState'\r\nimport type { EndpointDefinition } from './endpointDefinitions'\r\nimport { isPlainObject } from '@reduxjs/toolkit'\r\n\r\nconst cache: WeakMap<any, string> | undefined = WeakMap\r\n ? new WeakMap()\r\n : undefined\r\n\r\nexport const defaultSerializeQueryArgs: SerializeQueryArgs<any> = ({\r\n endpointName,\r\n queryArgs,\r\n}) => {\r\n let serialized = ''\r\n\r\n const cached = cache?.get(queryArgs)\r\n\r\n if (typeof cached === 'string') {\r\n serialized = cached\r\n } else {\r\n const stringified = JSON.stringify(queryArgs, (key, value) =>\r\n isPlainObject(value)\r\n ? Object.keys(value)\r\n .sort()\r\n .reduce<any>((acc, key) => {\r\n acc[key] = (value as any)[key]\r\n return acc\r\n }, {})\r\n : value\r\n )\r\n if (isPlainObject(queryArgs)) {\r\n cache?.set(queryArgs, stringified)\r\n }\r\n serialized = stringified\r\n }\r\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 })\r\n return `${endpointName}(${serialized})`\r\n}\r\n\r\nexport type SerializeQueryArgs<QueryArgs, ReturnType = string> = (_: {\r\n queryArgs: QueryArgs\r\n endpointDefinition: EndpointDefinition<any, any, any, any>\r\n endpointName: string\r\n}) => ReturnType\r\n\r\nexport type InternalSerializeQueryArgs = (_: {\r\n queryArgs: any\r\n endpointDefinition: EndpointDefinition<any, any, any, any>\r\n endpointName: string\r\n}) => QueryCacheKey\r\n","import type { Api, ApiContext, Module, ModuleName } from './apiTypes'\r\nimport type { CombinedState } from './core/apiState'\r\nimport type { BaseQueryArg, BaseQueryFn } from './baseQueryTypes'\r\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs'\r\nimport { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs'\r\nimport type {\r\n EndpointBuilder,\r\n EndpointDefinitions,\r\n} from './endpointDefinitions'\r\nimport { DefinitionType, isQueryDefinition } from './endpointDefinitions'\r\nimport { nanoid } from '@reduxjs/toolkit'\r\nimport type { AnyAction } from '@reduxjs/toolkit'\r\nimport type { NoInfer } from './tsHelpers'\r\nimport { defaultMemoize } from 'reselect'\r\n\r\nexport interface CreateApiOptions<\r\n BaseQuery extends BaseQueryFn,\r\n Definitions extends EndpointDefinitions,\r\n ReducerPath extends string = 'api',\r\n TagTypes extends string = never\r\n> {\r\n /**\r\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.\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\r\n *\r\n * const api = createApi({\r\n * // highlight-start\r\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\r\n * // highlight-end\r\n * endpoints: (build) => ({\r\n * // ...endpoints\r\n * }),\r\n * })\r\n * ```\r\n */\r\n baseQuery: BaseQuery\r\n /**\r\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).\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\r\n *\r\n * const api = createApi({\r\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\r\n * // highlight-start\r\n * tagTypes: ['Post', 'User'],\r\n * // highlight-end\r\n * endpoints: (build) => ({\r\n * // ...endpoints\r\n * }),\r\n * })\r\n * ```\r\n */\r\n tagTypes?: readonly TagTypes[]\r\n /**\r\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'`.\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * // codeblock-meta title=\"apis.js\"\r\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query';\r\n *\r\n * const apiOne = createApi({\r\n * // highlight-start\r\n * reducerPath: 'apiOne',\r\n * // highlight-end\r\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\r\n * endpoints: (builder) => ({\r\n * // ...endpoints\r\n * }),\r\n * });\r\n *\r\n * const apiTwo = createApi({\r\n * // highlight-start\r\n * reducerPath: 'apiTwo',\r\n * // highlight-end\r\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\r\n * endpoints: (builder) => ({\r\n * // ...endpoints\r\n * }),\r\n * });\r\n * ```\r\n */\r\n reducerPath?: ReducerPath\r\n /**\r\n * Accepts a custom function if you have a need to change the creation of cache keys for any reason.\r\n */\r\n serializeQueryArgs?: SerializeQueryArgs<BaseQueryArg<BaseQuery>>\r\n /**\r\n * Endpoints are just a set of operations that you want to perform against your server. You define them as an object using the builder syntax. There are two basic endpoint types: [`query`](../../rtk-query/usage/queries) and [`mutation`](../../rtk-query/usage/mutations).\r\n */\r\n endpoints(\r\n build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>\r\n ): Definitions\r\n /**\r\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.\r\n *\r\n * ```ts\r\n * // codeblock-meta title=\"keepUnusedDataFor example\"\r\n *\r\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\r\n * interface Post {\r\n * id: number\r\n * name: string\r\n * }\r\n * type PostsResponse = Post[]\r\n *\r\n * const api = createApi({\r\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\r\n * endpoints: (build) => ({\r\n * getPosts: build.query<PostsResponse, void>({\r\n * query: () => 'posts',\r\n * // highlight-start\r\n * keepUnusedDataFor: 5\r\n * // highlight-end\r\n * })\r\n * })\r\n * })\r\n * ```\r\n */\r\n keepUnusedDataFor?: number\r\n /**\r\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.\r\n * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.\r\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.\r\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.\r\n *\r\n * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\r\n */\r\n refetchOnMountOrArgChange?: boolean | number\r\n /**\r\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.\r\n *\r\n * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\r\n *\r\n * Note: requires [`setupListeners`](./setupListeners) to have been called.\r\n */\r\n refetchOnFocus?: boolean\r\n /**\r\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.\r\n *\r\n * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\r\n *\r\n * Note: requires [`setupListeners`](./setupListeners) to have been called.\r\n */\r\n refetchOnReconnect?: boolean\r\n /**\r\n * A function that is passed every dispatched action. If this returns something other than `undefined`,\r\n * that return value will be used to rehydrate fulfilled & errored queries.\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * // codeblock-meta title=\"next-redux-wrapper rehydration example\"\r\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\r\n * import { HYDRATE } from 'next-redux-wrapper'\r\n *\r\n * export const api = createApi({\r\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\r\n * // highlight-start\r\n * extractRehydrationInfo(action, { reducerPath }) {\r\n * if (action.type === HYDRATE) {\r\n * return action.payload[reducerPath]\r\n * }\r\n * },\r\n * // highlight-end\r\n * endpoints: (build) => ({\r\n * // omitted\r\n * }),\r\n * })\r\n * ```\r\n */\r\n extractRehydrationInfo?: (\r\n action: AnyAction,\r\n {\r\n reducerPath,\r\n }: {\r\n reducerPath: ReducerPath\r\n }\r\n ) =>\r\n | undefined\r\n | CombinedState<\r\n NoInfer<Definitions>,\r\n NoInfer<TagTypes>,\r\n NoInfer<ReducerPath>\r\n >\r\n}\r\n\r\nexport type CreateApi<Modules extends ModuleName> = {\r\n /**\r\n * Creates a service to use in your application. Contains only the basic redux logic (the core module).\r\n *\r\n * @link https://rtk-query-docs.netlify.app/api/createApi\r\n */\r\n <\r\n BaseQuery extends BaseQueryFn,\r\n Definitions extends EndpointDefinitions,\r\n ReducerPath extends string = 'api',\r\n TagTypes extends string = never\r\n >(\r\n options: CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>\r\n ): Api<BaseQuery, Definitions, ReducerPath, TagTypes, Modules>\r\n}\r\n\r\n/**\r\n * Builds a `createApi` method based on the provided `modules`.\r\n *\r\n * @link https://rtk-query-docs.netlify.app/concepts/customizing-create-api\r\n *\r\n * @example\r\n * ```ts\r\n * const MyContext = React.createContext<ReactReduxContextValue>(null as any);\r\n * const customCreateApi = buildCreateApi(\r\n * coreModule(),\r\n * reactHooksModule({ useDispatch: createDispatchHook(MyContext) })\r\n * );\r\n * ```\r\n *\r\n * @param modules - A variable number of modules that customize how the `createApi` method handles endpoints\r\n * @returns A `createApi` method using the provided `modules`.\r\n */\r\nexport function buildCreateApi<Modules extends [Module<any>, ...Module<any>[]]>(\r\n ...modules: Modules\r\n): CreateApi<Modules[number]['name']> {\r\n return function baseCreateApi(options) {\r\n const extractRehydrationInfo = defaultMemoize((action: AnyAction) =>\r\n options.extractRehydrationInfo?.(action, {\r\n reducerPath: (options.reducerPath ?? 'api') as any,\r\n })\r\n )\r\n\r\n const optionsWithDefaults: CreateApiOptions<any, any, any, any> = {\r\n reducerPath: 'api',\r\n keepUnusedDataFor: 60,\r\n refetchOnMountOrArgChange: false,\r\n refetchOnFocus: false,\r\n refetchOnReconnect: false,\r\n ...options,\r\n extractRehydrationInfo,\r\n serializeQueryArgs(queryArgsApi) {\r\n let finalSerializeQueryArgs = defaultSerializeQueryArgs\r\n if ('serializeQueryArgs' in queryArgsApi.endpointDefinition) {\r\n const endpointSQA =\r\n queryArgsApi.endpointDefinition.serializeQueryArgs!\r\n finalSerializeQueryArgs = (queryArgsApi) => {\r\n const initialResult = endpointSQA(queryArgsApi)\r\n if (typeof initialResult === 'string') {\r\n // If the user function returned a string, use it as-is\r\n return initialResult\r\n } else {\r\n // Assume they returned an object (such as a subset of the original\r\n // query args) or a primitive, and serialize it ourselves\r\n return defaultSerializeQueryArgs({\r\n ...queryArgsApi,\r\n queryArgs: initialResult,\r\n })\r\n }\r\n }\r\n } else if (options.serializeQueryArgs) {\r\n finalSerializeQueryArgs = options.serializeQueryArgs\r\n }\r\n\r\n return finalSerializeQueryArgs(queryArgsApi)\r\n },\r\n tagTypes: [...(options.tagTypes || [])],\r\n }\r\n\r\n const context: ApiContext<EndpointDefinitions> = {\r\n endpointDefinitions: {},\r\n batch(fn) {\r\n // placeholder \"batch\" method to be overridden by plugins, for example with React.unstable_batchedUpdate\r\n fn()\r\n },\r\n apiUid: nanoid(),\r\n extractRehydrationInfo,\r\n hasRehydrationInfo: defaultMemoize(\r\n (action) => extractRehydrationInfo(action) != null\r\n ),\r\n }\r\n\r\n const api = {\r\n injectEndpoints,\r\n enhanceEndpoints({ addTagTypes, endpoints }) {\r\n if (addTagTypes) {\r\n for (const eT of addTagTypes) {\r\n if (!optionsWithDefaults.tagTypes!.includes(eT as any)) {\r\n ;(optionsWithDefaults.tagTypes as any[]).push(eT)\r\n }\r\n }\r\n }\r\n if (endpoints) {\r\n for (const [endpointName, partialDefinition] of Object.entries(\r\n endpoints\r\n )) {\r\n if (typeof partialDefinition === 'function') {\r\n partialDefinition(context.endpointDefinitions[endpointName])\r\n } else {\r\n Object.assign(\r\n context.endpointDefinitions[endpointName] || {},\r\n partialDefinition\r\n )\r\n }\r\n }\r\n }\r\n return api\r\n },\r\n } as Api<BaseQueryFn, {}, string, string, Modules[number]['name']>\r\n\r\n const initializedModules = modules.map((m) =>\r\n m.init(api as any, optionsWithDefaults as any, context)\r\n )\r\n\r\n function injectEndpoints(\r\n inject: Parameters<typeof api.injectEndpoints>[0]\r\n ) {\r\n const evaluatedEndpoints = inject.endpoints({\r\n query: (x) => ({ ...x, type: DefinitionType.query } as any),\r\n mutation: (x) => ({ ...x, type: DefinitionType.mutation } as any),\r\n })\r\n\r\n for (const [endpointName, definition] of Object.entries(\r\n evaluatedEndpoints\r\n )) {\r\n if (\r\n !inject.overrideExisting &&\r\n endpointName in context.endpointDefinitions\r\n ) {\r\n if (\r\n typeof process !== 'undefined' &&\r\n process.env.NODE_ENV === 'development'\r\n ) {\r\n console.error(\r\n `called \\`injectEndpoints\\` to override already-existing endpointName ${endpointName} without specifying \\`overrideExisting: true\\``\r\n )\r\n }\r\n\r\n continue\r\n }\r\n\r\n context.endpointDefinitions[endpointName] = definition\r\n for (const m of initializedModules) {\r\n m.injectEndpoint(endpointName, definition)\r\n }\r\n }\r\n\r\n return api as any\r\n }\r\n\r\n return api.injectEndpoints({ endpoints: options.endpoints as any })\r\n }\r\n}\r\n","import type { BaseQueryFn } from './baseQueryTypes'\r\n\r\nconst _NEVER = /* @__PURE__ */ Symbol()\r\nexport type NEVER = typeof _NEVER\r\n\r\n/**\r\n * Creates a \"fake\" baseQuery to be used if your api *only* uses the `queryFn` definition syntax.\r\n * This also allows you to specify a specific error type to be shared by all your `queryFn` definitions.\r\n */\r\nexport function fakeBaseQuery<ErrorType>(): BaseQueryFn<\r\n void,\r\n NEVER,\r\n ErrorType,\r\n {}\r\n> {\r\n return function () {\r\n throw new Error(\r\n 'When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.'\r\n )\r\n }\r\n}\r\n","import type { AnyAction, Middleware, ThunkDispatch } from '@reduxjs/toolkit'\r\nimport { createAction } from '@reduxjs/toolkit'\r\n\r\nimport type {\r\n EndpointDefinitions,\r\n FullTagDescription,\r\n} from '../../endpointDefinitions'\r\nimport type { QueryStatus, QuerySubState, RootState } from '../apiState'\r\nimport type { QueryThunkArg } from '../buildThunks'\r\nimport { buildCacheCollectionHandler } from './cacheCollection'\r\nimport { buildInvalidationByTagsHandler } from './invalidationByTags'\r\nimport { buildPollingHandler } from './polling'\r\nimport type {\r\n BuildMiddlewareInput,\r\n InternalHandlerBuilder,\r\n InternalMiddlewareState,\r\n} from './types'\r\nimport { buildWindowEventHandler } from './windowEventHandling'\r\nimport { buildCacheLifecycleHandler } from './cacheLifecycle'\r\nimport { buildQueryLifecycleHandler } from './queryLifecycle'\r\nimport { buildDevCheckHandler } from './devMiddleware'\r\nimport { buildBatchedActionsHandler } from './batchActions'\r\n\r\nexport function buildMiddleware<\r\n Definitions extends EndpointDefinitions,\r\n ReducerPath extends string,\r\n TagTypes extends string\r\n>(input: BuildMiddlewareInput<Definitions, ReducerPath, TagTypes>) {\r\n const { reducerPath, queryThunk, api, context } = input\r\n const { apiUid } = context\r\n\r\n const actions = {\r\n invalidateTags: createAction<\r\n Array<TagTypes | FullTagDescription<TagTypes>>\r\n >(`${reducerPath}/invalidateTags`),\r\n }\r\n\r\n const isThisApiSliceAction = (action: AnyAction) => {\r\n return (\r\n !!action &&\r\n typeof action.type === 'string' &&\r\n action.type.startsWith(`${reducerPath}/`)\r\n )\r\n }\r\n\r\n const handlerBuilders: InternalHandlerBuilder[] = [\r\n buildDevCheckHandler,\r\n buildCacheCollectionHandler,\r\n buildInvalidationByTagsHandler,\r\n buildPollingHandler,\r\n buildCacheLifecycleHandler,\r\n buildQueryLifecycleHandler,\r\n ]\r\n\r\n const middleware: Middleware<\r\n {},\r\n RootState<Definitions, string, ReducerPath>,\r\n ThunkDispatch<any, any, AnyAction>\r\n > = (mwApi) => {\r\n let initialized = false\r\n\r\n let internalState: InternalMiddlewareState = {\r\n currentSubscriptions: {},\r\n }\r\n\r\n const builderArgs = {\r\n ...(input as any as BuildMiddlewareInput<\r\n EndpointDefinitions,\r\n string,\r\n string\r\n >),\r\n internalState,\r\n refetchQuery,\r\n }\r\n\r\n const handlers = handlerBuilders.map((build) => build(builderArgs))\r\n\r\n const batchedActionsHandler = buildBatchedActionsHandler(builderArgs)\r\n const windowEventsHandler = buildWindowEventHandler(builderArgs)\r\n\r\n return (next) => {\r\n return (action) => {\r\n if (!initialized) {\r\n initialized = true\r\n // dispatch before any other action\r\n mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid))\r\n }\r\n\r\n const mwApiWithNext = { ...mwApi, next }\r\n\r\n const stateBefore = mwApi.getState()\r\n\r\n const [actionShouldContinue, hasSubscription] = batchedActionsHandler(\r\n action,\r\n mwApiWithNext,\r\n stateBefore\r\n )\r\n\r\n let res: any\r\n\r\n if (actionShouldContinue) {\r\n res = next(action)\r\n } else {\r\n res = hasSubscription\r\n }\r\n\r\n if (!!mwApi.getState()[reducerPath]) {\r\n // Only run these checks if the middleware is registered okay\r\n\r\n // This looks for actions that aren't specific to the API slice\r\n windowEventsHandler(action, mwApiWithNext, stateBefore)\r\n\r\n if (\r\n isThisApiSliceAction(action) ||\r\n context.hasRehydrationInfo(action)\r\n ) {\r\n // Only run these additional checks if the actions are part of the API slice,\r\n // or the action has hydration-related data\r\n for (let handler of handlers) {\r\n handler(action, mwApiWithNext, stateBefore)\r\n }\r\n }\r\n }\r\n\r\n return res\r\n }\r\n }\r\n }\r\n\r\n return { middleware, actions }\r\n\r\n function refetchQuery(\r\n querySubState: Exclude<\r\n QuerySubState<any>,\r\n { status: QueryStatus.uninitialized }\r\n >,\r\n queryCacheKey: string,\r\n override: Partial<QueryThunkArg> = {}\r\n ) {\r\n return queryThunk({\r\n type: 'query',\r\n endpointName: querySubState.endpointName,\r\n originalArgs: querySubState.originalArgs,\r\n subscribe: false,\r\n forceRefetch: true,\r\n queryCacheKey: queryCacheKey as any,\r\n ...override,\r\n })\r\n }\r\n}\r\n","import type { BaseQueryFn } from '../../baseQueryTypes'\r\nimport type { QueryDefinition } from '../../endpointDefinitions'\r\nimport type { ConfigState, QueryCacheKey } from '../apiState'\r\nimport type {\r\n QueryStateMeta,\r\n SubMiddlewareApi,\r\n TimeoutId,\r\n InternalHandlerBuilder,\r\n ApiMiddlewareInternalHandler,\r\n InternalMiddlewareState,\r\n} from './types'\r\n\r\nexport type ReferenceCacheCollection = never\r\n\r\nfunction isObjectEmpty(obj: Record<any, any>) {\r\n // Apparently a for..in loop is faster than `Object.keys()` here:\r\n // https://stackoverflow.com/a/59787784/62937\r\n for (let k in obj) {\r\n // If there is at least one key, it's not empty\r\n return false\r\n }\r\n return true\r\n}\r\n\r\ndeclare module '../../endpointDefinitions' {\r\n interface QueryExtraOptions<\r\n TagTypes extends string,\r\n ResultType,\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ReducerPath extends string = string\r\n > {\r\n /**\r\n * Overrides the api-wide definition of `keepUnusedDataFor` for this endpoint only. _(This value is in seconds.)_\r\n *\r\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.\r\n */\r\n keepUnusedDataFor?: number\r\n }\r\n}\r\n\r\n// Per https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value , browsers store\r\n// `setTimeout()` timer values in a 32-bit int. If we pass a value in that's larger than that,\r\n// it wraps and ends up executing immediately.\r\n// Our `keepUnusedDataFor` values are in seconds, so adjust the numbers here accordingly.\r\nexport const THIRTY_TWO_BIT_MAX_INT = 2_147_483_647\r\nexport const THIRTY_TWO_BIT_MAX_TIMER_SECONDS = 2_147_483_647 / 1_000 - 1\r\n\r\nexport const buildCacheCollectionHandler: InternalHandlerBuilder = ({\r\n reducerPath,\r\n api,\r\n context,\r\n internalState,\r\n}) => {\r\n const { removeQueryResult, unsubscribeQueryResult } = api.internalActions\r\n\r\n function anySubscriptionsRemainingForKey(queryCacheKey: string) {\r\n const subscriptions = internalState.currentSubscriptions[queryCacheKey]\r\n return !!subscriptions && !isObjectEmpty(subscriptions)\r\n }\r\n\r\n const currentRemovalTimeouts: QueryStateMeta<TimeoutId> = {}\r\n\r\n const handler: ApiMiddlewareInternalHandler = (\r\n action,\r\n mwApi,\r\n internalState\r\n ) => {\r\n if (unsubscribeQueryResult.match(action)) {\r\n const state = mwApi.getState()[reducerPath]\r\n const { queryCacheKey } = action.payload\r\n\r\n handleUnsubscribe(\r\n queryCacheKey,\r\n state.queries[queryCacheKey]?.endpointName,\r\n mwApi,\r\n state.config\r\n )\r\n }\r\n\r\n if (api.util.resetApiState.match(action)) {\r\n for (const [key, timeout] of Object.entries(currentRemovalTimeouts)) {\r\n if (timeout) clearTimeout(timeout)\r\n delete currentRemovalTimeouts[key]\r\n }\r\n }\r\n\r\n if (context.hasRehydrationInfo(action)) {\r\n const state = mwApi.getState()[reducerPath]\r\n const { queries } = context.extractRehydrationInfo(action)!\r\n for (const [queryCacheKey, queryState] of Object.entries(queries)) {\r\n // Gotcha:\r\n // If rehydrating before the endpoint has been injected,the global `keepUnusedDataFor`\r\n // will be used instead of the endpoint-specific one.\r\n handleUnsubscribe(\r\n queryCacheKey as QueryCacheKey,\r\n queryState?.endpointName,\r\n mwApi,\r\n state.config\r\n )\r\n }\r\n }\r\n }\r\n\r\n function handleUnsubscribe(\r\n queryCacheKey: QueryCacheKey,\r\n endpointName: string | undefined,\r\n api: SubMiddlewareApi,\r\n config: ConfigState<string>\r\n ) {\r\n const endpointDefinition = context.endpointDefinitions[\r\n endpointName!\r\n ] as QueryDefinition<any, any, any, any>\r\n const keepUnusedDataFor =\r\n endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor\r\n\r\n if (keepUnusedDataFor === Infinity) {\r\n // Hey, user said keep this forever!\r\n return\r\n }\r\n // Prevent `setTimeout` timers from overflowing a 32-bit internal int, by\r\n // clamping the max value to be at most 1000ms less than the 32-bit max.\r\n // Look, a 24.8-day keepalive ought to be enough for anybody, right? :)\r\n // Also avoid negative values too.\r\n const finalKeepUnusedDataFor = Math.max(\r\n 0,\r\n Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS)\r\n )\r\n\r\n if (!anySubscriptionsRemainingForKey(queryCacheKey)) {\r\n const currentTimeout = currentRemovalTimeouts[queryCacheKey]\r\n if (currentTimeout) {\r\n clearTimeout(currentTimeout)\r\n }\r\n currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {\r\n if (!anySubscriptionsRemainingForKey(queryCacheKey)) {\r\n api.dispatch(removeQueryResult({ queryCacheKey }))\r\n }\r\n delete currentRemovalTimeouts![queryCacheKey]\r\n }, finalKeepUnusedDataFor * 1000)\r\n }\r\n }\r\n\r\n return handler\r\n}\r\n","import { isAnyOf, isFulfilled, isRejectedWithValue } from '@reduxjs/toolkit'\r\n\r\nimport type { FullTagDescription } from '../../endpointDefinitions'\r\nimport { calculateProvidedBy } from '../../endpointDefinitions'\r\nimport type { QueryCacheKey } from '../apiState'\r\nimport { QueryStatus } from '../apiState'\r\nimport { calculateProvidedByThunk } from '../buildThunks'\r\nimport type {\r\n SubMiddlewareApi,\r\n InternalHandlerBuilder,\r\n ApiMiddlewareInternalHandler,\r\n} from './types'\r\n\r\nexport const buildInvalidationByTagsHandler: InternalHandlerBuilder = ({\r\n reducerPath,\r\n context,\r\n context: { endpointDefinitions },\r\n mutationThunk,\r\n api,\r\n assertTagType,\r\n refetchQuery,\r\n}) => {\r\n const { removeQueryResult } = api.internalActions\r\n const isThunkActionWithTags = isAnyOf(\r\n isFulfilled(mutationThunk),\r\n isRejectedWithValue(mutationThunk)\r\n )\r\n\r\n const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\r\n if (isThunkActionWithTags(action)) {\r\n invalidateTags(\r\n calculateProvidedByThunk(\r\n action,\r\n 'invalidatesTags',\r\n endpointDefinitions,\r\n assertTagType\r\n ),\r\n mwApi\r\n )\r\n }\r\n\r\n if (api.util.invalidateTags.match(action)) {\r\n invalidateTags(\r\n calculateProvidedBy(\r\n action.payload,\r\n undefined,\r\n undefined,\r\n undefined,\r\n undefined,\r\n assertTagType\r\n ),\r\n mwApi\r\n )\r\n }\r\n }\r\n\r\n function invalidateTags(\r\n tags: readonly FullTagDescription<string>[],\r\n mwApi: SubMiddlewareApi\r\n ) {\r\n const rootState = mwApi.getState()\r\n const state = rootState[reducerPath]\r\n\r\n const toInvalidate = api.util.selectInvalidatedBy(rootState, tags)\r\n\r\n context.batch(() => {\r\n const valuesArray = Array.from(toInvalidate.values())\r\n for (const { queryCacheKey } of valuesArray) {\r\n const querySubState = state.queries[queryCacheKey]\r\n const subscriptionSubState = state.subscriptions[queryCacheKey] ?? {}\r\n\r\n if (querySubState) {\r\n if (Object.keys(subscriptionSubState).length === 0) {\r\n mwApi.dispatch(\r\n removeQueryResult({\r\n queryCacheKey: queryCacheKey as QueryCacheKey,\r\n })\r\n )\r\n } else if (querySubState.status !== QueryStatus.uninitialized) {\r\n mwApi.dispatch(refetchQuery(querySubState, queryCacheKey))\r\n }\r\n }\r\n }\r\n })\r\n }\r\n\r\n return handler\r\n}\r\n","import type { QuerySubstateIdentifier, Subscribers } from '../apiState'\r\nimport { QueryStatus } from '../apiState'\r\nimport type {\r\n QueryStateMeta,\r\n SubMiddlewareApi,\r\n TimeoutId,\r\n InternalHandlerBuilder,\r\n ApiMiddlewareInternalHandler,\r\n InternalMiddlewareState,\r\n} from './types'\r\n\r\nexport const buildPollingHandler: InternalHandlerBuilder = ({\r\n reducerPath,\r\n queryThunk,\r\n api,\r\n refetchQuery,\r\n internalState,\r\n}) => {\r\n const currentPolls: QueryStateMeta<{\r\n nextPollTimestamp: number\r\n timeout?: TimeoutId\r\n pollingInterval: number\r\n }> = {}\r\n\r\n const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\r\n if (\r\n api.internalActions.updateSubscriptionOptions.match(action) ||\r\n api.internalActions.unsubscribeQueryResult.match(action)\r\n ) {\r\n updatePollingInterval(action.payload, mwApi)\r\n }\r\n\r\n if (\r\n queryThunk.pending.match(action) ||\r\n (queryThunk.rejected.match(action) && action.meta.condition)\r\n ) {\r\n updatePollingInterval(action.meta.arg, mwApi)\r\n }\r\n\r\n if (\r\n queryThunk.fulfilled.match(action) ||\r\n (queryThunk.rejected.match(action) && !action.meta.condition)\r\n ) {\r\n startNextPoll(action.meta.arg, mwApi)\r\n }\r\n\r\n if (api.util.resetApiState.match(action)) {\r\n clearPolls()\r\n }\r\n }\r\n\r\n function startNextPoll(\r\n { queryCacheKey }: QuerySubstateIdentifier,\r\n api: SubMiddlewareApi\r\n ) {\r\n const state = api.getState()[reducerPath]\r\n const querySubState = state.queries[queryCacheKey]\r\n const subscriptions = internalState.currentSubscriptions[queryCacheKey]\r\n\r\n if (!querySubState || querySubState.status === QueryStatus.uninitialized)\r\n return\r\n\r\n const lowestPollingInterval = findLowestPollingInterval(subscriptions)\r\n if (!Number.isFinite(lowestPollingInterval)) return\r\n\r\n const currentPoll = currentPolls[queryCacheKey]\r\n\r\n if (currentPoll?.timeout) {\r\n clearTimeout(currentPoll.timeout)\r\n currentPoll.timeout = undefined\r\n }\r\n\r\n const nextPollTimestamp = Date.now() + lowestPollingInterval\r\n\r\n const currentInterval: typeof currentPolls[number] = (currentPolls[\r\n queryCacheKey\r\n ] = {\r\n nextPollTimestamp,\r\n pollingInterval: lowestPollingInterval,\r\n timeout: setTimeout(() => {\r\n currentInterval!.timeout = undefined\r\n api.dispatch(refetchQuery(querySubState, queryCacheKey))\r\n }, lowestPollingInterval),\r\n })\r\n }\r\n\r\n function updatePollingInterval(\r\n { queryCacheKey }: QuerySubstateIdentifier,\r\n api: SubMiddlewareApi\r\n ) {\r\n const state = api.getState()[reducerPath]\r\n const querySubState = state.queries[queryCacheKey]\r\n const subscriptions = internalState.currentSubscriptions[queryCacheKey]\r\n\r\n if (!querySubState || querySubState.status === QueryStatus.uninitialized) {\r\n return\r\n }\r\n\r\n const lowestPollingInterval = findLowestPollingInterval(subscriptions)\r\n\r\n if (!Number.isFinite(lowestPollingInterval)) {\r\n cleanupPollForKey(queryCacheKey)\r\n return\r\n }\r\n\r\n const currentPoll = currentPolls[queryCacheKey]\r\n const nextPollTimestamp = Date.now() + lowestPollingInterval\r\n\r\n if (!currentPoll || nextPollTimestamp < currentPoll.nextPollTimestamp) {\r\n startNextPoll({ queryCacheKey }, api)\r\n }\r\n }\r\n\r\n function cleanupPollForKey(key: string) {\r\n const existingPoll = currentPolls[key]\r\n if (existingPoll?.timeout) {\r\n clearTimeout(existingPoll.timeout)\r\n }\r\n delete currentPolls[key]\r\n }\r\n\r\n function clearPolls() {\r\n for (const key of Object.keys(currentPolls)) {\r\n cleanupPollForKey(key)\r\n }\r\n }\r\n\r\n function findLowestPollingInterval(subscribers: Subscribers = {}) {\r\n let lowestPollingInterval = Number.POSITIVE_INFINITY\r\n for (let key in subscribers) {\r\n if (!!subscribers[key].pollingInterval) {\r\n lowestPollingInterval = Math.min(\r\n subscribers[key].pollingInterval!,\r\n lowestPollingInterval\r\n )\r\n }\r\n }\r\n\r\n return lowestPollingInterval\r\n }\r\n return handler\r\n}\r\n","import { isAsyncThunkAction, isFulfilled } from '@reduxjs/toolkit'\r\nimport type { AnyAction } from 'redux'\r\nimport type { ThunkDispatch } from 'redux-thunk'\r\nimport type { BaseQueryFn, BaseQueryMeta } from '../../baseQueryTypes'\r\nimport { DefinitionType } from '../../endpointDefinitions'\r\nimport type { RootState } from '../apiState'\r\nimport type {\r\n MutationResultSelectorResult,\r\n QueryResultSelectorResult,\r\n} from '../buildSelectors'\r\nimport { getMutationCacheKey } from '../buildSlice'\r\nimport type { PatchCollection, Recipe } from '../buildThunks'\r\nimport type {\r\n ApiMiddlewareInternalHandler,\r\n InternalHandlerBuilder,\r\n PromiseWithKnownReason,\r\n SubMiddlewareApi,\r\n} from './types'\r\n\r\nexport type ReferenceCacheLifecycle = never\r\n\r\ndeclare module '../../endpointDefinitions' {\r\n export interface QueryBaseLifecycleApi<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ResultType,\r\n ReducerPath extends string = string\r\n > extends LifecycleApi<ReducerPath> {\r\n /**\r\n * Gets the current value of this cache entry.\r\n */\r\n getCacheEntry(): QueryResultSelectorResult<\r\n { type: DefinitionType.query } & BaseEndpointDefinition<\r\n QueryArg,\r\n BaseQuery,\r\n ResultType\r\n >\r\n >\r\n /**\r\n * Updates the current cache entry value.\r\n * For documentation see `api.util.updateQueryData`.\r\n */\r\n updateCachedData(updateRecipe: Recipe<ResultType>): PatchCollection\r\n }\r\n\r\n export interface MutationBaseLifecycleApi<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ResultType,\r\n ReducerPath extends string = string\r\n > extends LifecycleApi<ReducerPath> {\r\n /**\r\n * Gets the current value of this cache entry.\r\n */\r\n getCacheEntry(): MutationResultSelectorResult<\r\n { type: DefinitionType.mutation } & BaseEndpointDefinition<\r\n QueryArg,\r\n BaseQuery,\r\n ResultType\r\n >\r\n >\r\n }\r\n\r\n export interface LifecycleApi<ReducerPath extends string = string> {\r\n /**\r\n * The dispatch method for the store\r\n */\r\n dispatch: ThunkDispatch<any, any, AnyAction>\r\n /**\r\n * A method to get the current state\r\n */\r\n getState(): RootState<any, any, ReducerPath>\r\n /**\r\n * `extra` as provided as `thunk.extraArgument` to the `configureStore` `getDefaultMiddleware` option.\r\n */\r\n extra: unknown\r\n /**\r\n * A unique ID generated for the mutation\r\n */\r\n requestId: string\r\n }\r\n\r\n export interface CacheLifecyclePromises<\r\n ResultType = unknown,\r\n MetaType = unknown\r\n > {\r\n /**\r\n * Promise that will resolve with the first value for this cache key.\r\n * This allows you to `await` until an actual value is in cache.\r\n *\r\n * If the cache entry is removed from the cache before any value has ever\r\n * been resolved, this Promise will reject with\r\n * `new Error('Promise never resolved before cacheEntryRemoved.')`\r\n * to prevent memory leaks.\r\n * You can just re-throw that error (or not handle it at all) -\r\n * it will be caught outside of `cacheEntryAdded`.\r\n *\r\n * If you don't interact with this promise, it will not throw.\r\n */\r\n cacheDataLoaded: PromiseWithKnownReason<\r\n {\r\n /**\r\n * The (transformed) query result.\r\n */\r\n data: ResultType\r\n /**\r\n * The `meta` returned by the `baseQuery`\r\n */\r\n meta: MetaType\r\n },\r\n typeof neverResolvedError\r\n >\r\n /**\r\n * Promise that allows you to wait for the point in time when the cache entry\r\n * has been removed from the cache, by not being used/subscribed to any more\r\n * in the application for too long or by dispatching `api.util.resetApiState`.\r\n */\r\n cacheEntryRemoved: Promise<void>\r\n }\r\n\r\n export interface QueryCacheLifecycleApi<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ResultType,\r\n ReducerPath extends string = string\r\n > extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>,\r\n CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>> {}\r\n\r\n export interface MutationCacheLifecycleApi<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ResultType,\r\n ReducerPath extends string = string\r\n > extends MutationBaseLifecycleApi<\r\n QueryArg,\r\n BaseQuery,\r\n ResultType,\r\n ReducerPath\r\n >,\r\n CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>> {}\r\n\r\n interface QueryExtraOptions<\r\n TagTypes extends string,\r\n ResultType,\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ReducerPath extends string = string\r\n > {\r\n onCacheEntryAdded?(\r\n arg: QueryArg,\r\n api: QueryCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>\r\n ): Promise<void> | void\r\n }\r\n\r\n interface MutationExtraOptions<\r\n TagTypes extends string,\r\n ResultType,\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ReducerPath extends string = string\r\n > {\r\n onCacheEntryAdded?(\r\n arg: QueryArg,\r\n api: MutationCacheLifecycleApi<\r\n QueryArg,\r\n BaseQuery,\r\n ResultType,\r\n ReducerPath\r\n >\r\n ): Promise<void> | void\r\n }\r\n}\r\n\r\nconst neverResolvedError = new Error(\r\n 'Promise never resolved before cacheEntryRemoved.'\r\n) as Error & {\r\n message: 'Promise never resolved before cacheEntryRemoved.'\r\n}\r\n\r\nexport const buildCacheLifecycleHandler: InternalHandlerBuilder = ({\r\n api,\r\n reducerPath,\r\n context,\r\n queryThunk,\r\n mutationThunk,\r\n internalState,\r\n}) => {\r\n const isQueryThunk = isAsyncThunkAction(queryThunk)\r\n const isMutationThunk = isAsyncThunkAction(mutationThunk)\r\n const isFulfilledThunk = isFulfilled(queryThunk, mutationThunk)\r\n\r\n type CacheLifecycle = {\r\n valueResolved?(value: { data: unknown; meta: unknown }): unknown\r\n cacheEntryRemoved(): void\r\n }\r\n const lifecycleMap: Record<string, CacheLifecycle> = {}\r\n\r\n const handler: ApiMiddlewareInternalHandler = (\r\n action,\r\n mwApi,\r\n stateBefore\r\n ) => {\r\n const cacheKey = getCacheKey(action)\r\n\r\n if (queryThunk.pending.match(action)) {\r\n const oldState = stateBefore[reducerPath].queries[cacheKey]\r\n const state = mwApi.getState()[reducerPath].queries[cacheKey]\r\n if (!oldState && state) {\r\n handleNewKey(\r\n action.meta.arg.endpointName,\r\n action.meta.arg.originalArgs,\r\n cacheKey,\r\n mwApi,\r\n action.meta.requestId\r\n )\r\n }\r\n } else if (mutationThunk.pending.match(action)) {\r\n const state = mwApi.getState()[reducerPath].mutations[cacheKey]\r\n if (state) {\r\n handleNewKey(\r\n action.meta.arg.endpointName,\r\n action.meta.arg.originalArgs,\r\n cacheKey,\r\n mwApi,\r\n action.meta.requestId\r\n )\r\n }\r\n } else if (isFulfilledThunk(action)) {\r\n const lifecycle = lifecycleMap[cacheKey]\r\n if (lifecycle?.valueResolved) {\r\n lifecycle.valueResolved({\r\n data: action.payload,\r\n meta: action.meta.baseQueryMeta,\r\n })\r\n delete lifecycle.valueResolved\r\n }\r\n } else if (\r\n api.internalActions.removeQueryResult.match(action) ||\r\n api.internalActions.removeMutationResult.match(action)\r\n ) {\r\n const lifecycle = lifecycleMap[cacheKey]\r\n if (lifecycle) {\r\n delete lifecycleMap[cacheKey]\r\n lifecycle.cacheEntryRemoved()\r\n }\r\n } else if (api.util.resetApiState.match(action)) {\r\n for (const [cacheKey, lifecycle] of Object.entries(lifecycleMap)) {\r\n delete lifecycleMap[cacheKey]\r\n lifecycle.cacheEntryRemoved()\r\n }\r\n }\r\n }\r\n\r\n function getCacheKey(action: any) {\r\n if (isQueryThunk(action)) return action.meta.arg.queryCacheKey\r\n if (isMutationThunk(action)) return action.meta.requestId\r\n if (api.internalActions.removeQueryResult.match(action))\r\n return action.payload.queryCacheKey\r\n if (api.internalActions.removeMutationResult.match(action))\r\n return getMutationCacheKey(action.payload)\r\n return ''\r\n }\r\n\r\n function handleNewKey(\r\n endpointName: string,\r\n originalArgs: any,\r\n queryCacheKey: string,\r\n mwApi: SubMiddlewareApi,\r\n requestId: string\r\n ) {\r\n const endpointDefinition = context.endpointDefinitions[endpointName]\r\n const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded\r\n if (!onCacheEntryAdded) return\r\n\r\n let lifecycle = {} as CacheLifecycle\r\n\r\n const cacheEntryRemoved = new Promise<void>((resolve) => {\r\n lifecycle.cacheEntryRemoved = resolve\r\n })\r\n const cacheDataLoaded: PromiseWithKnownReason<\r\n { data: unknown; meta: unknown },\r\n typeof neverResolvedError\r\n > = Promise.race([\r\n new Promise<{ data: unknown; meta: unknown }>((resolve) => {\r\n lifecycle.valueResolved = resolve\r\n }),\r\n cacheEntryRemoved.then(() => {\r\n throw neverResolvedError\r\n }),\r\n ])\r\n // prevent uncaught promise rejections from happening.\r\n // if the original promise is used in any way, that will create a new promise that will throw again\r\n cacheDataLoaded.catch(() => {})\r\n lifecycleMap[queryCacheKey] = lifecycle\r\n const selector = (api.endpoints[endpointName] as any).select(\r\n endpointDefinition.type === DefinitionType.query\r\n ? originalArgs\r\n : queryCacheKey\r\n )\r\n\r\n const extra = mwApi.dispatch((_, __, extra) => extra)\r\n const lifecycleApi = {\r\n ...mwApi,\r\n getCacheEntry: () => selector(mwApi.getState()),\r\n requestId,\r\n extra,\r\n updateCachedData: (endpointDefinition.type === DefinitionType.query\r\n ? (updateRecipe: Recipe<any>) =>\r\n mwApi.dispatch(\r\n api.util.updateQueryData(\r\n endpointName as never,\r\n originalArgs,\r\n updateRecipe\r\n )\r\n )\r\n : undefined) as any,\r\n\r\n cacheDataLoaded,\r\n cacheEntryRemoved,\r\n }\r\n\r\n const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi)\r\n // if a `neverResolvedError` was thrown, but not handled in the running handler, do not let it leak out further\r\n Promise.resolve(runningHandler).catch((e) => {\r\n if (e === neverResolvedError) return\r\n throw e\r\n })\r\n }\r\n\r\n return handler\r\n}\r\n","import { isPending, isRejected, isFulfilled } from '@reduxjs/toolkit'\r\nimport type {\r\n BaseQueryError,\r\n BaseQueryFn,\r\n BaseQueryMeta,\r\n} from '../../baseQueryTypes'\r\nimport { DefinitionType } from '../../endpointDefinitions'\r\nimport type { QueryFulfilledRejectionReason } from '../../endpointDefinitions'\r\nimport type { Recipe } from '../buildThunks'\r\nimport type {\r\n PromiseWithKnownReason,\r\n PromiseConstructorWithKnownReason,\r\n InternalHandlerBuilder,\r\n ApiMiddlewareInternalHandler,\r\n} from './types'\r\n\r\nexport type ReferenceQueryLifecycle = never\r\n\r\ndeclare module '../../endpointDefinitions' {\r\n export interface QueryLifecyclePromises<\r\n ResultType,\r\n BaseQuery extends BaseQueryFn\r\n > {\r\n /**\r\n * Promise that will resolve with the (transformed) query result.\r\n *\r\n * If the query fails, this promise will reject with the error.\r\n *\r\n * This allows you to `await` for the query to finish.\r\n *\r\n * If you don't interact with this promise, it will not throw.\r\n */\r\n queryFulfilled: PromiseWithKnownReason<\r\n {\r\n /**\r\n * The (transformed) query result.\r\n */\r\n data: ResultType\r\n /**\r\n * The `meta` returned by the `baseQuery`\r\n */\r\n meta: BaseQueryMeta<BaseQuery>\r\n },\r\n QueryFulfilledRejectionReason<BaseQuery>\r\n >\r\n }\r\n\r\n type QueryFulfilledRejectionReason<BaseQuery extends BaseQueryFn> =\r\n | {\r\n error: BaseQueryError<BaseQuery>\r\n /**\r\n * If this is `false`, that means this error was returned from the `baseQuery` or `queryFn` in a controlled manner.\r\n */\r\n isUnhandledError: false\r\n /**\r\n * The `meta` returned by the `baseQuery`\r\n */\r\n meta: BaseQueryMeta<BaseQuery>\r\n }\r\n | {\r\n error: unknown\r\n meta?: undefined\r\n /**\r\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.\r\n * There can not be made any assumption about the shape of `error`.\r\n */\r\n isUnhandledError: true\r\n }\r\n\r\n interface QueryExtraOptions<\r\n TagTypes extends string,\r\n ResultType,\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ReducerPath extends string = string\r\n > {\r\n /**\r\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).\r\n *\r\n * Can be used to perform side-effects throughout the lifecycle of the query.\r\n *\r\n * @example\r\n * ```ts\r\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\r\n * import { messageCreated } from './notificationsSlice\r\n * export interface Post {\r\n * id: number\r\n * name: string\r\n * }\r\n *\r\n * const api = createApi({\r\n * baseQuery: fetchBaseQuery({\r\n * baseUrl: '/',\r\n * }),\r\n * endpoints: (build) => ({\r\n * getPost: build.query<Post, number>({\r\n * query: (id) => `post/${id}`,\r\n * async onQueryStarted(id, { dispatch, queryFulfilled }) {\r\n * // `onStart` side-effect\r\n * dispatch(messageCreated('Fetching posts...'))\r\n * try {\r\n * const { data } = await queryFulfilled\r\n * // `onSuccess` side-effect\r\n * dispatch(messageCreated('Posts received!'))\r\n * } catch (err) {\r\n * // `onError` side-effect\r\n * dispatch(messageCreated('Error fetching posts!'))\r\n * }\r\n * }\r\n * }),\r\n * }),\r\n * })\r\n * ```\r\n */\r\n onQueryStarted?(\r\n arg: QueryArg,\r\n api: QueryLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>\r\n ): Promise<void> | void\r\n }\r\n\r\n interface MutationExtraOptions<\r\n TagTypes extends string,\r\n ResultType,\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ReducerPath extends string = string\r\n > {\r\n /**\r\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).\r\n *\r\n * Can be used for `optimistic updates`.\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\r\n * export interface Post {\r\n * id: number\r\n * name: string\r\n * }\r\n *\r\n * const api = createApi({\r\n * baseQuery: fetchBaseQuery({\r\n * baseUrl: '/',\r\n * }),\r\n * tagTypes: ['Post'],\r\n * endpoints: (build) => ({\r\n * getPost: build.query<Post, number>({\r\n * query: (id) => `post/${id}`,\r\n * providesTags: ['Post'],\r\n * }),\r\n * updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({\r\n * query: ({ id, ...patch }) => ({\r\n * url: `post/${id}`,\r\n * method: 'PATCH',\r\n * body: patch,\r\n * }),\r\n * invalidatesTags: ['Post'],\r\n * async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {\r\n * const patchResult = dispatch(\r\n * api.util.updateQueryData('getPost', id, (draft) => {\r\n * Object.assign(draft, patch)\r\n * })\r\n * )\r\n * try {\r\n * await queryFulfilled\r\n * } catch {\r\n * patchResult.undo()\r\n * }\r\n * },\r\n * }),\r\n * }),\r\n * })\r\n * ```\r\n */\r\n onQueryStarted?(\r\n arg: QueryArg,\r\n api: MutationLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>\r\n ): Promise<void> | void\r\n }\r\n\r\n export interface QueryLifecycleApi<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ResultType,\r\n ReducerPath extends string = string\r\n > extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>,\r\n QueryLifecyclePromises<ResultType, BaseQuery> {}\r\n\r\n export interface MutationLifecycleApi<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ResultType,\r\n ReducerPath extends string = string\r\n > extends MutationBaseLifecycleApi<\r\n QueryArg,\r\n BaseQuery,\r\n ResultType,\r\n ReducerPath\r\n >,\r\n QueryLifecyclePromises<ResultType, BaseQuery> {}\r\n}\r\n\r\nexport const buildQueryLifecycleHandler: InternalHandlerBuilder = ({\r\n api,\r\n context,\r\n queryThunk,\r\n mutationThunk,\r\n}) => {\r\n const isPendingThunk = isPending(queryThunk, mutationThunk)\r\n const isRejectedThunk = isRejected(queryThunk, mutationThunk)\r\n const isFullfilledThunk = isFulfilled(queryThunk, mutationThunk)\r\n\r\n type CacheLifecycle = {\r\n resolve(value: { data: unknown; meta: unknown }): unknown\r\n reject(value: QueryFulfilledRejectionReason<any>): unknown\r\n }\r\n const lifecycleMap: Record<string, CacheLifecycle> = {}\r\n\r\n const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\r\n if (isPendingThunk(action)) {\r\n const {\r\n requestId,\r\n arg: { endpointName, originalArgs },\r\n } = action.meta\r\n const endpointDefinition = context.endpointDefinitions[endpointName]\r\n const onQueryStarted = endpointDefinition?.onQueryStarted\r\n if (onQueryStarted) {\r\n const lifecycle = {} as CacheLifecycle\r\n const queryFulfilled =\r\n new (Promise as PromiseConstructorWithKnownReason)<\r\n { data: unknown; meta: unknown },\r\n QueryFulfilledRejectionReason<any>\r\n >((resolve, reject) => {\r\n lifecycle.resolve = resolve\r\n lifecycle.reject = reject\r\n })\r\n // prevent uncaught promise rejections from happening.\r\n // if the original promise is used in any way, that will create a new promise that will throw again\r\n queryFulfilled.catch(() => {})\r\n lifecycleMap[requestId] = lifecycle\r\n const selector = (api.endpoints[endpointName] as any).select(\r\n endpointDefinition.type === DefinitionType.query\r\n ? originalArgs\r\n : requestId\r\n )\r\n\r\n const extra = mwApi.dispatch((_, __, extra) => extra)\r\n const lifecycleApi = {\r\n ...mwApi,\r\n getCacheEntry: () => selector(mwApi.getState()),\r\n requestId,\r\n extra,\r\n updateCachedData: (endpointDefinition.type === DefinitionType.query\r\n ? (updateRecipe: Recipe<any>) =>\r\n mwApi.dispatch(\r\n api.util.updateQueryData(\r\n endpointName as never,\r\n originalArgs,\r\n updateRecipe\r\n )\r\n )\r\n : undefined) as any,\r\n queryFulfilled,\r\n }\r\n onQueryStarted(originalArgs, lifecycleApi)\r\n }\r\n } else if (isFullfilledThunk(action)) {\r\n const { requestId, baseQueryMeta } = action.meta\r\n lifecycleMap[requestId]?.resolve({\r\n data: action.payload,\r\n meta: baseQueryMeta,\r\n })\r\n delete lifecycleMap[requestId]\r\n } else if (isRejectedThunk(action)) {\r\n const { requestId, rejectedWithValue, baseQueryMeta } = action.meta\r\n lifecycleMap[requestId]?.reject({\r\n error: action.payload ?? action.error,\r\n isUnhandledError: !rejectedWithValue,\r\n meta: baseQueryMeta as any,\r\n })\r\n delete lifecycleMap[requestId]\r\n }\r\n }\r\n\r\n return handler\r\n}\r\n","import type { QueryThunk, RejectedAction } from '../buildThunks'\r\nimport type { InternalHandlerBuilder } from './types'\r\nimport type {\r\n SubscriptionState,\r\n QuerySubstateIdentifier,\r\n Subscribers,\r\n} from '../apiState'\r\nimport { produceWithPatches } from 'immer'\r\nimport type { AnyAction } from '@reduxjs/toolkit';\r\nimport { createSlice, PayloadAction } from '@reduxjs/toolkit'\r\n\r\n// Copied from https://github.com/feross/queue-microtask\r\nlet promise: Promise<any>\r\nconst queueMicrotaskShim =\r\n typeof queueMicrotask === 'function'\r\n ? queueMicrotask.bind(\r\n typeof window !== 'undefined'\r\n ? window\r\n : typeof global !== 'undefined'\r\n ? global\r\n : globalThis\r\n )\r\n : // reuse resolved promise, and allocate it lazily\r\n (cb: () => void) =>\r\n (promise || (promise = Promise.resolve())).then(cb).catch((err: any) =>\r\n setTimeout(() => {\r\n throw err\r\n }, 0)\r\n )\r\n\r\nexport const buildBatchedActionsHandler: InternalHandlerBuilder<\r\n [actionShouldContinue: boolean, subscriptionExists: boolean]\r\n> = ({ api, queryThunk, internalState }) => {\r\n const subscriptionsPrefix = `${api.reducerPath}/subscriptions`\r\n\r\n let previousSubscriptions: SubscriptionState =\r\n null as unknown as SubscriptionState\r\n\r\n let dispatchQueued = false\r\n\r\n const { updateSubscriptionOptions, unsubscribeQueryResult } =\r\n api.internalActions\r\n\r\n // Actually intentionally mutate the subscriptions state used in the middleware\r\n // This is done to speed up perf when loading many components\r\n const actuallyMutateSubscriptions = (\r\n mutableState: SubscriptionState,\r\n action: AnyAction\r\n ) => {\r\n if (updateSubscriptionOptions.match(action)) {\r\n const { queryCacheKey, requestId, options } = action.payload\r\n\r\n if (mutableState?.[queryCacheKey]?.[requestId]) {\r\n mutableState[queryCacheKey]![requestId] = options\r\n }\r\n return true\r\n }\r\n if (unsubscribeQueryResult.match(action)) {\r\n const { queryCacheKey, requestId } = action.payload\r\n if (mutableState[queryCacheKey]) {\r\n delete mutableState[queryCacheKey]![requestId]\r\n }\r\n return true\r\n }\r\n if (api.internalActions.removeQueryResult.match(action)) {\r\n delete mutableState[action.payload.queryCacheKey]\r\n return true\r\n }\r\n if (queryThunk.pending.match(action)) {\r\n const {\r\n meta: { arg, requestId },\r\n } = action\r\n if (arg.subscribe) {\r\n const substate = (mutableState[arg.queryCacheKey] ??= {})\r\n substate[requestId] =\r\n arg.subscriptionOptions ?? substate[requestId] ?? {}\r\n\r\n return true\r\n }\r\n }\r\n if (queryThunk.rejected.match(action)) {\r\n const {\r\n meta: { condition, arg, requestId },\r\n } = action\r\n if (condition && arg.subscribe) {\r\n const substate = (mutableState[arg.queryCacheKey] ??= {})\r\n substate[requestId] =\r\n arg.subscriptionOptions ?? substate[requestId] ?? {}\r\n\r\n return true\r\n }\r\n }\r\n\r\n return false\r\n }\r\n\r\n return (action, mwApi) => {\r\n if (!previousSubscriptions) {\r\n // Initialize it the first time this handler runs\r\n previousSubscriptions = JSON.parse(\r\n JSON.stringify(internalState.currentSubscriptions)\r\n )\r\n }\r\n\r\n if (api.util.resetApiState.match(action)) {\r\n previousSubscriptions = internalState.currentSubscriptions = {}\r\n return [true, false]\r\n }\r\n\r\n // Intercept requests by hooks to see if they're subscribed\r\n // Necessary because we delay updating store state to the end of the tick\r\n if (api.internalActions.internal_probeSubscription.match(action)) {\r\n const { queryCacheKey, requestId } = action.payload\r\n const hasSubscription =\r\n !!internalState.currentSubscriptions[queryCacheKey]?.[requestId]\r\n return [false, hasSubscription]\r\n }\r\n\r\n // Update subscription data based on this action\r\n const didMutate = actuallyMutateSubscriptions(\r\n internalState.currentSubscriptions,\r\n action\r\n )\r\n\r\n if (didMutate) {\r\n if (!dispatchQueued) {\r\n queueMicrotaskShim(() => {\r\n // Deep clone the current subscription data\r\n const newSubscriptions: SubscriptionState = JSON.parse(\r\n JSON.stringify(internalState.currentSubscriptions)\r\n )\r\n // Figure out a smaller diff between original and current\r\n const [, patches] = produceWithPatches(\r\n previousSubscriptions,\r\n () => newSubscriptions\r\n )\r\n\r\n // Sync the store state for visibility\r\n mwApi.next(api.internalActions.subscriptionsUpdated(patches))\r\n // Save the cloned state for later reference\r\n previousSubscriptions = newSubscriptions\r\n dispatchQueued = false\r\n })\r\n dispatchQueued = true\r\n }\r\n\r\n const isSubscriptionSliceAction =\r\n !!action.type?.startsWith(subscriptionsPrefix)\r\n const isAdditionalSubscriptionAction =\r\n queryThunk.rejected.match(action) &&\r\n action.meta.condition &&\r\n !!action.meta.arg.subscribe\r\n\r\n const actionShouldContinue =\r\n !isSubscriptionSliceAction && !isAdditionalSubscriptionAction\r\n\r\n return [actionShouldContinue, false]\r\n }\r\n\r\n return [true, false]\r\n }\r\n}\r\n","import type { InternalHandlerBuilder } from './types'\r\n\r\nexport const buildDevCheckHandler: InternalHandlerBuilder = ({\r\n api,\r\n context: { apiUid },\r\n reducerPath,\r\n}) => {\r\n return (action, mwApi) => {\r\n if (api.util.resetApiState.match(action)) {\r\n // dispatch after api reset\r\n mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid))\r\n }\r\n\r\n if (\r\n typeof process !== 'undefined' &&\r\n process.env.NODE_ENV === 'development'\r\n ) {\r\n if (\r\n api.internalActions.middlewareRegistered.match(action) &&\r\n action.payload === apiUid &&\r\n mwApi.getState()[reducerPath]?.config?.middlewareRegistered ===\r\n 'conflict'\r\n ) {\r\n console.warn(`There is a mismatch between slice and middleware for the reducerPath \"${reducerPath}\".\r\nYou can only have one api per reducer path, this will lead to crashes in various situations!${\r\n reducerPath === 'api'\r\n ? `\r\nIf you have multiple apis, you *have* to specify the reducerPath option when using createApi!`\r\n : ''\r\n }`)\r\n }\r\n }\r\n }\r\n}\r\n","export type Id<T> = { [K in keyof T]: T[K] } & {}\r\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> &\r\n Required<Pick<T, K>>\r\nexport type Override<T1, T2> = T2 extends any ? Omit<T1, keyof T2> & T2 : never\r\nexport function assertCast<T>(v: any): asserts v is T {}\r\n\r\nexport function safeAssign<T extends object>(\r\n target: T,\r\n ...args: Array<Partial<NoInfer<T>>>\r\n) {\r\n Object.assign(target, ...args)\r\n}\r\n\r\n/**\r\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\r\n */\r\nexport type UnionToIntersection<U> = (\r\n U extends any ? (k: U) => void : never\r\n) extends (k: infer I) => void\r\n ? I\r\n : never\r\n\r\nexport type NonOptionalKeys<T> = {\r\n [K in keyof T]-?: undefined extends T[K] ? never : K\r\n}[keyof T]\r\n\r\nexport type HasRequiredProps<T, True, False> = NonOptionalKeys<T> extends never\r\n ? False\r\n : True\r\n\r\nexport type OptionalIfAllPropsOptional<T> = HasRequiredProps<T, T, T | never>\r\n\r\nexport type NoInfer<T> = [T][T extends any ? 0 : never]\r\n\r\nexport type NonUndefined<T> = T extends undefined ? never : T\r\n\r\nexport type UnwrapPromise<T> = T extends PromiseLike<infer V> ? V : T\r\n\r\nexport type MaybePromise<T> = T | PromiseLike<T>\r\n\r\nexport type OmitFromUnion<T, K extends keyof T> = T extends any\r\n ? Omit<T, K>\r\n : never\r\n\r\nexport type IsAny<T, True, False = never> = true | false extends (\r\n T extends never ? true : false\r\n)\r\n ? True\r\n : False\r\n\r\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>\r\n","/**\r\n * Note: this file should import all other files for type discovery and declaration merging\r\n */\r\nimport type {\r\n PatchQueryDataThunk,\r\n UpdateQueryDataThunk,\r\n UpsertQueryDataThunk,\r\n} from './buildThunks'\r\nimport { buildThunks } from './buildThunks'\r\nimport type {\r\n ActionCreatorWithPayload,\r\n AnyAction,\r\n Middleware,\r\n Reducer,\r\n ThunkAction,\r\n ThunkDispatch,\r\n} from '@reduxjs/toolkit'\r\nimport type {\r\n EndpointDefinitions,\r\n QueryArgFrom,\r\n QueryDefinition,\r\n MutationDefinition,\r\n AssertTagTypes,\r\n TagDescription,\r\n} from '../endpointDefinitions'\r\nimport { isQueryDefinition, isMutationDefinition } from '../endpointDefinitions'\r\nimport type {\r\n CombinedState,\r\n QueryKeys,\r\n MutationKeys,\r\n RootState,\r\n} from './apiState'\r\nimport type { Api, Module } from '../apiTypes'\r\nimport { onFocus, onFocusLost, onOnline, onOffline } from './setupListeners'\r\nimport { buildSlice } from './buildSlice'\r\nimport { buildMiddleware } from './buildMiddleware'\r\nimport { buildSelectors } from './buildSelectors'\r\nimport type {\r\n MutationActionCreatorResult,\r\n QueryActionCreatorResult,\r\n} from './buildInitiate'\r\nimport { buildInitiate } from './buildInitiate'\r\nimport { assertCast, safeAssign } from '../tsHelpers'\r\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'\r\nimport type { SliceActions } from './buildSlice'\r\nimport type { BaseQueryFn } from '../baseQueryTypes'\r\n\r\nimport type { ReferenceCacheLifecycle } from './buildMiddleware/cacheLifecycle'\r\nimport type { ReferenceQueryLifecycle } from './buildMiddleware/queryLifecycle'\r\nimport type { ReferenceCacheCollection } from './buildMiddleware/cacheCollection'\r\nimport { enablePatches } from 'immer'\r\n\r\n/**\r\n * `ifOlderThan` - (default: `false` | `number`) - _number is value in seconds_\r\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\r\n *\r\n * @overloadSummary\r\n * `force`\r\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.\r\n */\r\nexport type PrefetchOptions =\r\n | {\r\n ifOlderThan?: false | number\r\n }\r\n | { force?: boolean }\r\n\r\nexport const coreModuleName = /* @__PURE__ */ Symbol()\r\nexport type CoreModule =\r\n | typeof coreModuleName\r\n | ReferenceCacheLifecycle\r\n | ReferenceQueryLifecycle\r\n | ReferenceCacheCollection\r\n\r\nexport interface ThunkWithReturnValue<T> extends ThunkAction<T, any, any, AnyAction> {}\r\n\r\ndeclare module '../apiTypes' {\r\n export interface ApiModules<\r\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\r\n BaseQuery extends BaseQueryFn,\r\n Definitions extends EndpointDefinitions,\r\n ReducerPath extends string,\r\n TagTypes extends string\r\n > {\r\n [coreModuleName]: {\r\n /**\r\n * This api's reducer should be mounted at `store[api.reducerPath]`.\r\n *\r\n * @example\r\n * ```ts\r\n * configureStore({\r\n * reducer: {\r\n * [api.reducerPath]: api.reducer,\r\n * },\r\n * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\r\n * })\r\n * ```\r\n */\r\n reducerPath: ReducerPath\r\n /**\r\n * Internal actions not part of the public API. Note: These are subject to change at any given time.\r\n */\r\n internalActions: InternalActions\r\n /**\r\n * A standard redux reducer that enables core functionality. Make sure it's included in your store.\r\n *\r\n * @example\r\n * ```ts\r\n * configureStore({\r\n * reducer: {\r\n * [api.reducerPath]: api.reducer,\r\n * },\r\n * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\r\n * })\r\n * ```\r\n */\r\n reducer: Reducer<\r\n CombinedState<Definitions, TagTypes, ReducerPath>,\r\n AnyAction\r\n >\r\n /**\r\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.\r\n *\r\n * @example\r\n * ```ts\r\n * configureStore({\r\n * reducer: {\r\n * [api.reducerPath]: api.reducer,\r\n * },\r\n * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\r\n * })\r\n * ```\r\n */\r\n middleware: Middleware<\r\n {},\r\n RootState<Definitions, string, ReducerPath>,\r\n ThunkDispatch<any, any, AnyAction>\r\n >\r\n /**\r\n * A collection of utility thunks for various situations.\r\n */\r\n util: {\r\n /**\r\n * This method had to be removed due to a conceptual bug in RTK.\r\n *\r\n * Despite TypeScript errors, it will continue working in the \"buggy\" way it did\r\n * before in production builds and will be removed in the next major release.\r\n *\r\n * Nonetheless, you should immediately replace it with the new recommended approach.\r\n * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for new guidance on SSR.\r\n *\r\n * Please see https://github.com/reduxjs/redux-toolkit/pull/2481 for details.\r\n * @deprecated\r\n */\r\n getRunningOperationPromises: never // this is now types as `never` to immediately throw TS errors on use, but still allow for a comment\r\n\r\n /**\r\n * This method had to be removed due to a conceptual bug in RTK.\r\n * It has been replaced by `api.util.getRunningQueryThunk` and `api.util.getRunningMutationThunk`.\r\n * Please see https://github.com/reduxjs/redux-toolkit/pull/2481 for details.\r\n * @deprecated\r\n */\r\n getRunningOperationPromise: never // this is now types as `never` to immediately throw TS errors on use, but still allow for a comment\r\n\r\n /**\r\n * A thunk that (if dispatched) will return a specific running query, identified\r\n * by `endpointName` and `args`.\r\n * If that query is not running, dispatching the thunk will result in `undefined`.\r\n *\r\n * Can be used to await a specific query triggered in any way,\r\n * including via hook calls or manually dispatching `initiate` actions.\r\n *\r\n * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\r\n */\r\n getRunningQueryThunk<EndpointName extends QueryKeys<Definitions>>(\r\n endpointName: EndpointName,\r\n args: QueryArgFrom<Definitions[EndpointName]>\r\n ): ThunkWithReturnValue<\r\n | QueryActionCreatorResult<\r\n Definitions[EndpointName] & { type: 'query' }\r\n >\r\n | undefined\r\n >\r\n\r\n /**\r\n * A thunk that (if dispatched) will return a specific running mutation, identified\r\n * by `endpointName` and `fixedCacheKey` or `requestId`.\r\n * If that mutation is not running, dispatching the thunk will result in `undefined`.\r\n *\r\n * Can be used to await a specific mutation triggered in any way,\r\n * including via hook trigger functions or manually dispatching `initiate` actions.\r\n *\r\n * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\r\n */\r\n getRunningMutationThunk<EndpointName extends MutationKeys<Definitions>>(\r\n endpointName: EndpointName,\r\n fixedCacheKeyOrRequestId: string\r\n ): ThunkWithReturnValue<\r\n | MutationActionCreatorResult<\r\n Definitions[EndpointName] & { type: 'mutation' }\r\n >\r\n | undefined\r\n >\r\n\r\n /**\r\n * A thunk that (if dispatched) will return all running queries.\r\n *\r\n * Useful for SSR scenarios to await all running queries triggered in any way,\r\n * including via hook calls or manually dispatching `initiate` actions.\r\n *\r\n * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\r\n */\r\n getRunningQueriesThunk(): ThunkWithReturnValue<\r\n Array<QueryActionCreatorResult<any>>\r\n >\r\n\r\n /**\r\n * A thunk that (if dispatched) will return all running mutations.\r\n *\r\n * Useful for SSR scenarios to await all running mutations triggered in any way,\r\n * including via hook calls or manually dispatching `initiate` actions.\r\n *\r\n * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\r\n */\r\n getRunningMutationsThunk(): ThunkWithReturnValue<\r\n Array<MutationActionCreatorResult<any>>\r\n >\r\n\r\n /**\r\n * A Redux thunk that can be used to manually trigger pre-fetching of data.\r\n *\r\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.\r\n *\r\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.\r\n *\r\n * @example\r\n *\r\n * ```ts no-transpile\r\n * dispatch(api.util.prefetch('getPosts', undefined, { force: true }))\r\n * ```\r\n */\r\n prefetch<EndpointName extends QueryKeys<Definitions>>(\r\n endpointName: EndpointName,\r\n arg: QueryArgFrom<Definitions[EndpointName]>,\r\n options: PrefetchOptions\r\n ): ThunkAction<void, any, any, AnyAction>\r\n /**\r\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.\r\n *\r\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.\r\n *\r\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).\r\n *\r\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, args, inversePatches))`. Alternatively, the `undo` method can be called directly to achieve the same effect.\r\n *\r\n * Note that the first two arguments (`endpointName` and `args`) are used to determine which existing cache entry to update. If no existing cache entry is found, the `updateRecipe` callback will not run.\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * const patchCollection = dispatch(\r\n * api.util.updateQueryData('getPosts', undefined, (draftPosts) => {\r\n * draftPosts.push({ id: 1, name: 'Teddy' })\r\n * })\r\n * )\r\n * ```\r\n */\r\n updateQueryData: UpdateQueryDataThunk<\r\n Definitions,\r\n RootState<Definitions, string, ReducerPath>\r\n >\r\n /** @deprecated renamed to `updateQueryData` */\r\n updateQueryResult: UpdateQueryDataThunk<\r\n Definitions,\r\n RootState<Definitions, string, ReducerPath>\r\n >\r\n /**\r\n * A Redux thunk action creator that, when dispatched, acts as an artificial API request to upsert a value into the cache.\r\n *\r\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.\r\n *\r\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.\r\n *\r\n * The thunk executes _asynchronously_, and returns a promise that resolves when the store has been updated.\r\n *\r\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.\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * await dispatch(\r\n * api.util.upsertQueryData('getPost', {id: 1}, {id: 1, text: \"Hello!\"})\r\n * )\r\n * ```\r\n */\r\n upsertQueryData: UpsertQueryDataThunk<\r\n Definitions,\r\n RootState<Definitions, string, ReducerPath>\r\n >\r\n /**\r\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.\r\n *\r\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`.\r\n *\r\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.\r\n *\r\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.\r\n *\r\n * @example\r\n * ```ts\r\n * const patchCollection = dispatch(\r\n * api.util.updateQueryData('getPosts', undefined, (draftPosts) => {\r\n * draftPosts.push({ id: 1, name: 'Teddy' })\r\n * })\r\n * )\r\n *\r\n * // later\r\n * dispatch(\r\n * api.util.patchQueryData('getPosts', undefined, patchCollection.inversePatches)\r\n * )\r\n *\r\n * // or\r\n * patchCollection.undo()\r\n * ```\r\n */\r\n patchQueryData: PatchQueryDataThunk<\r\n Definitions,\r\n RootState<Definitions, string, ReducerPath>\r\n >\r\n /** @deprecated renamed to `patchQueryData` */\r\n patchQueryResult: PatchQueryDataThunk<\r\n Definitions,\r\n RootState<Definitions, string, ReducerPath>\r\n >\r\n /**\r\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'.\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * dispatch(api.util.resetApiState())\r\n * ```\r\n */\r\n resetApiState: SliceActions['resetApiState']\r\n /**\r\n * A Redux action creator that can be used to manually invalidate cache tags for [automated re-fetching](../../usage/automated-refetching.mdx).\r\n *\r\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.\r\n *\r\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.\r\n *\r\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:\r\n *\r\n * - `[TagType]`\r\n * - `[{ type: TagType }]`\r\n * - `[{ type: TagType, id: number | string }]`\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * dispatch(api.util.invalidateTags(['Post']))\r\n * dispatch(api.util.invalidateTags([{ type: 'Post', id: 1 }]))\r\n * dispatch(\r\n * api.util.invalidateTags([\r\n * { type: 'Post', id: 1 },\r\n * { type: 'Post', id: 'LIST' },\r\n * ])\r\n * )\r\n * ```\r\n */\r\n invalidateTags: ActionCreatorWithPayload<\r\n Array<TagDescription<TagTypes>>,\r\n string\r\n >\r\n\r\n /**\r\n * A function to select all `{ endpointName, originalArgs, queryCacheKey }` combinations that would be invalidated by a specific set of tags.\r\n *\r\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.\r\n */\r\n selectInvalidatedBy: (\r\n state: RootState<Definitions, string, ReducerPath>,\r\n tags: ReadonlyArray<TagDescription<TagTypes>>\r\n ) => Array<{\r\n endpointName: string\r\n originalArgs: any\r\n queryCacheKey: string\r\n }>\r\n }\r\n /**\r\n * Endpoints based on the input endpoints provided to `createApi`, containing `select` and `action matchers`.\r\n */\r\n endpoints: {\r\n [K in keyof Definitions]: Definitions[K] extends QueryDefinition<\r\n any,\r\n any,\r\n any,\r\n any,\r\n any\r\n >\r\n ? ApiEndpointQuery<Definitions[K], Definitions>\r\n : Definitions[K] extends MutationDefinition<any, any, any, any, any>\r\n ? ApiEndpointMutation<Definitions[K], Definitions>\r\n : never\r\n }\r\n }\r\n }\r\n}\r\n\r\nexport interface ApiEndpointQuery<\r\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\r\n Definition extends QueryDefinition<any, any, any, any, any>,\r\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\r\n Definitions extends EndpointDefinitions\r\n> {\r\n name: string\r\n /**\r\n * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\r\n */\r\n Types: NonNullable<Definition['Types']>\r\n}\r\n\r\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\r\nexport interface ApiEndpointMutation<\r\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\r\n Definition extends MutationDefinition<any, any, any, any, any>,\r\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\r\n Definitions extends EndpointDefinitions\r\n> {\r\n name: string\r\n /**\r\n * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\r\n */\r\n Types: NonNullable<Definition['Types']>\r\n}\r\n\r\nexport type ListenerActions = {\r\n /**\r\n * Will cause the RTK Query middleware to trigger any refetchOnReconnect-related behavior\r\n * @link https://rtk-query-docs.netlify.app/api/setupListeners\r\n */\r\n onOnline: typeof onOnline\r\n onOffline: typeof onOffline\r\n /**\r\n * Will cause the RTK Query middleware to trigger any refetchOnFocus-related behavior\r\n * @link https://rtk-query-docs.netlify.app/api/setupListeners\r\n */\r\n onFocus: typeof onFocus\r\n onFocusLost: typeof onFocusLost\r\n}\r\n\r\nexport type InternalActions = SliceActions & ListenerActions\r\n\r\n/**\r\n * Creates a module containing the basic redux logic for use with `buildCreateApi`.\r\n *\r\n * @example\r\n * ```ts\r\n * const createBaseApi = buildCreateApi(coreModule());\r\n * ```\r\n */\r\nexport const coreModule = (): Module<CoreModule> => ({\r\n name: coreModuleName,\r\n init(\r\n api,\r\n {\r\n baseQuery,\r\n tagTypes,\r\n reducerPath,\r\n serializeQueryArgs,\r\n keepUnusedDataFor,\r\n refetchOnMountOrArgChange,\r\n refetchOnFocus,\r\n refetchOnReconnect,\r\n },\r\n context\r\n ) {\r\n enablePatches()\r\n\r\n assertCast<InternalSerializeQueryArgs>(serializeQueryArgs)\r\n\r\n const assertTagType: AssertTagTypes = (tag) => {\r\n if (\r\n typeof process !== 'undefined' &&\r\n process.env.NODE_ENV === 'development'\r\n ) {\r\n if (!tagTypes.includes(tag.type as any)) {\r\n console.error(\r\n `Tag type '${tag.type}' was used, but not specified in \\`tagTypes\\`!`\r\n )\r\n }\r\n }\r\n return tag\r\n }\r\n\r\n Object.assign(api, {\r\n reducerPath,\r\n endpoints: {},\r\n internalActions: {\r\n onOnline,\r\n onOffline,\r\n onFocus,\r\n onFocusLost,\r\n },\r\n util: {},\r\n })\r\n\r\n const {\r\n queryThunk,\r\n mutationThunk,\r\n patchQueryData,\r\n updateQueryData,\r\n upsertQueryData,\r\n prefetch,\r\n buildMatchThunkActions,\r\n } = buildThunks({\r\n baseQuery,\r\n reducerPath,\r\n context,\r\n api,\r\n serializeQueryArgs,\r\n assertTagType,\r\n })\r\n\r\n const { reducer, actions: sliceActions } = buildSlice({\r\n context,\r\n queryThunk,\r\n mutationThunk,\r\n reducerPath,\r\n assertTagType,\r\n config: {\r\n refetchOnFocus,\r\n refetchOnReconnect,\r\n refetchOnMountOrArgChange,\r\n keepUnusedDataFor,\r\n reducerPath,\r\n },\r\n })\r\n\r\n safeAssign(api.util, {\r\n patchQueryData,\r\n updateQueryData,\r\n upsertQueryData,\r\n prefetch,\r\n resetApiState: sliceActions.resetApiState,\r\n })\r\n safeAssign(api.internalActions, sliceActions)\r\n\r\n const { middleware, actions: middlewareActions } = buildMiddleware({\r\n reducerPath,\r\n context,\r\n queryThunk,\r\n mutationThunk,\r\n api,\r\n assertTagType,\r\n })\r\n safeAssign(api.util, middlewareActions)\r\n\r\n safeAssign(api, { reducer: reducer as any, middleware })\r\n\r\n const { buildQuerySelector, buildMutationSelector, selectInvalidatedBy } =\r\n buildSelectors({\r\n serializeQueryArgs: serializeQueryArgs as any,\r\n reducerPath,\r\n })\r\n\r\n safeAssign(api.util, { selectInvalidatedBy })\r\n\r\n const {\r\n buildInitiateQuery,\r\n buildInitiateMutation,\r\n getRunningMutationThunk,\r\n getRunningMutationsThunk,\r\n getRunningQueriesThunk,\r\n getRunningQueryThunk,\r\n getRunningOperationPromises,\r\n removalWarning,\r\n } = buildInitiate({\r\n queryThunk,\r\n mutationThunk,\r\n api,\r\n serializeQueryArgs: serializeQueryArgs as any,\r\n context,\r\n })\r\n\r\n safeAssign(api.util, {\r\n getRunningOperationPromises: getRunningOperationPromises as any,\r\n getRunningOperationPromise: removalWarning as any,\r\n getRunningMutationThunk,\r\n getRunningMutationsThunk,\r\n getRunningQueryThunk,\r\n getRunningQueriesThunk,\r\n })\r\n\r\n return {\r\n name: coreModuleName,\r\n injectEndpoint(endpointName, definition) {\r\n const anyApi = api as any as Api<\r\n any,\r\n Record<string, any>,\r\n string,\r\n string,\r\n CoreModule\r\n >\r\n anyApi.endpoints[endpointName] ??= {} as any\r\n if (isQueryDefinition(definition)) {\r\n safeAssign(\r\n anyApi.endpoints[endpointName],\r\n {\r\n name: endpointName,\r\n select: buildQuerySelector(endpointName, definition),\r\n initiate: buildInitiateQuery(endpointName, definition),\r\n },\r\n buildMatchThunkActions(queryThunk, endpointName)\r\n )\r\n } else if (isMutationDefinition(definition)) {\r\n safeAssign(\r\n anyApi.endpoints[endpointName],\r\n {\r\n name: endpointName,\r\n select: buildMutationSelector(),\r\n initiate: buildInitiateMutation(endpointName),\r\n },\r\n buildMatchThunkActions(mutationThunk, endpointName)\r\n )\r\n }\r\n },\r\n }\r\n },\r\n})\r\n","/**\r\n * Assumes a browser is online if `undefined`, otherwise makes a best effort\r\n * @link https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine\r\n */\r\nexport function isOnline() {\r\n // We set the default config value in the store, so we'd need to check for this in a SSR env\r\n return typeof navigator === 'undefined'\r\n ? true\r\n : navigator.onLine === undefined\r\n ? true\r\n : navigator.onLine\r\n}\r\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 */\r\nexport function isDocumentVisible(): boolean {\r\n // `document` may not exist in non-browser envs (like RN)\r\n if (typeof document === 'undefined') {\r\n return true\r\n }\r\n // Match true for visible, prerender, undefined\r\n return document.visibilityState !== 'hidden'\r\n}\r\n","import { QueryStatus } from '../apiState'\r\nimport type { QueryCacheKey } from '../apiState'\r\nimport { onFocus, onOnline } from '../setupListeners'\r\nimport type {\r\n ApiMiddlewareInternalHandler,\r\n InternalHandlerBuilder,\r\n SubMiddlewareApi,\r\n} from './types'\r\n\r\nexport const buildWindowEventHandler: InternalHandlerBuilder = ({\r\n reducerPath,\r\n context,\r\n api,\r\n refetchQuery,\r\n internalState,\r\n}) => {\r\n const { removeQueryResult } = api.internalActions\r\n\r\n const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\r\n if (onFocus.match(action)) {\r\n refetchValidQueries(mwApi, 'refetchOnFocus')\r\n }\r\n if (onOnline.match(action)) {\r\n refetchValidQueries(mwApi, 'refetchOnReconnect')\r\n }\r\n }\r\n\r\n function refetchValidQueries(\r\n api: SubMiddlewareApi,\r\n type: 'refetchOnFocus' | 'refetchOnReconnect'\r\n ) {\r\n const state = api.getState()[reducerPath]\r\n const queries = state.queries\r\n const subscriptions = internalState.currentSubscriptions\r\n\r\n context.batch(() => {\r\n for (const queryCacheKey of Object.keys(subscriptions)) {\r\n const querySubState = queries[queryCacheKey]\r\n const subscriptionSubState = subscriptions[queryCacheKey]\r\n\r\n if (!subscriptionSubState || !querySubState) continue\r\n\r\n const shouldRefetch =\r\n Object.values(subscriptionSubState).some(\r\n (sub) => sub[type] === true\r\n ) ||\r\n (Object.values(subscriptionSubState).every(\r\n (sub) => sub[type] === undefined\r\n ) &&\r\n state.config[type])\r\n\r\n if (shouldRefetch) {\r\n if (Object.keys(subscriptionSubState).length === 0) {\r\n api.dispatch(\r\n removeQueryResult({\r\n queryCacheKey: queryCacheKey as QueryCacheKey,\r\n })\r\n )\r\n } else if (querySubState.status !== QueryStatus.uninitialized) {\r\n api.dispatch(refetchQuery(querySubState, queryCacheKey))\r\n }\r\n }\r\n }\r\n })\r\n }\r\n\r\n return handler\r\n}\r\n","import { buildCreateApi, CreateApi } from '../createApi'\r\nimport { coreModule, coreModuleName } from './module'\r\n\r\nconst createApi = /* @__PURE__ */ buildCreateApi(coreModule())\r\n\r\nexport { createApi, coreModule, coreModuleName }\r\n"],"mappings":"IAiCYA,EAAAC,E,wjBAAAA,EAAAD,MAAA,KACV,cAAgB,gBAChBC,EAAA,QAAU,UACVA,EAAA,UAAY,YACZA,EAAA,SAAW,WChCN,IAAMC,EAAWC,GAAwB,GAAGC,UAAUD,2BCL7DE,MAAA,mBAGA,IAAMC,EAAqCD,EAGpC,SAAAE,EAAmCC,EAAaC,GACrD,GACED,IAAWC,KAERH,EAAcE,IAAWF,EAAcG,IACvCC,MAAMC,QAAQH,IAAWE,MAAMC,QAAQF,IAG1C,OAAOA,EAET,MAAMG,EAAUC,OAAOC,KAAKL,GACtBM,EAAUF,OAAOC,KAAKN,GAE5B,IAAIQ,EAAeJ,EAAQK,SAAWF,EAAQE,OAC9C,MAAMC,EAAgBR,MAAMC,QAAQF,GAAU,GAAK,GACnD,UAAWU,KAAOP,EAChBM,EAASC,GAAOZ,EAA0BC,EAAOW,GAAMV,EAAOU,IAC1DH,IAAcA,EAAeR,EAAOW,KAASD,EAASC,IAE5D,OAAOH,EAAeR,EAASU,0BCxBjCE,MAAA,mBAsCA,IAAMC,EAA+B,IAAIC,IAASC,SAASD,GAErDE,EAAyBC,GAC7BA,EAASC,QAAU,KAAOD,EAASC,QAAU,IAEzCC,EAA4BC,GACnB,yBAAyBC,KAAKD,EAAQE,IAAI,iBAAmB,IAmD5E,SAAAC,EAAwBC,GACtB,IAAKZ,EAAcY,GACjB,OAAOA,EAET,MAAMC,EAA4BC,EAAA,GAAKF,GACvC,UAAYG,EAAGC,KAAMvB,OAAO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