rtk-query.legacy-esm.js 76 KB

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