redux-toolkit.development.cjs 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256
  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 __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
  19. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  20. // src/index.ts
  21. var src_exports = {};
  22. __export(src_exports, {
  23. ReducerType: () => ReducerType,
  24. SHOULD_AUTOBATCH: () => SHOULD_AUTOBATCH,
  25. TaskAbortError: () => TaskAbortError,
  26. Tuple: () => Tuple,
  27. addListener: () => addListener,
  28. asyncThunkCreator: () => asyncThunkCreator,
  29. autoBatchEnhancer: () => autoBatchEnhancer,
  30. buildCreateSlice: () => buildCreateSlice,
  31. clearAllListeners: () => clearAllListeners,
  32. combineSlices: () => combineSlices,
  33. configureStore: () => configureStore,
  34. createAction: () => createAction,
  35. createActionCreatorInvariantMiddleware: () => createActionCreatorInvariantMiddleware,
  36. createAsyncThunk: () => createAsyncThunk,
  37. createDraftSafeSelector: () => createDraftSafeSelector,
  38. createDraftSafeSelectorCreator: () => createDraftSafeSelectorCreator,
  39. createDynamicMiddleware: () => createDynamicMiddleware,
  40. createEntityAdapter: () => createEntityAdapter,
  41. createImmutableStateInvariantMiddleware: () => createImmutableStateInvariantMiddleware,
  42. createListenerMiddleware: () => createListenerMiddleware,
  43. createNextState: () => import_immer5.produce,
  44. createReducer: () => createReducer,
  45. createSelector: () => import_reselect2.createSelector,
  46. createSelectorCreator: () => import_reselect2.createSelectorCreator,
  47. createSerializableStateInvariantMiddleware: () => createSerializableStateInvariantMiddleware,
  48. createSlice: () => createSlice,
  49. current: () => import_immer5.current,
  50. findNonSerializableValue: () => findNonSerializableValue,
  51. formatProdErrorMessage: () => formatProdErrorMessage,
  52. freeze: () => import_immer5.freeze,
  53. isActionCreator: () => isActionCreator,
  54. isAllOf: () => isAllOf,
  55. isAnyOf: () => isAnyOf,
  56. isAsyncThunkAction: () => isAsyncThunkAction,
  57. isDraft: () => import_immer5.isDraft,
  58. isFluxStandardAction: () => isFSA,
  59. isFulfilled: () => isFulfilled,
  60. isImmutableDefault: () => isImmutableDefault,
  61. isPending: () => isPending,
  62. isPlain: () => isPlain,
  63. isRejected: () => isRejected,
  64. isRejectedWithValue: () => isRejectedWithValue,
  65. lruMemoize: () => import_reselect2.lruMemoize,
  66. miniSerializeError: () => miniSerializeError,
  67. nanoid: () => nanoid,
  68. original: () => import_immer5.original,
  69. prepareAutoBatched: () => prepareAutoBatched,
  70. removeListener: () => removeListener,
  71. unwrapResult: () => unwrapResult,
  72. weakMapMemoize: () => import_reselect2.weakMapMemoize
  73. });
  74. module.exports = __toCommonJS(src_exports);
  75. __reExport(src_exports, require("redux"), module.exports);
  76. var import_immer5 = require("immer");
  77. var import_reselect2 = require("reselect");
  78. // src/createDraftSafeSelector.ts
  79. var import_immer = require("immer");
  80. var import_reselect = require("reselect");
  81. var createDraftSafeSelectorCreator = (...args) => {
  82. const createSelector2 = (0, import_reselect.createSelectorCreator)(...args);
  83. return (...args2) => {
  84. const selector = createSelector2(...args2);
  85. const wrappedSelector = (value, ...rest) => selector((0, import_immer.isDraft)(value) ? (0, import_immer.current)(value) : value, ...rest);
  86. Object.assign(wrappedSelector, selector);
  87. return wrappedSelector;
  88. };
  89. };
  90. var createDraftSafeSelector = createDraftSafeSelectorCreator(import_reselect.weakMapMemoize);
  91. // src/configureStore.ts
  92. var import_redux4 = require("redux");
  93. // src/devtoolsExtension.ts
  94. var import_redux = require("redux");
  95. var composeWithDevTools = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function() {
  96. if (arguments.length === 0)
  97. return void 0;
  98. if (typeof arguments[0] === "object")
  99. return import_redux.compose;
  100. return import_redux.compose.apply(null, arguments);
  101. };
  102. var devToolsEnhancer = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__ : function() {
  103. return function(noop3) {
  104. return noop3;
  105. };
  106. };
  107. // src/getDefaultMiddleware.ts
  108. var import_redux_thunk = require("redux-thunk");
  109. // src/createAction.ts
  110. var import_redux2 = require("redux");
  111. // src/tsHelpers.ts
  112. var hasMatchFunction = (v) => {
  113. return v && typeof v.match === "function";
  114. };
  115. // src/createAction.ts
  116. function createAction(type, prepareAction) {
  117. function actionCreator(...args) {
  118. if (prepareAction) {
  119. let prepared = prepareAction(...args);
  120. if (!prepared) {
  121. throw new Error(false ? _formatProdErrorMessage(0) : "prepareAction did not return an object");
  122. }
  123. return {
  124. type,
  125. payload: prepared.payload,
  126. ..."meta" in prepared && {
  127. meta: prepared.meta
  128. },
  129. ..."error" in prepared && {
  130. error: prepared.error
  131. }
  132. };
  133. }
  134. return {
  135. type,
  136. payload: args[0]
  137. };
  138. }
  139. actionCreator.toString = () => `${type}`;
  140. actionCreator.type = type;
  141. actionCreator.match = (action) => (0, import_redux2.isAction)(action) && action.type === type;
  142. return actionCreator;
  143. }
  144. function isActionCreator(action) {
  145. return typeof action === "function" && "type" in action && // hasMatchFunction only wants Matchers but I don't see the point in rewriting it
  146. hasMatchFunction(action);
  147. }
  148. function isFSA(action) {
  149. return (0, import_redux2.isAction)(action) && Object.keys(action).every(isValidKey);
  150. }
  151. function isValidKey(key) {
  152. return ["type", "payload", "error", "meta"].indexOf(key) > -1;
  153. }
  154. // src/actionCreatorInvariantMiddleware.ts
  155. function getMessage(type) {
  156. const splitType = type ? `${type}`.split("/") : [];
  157. const actionName = splitType[splitType.length - 1] || "actionCreator";
  158. return `Detected an action creator with type "${type || "unknown"}" being dispatched.
  159. Make sure you're calling the action creator before dispatching, i.e. \`dispatch(${actionName}())\` instead of \`dispatch(${actionName})\`. This is necessary even if the action has no payload.`;
  160. }
  161. function createActionCreatorInvariantMiddleware(options = {}) {
  162. if (false) {
  163. return () => (next) => (action) => next(action);
  164. }
  165. const {
  166. isActionCreator: isActionCreator2 = isActionCreator
  167. } = options;
  168. return () => (next) => (action) => {
  169. if (isActionCreator2(action)) {
  170. console.warn(getMessage(action.type));
  171. }
  172. return next(action);
  173. };
  174. }
  175. // src/utils.ts
  176. var import_immer2 = require("immer");
  177. function getTimeMeasureUtils(maxDelay, fnName) {
  178. let elapsed = 0;
  179. return {
  180. measureTime(fn) {
  181. const started = Date.now();
  182. try {
  183. return fn();
  184. } finally {
  185. const finished = Date.now();
  186. elapsed += finished - started;
  187. }
  188. },
  189. warnIfExceeded() {
  190. if (elapsed > maxDelay) {
  191. console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms.
  192. If your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.
  193. It is disabled in production builds, so you don't need to worry about that.`);
  194. }
  195. }
  196. };
  197. }
  198. function find(iterable, comparator) {
  199. for (const entry of iterable) {
  200. if (comparator(entry)) {
  201. return entry;
  202. }
  203. }
  204. return void 0;
  205. }
  206. var Tuple = class _Tuple extends Array {
  207. constructor(...items) {
  208. super(...items);
  209. Object.setPrototypeOf(this, _Tuple.prototype);
  210. }
  211. static get [Symbol.species]() {
  212. return _Tuple;
  213. }
  214. concat(...arr) {
  215. return super.concat.apply(this, arr);
  216. }
  217. prepend(...arr) {
  218. if (arr.length === 1 && Array.isArray(arr[0])) {
  219. return new _Tuple(...arr[0].concat(this));
  220. }
  221. return new _Tuple(...arr.concat(this));
  222. }
  223. };
  224. function freezeDraftable(val) {
  225. return (0, import_immer2.isDraftable)(val) ? (0, import_immer2.produce)(val, () => {
  226. }) : val;
  227. }
  228. function emplace(map, key, handler) {
  229. if (map.has(key)) {
  230. let value = map.get(key);
  231. if (handler.update) {
  232. value = handler.update(value, key, map);
  233. map.set(key, value);
  234. }
  235. return value;
  236. }
  237. if (!handler.insert)
  238. throw new Error(false ? _formatProdErrorMessage(10) : "No insert provided for key not already in map");
  239. const inserted = handler.insert(key, map);
  240. map.set(key, inserted);
  241. return inserted;
  242. }
  243. // src/immutableStateInvariantMiddleware.ts
  244. function isImmutableDefault(value) {
  245. return typeof value !== "object" || value == null || Object.isFrozen(value);
  246. }
  247. function trackForMutations(isImmutable, ignorePaths, obj) {
  248. const trackedProperties = trackProperties(isImmutable, ignorePaths, obj);
  249. return {
  250. detectMutations() {
  251. return detectMutations(isImmutable, ignorePaths, trackedProperties, obj);
  252. }
  253. };
  254. }
  255. function trackProperties(isImmutable, ignorePaths = [], obj, path = "", checkedObjects = /* @__PURE__ */ new Set()) {
  256. const tracked = {
  257. value: obj
  258. };
  259. if (!isImmutable(obj) && !checkedObjects.has(obj)) {
  260. checkedObjects.add(obj);
  261. tracked.children = {};
  262. for (const key in obj) {
  263. const childPath = path ? path + "." + key : key;
  264. if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) {
  265. continue;
  266. }
  267. tracked.children[key] = trackProperties(isImmutable, ignorePaths, obj[key], childPath);
  268. }
  269. }
  270. return tracked;
  271. }
  272. function detectMutations(isImmutable, ignoredPaths = [], trackedProperty, obj, sameParentRef = false, path = "") {
  273. const prevObj = trackedProperty ? trackedProperty.value : void 0;
  274. const sameRef = prevObj === obj;
  275. if (sameParentRef && !sameRef && !Number.isNaN(obj)) {
  276. return {
  277. wasMutated: true,
  278. path
  279. };
  280. }
  281. if (isImmutable(prevObj) || isImmutable(obj)) {
  282. return {
  283. wasMutated: false
  284. };
  285. }
  286. const keysToDetect = {};
  287. for (let key in trackedProperty.children) {
  288. keysToDetect[key] = true;
  289. }
  290. for (let key in obj) {
  291. keysToDetect[key] = true;
  292. }
  293. const hasIgnoredPaths = ignoredPaths.length > 0;
  294. for (let key in keysToDetect) {
  295. const nestedPath = path ? path + "." + key : key;
  296. if (hasIgnoredPaths) {
  297. const hasMatches = ignoredPaths.some((ignored) => {
  298. if (ignored instanceof RegExp) {
  299. return ignored.test(nestedPath);
  300. }
  301. return nestedPath === ignored;
  302. });
  303. if (hasMatches) {
  304. continue;
  305. }
  306. }
  307. const result = detectMutations(isImmutable, ignoredPaths, trackedProperty.children[key], obj[key], sameRef, nestedPath);
  308. if (result.wasMutated) {
  309. return result;
  310. }
  311. }
  312. return {
  313. wasMutated: false
  314. };
  315. }
  316. function createImmutableStateInvariantMiddleware(options = {}) {
  317. if (false) {
  318. return () => (next) => (action) => next(action);
  319. } else {
  320. let stringify2 = function(obj, serializer, indent, decycler) {
  321. return JSON.stringify(obj, getSerialize2(serializer, decycler), indent);
  322. }, getSerialize2 = function(serializer, decycler) {
  323. let stack = [], keys = [];
  324. if (!decycler)
  325. decycler = function(_, value) {
  326. if (stack[0] === value)
  327. return "[Circular ~]";
  328. return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]";
  329. };
  330. return function(key, value) {
  331. if (stack.length > 0) {
  332. var thisPos = stack.indexOf(this);
  333. ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);
  334. ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);
  335. if (~stack.indexOf(value))
  336. value = decycler.call(this, key, value);
  337. } else
  338. stack.push(value);
  339. return serializer == null ? value : serializer.call(this, key, value);
  340. };
  341. };
  342. var stringify = stringify2, getSerialize = getSerialize2;
  343. let {
  344. isImmutable = isImmutableDefault,
  345. ignoredPaths,
  346. warnAfter = 32
  347. } = options;
  348. const track = trackForMutations.bind(null, isImmutable, ignoredPaths);
  349. return ({
  350. getState
  351. }) => {
  352. let state = getState();
  353. let tracker = track(state);
  354. let result;
  355. return (next) => (action) => {
  356. const measureUtils = getTimeMeasureUtils(warnAfter, "ImmutableStateInvariantMiddleware");
  357. measureUtils.measureTime(() => {
  358. state = getState();
  359. result = tracker.detectMutations();
  360. tracker = track(state);
  361. if (result.wasMutated) {
  362. throw new Error(false ? _formatProdErrorMessage(19) : `A state mutation was detected between dispatches, in the path '${result.path || ""}'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);
  363. }
  364. });
  365. const dispatchedAction = next(action);
  366. measureUtils.measureTime(() => {
  367. state = getState();
  368. result = tracker.detectMutations();
  369. tracker = track(state);
  370. if (result.wasMutated) {
  371. throw new Error(false ? _formatProdErrorMessage2(20) : `A state mutation was detected inside a dispatch, in the path: ${result.path || ""}. Take a look at the reducer(s) handling the action ${stringify2(action)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);
  372. }
  373. });
  374. measureUtils.warnIfExceeded();
  375. return dispatchedAction;
  376. };
  377. };
  378. }
  379. }
  380. // src/serializableStateInvariantMiddleware.ts
  381. var import_redux3 = require("redux");
  382. function isPlain(val) {
  383. const type = typeof val;
  384. return val == null || type === "string" || type === "boolean" || type === "number" || Array.isArray(val) || (0, import_redux3.isPlainObject)(val);
  385. }
  386. function findNonSerializableValue(value, path = "", isSerializable = isPlain, getEntries, ignoredPaths = [], cache) {
  387. let foundNestedSerializable;
  388. if (!isSerializable(value)) {
  389. return {
  390. keyPath: path || "<root>",
  391. value
  392. };
  393. }
  394. if (typeof value !== "object" || value === null) {
  395. return false;
  396. }
  397. if (cache?.has(value))
  398. return false;
  399. const entries = getEntries != null ? getEntries(value) : Object.entries(value);
  400. const hasIgnoredPaths = ignoredPaths.length > 0;
  401. for (const [key, nestedValue] of entries) {
  402. const nestedPath = path ? path + "." + key : key;
  403. if (hasIgnoredPaths) {
  404. const hasMatches = ignoredPaths.some((ignored) => {
  405. if (ignored instanceof RegExp) {
  406. return ignored.test(nestedPath);
  407. }
  408. return nestedPath === ignored;
  409. });
  410. if (hasMatches) {
  411. continue;
  412. }
  413. }
  414. if (!isSerializable(nestedValue)) {
  415. return {
  416. keyPath: nestedPath,
  417. value: nestedValue
  418. };
  419. }
  420. if (typeof nestedValue === "object") {
  421. foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths, cache);
  422. if (foundNestedSerializable) {
  423. return foundNestedSerializable;
  424. }
  425. }
  426. }
  427. if (cache && isNestedFrozen(value))
  428. cache.add(value);
  429. return false;
  430. }
  431. function isNestedFrozen(value) {
  432. if (!Object.isFrozen(value))
  433. return false;
  434. for (const nestedValue of Object.values(value)) {
  435. if (typeof nestedValue !== "object" || nestedValue === null)
  436. continue;
  437. if (!isNestedFrozen(nestedValue))
  438. return false;
  439. }
  440. return true;
  441. }
  442. function createSerializableStateInvariantMiddleware(options = {}) {
  443. if (false) {
  444. return () => (next) => (action) => next(action);
  445. } else {
  446. const {
  447. isSerializable = isPlain,
  448. getEntries,
  449. ignoredActions = [],
  450. ignoredActionPaths = ["meta.arg", "meta.baseQueryMeta"],
  451. ignoredPaths = [],
  452. warnAfter = 32,
  453. ignoreState = false,
  454. ignoreActions = false,
  455. disableCache = false
  456. } = options;
  457. const cache = !disableCache && WeakSet ? /* @__PURE__ */ new WeakSet() : void 0;
  458. return (storeAPI) => (next) => (action) => {
  459. if (!(0, import_redux3.isAction)(action)) {
  460. return next(action);
  461. }
  462. const result = next(action);
  463. const measureUtils = getTimeMeasureUtils(warnAfter, "SerializableStateInvariantMiddleware");
  464. if (!ignoreActions && !(ignoredActions.length && ignoredActions.indexOf(action.type) !== -1)) {
  465. measureUtils.measureTime(() => {
  466. const foundActionNonSerializableValue = findNonSerializableValue(action, "", isSerializable, getEntries, ignoredActionPaths, cache);
  467. if (foundActionNonSerializableValue) {
  468. const {
  469. keyPath,
  470. value
  471. } = foundActionNonSerializableValue;
  472. console.error(`A non-serializable value was detected in an action, in the path: \`${keyPath}\`. Value:`, value, "\nTake a look at the logic that dispatched this action: ", action, "\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)", "\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)");
  473. }
  474. });
  475. }
  476. if (!ignoreState) {
  477. measureUtils.measureTime(() => {
  478. const state = storeAPI.getState();
  479. const foundStateNonSerializableValue = findNonSerializableValue(state, "", isSerializable, getEntries, ignoredPaths, cache);
  480. if (foundStateNonSerializableValue) {
  481. const {
  482. keyPath,
  483. value
  484. } = foundStateNonSerializableValue;
  485. console.error(`A non-serializable value was detected in the state, in the path: \`${keyPath}\`. Value:`, value, `
  486. Take a look at the reducer(s) handling this action type: ${action.type}.
  487. (See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`);
  488. }
  489. });
  490. measureUtils.warnIfExceeded();
  491. }
  492. return result;
  493. };
  494. }
  495. }
  496. // src/getDefaultMiddleware.ts
  497. function isBoolean(x) {
  498. return typeof x === "boolean";
  499. }
  500. var buildGetDefaultMiddleware = () => function getDefaultMiddleware(options) {
  501. const {
  502. thunk = true,
  503. immutableCheck = true,
  504. serializableCheck = true,
  505. actionCreatorCheck = true
  506. } = options ?? {};
  507. let middlewareArray = new Tuple();
  508. if (thunk) {
  509. if (isBoolean(thunk)) {
  510. middlewareArray.push(import_redux_thunk.thunk);
  511. } else {
  512. middlewareArray.push((0, import_redux_thunk.withExtraArgument)(thunk.extraArgument));
  513. }
  514. }
  515. if (true) {
  516. if (immutableCheck) {
  517. let immutableOptions = {};
  518. if (!isBoolean(immutableCheck)) {
  519. immutableOptions = immutableCheck;
  520. }
  521. middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));
  522. }
  523. if (serializableCheck) {
  524. let serializableOptions = {};
  525. if (!isBoolean(serializableCheck)) {
  526. serializableOptions = serializableCheck;
  527. }
  528. middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));
  529. }
  530. if (actionCreatorCheck) {
  531. let actionCreatorOptions = {};
  532. if (!isBoolean(actionCreatorCheck)) {
  533. actionCreatorOptions = actionCreatorCheck;
  534. }
  535. middlewareArray.unshift(createActionCreatorInvariantMiddleware(actionCreatorOptions));
  536. }
  537. }
  538. return middlewareArray;
  539. };
  540. // src/autoBatchEnhancer.ts
  541. var SHOULD_AUTOBATCH = "RTK_autoBatch";
  542. var prepareAutoBatched = () => (payload) => ({
  543. payload,
  544. meta: {
  545. [SHOULD_AUTOBATCH]: true
  546. }
  547. });
  548. var createQueueWithTimer = (timeout) => {
  549. return (notify) => {
  550. setTimeout(notify, timeout);
  551. };
  552. };
  553. var rAF = typeof window !== "undefined" && window.requestAnimationFrame ? window.requestAnimationFrame : createQueueWithTimer(10);
  554. var autoBatchEnhancer = (options = {
  555. type: "raf"
  556. }) => (next) => (...args) => {
  557. const store = next(...args);
  558. let notifying = true;
  559. let shouldNotifyAtEndOfTick = false;
  560. let notificationQueued = false;
  561. const listeners = /* @__PURE__ */ new Set();
  562. const queueCallback = options.type === "tick" ? queueMicrotask : options.type === "raf" ? rAF : options.type === "callback" ? options.queueNotification : createQueueWithTimer(options.timeout);
  563. const notifyListeners = () => {
  564. notificationQueued = false;
  565. if (shouldNotifyAtEndOfTick) {
  566. shouldNotifyAtEndOfTick = false;
  567. listeners.forEach((l) => l());
  568. }
  569. };
  570. return Object.assign({}, store, {
  571. // Override the base `store.subscribe` method to keep original listeners
  572. // from running if we're delaying notifications
  573. subscribe(listener2) {
  574. const wrappedListener = () => notifying && listener2();
  575. const unsubscribe = store.subscribe(wrappedListener);
  576. listeners.add(listener2);
  577. return () => {
  578. unsubscribe();
  579. listeners.delete(listener2);
  580. };
  581. },
  582. // Override the base `store.dispatch` method so that we can check actions
  583. // for the `shouldAutoBatch` flag and determine if batching is active
  584. dispatch(action) {
  585. try {
  586. notifying = !action?.meta?.[SHOULD_AUTOBATCH];
  587. shouldNotifyAtEndOfTick = !notifying;
  588. if (shouldNotifyAtEndOfTick) {
  589. if (!notificationQueued) {
  590. notificationQueued = true;
  591. queueCallback(notifyListeners);
  592. }
  593. }
  594. return store.dispatch(action);
  595. } finally {
  596. notifying = true;
  597. }
  598. }
  599. });
  600. };
  601. // src/getDefaultEnhancers.ts
  602. var buildGetDefaultEnhancers = (middlewareEnhancer) => function getDefaultEnhancers(options) {
  603. const {
  604. autoBatch = true
  605. } = options ?? {};
  606. let enhancerArray = new Tuple(middlewareEnhancer);
  607. if (autoBatch) {
  608. enhancerArray.push(autoBatchEnhancer(typeof autoBatch === "object" ? autoBatch : void 0));
  609. }
  610. return enhancerArray;
  611. };
  612. // src/configureStore.ts
  613. var IS_PRODUCTION = false;
  614. function configureStore(options) {
  615. const getDefaultMiddleware = buildGetDefaultMiddleware();
  616. const {
  617. reducer = void 0,
  618. middleware,
  619. devTools = true,
  620. preloadedState = void 0,
  621. enhancers = void 0
  622. } = options || {};
  623. let rootReducer;
  624. if (typeof reducer === "function") {
  625. rootReducer = reducer;
  626. } else if ((0, import_redux4.isPlainObject)(reducer)) {
  627. rootReducer = (0, import_redux4.combineReducers)(reducer);
  628. } else {
  629. throw new Error(false ? _formatProdErrorMessage(1) : "`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers");
  630. }
  631. if (!IS_PRODUCTION && middleware && typeof middleware !== "function") {
  632. throw new Error(false ? _formatProdErrorMessage2(2) : "`middleware` field must be a callback");
  633. }
  634. let finalMiddleware;
  635. if (typeof middleware === "function") {
  636. finalMiddleware = middleware(getDefaultMiddleware);
  637. if (!IS_PRODUCTION && !Array.isArray(finalMiddleware)) {
  638. throw new Error(false ? _formatProdErrorMessage3(3) : "when using a middleware builder function, an array of middleware must be returned");
  639. }
  640. } else {
  641. finalMiddleware = getDefaultMiddleware();
  642. }
  643. if (!IS_PRODUCTION && finalMiddleware.some((item) => typeof item !== "function")) {
  644. throw new Error(false ? _formatProdErrorMessage4(4) : "each middleware provided to configureStore must be a function");
  645. }
  646. let finalCompose = import_redux4.compose;
  647. if (devTools) {
  648. finalCompose = composeWithDevTools({
  649. // Enable capture of stack traces for dispatched Redux actions
  650. trace: !IS_PRODUCTION,
  651. ...typeof devTools === "object" && devTools
  652. });
  653. }
  654. const middlewareEnhancer = (0, import_redux4.applyMiddleware)(...finalMiddleware);
  655. const getDefaultEnhancers = buildGetDefaultEnhancers(middlewareEnhancer);
  656. if (!IS_PRODUCTION && enhancers && typeof enhancers !== "function") {
  657. throw new Error(false ? _formatProdErrorMessage5(5) : "`enhancers` field must be a callback");
  658. }
  659. let storeEnhancers = typeof enhancers === "function" ? enhancers(getDefaultEnhancers) : getDefaultEnhancers();
  660. if (!IS_PRODUCTION && !Array.isArray(storeEnhancers)) {
  661. throw new Error(false ? _formatProdErrorMessage6(6) : "`enhancers` callback must return an array");
  662. }
  663. if (!IS_PRODUCTION && storeEnhancers.some((item) => typeof item !== "function")) {
  664. throw new Error(false ? _formatProdErrorMessage7(7) : "each enhancer provided to configureStore must be a function");
  665. }
  666. if (!IS_PRODUCTION && finalMiddleware.length && !storeEnhancers.includes(middlewareEnhancer)) {
  667. console.error("middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`");
  668. }
  669. const composedEnhancer = finalCompose(...storeEnhancers);
  670. return (0, import_redux4.createStore)(rootReducer, preloadedState, composedEnhancer);
  671. }
  672. // src/createReducer.ts
  673. var import_immer3 = require("immer");
  674. // src/mapBuilders.ts
  675. function executeReducerBuilderCallback(builderCallback) {
  676. const actionsMap = {};
  677. const actionMatchers = [];
  678. let defaultCaseReducer;
  679. const builder = {
  680. addCase(typeOrActionCreator, reducer) {
  681. if (true) {
  682. if (actionMatchers.length > 0) {
  683. throw new Error(false ? _formatProdErrorMessage(26) : "`builder.addCase` should only be called before calling `builder.addMatcher`");
  684. }
  685. if (defaultCaseReducer) {
  686. throw new Error(false ? _formatProdErrorMessage2(27) : "`builder.addCase` should only be called before calling `builder.addDefaultCase`");
  687. }
  688. }
  689. const type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type;
  690. if (!type) {
  691. throw new Error(false ? _formatProdErrorMessage3(28) : "`builder.addCase` cannot be called with an empty action type");
  692. }
  693. if (type in actionsMap) {
  694. throw new Error(false ? _formatProdErrorMessage4(29) : `\`builder.addCase\` cannot be called with two reducers for the same action type '${type}'`);
  695. }
  696. actionsMap[type] = reducer;
  697. return builder;
  698. },
  699. addMatcher(matcher, reducer) {
  700. if (true) {
  701. if (defaultCaseReducer) {
  702. throw new Error(false ? _formatProdErrorMessage5(30) : "`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");
  703. }
  704. }
  705. actionMatchers.push({
  706. matcher,
  707. reducer
  708. });
  709. return builder;
  710. },
  711. addDefaultCase(reducer) {
  712. if (true) {
  713. if (defaultCaseReducer) {
  714. throw new Error(false ? _formatProdErrorMessage6(31) : "`builder.addDefaultCase` can only be called once");
  715. }
  716. }
  717. defaultCaseReducer = reducer;
  718. return builder;
  719. }
  720. };
  721. builderCallback(builder);
  722. return [actionsMap, actionMatchers, defaultCaseReducer];
  723. }
  724. // src/createReducer.ts
  725. function isStateFunction(x) {
  726. return typeof x === "function";
  727. }
  728. function createReducer(initialState, mapOrBuilderCallback) {
  729. if (true) {
  730. if (typeof mapOrBuilderCallback === "object") {
  731. throw new Error(false ? _formatProdErrorMessage(8) : "The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer");
  732. }
  733. }
  734. let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] = executeReducerBuilderCallback(mapOrBuilderCallback);
  735. let getInitialState;
  736. if (isStateFunction(initialState)) {
  737. getInitialState = () => freezeDraftable(initialState());
  738. } else {
  739. const frozenInitialState = freezeDraftable(initialState);
  740. getInitialState = () => frozenInitialState;
  741. }
  742. function reducer(state = getInitialState(), action) {
  743. let caseReducers = [actionsMap[action.type], ...finalActionMatchers.filter(({
  744. matcher
  745. }) => matcher(action)).map(({
  746. reducer: reducer2
  747. }) => reducer2)];
  748. if (caseReducers.filter((cr) => !!cr).length === 0) {
  749. caseReducers = [finalDefaultCaseReducer];
  750. }
  751. return caseReducers.reduce((previousState, caseReducer) => {
  752. if (caseReducer) {
  753. if ((0, import_immer3.isDraft)(previousState)) {
  754. const draft = previousState;
  755. const result = caseReducer(draft, action);
  756. if (result === void 0) {
  757. return previousState;
  758. }
  759. return result;
  760. } else if (!(0, import_immer3.isDraftable)(previousState)) {
  761. const result = caseReducer(previousState, action);
  762. if (result === void 0) {
  763. if (previousState === null) {
  764. return previousState;
  765. }
  766. throw new Error(false ? _formatProdErrorMessage2(9) : "A case reducer on a non-draftable value must not return undefined");
  767. }
  768. return result;
  769. } else {
  770. return (0, import_immer3.produce)(previousState, (draft) => {
  771. return caseReducer(draft, action);
  772. });
  773. }
  774. }
  775. return previousState;
  776. }, state);
  777. }
  778. reducer.getInitialState = getInitialState;
  779. return reducer;
  780. }
  781. // src/nanoid.ts
  782. var urlAlphabet = "ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW";
  783. var nanoid = (size = 21) => {
  784. let id = "";
  785. let i = size;
  786. while (i--) {
  787. id += urlAlphabet[Math.random() * 64 | 0];
  788. }
  789. return id;
  790. };
  791. // src/matchers.ts
  792. var matches = (matcher, action) => {
  793. if (hasMatchFunction(matcher)) {
  794. return matcher.match(action);
  795. } else {
  796. return matcher(action);
  797. }
  798. };
  799. function isAnyOf(...matchers) {
  800. return (action) => {
  801. return matchers.some((matcher) => matches(matcher, action));
  802. };
  803. }
  804. function isAllOf(...matchers) {
  805. return (action) => {
  806. return matchers.every((matcher) => matches(matcher, action));
  807. };
  808. }
  809. function hasExpectedRequestMetadata(action, validStatus) {
  810. if (!action || !action.meta)
  811. return false;
  812. const hasValidRequestId = typeof action.meta.requestId === "string";
  813. const hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;
  814. return hasValidRequestId && hasValidRequestStatus;
  815. }
  816. function isAsyncThunkArray(a) {
  817. return typeof a[0] === "function" && "pending" in a[0] && "fulfilled" in a[0] && "rejected" in a[0];
  818. }
  819. function isPending(...asyncThunks) {
  820. if (asyncThunks.length === 0) {
  821. return (action) => hasExpectedRequestMetadata(action, ["pending"]);
  822. }
  823. if (!isAsyncThunkArray(asyncThunks)) {
  824. return isPending()(asyncThunks[0]);
  825. }
  826. return (action) => {
  827. const matchers = asyncThunks.map((asyncThunk) => asyncThunk.pending);
  828. const combinedMatcher = isAnyOf(...matchers);
  829. return combinedMatcher(action);
  830. };
  831. }
  832. function isRejected(...asyncThunks) {
  833. if (asyncThunks.length === 0) {
  834. return (action) => hasExpectedRequestMetadata(action, ["rejected"]);
  835. }
  836. if (!isAsyncThunkArray(asyncThunks)) {
  837. return isRejected()(asyncThunks[0]);
  838. }
  839. return (action) => {
  840. const matchers = asyncThunks.map((asyncThunk) => asyncThunk.rejected);
  841. const combinedMatcher = isAnyOf(...matchers);
  842. return combinedMatcher(action);
  843. };
  844. }
  845. function isRejectedWithValue(...asyncThunks) {
  846. const hasFlag = (action) => {
  847. return action && action.meta && action.meta.rejectedWithValue;
  848. };
  849. if (asyncThunks.length === 0) {
  850. return (action) => {
  851. const combinedMatcher = isAllOf(isRejected(...asyncThunks), hasFlag);
  852. return combinedMatcher(action);
  853. };
  854. }
  855. if (!isAsyncThunkArray(asyncThunks)) {
  856. return isRejectedWithValue()(asyncThunks[0]);
  857. }
  858. return (action) => {
  859. const combinedMatcher = isAllOf(isRejected(...asyncThunks), hasFlag);
  860. return combinedMatcher(action);
  861. };
  862. }
  863. function isFulfilled(...asyncThunks) {
  864. if (asyncThunks.length === 0) {
  865. return (action) => hasExpectedRequestMetadata(action, ["fulfilled"]);
  866. }
  867. if (!isAsyncThunkArray(asyncThunks)) {
  868. return isFulfilled()(asyncThunks[0]);
  869. }
  870. return (action) => {
  871. const matchers = asyncThunks.map((asyncThunk) => asyncThunk.fulfilled);
  872. const combinedMatcher = isAnyOf(...matchers);
  873. return combinedMatcher(action);
  874. };
  875. }
  876. function isAsyncThunkAction(...asyncThunks) {
  877. if (asyncThunks.length === 0) {
  878. return (action) => hasExpectedRequestMetadata(action, ["pending", "fulfilled", "rejected"]);
  879. }
  880. if (!isAsyncThunkArray(asyncThunks)) {
  881. return isAsyncThunkAction()(asyncThunks[0]);
  882. }
  883. return (action) => {
  884. const matchers = [];
  885. for (const asyncThunk of asyncThunks) {
  886. matchers.push(asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled);
  887. }
  888. const combinedMatcher = isAnyOf(...matchers);
  889. return combinedMatcher(action);
  890. };
  891. }
  892. // src/createAsyncThunk.ts
  893. var commonProperties = ["name", "message", "stack", "code"];
  894. var RejectWithValue = class {
  895. constructor(payload, meta) {
  896. this.payload = payload;
  897. this.meta = meta;
  898. }
  899. /*
  900. type-only property to distinguish between RejectWithValue and FulfillWithMeta
  901. does not exist at runtime
  902. */
  903. _type;
  904. };
  905. var FulfillWithMeta = class {
  906. constructor(payload, meta) {
  907. this.payload = payload;
  908. this.meta = meta;
  909. }
  910. /*
  911. type-only property to distinguish between RejectWithValue and FulfillWithMeta
  912. does not exist at runtime
  913. */
  914. _type;
  915. };
  916. var miniSerializeError = (value) => {
  917. if (typeof value === "object" && value !== null) {
  918. const simpleError = {};
  919. for (const property of commonProperties) {
  920. if (typeof value[property] === "string") {
  921. simpleError[property] = value[property];
  922. }
  923. }
  924. return simpleError;
  925. }
  926. return {
  927. message: String(value)
  928. };
  929. };
  930. var createAsyncThunk = /* @__PURE__ */ (() => {
  931. function createAsyncThunk2(typePrefix, payloadCreator, options) {
  932. const fulfilled = createAction(typePrefix + "/fulfilled", (payload, requestId, arg, meta) => ({
  933. payload,
  934. meta: {
  935. ...meta || {},
  936. arg,
  937. requestId,
  938. requestStatus: "fulfilled"
  939. }
  940. }));
  941. const pending = createAction(typePrefix + "/pending", (requestId, arg, meta) => ({
  942. payload: void 0,
  943. meta: {
  944. ...meta || {},
  945. arg,
  946. requestId,
  947. requestStatus: "pending"
  948. }
  949. }));
  950. const rejected = createAction(typePrefix + "/rejected", (error, requestId, arg, payload, meta) => ({
  951. payload,
  952. error: (options && options.serializeError || miniSerializeError)(error || "Rejected"),
  953. meta: {
  954. ...meta || {},
  955. arg,
  956. requestId,
  957. rejectedWithValue: !!payload,
  958. requestStatus: "rejected",
  959. aborted: error?.name === "AbortError",
  960. condition: error?.name === "ConditionError"
  961. }
  962. }));
  963. function actionCreator(arg) {
  964. return (dispatch, getState, extra) => {
  965. const requestId = options?.idGenerator ? options.idGenerator(arg) : nanoid();
  966. const abortController = new AbortController();
  967. let abortReason;
  968. function abort(reason) {
  969. abortReason = reason;
  970. abortController.abort();
  971. }
  972. const promise = async function() {
  973. let finalAction;
  974. try {
  975. let conditionResult = options?.condition?.(arg, {
  976. getState,
  977. extra
  978. });
  979. if (isThenable(conditionResult)) {
  980. conditionResult = await conditionResult;
  981. }
  982. if (conditionResult === false || abortController.signal.aborted) {
  983. throw {
  984. name: "ConditionError",
  985. message: "Aborted due to condition callback returning false."
  986. };
  987. }
  988. const abortedPromise = new Promise((_, reject) => abortController.signal.addEventListener("abort", () => reject({
  989. name: "AbortError",
  990. message: abortReason || "Aborted"
  991. })));
  992. dispatch(pending(requestId, arg, options?.getPendingMeta?.({
  993. requestId,
  994. arg
  995. }, {
  996. getState,
  997. extra
  998. })));
  999. finalAction = await Promise.race([abortedPromise, Promise.resolve(payloadCreator(arg, {
  1000. dispatch,
  1001. getState,
  1002. extra,
  1003. requestId,
  1004. signal: abortController.signal,
  1005. abort,
  1006. rejectWithValue: (value, meta) => {
  1007. return new RejectWithValue(value, meta);
  1008. },
  1009. fulfillWithValue: (value, meta) => {
  1010. return new FulfillWithMeta(value, meta);
  1011. }
  1012. })).then((result) => {
  1013. if (result instanceof RejectWithValue) {
  1014. throw result;
  1015. }
  1016. if (result instanceof FulfillWithMeta) {
  1017. return fulfilled(result.payload, requestId, arg, result.meta);
  1018. }
  1019. return fulfilled(result, requestId, arg);
  1020. })]);
  1021. } catch (err) {
  1022. finalAction = err instanceof RejectWithValue ? rejected(null, requestId, arg, err.payload, err.meta) : rejected(err, requestId, arg);
  1023. }
  1024. const skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && finalAction.meta.condition;
  1025. if (!skipDispatch) {
  1026. dispatch(finalAction);
  1027. }
  1028. return finalAction;
  1029. }();
  1030. return Object.assign(promise, {
  1031. abort,
  1032. requestId,
  1033. arg,
  1034. unwrap() {
  1035. return promise.then(unwrapResult);
  1036. }
  1037. });
  1038. };
  1039. }
  1040. return Object.assign(actionCreator, {
  1041. pending,
  1042. rejected,
  1043. fulfilled,
  1044. settled: isAnyOf(rejected, fulfilled),
  1045. typePrefix
  1046. });
  1047. }
  1048. createAsyncThunk2.withTypes = () => createAsyncThunk2;
  1049. return createAsyncThunk2;
  1050. })();
  1051. function unwrapResult(action) {
  1052. if (action.meta && action.meta.rejectedWithValue) {
  1053. throw action.payload;
  1054. }
  1055. if (action.error) {
  1056. throw action.error;
  1057. }
  1058. return action.payload;
  1059. }
  1060. function isThenable(value) {
  1061. return value !== null && typeof value === "object" && typeof value.then === "function";
  1062. }
  1063. // src/createSlice.ts
  1064. var asyncThunkSymbol = Symbol.for("rtk-slice-createasyncthunk");
  1065. var asyncThunkCreator = {
  1066. [asyncThunkSymbol]: createAsyncThunk
  1067. };
  1068. var ReducerType = /* @__PURE__ */ ((ReducerType2) => {
  1069. ReducerType2["reducer"] = "reducer";
  1070. ReducerType2["reducerWithPrepare"] = "reducerWithPrepare";
  1071. ReducerType2["asyncThunk"] = "asyncThunk";
  1072. return ReducerType2;
  1073. })(ReducerType || {});
  1074. function getType(slice, actionKey) {
  1075. return `${slice}/${actionKey}`;
  1076. }
  1077. function buildCreateSlice({
  1078. creators
  1079. } = {}) {
  1080. const cAT = creators?.asyncThunk?.[asyncThunkSymbol];
  1081. return function createSlice2(options) {
  1082. const {
  1083. name,
  1084. reducerPath = name
  1085. } = options;
  1086. if (!name) {
  1087. throw new Error(false ? _formatProdErrorMessage(11) : "`name` is a required option for createSlice");
  1088. }
  1089. if (typeof process !== "undefined" && true) {
  1090. if (options.initialState === void 0) {
  1091. console.error("You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`");
  1092. }
  1093. }
  1094. const reducers = (typeof options.reducers === "function" ? options.reducers(buildReducerCreators()) : options.reducers) || {};
  1095. const reducerNames = Object.keys(reducers);
  1096. const context = {
  1097. sliceCaseReducersByName: {},
  1098. sliceCaseReducersByType: {},
  1099. actionCreators: {},
  1100. sliceMatchers: []
  1101. };
  1102. const contextMethods = {
  1103. addCase(typeOrActionCreator, reducer) {
  1104. const type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type;
  1105. if (!type) {
  1106. throw new Error(false ? _formatProdErrorMessage2(12) : "`context.addCase` cannot be called with an empty action type");
  1107. }
  1108. if (type in context.sliceCaseReducersByType) {
  1109. throw new Error(false ? _formatProdErrorMessage3(13) : "`context.addCase` cannot be called with two reducers for the same action type: " + type);
  1110. }
  1111. context.sliceCaseReducersByType[type] = reducer;
  1112. return contextMethods;
  1113. },
  1114. addMatcher(matcher, reducer) {
  1115. context.sliceMatchers.push({
  1116. matcher,
  1117. reducer
  1118. });
  1119. return contextMethods;
  1120. },
  1121. exposeAction(name2, actionCreator) {
  1122. context.actionCreators[name2] = actionCreator;
  1123. return contextMethods;
  1124. },
  1125. exposeCaseReducer(name2, reducer) {
  1126. context.sliceCaseReducersByName[name2] = reducer;
  1127. return contextMethods;
  1128. }
  1129. };
  1130. reducerNames.forEach((reducerName) => {
  1131. const reducerDefinition = reducers[reducerName];
  1132. const reducerDetails = {
  1133. reducerName,
  1134. type: getType(name, reducerName),
  1135. createNotation: typeof options.reducers === "function"
  1136. };
  1137. if (isAsyncThunkSliceReducerDefinition(reducerDefinition)) {
  1138. handleThunkCaseReducerDefinition(reducerDetails, reducerDefinition, contextMethods, cAT);
  1139. } else {
  1140. handleNormalReducerDefinition(reducerDetails, reducerDefinition, contextMethods);
  1141. }
  1142. });
  1143. function buildReducer() {
  1144. if (true) {
  1145. if (typeof options.extraReducers === "object") {
  1146. throw new Error(false ? _formatProdErrorMessage4(14) : "The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice");
  1147. }
  1148. }
  1149. const [extraReducers = {}, actionMatchers = [], defaultCaseReducer = void 0] = typeof options.extraReducers === "function" ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers];
  1150. const finalCaseReducers = {
  1151. ...extraReducers,
  1152. ...context.sliceCaseReducersByType
  1153. };
  1154. return createReducer(options.initialState, (builder) => {
  1155. for (let key in finalCaseReducers) {
  1156. builder.addCase(key, finalCaseReducers[key]);
  1157. }
  1158. for (let sM of context.sliceMatchers) {
  1159. builder.addMatcher(sM.matcher, sM.reducer);
  1160. }
  1161. for (let m of actionMatchers) {
  1162. builder.addMatcher(m.matcher, m.reducer);
  1163. }
  1164. if (defaultCaseReducer) {
  1165. builder.addDefaultCase(defaultCaseReducer);
  1166. }
  1167. });
  1168. }
  1169. const selectSelf = (state) => state;
  1170. const injectedSelectorCache = /* @__PURE__ */ new WeakMap();
  1171. let _reducer;
  1172. const slice = {
  1173. name,
  1174. reducerPath,
  1175. reducer(state, action) {
  1176. if (!_reducer)
  1177. _reducer = buildReducer();
  1178. return _reducer(state, action);
  1179. },
  1180. actions: context.actionCreators,
  1181. caseReducers: context.sliceCaseReducersByName,
  1182. getInitialState() {
  1183. if (!_reducer)
  1184. _reducer = buildReducer();
  1185. return _reducer.getInitialState();
  1186. },
  1187. getSelectors(selectState = selectSelf) {
  1188. const selectorCache = emplace(injectedSelectorCache, this, {
  1189. insert: () => /* @__PURE__ */ new WeakMap()
  1190. });
  1191. return emplace(selectorCache, selectState, {
  1192. insert: () => {
  1193. const map = {};
  1194. for (const [name2, selector] of Object.entries(options.selectors ?? {})) {
  1195. map[name2] = wrapSelector(this, selector, selectState, this !== slice);
  1196. }
  1197. return map;
  1198. }
  1199. });
  1200. },
  1201. selectSlice(state) {
  1202. let sliceState = state[this.reducerPath];
  1203. if (typeof sliceState === "undefined") {
  1204. if (this !== slice) {
  1205. sliceState = this.getInitialState();
  1206. } else if (true) {
  1207. throw new Error(false ? _formatProdErrorMessage5(15) : "selectSlice returned undefined for an uninjected slice reducer");
  1208. }
  1209. }
  1210. return sliceState;
  1211. },
  1212. get selectors() {
  1213. return this.getSelectors(this.selectSlice);
  1214. },
  1215. injectInto(injectable, {
  1216. reducerPath: pathOpt,
  1217. ...config
  1218. } = {}) {
  1219. const reducerPath2 = pathOpt ?? this.reducerPath;
  1220. injectable.inject({
  1221. reducerPath: reducerPath2,
  1222. reducer: this.reducer
  1223. }, config);
  1224. return {
  1225. ...this,
  1226. reducerPath: reducerPath2
  1227. };
  1228. }
  1229. };
  1230. return slice;
  1231. };
  1232. }
  1233. function wrapSelector(slice, selector, selectState, injected) {
  1234. function wrapper(rootState, ...args) {
  1235. let sliceState = selectState.call(slice, rootState);
  1236. if (typeof sliceState === "undefined") {
  1237. if (injected) {
  1238. sliceState = slice.getInitialState();
  1239. } else if (true) {
  1240. throw new Error(false ? _formatProdErrorMessage6(16) : "selectState returned undefined for an uninjected slice reducer");
  1241. }
  1242. }
  1243. return selector(sliceState, ...args);
  1244. }
  1245. wrapper.unwrapped = selector;
  1246. return wrapper;
  1247. }
  1248. var createSlice = buildCreateSlice();
  1249. function buildReducerCreators() {
  1250. function asyncThunk(payloadCreator, config) {
  1251. return {
  1252. _reducerDefinitionType: "asyncThunk" /* asyncThunk */,
  1253. payloadCreator,
  1254. ...config
  1255. };
  1256. }
  1257. asyncThunk.withTypes = () => asyncThunk;
  1258. return {
  1259. reducer(caseReducer) {
  1260. return Object.assign({
  1261. // hack so the wrapping function has the same name as the original
  1262. // we need to create a wrapper so the `reducerDefinitionType` is not assigned to the original
  1263. [caseReducer.name](...args) {
  1264. return caseReducer(...args);
  1265. }
  1266. }[caseReducer.name], {
  1267. _reducerDefinitionType: "reducer" /* reducer */
  1268. });
  1269. },
  1270. preparedReducer(prepare, reducer) {
  1271. return {
  1272. _reducerDefinitionType: "reducerWithPrepare" /* reducerWithPrepare */,
  1273. prepare,
  1274. reducer
  1275. };
  1276. },
  1277. asyncThunk
  1278. };
  1279. }
  1280. function handleNormalReducerDefinition({
  1281. type,
  1282. reducerName,
  1283. createNotation
  1284. }, maybeReducerWithPrepare, context) {
  1285. let caseReducer;
  1286. let prepareCallback;
  1287. if ("reducer" in maybeReducerWithPrepare) {
  1288. if (createNotation && !isCaseReducerWithPrepareDefinition(maybeReducerWithPrepare)) {
  1289. throw new Error(false ? _formatProdErrorMessage7(17) : "Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.");
  1290. }
  1291. caseReducer = maybeReducerWithPrepare.reducer;
  1292. prepareCallback = maybeReducerWithPrepare.prepare;
  1293. } else {
  1294. caseReducer = maybeReducerWithPrepare;
  1295. }
  1296. context.addCase(type, caseReducer).exposeCaseReducer(reducerName, caseReducer).exposeAction(reducerName, prepareCallback ? createAction(type, prepareCallback) : createAction(type));
  1297. }
  1298. function isAsyncThunkSliceReducerDefinition(reducerDefinition) {
  1299. return reducerDefinition._reducerDefinitionType === "asyncThunk" /* asyncThunk */;
  1300. }
  1301. function isCaseReducerWithPrepareDefinition(reducerDefinition) {
  1302. return reducerDefinition._reducerDefinitionType === "reducerWithPrepare" /* reducerWithPrepare */;
  1303. }
  1304. function handleThunkCaseReducerDefinition({
  1305. type,
  1306. reducerName
  1307. }, reducerDefinition, context, cAT) {
  1308. if (!cAT) {
  1309. throw new Error(false ? _formatProdErrorMessage8(18) : "Cannot use `create.asyncThunk` in the built-in `createSlice`. Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.");
  1310. }
  1311. const {
  1312. payloadCreator,
  1313. fulfilled,
  1314. pending,
  1315. rejected,
  1316. settled,
  1317. options
  1318. } = reducerDefinition;
  1319. const thunk = cAT(type, payloadCreator, options);
  1320. context.exposeAction(reducerName, thunk);
  1321. if (fulfilled) {
  1322. context.addCase(thunk.fulfilled, fulfilled);
  1323. }
  1324. if (pending) {
  1325. context.addCase(thunk.pending, pending);
  1326. }
  1327. if (rejected) {
  1328. context.addCase(thunk.rejected, rejected);
  1329. }
  1330. if (settled) {
  1331. context.addMatcher(thunk.settled, settled);
  1332. }
  1333. context.exposeCaseReducer(reducerName, {
  1334. fulfilled: fulfilled || noop,
  1335. pending: pending || noop,
  1336. rejected: rejected || noop,
  1337. settled: settled || noop
  1338. });
  1339. }
  1340. function noop() {
  1341. }
  1342. // src/entities/entity_state.ts
  1343. function getInitialEntityState() {
  1344. return {
  1345. ids: [],
  1346. entities: {}
  1347. };
  1348. }
  1349. function createInitialStateFactory() {
  1350. function getInitialState(additionalState = {}) {
  1351. return Object.assign(getInitialEntityState(), additionalState);
  1352. }
  1353. return {
  1354. getInitialState
  1355. };
  1356. }
  1357. // src/entities/state_selectors.ts
  1358. function createSelectorsFactory() {
  1359. function getSelectors(selectState, options = {}) {
  1360. const {
  1361. createSelector: createSelector2 = createDraftSafeSelector
  1362. } = options;
  1363. const selectIds = (state) => state.ids;
  1364. const selectEntities = (state) => state.entities;
  1365. const selectAll = createSelector2(selectIds, selectEntities, (ids, entities) => ids.map((id) => entities[id]));
  1366. const selectId = (_, id) => id;
  1367. const selectById = (entities, id) => entities[id];
  1368. const selectTotal = createSelector2(selectIds, (ids) => ids.length);
  1369. if (!selectState) {
  1370. return {
  1371. selectIds,
  1372. selectEntities,
  1373. selectAll,
  1374. selectTotal,
  1375. selectById: createSelector2(selectEntities, selectId, selectById)
  1376. };
  1377. }
  1378. const selectGlobalizedEntities = createSelector2(selectState, selectEntities);
  1379. return {
  1380. selectIds: createSelector2(selectState, selectIds),
  1381. selectEntities: selectGlobalizedEntities,
  1382. selectAll: createSelector2(selectState, selectAll),
  1383. selectTotal: createSelector2(selectState, selectTotal),
  1384. selectById: createSelector2(selectGlobalizedEntities, selectId, selectById)
  1385. };
  1386. }
  1387. return {
  1388. getSelectors
  1389. };
  1390. }
  1391. // src/entities/state_adapter.ts
  1392. var import_immer4 = require("immer");
  1393. var isDraftTyped = import_immer4.isDraft;
  1394. function createSingleArgumentStateOperator(mutator) {
  1395. const operator = createStateOperator((_, state) => mutator(state));
  1396. return function operation(state) {
  1397. return operator(state, void 0);
  1398. };
  1399. }
  1400. function createStateOperator(mutator) {
  1401. return function operation(state, arg) {
  1402. function isPayloadActionArgument(arg2) {
  1403. return isFSA(arg2);
  1404. }
  1405. const runMutator = (draft) => {
  1406. if (isPayloadActionArgument(arg)) {
  1407. mutator(arg.payload, draft);
  1408. } else {
  1409. mutator(arg, draft);
  1410. }
  1411. };
  1412. if (isDraftTyped(state)) {
  1413. runMutator(state);
  1414. return state;
  1415. }
  1416. return (0, import_immer4.produce)(state, runMutator);
  1417. };
  1418. }
  1419. // src/entities/utils.ts
  1420. function selectIdValue(entity, selectId) {
  1421. const key = selectId(entity);
  1422. if (key === void 0) {
  1423. console.warn("The entity passed to the `selectId` implementation returned undefined.", "You should probably provide your own `selectId` implementation.", "The entity that was passed:", entity, "The `selectId` implementation:", selectId.toString());
  1424. }
  1425. return key;
  1426. }
  1427. function ensureEntitiesArray(entities) {
  1428. if (!Array.isArray(entities)) {
  1429. entities = Object.values(entities);
  1430. }
  1431. return entities;
  1432. }
  1433. function splitAddedUpdatedEntities(newEntities, selectId, state) {
  1434. newEntities = ensureEntitiesArray(newEntities);
  1435. const added = [];
  1436. const updated = [];
  1437. for (const entity of newEntities) {
  1438. const id = selectIdValue(entity, selectId);
  1439. if (id in state.entities) {
  1440. updated.push({
  1441. id,
  1442. changes: entity
  1443. });
  1444. } else {
  1445. added.push(entity);
  1446. }
  1447. }
  1448. return [added, updated];
  1449. }
  1450. // src/entities/unsorted_state_adapter.ts
  1451. function createUnsortedStateAdapter(selectId) {
  1452. function addOneMutably(entity, state) {
  1453. const key = selectIdValue(entity, selectId);
  1454. if (key in state.entities) {
  1455. return;
  1456. }
  1457. state.ids.push(key);
  1458. state.entities[key] = entity;
  1459. }
  1460. function addManyMutably(newEntities, state) {
  1461. newEntities = ensureEntitiesArray(newEntities);
  1462. for (const entity of newEntities) {
  1463. addOneMutably(entity, state);
  1464. }
  1465. }
  1466. function setOneMutably(entity, state) {
  1467. const key = selectIdValue(entity, selectId);
  1468. if (!(key in state.entities)) {
  1469. state.ids.push(key);
  1470. }
  1471. state.entities[key] = entity;
  1472. }
  1473. function setManyMutably(newEntities, state) {
  1474. newEntities = ensureEntitiesArray(newEntities);
  1475. for (const entity of newEntities) {
  1476. setOneMutably(entity, state);
  1477. }
  1478. }
  1479. function setAllMutably(newEntities, state) {
  1480. newEntities = ensureEntitiesArray(newEntities);
  1481. state.ids = [];
  1482. state.entities = {};
  1483. addManyMutably(newEntities, state);
  1484. }
  1485. function removeOneMutably(key, state) {
  1486. return removeManyMutably([key], state);
  1487. }
  1488. function removeManyMutably(keys, state) {
  1489. let didMutate = false;
  1490. keys.forEach((key) => {
  1491. if (key in state.entities) {
  1492. delete state.entities[key];
  1493. didMutate = true;
  1494. }
  1495. });
  1496. if (didMutate) {
  1497. state.ids = state.ids.filter((id) => id in state.entities);
  1498. }
  1499. }
  1500. function removeAllMutably(state) {
  1501. Object.assign(state, {
  1502. ids: [],
  1503. entities: {}
  1504. });
  1505. }
  1506. function takeNewKey(keys, update, state) {
  1507. const original3 = state.entities[update.id];
  1508. if (original3 === void 0) {
  1509. return false;
  1510. }
  1511. const updated = Object.assign({}, original3, update.changes);
  1512. const newKey = selectIdValue(updated, selectId);
  1513. const hasNewKey = newKey !== update.id;
  1514. if (hasNewKey) {
  1515. keys[update.id] = newKey;
  1516. delete state.entities[update.id];
  1517. }
  1518. state.entities[newKey] = updated;
  1519. return hasNewKey;
  1520. }
  1521. function updateOneMutably(update, state) {
  1522. return updateManyMutably([update], state);
  1523. }
  1524. function updateManyMutably(updates, state) {
  1525. const newKeys = {};
  1526. const updatesPerEntity = {};
  1527. updates.forEach((update) => {
  1528. if (update.id in state.entities) {
  1529. updatesPerEntity[update.id] = {
  1530. id: update.id,
  1531. // Spreads ignore falsy values, so this works even if there isn't
  1532. // an existing update already at this key
  1533. changes: {
  1534. ...updatesPerEntity[update.id] ? updatesPerEntity[update.id].changes : null,
  1535. ...update.changes
  1536. }
  1537. };
  1538. }
  1539. });
  1540. updates = Object.values(updatesPerEntity);
  1541. const didMutateEntities = updates.length > 0;
  1542. if (didMutateEntities) {
  1543. const didMutateIds = updates.filter((update) => takeNewKey(newKeys, update, state)).length > 0;
  1544. if (didMutateIds) {
  1545. state.ids = Object.values(state.entities).map((e) => selectIdValue(e, selectId));
  1546. }
  1547. }
  1548. }
  1549. function upsertOneMutably(entity, state) {
  1550. return upsertManyMutably([entity], state);
  1551. }
  1552. function upsertManyMutably(newEntities, state) {
  1553. const [added, updated] = splitAddedUpdatedEntities(newEntities, selectId, state);
  1554. updateManyMutably(updated, state);
  1555. addManyMutably(added, state);
  1556. }
  1557. return {
  1558. removeAll: createSingleArgumentStateOperator(removeAllMutably),
  1559. addOne: createStateOperator(addOneMutably),
  1560. addMany: createStateOperator(addManyMutably),
  1561. setOne: createStateOperator(setOneMutably),
  1562. setMany: createStateOperator(setManyMutably),
  1563. setAll: createStateOperator(setAllMutably),
  1564. updateOne: createStateOperator(updateOneMutably),
  1565. updateMany: createStateOperator(updateManyMutably),
  1566. upsertOne: createStateOperator(upsertOneMutably),
  1567. upsertMany: createStateOperator(upsertManyMutably),
  1568. removeOne: createStateOperator(removeOneMutably),
  1569. removeMany: createStateOperator(removeManyMutably)
  1570. };
  1571. }
  1572. // src/entities/sorted_state_adapter.ts
  1573. function createSortedStateAdapter(selectId, sort) {
  1574. const {
  1575. removeOne,
  1576. removeMany,
  1577. removeAll
  1578. } = createUnsortedStateAdapter(selectId);
  1579. function addOneMutably(entity, state) {
  1580. return addManyMutably([entity], state);
  1581. }
  1582. function addManyMutably(newEntities, state) {
  1583. newEntities = ensureEntitiesArray(newEntities);
  1584. const models = newEntities.filter((model) => !(selectIdValue(model, selectId) in state.entities));
  1585. if (models.length !== 0) {
  1586. merge(models, state);
  1587. }
  1588. }
  1589. function setOneMutably(entity, state) {
  1590. return setManyMutably([entity], state);
  1591. }
  1592. function setManyMutably(newEntities, state) {
  1593. newEntities = ensureEntitiesArray(newEntities);
  1594. if (newEntities.length !== 0) {
  1595. merge(newEntities, state);
  1596. }
  1597. }
  1598. function setAllMutably(newEntities, state) {
  1599. newEntities = ensureEntitiesArray(newEntities);
  1600. state.entities = {};
  1601. state.ids = [];
  1602. addManyMutably(newEntities, state);
  1603. }
  1604. function updateOneMutably(update, state) {
  1605. return updateManyMutably([update], state);
  1606. }
  1607. function updateManyMutably(updates, state) {
  1608. let appliedUpdates = false;
  1609. for (let update of updates) {
  1610. const entity = state.entities[update.id];
  1611. if (!entity) {
  1612. continue;
  1613. }
  1614. appliedUpdates = true;
  1615. Object.assign(entity, update.changes);
  1616. const newId = selectId(entity);
  1617. if (update.id !== newId) {
  1618. delete state.entities[update.id];
  1619. state.entities[newId] = entity;
  1620. }
  1621. }
  1622. if (appliedUpdates) {
  1623. resortEntities(state);
  1624. }
  1625. }
  1626. function upsertOneMutably(entity, state) {
  1627. return upsertManyMutably([entity], state);
  1628. }
  1629. function upsertManyMutably(newEntities, state) {
  1630. const [added, updated] = splitAddedUpdatedEntities(newEntities, selectId, state);
  1631. updateManyMutably(updated, state);
  1632. addManyMutably(added, state);
  1633. }
  1634. function areArraysEqual(a, b) {
  1635. if (a.length !== b.length) {
  1636. return false;
  1637. }
  1638. for (let i = 0; i < a.length && i < b.length; i++) {
  1639. if (a[i] === b[i]) {
  1640. continue;
  1641. }
  1642. return false;
  1643. }
  1644. return true;
  1645. }
  1646. function merge(models, state) {
  1647. models.forEach((model) => {
  1648. state.entities[selectId(model)] = model;
  1649. });
  1650. resortEntities(state);
  1651. }
  1652. function resortEntities(state) {
  1653. const allEntities = Object.values(state.entities);
  1654. allEntities.sort(sort);
  1655. const newSortedIds = allEntities.map(selectId);
  1656. const {
  1657. ids
  1658. } = state;
  1659. if (!areArraysEqual(ids, newSortedIds)) {
  1660. state.ids = newSortedIds;
  1661. }
  1662. }
  1663. return {
  1664. removeOne,
  1665. removeMany,
  1666. removeAll,
  1667. addOne: createStateOperator(addOneMutably),
  1668. updateOne: createStateOperator(updateOneMutably),
  1669. upsertOne: createStateOperator(upsertOneMutably),
  1670. setOne: createStateOperator(setOneMutably),
  1671. setMany: createStateOperator(setManyMutably),
  1672. setAll: createStateOperator(setAllMutably),
  1673. addMany: createStateOperator(addManyMutably),
  1674. updateMany: createStateOperator(updateManyMutably),
  1675. upsertMany: createStateOperator(upsertManyMutably)
  1676. };
  1677. }
  1678. // src/entities/create_adapter.ts
  1679. function createEntityAdapter(options = {}) {
  1680. const {
  1681. selectId,
  1682. sortComparer
  1683. } = {
  1684. sortComparer: false,
  1685. selectId: (instance) => instance.id,
  1686. ...options
  1687. };
  1688. const stateFactory = createInitialStateFactory();
  1689. const selectorsFactory = createSelectorsFactory();
  1690. const stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);
  1691. return {
  1692. selectId,
  1693. sortComparer,
  1694. ...stateFactory,
  1695. ...selectorsFactory,
  1696. ...stateAdapter
  1697. };
  1698. }
  1699. // src/listenerMiddleware/index.ts
  1700. var import_redux5 = require("redux");
  1701. // src/listenerMiddleware/utils.ts
  1702. var assertFunction = (func, expected) => {
  1703. if (typeof func !== "function") {
  1704. throw new Error(false ? _formatProdErrorMessage(32) : `${expected} is not a function`);
  1705. }
  1706. };
  1707. var noop2 = () => {
  1708. };
  1709. var catchRejection = (promise, onError = noop2) => {
  1710. promise.catch(onError);
  1711. return promise;
  1712. };
  1713. var addAbortSignalListener = (abortSignal, callback) => {
  1714. abortSignal.addEventListener("abort", callback, {
  1715. once: true
  1716. });
  1717. return () => abortSignal.removeEventListener("abort", callback);
  1718. };
  1719. var abortControllerWithReason = (abortController, reason) => {
  1720. const signal = abortController.signal;
  1721. if (signal.aborted) {
  1722. return;
  1723. }
  1724. if (!("reason" in signal)) {
  1725. Object.defineProperty(signal, "reason", {
  1726. enumerable: true,
  1727. value: reason,
  1728. configurable: true,
  1729. writable: true
  1730. });
  1731. }
  1732. ;
  1733. abortController.abort(reason);
  1734. };
  1735. // src/listenerMiddleware/exceptions.ts
  1736. var task = "task";
  1737. var listener = "listener";
  1738. var completed = "completed";
  1739. var cancelled = "cancelled";
  1740. var taskCancelled = `task-${cancelled}`;
  1741. var taskCompleted = `task-${completed}`;
  1742. var listenerCancelled = `${listener}-${cancelled}`;
  1743. var listenerCompleted = `${listener}-${completed}`;
  1744. var TaskAbortError = class {
  1745. constructor(code) {
  1746. this.code = code;
  1747. this.message = `${task} ${cancelled} (reason: ${code})`;
  1748. }
  1749. name = "TaskAbortError";
  1750. message;
  1751. };
  1752. // src/listenerMiddleware/task.ts
  1753. var validateActive = (signal) => {
  1754. if (signal.aborted) {
  1755. const {
  1756. reason
  1757. } = signal;
  1758. throw new TaskAbortError(reason);
  1759. }
  1760. };
  1761. function raceWithSignal(signal, promise) {
  1762. let cleanup = noop2;
  1763. return new Promise((resolve, reject) => {
  1764. const notifyRejection = () => reject(new TaskAbortError(signal.reason));
  1765. if (signal.aborted) {
  1766. notifyRejection();
  1767. return;
  1768. }
  1769. cleanup = addAbortSignalListener(signal, notifyRejection);
  1770. promise.finally(() => cleanup()).then(resolve, reject);
  1771. }).finally(() => {
  1772. cleanup = noop2;
  1773. });
  1774. }
  1775. var runTask = async (task2, cleanUp) => {
  1776. try {
  1777. await Promise.resolve();
  1778. const value = await task2();
  1779. return {
  1780. status: "ok",
  1781. value
  1782. };
  1783. } catch (error) {
  1784. return {
  1785. status: error instanceof TaskAbortError ? "cancelled" : "rejected",
  1786. error
  1787. };
  1788. } finally {
  1789. cleanUp?.();
  1790. }
  1791. };
  1792. var createPause = (signal) => {
  1793. return (promise) => {
  1794. return catchRejection(raceWithSignal(signal, promise).then((output) => {
  1795. validateActive(signal);
  1796. return output;
  1797. }));
  1798. };
  1799. };
  1800. var createDelay = (signal) => {
  1801. const pause = createPause(signal);
  1802. return (timeoutMs) => {
  1803. return pause(new Promise((resolve) => setTimeout(resolve, timeoutMs)));
  1804. };
  1805. };
  1806. // src/listenerMiddleware/index.ts
  1807. var {
  1808. assign
  1809. } = Object;
  1810. var INTERNAL_NIL_TOKEN = {};
  1811. var alm = "listenerMiddleware";
  1812. var createFork = (parentAbortSignal, parentBlockingPromises) => {
  1813. const linkControllers = (controller) => addAbortSignalListener(parentAbortSignal, () => abortControllerWithReason(controller, parentAbortSignal.reason));
  1814. return (taskExecutor, opts) => {
  1815. assertFunction(taskExecutor, "taskExecutor");
  1816. const childAbortController = new AbortController();
  1817. linkControllers(childAbortController);
  1818. const result = runTask(async () => {
  1819. validateActive(parentAbortSignal);
  1820. validateActive(childAbortController.signal);
  1821. const result2 = await taskExecutor({
  1822. pause: createPause(childAbortController.signal),
  1823. delay: createDelay(childAbortController.signal),
  1824. signal: childAbortController.signal
  1825. });
  1826. validateActive(childAbortController.signal);
  1827. return result2;
  1828. }, () => abortControllerWithReason(childAbortController, taskCompleted));
  1829. if (opts?.autoJoin) {
  1830. parentBlockingPromises.push(result);
  1831. }
  1832. return {
  1833. result: createPause(parentAbortSignal)(result),
  1834. cancel() {
  1835. abortControllerWithReason(childAbortController, taskCancelled);
  1836. }
  1837. };
  1838. };
  1839. };
  1840. var createTakePattern = (startListening, signal) => {
  1841. const take = async (predicate, timeout) => {
  1842. validateActive(signal);
  1843. let unsubscribe = () => {
  1844. };
  1845. const tuplePromise = new Promise((resolve, reject) => {
  1846. let stopListening = startListening({
  1847. predicate,
  1848. effect: (action, listenerApi) => {
  1849. listenerApi.unsubscribe();
  1850. resolve([action, listenerApi.getState(), listenerApi.getOriginalState()]);
  1851. }
  1852. });
  1853. unsubscribe = () => {
  1854. stopListening();
  1855. reject();
  1856. };
  1857. });
  1858. const promises = [tuplePromise];
  1859. if (timeout != null) {
  1860. promises.push(new Promise((resolve) => setTimeout(resolve, timeout, null)));
  1861. }
  1862. try {
  1863. const output = await raceWithSignal(signal, Promise.race(promises));
  1864. validateActive(signal);
  1865. return output;
  1866. } finally {
  1867. unsubscribe();
  1868. }
  1869. };
  1870. return (predicate, timeout) => catchRejection(take(predicate, timeout));
  1871. };
  1872. var getListenerEntryPropsFrom = (options) => {
  1873. let {
  1874. type,
  1875. actionCreator,
  1876. matcher,
  1877. predicate,
  1878. effect
  1879. } = options;
  1880. if (type) {
  1881. predicate = createAction(type).match;
  1882. } else if (actionCreator) {
  1883. type = actionCreator.type;
  1884. predicate = actionCreator.match;
  1885. } else if (matcher) {
  1886. predicate = matcher;
  1887. } else if (predicate) {
  1888. } else {
  1889. throw new Error(false ? _formatProdErrorMessage(21) : "Creating or removing a listener requires one of the known fields for matching an action");
  1890. }
  1891. assertFunction(effect, "options.listener");
  1892. return {
  1893. predicate,
  1894. type,
  1895. effect
  1896. };
  1897. };
  1898. var createListenerEntry = (options) => {
  1899. const {
  1900. type,
  1901. predicate,
  1902. effect
  1903. } = getListenerEntryPropsFrom(options);
  1904. const id = nanoid();
  1905. const entry = {
  1906. id,
  1907. effect,
  1908. type,
  1909. predicate,
  1910. pending: /* @__PURE__ */ new Set(),
  1911. unsubscribe: () => {
  1912. throw new Error(false ? _formatProdErrorMessage2(22) : "Unsubscribe not initialized");
  1913. }
  1914. };
  1915. return entry;
  1916. };
  1917. var cancelActiveListeners = (entry) => {
  1918. entry.pending.forEach((controller) => {
  1919. abortControllerWithReason(controller, listenerCancelled);
  1920. });
  1921. };
  1922. var createClearListenerMiddleware = (listenerMap) => {
  1923. return () => {
  1924. listenerMap.forEach(cancelActiveListeners);
  1925. listenerMap.clear();
  1926. };
  1927. };
  1928. var safelyNotifyError = (errorHandler, errorToNotify, errorInfo) => {
  1929. try {
  1930. errorHandler(errorToNotify, errorInfo);
  1931. } catch (errorHandlerError) {
  1932. setTimeout(() => {
  1933. throw errorHandlerError;
  1934. }, 0);
  1935. }
  1936. };
  1937. var addListener = createAction(`${alm}/add`);
  1938. var clearAllListeners = createAction(`${alm}/removeAll`);
  1939. var removeListener = createAction(`${alm}/remove`);
  1940. var defaultErrorHandler = (...args) => {
  1941. console.error(`${alm}/error`, ...args);
  1942. };
  1943. function createListenerMiddleware(middlewareOptions = {}) {
  1944. const listenerMap = /* @__PURE__ */ new Map();
  1945. const {
  1946. extra,
  1947. onError = defaultErrorHandler
  1948. } = middlewareOptions;
  1949. assertFunction(onError, "onError");
  1950. const insertEntry = (entry) => {
  1951. entry.unsubscribe = () => listenerMap.delete(entry.id);
  1952. listenerMap.set(entry.id, entry);
  1953. return (cancelOptions) => {
  1954. entry.unsubscribe();
  1955. if (cancelOptions?.cancelActive) {
  1956. cancelActiveListeners(entry);
  1957. }
  1958. };
  1959. };
  1960. const startListening = (options) => {
  1961. let entry = find(Array.from(listenerMap.values()), (existingEntry) => existingEntry.effect === options.effect);
  1962. if (!entry) {
  1963. entry = createListenerEntry(options);
  1964. }
  1965. return insertEntry(entry);
  1966. };
  1967. const stopListening = (options) => {
  1968. const {
  1969. type,
  1970. effect,
  1971. predicate
  1972. } = getListenerEntryPropsFrom(options);
  1973. const entry = find(Array.from(listenerMap.values()), (entry2) => {
  1974. const matchPredicateOrType = typeof type === "string" ? entry2.type === type : entry2.predicate === predicate;
  1975. return matchPredicateOrType && entry2.effect === effect;
  1976. });
  1977. if (entry) {
  1978. entry.unsubscribe();
  1979. if (options.cancelActive) {
  1980. cancelActiveListeners(entry);
  1981. }
  1982. }
  1983. return !!entry;
  1984. };
  1985. const notifyListener = async (entry, action, api, getOriginalState) => {
  1986. const internalTaskController = new AbortController();
  1987. const take = createTakePattern(startListening, internalTaskController.signal);
  1988. const autoJoinPromises = [];
  1989. try {
  1990. entry.pending.add(internalTaskController);
  1991. await Promise.resolve(entry.effect(
  1992. action,
  1993. // Use assign() rather than ... to avoid extra helper functions added to bundle
  1994. assign({}, api, {
  1995. getOriginalState,
  1996. condition: (predicate, timeout) => take(predicate, timeout).then(Boolean),
  1997. take,
  1998. delay: createDelay(internalTaskController.signal),
  1999. pause: createPause(internalTaskController.signal),
  2000. extra,
  2001. signal: internalTaskController.signal,
  2002. fork: createFork(internalTaskController.signal, autoJoinPromises),
  2003. unsubscribe: entry.unsubscribe,
  2004. subscribe: () => {
  2005. listenerMap.set(entry.id, entry);
  2006. },
  2007. cancelActiveListeners: () => {
  2008. entry.pending.forEach((controller, _, set) => {
  2009. if (controller !== internalTaskController) {
  2010. abortControllerWithReason(controller, listenerCancelled);
  2011. set.delete(controller);
  2012. }
  2013. });
  2014. },
  2015. cancel: () => {
  2016. abortControllerWithReason(internalTaskController, listenerCancelled);
  2017. entry.pending.delete(internalTaskController);
  2018. },
  2019. throwIfCancelled: () => {
  2020. validateActive(internalTaskController.signal);
  2021. }
  2022. })
  2023. ));
  2024. } catch (listenerError) {
  2025. if (!(listenerError instanceof TaskAbortError)) {
  2026. safelyNotifyError(onError, listenerError, {
  2027. raisedBy: "effect"
  2028. });
  2029. }
  2030. } finally {
  2031. await Promise.allSettled(autoJoinPromises);
  2032. abortControllerWithReason(internalTaskController, listenerCompleted);
  2033. entry.pending.delete(internalTaskController);
  2034. }
  2035. };
  2036. const clearListenerMiddleware = createClearListenerMiddleware(listenerMap);
  2037. const middleware = (api) => (next) => (action) => {
  2038. if (!(0, import_redux5.isAction)(action)) {
  2039. return next(action);
  2040. }
  2041. if (addListener.match(action)) {
  2042. return startListening(action.payload);
  2043. }
  2044. if (clearAllListeners.match(action)) {
  2045. clearListenerMiddleware();
  2046. return;
  2047. }
  2048. if (removeListener.match(action)) {
  2049. return stopListening(action.payload);
  2050. }
  2051. let originalState = api.getState();
  2052. const getOriginalState = () => {
  2053. if (originalState === INTERNAL_NIL_TOKEN) {
  2054. throw new Error(false ? _formatProdErrorMessage3(23) : `${alm}: getOriginalState can only be called synchronously`);
  2055. }
  2056. return originalState;
  2057. };
  2058. let result;
  2059. try {
  2060. result = next(action);
  2061. if (listenerMap.size > 0) {
  2062. let currentState = api.getState();
  2063. const listenerEntries = Array.from(listenerMap.values());
  2064. for (let entry of listenerEntries) {
  2065. let runListener = false;
  2066. try {
  2067. runListener = entry.predicate(action, currentState, originalState);
  2068. } catch (predicateError) {
  2069. runListener = false;
  2070. safelyNotifyError(onError, predicateError, {
  2071. raisedBy: "predicate"
  2072. });
  2073. }
  2074. if (!runListener) {
  2075. continue;
  2076. }
  2077. notifyListener(entry, action, api, getOriginalState);
  2078. }
  2079. }
  2080. } finally {
  2081. originalState = INTERNAL_NIL_TOKEN;
  2082. }
  2083. return result;
  2084. };
  2085. return {
  2086. middleware,
  2087. startListening,
  2088. stopListening,
  2089. clearListeners: clearListenerMiddleware
  2090. };
  2091. }
  2092. // src/dynamicMiddleware/index.ts
  2093. var import_redux6 = require("redux");
  2094. var createMiddlewareEntry = (middleware) => ({
  2095. id: nanoid(),
  2096. middleware,
  2097. applied: /* @__PURE__ */ new Map()
  2098. });
  2099. var matchInstance = (instanceId) => (action) => action?.meta?.instanceId === instanceId;
  2100. var createDynamicMiddleware = () => {
  2101. const instanceId = nanoid();
  2102. const middlewareMap = /* @__PURE__ */ new Map();
  2103. const withMiddleware = Object.assign(createAction("dynamicMiddleware/add", (...middlewares) => ({
  2104. payload: middlewares,
  2105. meta: {
  2106. instanceId
  2107. }
  2108. })), {
  2109. withTypes: () => withMiddleware
  2110. });
  2111. const addMiddleware = Object.assign(function addMiddleware2(...middlewares) {
  2112. middlewares.forEach((middleware2) => {
  2113. let entry = find(Array.from(middlewareMap.values()), (entry2) => entry2.middleware === middleware2);
  2114. if (!entry) {
  2115. entry = createMiddlewareEntry(middleware2);
  2116. }
  2117. middlewareMap.set(entry.id, entry);
  2118. });
  2119. }, {
  2120. withTypes: () => addMiddleware
  2121. });
  2122. const getFinalMiddleware = (api) => {
  2123. const appliedMiddleware = Array.from(middlewareMap.values()).map((entry) => emplace(entry.applied, api, {
  2124. insert: () => entry.middleware(api)
  2125. }));
  2126. return (0, import_redux6.compose)(...appliedMiddleware);
  2127. };
  2128. const isWithMiddleware = isAllOf(withMiddleware, matchInstance(instanceId));
  2129. const middleware = (api) => (next) => (action) => {
  2130. if (isWithMiddleware(action)) {
  2131. addMiddleware(...action.payload);
  2132. return api.dispatch;
  2133. }
  2134. return getFinalMiddleware(api)(next)(action);
  2135. };
  2136. return {
  2137. middleware,
  2138. addMiddleware,
  2139. withMiddleware,
  2140. instanceId
  2141. };
  2142. };
  2143. // src/combineSlices.ts
  2144. var import_redux7 = require("redux");
  2145. var isSliceLike = (maybeSliceLike) => "reducerPath" in maybeSliceLike && typeof maybeSliceLike.reducerPath === "string";
  2146. var getReducers = (slices) => slices.flatMap((sliceOrMap) => isSliceLike(sliceOrMap) ? [[sliceOrMap.reducerPath, sliceOrMap.reducer]] : Object.entries(sliceOrMap));
  2147. var ORIGINAL_STATE = Symbol.for("rtk-state-proxy-original");
  2148. var isStateProxy = (value) => !!value && !!value[ORIGINAL_STATE];
  2149. var stateProxyMap = /* @__PURE__ */ new WeakMap();
  2150. var createStateProxy = (state, reducerMap) => emplace(stateProxyMap, state, {
  2151. insert: () => new Proxy(state, {
  2152. get: (target, prop, receiver) => {
  2153. if (prop === ORIGINAL_STATE)
  2154. return target;
  2155. const result = Reflect.get(target, prop, receiver);
  2156. if (typeof result === "undefined") {
  2157. const reducer = reducerMap[prop.toString()];
  2158. if (reducer) {
  2159. const reducerResult = reducer(void 0, {
  2160. type: nanoid()
  2161. });
  2162. if (typeof reducerResult === "undefined") {
  2163. throw new Error(false ? _formatProdErrorMessage(24) : `The slice reducer for key "${prop.toString()}" returned undefined when called for selector(). If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.`);
  2164. }
  2165. return reducerResult;
  2166. }
  2167. }
  2168. return result;
  2169. }
  2170. })
  2171. });
  2172. var original = (state) => {
  2173. if (!isStateProxy(state)) {
  2174. throw new Error(false ? _formatProdErrorMessage2(25) : "original must be used on state Proxy");
  2175. }
  2176. return state[ORIGINAL_STATE];
  2177. };
  2178. function combineSlices(...slices) {
  2179. const reducerMap = Object.fromEntries(getReducers(slices));
  2180. const getReducer = () => (0, import_redux7.combineReducers)(reducerMap);
  2181. let reducer = getReducer();
  2182. function combinedReducer(state, action) {
  2183. return reducer(state, action);
  2184. }
  2185. combinedReducer.withLazyLoadedSlices = () => combinedReducer;
  2186. const inject = (slice, config = {}) => {
  2187. const {
  2188. reducerPath,
  2189. reducer: reducerToInject
  2190. } = slice;
  2191. const currentReducer = reducerMap[reducerPath];
  2192. if (!config.overrideExisting && currentReducer && currentReducer !== reducerToInject) {
  2193. if (typeof process !== "undefined" && true) {
  2194. console.error(`called \`inject\` to override already-existing reducer ${reducerPath} without specifying \`overrideExisting: true\``);
  2195. }
  2196. return combinedReducer;
  2197. }
  2198. reducerMap[reducerPath] = reducerToInject;
  2199. reducer = getReducer();
  2200. return combinedReducer;
  2201. };
  2202. const selector = Object.assign(function makeSelector(selectorFn, selectState) {
  2203. return function selector2(state, ...args) {
  2204. return selectorFn(createStateProxy(selectState ? selectState(state, ...args) : state, reducerMap), ...args);
  2205. };
  2206. }, {
  2207. original
  2208. });
  2209. return Object.assign(combinedReducer, {
  2210. inject,
  2211. selector
  2212. });
  2213. }
  2214. // src/formatProdErrorMessage.ts
  2215. function formatProdErrorMessage(code) {
  2216. return `Minified Redux Toolkit error #${code}; visit https://redux-toolkit.js.org/Errors?code=${code} for the full message or use the non-minified dev environment for full errors. `;
  2217. }
  2218. //# sourceMappingURL=redux-toolkit.development.cjs.map