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