@me1a/ui 1.2.10 → 1.2.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -476,6 +476,9 @@ function getArchtype(thing) {
476
476
  function has(thing, prop) {
477
477
  return getArchtype(thing) === 2 /* Map */ ? thing.has(prop) : Object.prototype.hasOwnProperty.call(thing, prop);
478
478
  }
479
+ function get(thing, prop) {
480
+ return getArchtype(thing) === 2 /* Map */ ? thing.get(prop) : thing[prop];
481
+ }
479
482
  function set(thing, propOrOldValue, value) {
480
483
  const t = getArchtype(thing);
481
484
  if (t === 2 /* Map */)
@@ -568,6 +571,10 @@ function getPlugin(pluginKey) {
568
571
  }
569
572
  return plugin;
570
573
  }
574
+ function loadPlugin(pluginKey, implementation) {
575
+ if (!plugins[pluginKey])
576
+ plugins[pluginKey] = implementation;
577
+ }
571
578
 
572
579
  // src/core/scope.ts
573
580
  var currentScope;
@@ -1083,15 +1090,250 @@ function currentImpl(value) {
1083
1090
  return copy;
1084
1091
  }
1085
1092
 
1093
+ // src/plugins/patches.ts
1094
+ function enablePatches() {
1095
+ const errorOffset = 16;
1096
+ if (process.env.NODE_ENV !== "production") {
1097
+ errors.push(
1098
+ 'Sets cannot have "replace" patches.',
1099
+ function(op) {
1100
+ return "Unsupported patch operation: " + op;
1101
+ },
1102
+ function(path) {
1103
+ return "Cannot apply patch, path doesn't resolve: " + path;
1104
+ },
1105
+ "Patching reserved attributes like __proto__, prototype and constructor is not allowed"
1106
+ );
1107
+ }
1108
+ const REPLACE = "replace";
1109
+ const ADD = "add";
1110
+ const REMOVE = "remove";
1111
+ function generatePatches_(state, basePath, patches, inversePatches) {
1112
+ switch (state.type_) {
1113
+ case 0 /* Object */:
1114
+ case 2 /* Map */:
1115
+ return generatePatchesFromAssigned(
1116
+ state,
1117
+ basePath,
1118
+ patches,
1119
+ inversePatches
1120
+ );
1121
+ case 1 /* Array */:
1122
+ return generateArrayPatches(state, basePath, patches, inversePatches);
1123
+ case 3 /* Set */:
1124
+ return generateSetPatches(
1125
+ state,
1126
+ basePath,
1127
+ patches,
1128
+ inversePatches
1129
+ );
1130
+ }
1131
+ }
1132
+ function generateArrayPatches(state, basePath, patches, inversePatches) {
1133
+ let { base_, assigned_ } = state;
1134
+ let copy_ = state.copy_;
1135
+ if (copy_.length < base_.length) {
1136
+ [base_, copy_] = [copy_, base_];
1137
+ [patches, inversePatches] = [inversePatches, patches];
1138
+ }
1139
+ for (let i = 0; i < base_.length; i++) {
1140
+ if (assigned_[i] && copy_[i] !== base_[i]) {
1141
+ const path = basePath.concat([i]);
1142
+ patches.push({
1143
+ op: REPLACE,
1144
+ path,
1145
+ // Need to maybe clone it, as it can in fact be the original value
1146
+ // due to the base/copy inversion at the start of this function
1147
+ value: clonePatchValueIfNeeded(copy_[i])
1148
+ });
1149
+ inversePatches.push({
1150
+ op: REPLACE,
1151
+ path,
1152
+ value: clonePatchValueIfNeeded(base_[i])
1153
+ });
1154
+ }
1155
+ }
1156
+ for (let i = base_.length; i < copy_.length; i++) {
1157
+ const path = basePath.concat([i]);
1158
+ patches.push({
1159
+ op: ADD,
1160
+ path,
1161
+ // Need to maybe clone it, as it can in fact be the original value
1162
+ // due to the base/copy inversion at the start of this function
1163
+ value: clonePatchValueIfNeeded(copy_[i])
1164
+ });
1165
+ }
1166
+ for (let i = copy_.length - 1; base_.length <= i; --i) {
1167
+ const path = basePath.concat([i]);
1168
+ inversePatches.push({
1169
+ op: REMOVE,
1170
+ path
1171
+ });
1172
+ }
1173
+ }
1174
+ function generatePatchesFromAssigned(state, basePath, patches, inversePatches) {
1175
+ const { base_, copy_ } = state;
1176
+ each(state.assigned_, (key, assignedValue) => {
1177
+ const origValue = get(base_, key);
1178
+ const value = get(copy_, key);
1179
+ const op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD;
1180
+ if (origValue === value && op === REPLACE)
1181
+ return;
1182
+ const path = basePath.concat(key);
1183
+ patches.push(op === REMOVE ? { op, path } : { op, path, value });
1184
+ inversePatches.push(
1185
+ op === ADD ? { op: REMOVE, path } : op === REMOVE ? { op: ADD, path, value: clonePatchValueIfNeeded(origValue) } : { op: REPLACE, path, value: clonePatchValueIfNeeded(origValue) }
1186
+ );
1187
+ });
1188
+ }
1189
+ function generateSetPatches(state, basePath, patches, inversePatches) {
1190
+ let { base_, copy_ } = state;
1191
+ let i = 0;
1192
+ base_.forEach((value) => {
1193
+ if (!copy_.has(value)) {
1194
+ const path = basePath.concat([i]);
1195
+ patches.push({
1196
+ op: REMOVE,
1197
+ path,
1198
+ value
1199
+ });
1200
+ inversePatches.unshift({
1201
+ op: ADD,
1202
+ path,
1203
+ value
1204
+ });
1205
+ }
1206
+ i++;
1207
+ });
1208
+ i = 0;
1209
+ copy_.forEach((value) => {
1210
+ if (!base_.has(value)) {
1211
+ const path = basePath.concat([i]);
1212
+ patches.push({
1213
+ op: ADD,
1214
+ path,
1215
+ value
1216
+ });
1217
+ inversePatches.unshift({
1218
+ op: REMOVE,
1219
+ path,
1220
+ value
1221
+ });
1222
+ }
1223
+ i++;
1224
+ });
1225
+ }
1226
+ function generateReplacementPatches_(baseValue, replacement, patches, inversePatches) {
1227
+ patches.push({
1228
+ op: REPLACE,
1229
+ path: [],
1230
+ value: replacement === NOTHING ? void 0 : replacement
1231
+ });
1232
+ inversePatches.push({
1233
+ op: REPLACE,
1234
+ path: [],
1235
+ value: baseValue
1236
+ });
1237
+ }
1238
+ function applyPatches_(draft, patches) {
1239
+ patches.forEach((patch) => {
1240
+ const { path, op } = patch;
1241
+ let base = draft;
1242
+ for (let i = 0; i < path.length - 1; i++) {
1243
+ const parentType = getArchtype(base);
1244
+ let p = path[i];
1245
+ if (typeof p !== "string" && typeof p !== "number") {
1246
+ p = "" + p;
1247
+ }
1248
+ if ((parentType === 0 /* Object */ || parentType === 1 /* Array */) && (p === "__proto__" || p === "constructor"))
1249
+ die(errorOffset + 3);
1250
+ if (typeof base === "function" && p === "prototype")
1251
+ die(errorOffset + 3);
1252
+ base = get(base, p);
1253
+ if (typeof base !== "object")
1254
+ die(errorOffset + 2, path.join("/"));
1255
+ }
1256
+ const type = getArchtype(base);
1257
+ const value = deepClonePatchValue(patch.value);
1258
+ const key = path[path.length - 1];
1259
+ switch (op) {
1260
+ case REPLACE:
1261
+ switch (type) {
1262
+ case 2 /* Map */:
1263
+ return base.set(key, value);
1264
+ case 3 /* Set */:
1265
+ die(errorOffset);
1266
+ default:
1267
+ return base[key] = value;
1268
+ }
1269
+ case ADD:
1270
+ switch (type) {
1271
+ case 1 /* Array */:
1272
+ return key === "-" ? base.push(value) : base.splice(key, 0, value);
1273
+ case 2 /* Map */:
1274
+ return base.set(key, value);
1275
+ case 3 /* Set */:
1276
+ return base.add(value);
1277
+ default:
1278
+ return base[key] = value;
1279
+ }
1280
+ case REMOVE:
1281
+ switch (type) {
1282
+ case 1 /* Array */:
1283
+ return base.splice(key, 1);
1284
+ case 2 /* Map */:
1285
+ return base.delete(key);
1286
+ case 3 /* Set */:
1287
+ return base.delete(patch.value);
1288
+ default:
1289
+ return delete base[key];
1290
+ }
1291
+ default:
1292
+ die(errorOffset + 1, op);
1293
+ }
1294
+ });
1295
+ return draft;
1296
+ }
1297
+ function deepClonePatchValue(obj) {
1298
+ if (!isDraftable(obj))
1299
+ return obj;
1300
+ if (Array.isArray(obj))
1301
+ return obj.map(deepClonePatchValue);
1302
+ if (isMap(obj))
1303
+ return new Map(
1304
+ Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])
1305
+ );
1306
+ if (isSet(obj))
1307
+ return new Set(Array.from(obj).map(deepClonePatchValue));
1308
+ const cloned = Object.create(getPrototypeOf(obj));
1309
+ for (const key in obj)
1310
+ cloned[key] = deepClonePatchValue(obj[key]);
1311
+ if (has(obj, DRAFTABLE))
1312
+ cloned[DRAFTABLE] = obj[DRAFTABLE];
1313
+ return cloned;
1314
+ }
1315
+ function clonePatchValueIfNeeded(obj) {
1316
+ if (isDraft(obj)) {
1317
+ return deepClonePatchValue(obj);
1318
+ } else
1319
+ return obj;
1320
+ }
1321
+ loadPlugin("Patches", {
1322
+ applyPatches_,
1323
+ generatePatches_,
1324
+ generateReplacementPatches_
1325
+ });
1326
+ }
1327
+
1086
1328
  // src/immer.ts
1087
1329
  var immer = new Immer2();
1088
1330
  var produce = immer.produce;
