UNPKG

76.2 kBJavaScriptView Raw
1var __defProp = Object.defineProperty;
2var __defProps = Object.defineProperties;
3var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5var __hasOwnProp = Object.prototype.hasOwnProperty;
6var __propIsEnum = Object.prototype.propertyIsEnumerable;
7var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8var __spreadValues = (a, b) => {
9 for (var prop in b || (b = {}))
10 if (__hasOwnProp.call(b, prop))
11 __defNormalProp(a, prop, b[prop]);
12 if (__getOwnPropSymbols)
13 for (var prop of __getOwnPropSymbols(b)) {
14 if (__propIsEnum.call(b, prop))
15 __defNormalProp(a, prop, b[prop]);
16 }
17 return a;
18};
19var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20var __objRest = (source, exclude) => {
21 var target = {};
22 for (var prop in source)
23 if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
24 target[prop] = source[prop];
25 if (source != null && __getOwnPropSymbols)
26 for (var prop of __getOwnPropSymbols(source)) {
27 if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
28 target[prop] = source[prop];
29 }
30 return target;
31};
32// src/query/core/apiState.ts
33var QueryStatus;
34(function (QueryStatus2) {
35 QueryStatus2["uninitialized"] = "uninitialized";
36 QueryStatus2["pending"] = "pending";
37 QueryStatus2["fulfilled"] = "fulfilled";
38 QueryStatus2["rejected"] = "rejected";
39})(QueryStatus || (QueryStatus = {}));
40function getRequestStatusFlags(status) {
41 return {
42 status,
43 isUninitialized: status === QueryStatus.uninitialized,
44 isLoading: status === QueryStatus.pending,
45 isSuccess: status === QueryStatus.fulfilled,
46 isError: status === QueryStatus.rejected
47 };
48}
49// src/query/utils/isAbsoluteUrl.ts
50function isAbsoluteUrl(url) {
51 return new RegExp(`(^|:)//`).test(url);
52}
53// src/query/utils/joinUrls.ts
54var withoutTrailingSlash = (url) => url.replace(/\/$/, "");
55var withoutLeadingSlash = (url) => url.replace(/^\//, "");
56function joinUrls(base, url) {
57 if (!base) {
58 return url;
59 }
60 if (!url) {
61 return base;
62 }
63 if (isAbsoluteUrl(url)) {
64 return url;
65 }
66 base = withoutTrailingSlash(base);
67 url = withoutLeadingSlash(url);
68 return `${base}/${url}`;
69}
70// src/query/utils/flatten.ts
71var flatten = (arr) => [].concat(...arr);
72// src/query/utils/isOnline.ts
73function isOnline() {
74 return typeof navigator === "undefined" ? true : navigator.onLine === void 0 ? true : navigator.onLine;
75}
76// src/query/utils/isDocumentVisible.ts
77function isDocumentVisible() {
78 if (typeof document === "undefined") {
79 return true;
80 }
81 return document.visibilityState !== "hidden";
82}
83// src/query/utils/copyWithStructuralSharing.ts
84import { isPlainObject as _iPO } from "@reduxjs/toolkit";
85var isPlainObject = _iPO;
86function copyWithStructuralSharing(oldObj, newObj) {
87 if (oldObj === newObj || !(isPlainObject(oldObj) && isPlainObject(newObj) || Array.isArray(oldObj) && Array.isArray(newObj))) {
88 return newObj;
89 }
90 const newKeys = Object.keys(newObj);
91 const oldKeys = Object.keys(oldObj);
92 let isSameObject = newKeys.length === oldKeys.length;
93 const mergeObj = Array.isArray(newObj) ? [] : {};
94 for (const key of newKeys) {
95 mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key]);
96 if (isSameObject)
97 isSameObject = oldObj[key] === mergeObj[key];
98 }
99 return isSameObject ? oldObj : mergeObj;
100}
101// src/query/fetchBaseQuery.ts
102import { isPlainObject as isPlainObject2 } from "@reduxjs/toolkit";
103var defaultFetchFn = (...args) => fetch(...args);
104var defaultValidateStatus = (response) => response.status >= 200 && response.status <= 299;
105var isJsonContentType = (headers) => {
106 var _a, _b;
107 return (_b = (_a = headers.get("content-type")) == null ? void 0 : _a.trim()) == null ? void 0 : _b.startsWith("application/json");
108};
109var handleResponse = async (response, responseHandler) => {
110 if (typeof responseHandler === "function") {
111 return responseHandler(response);
112 }
113 if (responseHandler === "text") {
114 return response.text();
115 }
116 if (responseHandler === "json") {
117 const text = await response.text();
118 return text.length ? JSON.parse(text) : null;
119 }
120};
121function stripUndefined(obj) {
122 if (!isPlainObject2(obj)) {
123 return obj;
124 }
125 const copy = __spreadValues({}, obj);
126 for (const [k, v] of Object.entries(copy)) {
127 if (typeof v === "undefined")
128 delete copy[k];
129 }
130 return copy;
131}
132function fetchBaseQuery(_a = {}) {
133 var _b = _a, { baseUrl, prepareHeaders = (x) => x, fetchFn = defaultFetchFn, paramsSerializer } = _b, baseFetchOptions = __objRest(_b, [
134 "baseUrl",
135 "prepareHeaders",
136 "fetchFn",
137 "paramsSerializer"
138 ]);
139 if (typeof fetch === "undefined" && fetchFn === defaultFetchFn) {
140 console.warn("Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.");
141 }
142 return async (arg, api) => {
143 const { signal, getState, extra, endpoint, forced, type } = api;
144 let meta;
145 let _a2 = typeof arg == "string" ? { url: arg } : arg, { url, method = "GET", headers = new Headers({}), body = void 0, params = void 0, responseHandler = "json", validateStatus = defaultValidateStatus } = _a2, rest = __objRest(_a2, [
146 "url",
147 "method",
148 "headers",
149 "body",
150 "params",
151 "responseHandler",
152 "validateStatus"
153 ]);
154 let config = __spreadValues(__spreadProps(__spreadValues({}, baseFetchOptions), {
155 method,
156 signal,
157 body
158 }), rest);
159 config.headers = await prepareHeaders(new Headers(stripUndefined(headers)), { getState, extra, endpoint, forced, type });
160 const isJsonifiable = (body2) => typeof body2 === "object" && (isPlainObject2(body2) || Array.isArray(body2) || typeof body2.toJSON === "function");
161 if (!config.headers.has("content-type") && isJsonifiable(body)) {
162 config.headers.set("content-type", "application/json");
163 }
164 if (body && isJsonContentType(config.headers)) {
165 config.body = JSON.stringify(body);
166 }
167 if (params) {
168 const divider = ~url.indexOf("?") ? "&" : "?";
169 const query = paramsSerializer ? paramsSerializer(params) : new URLSearchParams(stripUndefined(params));
170 url += divider + query;
171 }
172 url = joinUrls(baseUrl, url);
173 const request = new Request(url, config);
174 const requestClone = request.clone();
175 meta = { request: requestClone };
176 let response;
177 try {
178 response = await fetchFn(request);
179 }
180 catch (e) {
181 return { error: { status: "FETCH_ERROR", error: String(e) }, meta };
182 }
183 const responseClone = response.clone();
184 meta.response = responseClone;
185 let resultData;
186 let responseText = "";
187 try {
188 let handleResponseError;
189 await Promise.all([
190 handleResponse(response, responseHandler).then((r) => resultData = r, (e) => handleResponseError = e),
191 responseClone.text().then((r) => responseText = r, () => {
192 })
193 ]);
194 if (handleResponseError)
195 throw handleResponseError;
196 }
197 catch (e) {
198 return {
199 error: {
200 status: "PARSING_ERROR",
201 originalStatus: response.status,
202 data: responseText,
203 error: String(e)
204 },
205 meta
206 };
207 }
208 return validateStatus(response, resultData) ? {
209 data: resultData,
210 meta
211 } : {
212 error: {
213 status: response.status,
214 data: resultData
215 },
216 meta
217 };
218 };
219}
220// src/query/HandledError.ts
221var HandledError = class {
222 constructor(value, meta = void 0) {
223 this.value = value;
224 this.meta = meta;
225 }
226};
227// src/query/retry.ts
228async function defaultBackoff(attempt = 0, maxRetries = 5) {
229 const attempts = Math.min(attempt, maxRetries);
230 const timeout = ~~((Math.random() + 0.4) * (300 << attempts));
231 await new Promise((resolve) => setTimeout((res) => resolve(res), timeout));
232}
233function fail(e) {
234 throw Object.assign(new HandledError({ error: e }), {
235 throwImmediately: true
236 });
237}
238var retryWithBackoff = (baseQuery, defaultOptions) => async (args, api, extraOptions) => {
239 const options = __spreadValues(__spreadValues({
240 maxRetries: 5,
241 backoff: defaultBackoff
242 }, defaultOptions), extraOptions);
243 let retry2 = 0;
244 while (true) {
245 try {
246 const result = await baseQuery(args, api, extraOptions);
247 if (result.error) {
248 throw new HandledError(result);
249 }
250 return result;
251 }
252 catch (e) {
253 retry2++;
254 if (e.throwImmediately || retry2 > options.maxRetries) {
255 if (e instanceof HandledError) {
256 return e.value;
257 }
258 throw e;
259 }
260 await options.backoff(retry2, options.maxRetries);
261 }
262 }
263};
264var retry = /* @__PURE__ */ Object.assign(retryWithBackoff, { fail });
265// src/query/core/setupListeners.ts
266import { createAction } from "@reduxjs/toolkit";
267var onFocus = /* @__PURE__ */ createAction("__rtkq/focused");
268var onFocusLost = /* @__PURE__ */ createAction("__rtkq/unfocused");
269var onOnline = /* @__PURE__ */ createAction("__rtkq/online");
270var onOffline = /* @__PURE__ */ createAction("__rtkq/offline");
271var initialized = false;
272function setupListeners(dispatch, customHandler) {
273 function defaultHandler() {
274 const handleFocus = () => dispatch(onFocus());
275 const handleFocusLost = () => dispatch(onFocusLost());
276 const handleOnline = () => dispatch(onOnline());
277 const handleOffline = () => dispatch(onOffline());
278 const handleVisibilityChange = () => {
279 if (window.document.visibilityState === "visible") {
280 handleFocus();
281 }
282 else {
283 handleFocusLost();
284 }
285 };
286 if (!initialized) {
287 if (typeof window !== "undefined" && window.addEventListener) {
288 window.addEventListener("visibilitychange", handleVisibilityChange, false);
289 window.addEventListener("focus", handleFocus, false);
290 window.addEventListener("online", handleOnline, false);
291 window.addEventListener("offline", handleOffline, false);
292 initialized = true;
293 }
294 }
295 const unsubscribe = () => {
296 window.removeEventListener("focus", handleFocus);
297 window.removeEventListener("visibilitychange", handleVisibilityChange);
298 window.removeEventListener("online", handleOnline);
299 window.removeEventListener("offline", handleOffline);
300 initialized = false;
301 };
302 return unsubscribe;
303 }
304 return customHandler ? customHandler(dispatch, { onFocus, onFocusLost, onOffline, onOnline }) : defaultHandler();
305}
306// src/query/core/buildSelectors.ts
307import { createNextState, createSelector } from "@reduxjs/toolkit";
308// src/query/endpointDefinitions.ts
309var DefinitionType;
310(function (DefinitionType2) {
311 DefinitionType2["query"] = "query";
312 DefinitionType2["mutation"] = "mutation";
313})(DefinitionType || (DefinitionType = {}));
314function isQueryDefinition(e) {
315 return e.type === DefinitionType.query;
316}
317function isMutationDefinition(e) {
318 return e.type === DefinitionType.mutation;
319}
320function calculateProvidedBy(description, result, error, queryArg, meta, assertTagTypes) {
321 if (isFunction(description)) {
322 return description(result, error, queryArg, meta).map(expandTagDescription).map(assertTagTypes);
323 }
324 if (Array.isArray(description)) {
325 return description.map(expandTagDescription).map(assertTagTypes);
326 }
327 return [];
328}
329function isFunction(t) {
330 return typeof t === "function";
331}
332function expandTagDescription(description) {
333 return typeof description === "string" ? { type: description } : description;
334}
335// src/query/core/buildSlice.ts
336import { combineReducers, createAction as createAction2, createSlice, isAnyOf, isFulfilled as isFulfilled2, isRejectedWithValue as isRejectedWithValue2 } from "@reduxjs/toolkit";
337// src/query/core/buildThunks.ts
338import { isAllOf, isFulfilled, isPending, isRejected, isRejectedWithValue } from "@reduxjs/toolkit";
339import { isDraftable, produceWithPatches } from "immer";
340import { createAsyncThunk } from "@reduxjs/toolkit";
341function defaultTransformResponse(baseQueryReturnValue) {
342 return baseQueryReturnValue;
343}
344function buildThunks({ reducerPath, baseQuery, context: { endpointDefinitions }, serializeQueryArgs, api }) {
345 const patchQueryData = (endpointName, args, patches) => (dispatch) => {
346 const endpointDefinition = endpointDefinitions[endpointName];
347 dispatch(api.internalActions.queryResultPatched({
348 queryCacheKey: serializeQueryArgs({
349 queryArgs: args,
350 endpointDefinition,
351 endpointName
352 }),
353 patches
354 }));
355 };
356 const updateQueryData = (endpointName, args, updateRecipe) => (dispatch, getState) => {
357 const currentState = api.endpoints[endpointName].select(args)(getState());
358 let ret = {
359 patches: [],
360 inversePatches: [],
361 undo: () => dispatch(api.util.patchQueryData(endpointName, args, ret.inversePatches))
362 };
363 if (currentState.status === QueryStatus.uninitialized) {
364 return ret;
365 }
366 if ("data" in currentState) {
367 if (isDraftable(currentState.data)) {
368 const [, patches, inversePatches] = produceWithPatches(currentState.data, updateRecipe);
369 ret.patches.push(...patches);
370 ret.inversePatches.push(...inversePatches);
371 }
372 else {
373 const value = updateRecipe(currentState.data);
374 ret.patches.push({ op: "replace", path: [], value });
375 ret.inversePatches.push({
376 op: "replace",
377 path: [],
378 value: currentState.data
379 });
380 }
381 }
382 dispatch(api.util.patchQueryData(endpointName, args, ret.patches));
383 return ret;
384 };
385 const executeEndpoint = async (arg, { signal, rejectWithValue, fulfillWithValue, dispatch, getState, extra }) => {
386 const endpointDefinition = endpointDefinitions[arg.endpointName];
387 try {
388 let transformResponse = defaultTransformResponse;
389 let result;
390 const baseQueryApi = {
391 signal,
392 dispatch,
393 getState,
394 extra,
395 endpoint: arg.endpointName,
396 type: arg.type,
397 forced: arg.type === "query" ? isForcedQuery(arg, getState()) : void 0
398 };
399 if (endpointDefinition.query) {
400 result = await baseQuery(endpointDefinition.query(arg.originalArgs), baseQueryApi, endpointDefinition.extraOptions);
401 if (endpointDefinition.transformResponse) {
402 transformResponse = endpointDefinition.transformResponse;
403 }
404 }
405 else {
406 result = await endpointDefinition.queryFn(arg.originalArgs, baseQueryApi, endpointDefinition.extraOptions, (arg2) => baseQuery(arg2, baseQueryApi, endpointDefinition.extraOptions));
407 }
408 if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
409 const what = endpointDefinition.query ? "`baseQuery`" : "`queryFn`";
410 let err;
411 if (!result) {
412 err = `${what} did not return anything.`;
413 }
414 else if (typeof result !== "object") {
415 err = `${what} did not return an object.`;
416 }
417 else if (result.error && result.data) {
418 err = `${what} returned an object containing both \`error\` and \`result\`.`;
419 }
420 else if (result.error === void 0 && result.data === void 0) {
421 err = `${what} returned an object containing neither a valid \`error\` and \`result\`. At least one of them should not be \`undefined\``;
422 }
423 else {
424 for (const key of Object.keys(result)) {
425 if (key !== "error" && key !== "data" && key !== "meta") {
426 err = `The object returned by ${what} has the unknown property ${key}.`;
427 break;
428 }
429 }
430 }
431 if (err) {
432 console.error(`Error encountered handling the endpoint ${arg.endpointName}.
433 ${err}
434 It needs to return an object with either the shape \`{ data: <value> }\` or \`{ error: <value> }\` that may contain an optional \`meta\` property.
435 Object returned was:`, result);
436 }
437 }
438 if (result.error)
439 throw new HandledError(result.error, result.meta);
440 return fulfillWithValue(await transformResponse(result.data, result.meta, arg.originalArgs), {
441 fulfilledTimeStamp: Date.now(),
442 baseQueryMeta: result.meta
443 });
444 }
445 catch (error) {
446 if (error instanceof HandledError) {
447 return rejectWithValue(error.value, { baseQueryMeta: error.meta });
448 }
449 if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
450 console.error(`An unhandled error occured processing a request for the endpoint "${arg.endpointName}".
451In the case of an unhandled error, no tags will be "provided" or "invalidated".`, error);
452 }
453 else {
454 console.error(error);
455 }
456 throw error;
457 }
458 };
459 function isForcedQuery(arg, state) {
460 var _a, _b, _c, _d;
461 const requestState = (_b = (_a = state[reducerPath]) == null ? void 0 : _a.queries) == null ? void 0 : _b[arg.queryCacheKey];
462 const baseFetchOnMountOrArgChange = (_c = state[reducerPath]) == null ? void 0 : _c.config.refetchOnMountOrArgChange;
463 const fulfilledVal = requestState == null ? void 0 : requestState.fulfilledTimeStamp;
464 const refetchVal = (_d = arg.forceRefetch) != null ? _d : arg.subscribe && baseFetchOnMountOrArgChange;
465 if (refetchVal) {
466 return refetchVal === true || (Number(new Date()) - Number(fulfilledVal)) / 1e3 >= refetchVal;
467 }
468 return false;
469 }
470 const queryThunk = createAsyncThunk(`${reducerPath}/executeQuery`, executeEndpoint, {
471 getPendingMeta() {
472 return { startedTimeStamp: Date.now() };
473 },
474 condition(arg, { getState }) {
475 var _a, _b;
476 const state = getState();
477 const requestState = (_b = (_a = state[reducerPath]) == null ? void 0 : _a.queries) == null ? void 0 : _b[arg.queryCacheKey];
478 const fulfilledVal = requestState == null ? void 0 : requestState.fulfilledTimeStamp;
479 if ((requestState == null ? void 0 : requestState.status) === "pending")
480 return false;
481 if (isForcedQuery(arg, state))
482 return true;
483 if (fulfilledVal)
484 return false;
485 return true;
486 },
487 dispatchConditionRejection: true
488 });
489 const mutationThunk = createAsyncThunk(`${reducerPath}/executeMutation`, executeEndpoint, {
490 getPendingMeta() {
491 return { startedTimeStamp: Date.now() };
492 }
493 });
494 const hasTheForce = (options) => "force" in options;
495 const hasMaxAge = (options) => "ifOlderThan" in options;
496 const prefetch = (endpointName, arg, options) => (dispatch, getState) => {
497 const force = hasTheForce(options) && options.force;
498 const maxAge = hasMaxAge(options) && options.ifOlderThan;
499 const queryAction = (force2 = true) => api.endpoints[endpointName].initiate(arg, { forceRefetch: force2 });
500 const latestStateValue = api.endpoints[endpointName].select(arg)(getState());
501 if (force) {
502 dispatch(queryAction());
503 }
504 else if (maxAge) {
505 const lastFulfilledTs = latestStateValue == null ? void 0 : latestStateValue.fulfilledTimeStamp;
506 if (!lastFulfilledTs) {
507 dispatch(queryAction());
508 return;
509 }
510 const shouldRetrigger = (Number(new Date()) - Number(new Date(lastFulfilledTs))) / 1e3 >= maxAge;
511 if (shouldRetrigger) {
512 dispatch(queryAction());
513 }
514 }
515 else {
516 dispatch(queryAction(false));
517 }
518 };
519 function matchesEndpoint(endpointName) {
520 return (action) => {
521 var _a, _b;
522 return ((_b = (_a = action == null ? void 0 : action.meta) == null ? void 0 : _a.arg) == null ? void 0 : _b.endpointName) === endpointName;
523 };
524 }
525 function buildMatchThunkActions(thunk, endpointName) {
526 return {
527 matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)),
528 matchFulfilled: isAllOf(isFulfilled(thunk), matchesEndpoint(endpointName)),
529 matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpointName))
530 };
531 }
532 return {
533 queryThunk,
534 mutationThunk,
535 prefetch,
536 updateQueryData,
537 patchQueryData,
538 buildMatchThunkActions
539 };
540}
541function calculateProvidedByThunk(action, type, endpointDefinitions, assertTagType) {
542 return calculateProvidedBy(endpointDefinitions[action.meta.arg.endpointName][type], isFulfilled(action) ? action.payload : void 0, isRejectedWithValue(action) ? action.payload : void 0, action.meta.arg.originalArgs, "baseQueryMeta" in action.meta ? action.meta.baseQueryMeta : void 0, assertTagType);
543}
544// src/query/core/buildSlice.ts
545import { applyPatches } from "immer";
546function updateQuerySubstateIfExists(state, queryCacheKey, update) {
547 const substate = state[queryCacheKey];
548 if (substate) {
549 update(substate);
550 }
551}
552function getMutationCacheKey(id) {
553 var _a;
554 return (_a = "arg" in id ? id.arg.fixedCacheKey : id.fixedCacheKey) != null ? _a : id.requestId;
555}
556function updateMutationSubstateIfExists(state, id, update) {
557 const substate = state[getMutationCacheKey(id)];
558 if (substate) {
559 update(substate);
560 }
561}
562var initialState = {};
563function buildSlice({ reducerPath, queryThunk, mutationThunk, context: { endpointDefinitions: definitions, apiUid, extractRehydrationInfo, hasRehydrationInfo }, assertTagType, config }) {
564 const resetApiState = createAction2(`${reducerPath}/resetApiState`);
565 const querySlice = createSlice({
566 name: `${reducerPath}/queries`,
567 initialState,
568 reducers: {
569 removeQueryResult(draft, { payload: { queryCacheKey } }) {
570 delete draft[queryCacheKey];
571 },
572 queryResultPatched(draft, { payload: { queryCacheKey, patches } }) {
573 updateQuerySubstateIfExists(draft, queryCacheKey, (substate) => {
574 substate.data = applyPatches(substate.data, patches.concat());
575 });
576 }
577 },
578 extraReducers(builder) {
579 builder.addCase(queryThunk.pending, (draft, { meta, meta: { arg } }) => {
580 var _a, _b;
581 if (arg.subscribe) {
582 (_b = draft[_a = arg.queryCacheKey]) != null ? _b : draft[_a] = {
583 status: QueryStatus.uninitialized,
584 endpointName: arg.endpointName
585 };
586 }
587 updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {
588 substate.status = QueryStatus.pending;
589 substate.requestId = meta.requestId;
590 if (arg.originalArgs !== void 0) {
591 substate.originalArgs = arg.originalArgs;
592 }
593 substate.startedTimeStamp = meta.startedTimeStamp;
594 });
595 }).addCase(queryThunk.fulfilled, (draft, { meta, payload }) => {
596 updateQuerySubstateIfExists(draft, meta.arg.queryCacheKey, (substate) => {
597 var _a;
598 if (substate.requestId !== meta.requestId)
599 return;
600 substate.status = QueryStatus.fulfilled;
601 substate.data = ((_a = definitions[meta.arg.endpointName].structuralSharing) != null ? _a : true) ? copyWithStructuralSharing(substate.data, payload) : payload;
602 delete substate.error;
603 substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;
604 });
605 }).addCase(queryThunk.rejected, (draft, { meta: { condition, arg, requestId }, error, payload }) => {
606 updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {
607 if (condition) {
608 }
609 else {
610 if (substate.requestId !== requestId)
611 return;
612 substate.status = QueryStatus.rejected;
613 substate.error = payload != null ? payload : error;
614 }
615 });
616 }).addMatcher(hasRehydrationInfo, (draft, action) => {
617 const { queries } = extractRehydrationInfo(action);
618 for (const [key, entry] of Object.entries(queries)) {
619 if ((entry == null ? void 0 : entry.status) === QueryStatus.fulfilled || (entry == null ? void 0 : entry.status) === QueryStatus.rejected) {
620 draft[key] = entry;
621 }
622 }
623 });
624 }
625 });
626 const mutationSlice = createSlice({
627 name: `${reducerPath}/mutations`,
628 initialState,
629 reducers: {
630 removeMutationResult(draft, { payload }) {
631 const cacheKey = getMutationCacheKey(payload);
632 if (cacheKey in draft) {
633 delete draft[cacheKey];
634 }
635 }
636 },
637 extraReducers(builder) {
638 builder.addCase(mutationThunk.pending, (draft, { meta, meta: { requestId, arg, startedTimeStamp } }) => {
639 if (!arg.track)
640 return;
641 draft[getMutationCacheKey(meta)] = {
642 requestId,
643 status: QueryStatus.pending,
644 endpointName: arg.endpointName,
645 startedTimeStamp
646 };
647 }).addCase(mutationThunk.fulfilled, (draft, { payload, meta }) => {
648 if (!meta.arg.track)
649 return;
650 updateMutationSubstateIfExists(draft, meta, (substate) => {
651 if (substate.requestId !== meta.requestId)
652 return;
653 substate.status = QueryStatus.fulfilled;
654 substate.data = payload;
655 substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;
656 });
657 }).addCase(mutationThunk.rejected, (draft, { payload, error, meta }) => {
658 if (!meta.arg.track)
659 return;
660 updateMutationSubstateIfExists(draft, meta, (substate) => {
661 if (substate.requestId !== meta.requestId)
662 return;
663 substate.status = QueryStatus.rejected;
664 substate.error = payload != null ? payload : error;
665 });
666 }).addMatcher(hasRehydrationInfo, (draft, action) => {
667 const { mutations } = extractRehydrationInfo(action);
668 for (const [key, entry] of Object.entries(mutations)) {
669 if (((entry == null ? void 0 : entry.status) === QueryStatus.fulfilled || (entry == null ? void 0 : entry.status) === QueryStatus.rejected) && key !== (entry == null ? void 0 : entry.requestId)) {
670 draft[key] = entry;
671 }
672 }
673 });
674 }
675 });
676 const invalidationSlice = createSlice({
677 name: `${reducerPath}/invalidation`,
678 initialState,
679 reducers: {},
680 extraReducers(builder) {
681 builder.addCase(querySlice.actions.removeQueryResult, (draft, { payload: { queryCacheKey } }) => {
682 for (const tagTypeSubscriptions of Object.values(draft)) {
683 for (const idSubscriptions of Object.values(tagTypeSubscriptions)) {
684 const foundAt = idSubscriptions.indexOf(queryCacheKey);
685 if (foundAt !== -1) {
686 idSubscriptions.splice(foundAt, 1);
687 }
688 }
689 }
690 }).addMatcher(hasRehydrationInfo, (draft, action) => {
691 var _a, _b, _c, _d;
692 const { provided } = extractRehydrationInfo(action);
693 for (const [type, incomingTags] of Object.entries(provided)) {
694 for (const [id, cacheKeys] of Object.entries(incomingTags)) {
695 const subscribedQueries = (_d = (_b = (_a = draft[type]) != null ? _a : draft[type] = {})[_c = id || "__internal_without_id"]) != null ? _d : _b[_c] = [];
696 for (const queryCacheKey of cacheKeys) {
697 const alreadySubscribed = subscribedQueries.includes(queryCacheKey);
698 if (!alreadySubscribed) {
699 subscribedQueries.push(queryCacheKey);
700 }
701 }
702 }
703 }
704 }).addMatcher(isAnyOf(isFulfilled2(queryThunk), isRejectedWithValue2(queryThunk)), (draft, action) => {
705 var _a, _b, _c, _d;
706 const providedTags = calculateProvidedByThunk(action, "providesTags", definitions, assertTagType);
707 const { queryCacheKey } = action.meta.arg;
708 for (const { type, id } of providedTags) {
709 const subscribedQueries = (_d = (_b = (_a = draft[type]) != null ? _a : draft[type] = {})[_c = id || "__internal_without_id"]) != null ? _d : _b[_c] = [];
710 const alreadySubscribed = subscribedQueries.includes(queryCacheKey);
711 if (!alreadySubscribed) {
712 subscribedQueries.push(queryCacheKey);
713 }
714 }
715 });
716 }
717 });
718 const subscriptionSlice = createSlice({
719 name: `${reducerPath}/subscriptions`,
720 initialState,
721 reducers: {
722 updateSubscriptionOptions(draft, { payload: { queryCacheKey, requestId, options } }) {
723 var _a;
724 if ((_a = draft == null ? void 0 : draft[queryCacheKey]) == null ? void 0 : _a[requestId]) {
725 draft[queryCacheKey][requestId] = options;
726 }
727 },
728 unsubscribeQueryResult(draft, { payload: { queryCacheKey, requestId } }) {
729 if (draft[queryCacheKey]) {
730 delete draft[queryCacheKey][requestId];
731 }
732 }
733 },
734 extraReducers: (builder) => {
735 builder.addCase(querySlice.actions.removeQueryResult, (draft, { payload: { queryCacheKey } }) => {
736 delete draft[queryCacheKey];
737 }).addCase(queryThunk.pending, (draft, { meta: { arg, requestId } }) => {
738 var _a, _b, _c, _d;
739 if (arg.subscribe) {
740 const substate = (_b = draft[_a = arg.queryCacheKey]) != null ? _b : draft[_a] = {};
741 substate[requestId] = (_d = (_c = arg.subscriptionOptions) != null ? _c : substate[requestId]) != null ? _d : {};
742 }
743 }).addCase(queryThunk.rejected, (draft, { meta: { condition, arg, requestId }, error, payload }) => {
744 var _a, _b, _c, _d;
745 if (condition && arg.subscribe) {
746 const substate = (_b = draft[_a = arg.queryCacheKey]) != null ? _b : draft[_a] = {};
747 substate[requestId] = (_d = (_c = arg.subscriptionOptions) != null ? _c : substate[requestId]) != null ? _d : {};
748 }
749 }).addMatcher(hasRehydrationInfo, (draft) => __spreadValues({}, draft));
750 }
751 });
752 const configSlice = createSlice({
753 name: `${reducerPath}/config`,
754 initialState: __spreadValues({
755 online: isOnline(),
756 focused: isDocumentVisible(),
757 middlewareRegistered: false
758 }, config),
759 reducers: {
760 middlewareRegistered(state, { payload }) {
761 state.middlewareRegistered = state.middlewareRegistered === "conflict" || apiUid !== payload ? "conflict" : true;
762 }
763 },
764 extraReducers: (builder) => {
765 builder.addCase(onOnline, (state) => {
766 state.online = true;
767 }).addCase(onOffline, (state) => {
768 state.online = false;
769 }).addCase(onFocus, (state) => {
770 state.focused = true;
771 }).addCase(onFocusLost, (state) => {
772 state.focused = false;
773 }).addMatcher(hasRehydrationInfo, (draft) => __spreadValues({}, draft));
774 }
775 });
776 const combinedReducer = combineReducers({
777 queries: querySlice.reducer,
778 mutations: mutationSlice.reducer,
779 provided: invalidationSlice.reducer,
780 subscriptions: subscriptionSlice.reducer,
781 config: configSlice.reducer
782 });
783 const reducer = (state, action) => combinedReducer(resetApiState.match(action) ? void 0 : state, action);
784 const actions = __spreadProps(__spreadValues(__spreadValues(__spreadValues(__spreadValues({}, configSlice.actions), querySlice.actions), subscriptionSlice.actions), mutationSlice.actions), {
785 unsubscribeMutationResult: mutationSlice.actions.removeMutationResult,
786 resetApiState
787 });
788 return { reducer, actions };
789}
790// src/query/core/buildSelectors.ts
791var skipToken = /* @__PURE__ */ Symbol.for("RTKQ/skipToken");
792var skipSelector = skipToken;
793var initialSubState = {
794 status: QueryStatus.uninitialized
795};
796var defaultQuerySubState = /* @__PURE__ */ createNextState(initialSubState, () => {
797});
798var defaultMutationSubState = /* @__PURE__ */ createNextState(initialSubState, () => {
799});
800function buildSelectors({ serializeQueryArgs, reducerPath }) {
801 return { buildQuerySelector, buildMutationSelector, selectInvalidatedBy };
802 function withRequestFlags(substate) {
803 return __spreadValues(__spreadValues({}, substate), getRequestStatusFlags(substate.status));
804 }
805 function selectInternalState(rootState) {
806 const state = rootState[reducerPath];
807 if (process.env.NODE_ENV !== "production") {
808 if (!state) {
809 if (selectInternalState.triggered)
810 return state;
811 selectInternalState.triggered = true;
812 console.error(`Error: No data found at \`state.${reducerPath}\`. Did you forget to add the reducer to the store?`);
813 }
814 }
815 return state;
816 }
817 function buildQuerySelector(endpointName, endpointDefinition) {
818 return (queryArgs) => {
819 const selectQuerySubState = createSelector(selectInternalState, (internalState) => {
820 var _a, _b;
821 return (_b = queryArgs === skipToken ? void 0 : (_a = internalState == null ? void 0 : internalState.queries) == null ? void 0 : _a[serializeQueryArgs({
822 queryArgs,
823 endpointDefinition,
824 endpointName
825 })]) != null ? _b : defaultQuerySubState;
826 });
827 return createSelector(selectQuerySubState, withRequestFlags);
828 };
829 }
830 function buildMutationSelector() {
831 return (id) => {
832 var _a;
833 let mutationId;
834 if (typeof id === "object") {
835 mutationId = (_a = getMutationCacheKey(id)) != null ? _a : skipToken;
836 }
837 else {
838 mutationId = id;
839 }
840 const selectMutationSubstate = createSelector(selectInternalState, (internalState) => {
841 var _a2, _b;
842 return (_b = mutationId === skipToken ? void 0 : (_a2 = internalState == null ? void 0 : internalState.mutations) == null ? void 0 : _a2[mutationId]) != null ? _b : defaultMutationSubState;
843 });
844 return createSelector(selectMutationSubstate, withRequestFlags);
845 };
846 }
847 function selectInvalidatedBy(state, tags) {
848 var _a;
849 const apiState = state[reducerPath];
850 const toInvalidate = new Set();
851 for (const tag of tags.map(expandTagDescription)) {
852 const provided = apiState.provided[tag.type];
853 if (!provided) {
854 continue;
855 }
856 let invalidateSubscriptions = (_a = tag.id !== void 0 ? provided[tag.id] : flatten(Object.values(provided))) != null ? _a : [];
857 for (const invalidate of invalidateSubscriptions) {
858 toInvalidate.add(invalidate);
859 }
860 }
861 return flatten(Array.from(toInvalidate.values()).map((queryCacheKey) => {
862 const querySubState = apiState.queries[queryCacheKey];
863 return querySubState ? [
864 {
865 queryCacheKey,
866 endpointName: querySubState.endpointName,
867 originalArgs: querySubState.originalArgs
868 }
869 ] : [];
870 }));
871 }
872}
873// src/query/defaultSerializeQueryArgs.ts
874import { isPlainObject as isPlainObject3 } from "@reduxjs/toolkit";
875var defaultSerializeQueryArgs = ({ endpointName, queryArgs }) => {
876 return `${endpointName}(${JSON.stringify(queryArgs, (key, value) => isPlainObject3(value) ? Object.keys(value).sort().reduce((acc, key2) => {
877 acc[key2] = value[key2];
878 return acc;
879 }, {}) : value)})`;
880};
881// src/query/createApi.ts
882import { nanoid } from "@reduxjs/toolkit";
883import { defaultMemoize } from "reselect";
884function buildCreateApi(...modules) {
885 return function baseCreateApi(options) {
886 const extractRehydrationInfo = defaultMemoize((action) => {
887 var _a, _b;
888 return (_b = options.extractRehydrationInfo) == null ? void 0 : _b.call(options, action, {
889 reducerPath: (_a = options.reducerPath) != null ? _a : "api"
890 });
891 });
892 const optionsWithDefaults = __spreadProps(__spreadValues({
893 reducerPath: "api",
894 serializeQueryArgs: defaultSerializeQueryArgs,
895 keepUnusedDataFor: 60,
896 refetchOnMountOrArgChange: false,
897 refetchOnFocus: false,
898 refetchOnReconnect: false
899 }, options), {
900 extractRehydrationInfo,
901 tagTypes: [...options.tagTypes || []]
902 });
903 const context = {
904 endpointDefinitions: {},
905 batch(fn) {
906 fn();
907 },
908 apiUid: nanoid(),
909 extractRehydrationInfo,
910 hasRehydrationInfo: defaultMemoize((action) => extractRehydrationInfo(action) != null)
911 };
912 const api = {
913 injectEndpoints,
914 enhanceEndpoints({ addTagTypes, endpoints }) {
915 if (addTagTypes) {
916 for (const eT of addTagTypes) {
917 if (!optionsWithDefaults.tagTypes.includes(eT)) {
918 optionsWithDefaults.tagTypes.push(eT);
919 }
920 }
921 }
922 if (endpoints) {
923 for (const [endpointName, partialDefinition] of Object.entries(endpoints)) {
924 if (typeof partialDefinition === "function") {
925 partialDefinition(context.endpointDefinitions[endpointName]);
926 }
927 Object.assign(context.endpointDefinitions[endpointName] || {}, partialDefinition);
928 }
929 }
930 return api;
931 }
932 };
933 const initializedModules = modules.map((m) => m.init(api, optionsWithDefaults, context));
934 function injectEndpoints(inject) {
935 const evaluatedEndpoints = inject.endpoints({
936 query: (x) => __spreadProps(__spreadValues({}, x), { type: DefinitionType.query }),
937 mutation: (x) => __spreadProps(__spreadValues({}, x), { type: DefinitionType.mutation })
938 });
939 for (const [endpointName, definition] of Object.entries(evaluatedEndpoints)) {
940 if (!inject.overrideExisting && endpointName in context.endpointDefinitions) {
941 if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
942 console.error(`called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``);
943 }
944 continue;
945 }
946 context.endpointDefinitions[endpointName] = definition;
947 for (const m of initializedModules) {
948 m.injectEndpoint(endpointName, definition);
949 }
950 }
951 return api;
952 }
953 return api.injectEndpoints({ endpoints: options.endpoints });
954 };
955}
956// src/query/fakeBaseQuery.ts
957function fakeBaseQuery() {
958 return function () {
959 throw new Error("When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.");
960 };
961}
962// src/query/core/buildMiddleware/index.ts
963import { compose } from "redux";
964import { createAction as createAction3 } from "@reduxjs/toolkit";
965// src/query/core/buildMiddleware/cacheCollection.ts
966var build = ({ reducerPath, api, context }) => {
967 const { removeQueryResult, unsubscribeQueryResult } = api.internalActions;
968 return (mwApi) => {
969 const currentRemovalTimeouts = {};
970 return (next) => (action) => {
971 var _a;
972 const result = next(action);
973 if (unsubscribeQueryResult.match(action)) {
974 const state = mwApi.getState()[reducerPath];
975 const { queryCacheKey } = action.payload;
976 handleUnsubscribe(queryCacheKey, (_a = state.queries[queryCacheKey]) == null ? void 0 : _a.endpointName, mwApi, state.config);
977 }
978 if (api.util.resetApiState.match(action)) {
979 for (const [key, timeout] of Object.entries(currentRemovalTimeouts)) {
980 if (timeout)
981 clearTimeout(timeout);
982 delete currentRemovalTimeouts[key];
983 }
984 }
985 if (context.hasRehydrationInfo(action)) {
986 const state = mwApi.getState()[reducerPath];
987 const { queries } = context.extractRehydrationInfo(action);
988 for (const [queryCacheKey, queryState] of Object.entries(queries)) {
989 handleUnsubscribe(queryCacheKey, queryState == null ? void 0 : queryState.endpointName, mwApi, state.config);
990 }
991 }
992 return result;
993 };
994 function handleUnsubscribe(queryCacheKey, endpointName, api2, config) {
995 var _a;
996 const endpointDefinition = context.endpointDefinitions[endpointName];
997 const keepUnusedDataFor = (_a = endpointDefinition == null ? void 0 : endpointDefinition.keepUnusedDataFor) != null ? _a : config.keepUnusedDataFor;
998 const currentTimeout = currentRemovalTimeouts[queryCacheKey];
999 if (currentTimeout) {
1000 clearTimeout(currentTimeout);
1001 }
1002 currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {
1003 const subscriptions = api2.getState()[reducerPath].subscriptions[queryCacheKey];
1004 if (!subscriptions || Object.keys(subscriptions).length === 0) {
1005 api2.dispatch(removeQueryResult({ queryCacheKey }));
1006 }
1007 delete currentRemovalTimeouts[queryCacheKey];
1008 }, keepUnusedDataFor * 1e3);
1009 }
1010 };
1011};
1012// src/query/core/buildMiddleware/invalidationByTags.ts
1013import { isAnyOf as isAnyOf2, isFulfilled as isFulfilled3, isRejectedWithValue as isRejectedWithValue3 } from "@reduxjs/toolkit";
1014var build2 = ({ reducerPath, context, context: { endpointDefinitions }, mutationThunk, api, assertTagType, refetchQuery }) => {
1015 const { removeQueryResult } = api.internalActions;
1016 return (mwApi) => (next) => (action) => {
1017 const result = next(action);
1018 if (isAnyOf2(isFulfilled3(mutationThunk), isRejectedWithValue3(mutationThunk))(action)) {
1019 invalidateTags(calculateProvidedByThunk(action, "invalidatesTags", endpointDefinitions, assertTagType), mwApi);
1020 }
1021 if (api.util.invalidateTags.match(action)) {
1022 invalidateTags(calculateProvidedBy(action.payload, void 0, void 0, void 0, void 0, assertTagType), mwApi);
1023 }
1024 return result;
1025 };
1026 function invalidateTags(tags, mwApi) {
1027 const rootState = mwApi.getState();
1028 const state = rootState[reducerPath];
1029 const toInvalidate = api.util.selectInvalidatedBy(rootState, tags);
1030 context.batch(() => {
1031 const valuesArray = Array.from(toInvalidate.values());
1032 for (const { queryCacheKey } of valuesArray) {
1033 const querySubState = state.queries[queryCacheKey];
1034 const subscriptionSubState = state.subscriptions[queryCacheKey];
1035 if (querySubState && subscriptionSubState) {
1036 if (Object.keys(subscriptionSubState).length === 0) {
1037 mwApi.dispatch(removeQueryResult({
1038 queryCacheKey
1039 }));
1040 }
1041 else if (querySubState.status !== QueryStatus.uninitialized) {
1042 mwApi.dispatch(refetchQuery(querySubState, queryCacheKey));
1043 }
1044 else {
1045 }
1046 }
1047 }
1048 });
1049 }
1050};
1051// src/query/core/buildMiddleware/polling.ts
1052var build3 = ({ reducerPath, queryThunk, api, refetchQuery }) => {
1053 return (mwApi) => {
1054 const currentPolls = {};
1055 return (next) => (action) => {
1056 const result = next(action);
1057 if (api.internalActions.updateSubscriptionOptions.match(action) || api.internalActions.unsubscribeQueryResult.match(action)) {
1058 updatePollingInterval(action.payload, mwApi);
1059 }
1060 if (queryThunk.pending.match(action) || queryThunk.rejected.match(action) && action.meta.condition) {
1061 updatePollingInterval(action.meta.arg, mwApi);
1062 }
1063 if (queryThunk.fulfilled.match(action) || queryThunk.rejected.match(action) && !action.meta.condition) {
1064 startNextPoll(action.meta.arg, mwApi);
1065 }
1066 if (api.util.resetApiState.match(action)) {
1067 clearPolls();
1068 }
1069 return result;
1070 };
1071 function startNextPoll({ queryCacheKey }, api2) {
1072 const state = api2.getState()[reducerPath];
1073 const querySubState = state.queries[queryCacheKey];
1074 const subscriptions = state.subscriptions[queryCacheKey];
1075 if (!querySubState || querySubState.status === QueryStatus.uninitialized)
1076 return;
1077 const lowestPollingInterval = findLowestPollingInterval(subscriptions);
1078 if (!Number.isFinite(lowestPollingInterval))
1079 return;
1080 const currentPoll = currentPolls[queryCacheKey];
1081 if (currentPoll == null ? void 0 : currentPoll.timeout) {
1082 clearTimeout(currentPoll.timeout);
1083 currentPoll.timeout = void 0;
1084 }
1085 const nextPollTimestamp = Date.now() + lowestPollingInterval;
1086 const currentInterval = currentPolls[queryCacheKey] = {
1087 nextPollTimestamp,
1088 pollingInterval: lowestPollingInterval,
1089 timeout: setTimeout(() => {
1090 currentInterval.timeout = void 0;
1091 api2.dispatch(refetchQuery(querySubState, queryCacheKey));
1092 }, lowestPollingInterval)
1093 };
1094 }
1095 function updatePollingInterval({ queryCacheKey }, api2) {
1096 const state = api2.getState()[reducerPath];
1097 const querySubState = state.queries[queryCacheKey];
1098 const subscriptions = state.subscriptions[queryCacheKey];
1099 if (!querySubState || querySubState.status === QueryStatus.uninitialized) {
1100 return;
1101 }
1102 const lowestPollingInterval = findLowestPollingInterval(subscriptions);
1103 if (!Number.isFinite(lowestPollingInterval)) {
1104 cleanupPollForKey(queryCacheKey);
1105 return;
1106 }
1107 const currentPoll = currentPolls[queryCacheKey];
1108 const nextPollTimestamp = Date.now() + lowestPollingInterval;
1109 if (!currentPoll || nextPollTimestamp < currentPoll.nextPollTimestamp) {
1110 startNextPoll({ queryCacheKey }, api2);
1111 }
1112 }
1113 function cleanupPollForKey(key) {
1114 const existingPoll = currentPolls[key];
1115 if (existingPoll == null ? void 0 : existingPoll.timeout) {
1116 clearTimeout(existingPoll.timeout);
1117 }
1118 delete currentPolls[key];
1119 }
1120 function clearPolls() {
1121 for (const key of Object.keys(currentPolls)) {
1122 cleanupPollForKey(key);
1123 }
1124 }
1125 };
1126 function findLowestPollingInterval(subscribers = {}) {
1127 let lowestPollingInterval = Number.POSITIVE_INFINITY;
1128 for (const subscription of Object.values(subscribers)) {
1129 if (!!subscription.pollingInterval)
1130 lowestPollingInterval = Math.min(subscription.pollingInterval, lowestPollingInterval);
1131 }
1132 return lowestPollingInterval;
1133 }
1134};
1135// src/query/core/buildMiddleware/windowEventHandling.ts
1136var build4 = ({ reducerPath, context, api, refetchQuery }) => {
1137 const { removeQueryResult } = api.internalActions;
1138 return (mwApi) => (next) => (action) => {
1139 const result = next(action);
1140 if (onFocus.match(action)) {
1141 refetchValidQueries(mwApi, "refetchOnFocus");
1142 }
1143 if (onOnline.match(action)) {
1144 refetchValidQueries(mwApi, "refetchOnReconnect");
1145 }
1146 return result;
1147 };
1148 function refetchValidQueries(api2, type) {
1149 const state = api2.getState()[reducerPath];
1150 const queries = state.queries;
1151 const subscriptions = state.subscriptions;
1152 context.batch(() => {
1153 for (const queryCacheKey of Object.keys(subscriptions)) {
1154 const querySubState = queries[queryCacheKey];
1155 const subscriptionSubState = subscriptions[queryCacheKey];
1156 if (!subscriptionSubState || !querySubState)
1157 continue;
1158 const shouldRefetch = Object.values(subscriptionSubState).some((sub) => sub[type] === true) || Object.values(subscriptionSubState).every((sub) => sub[type] === void 0) && state.config[type];
1159 if (shouldRefetch) {
1160 if (Object.keys(subscriptionSubState).length === 0) {
1161 api2.dispatch(removeQueryResult({
1162 queryCacheKey
1163 }));
1164 }
1165 else if (querySubState.status !== QueryStatus.uninitialized) {
1166 api2.dispatch(refetchQuery(querySubState, queryCacheKey));
1167 }
1168 }
1169 }
1170 });
1171 }
1172};
1173// src/query/core/buildMiddleware/cacheLifecycle.ts
1174import { isAsyncThunkAction, isFulfilled as isFulfilled4 } from "@reduxjs/toolkit";
1175var neverResolvedError = new Error("Promise never resolved before cacheEntryRemoved.");
1176var build5 = ({ api, reducerPath, context, queryThunk, mutationThunk }) => {
1177 const isQueryThunk = isAsyncThunkAction(queryThunk);
1178 const isMutationThunk = isAsyncThunkAction(mutationThunk);
1179 const isFullfilledThunk = isFulfilled4(queryThunk, mutationThunk);
1180 return (mwApi) => {
1181 const lifecycleMap = {};
1182 return (next) => (action) => {
1183 const stateBefore = mwApi.getState();
1184 const result = next(action);
1185 const cacheKey = getCacheKey(action);
1186 if (queryThunk.pending.match(action)) {
1187 const oldState = stateBefore[reducerPath].queries[cacheKey];
1188 const state = mwApi.getState()[reducerPath].queries[cacheKey];
1189 if (!oldState && state) {
1190 handleNewKey(action.meta.arg.endpointName, action.meta.arg.originalArgs, cacheKey, mwApi, action.meta.requestId);
1191 }
1192 }
1193 else if (mutationThunk.pending.match(action)) {
1194 const state = mwApi.getState()[reducerPath].mutations[cacheKey];
1195 if (state) {
1196 handleNewKey(action.meta.arg.endpointName, action.meta.arg.originalArgs, cacheKey, mwApi, action.meta.requestId);
1197 }
1198 }
1199 else if (isFullfilledThunk(action)) {
1200 const lifecycle = lifecycleMap[cacheKey];
1201 if (lifecycle == null ? void 0 : lifecycle.valueResolved) {
1202 lifecycle.valueResolved({
1203 data: action.payload,
1204 meta: action.meta.baseQueryMeta
1205 });
1206 delete lifecycle.valueResolved;
1207 }
1208 }
1209 else if (api.internalActions.removeQueryResult.match(action) || api.internalActions.removeMutationResult.match(action)) {
1210 const lifecycle = lifecycleMap[cacheKey];
1211 if (lifecycle) {
1212 delete lifecycleMap[cacheKey];
1213 lifecycle.cacheEntryRemoved();
1214 }
1215 }
1216 else if (api.util.resetApiState.match(action)) {
1217 for (const [cacheKey2, lifecycle] of Object.entries(lifecycleMap)) {
1218 delete lifecycleMap[cacheKey2];
1219 lifecycle.cacheEntryRemoved();
1220 }
1221 }
1222 return result;
1223 };
1224 function getCacheKey(action) {
1225 if (isQueryThunk(action))
1226 return action.meta.arg.queryCacheKey;
1227 if (isMutationThunk(action))
1228 return action.meta.requestId;
1229 if (api.internalActions.removeQueryResult.match(action))
1230 return action.payload.queryCacheKey;
1231 if (api.internalActions.removeMutationResult.match(action))
1232 return getMutationCacheKey(action.payload);
1233 return "";
1234 }
1235 function handleNewKey(endpointName, originalArgs, queryCacheKey, mwApi2, requestId) {
1236 const endpointDefinition = context.endpointDefinitions[endpointName];
1237 const onCacheEntryAdded = endpointDefinition == null ? void 0 : endpointDefinition.onCacheEntryAdded;
1238 if (!onCacheEntryAdded)
1239 return;
1240 let lifecycle = {};
1241 const cacheEntryRemoved = new Promise((resolve) => {
1242 lifecycle.cacheEntryRemoved = resolve;
1243 });
1244 const cacheDataLoaded = Promise.race([
1245 new Promise((resolve) => {
1246 lifecycle.valueResolved = resolve;
1247 }),
1248 cacheEntryRemoved.then(() => {
1249 throw neverResolvedError;
1250 })
1251 ]);
1252 cacheDataLoaded.catch(() => {
1253 });
1254 lifecycleMap[queryCacheKey] = lifecycle;
1255 const selector = api.endpoints[endpointName].select(endpointDefinition.type === DefinitionType.query ? originalArgs : queryCacheKey);
1256 const extra = mwApi2.dispatch((_, __, extra2) => extra2);
1257 const lifecycleApi = __spreadProps(__spreadValues({}, mwApi2), {
1258 getCacheEntry: () => selector(mwApi2.getState()),
1259 requestId,
1260 extra,
1261 updateCachedData: endpointDefinition.type === DefinitionType.query ? (updateRecipe) => mwApi2.dispatch(api.util.updateQueryData(endpointName, originalArgs, updateRecipe)) : void 0,
1262 cacheDataLoaded,
1263 cacheEntryRemoved
1264 });
1265 const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi);
1266 Promise.resolve(runningHandler).catch((e) => {
1267 if (e === neverResolvedError)
1268 return;
1269 throw e;
1270 });
1271 }
1272 };
1273};
1274// src/query/core/buildMiddleware/queryLifecycle.ts
1275import { isPending as isPending2, isRejected as isRejected2, isFulfilled as isFulfilled5 } from "@reduxjs/toolkit";
1276var build6 = ({ api, context, queryThunk, mutationThunk }) => {
1277 const isPendingThunk = isPending2(queryThunk, mutationThunk);
1278 const isRejectedThunk = isRejected2(queryThunk, mutationThunk);
1279 const isFullfilledThunk = isFulfilled5(queryThunk, mutationThunk);
1280 return (mwApi) => {
1281 const lifecycleMap = {};
1282 return (next) => (action) => {
1283 var _a, _b, _c;
1284 const result = next(action);
1285 if (isPendingThunk(action)) {
1286 const { requestId, arg: { endpointName, originalArgs } } = action.meta;
1287 const endpointDefinition = context.endpointDefinitions[endpointName];
1288 const onQueryStarted = endpointDefinition == null ? void 0 : endpointDefinition.onQueryStarted;
1289 if (onQueryStarted) {
1290 const lifecycle = {};
1291 const queryFulfilled = new Promise((resolve, reject) => {
1292 lifecycle.resolve = resolve;
1293 lifecycle.reject = reject;
1294 });
1295 queryFulfilled.catch(() => {
1296 });
1297 lifecycleMap[requestId] = lifecycle;
1298 const selector = api.endpoints[endpointName].select(endpointDefinition.type === DefinitionType.query ? originalArgs : requestId);
1299 const extra = mwApi.dispatch((_, __, extra2) => extra2);
1300 const lifecycleApi = __spreadProps(__spreadValues({}, mwApi), {
1301 getCacheEntry: () => selector(mwApi.getState()),
1302 requestId,
1303 extra,
1304 updateCachedData: endpointDefinition.type === DefinitionType.query ? (updateRecipe) => mwApi.dispatch(api.util.updateQueryData(endpointName, originalArgs, updateRecipe)) : void 0,
1305 queryFulfilled
1306 });
1307 onQueryStarted(originalArgs, lifecycleApi);
1308 }
1309 }
1310 else if (isFullfilledThunk(action)) {
1311 const { requestId, baseQueryMeta } = action.meta;
1312 (_a = lifecycleMap[requestId]) == null ? void 0 : _a.resolve({
1313 data: action.payload,
1314 meta: baseQueryMeta
1315 });
1316 delete lifecycleMap[requestId];
1317 }
1318 else if (isRejectedThunk(action)) {
1319 const { requestId, rejectedWithValue, baseQueryMeta } = action.meta;
1320 (_c = lifecycleMap[requestId]) == null ? void 0 : _c.reject({
1321 error: (_b = action.payload) != null ? _b : action.error,
1322 isUnhandledError: !rejectedWithValue,
1323 meta: baseQueryMeta
1324 });
1325 delete lifecycleMap[requestId];
1326 }
1327 return result;
1328 };
1329 };
1330};
1331// src/query/core/buildMiddleware/devMiddleware.ts
1332var build7 = ({ api, context: { apiUid }, reducerPath }) => {
1333 return (mwApi) => {
1334 let initialized2 = false;
1335 return (next) => (action) => {
1336 var _a, _b;
1337 if (!initialized2) {
1338 initialized2 = true;
1339 mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));
1340 }
1341 const result = next(action);
1342 if (api.util.resetApiState.match(action)) {
1343 mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));
1344 }
1345 if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
1346 if (api.internalActions.middlewareRegistered.match(action) && action.payload === apiUid && ((_b = (_a = mwApi.getState()[reducerPath]) == null ? void 0 : _a.config) == null ? void 0 : _b.middlewareRegistered) === "conflict") {
1347 console.warn(`There is a mismatch between slice and middleware for the reducerPath "${reducerPath}".
1348You can only have one api per reducer path, this will lead to crashes in various situations!${reducerPath === "api" ? `
1349If you have multiple apis, you *have* to specify the reducerPath option when using createApi!` : ""}`);
1350 }
1351 }
1352 return result;
1353 };
1354 };
1355};
1356// src/query/core/buildMiddleware/index.ts
1357function buildMiddleware(input) {
1358 const { reducerPath, queryThunk } = input;
1359 const actions = {
1360 invalidateTags: createAction3(`${reducerPath}/invalidateTags`)
1361 };
1362 const middlewares = [
1363 build7,
1364 build,
1365 build2,
1366 build3,
1367 build4,
1368 build5,
1369 build6
1370 ].map((build8) => build8(__spreadProps(__spreadValues({}, input), {
1371 refetchQuery
1372 })));
1373 const middleware = (mwApi) => (next) => {
1374 const applied = compose(...middlewares.map((middleware2) => middleware2(mwApi)))(next);
1375 return (action) => {
1376 if (mwApi.getState()[reducerPath]) {
1377 return applied(action);
1378 }
1379 return next(action);
1380 };
1381 };
1382 return { middleware, actions };
1383 function refetchQuery(querySubState, queryCacheKey, override = {}) {
1384 return queryThunk(__spreadValues({
1385 type: "query",
1386 endpointName: querySubState.endpointName,
1387 originalArgs: querySubState.originalArgs,
1388 subscribe: false,
1389 forceRefetch: true,
1390 queryCacheKey
1391 }, override));
1392 }
1393}
1394// src/query/core/buildInitiate.ts
1395function buildInitiate({ serializeQueryArgs, queryThunk, mutationThunk, api, context }) {
1396 const runningQueries = {};
1397 const runningMutations = {};
1398 const { unsubscribeQueryResult, removeMutationResult, updateSubscriptionOptions } = api.internalActions;
1399 return {
1400 buildInitiateQuery,
1401 buildInitiateMutation,
1402 getRunningOperationPromises,
1403 getRunningOperationPromise
1404 };
1405 function getRunningOperationPromise(endpointName, argOrRequestId) {
1406 const endpointDefinition = context.endpointDefinitions[endpointName];
1407 if (endpointDefinition.type === DefinitionType.query) {
1408 const queryCacheKey = serializeQueryArgs({
1409 queryArgs: argOrRequestId,
1410 endpointDefinition,
1411 endpointName
1412 });
1413 return runningQueries[queryCacheKey];
1414 }
1415 else {
1416 return runningMutations[argOrRequestId];
1417 }
1418 }
1419 function getRunningOperationPromises() {
1420 return [
1421 ...Object.values(runningQueries),
1422 ...Object.values(runningMutations)
1423 ].filter((t) => !!t);
1424 }
1425 function middlewareWarning(getState) {
1426 var _a, _b;
1427 if (process.env.NODE_ENV !== "production") {
1428 if (middlewareWarning.triggered)
1429 return;
1430 const registered = (_b = (_a = getState()[api.reducerPath]) == null ? void 0 : _a.config) == null ? void 0 : _b.middlewareRegistered;
1431 if (registered !== void 0) {
1432 ;
1433 middlewareWarning.triggered = true;
1434 }
1435 if (registered === false) {
1436 console.warn(`Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
1437Features like automatic cache collection, automatic refetching etc. will not be available.`);
1438 }
1439 }
1440 }
1441 function buildInitiateQuery(endpointName, endpointDefinition) {
1442 const queryAction = (arg, { subscribe = true, forceRefetch, subscriptionOptions } = {}) => (dispatch, getState) => {
1443 const queryCacheKey = serializeQueryArgs({
1444 queryArgs: arg,
1445 endpointDefinition,
1446 endpointName
1447 });
1448 const thunk = queryThunk({
1449 type: "query",
1450 subscribe,
1451 forceRefetch,
1452 subscriptionOptions,
1453 endpointName,
1454 originalArgs: arg,
1455 queryCacheKey
1456 });
1457 const thunkResult = dispatch(thunk);
1458 middlewareWarning(getState);
1459 const { requestId, abort } = thunkResult;
1460 const statePromise = Object.assign(Promise.all([runningQueries[queryCacheKey], thunkResult]).then(() => api.endpoints[endpointName].select(arg)(getState())), {
1461 arg,
1462 requestId,
1463 subscriptionOptions,
1464 queryCacheKey,
1465 abort,
1466 async unwrap() {
1467 const result = await statePromise;
1468 if (result.isError) {
1469 throw result.error;
1470 }
1471 return result.data;
1472 },
1473 refetch() {
1474 dispatch(queryAction(arg, { subscribe: false, forceRefetch: true }));
1475 },
1476 unsubscribe() {
1477 if (subscribe)
1478 dispatch(unsubscribeQueryResult({
1479 queryCacheKey,
1480 requestId
1481 }));
1482 },
1483 updateSubscriptionOptions(options) {
1484 statePromise.subscriptionOptions = options;
1485 dispatch(updateSubscriptionOptions({
1486 endpointName,
1487 requestId,
1488 queryCacheKey,
1489 options
1490 }));
1491 }
1492 });
1493 if (!runningQueries[queryCacheKey]) {
1494 runningQueries[queryCacheKey] = statePromise;
1495 statePromise.then(() => {
1496 delete runningQueries[queryCacheKey];
1497 });
1498 }
1499 return statePromise;
1500 };
1501 return queryAction;
1502 }
1503 function buildInitiateMutation(endpointName) {
1504 return (arg, { track = true, fixedCacheKey } = {}) => (dispatch, getState) => {
1505 const thunk = mutationThunk({
1506 type: "mutation",
1507 endpointName,
1508 originalArgs: arg,
1509 track,
1510 fixedCacheKey
1511 });
1512 const thunkResult = dispatch(thunk);
1513 middlewareWarning(getState);
1514 const { requestId, abort, unwrap } = thunkResult;
1515 const returnValuePromise = thunkResult.unwrap().then((data) => ({ data })).catch((error) => ({ error }));
1516 const reset = () => {
1517 dispatch(removeMutationResult({ requestId, fixedCacheKey }));
1518 };
1519 const ret = Object.assign(returnValuePromise, {
1520 arg: thunkResult.arg,
1521 requestId,
1522 abort,
1523 unwrap,
1524 unsubscribe: reset,
1525 reset
1526 });
1527 runningMutations[requestId] = ret;
1528 ret.then(() => {
1529 delete runningMutations[requestId];
1530 });
1531 if (fixedCacheKey) {
1532 runningMutations[fixedCacheKey] = ret;
1533 ret.then(() => {
1534 if (runningMutations[fixedCacheKey] === ret)
1535 delete runningMutations[fixedCacheKey];
1536 });
1537 }
1538 return ret;
1539 };
1540 }
1541}
1542// src/query/tsHelpers.ts
1543function assertCast(v) {
1544}
1545function safeAssign(target, ...args) {
1546 Object.assign(target, ...args);
1547}
1548// src/query/core/module.ts
1549import { enablePatches } from "immer";
1550var coreModuleName = /* @__PURE__ */ Symbol();
1551var coreModule = () => ({
1552 name: coreModuleName,
1553 init(api, { baseQuery, tagTypes, reducerPath, serializeQueryArgs, keepUnusedDataFor, refetchOnMountOrArgChange, refetchOnFocus, refetchOnReconnect }, context) {
1554 enablePatches();
1555 assertCast(serializeQueryArgs);
1556 const assertTagType = (tag) => {
1557 if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
1558 if (!tagTypes.includes(tag.type)) {
1559 console.error(`Tag type '${tag.type}' was used, but not specified in \`tagTypes\`!`);
1560 }
1561 }
1562 return tag;
1563 };
1564 Object.assign(api, {
1565 reducerPath,
1566 endpoints: {},
1567 internalActions: {
1568 onOnline,
1569 onOffline,
1570 onFocus,
1571 onFocusLost
1572 },
1573 util: {}
1574 });
1575 const { queryThunk, mutationThunk, patchQueryData, updateQueryData, prefetch, buildMatchThunkActions } = buildThunks({
1576 baseQuery,
1577 reducerPath,
1578 context,
1579 api,
1580 serializeQueryArgs
1581 });
1582 const { reducer, actions: sliceActions } = buildSlice({
1583 context,
1584 queryThunk,
1585 mutationThunk,
1586 reducerPath,
1587 assertTagType,
1588 config: {
1589 refetchOnFocus,
1590 refetchOnReconnect,
1591 refetchOnMountOrArgChange,
1592 keepUnusedDataFor,
1593 reducerPath
1594 }
1595 });
1596 safeAssign(api.util, {
1597 patchQueryData,
1598 updateQueryData,
1599 prefetch,
1600 resetApiState: sliceActions.resetApiState
1601 });
1602 safeAssign(api.internalActions, sliceActions);
1603 Object.defineProperty(api.util, "updateQueryResult", {
1604 get() {
1605 if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
1606 console.warn("`api.util.updateQueryResult` has been renamed to `api.util.updateQueryData`, please change your code accordingly");
1607 }
1608 return api.util.updateQueryData;
1609 }
1610 });
1611 Object.defineProperty(api.util, "patchQueryResult", {
1612 get() {
1613 if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
1614 console.warn("`api.util.patchQueryResult` has been renamed to `api.util.patchQueryData`, please change your code accordingly");
1615 }
1616 return api.util.patchQueryData;
1617 }
1618 });
1619 const { middleware, actions: middlewareActions } = buildMiddleware({
1620 reducerPath,
1621 context,
1622 queryThunk,
1623 mutationThunk,
1624 api,
1625 assertTagType
1626 });
1627 safeAssign(api.util, middlewareActions);
1628 safeAssign(api, { reducer, middleware });
1629 const { buildQuerySelector, buildMutationSelector, selectInvalidatedBy } = buildSelectors({
1630 serializeQueryArgs,
1631 reducerPath
1632 });
1633 safeAssign(api.util, { selectInvalidatedBy });
1634 const { buildInitiateQuery, buildInitiateMutation, getRunningOperationPromises, getRunningOperationPromise } = buildInitiate({
1635 queryThunk,
1636 mutationThunk,
1637 api,
1638 serializeQueryArgs,
1639 context
1640 });
1641 safeAssign(api.util, {
1642 getRunningOperationPromises,
1643 getRunningOperationPromise
1644 });
1645 return {
1646 name: coreModuleName,
1647 injectEndpoint(endpointName, definition) {
1648 var _a, _b;
1649 const anyApi = api;
1650 (_b = (_a = anyApi.endpoints)[endpointName]) != null ? _b : _a[endpointName] = {};
1651 if (isQueryDefinition(definition)) {
1652 safeAssign(anyApi.endpoints[endpointName], {
1653 select: buildQuerySelector(endpointName, definition),
1654 initiate: buildInitiateQuery(endpointName, definition)
1655 }, buildMatchThunkActions(queryThunk, endpointName));
1656 }
1657 else if (isMutationDefinition(definition)) {
1658 safeAssign(anyApi.endpoints[endpointName], {
1659 select: buildMutationSelector(),
1660 initiate: buildInitiateMutation(endpointName)
1661 }, buildMatchThunkActions(mutationThunk, endpointName));
1662 }
1663 }
1664 };
1665 }
1666});
1667// src/query/core/index.ts
1668var createApi = /* @__PURE__ */ buildCreateApi(coreModule());
1669export { QueryStatus, buildCreateApi, copyWithStructuralSharing, coreModule, createApi, fakeBaseQuery, fetchBaseQuery, retry, setupListeners, skipSelector, skipToken };
1670//# sourceMappingURL=rtk-query.modern.js.map
\No newline at end of file