UNPKG

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