1089
- immer.produceWithPatches.bind(
1331
+ var produceWithPatches = immer.produceWithPatches.bind(
1090
1332
  immer
1091
1333
  );
1092
1334
  immer.setAutoFreeze.bind(immer);
1093
1335
  immer.setUseStrictShallowCopy.bind(immer);
1094
- immer.applyPatches.bind(immer);
1336
+ var applyPatches = immer.applyPatches.bind(immer);
1095
1337
  immer.createDraft.bind(immer);
1096
1338
  immer.finishDraft.bind(immer);
1097
1339
 
@@ -3715,5 +3957,2454 @@ function formatProdErrorMessage(code) {
3715
3957
  return `Minified Redux Toolkit error #${code}; visit https://redux-toolkit.js.org/Errors?code=${code} for the full message or use the non-minified dev environment for full errors. `;
3716
3958
  }
3717
3959
 
3718
- export { ReducerType, SHOULD_AUTOBATCH, TaskAbortError, Tuple, actionTypes_default as __DO_NOT_USE__ActionTypes, addListener, applyMiddleware, asyncThunkCreator, autoBatchEnhancer, bindActionCreators, buildCreateSlice, clearAllListeners, combineReducers, combineSlices, compose, configureStore, createAction, createActionCreatorInvariantMiddleware, createAsyncThunk, createDraftSafeSelector, createDraftSafeSelectorCreator, createDynamicMiddleware, createEntityAdapter, createImmutableStateInvariantMiddleware, createListenerMiddleware, produce as createNextState, createReducer, createSelector, createSelectorCreator, createSerializableStateInvariantMiddleware, createSlice, createStore, current, findNonSerializableValue, formatProdErrorMessage, freeze, isAction, isActionCreator, isAllOf, isAnyOf, isAsyncThunkAction, isDraft, isFSA as isFluxStandardAction, isFulfilled, isImmutableDefault, isPending, isPlain, isPlainObject$1 as isPlainObject, isRejected, isRejectedWithValue, legacy_createStore, lruMemoize, miniSerializeError, nanoid, original$1 as original, prepareAutoBatched, removeListener, unwrapResult, weakMapMemoize };
3960
+ // src/query/core/apiState.ts
3961
+ var QueryStatus = /* @__PURE__ */ ((QueryStatus2) => {
3962
+ QueryStatus2["uninitialized"] = "uninitialized";
3963
+ QueryStatus2["pending"] = "pending";
3964
+ QueryStatus2["fulfilled"] = "fulfilled";
3965
+ QueryStatus2["rejected"] = "rejected";
3966
+ return QueryStatus2;
3967
+ })(QueryStatus || {});
3968
+ function getRequestStatusFlags(status) {
3969
+ return {
3970
+ status,
3971
+ isUninitialized: status === "uninitialized" /* uninitialized */,
3972
+ isLoading: status === "pending" /* pending */,
3973
+ isSuccess: status === "fulfilled" /* fulfilled */,
3974
+ isError: status === "rejected" /* rejected */
3975
+ };
3976
+ }
3977
+
3978
+ // src/query/utils/copyWithStructuralSharing.ts
3979
+ var isPlainObject2 = isPlainObject$1;
3980
+ function copyWithStructuralSharing(oldObj, newObj) {
3981
+ if (oldObj === newObj || !(isPlainObject2(oldObj) && isPlainObject2(newObj) || Array.isArray(oldObj) && Array.isArray(newObj))) {
3982
+ return newObj;
3983
+ }
3984
+ const newKeys = Object.keys(newObj);
3985
+ const oldKeys = Object.keys(oldObj);
3986
+ let isSameObject = newKeys.length === oldKeys.length;
3987
+ const mergeObj = Array.isArray(newObj) ? [] : {};
3988
+ for (const key of newKeys) {
3989
+ mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key]);
3990
+ if (isSameObject) isSameObject = oldObj[key] === mergeObj[key];
3991
+ }
3992
+ return isSameObject ? oldObj : mergeObj;
3993
+ }
3994
+
3995
+ // src/query/utils/countObjectKeys.ts
3996
+ function countObjectKeys(obj) {
3997
+ let count = 0;
3998
+ for (const _key in obj) {
3999
+ count++;
4000
+ }
4001
+ return count;
4002
+ }
4003
+
4004
+ // src/query/utils/flatten.ts
4005
+ var flatten = (arr) => [].concat(...arr);
4006
+
4007
+ // src/query/utils/isAbsoluteUrl.ts
4008
+ function isAbsoluteUrl(url) {
4009
+ return new RegExp(`(^|:)//`).test(url);
4010
+ }
4011
+
4012
+ // src/query/utils/isDocumentVisible.ts
4013
+ function isDocumentVisible() {
4014
+ if (typeof document === "undefined") {
4015
+ return true;
4016
+ }
4017
+ return document.visibilityState !== "hidden";
4018
+ }
4019
+
4020
+ // src/query/utils/isNotNullish.ts
4021
+ function isNotNullish(v) {
4022
+ return v != null;
4023
+ }
4024
+
4025
+ // src/query/utils/isOnline.ts
4026
+ function isOnline() {
4027
+ return typeof navigator === "undefined" ? true : navigator.onLine === void 0 ? true : navigator.onLine;
4028
+ }
4029
+
4030
+ // src/query/utils/joinUrls.ts
4031
+ var withoutTrailingSlash = (url) => url.replace(/\/$/, "");
4032
+ var withoutLeadingSlash = (url) => url.replace(/^\//, "");
4033
+ function joinUrls(base, url) {
4034
+ if (!base) {
4035
+ return url;
4036
+ }
4037
+ if (!url) {
4038
+ return base;
4039
+ }
4040
+ if (isAbsoluteUrl(url)) {
4041
+ return url;
4042
+ }
4043
+ const delimiter = base.endsWith("/") || !url.startsWith("?") ? "/" : "";
4044
+ base = withoutTrailingSlash(base);
4045
+ url = withoutLeadingSlash(url);
4046
+ return `${base}${delimiter}${url}`;
4047
+ }
4048
+
4049
+ // src/query/fetchBaseQuery.ts
4050
+ var defaultFetchFn = (...args) => fetch(...args);
4051
+ var defaultValidateStatus = (response) => response.status >= 200 && response.status <= 299;
4052
+ var defaultIsJsonContentType = (headers) => (
4053
+ /*applicat*/
4054
+ /ion\/(vnd\.api\+)?json/.test(headers.get("content-type") || "")
4055
+ );
4056
+ function stripUndefined(obj) {
4057
+ if (!isPlainObject$1(obj)) {
4058
+ return obj;
4059
+ }
4060
+ const copy = {
4061
+ ...obj
4062
+ };
4063
+ for (const [k, v] of Object.entries(copy)) {
4064
+ if (v === void 0) delete copy[k];
4065
+ }
4066
+ return copy;
4067
+ }
4068
+ function fetchBaseQuery({
4069
+ baseUrl,
4070
+ prepareHeaders = (x) => x,
4071
+ fetchFn = defaultFetchFn,
4072
+ paramsSerializer,
4073
+ isJsonContentType = defaultIsJsonContentType,
4074
+ jsonContentType = "application/json",
4075
+ jsonReplacer,
4076
+ timeout: defaultTimeout,
4077
+ responseHandler: globalResponseHandler,
4078
+ validateStatus: globalValidateStatus,
4079
+ ...baseFetchOptions
4080
+ } = {}) {
4081
+ if (typeof fetch === "undefined" && fetchFn === defaultFetchFn) {
4082
+ console.warn("Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.");
4083
+ }
4084
+ return async (arg, api, extraOptions) => {
4085
+ const {
4086
+ getState,
4087
+ extra,
4088
+ endpoint,
4089
+ forced,
4090
+ type
4091
+ } = api;
4092
+ let meta;
4093
+ let {
4094
+ url,
4095
+ headers = new Headers(baseFetchOptions.headers),
4096
+ params = void 0,
4097
+ responseHandler = globalResponseHandler ?? "json",
4098
+ validateStatus = globalValidateStatus ?? defaultValidateStatus,
4099
+ timeout = defaultTimeout,
4100
+ ...rest
4101
+ } = typeof arg == "string" ? {
4102
+ url: arg
4103
+ } : arg;
4104
+ let abortController, signal = api.signal;
4105
+ if (timeout) {
4106
+ abortController = new AbortController();
4107
+ api.signal.addEventListener("abort", abortController.abort);
4108
+ signal = abortController.signal;
4109
+ }
4110
+ let config = {
4111
+ ...baseFetchOptions,
4112
+ signal,
4113
+ ...rest
4114
+ };
4115
+ headers = new Headers(stripUndefined(headers));
4116
+ config.headers = await prepareHeaders(headers, {
4117
+ getState,
4118
+ arg,
4119
+ extra,
4120
+ endpoint,
4121
+ forced,
4122
+ type,
4123
+ extraOptions
4124
+ }) || headers;
4125
+ const isJsonifiable = (body) => typeof body === "object" && (isPlainObject$1(body) || Array.isArray(body) || typeof body.toJSON === "function");
4126
+ if (!config.headers.has("content-type") && isJsonifiable(config.body)) {
4127
+ config.headers.set("content-type", jsonContentType);
4128
+ }
4129
+ if (isJsonifiable(config.body) && isJsonContentType(config.headers)) {
4130
+ config.body = JSON.stringify(config.body, jsonReplacer);
4131
+ }
4132
+ if (params) {
4133
+ const divider = ~url.indexOf("?") ? "&" : "?";
4134
+ const query = paramsSerializer ? paramsSerializer(params) : new URLSearchParams(stripUndefined(params));
4135
+ url += divider + query;
4136
+ }
4137
+ url = joinUrls(baseUrl, url);
4138
+ const request = new Request(url, config);
4139
+ const requestClone = new Request(url, config);
4140
+ meta = {
4141
+ request: requestClone
4142
+ };
4143
+ let response, timedOut = false, timeoutId = abortController && setTimeout(() => {
4144
+ timedOut = true;
4145
+ abortController.abort();
4146
+ }, timeout);
4147
+ try {
4148
+ response = await fetchFn(request);
4149
+ } catch (e) {
4150
+ return {
4151
+ error: {
4152
+ status: timedOut ? "TIMEOUT_ERROR" : "FETCH_ERROR",
4153
+ error: String(e)
4154
+ },
4155
+ meta
4156
+ };
4157
+ } finally {
4158
+ if (timeoutId) clearTimeout(timeoutId);
4159
+ abortController?.signal.removeEventListener("abort", abortController.abort);
4160
+ }
4161
+ const responseClone = response.clone();
4162
+ meta.response = responseClone;
4163
+ let resultData;
4164
+ let responseText = "";
4165
+ try {
4166
+ let handleResponseError;
4167
+ await Promise.all([
4168
+ handleResponse(response, responseHandler).then((r) => resultData = r, (e) => handleResponseError = e),
4169
+ // see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182
4170
+ // we *have* to "use up" both streams at the same time or they will stop running in node-fetch scenarios
4171
+ responseClone.text().then((r) => responseText = r, () => {
4172
+ })
4173
+ ]);
4174
+ if (handleResponseError) throw handleResponseError;
4175
+ } catch (e) {
4176
+ return {
4177
+ error: {
4178
+ status: "PARSING_ERROR",
4179
+ originalStatus: response.status,
4180
+ data: responseText,
4181
+ error: String(e)
4182
+ },
4183
+ meta
4184
+ };
4185
+ }
4186
+ return validateStatus(response, resultData) ? {
4187
+ data: resultData,
4188
+ meta
4189
+ } : {
4190
+ error: {
4191
+ status: response.status,
4192
+ data: resultData
4193
+ },
4194
+ meta
4195
+ };
4196
+ };
4197
+ async function handleResponse(response, responseHandler) {
4198
+ if (typeof responseHandler === "function") {
4199
+ return responseHandler(response);
4200
+ }
4201
+ if (responseHandler === "content-type") {
4202
+ responseHandler = isJsonContentType(response.headers) ? "json" : "text";
4203
+ }
4204
+ if (responseHandler === "json") {
4205
+ const text = await response.text();
4206
+ return text.length ? JSON.parse(text) : null;
4207
+ }
4208
+ return response.text();
4209
+ }
4210
+ }
4211
+
4212
+ // src/query/HandledError.ts
4213
+ var HandledError = class {
4214
+ constructor(value, meta = void 0) {
4215
+ this.value = value;
4216
+ this.meta = meta;
4217
+ }
4218
+ };
4219
+
4220
+ // src/query/retry.ts
4221
+ async function defaultBackoff(attempt = 0, maxRetries = 5) {
4222
+ const attempts = Math.min(attempt, maxRetries);
4223
+ const timeout = ~~((Math.random() + 0.4) * (300 << attempts));
4224
+ await new Promise((resolve) => setTimeout((res) => resolve(res), timeout));
4225
+ }
4226
+ function fail(e) {
4227
+ throw Object.assign(new HandledError({
4228
+ error: e
4229
+ }), {
4230
+ throwImmediately: true
4231
+ });
4232
+ }
4233
+ var EMPTY_OPTIONS = {};
4234
+ var retryWithBackoff = (baseQuery, defaultOptions) => async (args, api, extraOptions) => {
4235
+ const possibleMaxRetries = [5, (defaultOptions || EMPTY_OPTIONS).maxRetries, (extraOptions || EMPTY_OPTIONS).maxRetries].filter((x) => x !== void 0);
4236
+ const [maxRetries] = possibleMaxRetries.slice(-1);
4237
+ const defaultRetryCondition = (_, __, {
4238
+ attempt
4239
+ }) => attempt <= maxRetries;
4240
+ const options = {
4241
+ maxRetries,
4242
+ backoff: defaultBackoff,
4243
+ retryCondition: defaultRetryCondition,
4244
+ ...defaultOptions,
4245
+ ...extraOptions
4246
+ };
4247
+ let retry2 = 0;
4248
+ while (true) {
4249
+ try {
4250
+ const result = await baseQuery(args, api, extraOptions);
4251
+ if (result.error) {
4252
+ throw new HandledError(result);
4253
+ }
4254
+ return result;
4255
+ } catch (e) {
4256
+ retry2++;
4257
+ if (e.throwImmediately) {
4258
+ if (e instanceof HandledError) {
4259
+ return e.value;
4260
+ }
4261
+ throw e;
4262
+ }
4263
+ if (e instanceof HandledError && !options.retryCondition(e.value.error, args, {
4264
+ attempt: retry2,
4265
+ baseQueryApi: api,
4266
+ extraOptions
4267
+ })) {
4268
+ return e.value;
4269
+ }
4270
+ await options.backoff(retry2, options.maxRetries);
4271
+ }
4272
+ }
4273
+ };
4274
+ var retry = /* @__PURE__ */ Object.assign(retryWithBackoff, {
4275
+ fail
4276
+ });
4277
+
4278
+ // src/query/core/setupListeners.ts
4279
+ var onFocus = /* @__PURE__ */ createAction("__rtkq/focused");
4280
+ var onFocusLost = /* @__PURE__ */ createAction("__rtkq/unfocused");
4281
+ var onOnline = /* @__PURE__ */ createAction("__rtkq/online");
4282
+ var onOffline = /* @__PURE__ */ createAction("__rtkq/offline");
4283
+ var initialized = false;
4284
+ function setupListeners(dispatch, customHandler) {
4285
+ function defaultHandler() {
4286
+ const handleFocus = () => dispatch(onFocus());
4287
+ const handleFocusLost = () => dispatch(onFocusLost());
4288
+ const handleOnline = () => dispatch(onOnline());
4289
+ const handleOffline = () => dispatch(onOffline());
4290
+ const handleVisibilityChange = () => {
4291
+ if (window.document.visibilityState === "visible") {
4292
+ handleFocus();
4293
+ } else {
4294
+ handleFocusLost();
4295
+ }
4296
+ };
4297
+ if (!initialized) {
4298
+ if (typeof window !== "undefined" && window.addEventListener) {
4299
+ window.addEventListener("visibilitychange", handleVisibilityChange, false);
4300
+ window.addEventListener("focus", handleFocus, false);
4301
+ window.addEventListener("online", handleOnline, false);
4302
+ window.addEventListener("offline", handleOffline, false);
4303
+ initialized = true;
4304
+ }
4305
+ }
4306
+ const unsubscribe = () => {
4307
+ window.removeEventListener("focus", handleFocus);
4308
+ window.removeEventListener("visibilitychange", handleVisibilityChange);
4309
+ window.removeEventListener("online", handleOnline);
4310
+ window.removeEventListener("offline", handleOffline);
4311
+ initialized = false;
4312
+ };
4313
+ return unsubscribe;
4314
+ }
4315
+ return customHandler ? customHandler(dispatch, {
4316
+ onFocus,
4317
+ onFocusLost,
4318
+ onOffline,
4319
+ onOnline
4320
+ }) : defaultHandler();
4321
+ }
4322
+
4323
+ // src/query/endpointDefinitions.ts
4324
+ function isQueryDefinition(e) {
4325
+ return e.type === "query" /* query */;
4326
+ }
4327
+ function isMutationDefinition(e) {
4328
+ return e.type === "mutation" /* mutation */;
4329
+ }
4330
+ function calculateProvidedBy(description, result, error, queryArg, meta, assertTagTypes) {
4331
+ if (isFunction(description)) {
4332
+ return description(result, error, queryArg, meta).map(expandTagDescription).map(assertTagTypes);
4333
+ }
4334
+ if (Array.isArray(description)) {
4335
+ return description.map(expandTagDescription).map(assertTagTypes);
4336
+ }
4337
+ return [];
4338
+ }
4339
+ function isFunction(t) {
4340
+ return typeof t === "function";
4341
+ }
4342
+ function expandTagDescription(description) {
4343
+ return typeof description === "string" ? {
4344
+ type: description
4345
+ } : description;
4346
+ }
4347
+
4348
+ // src/tsHelpers.ts
4349
+ function asSafePromise(promise, fallback) {
4350
+ return promise.catch(fallback);
4351
+ }
4352
+
4353
+ // src/query/core/buildInitiate.ts
4354
+ var forceQueryFnSymbol = Symbol("forceQueryFn");
4355
+ var isUpsertQuery = (arg) => typeof arg[forceQueryFnSymbol] === "function";
4356
+ function buildInitiate({
4357
+ serializeQueryArgs,
4358
+ queryThunk,
4359
+ mutationThunk,
4360
+ api,
4361
+ context
4362
+ }) {
4363
+ const runningQueries = /* @__PURE__ */ new Map();
4364
+ const runningMutations = /* @__PURE__ */ new Map();
4365
+ const {
4366
+ unsubscribeQueryResult,
4367
+ removeMutationResult,
4368
+ updateSubscriptionOptions
4369
+ } = api.internalActions;
4370
+ return {
4371
+ buildInitiateQuery,
4372
+ buildInitiateMutation,
4373
+ getRunningQueryThunk,
4374
+ getRunningMutationThunk,
4375
+ getRunningQueriesThunk,
4376
+ getRunningMutationsThunk
4377
+ };
4378
+ function getRunningQueryThunk(endpointName, queryArgs) {
4379
+ return (dispatch) => {
4380
+ const endpointDefinition = context.endpointDefinitions[endpointName];
4381
+ const queryCacheKey = serializeQueryArgs({
4382
+ queryArgs,
4383
+ endpointDefinition,
4384
+ endpointName
4385
+ });
4386
+ return runningQueries.get(dispatch)?.[queryCacheKey];
4387
+ };
4388
+ }
4389
+ function getRunningMutationThunk(_endpointName, fixedCacheKeyOrRequestId) {
4390
+ return (dispatch) => {
4391
+ return runningMutations.get(dispatch)?.[fixedCacheKeyOrRequestId];
4392
+ };
4393
+ }
4394
+ function getRunningQueriesThunk() {
4395
+ return (dispatch) => Object.values(runningQueries.get(dispatch) || {}).filter(isNotNullish);
4396
+ }
4397
+ function getRunningMutationsThunk() {
4398
+ return (dispatch) => Object.values(runningMutations.get(dispatch) || {}).filter(isNotNullish);
4399
+ }
4400
+ function middlewareWarning(dispatch) {
4401
+ if (process.env.NODE_ENV !== "production") {
4402
+ if (middlewareWarning.triggered) return;
4403
+ const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());
4404
+ middlewareWarning.triggered = true;
4405
+ if (typeof returnedValue !== "object" || typeof returnedValue?.type === "string") {
4406
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(34) : `Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
4407
+ You must add the middleware for RTK-Query to function correctly!`);
4408
+ }
4409
+ }
4410
+ }
4411
+ function buildInitiateQuery(endpointName, endpointDefinition) {
4412
+ const queryAction = (arg, {
4413
+ subscribe = true,
4414
+ forceRefetch,
4415
+ subscriptionOptions,
4416
+ [forceQueryFnSymbol]: forceQueryFn,
4417
+ ...rest
4418
+ } = {}) => (dispatch, getState) => {
4419
+ const queryCacheKey = serializeQueryArgs({
4420
+ queryArgs: arg,
4421
+ endpointDefinition,
4422
+ endpointName
4423
+ });
4424
+ const thunk = queryThunk({
4425
+ ...rest,
4426
+ type: "query",
4427
+ subscribe,
4428
+ forceRefetch,
4429
+ subscriptionOptions,
4430
+ endpointName,
4431
+ originalArgs: arg,
4432
+ queryCacheKey,
4433
+ [forceQueryFnSymbol]: forceQueryFn
4434
+ });
4435
+ const selector = api.endpoints[endpointName].select(arg);
4436
+ const thunkResult = dispatch(thunk);
4437
+ const stateAfter = selector(getState());
4438
+ middlewareWarning(dispatch);
4439
+ const {
4440
+ requestId,
4441
+ abort
4442
+ } = thunkResult;
4443
+ const skippedSynchronously = stateAfter.requestId !== requestId;
4444
+ const runningQuery = runningQueries.get(dispatch)?.[queryCacheKey];
4445
+ const selectFromState = () => selector(getState());
4446
+ const statePromise = Object.assign(forceQueryFn ? (
4447
+ // a query has been forced (upsertQueryData)
4448
+ // -> we want to resolve it once data has been written with the data that will be written
4449
+ thunkResult.then(selectFromState)
4450
+ ) : skippedSynchronously && !runningQuery ? (
4451
+ // a query has been skipped due to a condition and we do not have any currently running query
4452
+ // -> we want to resolve it immediately with the current data
4453
+ Promise.resolve(stateAfter)
4454
+ ) : (
4455
+ // query just started or one is already in flight
4456
+ // -> wait for the running query, then resolve with data from after that
4457
+ Promise.all([runningQuery, thunkResult]).then(selectFromState)
4458
+ ), {
4459
+ arg,
4460
+ requestId,
4461
+ subscriptionOptions,
4462
+ queryCacheKey,
4463
+ abort,
4464
+ async unwrap() {
4465
+ const result = await statePromise;
4466
+ if (result.isError) {
4467
+ throw result.error;
4468
+ }
4469
+ return result.data;
4470
+ },
4471
+ refetch: () => dispatch(queryAction(arg, {
4472
+ subscribe: false,
4473
+ forceRefetch: true
4474
+ })),
4475
+ unsubscribe() {
4476
+ if (subscribe) dispatch(unsubscribeQueryResult({
4477
+ queryCacheKey,
4478
+ requestId
4479
+ }));
4480
+ },
4481
+ updateSubscriptionOptions(options) {
4482
+ statePromise.subscriptionOptions = options;
4483
+ dispatch(updateSubscriptionOptions({
4484
+ endpointName,
4485
+ requestId,
4486
+ queryCacheKey,
4487
+ options
4488
+ }));
4489
+ }
4490
+ });
4491
+ if (!runningQuery && !skippedSynchronously && !forceQueryFn) {
4492
+ const running = runningQueries.get(dispatch) || {};
4493
+ running[queryCacheKey] = statePromise;
4494
+ runningQueries.set(dispatch, running);
4495
+ statePromise.then(() => {
4496
+ delete running[queryCacheKey];
4497
+ if (!countObjectKeys(running)) {
4498
+ runningQueries.delete(dispatch);
4499
+ }
4500
+ });
4501
+ }
4502
+ return statePromise;
4503
+ };
4504
+ return queryAction;
4505
+ }
4506
+ function buildInitiateMutation(endpointName) {
4507
+ return (arg, {
4508
+ track = true,
4509
+ fixedCacheKey
4510
+ } = {}) => (dispatch, getState) => {
4511
+ const thunk = mutationThunk({
4512
+ type: "mutation",
4513
+ endpointName,
4514
+ originalArgs: arg,
4515
+ track,
4516
+ fixedCacheKey
4517
+ });
4518
+ const thunkResult = dispatch(thunk);
4519
+ middlewareWarning(dispatch);
4520
+ const {
4521
+ requestId,
4522
+ abort,
4523
+ unwrap
4524
+ } = thunkResult;
4525
+ const returnValuePromise = asSafePromise(thunkResult.unwrap().then((data) => ({
4526
+ data
4527
+ })), (error) => ({
4528
+ error
4529
+ }));
4530
+ const reset = () => {
4531
+ dispatch(removeMutationResult({
4532
+ requestId,
4533
+ fixedCacheKey
4534
+ }));
4535
+ };
4536
+ const ret = Object.assign(returnValuePromise, {
4537
+ arg: thunkResult.arg,
4538
+ requestId,
4539
+ abort,
4540
+ unwrap,
4541
+ reset
4542
+ });
4543
+ const running = runningMutations.get(dispatch) || {};
4544
+ runningMutations.set(dispatch, running);
4545
+ running[requestId] = ret;
4546
+ ret.then(() => {
4547
+ delete running[requestId];
4548
+ if (!countObjectKeys(running)) {
4549
+ runningMutations.delete(dispatch);
4550
+ }
4551
+ });
4552
+ if (fixedCacheKey) {
4553
+ running[fixedCacheKey] = ret;
4554
+ ret.then(() => {
4555
+ if (running[fixedCacheKey] === ret) {
4556
+ delete running[fixedCacheKey];
4557
+ if (!countObjectKeys(running)) {
4558
+ runningMutations.delete(dispatch);
4559
+ }
4560
+ }
4561
+ });
4562
+ }
4563
+ return ret;
4564
+ };
4565
+ }
4566
+ }
4567
+
4568
+ // src/query/core/buildThunks.ts
4569
+ function defaultTransformResponse(baseQueryReturnValue) {
4570
+ return baseQueryReturnValue;
4571
+ }
4572
+ function buildThunks({
4573
+ reducerPath,
4574
+ baseQuery,
4575
+ context: {
4576
+ endpointDefinitions
4577
+ },
4578
+ serializeQueryArgs,
4579
+ api,
4580
+ assertTagType
4581
+ }) {
4582
+ const patchQueryData = (endpointName, arg, patches, updateProvided) => (dispatch, getState) => {
4583
+ const endpointDefinition = endpointDefinitions[endpointName];
4584
+ const queryCacheKey = serializeQueryArgs({
4585
+ queryArgs: arg,
4586
+ endpointDefinition,
4587
+ endpointName
4588
+ });
4589
+ dispatch(api.internalActions.queryResultPatched({
4590
+ queryCacheKey,
4591
+ patches
4592
+ }));
4593
+ if (!updateProvided) {
4594
+ return;
4595
+ }
4596
+ const newValue = api.endpoints[endpointName].select(arg)(
4597
+ // Work around TS 4.1 mismatch
4598
+ getState()
4599
+ );
4600
+ const providedTags = calculateProvidedBy(endpointDefinition.providesTags, newValue.data, void 0, arg, {}, assertTagType);
4601
+ dispatch(api.internalActions.updateProvidedBy({
4602
+ queryCacheKey,
4603
+ providedTags
4604
+ }));
4605
+ };
4606
+ const updateQueryData = (endpointName, arg, updateRecipe, updateProvided = true) => (dispatch, getState) => {
4607
+ const endpointDefinition = api.endpoints[endpointName];
4608
+ const currentState = endpointDefinition.select(arg)(
4609
+ // Work around TS 4.1 mismatch
4610
+ getState()
4611
+ );
4612
+ const ret = {
4613
+ patches: [],
4614
+ inversePatches: [],
4615
+ undo: () => dispatch(api.util.patchQueryData(endpointName, arg, ret.inversePatches, updateProvided))
4616
+ };
4617
+ if (currentState.status === "uninitialized" /* uninitialized */) {
4618
+ return ret;
4619
+ }
4620
+ let newValue;
4621
+ if ("data" in currentState) {
4622
+ if (isDraftable(currentState.data)) {
4623
+ const [value, patches, inversePatches] = produceWithPatches(currentState.data, updateRecipe);
4624
+ ret.patches.push(...patches);
4625
+ ret.inversePatches.push(...inversePatches);
4626
+ newValue = value;
4627
+ } else {
4628
+ newValue = updateRecipe(currentState.data);
4629
+ ret.patches.push({
4630
+ op: "replace",
4631
+ path: [],
4632
+ value: newValue
4633
+ });
4634
+ ret.inversePatches.push({
4635
+ op: "replace",
4636
+ path: [],
4637
+ value: currentState.data
4638
+ });
4639
+ }
4640
+ }
4641
+ if (ret.patches.length === 0) {
4642
+ return ret;
4643
+ }
4644
+ dispatch(api.util.patchQueryData(endpointName, arg, ret.patches, updateProvided));
4645
+ return ret;
4646
+ };
4647
+ const upsertQueryData = (endpointName, arg, value) => (dispatch) => {
4648
+ return dispatch(api.endpoints[endpointName].initiate(arg, {
4649
+ subscribe: false,
4650
+ forceRefetch: true,
4651
+ [forceQueryFnSymbol]: () => ({
4652
+ data: value
4653
+ })
4654
+ }));
4655
+ };
4656
+ const executeEndpoint = async (arg, {
4657
+ signal,
4658
+ abort,
4659
+ rejectWithValue,
4660
+ fulfillWithValue,
4661
+ dispatch,
4662
+ getState,
4663
+ extra
4664
+ }) => {
4665
+ const endpointDefinition = endpointDefinitions[arg.endpointName];
4666
+ try {
4667
+ let transformResponse = defaultTransformResponse;
4668
+ let result;
4669
+ const baseQueryApi = {
4670
+ signal,
4671
+ abort,
4672
+ dispatch,
4673
+ getState,
4674
+ extra,
4675
+ endpoint: arg.endpointName,
4676
+ type: arg.type,
4677
+ forced: arg.type === "query" ? isForcedQuery(arg, getState()) : void 0,
4678
+ queryCacheKey: arg.type === "query" ? arg.queryCacheKey : void 0
4679
+ };
4680
+ const forceQueryFn = arg.type === "query" ? arg[forceQueryFnSymbol] : void 0;
4681
+ if (forceQueryFn) {
4682
+ result = forceQueryFn();
4683
+ } else if (endpointDefinition.query) {
4684
+ result = await baseQuery(endpointDefinition.query(arg.originalArgs), baseQueryApi, endpointDefinition.extraOptions);
4685
+ if (endpointDefinition.transformResponse) {
4686
+ transformResponse = endpointDefinition.transformResponse;
4687
+ }
4688
+ } else {
4689
+ result = await endpointDefinition.queryFn(arg.originalArgs, baseQueryApi, endpointDefinition.extraOptions, (arg2) => baseQuery(arg2, baseQueryApi, endpointDefinition.extraOptions));
4690
+ }
4691
+ if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
4692
+ const what = endpointDefinition.query ? "`baseQuery`" : "`queryFn`";
4693
+ let err;
4694
+ if (!result) {
4695
+ err = `${what} did not return anything.`;
4696
+ } else if (typeof result !== "object") {
4697
+ err = `${what} did not return an object.`;
4698
+ } else if (result.error && result.data) {
4699
+ err = `${what} returned an object containing both \`error\` and \`result\`.`;
4700
+ } else if (result.error === void 0 && result.data === void 0) {
4701
+ err = `${what} returned an object containing neither a valid \`error\` and \`result\`. At least one of them should not be \`undefined\``;
4702
+ } else {
4703
+ for (const key of Object.keys(result)) {
4704
+ if (key !== "error" && key !== "data" && key !== "meta") {
4705
+ err = `The object returned by ${what} has the unknown property ${key}.`;
4706
+ break;
4707
+ }
4708
+ }
4709
+ }
4710
+ if (err) {
4711
+ console.error(`Error encountered handling the endpoint ${arg.endpointName}.
4712
+ ${err}
4713
+ It needs to return an object with either the shape \`{ data: <value> }\` or \`{ error: <value> }\` that may contain an optional \`meta\` property.
4714
+ Object returned was:`, result);
4715
+ }
4716
+ }
4717
+ if (result.error) throw new HandledError(result.error, result.meta);
4718
+ return fulfillWithValue(await transformResponse(result.data, result.meta, arg.originalArgs), {
4719
+ fulfilledTimeStamp: Date.now(),
4720
+ baseQueryMeta: result.meta,
4721
+ [SHOULD_AUTOBATCH]: true
4722
+ });
4723
+ } catch (error) {
4724
+ let catchedError = error;
4725
+ if (catchedError instanceof HandledError) {
4726
+ let transformErrorResponse = defaultTransformResponse;
4727
+ if (endpointDefinition.query && endpointDefinition.transformErrorResponse) {
4728
+ transformErrorResponse = endpointDefinition.transformErrorResponse;
4729
+ }
4730
+ try {
4731
+ return rejectWithValue(await transformErrorResponse(catchedError.value, catchedError.meta, arg.originalArgs), {
4732
+ baseQueryMeta: catchedError.meta,
4733
+ [SHOULD_AUTOBATCH]: true
4734
+ });
4735
+ } catch (e) {
4736
+ catchedError = e;
4737
+ }
4738
+ }
4739
+ if (typeof process !== "undefined" && process.env.NODE_ENV !== "production") {
4740
+ console.error(`An unhandled error occurred processing a request for the endpoint "${arg.endpointName}".
4741
+ In the case of an unhandled error, no tags will be "provided" or "invalidated".`, catchedError);
4742
+ } else {
4743
+ console.error(catchedError);
4744
+ }
4745
+ throw catchedError;
4746
+ }
4747
+ };
4748
+ function isForcedQuery(arg, state) {
4749
+ const requestState = state[reducerPath]?.queries?.[arg.queryCacheKey];
4750
+ const baseFetchOnMountOrArgChange = state[reducerPath]?.config.refetchOnMountOrArgChange;
4751
+ const fulfilledVal = requestState?.fulfilledTimeStamp;
4752
+ const refetchVal = arg.forceRefetch ?? (arg.subscribe && baseFetchOnMountOrArgChange);
4753
+ if (refetchVal) {
4754
+ return refetchVal === true || (Number(/* @__PURE__ */ new Date()) - Number(fulfilledVal)) / 1e3 >= refetchVal;
4755
+ }
4756
+ return false;
4757
+ }
4758
+ const queryThunk = createAsyncThunk(`${reducerPath}/executeQuery`, executeEndpoint, {
4759
+ getPendingMeta() {
4760
+ return {
4761
+ startedTimeStamp: Date.now(),
4762
+ [SHOULD_AUTOBATCH]: true
4763
+ };
4764
+ },
4765
+ condition(queryThunkArgs, {
4766
+ getState
4767
+ }) {
4768
+ const state = getState();
4769
+ const requestState = state[reducerPath]?.queries?.[queryThunkArgs.queryCacheKey];
4770
+ const fulfilledVal = requestState?.fulfilledTimeStamp;
4771
+ const currentArg = queryThunkArgs.originalArgs;
4772
+ const previousArg = requestState?.originalArgs;
4773
+ const endpointDefinition = endpointDefinitions[queryThunkArgs.endpointName];
4774
+ if (isUpsertQuery(queryThunkArgs)) {
4775
+ return true;
4776
+ }
4777
+ if (requestState?.status === "pending") {
4778
+ return false;
4779
+ }
4780
+ if (isForcedQuery(queryThunkArgs, state)) {
4781
+ return true;
4782
+ }
4783
+ if (isQueryDefinition(endpointDefinition) && endpointDefinition?.forceRefetch?.({
4784
+ currentArg,
4785
+ previousArg,
4786
+ endpointState: requestState,
4787
+ state
4788
+ })) {
4789
+ return true;
4790
+ }
4791
+ if (fulfilledVal) {
4792
+ return false;
4793
+ }
4794
+ return true;
4795
+ },
4796
+ dispatchConditionRejection: true
4797
+ });
4798
+ const mutationThunk = createAsyncThunk(`${reducerPath}/executeMutation`, executeEndpoint, {
4799
+ getPendingMeta() {
4800
+ return {
4801
+ startedTimeStamp: Date.now(),
4802
+ [SHOULD_AUTOBATCH]: true
4803
+ };
4804
+ }
4805
+ });
4806
+ const hasTheForce = (options) => "force" in options;
4807
+ const hasMaxAge = (options) => "ifOlderThan" in options;
4808
+ const prefetch = (endpointName, arg, options) => (dispatch, getState) => {
4809
+ const force = hasTheForce(options) && options.force;
4810
+ const maxAge = hasMaxAge(options) && options.ifOlderThan;
4811
+ const queryAction = (force2 = true) => {
4812
+ const options2 = {
4813
+ forceRefetch: force2,
4814
+ isPrefetch: true
4815
+ };
4816
+ return api.endpoints[endpointName].initiate(arg, options2);
4817
+ };
4818
+ const latestStateValue = api.endpoints[endpointName].select(arg)(getState());
4819
+ if (force) {
4820
+ dispatch(queryAction());
4821
+ } else if (maxAge) {
4822
+ const lastFulfilledTs = latestStateValue?.fulfilledTimeStamp;
4823
+ if (!lastFulfilledTs) {
4824
+ dispatch(queryAction());
4825
+ return;
4826
+ }
4827
+ const shouldRetrigger = (Number(/* @__PURE__ */ new Date()) - Number(new Date(lastFulfilledTs))) / 1e3 >= maxAge;
4828
+ if (shouldRetrigger) {
4829
+ dispatch(queryAction());
4830
+ }
4831
+ } else {
4832
+ dispatch(queryAction(false));
4833
+ }
4834
+ };
4835
+ function matchesEndpoint(endpointName) {
4836
+ return (action) => action?.meta?.arg?.endpointName === endpointName;
4837
+ }
4838
+ function buildMatchThunkActions(thunk, endpointName) {
4839
+ return {
4840
+ matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)),
4841
+ matchFulfilled: isAllOf(isFulfilled(thunk), matchesEndpoint(endpointName)),
4842
+ matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpointName))
4843
+ };
4844
+ }
4845
+ return {
4846
+ queryThunk,
4847
+ mutationThunk,
4848
+ prefetch,
4849
+ updateQueryData,
4850
+ upsertQueryData,
4851
+ patchQueryData,
4852
+ buildMatchThunkActions
4853
+ };
4854
+ }
4855
+ function calculateProvidedByThunk(action, type, endpointDefinitions, assertTagType) {
4856
+ 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);
4857
+ }
4858
+ function updateQuerySubstateIfExists(state, queryCacheKey, update) {
4859
+ const substate = state[queryCacheKey];
4860
+ if (substate) {
4861
+ update(substate);
4862
+ }
4863
+ }
4864
+ function getMutationCacheKey(id) {
4865
+ return ("arg" in id ? id.arg.fixedCacheKey : id.fixedCacheKey) ?? id.requestId;
4866
+ }
4867
+ function updateMutationSubstateIfExists(state, id, update) {
4868
+ const substate = state[getMutationCacheKey(id)];
4869
+ if (substate) {
4870
+ update(substate);
4871
+ }
4872
+ }
4873
+ var initialState = {};
4874
+ function buildSlice({
4875
+ reducerPath,
4876
+ queryThunk,
4877
+ mutationThunk,
4878
+ serializeQueryArgs,
4879
+ context: {
4880
+ endpointDefinitions: definitions,
4881
+ apiUid,
4882
+ extractRehydrationInfo,
4883
+ hasRehydrationInfo
4884
+ },
4885
+ assertTagType,
4886
+ config
4887
+ }) {
4888
+ const resetApiState = createAction(`${reducerPath}/resetApiState`);
4889
+ function writePendingCacheEntry(draft, arg, upserting, meta) {
4890
+ draft[arg.queryCacheKey] ??= {
4891
+ status: "uninitialized" /* uninitialized */,
4892
+ endpointName: arg.endpointName
4893
+ };
4894
+ updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {
4895
+ substate.status = "pending" /* pending */;
4896
+ substate.requestId = upserting && substate.requestId ? (
4897
+ // for `upsertQuery` **updates**, keep the current `requestId`
4898
+ substate.requestId
4899
+ ) : (
4900
+ // for normal queries or `upsertQuery` **inserts** always update the `requestId`
4901
+ meta.requestId
4902
+ );
4903
+ if (arg.originalArgs !== void 0) {
4904
+ substate.originalArgs = arg.originalArgs;
4905
+ }
4906
+ substate.startedTimeStamp = meta.startedTimeStamp;
4907
+ });
4908
+ }
4909
+ function writeFulfilledCacheEntry(draft, meta, payload) {
4910
+ updateQuerySubstateIfExists(draft, meta.arg.queryCacheKey, (substate) => {
4911
+ if (substate.requestId !== meta.requestId && !isUpsertQuery(meta.arg)) return;
4912
+ const {
4913
+ merge
4914
+ } = definitions[meta.arg.endpointName];
4915
+ substate.status = "fulfilled" /* fulfilled */;
4916
+ if (merge) {
4917
+ if (substate.data !== void 0) {
4918
+ const {
4919
+ fulfilledTimeStamp,
4920
+ arg,
4921
+ baseQueryMeta,
4922
+ requestId
4923
+ } = meta;
4924
+ let newData = produce(substate.data, (draftSubstateData) => {
4925
+ return merge(draftSubstateData, payload, {
4926
+ arg: arg.originalArgs,
4927
+ baseQueryMeta,
4928
+ fulfilledTimeStamp,
4929
+ requestId
4930
+ });
4931
+ });
4932
+ substate.data = newData;
4933
+ } else {
4934
+ substate.data = payload;
4935
+ }
4936
+ } else {
4937
+ substate.data = definitions[meta.arg.endpointName].structuralSharing ?? true ? copyWithStructuralSharing(isDraft(substate.data) ? original$1(substate.data) : substate.data, payload) : payload;
4938
+ }
4939
+ delete substate.error;
4940
+ substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;
4941
+ });
4942
+ }
4943
+ const querySlice = createSlice({
4944
+ name: `${reducerPath}/queries`,
4945
+ initialState,
4946
+ reducers: {
4947
+ removeQueryResult: {
4948
+ reducer(draft, {
4949
+ payload: {
4950
+ queryCacheKey
4951
+ }
4952
+ }) {
4953
+ delete draft[queryCacheKey];
4954
+ },
4955
+ prepare: prepareAutoBatched()
4956
+ },
4957
+ cacheEntriesUpserted: {
4958
+ reducer(draft, action) {
4959
+ for (const entry of action.payload) {
4960
+ const {
4961
+ queryDescription: arg,
4962
+ value
4963
+ } = entry;
4964
+ writePendingCacheEntry(draft, arg, true, {
4965
+ arg,
4966
+ requestId: action.meta.requestId,
4967
+ startedTimeStamp: action.meta.timestamp
4968
+ });
4969
+ writeFulfilledCacheEntry(draft, {
4970
+ arg,
4971
+ requestId: action.meta.requestId,
4972
+ fulfilledTimeStamp: action.meta.timestamp,
4973
+ baseQueryMeta: {}
4974
+ }, value);
4975
+ }
4976
+ },
4977
+ prepare: (payload) => {
4978
+ const queryDescriptions = payload.map((entry) => {
4979
+ const {
4980
+ endpointName,
4981
+ arg,
4982
+ value
4983
+ } = entry;
4984
+ const endpointDefinition = definitions[endpointName];
4985
+ const queryDescription = {
4986
+ type: "query",
4987
+ endpointName,
4988
+ originalArgs: entry.arg,
4989
+ queryCacheKey: serializeQueryArgs({
4990
+ queryArgs: arg,
4991
+ endpointDefinition,
4992
+ endpointName
4993
+ })
4994
+ };
4995
+ return {
4996
+ queryDescription,
4997
+ value
4998
+ };
4999
+ });
5000
+ const result = {
5001
+ payload: queryDescriptions,
5002
+ meta: {
5003
+ [SHOULD_AUTOBATCH]: true,
5004
+ requestId: nanoid(),
5005
+ timestamp: Date.now()
5006
+ }
5007
+ };
5008
+ return result;
5009
+ }
5010
+ },
5011
+ queryResultPatched: {
5012
+ reducer(draft, {
5013
+ payload: {
5014
+ queryCacheKey,
5015
+ patches
5016
+ }
5017
+ }) {
5018
+ updateQuerySubstateIfExists(draft, queryCacheKey, (substate) => {
5019
+ substate.data = applyPatches(substate.data, patches.concat());
5020
+ });
5021
+ },
5022
+ prepare: prepareAutoBatched()
5023
+ }
5024
+ },
5025
+ extraReducers(builder) {
5026
+ builder.addCase(queryThunk.pending, (draft, {
5027
+ meta,
5028
+ meta: {
5029
+ arg
5030
+ }
5031
+ }) => {
5032
+ const upserting = isUpsertQuery(arg);
5033
+ writePendingCacheEntry(draft, arg, upserting, meta);
5034
+ }).addCase(queryThunk.fulfilled, (draft, {
5035
+ meta,
5036
+ payload
5037
+ }) => {
5038
+ writeFulfilledCacheEntry(draft, meta, payload);
5039
+ }).addCase(queryThunk.rejected, (draft, {
5040
+ meta: {
5041
+ condition,
5042
+ arg,
5043
+ requestId
5044
+ },
5045
+ error,
5046
+ payload
5047
+ }) => {
5048
+ updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {
5049
+ if (condition) ; else {
5050
+ if (substate.requestId !== requestId) return;
5051
+ substate.status = "rejected" /* rejected */;
5052
+ substate.error = payload ?? error;
5053
+ }
5054
+ });
5055
+ }).addMatcher(hasRehydrationInfo, (draft, action) => {
5056
+ const {
5057
+ queries
5058
+ } = extractRehydrationInfo(action);
5059
+ for (const [key, entry] of Object.entries(queries)) {
5060
+ if (
5061
+ // do not rehydrate entries that were currently in flight.
5062
+ entry?.status === "fulfilled" /* fulfilled */ || entry?.status === "rejected" /* rejected */
5063
+ ) {
5064
+ draft[key] = entry;
5065
+ }
5066
+ }
5067
+ });
5068
+ }
5069
+ });
5070
+ const mutationSlice = createSlice({
5071
+ name: `${reducerPath}/mutations`,
5072
+ initialState,
5073
+ reducers: {
5074
+ removeMutationResult: {
5075
+ reducer(draft, {
5076
+ payload
5077
+ }) {
5078
+ const cacheKey = getMutationCacheKey(payload);
5079
+ if (cacheKey in draft) {
5080
+ delete draft[cacheKey];
5081
+ }
5082
+ },
5083
+ prepare: prepareAutoBatched()
5084
+ }
5085
+ },
5086
+ extraReducers(builder) {
5087
+ builder.addCase(mutationThunk.pending, (draft, {
5088
+ meta,
5089
+ meta: {
5090
+ requestId,
5091
+ arg,
5092
+ startedTimeStamp
5093
+ }
5094
+ }) => {
5095
+ if (!arg.track) return;
5096
+ draft[getMutationCacheKey(meta)] = {
5097
+ requestId,
5098
+ status: "pending" /* pending */,
5099
+ endpointName: arg.endpointName,
5100
+ startedTimeStamp
5101
+ };
5102
+ }).addCase(mutationThunk.fulfilled, (draft, {
5103
+ payload,
5104
+ meta
5105
+ }) => {
5106
+ if (!meta.arg.track) return;
5107
+ updateMutationSubstateIfExists(draft, meta, (substate) => {
5108
+ if (substate.requestId !== meta.requestId) return;
5109
+ substate.status = "fulfilled" /* fulfilled */;
5110
+ substate.data = payload;
5111
+ substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;
5112
+ });
5113
+ }).addCase(mutationThunk.rejected, (draft, {
5114
+ payload,
5115
+ error,
5116
+ meta
5117
+ }) => {
5118
+ if (!meta.arg.track) return;
5119
+ updateMutationSubstateIfExists(draft, meta, (substate) => {
5120
+ if (substate.requestId !== meta.requestId) return;
5121
+ substate.status = "rejected" /* rejected */;
5122
+ substate.error = payload ?? error;
5123
+ });
5124
+ }).addMatcher(hasRehydrationInfo, (draft, action) => {
5125
+ const {
5126
+ mutations
5127
+ } = extractRehydrationInfo(action);
5128
+ for (const [key, entry] of Object.entries(mutations)) {
5129
+ if (
5130
+ // do not rehydrate entries that were currently in flight.
5131
+ (entry?.status === "fulfilled" /* fulfilled */ || entry?.status === "rejected" /* rejected */) && // only rehydrate endpoints that were persisted using a `fixedCacheKey`
5132
+ key !== entry?.requestId
5133
+ ) {
5134
+ draft[key] = entry;
5135
+ }
5136
+ }
5137
+ });
5138
+ }
5139
+ });
5140
+ const invalidationSlice = createSlice({
5141
+ name: `${reducerPath}/invalidation`,
5142
+ initialState,
5143
+ reducers: {
5144
+ updateProvidedBy: {
5145
+ reducer(draft, action) {
5146
+ const {
5147
+ queryCacheKey,
5148
+ providedTags
5149
+ } = action.payload;
5150
+ for (const tagTypeSubscriptions of Object.values(draft)) {
5151
+ for (const idSubscriptions of Object.values(tagTypeSubscriptions)) {
5152
+ const foundAt = idSubscriptions.indexOf(queryCacheKey);
5153
+ if (foundAt !== -1) {
5154
+ idSubscriptions.splice(foundAt, 1);
5155
+ }
5156
+ }
5157
+ }
5158
+ for (const {
5159
+ type,
5160
+ id
5161
+ } of providedTags) {
5162
+ const subscribedQueries = (draft[type] ??= {})[id || "__internal_without_id"] ??= [];
5163
+ const alreadySubscribed = subscribedQueries.includes(queryCacheKey);
5164
+ if (!alreadySubscribed) {
5165
+ subscribedQueries.push(queryCacheKey);
5166
+ }
5167
+ }
5168
+ },
5169
+ prepare: prepareAutoBatched()
5170
+ }
5171
+ },
5172
+ extraReducers(builder) {
5173
+ builder.addCase(querySlice.actions.removeQueryResult, (draft, {
5174
+ payload: {
5175
+ queryCacheKey
5176
+ }
5177
+ }) => {
5178
+ for (const tagTypeSubscriptions of Object.values(draft)) {
5179
+ for (const idSubscriptions of Object.values(tagTypeSubscriptions)) {
5180
+ const foundAt = idSubscriptions.indexOf(queryCacheKey);
5181
+ if (foundAt !== -1) {
5182
+ idSubscriptions.splice(foundAt, 1);
5183
+ }
5184
+ }
5185
+ }
5186
+ }).addMatcher(hasRehydrationInfo, (draft, action) => {
5187
+ const {
5188
+ provided
5189
+ } = extractRehydrationInfo(action);
5190
+ for (const [type, incomingTags] of Object.entries(provided)) {
5191
+ for (const [id, cacheKeys] of Object.entries(incomingTags)) {
5192
+ const subscribedQueries = (draft[type] ??= {})[id || "__internal_without_id"] ??= [];
5193
+ for (const queryCacheKey of cacheKeys) {
5194
+ const alreadySubscribed = subscribedQueries.includes(queryCacheKey);
5195
+ if (!alreadySubscribed) {
5196
+ subscribedQueries.push(queryCacheKey);
5197
+ }
5198
+ }
5199
+ }
5200
+ }
5201
+ }).addMatcher(isAnyOf(isFulfilled(queryThunk), isRejectedWithValue(queryThunk)), (draft, action) => {
5202
+ const providedTags = calculateProvidedByThunk(action, "providesTags", definitions, assertTagType);
5203
+ const {
5204
+ queryCacheKey
5205
+ } = action.meta.arg;
5206
+ invalidationSlice.caseReducers.updateProvidedBy(draft, invalidationSlice.actions.updateProvidedBy({
5207
+ queryCacheKey,
5208
+ providedTags
5209
+ }));
5210
+ });
5211
+ }
5212
+ });
5213
+ const subscriptionSlice = createSlice({
5214
+ name: `${reducerPath}/subscriptions`,
5215
+ initialState,
5216
+ reducers: {
5217
+ updateSubscriptionOptions(d, a) {
5218
+ },
5219
+ unsubscribeQueryResult(d, a) {
5220
+ },
5221
+ internal_getRTKQSubscriptions() {
5222
+ }
5223
+ }
5224
+ });
5225
+ const internalSubscriptionsSlice = createSlice({
5226
+ name: `${reducerPath}/internalSubscriptions`,
5227
+ initialState,
5228
+ reducers: {
5229
+ subscriptionsUpdated: {
5230
+ reducer(state, action) {
5231
+ return applyPatches(state, action.payload);
5232
+ },
5233
+ prepare: prepareAutoBatched()
5234
+ }
5235
+ }
5236
+ });
5237
+ const configSlice = createSlice({
5238
+ name: `${reducerPath}/config`,
5239
+ initialState: {
5240
+ online: isOnline(),
5241
+ focused: isDocumentVisible(),
5242
+ middlewareRegistered: false,
5243
+ ...config
5244
+ },
5245
+ reducers: {
5246
+ middlewareRegistered(state, {
5247
+ payload
5248
+ }) {
5249
+ state.middlewareRegistered = state.middlewareRegistered === "conflict" || apiUid !== payload ? "conflict" : true;
5250
+ }
5251
+ },
5252
+ extraReducers: (builder) => {
5253
+ builder.addCase(onOnline, (state) => {
5254
+ state.online = true;
5255
+ }).addCase(onOffline, (state) => {
5256
+ state.online = false;
5257
+ }).addCase(onFocus, (state) => {
5258
+ state.focused = true;
5259
+ }).addCase(onFocusLost, (state) => {
5260
+ state.focused = false;
5261
+ }).addMatcher(hasRehydrationInfo, (draft) => ({
5262
+ ...draft
5263
+ }));
5264
+ }
5265
+ });
5266
+ const combinedReducer = combineReducers({
5267
+ queries: querySlice.reducer,
5268
+ mutations: mutationSlice.reducer,
5269
+ provided: invalidationSlice.reducer,
5270
+ subscriptions: internalSubscriptionsSlice.reducer,
5271
+ config: configSlice.reducer
5272
+ });
5273
+ const reducer = (state, action) => combinedReducer(resetApiState.match(action) ? void 0 : state, action);
5274
+ const actions = {
5275
+ ...configSlice.actions,
5276
+ ...querySlice.actions,
5277
+ ...subscriptionSlice.actions,
5278
+ ...internalSubscriptionsSlice.actions,
5279
+ ...mutationSlice.actions,
5280
+ ...invalidationSlice.actions,
5281
+ resetApiState
5282
+ };
5283
+ return {
5284
+ reducer,
5285
+ actions
5286
+ };
5287
+ }
5288
+
5289
+ // src/query/core/buildSelectors.ts
5290
+ var skipToken = /* @__PURE__ */ Symbol.for("RTKQ/skipToken");
5291
+ var initialSubState = {
5292
+ status: "uninitialized" /* uninitialized */
5293
+ };
5294
+ var defaultQuerySubState = /* @__PURE__ */ produce(initialSubState, () => {
5295
+ });
5296
+ var defaultMutationSubState = /* @__PURE__ */ produce(initialSubState, () => {
5297
+ });
5298
+ function buildSelectors({
5299
+ serializeQueryArgs,
5300
+ reducerPath,
5301
+ createSelector: createSelector2
5302
+ }) {
5303
+ const selectSkippedQuery = (state) => defaultQuerySubState;
5304
+ const selectSkippedMutation = (state) => defaultMutationSubState;
5305
+ return {
5306
+ buildQuerySelector,
5307
+ buildMutationSelector,
5308
+ selectInvalidatedBy,
5309
+ selectCachedArgsForQuery
5310
+ };
5311
+ function withRequestFlags(substate) {
5312
+ return {
5313
+ ...substate,
5314
+ ...getRequestStatusFlags(substate.status)
5315
+ };
5316
+ }
5317
+ function selectInternalState(rootState) {
5318
+ const state = rootState[reducerPath];
5319
+ if (process.env.NODE_ENV !== "production") {
5320
+ if (!state) {
5321
+ if (selectInternalState.triggered) return state;
5322
+ selectInternalState.triggered = true;
5323
+ console.error(`Error: No data found at \`state.${reducerPath}\`. Did you forget to add the reducer to the store?`);
5324
+ }
5325
+ }
5326
+ return state;
5327
+ }
5328
+ function buildQuerySelector(endpointName, endpointDefinition) {
5329
+ return (queryArgs) => {
5330
+ const serializedArgs = serializeQueryArgs({
5331
+ queryArgs,
5332
+ endpointDefinition,
5333
+ endpointName
5334
+ });
5335
+ const selectQuerySubstate = (state) => selectInternalState(state)?.queries?.[serializedArgs] ?? defaultQuerySubState;
5336
+ const finalSelectQuerySubState = queryArgs === skipToken ? selectSkippedQuery : selectQuerySubstate;
5337
+ return createSelector2(finalSelectQuerySubState, withRequestFlags);
5338
+ };
5339
+ }
5340
+ function buildMutationSelector() {
5341
+ return (id) => {
5342
+ let mutationId;
5343
+ if (typeof id === "object") {
5344
+ mutationId = getMutationCacheKey(id) ?? skipToken;
5345
+ } else {
5346
+ mutationId = id;
5347
+ }
5348
+ const selectMutationSubstate = (state) => selectInternalState(state)?.mutations?.[mutationId] ?? defaultMutationSubState;
5349
+ const finalSelectMutationSubstate = mutationId === skipToken ? selectSkippedMutation : selectMutationSubstate;
5350
+ return createSelector2(finalSelectMutationSubstate, withRequestFlags);
5351
+ };
5352
+ }
5353
+ function selectInvalidatedBy(state, tags) {
5354
+ const apiState = state[reducerPath];
5355
+ const toInvalidate = /* @__PURE__ */ new Set();
5356
+ for (const tag of tags.map(expandTagDescription)) {
5357
+ const provided = apiState.provided[tag.type];
5358
+ if (!provided) {
5359
+ continue;
5360
+ }
5361
+ let invalidateSubscriptions = (tag.id !== void 0 ? (
5362
+ // id given: invalidate all queries that provide this type & id
5363
+ provided[tag.id]
5364
+ ) : (
5365
+ // no id: invalidate all queries that provide this type
5366
+ flatten(Object.values(provided))
5367
+ )) ?? [];
5368
+ for (const invalidate of invalidateSubscriptions) {
5369
+ toInvalidate.add(invalidate);
5370
+ }
5371
+ }
5372
+ return flatten(Array.from(toInvalidate.values()).map((queryCacheKey) => {
5373
+ const querySubState = apiState.queries[queryCacheKey];
5374
+ return querySubState ? [{
5375
+ queryCacheKey,
5376
+ endpointName: querySubState.endpointName,
5377
+ originalArgs: querySubState.originalArgs
5378
+ }] : [];
5379
+ }));
5380
+ }
5381
+ function selectCachedArgsForQuery(state, queryName) {
5382
+ return Object.values(state[reducerPath].queries).filter((entry) => entry?.endpointName === queryName && entry.status !== "uninitialized" /* uninitialized */).map((entry) => entry.originalArgs);
5383
+ }
5384
+ }
5385
+
5386
+ // src/query/defaultSerializeQueryArgs.ts
5387
+ var cache = WeakMap ? /* @__PURE__ */ new WeakMap() : void 0;
5388
+ var defaultSerializeQueryArgs = ({
5389
+ endpointName,
5390
+ queryArgs
5391
+ }) => {
5392
+ let serialized = "";
5393
+ const cached = cache?.get(queryArgs);
5394
+ if (typeof cached === "string") {
5395
+ serialized = cached;
5396
+ } else {
5397
+ const stringified = JSON.stringify(queryArgs, (key, value) => {
5398
+ value = typeof value === "bigint" ? {
5399
+ $bigint: value.toString()
5400
+ } : value;
5401
+ value = isPlainObject$1(value) ? Object.keys(value).sort().reduce((acc, key2) => {
5402
+ acc[key2] = value[key2];
5403
+ return acc;
5404
+ }, {}) : value;
5405
+ return value;
5406
+ });
5407
+ if (isPlainObject$1(queryArgs)) {
5408
+ cache?.set(queryArgs, stringified);
5409
+ }
5410
+ serialized = stringified;
5411
+ }
5412
+ return `${endpointName}(${serialized})`;
5413
+ };
5414
+ function buildCreateApi(...modules) {
5415
+ return function baseCreateApi(options) {
5416
+ const extractRehydrationInfo = weakMapMemoize((action) => options.extractRehydrationInfo?.(action, {
5417
+ reducerPath: options.reducerPath ?? "api"
5418
+ }));
5419
+ const optionsWithDefaults = {
5420
+ reducerPath: "api",
5421
+ keepUnusedDataFor: 60,
5422
+ refetchOnMountOrArgChange: false,
5423
+ refetchOnFocus: false,
5424
+ refetchOnReconnect: false,
5425
+ invalidationBehavior: "delayed",
5426
+ ...options,
5427
+ extractRehydrationInfo,
5428
+ serializeQueryArgs(queryArgsApi) {
5429
+ let finalSerializeQueryArgs = defaultSerializeQueryArgs;
5430
+ if ("serializeQueryArgs" in queryArgsApi.endpointDefinition) {
5431
+ const endpointSQA = queryArgsApi.endpointDefinition.serializeQueryArgs;
5432
+ finalSerializeQueryArgs = (queryArgsApi2) => {
5433
+ const initialResult = endpointSQA(queryArgsApi2);
5434
+ if (typeof initialResult === "string") {
5435
+ return initialResult;
5436
+ } else {
5437
+ return defaultSerializeQueryArgs({
5438
+ ...queryArgsApi2,
5439
+ queryArgs: initialResult
5440
+ });
5441
+ }
5442
+ };
5443
+ } else if (options.serializeQueryArgs) {
5444
+ finalSerializeQueryArgs = options.serializeQueryArgs;
5445
+ }
5446
+ return finalSerializeQueryArgs(queryArgsApi);
5447
+ },
5448
+ tagTypes: [...options.tagTypes || []]
5449
+ };
5450
+ const context = {
5451
+ endpointDefinitions: {},
5452
+ batch(fn) {
5453
+ fn();
5454
+ },
5455
+ apiUid: nanoid(),
5456
+ extractRehydrationInfo,
5457
+ hasRehydrationInfo: weakMapMemoize((action) => extractRehydrationInfo(action) != null)
5458
+ };
5459
+ const api = {
5460
+ injectEndpoints,
5461
+ enhanceEndpoints({
5462
+ addTagTypes,
5463
+ endpoints
5464
+ }) {
5465
+ if (addTagTypes) {
5466
+ for (const eT of addTagTypes) {
5467
+ if (!optionsWithDefaults.tagTypes.includes(eT)) {
5468
+ optionsWithDefaults.tagTypes.push(eT);
5469
+ }
5470
+ }
5471
+ }
5472
+ if (endpoints) {
5473
+ for (const [endpointName, partialDefinition] of Object.entries(endpoints)) {
5474
+ if (typeof partialDefinition === "function") {
5475
+ partialDefinition(context.endpointDefinitions[endpointName]);
5476
+ } else {
5477
+ Object.assign(context.endpointDefinitions[endpointName] || {}, partialDefinition);
5478
+ }
5479
+ }
5480
+ }
5481
+ return api;
5482
+ }
5483
+ };
5484
+ const initializedModules = modules.map((m) => m.init(api, optionsWithDefaults, context));
5485
+ function injectEndpoints(inject) {
5486
+ const evaluatedEndpoints = inject.endpoints({
5487
+ query: (x) => ({
5488
+ ...x,
5489
+ type: "query" /* query */
5490
+ }),
5491
+ mutation: (x) => ({
5492
+ ...x,
5493
+ type: "mutation" /* mutation */
5494
+ })
5495
+ });
5496
+ for (const [endpointName, definition] of Object.entries(evaluatedEndpoints)) {
5497
+ if (inject.overrideExisting !== true && endpointName in context.endpointDefinitions) {
5498
+ if (inject.overrideExisting === "throw") {
5499
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(39) : `called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``);
5500
+ } else if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
5501
+ console.error(`called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``);
5502
+ }
5503
+ continue;
5504
+ }
5505
+ context.endpointDefinitions[endpointName] = definition;
5506
+ for (const m of initializedModules) {
5507
+ m.injectEndpoint(endpointName, definition);
5508
+ }
5509
+ }
5510
+ return api;
5511
+ }
5512
+ return api.injectEndpoints({
5513
+ endpoints: options.endpoints
5514
+ });
5515
+ };
5516
+ }
5517
+ var _NEVER = /* @__PURE__ */ Symbol();
5518
+ function fakeBaseQuery() {
5519
+ return function() {
5520
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(33) : "When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.");
5521
+ };
5522
+ }
5523
+ function safeAssign(target, ...args) {
5524
+ return Object.assign(target, ...args);
5525
+ }
5526
+ var buildBatchedActionsHandler = ({
5527
+ api,
5528
+ queryThunk,
5529
+ internalState
5530
+ }) => {
5531
+ const subscriptionsPrefix = `${api.reducerPath}/subscriptions`;
5532
+ let previousSubscriptions = null;
5533
+ let updateSyncTimer = null;
5534
+ const {
5535
+ updateSubscriptionOptions,
5536
+ unsubscribeQueryResult
5537
+ } = api.internalActions;
5538
+ const actuallyMutateSubscriptions = (mutableState, action) => {
5539
+ if (updateSubscriptionOptions.match(action)) {
5540
+ const {
5541
+ queryCacheKey,
5542
+ requestId,
5543
+ options
5544
+ } = action.payload;
5545
+ if (mutableState?.[queryCacheKey]?.[requestId]) {
5546
+ mutableState[queryCacheKey][requestId] = options;
5547
+ }
5548
+ return true;
5549
+ }
5550
+ if (unsubscribeQueryResult.match(action)) {
5551
+ const {
5552
+ queryCacheKey,
5553
+ requestId
5554
+ } = action.payload;
5555
+ if (mutableState[queryCacheKey]) {
5556
+ delete mutableState[queryCacheKey][requestId];
5557
+ }
5558
+ return true;
5559
+ }
5560
+ if (api.internalActions.removeQueryResult.match(action)) {
5561
+ delete mutableState[action.payload.queryCacheKey];
5562
+ return true;
5563
+ }
5564
+ if (queryThunk.pending.match(action)) {
5565
+ const {
5566
+ meta: {
5567
+ arg,
5568
+ requestId
5569
+ }
5570
+ } = action;
5571
+ const substate = mutableState[arg.queryCacheKey] ??= {};
5572
+ substate[`${requestId}_running`] = {};
5573
+ if (arg.subscribe) {
5574
+ substate[requestId] = arg.subscriptionOptions ?? substate[requestId] ?? {};
5575
+ }
5576
+ return true;
5577
+ }
5578
+ let mutated = false;
5579
+ if (queryThunk.fulfilled.match(action) || queryThunk.rejected.match(action)) {
5580
+ const state = mutableState[action.meta.arg.queryCacheKey] || {};
5581
+ const key = `${action.meta.requestId}_running`;
5582
+ mutated ||= !!state[key];
5583
+ delete state[key];
5584
+ }
5585
+ if (queryThunk.rejected.match(action)) {
5586
+ const {
5587
+ meta: {
5588
+ condition,
5589
+ arg,
5590
+ requestId
5591
+ }
5592
+ } = action;
5593
+ if (condition && arg.subscribe) {
5594
+ const substate = mutableState[arg.queryCacheKey] ??= {};
5595
+ substate[requestId] = arg.subscriptionOptions ?? substate[requestId] ?? {};
5596
+ mutated = true;
5597
+ }
5598
+ }
5599
+ return mutated;
5600
+ };
5601
+ const getSubscriptions = () => internalState.currentSubscriptions;
5602
+ const getSubscriptionCount = (queryCacheKey) => {
5603
+ const subscriptions = getSubscriptions();
5604
+ const subscriptionsForQueryArg = subscriptions[queryCacheKey] ?? {};
5605
+ return countObjectKeys(subscriptionsForQueryArg);
5606
+ };
5607
+ const isRequestSubscribed = (queryCacheKey, requestId) => {
5608
+ const subscriptions = getSubscriptions();
5609
+ return !!subscriptions?.[queryCacheKey]?.[requestId];
5610
+ };
5611
+ const subscriptionSelectors = {
5612
+ getSubscriptions,
5613
+ getSubscriptionCount,
5614
+ isRequestSubscribed
5615
+ };
5616
+ return (action, mwApi) => {
5617
+ if (!previousSubscriptions) {
5618
+ previousSubscriptions = JSON.parse(JSON.stringify(internalState.currentSubscriptions));
5619
+ }
5620
+ if (api.util.resetApiState.match(action)) {
5621
+ previousSubscriptions = internalState.currentSubscriptions = {};
5622
+ updateSyncTimer = null;
5623
+ return [true, false];
5624
+ }
5625
+ if (api.internalActions.internal_getRTKQSubscriptions.match(action)) {
5626
+ return [false, subscriptionSelectors];
5627
+ }
5628
+ const didMutate = actuallyMutateSubscriptions(internalState.currentSubscriptions, action);
5629
+ let actionShouldContinue = true;
5630
+ if (didMutate) {
5631
+ if (!updateSyncTimer) {
5632
+ updateSyncTimer = setTimeout(() => {
5633
+ const newSubscriptions = JSON.parse(JSON.stringify(internalState.currentSubscriptions));
5634
+ const [, patches] = produceWithPatches(previousSubscriptions, () => newSubscriptions);
5635
+ mwApi.next(api.internalActions.subscriptionsUpdated(patches));
5636
+ previousSubscriptions = newSubscriptions;
5637
+ updateSyncTimer = null;
5638
+ }, 500);
5639
+ }
5640
+ const isSubscriptionSliceAction = typeof action.type == "string" && !!action.type.startsWith(subscriptionsPrefix);
5641
+ const isAdditionalSubscriptionAction = queryThunk.rejected.match(action) && action.meta.condition && !!action.meta.arg.subscribe;
5642
+ actionShouldContinue = !isSubscriptionSliceAction && !isAdditionalSubscriptionAction;
5643
+ }
5644
+ return [actionShouldContinue, false];
5645
+ };
5646
+ };
5647
+
5648
+ // src/query/core/buildMiddleware/cacheCollection.ts
5649
+ function isObjectEmpty(obj) {
5650
+ for (const k in obj) {
5651
+ return false;
5652
+ }
5653
+ return true;
5654
+ }
5655
+ var THIRTY_TWO_BIT_MAX_TIMER_SECONDS = 2147483647 / 1e3 - 1;
5656
+ var buildCacheCollectionHandler = ({
5657
+ reducerPath,
5658
+ api,
5659
+ queryThunk,
5660
+ context,
5661
+ internalState
5662
+ }) => {
5663
+ const {
5664
+ removeQueryResult,
5665
+ unsubscribeQueryResult,
5666
+ cacheEntriesUpserted
5667
+ } = api.internalActions;
5668
+ const canTriggerUnsubscribe = isAnyOf(unsubscribeQueryResult.match, queryThunk.fulfilled, queryThunk.rejected, cacheEntriesUpserted.match);
5669
+ function anySubscriptionsRemainingForKey(queryCacheKey) {
5670
+ const subscriptions = internalState.currentSubscriptions[queryCacheKey];
5671
+ return !!subscriptions && !isObjectEmpty(subscriptions);
5672
+ }
5673
+ const currentRemovalTimeouts = {};
5674
+ const handler = (action, mwApi, internalState2) => {
5675
+ if (canTriggerUnsubscribe(action)) {
5676
+ const state = mwApi.getState()[reducerPath];
5677
+ let queryCacheKeys;
5678
+ if (cacheEntriesUpserted.match(action)) {
5679
+ queryCacheKeys = action.payload.map((entry) => entry.queryDescription.queryCacheKey);
5680
+ } else {
5681
+ const {
5682
+ queryCacheKey
5683
+ } = unsubscribeQueryResult.match(action) ? action.payload : action.meta.arg;
5684
+ queryCacheKeys = [queryCacheKey];
5685
+ }
5686
+ for (const queryCacheKey of queryCacheKeys) {
5687
+ handleUnsubscribe(queryCacheKey, state.queries[queryCacheKey]?.endpointName, mwApi, state.config);
5688
+ }
5689
+ }
5690
+ if (api.util.resetApiState.match(action)) {
5691
+ for (const [key, timeout] of Object.entries(currentRemovalTimeouts)) {
5692
+ if (timeout) clearTimeout(timeout);
5693
+ delete currentRemovalTimeouts[key];
5694
+ }
5695
+ }
5696
+ if (context.hasRehydrationInfo(action)) {
5697
+ const state = mwApi.getState()[reducerPath];
5698
+ const {
5699
+ queries
5700
+ } = context.extractRehydrationInfo(action);
5701
+ for (const [queryCacheKey, queryState] of Object.entries(queries)) {
5702
+ handleUnsubscribe(queryCacheKey, queryState?.endpointName, mwApi, state.config);
5703
+ }
5704
+ }
5705
+ };
5706
+ function handleUnsubscribe(queryCacheKey, endpointName, api2, config) {
5707
+ const endpointDefinition = context.endpointDefinitions[endpointName];
5708
+ const keepUnusedDataFor = endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor;
5709
+ if (keepUnusedDataFor === Infinity) {
5710
+ return;
5711
+ }
5712
+ const finalKeepUnusedDataFor = Math.max(0, Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS));
5713
+ if (!anySubscriptionsRemainingForKey(queryCacheKey)) {
5714
+ const currentTimeout = currentRemovalTimeouts[queryCacheKey];
5715
+ if (currentTimeout) {
5716
+ clearTimeout(currentTimeout);
5717
+ }
5718
+ currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {
5719
+ if (!anySubscriptionsRemainingForKey(queryCacheKey)) {
5720
+ api2.dispatch(removeQueryResult({
5721
+ queryCacheKey
5722
+ }));
5723
+ }
5724
+ delete currentRemovalTimeouts[queryCacheKey];
5725
+ }, finalKeepUnusedDataFor * 1e3);
5726
+ }
5727
+ }
5728
+ return handler;
5729
+ };
5730
+
5731
+ // src/query/core/buildMiddleware/cacheLifecycle.ts
5732
+ var neverResolvedError = new Error("Promise never resolved before cacheEntryRemoved.");
5733
+ var buildCacheLifecycleHandler = ({
5734
+ api,
5735
+ reducerPath,
5736
+ context,
5737
+ queryThunk,
5738
+ mutationThunk,
5739
+ internalState
5740
+ }) => {
5741
+ const isQueryThunk = isAsyncThunkAction(queryThunk);
5742
+ const isMutationThunk = isAsyncThunkAction(mutationThunk);
5743
+ const isFulfilledThunk = isFulfilled(queryThunk, mutationThunk);
5744
+ const lifecycleMap = {};
5745
+ function resolveLifecycleEntry(cacheKey, data, meta) {
5746
+ const lifecycle = lifecycleMap[cacheKey];
5747
+ if (lifecycle?.valueResolved) {
5748
+ lifecycle.valueResolved({
5749
+ data,
5750
+ meta
5751
+ });
5752
+ delete lifecycle.valueResolved;
5753
+ }
5754
+ }
5755
+ function removeLifecycleEntry(cacheKey) {
5756
+ const lifecycle = lifecycleMap[cacheKey];
5757
+ if (lifecycle) {
5758
+ delete lifecycleMap[cacheKey];
5759
+ lifecycle.cacheEntryRemoved();
5760
+ }
5761
+ }
5762
+ const handler = (action, mwApi, stateBefore) => {
5763
+ const cacheKey = getCacheKey(action);
5764
+ function checkForNewCacheKey(endpointName, cacheKey2, requestId, originalArgs) {
5765
+ const oldState = stateBefore[reducerPath].queries[cacheKey2];
5766
+ const state = mwApi.getState()[reducerPath].queries[cacheKey2];
5767
+ if (!oldState && state) {
5768
+ handleNewKey(endpointName, originalArgs, cacheKey2, mwApi, requestId);
5769
+ }
5770
+ }
5771
+ if (queryThunk.pending.match(action)) {
5772
+ checkForNewCacheKey(action.meta.arg.endpointName, cacheKey, action.meta.requestId, action.meta.arg.originalArgs);
5773
+ } else if (api.internalActions.cacheEntriesUpserted.match(action)) {
5774
+ for (const {
5775
+ queryDescription,
5776
+ value
5777
+ } of action.payload) {
5778
+ const {
5779
+ endpointName,
5780
+ originalArgs,
5781
+ queryCacheKey
5782
+ } = queryDescription;
5783
+ checkForNewCacheKey(endpointName, queryCacheKey, action.meta.requestId, originalArgs);
5784
+ resolveLifecycleEntry(queryCacheKey, value, {});
5785
+ }
5786
+ } else if (mutationThunk.pending.match(action)) {
5787
+ const state = mwApi.getState()[reducerPath].mutations[cacheKey];
5788
+ if (state) {
5789
+ handleNewKey(action.meta.arg.endpointName, action.meta.arg.originalArgs, cacheKey, mwApi, action.meta.requestId);
5790
+ }
5791
+ } else if (isFulfilledThunk(action)) {
5792
+ resolveLifecycleEntry(cacheKey, action.payload, action.meta.baseQueryMeta);
5793
+ } else if (api.internalActions.removeQueryResult.match(action) || api.internalActions.removeMutationResult.match(action)) {
5794
+ removeLifecycleEntry(cacheKey);
5795
+ } else if (api.util.resetApiState.match(action)) {
5796
+ for (const cacheKey2 of Object.keys(lifecycleMap)) {
5797
+ removeLifecycleEntry(cacheKey2);
5798
+ }
5799
+ }
5800
+ };
5801
+ function getCacheKey(action) {
5802
+ if (isQueryThunk(action)) return action.meta.arg.queryCacheKey;
5803
+ if (isMutationThunk(action)) {
5804
+ return action.meta.arg.fixedCacheKey ?? action.meta.requestId;
5805
+ }
5806
+ if (api.internalActions.removeQueryResult.match(action)) return action.payload.queryCacheKey;
5807
+ if (api.internalActions.removeMutationResult.match(action)) return getMutationCacheKey(action.payload);
5808
+ return "";
5809
+ }
5810
+ function handleNewKey(endpointName, originalArgs, queryCacheKey, mwApi, requestId) {
5811
+ const endpointDefinition = context.endpointDefinitions[endpointName];
5812
+ const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded;
5813
+ if (!onCacheEntryAdded) return;
5814
+ const lifecycle = {};
5815
+ const cacheEntryRemoved = new Promise((resolve) => {
5816
+ lifecycle.cacheEntryRemoved = resolve;
5817
+ });
5818
+ const cacheDataLoaded = Promise.race([new Promise((resolve) => {
5819
+ lifecycle.valueResolved = resolve;
5820
+ }), cacheEntryRemoved.then(() => {
5821
+ throw neverResolvedError;
5822
+ })]);
5823
+ cacheDataLoaded.catch(() => {
5824
+ });
5825
+ lifecycleMap[queryCacheKey] = lifecycle;
5826
+ const selector = api.endpoints[endpointName].select(endpointDefinition.type === "query" /* query */ ? originalArgs : queryCacheKey);
5827
+ const extra = mwApi.dispatch((_, __, extra2) => extra2);
5828
+ const lifecycleApi = {
5829
+ ...mwApi,
5830
+ getCacheEntry: () => selector(mwApi.getState()),
5831
+ requestId,
5832
+ extra,
5833
+ updateCachedData: endpointDefinition.type === "query" /* query */ ? (updateRecipe) => mwApi.dispatch(api.util.updateQueryData(endpointName, originalArgs, updateRecipe)) : void 0,
5834
+ cacheDataLoaded,
5835
+ cacheEntryRemoved
5836
+ };
5837
+ const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi);
5838
+ Promise.resolve(runningHandler).catch((e) => {
5839
+ if (e === neverResolvedError) return;
5840
+ throw e;
5841
+ });
5842
+ }
5843
+ return handler;
5844
+ };
5845
+
5846
+ // src/query/core/buildMiddleware/devMiddleware.ts
5847
+ var buildDevCheckHandler = ({
5848
+ api,
5849
+ context: {
5850
+ apiUid
5851
+ },
5852
+ reducerPath
5853
+ }) => {
5854
+ return (action, mwApi) => {
5855
+ if (api.util.resetApiState.match(action)) {
5856
+ mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));
5857
+ }
5858
+ if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
5859
+ if (api.internalActions.middlewareRegistered.match(action) && action.payload === apiUid && mwApi.getState()[reducerPath]?.config?.middlewareRegistered === "conflict") {
5860
+ console.warn(`There is a mismatch between slice and middleware for the reducerPath "${reducerPath}".
5861
+ You can only have one api per reducer path, this will lead to crashes in various situations!${reducerPath === "api" ? `
5862
+ If you have multiple apis, you *have* to specify the reducerPath option when using createApi!` : ""}`);
5863
+ }
5864
+ }
5865
+ };
5866
+ };
5867
+
5868
+ // src/query/core/buildMiddleware/invalidationByTags.ts
5869
+ var buildInvalidationByTagsHandler = ({
5870
+ reducerPath,
5871
+ context,
5872
+ context: {
5873
+ endpointDefinitions
5874
+ },
5875
+ mutationThunk,
5876
+ queryThunk,
5877
+ api,
5878
+ assertTagType,
5879
+ refetchQuery,
5880
+ internalState
5881
+ }) => {
5882
+ const {
5883
+ removeQueryResult
5884
+ } = api.internalActions;
5885
+ const isThunkActionWithTags = isAnyOf(isFulfilled(mutationThunk), isRejectedWithValue(mutationThunk));
5886
+ const isQueryEnd = isAnyOf(isFulfilled(mutationThunk, queryThunk), isRejected(mutationThunk, queryThunk));
5887
+ let pendingTagInvalidations = [];
5888
+ const handler = (action, mwApi) => {
5889
+ if (isThunkActionWithTags(action)) {
5890
+ invalidateTags(calculateProvidedByThunk(action, "invalidatesTags", endpointDefinitions, assertTagType), mwApi);
5891
+ } else if (isQueryEnd(action)) {
5892
+ invalidateTags([], mwApi);
5893
+ } else if (api.util.invalidateTags.match(action)) {
5894
+ invalidateTags(calculateProvidedBy(action.payload, void 0, void 0, void 0, void 0, assertTagType), mwApi);
5895
+ }
5896
+ };
5897
+ function hasPendingRequests(state) {
5898
+ for (const key in state.queries) {
5899
+ if (state.queries[key]?.status === "pending" /* pending */) return true;
5900
+ }
5901
+ for (const key in state.mutations) {
5902
+ if (state.mutations[key]?.status === "pending" /* pending */) return true;
5903
+ }
5904
+ return false;
5905
+ }
5906
+ function invalidateTags(newTags, mwApi) {
5907
+ const rootState = mwApi.getState();
5908
+ const state = rootState[reducerPath];
5909
+ pendingTagInvalidations.push(...newTags);
5910
+ if (state.config.invalidationBehavior === "delayed" && hasPendingRequests(state)) {
5911
+ return;
5912
+ }
5913
+ const tags = pendingTagInvalidations;
5914
+ pendingTagInvalidations = [];
5915
+ if (tags.length === 0) return;
5916
+ const toInvalidate = api.util.selectInvalidatedBy(rootState, tags);
5917
+ context.batch(() => {
5918
+ const valuesArray = Array.from(toInvalidate.values());
5919
+ for (const {
5920
+ queryCacheKey
5921
+ } of valuesArray) {
5922
+ const querySubState = state.queries[queryCacheKey];
5923
+ const subscriptionSubState = internalState.currentSubscriptions[queryCacheKey] ?? {};
5924
+ if (querySubState) {
5925
+ if (countObjectKeys(subscriptionSubState) === 0) {
5926
+ mwApi.dispatch(removeQueryResult({
5927
+ queryCacheKey
5928
+ }));
5929
+ } else if (querySubState.status !== "uninitialized" /* uninitialized */) {
5930
+ mwApi.dispatch(refetchQuery(querySubState));
5931
+ }
5932
+ }
5933
+ }
5934
+ });
5935
+ }
5936
+ return handler;
5937
+ };
5938
+
5939
+ // src/query/core/buildMiddleware/polling.ts
5940
+ var buildPollingHandler = ({
5941
+ reducerPath,
5942
+ queryThunk,
5943
+ api,
5944
+ refetchQuery,
5945
+ internalState
5946
+ }) => {
5947
+ const currentPolls = {};
5948
+ const handler = (action, mwApi) => {
5949
+ if (api.internalActions.updateSubscriptionOptions.match(action) || api.internalActions.unsubscribeQueryResult.match(action)) {
5950
+ updatePollingInterval(action.payload, mwApi);
5951
+ }
5952
+ if (queryThunk.pending.match(action) || queryThunk.rejected.match(action) && action.meta.condition) {
5953
+ updatePollingInterval(action.meta.arg, mwApi);
5954
+ }
5955
+ if (queryThunk.fulfilled.match(action) || queryThunk.rejected.match(action) && !action.meta.condition) {
5956
+ startNextPoll(action.meta.arg, mwApi);
5957
+ }
5958
+ if (api.util.resetApiState.match(action)) {
5959
+ clearPolls();
5960
+ }
5961
+ };
5962
+ function startNextPoll({
5963
+ queryCacheKey
5964
+ }, api2) {
5965
+ const state = api2.getState()[reducerPath];
5966
+ const querySubState = state.queries[queryCacheKey];
5967
+ const subscriptions = internalState.currentSubscriptions[queryCacheKey];
5968
+ if (!querySubState || querySubState.status === "uninitialized" /* uninitialized */) return;
5969
+ const {
5970
+ lowestPollingInterval,
5971
+ skipPollingIfUnfocused
5972
+ } = findLowestPollingInterval(subscriptions);
5973
+ if (!Number.isFinite(lowestPollingInterval)) return;
5974
+ const currentPoll = currentPolls[queryCacheKey];
5975
+ if (currentPoll?.timeout) {
5976
+ clearTimeout(currentPoll.timeout);
5977
+ currentPoll.timeout = void 0;
5978
+ }
5979
+ const nextPollTimestamp = Date.now() + lowestPollingInterval;
5980
+ currentPolls[queryCacheKey] = {
5981
+ nextPollTimestamp,
5982
+ pollingInterval: lowestPollingInterval,
5983
+ timeout: setTimeout(() => {
5984
+ if (state.config.focused || !skipPollingIfUnfocused) {
5985
+ api2.dispatch(refetchQuery(querySubState));
5986
+ }
5987
+ startNextPoll({
5988
+ queryCacheKey
5989
+ }, api2);
5990
+ }, lowestPollingInterval)
5991
+ };
5992
+ }
5993
+ function updatePollingInterval({
5994
+ queryCacheKey
5995
+ }, api2) {
5996
+ const state = api2.getState()[reducerPath];
5997
+ const querySubState = state.queries[queryCacheKey];
5998
+ const subscriptions = internalState.currentSubscriptions[queryCacheKey];
5999
+ if (!querySubState || querySubState.status === "uninitialized" /* uninitialized */) {
6000
+ return;
6001
+ }
6002
+ const {
6003
+ lowestPollingInterval
6004
+ } = findLowestPollingInterval(subscriptions);
6005
+ if (!Number.isFinite(lowestPollingInterval)) {
6006
+ cleanupPollForKey(queryCacheKey);
6007
+ return;
6008
+ }
6009
+ const currentPoll = currentPolls[queryCacheKey];
6010
+ const nextPollTimestamp = Date.now() + lowestPollingInterval;
6011
+ if (!currentPoll || nextPollTimestamp < currentPoll.nextPollTimestamp) {
6012
+ startNextPoll({
6013
+ queryCacheKey
6014
+ }, api2);
6015
+ }
6016
+ }
6017
+ function cleanupPollForKey(key) {
6018
+ const existingPoll = currentPolls[key];
6019
+ if (existingPoll?.timeout) {
6020
+ clearTimeout(existingPoll.timeout);
6021
+ }
6022
+ delete currentPolls[key];
6023
+ }
6024
+ function clearPolls() {
6025
+ for (const key of Object.keys(currentPolls)) {
6026
+ cleanupPollForKey(key);
6027
+ }
6028
+ }
6029
+ function findLowestPollingInterval(subscribers = {}) {
6030
+ let skipPollingIfUnfocused = false;
6031
+ let lowestPollingInterval = Number.POSITIVE_INFINITY;
6032
+ for (let key in subscribers) {
6033
+ if (!!subscribers[key].pollingInterval) {
6034
+ lowestPollingInterval = Math.min(subscribers[key].pollingInterval, lowestPollingInterval);
6035
+ skipPollingIfUnfocused = subscribers[key].skipPollingIfUnfocused || skipPollingIfUnfocused;
6036
+ }
6037
+ }
6038
+ return {
6039
+ lowestPollingInterval,
6040
+ skipPollingIfUnfocused
6041
+ };
6042
+ }
6043
+ return handler;
6044
+ };
6045
+
6046
+ // src/query/core/buildMiddleware/queryLifecycle.ts
6047
+ var buildQueryLifecycleHandler = ({
6048
+ api,
6049
+ context,
6050
+ queryThunk,
6051
+ mutationThunk
6052
+ }) => {
6053
+ const isPendingThunk = isPending(queryThunk, mutationThunk);
6054
+ const isRejectedThunk = isRejected(queryThunk, mutationThunk);
6055
+ const isFullfilledThunk = isFulfilled(queryThunk, mutationThunk);
6056
+ const lifecycleMap = {};
6057
+ const handler = (action, mwApi) => {
6058
+ if (isPendingThunk(action)) {
6059
+ const {
6060
+ requestId,
6061
+ arg: {
6062
+ endpointName,
6063
+ originalArgs
6064
+ }
6065
+ } = action.meta;
6066
+ const endpointDefinition = context.endpointDefinitions[endpointName];
6067
+ const onQueryStarted = endpointDefinition?.onQueryStarted;
6068
+ if (onQueryStarted) {
6069
+ const lifecycle = {};
6070
+ const queryFulfilled = new Promise((resolve, reject) => {
6071
+ lifecycle.resolve = resolve;
6072
+ lifecycle.reject = reject;
6073
+ });
6074
+ queryFulfilled.catch(() => {
6075
+ });
6076
+ lifecycleMap[requestId] = lifecycle;
6077
+ const selector = api.endpoints[endpointName].select(endpointDefinition.type === "query" /* query */ ? originalArgs : requestId);
6078
+ const extra = mwApi.dispatch((_, __, extra2) => extra2);
6079
+ const lifecycleApi = {
6080
+ ...mwApi,
6081
+ getCacheEntry: () => selector(mwApi.getState()),
6082
+ requestId,
6083
+ extra,
6084
+ updateCachedData: endpointDefinition.type === "query" /* query */ ? (updateRecipe) => mwApi.dispatch(api.util.updateQueryData(endpointName, originalArgs, updateRecipe)) : void 0,
6085
+ queryFulfilled
6086
+ };
6087
+ onQueryStarted(originalArgs, lifecycleApi);
6088
+ }
6089
+ } else if (isFullfilledThunk(action)) {
6090
+ const {
6091
+ requestId,
6092
+ baseQueryMeta
6093
+ } = action.meta;
6094
+ lifecycleMap[requestId]?.resolve({
6095
+ data: action.payload,
6096
+ meta: baseQueryMeta
6097
+ });
6098
+ delete lifecycleMap[requestId];
6099
+ } else if (isRejectedThunk(action)) {
6100
+ const {
6101
+ requestId,
6102
+ rejectedWithValue,
6103
+ baseQueryMeta
6104
+ } = action.meta;
6105
+ lifecycleMap[requestId]?.reject({
6106
+ error: action.payload ?? action.error,
6107
+ isUnhandledError: !rejectedWithValue,
6108
+ meta: baseQueryMeta
6109
+ });
6110
+ delete lifecycleMap[requestId];
6111
+ }
6112
+ };
6113
+ return handler;
6114
+ };
6115
+
6116
+ // src/query/core/buildMiddleware/windowEventHandling.ts
6117
+ var buildWindowEventHandler = ({
6118
+ reducerPath,
6119
+ context,
6120
+ api,
6121
+ refetchQuery,
6122
+ internalState
6123
+ }) => {
6124
+ const {
6125
+ removeQueryResult
6126
+ } = api.internalActions;
6127
+ const handler = (action, mwApi) => {
6128
+ if (onFocus.match(action)) {
6129
+ refetchValidQueries(mwApi, "refetchOnFocus");
6130
+ }
6131
+ if (onOnline.match(action)) {
6132
+ refetchValidQueries(mwApi, "refetchOnReconnect");
6133
+ }
6134
+ };
6135
+ function refetchValidQueries(api2, type) {
6136
+ const state = api2.getState()[reducerPath];
6137
+ const queries = state.queries;
6138
+ const subscriptions = internalState.currentSubscriptions;
6139
+ context.batch(() => {
6140
+ for (const queryCacheKey of Object.keys(subscriptions)) {
6141
+ const querySubState = queries[queryCacheKey];
6142
+ const subscriptionSubState = subscriptions[queryCacheKey];
6143
+ if (!subscriptionSubState || !querySubState) continue;
6144
+ const shouldRefetch = Object.values(subscriptionSubState).some((sub) => sub[type] === true) || Object.values(subscriptionSubState).every((sub) => sub[type] === void 0) && state.config[type];
6145
+ if (shouldRefetch) {
6146
+ if (countObjectKeys(subscriptionSubState) === 0) {
6147
+ api2.dispatch(removeQueryResult({
6148
+ queryCacheKey
6149
+ }));
6150
+ } else if (querySubState.status !== "uninitialized" /* uninitialized */) {
6151
+ api2.dispatch(refetchQuery(querySubState));
6152
+ }
6153
+ }
6154
+ }
6155
+ });
6156
+ }
6157
+ return handler;
6158
+ };
6159
+
6160
+ // src/query/core/buildMiddleware/index.ts
6161
+ function buildMiddleware(input) {
6162
+ const {
6163
+ reducerPath,
6164
+ queryThunk,
6165
+ api,
6166
+ context
6167
+ } = input;
6168
+ const {
6169
+ apiUid
6170
+ } = context;
6171
+ const actions = {
6172
+ invalidateTags: createAction(`${reducerPath}/invalidateTags`)
6173
+ };
6174
+ const isThisApiSliceAction = (action) => action.type.startsWith(`${reducerPath}/`);
6175
+ const handlerBuilders = [buildDevCheckHandler, buildCacheCollectionHandler, buildInvalidationByTagsHandler, buildPollingHandler, buildCacheLifecycleHandler, buildQueryLifecycleHandler];
6176
+ const middleware = (mwApi) => {
6177
+ let initialized2 = false;
6178
+ const internalState = {
6179
+ currentSubscriptions: {}
6180
+ };
6181
+ const builderArgs = {
6182
+ ...input,
6183
+ internalState,
6184
+ refetchQuery,
6185
+ isThisApiSliceAction
6186
+ };
6187
+ const handlers = handlerBuilders.map((build) => build(builderArgs));
6188
+ const batchedActionsHandler = buildBatchedActionsHandler(builderArgs);
6189
+ const windowEventsHandler = buildWindowEventHandler(builderArgs);
6190
+ return (next) => {
6191
+ return (action) => {
6192
+ if (!isAction(action)) {
6193
+ return next(action);
6194
+ }
6195
+ if (!initialized2) {
6196
+ initialized2 = true;
6197
+ mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));
6198
+ }
6199
+ const mwApiWithNext = {
6200
+ ...mwApi,
6201
+ next
6202
+ };
6203
+ const stateBefore = mwApi.getState();
6204
+ const [actionShouldContinue, internalProbeResult] = batchedActionsHandler(action, mwApiWithNext, stateBefore);
6205
+ let res;
6206
+ if (actionShouldContinue) {
6207
+ res = next(action);
6208
+ } else {
6209
+ res = internalProbeResult;
6210
+ }
6211
+ if (!!mwApi.getState()[reducerPath]) {
6212
+ windowEventsHandler(action, mwApiWithNext, stateBefore);
6213
+ if (isThisApiSliceAction(action) || context.hasRehydrationInfo(action)) {
6214
+ for (const handler of handlers) {
6215
+ handler(action, mwApiWithNext, stateBefore);
6216
+ }
6217
+ }
6218
+ }
6219
+ return res;
6220
+ };
6221
+ };
6222
+ };
6223
+ return {
6224
+ middleware,
6225
+ actions
6226
+ };
6227
+ function refetchQuery(querySubState) {
6228
+ return input.api.endpoints[querySubState.endpointName].initiate(querySubState.originalArgs, {
6229
+ subscribe: false,
6230
+ forceRefetch: true
6231
+ });
6232
+ }
6233
+ }
6234
+
6235
+ // src/query/core/module.ts
6236
+ var coreModuleName = /* @__PURE__ */ Symbol();
6237
+ var coreModule = ({
6238
+ createSelector: createSelector2 = createSelector
6239
+ } = {}) => ({
6240
+ name: coreModuleName,
6241
+ init(api, {
6242
+ baseQuery,
6243
+ tagTypes,
6244
+ reducerPath,
6245
+ serializeQueryArgs,
6246
+ keepUnusedDataFor,
6247
+ refetchOnMountOrArgChange,
6248
+ refetchOnFocus,
6249
+ refetchOnReconnect,
6250
+ invalidationBehavior
6251
+ }, context) {
6252
+ enablePatches();
6253
+ const assertTagType = (tag) => {
6254
+ if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
6255
+ if (!tagTypes.includes(tag.type)) {
6256
+ console.error(`Tag type '${tag.type}' was used, but not specified in \`tagTypes\`!`);
6257
+ }
6258
+ }
6259
+ return tag;
6260
+ };
6261
+ Object.assign(api, {
6262
+ reducerPath,
6263
+ endpoints: {},
6264
+ internalActions: {
6265
+ onOnline,
6266
+ onOffline,
6267
+ onFocus,
6268
+ onFocusLost
6269
+ },
6270
+ util: {}
6271
+ });
6272
+ const {
6273
+ queryThunk,
6274
+ mutationThunk,
6275
+ patchQueryData,
6276
+ updateQueryData,
6277
+ upsertQueryData,
6278
+ prefetch,
6279
+ buildMatchThunkActions
6280
+ } = buildThunks({
6281
+ baseQuery,
6282
+ reducerPath,
6283
+ context,
6284
+ api,
6285
+ serializeQueryArgs,
6286
+ assertTagType
6287
+ });
6288
+ const {
6289
+ reducer,
6290
+ actions: sliceActions
6291
+ } = buildSlice({
6292
+ context,
6293
+ queryThunk,
6294
+ mutationThunk,
6295
+ serializeQueryArgs,
6296
+ reducerPath,
6297
+ assertTagType,
6298
+ config: {
6299
+ refetchOnFocus,
6300
+ refetchOnReconnect,
6301
+ refetchOnMountOrArgChange,
6302
+ keepUnusedDataFor,
6303
+ reducerPath,
6304
+ invalidationBehavior
6305
+ }
6306
+ });
6307
+ safeAssign(api.util, {
6308
+ patchQueryData,
6309
+ updateQueryData,
6310
+ upsertQueryData,
6311
+ prefetch,
6312
+ resetApiState: sliceActions.resetApiState,
6313
+ upsertQueryEntries: sliceActions.cacheEntriesUpserted
6314
+ });
6315
+ safeAssign(api.internalActions, sliceActions);
6316
+ const {
6317
+ middleware,
6318
+ actions: middlewareActions
6319
+ } = buildMiddleware({
6320
+ reducerPath,
6321
+ context,
6322
+ queryThunk,
6323
+ mutationThunk,
6324
+ api,
6325
+ assertTagType
6326
+ });
6327
+ safeAssign(api.util, middlewareActions);
6328
+ safeAssign(api, {
6329
+ reducer,
6330
+ middleware
6331
+ });
6332
+ const {
6333
+ buildQuerySelector,
6334
+ buildMutationSelector,
6335
+ selectInvalidatedBy,
6336
+ selectCachedArgsForQuery
6337
+ } = buildSelectors({
6338
+ serializeQueryArgs,
6339
+ reducerPath,
6340
+ createSelector: createSelector2
6341
+ });
6342
+ safeAssign(api.util, {
6343
+ selectInvalidatedBy,
6344
+ selectCachedArgsForQuery
6345
+ });
6346
+ const {
6347
+ buildInitiateQuery,
6348
+ buildInitiateMutation,
6349
+ getRunningMutationThunk,
6350
+ getRunningMutationsThunk,
6351
+ getRunningQueriesThunk,
6352
+ getRunningQueryThunk
6353
+ } = buildInitiate({
6354
+ queryThunk,
6355
+ mutationThunk,
6356
+ api,
6357
+ serializeQueryArgs,
6358
+ context
6359
+ });
6360
+ safeAssign(api.util, {
6361
+ getRunningMutationThunk,
6362
+ getRunningMutationsThunk,
6363
+ getRunningQueryThunk,
6364
+ getRunningQueriesThunk
6365
+ });
6366
+ return {
6367
+ name: coreModuleName,
6368
+ injectEndpoint(endpointName, definition) {
6369
+ const anyApi = api;
6370
+ anyApi.endpoints[endpointName] ??= {};
6371
+ if (isQueryDefinition(definition)) {
6372
+ safeAssign(anyApi.endpoints[endpointName], {
6373
+ name: endpointName,
6374
+ select: buildQuerySelector(endpointName, definition),
6375
+ initiate: buildInitiateQuery(endpointName, definition)
6376
+ }, buildMatchThunkActions(queryThunk, endpointName));
6377
+ } else if (isMutationDefinition(definition)) {
6378
+ safeAssign(anyApi.endpoints[endpointName], {
6379
+ name: endpointName,
6380
+ select: buildMutationSelector(),
6381
+ initiate: buildInitiateMutation(endpointName)
6382
+ }, buildMatchThunkActions(mutationThunk, endpointName));
6383
+ }
6384
+ }
6385
+ };
6386
+ }
6387
+ });
6388
+
6389
+ // src/query/core/index.ts
6390
+ var createApi = /* @__PURE__ */ buildCreateApi(coreModule());
6391
+
6392
+ var rtkQuery_modern = /*#__PURE__*/Object.freeze({
6393
+ __proto__: null,
6394
+ QueryStatus: QueryStatus,
6395
+ _NEVER: _NEVER,
6396
+ buildCreateApi: buildCreateApi,
6397
+ copyWithStructuralSharing: copyWithStructuralSharing,
6398
+ coreModule: coreModule,
6399
+ coreModuleName: coreModuleName,
6400
+ createApi: createApi,
6401
+ defaultSerializeQueryArgs: defaultSerializeQueryArgs,
6402
+ fakeBaseQuery: fakeBaseQuery,
6403
+ fetchBaseQuery: fetchBaseQuery,
6404
+ retry: retry,
6405
+ setupListeners: setupListeners,
6406
+ skipToken: skipToken
6407
+ });
6408
+
6409
+ export { ReducerType, SHOULD_AUTOBATCH, TaskAbortError, Tuple, actionTypes_default as __DO_NOT_USE__ActionTypes, addListener, applyMiddleware, asyncThunkCreator, autoBatchEnhancer, bindActionCreators, buildCreateSlice, clearAllListeners, combineReducers, combineSlices, compose, configureStore, createAction, createActionCreatorInvariantMiddleware, createAsyncThunk, createDraftSafeSelector, createDraftSafeSelectorCreator, createDynamicMiddleware, createEntityAdapter, createImmutableStateInvariantMiddleware, createListenerMiddleware, produce as createNextState, createReducer, createSelector, createSelectorCreator, createSerializableStateInvariantMiddleware, createSlice, createStore, current, findNonSerializableValue, formatProdErrorMessage, freeze, isAction, isActionCreator, isAllOf, isAnyOf, isAsyncThunkAction, isDraft, isFSA as isFluxStandardAction, isFulfilled, isImmutableDefault, isPending, isPlain, isPlainObject$1 as isPlainObject, isRejected, isRejectedWithValue, legacy_createStore, lruMemoize, miniSerializeError, nanoid, original$1 as original, prepareAutoBatched, rtkQuery_modern as reactQuery, removeListener, unwrapResult, weakMapMemoize };
3719
6410
  //# sourceMappingURL=index.es.js.map