rtk-query.esm.js 110 KB

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