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