Version 1.0.2 mit node_modules Verzeichnis

This commit is contained in:
ISA
2024-10-02 07:58:24 +02:00
parent f353a06b1b
commit 62b6e55a0a
68228 changed files with 4548477 additions and 651 deletions

21
node_modules/@reduxjs/toolkit/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Mark Erikson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

110
node_modules/@reduxjs/toolkit/README.md generated vendored Normal file
View File

@@ -0,0 +1,110 @@
# Redux Toolkit
![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/reduxjs/redux-toolkit/tests.yml?style=flat-square)
[![npm version](https://img.shields.io/npm/v/@reduxjs/toolkit.svg?style=flat-square)](https://www.npmjs.com/package/@reduxjs/toolkit)
[![npm downloads](https://img.shields.io/npm/dm/@reduxjs/toolkit.svg?style=flat-square&label=RTK+downloads)](https://www.npmjs.com/package/@reduxjs/toolkit)
**The official, opinionated, batteries-included toolset for efficient Redux development**
## Installation
### Create a React Redux App
The recommended way to start new apps with React and Redux Toolkit is by using [our official Redux Toolkit + TS template for Vite](https://github.com/reduxjs/redux-templates), or by creating a new Next.js project using [Next's `with-redux` template](https://github.com/vercel/next.js/tree/canary/examples/with-redux).
Both of these already have Redux Toolkit and React-Redux configured appropriately for that build tool, and come with a small example app that demonstrates how to use several of Redux Toolkit's features.
```bash
# Vite with our Redux+TS template
# (using the `degit` tool to clone and extract the template)
npx degit reduxjs/redux-templates/packages/vite-template-redux my-app
# Next.js using the `with-redux` template
npx create-next-app --example with-redux my-app
```
We do not currently have official React Native templates, but recommend these templates for standard React Native and for Expo:
- https://github.com/rahsheen/react-native-template-redux-typescript
- https://github.com/rahsheen/expo-template-redux-typescript
### An Existing App
Redux Toolkit is available as a package on NPM for use with a module bundler or in a Node application:
```bash
# NPM
npm install @reduxjs/toolkit
# Yarn
yarn add @reduxjs/toolkit
```
The package includes a precompiled ESM build that can be used as a [`<script type="module">` tag](https://unpkg.com/@reduxjs/toolkit/dist/redux-toolkit.browser.mjs) directly in the browser.
## Documentation
The Redux Toolkit docs are available at **https://redux-toolkit.js.org**, including API references and usage guides for all of the APIs included in Redux Toolkit.
The Redux core docs at https://redux.js.org includes the full Redux tutorials, as well usage guides on general Redux patterns.
## Purpose
The **Redux Toolkit** package is intended to be the standard way to write Redux logic. It was originally created to help address three common concerns about Redux:
- "Configuring a Redux store is too complicated"
- "I have to add a lot of packages to get Redux to do anything useful"
- "Redux requires too much boilerplate code"
We can't solve every use case, but in the spirit of [`create-react-app`](https://github.com/facebook/create-react-app), we can try to provide some tools that abstract over the setup process and handle the most common use cases, as well as include some useful utilities that will let the user simplify their application code.
Because of that, this package is deliberately limited in scope. It does _not_ address concepts like "reusable encapsulated Redux modules", folder or file structures, managing entity relationships in the store, and so on.
Redux Toolkit also includes a powerful data fetching and caching capability that we've dubbed "RTK Query". It's included in the package as a separate set of entry points. It's optional, but can eliminate the need to hand-write data fetching logic yourself.
## What's Included
Redux Toolkit includes these APIs:
- `configureStore()`: wraps `createStore` to provide simplified configuration options and good defaults. It can automatically combine your slice reducers, add whatever Redux middleware you supply, includes `redux-thunk` by default, and enables use of the Redux DevTools Extension.
- `createReducer()`: lets you supply a lookup table of action types to case reducer functions, rather than writing switch statements. In addition, it automatically uses the [`immer` library](https://github.com/mweststrate/immer) to let you write simpler immutable updates with normal mutative code, like `state.todos[3].completed = true`.
- `createAction()`: generates an action creator function for the given action type string. The function itself has `toString()` defined, so that it can be used in place of the type constant.
- `createSlice()`: combines `createReducer()` + `createAction()`. Accepts an object of reducer functions, a slice name, and an initial state value, and automatically generates a slice reducer with corresponding action creators and action types.
- `combineSlices()`: combines multiple slices into a single reducer, and allows "lazy loading" of slices after initialisation.
- `createListenerMiddleware()`: lets you define "listener" entries that contain an "effect" callback with additional logic, and a way to specify when that callback should run based on dispatched actions or state changes. A lightweight alternative to Redux async middleware like sagas and observables.
- `createAsyncThunk()`: accepts an action type string and a function that returns a promise, and generates a thunk that dispatches `pending/resolved/rejected` action types based on that promise
- `createEntityAdapter()`: generates a set of reusable reducers and selectors to manage normalized data in the store
- The `createSelector()` utility from the [Reselect](https://github.com/reduxjs/reselect) library, re-exported for ease of use.
For details, see [the Redux Toolkit API Reference section in the docs](https://redux-toolkit.js.org/api/configureStore).
## RTK Query
**RTK Query** is provided as an optional addon within the `@reduxjs/toolkit` package. It is purpose-built to solve the use case of data fetching and caching, supplying a compact, but powerful toolset to define an API interface layer for your app. It is intended to simplify common cases for loading data in a web application, eliminating the need to hand-write data fetching & caching logic yourself.
RTK Query is built on top of the Redux Toolkit core for its implementation, using [Redux](https://redux.js.org/) internally for its architecture. Although knowledge of Redux and RTK are not required to use RTK Query, you should explore all of the additional global store management capabilities they provide, as well as installing the [Redux DevTools browser extension](https://github.com/reduxjs/redux-devtools), which works flawlessly with RTK Query to traverse and replay a timeline of your request & cache behavior.
RTK Query is included within the installation of the core Redux Toolkit package. It is available via either of the two entry points below:
```ts no-transpile
import { createApi } from '@reduxjs/toolkit/query'
/* React-specific entry point that automatically generates
hooks corresponding to the defined endpoints */
import { createApi } from '@reduxjs/toolkit/query/react'
```
### What's included
RTK Query includes these APIs:
- `createApi()`: The core of RTK Query's functionality. It allows you to define a set of endpoints describe how to retrieve data from a series of endpoints, including configuration of how to fetch and transform that data. In most cases, you should use this once per app, with "one API slice per base URL" as a rule of thumb.
- `fetchBaseQuery()`: A small wrapper around fetch that aims to simplify requests. Intended as the recommended baseQuery to be used in createApi for the majority of users.
- `<ApiProvider />`: Can be used as a Provider if you do not already have a Redux store.
- `setupListeners()`: A utility used to enable refetchOnMount and refetchOnReconnect behaviors.
See the [**RTK Query Overview**](https://redux-toolkit.js.org/rtk-query/overview) page for more details on what RTK Query is, what problems it solves, and how to use it.
## Contributing
Please refer to our [contributing guide](/CONTRIBUTING.md) to learn about our development process, how to propose bugfixes and improvements, and how to build and test your changes to Redux Toolkit.

6
node_modules/@reduxjs/toolkit/dist/cjs/index.js generated vendored Normal file
View File

@@ -0,0 +1,6 @@
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./redux-toolkit.production.min.cjs')
} else {
module.exports = require('./redux-toolkit.development.cjs')
}

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

2608
node_modules/@reduxjs/toolkit/dist/index.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,6 @@
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./rtk-query.production.min.cjs')
} else {
module.exports = require('./rtk-query.development.cjs')
}

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

2119
node_modules/@reduxjs/toolkit/dist/query/index.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,6 @@
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./rtk-query-react.production.min.cjs')
} else {
module.exports = require('./rtk-query-react.development.cjs')
}

View File

@@ -0,0 +1,651 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/query/react/index.ts
var react_exports = {};
__export(react_exports, {
ApiProvider: () => ApiProvider,
UNINITIALIZED_VALUE: () => UNINITIALIZED_VALUE,
createApi: () => createApi,
reactHooksModule: () => reactHooksModule,
reactHooksModuleName: () => reactHooksModuleName
});
module.exports = __toCommonJS(react_exports);
var import_query3 = require("@reduxjs/toolkit/query");
// src/query/react/module.ts
var import_toolkit3 = require("@reduxjs/toolkit");
var import_react_redux3 = require("react-redux");
var import_reselect = require("reselect");
// src/query/endpointDefinitions.ts
function isQueryDefinition(e) {
return e.type === "query" /* query */;
}
function isMutationDefinition(e) {
return e.type === "mutation" /* mutation */;
}
// src/query/tsHelpers.ts
function safeAssign(target, ...args) {
return Object.assign(target, ...args);
}
// src/query/utils/capitalize.ts
function capitalize(str) {
return str.replace(str[0], str[0].toUpperCase());
}
// src/query/core/rtkImports.ts
var import_toolkit = require("@reduxjs/toolkit");
// src/query/utils/countObjectKeys.ts
function countObjectKeys(obj) {
let count = 0;
for (const _key in obj) {
count++;
}
return count;
}
// src/query/react/buildHooks.ts
var import_toolkit2 = require("@reduxjs/toolkit");
var import_query = require("@reduxjs/toolkit/query");
var import_react3 = require("react");
var import_react_redux2 = require("react-redux");
// src/query/defaultSerializeQueryArgs.ts
var cache = WeakMap ? /* @__PURE__ */ new WeakMap() : void 0;
var defaultSerializeQueryArgs = ({
endpointName,
queryArgs
}) => {
let serialized = "";
const cached = cache?.get(queryArgs);
if (typeof cached === "string") {
serialized = cached;
} else {
const stringified = JSON.stringify(queryArgs, (key, value) => {
value = typeof value === "bigint" ? {
$bigint: value.toString()
} : value;
value = (0, import_toolkit.isPlainObject)(value) ? Object.keys(value).sort().reduce((acc, key2) => {
acc[key2] = value[key2];
return acc;
}, {}) : value;
return value;
});
if ((0, import_toolkit.isPlainObject)(queryArgs)) {
cache?.set(queryArgs, stringified);
}
serialized = stringified;
}
return `${endpointName}(${serialized})`;
};
// src/query/react/constants.ts
var UNINITIALIZED_VALUE = Symbol();
// src/query/react/useSerializedStableValue.ts
var import_react = require("react");
function useStableQueryArgs(queryArgs, serialize, endpointDefinition, endpointName) {
const incoming = (0, import_react.useMemo)(() => ({
queryArgs,
serialized: typeof queryArgs == "object" ? serialize({
queryArgs,
endpointDefinition,
endpointName
}) : queryArgs
}), [queryArgs, serialize, endpointDefinition, endpointName]);
const cache2 = (0, import_react.useRef)(incoming);
(0, import_react.useEffect)(() => {
if (cache2.current.serialized !== incoming.serialized) {
cache2.current = incoming;
}
}, [incoming]);
return cache2.current.serialized === incoming.serialized ? cache2.current.queryArgs : queryArgs;
}
// src/query/react/useShallowStableValue.ts
var import_react2 = require("react");
var import_react_redux = require("react-redux");
function useShallowStableValue(value) {
const cache2 = (0, import_react2.useRef)(value);
(0, import_react2.useEffect)(() => {
if (!(0, import_react_redux.shallowEqual)(cache2.current, value)) {
cache2.current = value;
}
}, [value]);
return (0, import_react_redux.shallowEqual)(cache2.current, value) ? cache2.current : value;
}
// src/query/react/buildHooks.ts
var canUseDOM = () => !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined");
var isDOM = /* @__PURE__ */ canUseDOM();
var isRunningInReactNative = () => typeof navigator !== "undefined" && navigator.product === "ReactNative";
var isReactNative = /* @__PURE__ */ isRunningInReactNative();
var getUseIsomorphicLayoutEffect = () => isDOM || isReactNative ? import_react3.useLayoutEffect : import_react3.useEffect;
var useIsomorphicLayoutEffect = /* @__PURE__ */ getUseIsomorphicLayoutEffect();
var noPendingQueryStateSelector = (selected) => {
if (selected.isUninitialized) {
return {
...selected,
isUninitialized: false,
isFetching: true,
isLoading: selected.data !== void 0 ? false : true,
status: import_query.QueryStatus.pending
};
}
return selected;
};
function buildHooks({
api,
moduleOptions: {
batch,
hooks: {
useDispatch,
useSelector,
useStore
},
unstable__sideEffectsInRender,
createSelector: createSelector2
},
serializeQueryArgs,
context
}) {
const usePossiblyImmediateEffect = unstable__sideEffectsInRender ? (cb) => cb() : import_react3.useEffect;
return {
buildQueryHooks,
buildMutationHook,
usePrefetch
};
function queryStatePreSelector(currentState, lastResult, queryArgs) {
if (lastResult?.endpointName && currentState.isUninitialized) {
const {
endpointName
} = lastResult;
const endpointDefinition = context.endpointDefinitions[endpointName];
if (serializeQueryArgs({
queryArgs: lastResult.originalArgs,
endpointDefinition,
endpointName
}) === serializeQueryArgs({
queryArgs,
endpointDefinition,
endpointName
})) lastResult = void 0;
}
let data = currentState.isSuccess ? currentState.data : lastResult?.data;
if (data === void 0) data = currentState.data;
const hasData = data !== void 0;
const isFetching = currentState.isLoading;
const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;
const isSuccess = currentState.isSuccess || isFetching && hasData;
return {
...currentState,
data,
currentData: currentState.data,
isFetching,
isLoading,
isSuccess
};
}
function usePrefetch(endpointName, defaultOptions) {
const dispatch = useDispatch();
const stableDefaultOptions = useShallowStableValue(defaultOptions);
return (0, import_react3.useCallback)((arg, options) => dispatch(api.util.prefetch(endpointName, arg, {
...stableDefaultOptions,
...options
})), [endpointName, dispatch, stableDefaultOptions]);
}
function buildQueryHooks(name) {
const useQuerySubscription = (arg, {
refetchOnReconnect,
refetchOnFocus,
refetchOnMountOrArgChange,
skip = false,
pollingInterval = 0,
skipPollingIfUnfocused = false
} = {}) => {
const {
initiate
} = api.endpoints[name];
const dispatch = useDispatch();
const subscriptionSelectorsRef = (0, import_react3.useRef)(void 0);
if (!subscriptionSelectorsRef.current) {
const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());
if (true) {
if (typeof returnedValue !== "object" || typeof returnedValue?.type === "string") {
throw new Error(false ? _formatProdErrorMessage(37) : `Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
You must add the middleware for RTK-Query to function correctly!`);
}
}
subscriptionSelectorsRef.current = returnedValue;
}
const stableArg = useStableQueryArgs(
skip ? import_query.skipToken : arg,
// Even if the user provided a per-endpoint `serializeQueryArgs` with
// a consistent return value, _here_ we want to use the default behavior
// so we can tell if _anything_ actually changed. Otherwise, we can end up
// with a case where the query args did change but the serialization doesn't,
// and then we never try to initiate a refetch.
defaultSerializeQueryArgs,
context.endpointDefinitions[name],
name
);
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval,
skipPollingIfUnfocused
});
const lastRenderHadSubscription = (0, import_react3.useRef)(false);
const promiseRef = (0, import_react3.useRef)(void 0);
let {
queryCacheKey,
requestId
} = promiseRef.current || {};
let currentRenderHasSubscription = false;
if (queryCacheKey && requestId) {
currentRenderHasSubscription = subscriptionSelectorsRef.current.isRequestSubscribed(queryCacheKey, requestId);
}
const subscriptionRemoved = !currentRenderHasSubscription && lastRenderHadSubscription.current;
usePossiblyImmediateEffect(() => {
lastRenderHadSubscription.current = currentRenderHasSubscription;
});
usePossiblyImmediateEffect(() => {
if (subscriptionRemoved) {
promiseRef.current = void 0;
}
}, [subscriptionRemoved]);
usePossiblyImmediateEffect(() => {
const lastPromise = promiseRef.current;
if (typeof process !== "undefined" && false) {
console.log(subscriptionRemoved);
}
if (stableArg === import_query.skipToken) {
lastPromise?.unsubscribe();
promiseRef.current = void 0;
return;
}
const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions;
if (!lastPromise || lastPromise.arg !== stableArg) {
lastPromise?.unsubscribe();
const promise = dispatch(initiate(stableArg, {
subscriptionOptions: stableSubscriptionOptions,
forceRefetch: refetchOnMountOrArgChange
}));
promiseRef.current = promise;
} else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [dispatch, initiate, refetchOnMountOrArgChange, stableArg, stableSubscriptionOptions, subscriptionRemoved]);
(0, import_react3.useEffect)(() => {
return () => {
promiseRef.current?.unsubscribe();
promiseRef.current = void 0;
};
}, []);
return (0, import_react3.useMemo)(() => ({
/**
* A method to manually refetch data for the query
*/
refetch: () => {
if (!promiseRef.current) throw new Error(false ? _formatProdErrorMessage2(38) : "Cannot refetch a query that has not been started yet.");
return promiseRef.current?.refetch();
}
}), []);
};
const useLazyQuerySubscription = ({
refetchOnReconnect,
refetchOnFocus,
pollingInterval = 0,
skipPollingIfUnfocused = false
} = {}) => {
const {
initiate
} = api.endpoints[name];
const dispatch = useDispatch();
const [arg, setArg] = (0, import_react3.useState)(UNINITIALIZED_VALUE);
const promiseRef = (0, import_react3.useRef)(void 0);
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval,
skipPollingIfUnfocused
});
usePossiblyImmediateEffect(() => {
const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions;
if (stableSubscriptionOptions !== lastSubscriptionOptions) {
promiseRef.current?.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [stableSubscriptionOptions]);
const subscriptionOptionsRef = (0, import_react3.useRef)(stableSubscriptionOptions);
usePossiblyImmediateEffect(() => {
subscriptionOptionsRef.current = stableSubscriptionOptions;
}, [stableSubscriptionOptions]);
const trigger = (0, import_react3.useCallback)(function(arg2, preferCacheValue = false) {
let promise;
batch(() => {
promiseRef.current?.unsubscribe();
promiseRef.current = promise = dispatch(initiate(arg2, {
subscriptionOptions: subscriptionOptionsRef.current,
forceRefetch: !preferCacheValue
}));
setArg(arg2);
});
return promise;
}, [dispatch, initiate]);
(0, import_react3.useEffect)(() => {
return () => {
promiseRef?.current?.unsubscribe();
};
}, []);
(0, import_react3.useEffect)(() => {
if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
trigger(arg, true);
}
}, [arg, trigger]);
return (0, import_react3.useMemo)(() => [trigger, arg], [trigger, arg]);
};
const useQueryState = (arg, {
skip = false,
selectFromResult
} = {}) => {
const {
select
} = api.endpoints[name];
const stableArg = useStableQueryArgs(skip ? import_query.skipToken : arg, serializeQueryArgs, context.endpointDefinitions[name], name);
const lastValue = (0, import_react3.useRef)(void 0);
const selectDefaultResult = (0, import_react3.useMemo)(() => createSelector2([select(stableArg), (_, lastResult) => lastResult, (_) => stableArg], queryStatePreSelector, {
memoizeOptions: {
resultEqualityCheck: import_react_redux2.shallowEqual
}
}), [select, stableArg]);
const querySelector = (0, import_react3.useMemo)(() => selectFromResult ? createSelector2([selectDefaultResult], selectFromResult, {
devModeChecks: {
identityFunctionCheck: "never"
}
}) : selectDefaultResult, [selectDefaultResult, selectFromResult]);
const currentState = useSelector((state) => querySelector(state, lastValue.current), import_react_redux2.shallowEqual);
const store = useStore();
const newLastValue = selectDefaultResult(store.getState(), lastValue.current);
useIsomorphicLayoutEffect(() => {
lastValue.current = newLastValue;
}, [newLastValue]);
return currentState;
};
return {
useQueryState,
useQuerySubscription,
useLazyQuerySubscription,
useLazyQuery(options) {
const [trigger, arg] = useLazyQuerySubscription(options);
const queryStateResults = useQueryState(arg, {
...options,
skip: arg === UNINITIALIZED_VALUE
});
const info = (0, import_react3.useMemo)(() => ({
lastArg: arg
}), [arg]);
return (0, import_react3.useMemo)(() => [trigger, queryStateResults, info], [trigger, queryStateResults, info]);
},
useQuery(arg, options) {
const querySubscriptionResults = useQuerySubscription(arg, options);
const queryStateResults = useQueryState(arg, {
selectFromResult: arg === import_query.skipToken || options?.skip ? void 0 : noPendingQueryStateSelector,
...options
});
const {
data,
status,
isLoading,
isSuccess,
isError,
error
} = queryStateResults;
(0, import_react3.useDebugValue)({
data,
status,
isLoading,
isSuccess,
isError,
error
});
return (0, import_react3.useMemo)(() => ({
...queryStateResults,
...querySubscriptionResults
}), [queryStateResults, querySubscriptionResults]);
}
};
}
function buildMutationHook(name) {
return ({
selectFromResult,
fixedCacheKey
} = {}) => {
const {
select,
initiate
} = api.endpoints[name];
const dispatch = useDispatch();
const [promise, setPromise] = (0, import_react3.useState)();
(0, import_react3.useEffect)(() => () => {
if (!promise?.arg.fixedCacheKey) {
promise?.reset();
}
}, [promise]);
const triggerMutation = (0, import_react3.useCallback)(function(arg) {
const promise2 = dispatch(initiate(arg, {
fixedCacheKey
}));
setPromise(promise2);
return promise2;
}, [dispatch, initiate, fixedCacheKey]);
const {
requestId
} = promise || {};
const selectDefaultResult = (0, import_react3.useMemo)(() => select({
fixedCacheKey,
requestId: promise?.requestId
}), [fixedCacheKey, promise, select]);
const mutationSelector = (0, import_react3.useMemo)(() => selectFromResult ? createSelector2([selectDefaultResult], selectFromResult) : selectDefaultResult, [selectFromResult, selectDefaultResult]);
const currentState = useSelector(mutationSelector, import_react_redux2.shallowEqual);
const originalArgs = fixedCacheKey == null ? promise?.arg.originalArgs : void 0;
const reset = (0, import_react3.useCallback)(() => {
batch(() => {
if (promise) {
setPromise(void 0);
}
if (fixedCacheKey) {
dispatch(api.internalActions.removeMutationResult({
requestId,
fixedCacheKey
}));
}
});
}, [dispatch, fixedCacheKey, promise, requestId]);
const {
endpointName,
data,
status,
isLoading,
isSuccess,
isError,
error
} = currentState;
(0, import_react3.useDebugValue)({
endpointName,
data,
status,
isLoading,
isSuccess,
isError,
error
});
const finalState = (0, import_react3.useMemo)(() => ({
...currentState,
originalArgs,
reset
}), [currentState, originalArgs, reset]);
return (0, import_react3.useMemo)(() => [triggerMutation, finalState], [triggerMutation, finalState]);
};
}
}
// src/query/react/module.ts
var reactHooksModuleName = /* @__PURE__ */ Symbol();
var reactHooksModule = ({
batch = import_react_redux3.batch,
hooks = {
useDispatch: import_react_redux3.useDispatch,
useSelector: import_react_redux3.useSelector,
useStore: import_react_redux3.useStore
},
createSelector: createSelector2 = import_reselect.createSelector,
unstable__sideEffectsInRender = false,
...rest
} = {}) => {
if (true) {
const hookNames = ["useDispatch", "useSelector", "useStore"];
let warned = false;
for (const hookName of hookNames) {
if (countObjectKeys(rest) > 0) {
if (rest[hookName]) {
if (!warned) {
console.warn("As of RTK 2.0, the hooks now need to be specified as one object, provided under a `hooks` key:\n`reactHooksModule({ hooks: { useDispatch, useSelector, useStore } })`");
warned = true;
}
}
hooks[hookName] = rest[hookName];
}
if (typeof hooks[hookName] !== "function") {
throw new Error(false ? _formatProdErrorMessage3(36) : `When using custom hooks for context, all ${hookNames.length} hooks need to be provided: ${hookNames.join(", ")}.
Hook ${hookName} was either not provided or not a function.`);
}
}
}
return {
name: reactHooksModuleName,
init(api, {
serializeQueryArgs
}, context) {
const anyApi = api;
const {
buildQueryHooks,
buildMutationHook,
usePrefetch
} = buildHooks({
api,
moduleOptions: {
batch,
hooks,
unstable__sideEffectsInRender,
createSelector: createSelector2
},
serializeQueryArgs,
context
});
safeAssign(anyApi, {
usePrefetch
});
safeAssign(context, {
batch
});
return {
injectEndpoint(endpointName, definition) {
if (isQueryDefinition(definition)) {
const {
useQuery,
useLazyQuery,
useLazyQuerySubscription,
useQueryState,
useQuerySubscription
} = buildQueryHooks(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useQuery,
useLazyQuery,
useLazyQuerySubscription,
useQueryState,
useQuerySubscription
});
api[`use${capitalize(endpointName)}Query`] = useQuery;
api[`useLazy${capitalize(endpointName)}Query`] = useLazyQuery;
} else if (isMutationDefinition(definition)) {
const useMutation = buildMutationHook(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useMutation
});
api[`use${capitalize(endpointName)}Mutation`] = useMutation;
}
}
};
}
};
};
// src/query/react/index.ts
__reExport(react_exports, require("@reduxjs/toolkit/query"), module.exports);
// src/query/react/ApiProvider.tsx
var import_toolkit4 = require("@reduxjs/toolkit");
var import_react4 = require("react");
var import_react5 = require("react");
var React = __toESM(require("react"));
var import_react_redux4 = require("react-redux");
var import_query2 = require("@reduxjs/toolkit/query");
function ApiProvider(props) {
const context = props.context || import_react_redux4.ReactReduxContext;
const existingContext = (0, import_react4.useContext)(context);
if (existingContext) {
throw new Error(false ? _formatProdErrorMessage4(35) : "Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.");
}
const [store] = React.useState(() => (0, import_toolkit4.configureStore)({
reducer: {
[props.api.reducerPath]: props.api.reducer
},
middleware: (gDM) => gDM().concat(props.api.middleware)
}));
(0, import_react5.useEffect)(() => props.setupListeners === false ? void 0 : (0, import_query2.setupListeners)(store.dispatch, props.setupListeners), [props.setupListeners, store.dispatch]);
return /* @__PURE__ */ React.createElement(import_react_redux4.Provider, { store, context }, props.children);
}
// src/query/react/index.ts
var createApi = /* @__PURE__ */ (0, import_query3.buildCreateApi)((0, import_query3.coreModule)(), reactHooksModule());
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
ApiProvider,
UNINITIALIZED_VALUE,
createApi,
reactHooksModule,
reactHooksModuleName,
...require("@reduxjs/toolkit/query")
});
//# sourceMappingURL=rtk-query-react.development.cjs.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,501 @@
import * as _reduxjs_toolkit_query from '@reduxjs/toolkit/query';
import { QueryDefinition, MutationDefinition, QueryArgFrom, SkipToken, BaseQueryFn, SubscriptionOptions, QueryActionCreatorResult, TSHelpersNoInfer, TSHelpersId, TSHelpersOverride, QueryStatus, MutationResultSelectorResult, MutationActionCreatorResult, QuerySubState, ResultTypeFrom, EndpointDefinitions, DefinitionType, QueryKeys, PrefetchOptions, Module, Api, setupListeners } from '@reduxjs/toolkit/query';
export * from '@reduxjs/toolkit/query';
import * as react_redux from 'react-redux';
import { ReactReduxContextValue } from 'react-redux';
import { createSelector } from 'reselect';
import * as React from 'react';
import { Context } from 'react';
export declare const UNINITIALIZED_VALUE: unique symbol;
type UninitializedValue = typeof UNINITIALIZED_VALUE;
type QueryHooks<Definition extends QueryDefinition<any, any, any, any, any>> = {
useQuery: UseQuery<Definition>;
useLazyQuery: UseLazyQuery<Definition>;
useQuerySubscription: UseQuerySubscription<Definition>;
useLazyQuerySubscription: UseLazyQuerySubscription<Definition>;
useQueryState: UseQueryState<Definition>;
};
type MutationHooks<Definition extends MutationDefinition<any, any, any, any, any>> = {
useMutation: UseMutation<Definition>;
};
/**
* A React hook that automatically triggers fetches of data from an endpoint, 'subscribes' the component to the cached data, and reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.
*
* The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already, and the hook will return the data for that query arg once it's available.
*
* This hook combines the functionality of both [`useQueryState`](#usequerystate) and [`useQuerySubscription`](#usequerysubscription) together, and is intended to be used in the majority of situations.
*
* #### Features
*
* - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
* - Returns the latest request status and cached data from the Redux store
* - Re-renders as the request status changes and data becomes available
*/
type UseQuery<D extends QueryDefinition<any, any, any, any>> = <R extends Record<string, any> = UseQueryStateDefaultResult<D>>(arg: QueryArgFrom<D> | SkipToken, options?: UseQuerySubscriptionOptions & UseQueryStateOptions<D, R>) => UseQueryHookResult<D, R>;
type TypedUseQuery<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
type UseQueryHookResult<D extends QueryDefinition<any, any, any, any>, R = UseQueryStateDefaultResult<D>> = UseQueryStateResult<D, R> & UseQuerySubscriptionResult<D>;
/**
* Helper type to manually type the result
* of the `useQuery` hook in userland code.
*/
type TypedUseQueryHookResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery, R> & TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery>;
type UseQuerySubscriptionOptions = SubscriptionOptions & {
/**
* Prevents a query from automatically running.
*
* @remarks
* When `skip` is true (or `skipToken` is passed in as `arg`):
*
* - **If the query has cached data:**
* * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed
* * The query will have a status of `uninitialized`
* * If `skip: false` is set after the initial load, the cached result will be used
* - **If the query does not have cached data:**
* * The query will have a status of `uninitialized`
* * The query will not exist in the state when viewed with the dev tools
* * The query will not automatically fetch on mount
* * The query will not automatically run when additional components with the same query are added that do run
*
* @example
* ```tsx
* // codeblock-meta no-transpile title="Skip example"
* const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
* const { data, error, status } = useGetPokemonByNameQuery(name, {
* skip,
* });
*
* return (
* <div>
* {name} - {status}
* </div>
* );
* };
* ```
*/
skip?: boolean;
/**
* Defaults to `false`. This setting allows you to control whether if a cached result is already available, RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.
* - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
* - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.
* - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.
*
* If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
*/
refetchOnMountOrArgChange?: boolean | number;
};
/**
* A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data.
*
* The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already.
*
* Note that this hook does not return a request status or cached data. For that use-case, see [`useQuery`](#usequery) or [`useQueryState`](#usequerystate).
*
* #### Features
*
* - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
*/
type UseQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (arg: QueryArgFrom<D> | SkipToken, options?: UseQuerySubscriptionOptions) => UseQuerySubscriptionResult<D>;
type TypedUseQuerySubscription<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuerySubscription<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
type UseQuerySubscriptionResult<D extends QueryDefinition<any, any, any, any>> = Pick<QueryActionCreatorResult<D>, 'refetch'>;
/**
* Helper type to manually type the result
* of the `useQuerySubscription` hook in userland code.
*/
type TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuerySubscriptionResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
type UseLazyQueryLastPromiseInfo<D extends QueryDefinition<any, any, any, any>> = {
lastArg: QueryArgFrom<D>;
};
/**
* A React hook similar to [`useQuery`](#usequery), but with manual control over when the data fetching occurs.
*
* This hook includes the functionality of [`useLazyQuerySubscription`](#uselazyquerysubscription).
*
* #### Features
*
* - Manual control over firing a request to retrieve data
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Returns the latest request status and cached data from the Redux store
* - Re-renders as the request status changes and data becomes available
* - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met and the fetch has been manually called at least once
*
* #### Note
*
* When the trigger function returned from a LazyQuery is called, it always initiates a new request to the server even if there is cached data. Set `preferCacheValue`(the second argument to the function) as `true` if you want it to immediately return a cached value if one exists.
*/
type UseLazyQuery<D extends QueryDefinition<any, any, any, any>> = <R extends Record<string, any> = UseQueryStateDefaultResult<D>>(options?: SubscriptionOptions & Omit<UseQueryStateOptions<D, R>, 'skip'>) => [
LazyQueryTrigger<D>,
UseQueryStateResult<D, R>,
UseLazyQueryLastPromiseInfo<D>
];
type TypedUseLazyQuery<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseLazyQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
type LazyQueryTrigger<D extends QueryDefinition<any, any, any, any>> = {
/**
* Triggers a lazy query.
*
* By default, this will start a new request even if there is already a value in the cache.
* If you want to use the cache value and only start a request if there is no cache value, set the second argument to `true`.
*
* @remarks
* If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().
*
* @example
* ```ts
* // codeblock-meta title="Using .unwrap with async await"
* try {
* const payload = await getUserById(1).unwrap();
* console.log('fulfilled', payload)
* } catch (error) {
* console.error('rejected', error);
* }
* ```
*/
(arg: QueryArgFrom<D>, preferCacheValue?: boolean): QueryActionCreatorResult<D>;
};
type TypedLazyQueryTrigger<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = LazyQueryTrigger<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
/**
* A React hook similar to [`useQuerySubscription`](#usequerysubscription), but with manual control over when the data fetching occurs.
*
* Note that this hook does not return a request status or cached data. For that use-case, see [`useLazyQuery`](#uselazyquery).
*
* #### Features
*
* - Manual control over firing a request to retrieve data
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met and the fetch has been manually called at least once
*/
type UseLazyQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (options?: SubscriptionOptions) => readonly [LazyQueryTrigger<D>, QueryArgFrom<D> | UninitializedValue];
type TypedUseLazyQuerySubscription<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseLazyQuerySubscription<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
type QueryStateSelector<R extends Record<string, any>, D extends QueryDefinition<any, any, any, any>> = (state: UseQueryStateDefaultResult<D>) => R;
/**
* A React hook that reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.
*
* Note that this hook does not trigger fetching new data. For that use-case, see [`useQuery`](#usequery) or [`useQuerySubscription`](#usequerysubscription).
*
* #### Features
*
* - Returns the latest request status and cached data from the Redux store
* - Re-renders as the request status changes and data becomes available
*/
type UseQueryState<D extends QueryDefinition<any, any, any, any>> = <R extends Record<string, any> = UseQueryStateDefaultResult<D>>(arg: QueryArgFrom<D> | SkipToken, options?: UseQueryStateOptions<D, R>) => UseQueryStateResult<D, R>;
type TypedUseQueryState<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQueryState<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
type UseQueryStateOptions<D extends QueryDefinition<any, any, any, any>, R extends Record<string, any>> = {
/**
* Prevents a query from automatically running.
*
* @remarks
* When skip is true:
*
* - **If the query has cached data:**
* * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed
* * The query will have a status of `uninitialized`
* * If `skip: false` is set after skipping the initial load, the cached result will be used
* - **If the query does not have cached data:**
* * The query will have a status of `uninitialized`
* * The query will not exist in the state when viewed with the dev tools
* * The query will not automatically fetch on mount
* * The query will not automatically run when additional components with the same query are added that do run
*
* @example
* ```ts
* // codeblock-meta title="Skip example"
* const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
* const { data, error, status } = useGetPokemonByNameQuery(name, {
* skip,
* });
*
* return (
* <div>
* {name} - {status}
* </div>
* );
* };
* ```
*/
skip?: boolean;
/**
* `selectFromResult` allows you to get a specific segment from a query result in a performant manner.
* When using this feature, the component will not rerender unless the underlying data of the selected item has changed.
* If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.
*
* @example
* ```ts
* // codeblock-meta title="Using selectFromResult to extract a single result"
* function PostsList() {
* const { data: posts } = api.useGetPostsQuery();
*
* return (
* <ul>
* {posts?.data?.map((post) => (
* <PostById key={post.id} id={post.id} />
* ))}
* </ul>
* );
* }
*
* function PostById({ id }: { id: number }) {
* // Will select the post with the given id, and will only rerender if the given posts data changes
* const { post } = api.useGetPostsQuery(undefined, {
* selectFromResult: ({ data }) => ({ post: data?.find((post) => post.id === id) }),
* });
*
* return <li>{post?.name}</li>;
* }
* ```
*/
selectFromResult?: QueryStateSelector<R, D>;
};
type UseQueryStateResult<_ extends QueryDefinition<any, any, any, any>, R> = TSHelpersNoInfer<R>;
/**
* Helper type to manually type the result
* of the `useQueryState` hook in userland code.
*/
type TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = TSHelpersNoInfer<R>;
type UseQueryStateBaseResult<D extends QueryDefinition<any, any, any, any>> = QuerySubState<D> & {
/**
* Where `data` tries to hold data as much as possible, also re-using
* data from the last arguments passed into the hook, this property
* will always contain the received data from the query, for the current query arguments.
*/
currentData?: ResultTypeFrom<D>;
/**
* Query has not started yet.
*/
isUninitialized: false;
/**
* Query is currently loading for the first time. No data yet.
*/
isLoading: false;
/**
* Query is currently fetching, but might have data from an earlier request.
*/
isFetching: false;
/**
* Query has data from a successful load.
*/
isSuccess: false;
/**
* Query is currently in "error" state.
*/
isError: false;
};
type UseQueryStateDefaultResult<D extends QueryDefinition<any, any, any, any>> = TSHelpersId<TSHelpersOverride<Extract<UseQueryStateBaseResult<D>, {
status: QueryStatus.uninitialized;
}>, {
isUninitialized: true;
}> | TSHelpersOverride<UseQueryStateBaseResult<D>, {
isLoading: true;
isFetching: boolean;
data: undefined;
} | ({
isSuccess: true;
isFetching: true;
error: undefined;
} & Required<Pick<UseQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp'>>) | ({
isSuccess: true;
isFetching: false;
error: undefined;
} & Required<Pick<UseQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp' | 'currentData'>>) | ({
isError: true;
} & Required<Pick<UseQueryStateBaseResult<D>, 'error'>>)>> & {
/**
* @deprecated Included for completeness, but discouraged.
* Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`
* and `isUninitialized` flags instead
*/
status: QueryStatus;
};
type MutationStateSelector<R extends Record<string, any>, D extends MutationDefinition<any, any, any, any>> = (state: MutationResultSelectorResult<D>) => R;
type UseMutationStateOptions<D extends MutationDefinition<any, any, any, any>, R extends Record<string, any>> = {
selectFromResult?: MutationStateSelector<R, D>;
fixedCacheKey?: string;
};
type UseMutationStateResult<D extends MutationDefinition<any, any, any, any>, R> = TSHelpersNoInfer<R> & {
originalArgs?: QueryArgFrom<D>;
/**
* Resets the hook state to its initial `uninitialized` state.
* This will also remove the last result from the cache.
*/
reset: () => void;
};
/**
* Helper type to manually type the result
* of the `useMutation` hook in userland code.
*/
type TypedUseMutationResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = MutationResultSelectorResult<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = UseMutationStateResult<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>, R>;
/**
* A React hook that lets you trigger an update request for a given endpoint, and subscribes the component to read the request status from the Redux store. The component will re-render as the loading status changes.
*
* #### Features
*
* - Manual control over firing a request to alter data on the server or possibly invalidate the cache
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Returns the latest request status and cached data from the Redux store
* - Re-renders as the request status changes and data becomes available
*/
type UseMutation<D extends MutationDefinition<any, any, any, any>> = <R extends Record<string, any> = MutationResultSelectorResult<D>>(options?: UseMutationStateOptions<D, R>) => readonly [MutationTrigger<D>, UseMutationStateResult<D, R>];
type TypedUseMutation<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseMutation<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
type MutationTrigger<D extends MutationDefinition<any, any, any, any>> = {
/**
* Triggers the mutation and returns a Promise.
* @remarks
* If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().
*
* @example
* ```ts
* // codeblock-meta title="Using .unwrap with async await"
* try {
* const payload = await addPost({ id: 1, name: 'Example' }).unwrap();
* console.log('fulfilled', payload)
* } catch (error) {
* console.error('rejected', error);
* }
* ```
*/
(arg: QueryArgFrom<D>): MutationActionCreatorResult<D>;
};
type TypedMutationTrigger<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = MutationTrigger<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
type QueryHookNames<Definitions extends EndpointDefinitions> = {
[K in keyof Definitions as Definitions[K] extends {
type: DefinitionType.query;
} ? `use${Capitalize<K & string>}Query` : never]: UseQuery<Extract<Definitions[K], QueryDefinition<any, any, any, any>>>;
};
type LazyQueryHookNames<Definitions extends EndpointDefinitions> = {
[K in keyof Definitions as Definitions[K] extends {
type: DefinitionType.query;
} ? `useLazy${Capitalize<K & string>}Query` : never]: UseLazyQuery<Extract<Definitions[K], QueryDefinition<any, any, any, any>>>;
};
type MutationHookNames<Definitions extends EndpointDefinitions> = {
[K in keyof Definitions as Definitions[K] extends {
type: DefinitionType.mutation;
} ? `use${Capitalize<K & string>}Mutation` : never]: UseMutation<Extract<Definitions[K], MutationDefinition<any, any, any, any>>>;
};
type HooksWithUniqueNames<Definitions extends EndpointDefinitions> = QueryHookNames<Definitions> & LazyQueryHookNames<Definitions> & MutationHookNames<Definitions>;
export declare const reactHooksModuleName: unique symbol;
type ReactHooksModule = typeof reactHooksModuleName;
declare module '@reduxjs/toolkit/query' {
interface ApiModules<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string> {
[reactHooksModuleName]: {
/**
* Endpoints based on the input endpoints provided to `createApi`, containing `select`, `hooks` and `action matchers`.
*/
endpoints: {
[K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any, any> ? QueryHooks<Definitions[K]> : Definitions[K] extends MutationDefinition<any, any, any, any, any> ? MutationHooks<Definitions[K]> : never;
};
/**
* A hook that accepts a string endpoint name, and provides a callback that when called, pre-fetches the data for that endpoint.
*/
usePrefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, options?: PrefetchOptions): (arg: QueryArgFrom<Definitions[EndpointName]>, options?: PrefetchOptions) => void;
} & HooksWithUniqueNames<Definitions>;
}
}
type RR = typeof react_redux;
interface ReactHooksModuleOptions {
/**
* The hooks from React Redux to be used
*/
hooks?: {
/**
* The version of the `useDispatch` hook to be used
*/
useDispatch: RR['useDispatch'];
/**
* The version of the `useSelector` hook to be used
*/
useSelector: RR['useSelector'];
/**
* The version of the `useStore` hook to be used
*/
useStore: RR['useStore'];
};
/**
* The version of the `batchedUpdates` function to be used
*/
batch?: RR['batch'];
/**
* Enables performing asynchronous tasks immediately within a render.
*
* @example
*
* ```ts
* import {
* buildCreateApi,
* coreModule,
* reactHooksModule
* } from '@reduxjs/toolkit/query/react'
*
* const createApi = buildCreateApi(
* coreModule(),
* reactHooksModule({ unstable__sideEffectsInRender: true })
* )
* ```
*/
unstable__sideEffectsInRender?: boolean;
/**
* A selector creator (usually from `reselect`, or matching the same signature)
*/
createSelector?: typeof createSelector;
}
/**
* Creates a module that generates react hooks from endpoints, for use with `buildCreateApi`.
*
* @example
* ```ts
* const MyContext = React.createContext<ReactReduxContextValue | null>(null);
* const customCreateApi = buildCreateApi(
* coreModule(),
* reactHooksModule({
* hooks: {
* useDispatch: createDispatchHook(MyContext),
* useSelector: createSelectorHook(MyContext),
* useStore: createStoreHook(MyContext)
* }
* })
* );
* ```
*
* @returns A module for use with `buildCreateApi`
*/
declare const reactHooksModule: ({ batch, hooks, createSelector, unstable__sideEffectsInRender, ...rest }?: ReactHooksModuleOptions) => Module<ReactHooksModule>;
/**
* Can be used as a `Provider` if you **do not already have a Redux store**.
*
* @example
* ```tsx
* // codeblock-meta no-transpile title="Basic usage - wrap your App with ApiProvider"
* import * as React from 'react';
* import { ApiProvider } from '@reduxjs/toolkit/query/react';
* import { Pokemon } from './features/Pokemon';
*
* function App() {
* return (
* <ApiProvider api={api}>
* <Pokemon />
* </ApiProvider>
* );
* }
* ```
*
* @remarks
* Using this together with an existing redux store, both will
* conflict with each other - please use the traditional redux setup
* in that case.
*/
declare function ApiProvider(props: {
children: any;
api: Api<any, {}, any, any>;
setupListeners?: Parameters<typeof setupListeners>[1] | false;
context?: Context<ReactReduxContextValue | null>;
}): React.JSX.Element;
declare const createApi: _reduxjs_toolkit_query.CreateApi<typeof _reduxjs_toolkit_query.coreModuleName | typeof reactHooksModuleName>;
export { ApiProvider, type TypedLazyQueryTrigger, type TypedMutationTrigger, type TypedUseLazyQuery, type TypedUseLazyQuerySubscription, type TypedUseMutation, type TypedUseMutationResult, type TypedUseQuery, type TypedUseQueryHookResult, type TypedUseQueryState, type TypedUseQueryStateResult, type TypedUseQuerySubscription, type TypedUseQuerySubscriptionResult, createApi, reactHooksModule };

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,642 @@
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __objRest = (source, exclude) => {
var target = {};
for (var prop in source)
if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
target[prop] = source[prop];
if (source != null && __getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(source)) {
if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
target[prop] = source[prop];
}
return target;
};
// src/query/react/index.ts
import { buildCreateApi, coreModule } from "@reduxjs/toolkit/query";
// src/query/react/module.ts
import { formatProdErrorMessage as _formatProdErrorMessage3 } from "@reduxjs/toolkit";
import { batch as rrBatch, useDispatch as rrUseDispatch, useSelector as rrUseSelector, useStore as rrUseStore } from "react-redux";
import { createSelector as _createSelector } from "reselect";
// src/query/endpointDefinitions.ts
function isQueryDefinition(e) {
return e.type === "query" /* query */;
}
function isMutationDefinition(e) {
return e.type === "mutation" /* mutation */;
}
// src/query/tsHelpers.ts
function safeAssign(target, ...args) {
return Object.assign(target, ...args);
}
// src/query/utils/capitalize.ts
function capitalize(str) {
return str.replace(str[0], str[0].toUpperCase());
}
// src/query/core/rtkImports.ts
import { createAction, createSlice, createSelector, createAsyncThunk, combineReducers, createNextState, isAnyOf, isAllOf, isAction, isPending, isRejected, isFulfilled, isRejectedWithValue, isAsyncThunkAction, prepareAutoBatched, SHOULD_AUTOBATCH, isPlainObject, nanoid } from "@reduxjs/toolkit";
// src/query/utils/countObjectKeys.ts
function countObjectKeys(obj) {
let count = 0;
for (const _key in obj) {
count++;
}
return count;
}
// src/query/react/buildHooks.ts
import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2 } from "@reduxjs/toolkit";
import { QueryStatus, skipToken } from "@reduxjs/toolkit/query";
import { useCallback, useDebugValue, useEffect as useEffect3, useLayoutEffect, useMemo as useMemo2, useRef as useRef3, useState } from "react";
import { shallowEqual as shallowEqual2 } from "react-redux";
// src/query/defaultSerializeQueryArgs.ts
var cache = WeakMap ? /* @__PURE__ */ new WeakMap() : void 0;
var defaultSerializeQueryArgs = ({
endpointName,
queryArgs
}) => {
let serialized = "";
const cached = cache == null ? void 0 : cache.get(queryArgs);
if (typeof cached === "string") {
serialized = cached;
} else {
const stringified = JSON.stringify(queryArgs, (key, value) => {
value = typeof value === "bigint" ? {
$bigint: value.toString()
} : value;
value = isPlainObject(value) ? Object.keys(value).sort().reduce((acc, key2) => {
acc[key2] = value[key2];
return acc;
}, {}) : value;
return value;
});
if (isPlainObject(queryArgs)) {
cache == null ? void 0 : cache.set(queryArgs, stringified);
}
serialized = stringified;
}
return `${endpointName}(${serialized})`;
};
// src/query/react/constants.ts
var UNINITIALIZED_VALUE = Symbol();
// src/query/react/useSerializedStableValue.ts
import { useEffect, useRef, useMemo } from "react";
function useStableQueryArgs(queryArgs, serialize, endpointDefinition, endpointName) {
const incoming = useMemo(() => ({
queryArgs,
serialized: typeof queryArgs == "object" ? serialize({
queryArgs,
endpointDefinition,
endpointName
}) : queryArgs
}), [queryArgs, serialize, endpointDefinition, endpointName]);
const cache2 = useRef(incoming);
useEffect(() => {
if (cache2.current.serialized !== incoming.serialized) {
cache2.current = incoming;
}
}, [incoming]);
return cache2.current.serialized === incoming.serialized ? cache2.current.queryArgs : queryArgs;
}
// src/query/react/useShallowStableValue.ts
import { useEffect as useEffect2, useRef as useRef2 } from "react";
import { shallowEqual } from "react-redux";
function useShallowStableValue(value) {
const cache2 = useRef2(value);
useEffect2(() => {
if (!shallowEqual(cache2.current, value)) {
cache2.current = value;
}
}, [value]);
return shallowEqual(cache2.current, value) ? cache2.current : value;
}
// src/query/react/buildHooks.ts
var canUseDOM = () => !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined");
var isDOM = /* @__PURE__ */ canUseDOM();
var isRunningInReactNative = () => typeof navigator !== "undefined" && navigator.product === "ReactNative";
var isReactNative = /* @__PURE__ */ isRunningInReactNative();
var getUseIsomorphicLayoutEffect = () => isDOM || isReactNative ? useLayoutEffect : useEffect3;
var useIsomorphicLayoutEffect = /* @__PURE__ */ getUseIsomorphicLayoutEffect();
var noPendingQueryStateSelector = (selected) => {
if (selected.isUninitialized) {
return __spreadProps(__spreadValues({}, selected), {
isUninitialized: false,
isFetching: true,
isLoading: selected.data !== void 0 ? false : true,
status: QueryStatus.pending
});
}
return selected;
};
function buildHooks({
api,
moduleOptions: {
batch,
hooks: {
useDispatch,
useSelector,
useStore
},
unstable__sideEffectsInRender,
createSelector: createSelector2
},
serializeQueryArgs,
context
}) {
const usePossiblyImmediateEffect = unstable__sideEffectsInRender ? (cb) => cb() : useEffect3;
return {
buildQueryHooks,
buildMutationHook,
usePrefetch
};
function queryStatePreSelector(currentState, lastResult, queryArgs) {
if ((lastResult == null ? void 0 : lastResult.endpointName) && currentState.isUninitialized) {
const {
endpointName
} = lastResult;
const endpointDefinition = context.endpointDefinitions[endpointName];
if (serializeQueryArgs({
queryArgs: lastResult.originalArgs,
endpointDefinition,
endpointName
}) === serializeQueryArgs({
queryArgs,
endpointDefinition,
endpointName
})) lastResult = void 0;
}
let data = currentState.isSuccess ? currentState.data : lastResult == null ? void 0 : lastResult.data;
if (data === void 0) data = currentState.data;
const hasData = data !== void 0;
const isFetching = currentState.isLoading;
const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;
const isSuccess = currentState.isSuccess || isFetching && hasData;
return __spreadProps(__spreadValues({}, currentState), {
data,
currentData: currentState.data,
isFetching,
isLoading,
isSuccess
});
}
function usePrefetch(endpointName, defaultOptions) {
const dispatch = useDispatch();
const stableDefaultOptions = useShallowStableValue(defaultOptions);
return useCallback((arg, options) => dispatch(api.util.prefetch(endpointName, arg, __spreadValues(__spreadValues({}, stableDefaultOptions), options))), [endpointName, dispatch, stableDefaultOptions]);
}
function buildQueryHooks(name) {
const useQuerySubscription = (arg, {
refetchOnReconnect,
refetchOnFocus,
refetchOnMountOrArgChange,
skip = false,
pollingInterval = 0,
skipPollingIfUnfocused = false
} = {}) => {
const {
initiate
} = api.endpoints[name];
const dispatch = useDispatch();
const subscriptionSelectorsRef = useRef3(void 0);
if (!subscriptionSelectorsRef.current) {
const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());
if (process.env.NODE_ENV !== "production") {
if (typeof returnedValue !== "object" || typeof (returnedValue == null ? void 0 : returnedValue.type) === "string") {
throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage(37) : `Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
You must add the middleware for RTK-Query to function correctly!`);
}
}
subscriptionSelectorsRef.current = returnedValue;
}
const stableArg = useStableQueryArgs(
skip ? skipToken : arg,
// Even if the user provided a per-endpoint `serializeQueryArgs` with
// a consistent return value, _here_ we want to use the default behavior
// so we can tell if _anything_ actually changed. Otherwise, we can end up
// with a case where the query args did change but the serialization doesn't,
// and then we never try to initiate a refetch.
defaultSerializeQueryArgs,
context.endpointDefinitions[name],
name
);
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval,
skipPollingIfUnfocused
});
const lastRenderHadSubscription = useRef3(false);
const promiseRef = useRef3(void 0);
let {
queryCacheKey,
requestId
} = promiseRef.current || {};
let currentRenderHasSubscription = false;
if (queryCacheKey && requestId) {
currentRenderHasSubscription = subscriptionSelectorsRef.current.isRequestSubscribed(queryCacheKey, requestId);
}
const subscriptionRemoved = !currentRenderHasSubscription && lastRenderHadSubscription.current;
usePossiblyImmediateEffect(() => {
lastRenderHadSubscription.current = currentRenderHasSubscription;
});
usePossiblyImmediateEffect(() => {
if (subscriptionRemoved) {
promiseRef.current = void 0;
}
}, [subscriptionRemoved]);
usePossiblyImmediateEffect(() => {
var _a;
const lastPromise = promiseRef.current;
if (typeof process !== "undefined" && process.env.NODE_ENV === "removeMeOnCompilation") {
console.log(subscriptionRemoved);
}
if (stableArg === skipToken) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
promiseRef.current = void 0;
return;
}
const lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
if (!lastPromise || lastPromise.arg !== stableArg) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
const promise = dispatch(initiate(stableArg, {
subscriptionOptions: stableSubscriptionOptions,
forceRefetch: refetchOnMountOrArgChange
}));
promiseRef.current = promise;
} else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [dispatch, initiate, refetchOnMountOrArgChange, stableArg, stableSubscriptionOptions, subscriptionRemoved]);
useEffect3(() => {
return () => {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = void 0;
};
}, []);
return useMemo2(() => ({
/**
* A method to manually refetch data for the query
*/
refetch: () => {
var _a;
if (!promiseRef.current) throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage2(38) : "Cannot refetch a query that has not been started yet.");
return (_a = promiseRef.current) == null ? void 0 : _a.refetch();
}
}), []);
};
const useLazyQuerySubscription = ({
refetchOnReconnect,
refetchOnFocus,
pollingInterval = 0,
skipPollingIfUnfocused = false
} = {}) => {
const {
initiate
} = api.endpoints[name];
const dispatch = useDispatch();
const [arg, setArg] = useState(UNINITIALIZED_VALUE);
const promiseRef = useRef3(void 0);
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval,
skipPollingIfUnfocused
});
usePossiblyImmediateEffect(() => {
var _a, _b;
const lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
if (stableSubscriptionOptions !== lastSubscriptionOptions) {
(_b = promiseRef.current) == null ? void 0 : _b.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [stableSubscriptionOptions]);
const subscriptionOptionsRef = useRef3(stableSubscriptionOptions);
usePossiblyImmediateEffect(() => {
subscriptionOptionsRef.current = stableSubscriptionOptions;
}, [stableSubscriptionOptions]);
const trigger = useCallback(function(arg2, preferCacheValue = false) {
let promise;
batch(() => {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = promise = dispatch(initiate(arg2, {
subscriptionOptions: subscriptionOptionsRef.current,
forceRefetch: !preferCacheValue
}));
setArg(arg2);
});
return promise;
}, [dispatch, initiate]);
useEffect3(() => {
return () => {
var _a;
(_a = promiseRef == null ? void 0 : promiseRef.current) == null ? void 0 : _a.unsubscribe();
};
}, []);
useEffect3(() => {
if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
trigger(arg, true);
}
}, [arg, trigger]);
return useMemo2(() => [trigger, arg], [trigger, arg]);
};
const useQueryState = (arg, {
skip = false,
selectFromResult
} = {}) => {
const {
select
} = api.endpoints[name];
const stableArg = useStableQueryArgs(skip ? skipToken : arg, serializeQueryArgs, context.endpointDefinitions[name], name);
const lastValue = useRef3(void 0);
const selectDefaultResult = useMemo2(() => createSelector2([select(stableArg), (_, lastResult) => lastResult, (_) => stableArg], queryStatePreSelector, {
memoizeOptions: {
resultEqualityCheck: shallowEqual2
}
}), [select, stableArg]);
const querySelector = useMemo2(() => selectFromResult ? createSelector2([selectDefaultResult], selectFromResult, {
devModeChecks: {
identityFunctionCheck: "never"
}
}) : selectDefaultResult, [selectDefaultResult, selectFromResult]);
const currentState = useSelector((state) => querySelector(state, lastValue.current), shallowEqual2);
const store = useStore();
const newLastValue = selectDefaultResult(store.getState(), lastValue.current);
useIsomorphicLayoutEffect(() => {
lastValue.current = newLastValue;
}, [newLastValue]);
return currentState;
};
return {
useQueryState,
useQuerySubscription,
useLazyQuerySubscription,
useLazyQuery(options) {
const [trigger, arg] = useLazyQuerySubscription(options);
const queryStateResults = useQueryState(arg, __spreadProps(__spreadValues({}, options), {
skip: arg === UNINITIALIZED_VALUE
}));
const info = useMemo2(() => ({
lastArg: arg
}), [arg]);
return useMemo2(() => [trigger, queryStateResults, info], [trigger, queryStateResults, info]);
},
useQuery(arg, options) {
const querySubscriptionResults = useQuerySubscription(arg, options);
const queryStateResults = useQueryState(arg, __spreadValues({
selectFromResult: arg === skipToken || (options == null ? void 0 : options.skip) ? void 0 : noPendingQueryStateSelector
}, options));
const {
data,
status,
isLoading,
isSuccess,
isError,
error
} = queryStateResults;
useDebugValue({
data,
status,
isLoading,
isSuccess,
isError,
error
});
return useMemo2(() => __spreadValues(__spreadValues({}, queryStateResults), querySubscriptionResults), [queryStateResults, querySubscriptionResults]);
}
};
}
function buildMutationHook(name) {
return ({
selectFromResult,
fixedCacheKey
} = {}) => {
const {
select,
initiate
} = api.endpoints[name];
const dispatch = useDispatch();
const [promise, setPromise] = useState();
useEffect3(() => () => {
if (!(promise == null ? void 0 : promise.arg.fixedCacheKey)) {
promise == null ? void 0 : promise.reset();
}
}, [promise]);
const triggerMutation = useCallback(function(arg) {
const promise2 = dispatch(initiate(arg, {
fixedCacheKey
}));
setPromise(promise2);
return promise2;
}, [dispatch, initiate, fixedCacheKey]);
const {
requestId
} = promise || {};
const selectDefaultResult = useMemo2(() => select({
fixedCacheKey,
requestId: promise == null ? void 0 : promise.requestId
}), [fixedCacheKey, promise, select]);
const mutationSelector = useMemo2(() => selectFromResult ? createSelector2([selectDefaultResult], selectFromResult) : selectDefaultResult, [selectFromResult, selectDefaultResult]);
const currentState = useSelector(mutationSelector, shallowEqual2);
const originalArgs = fixedCacheKey == null ? promise == null ? void 0 : promise.arg.originalArgs : void 0;
const reset = useCallback(() => {
batch(() => {
if (promise) {
setPromise(void 0);
}
if (fixedCacheKey) {
dispatch(api.internalActions.removeMutationResult({
requestId,
fixedCacheKey
}));
}
});
}, [dispatch, fixedCacheKey, promise, requestId]);
const {
endpointName,
data,
status,
isLoading,
isSuccess,
isError,
error
} = currentState;
useDebugValue({
endpointName,
data,
status,
isLoading,
isSuccess,
isError,
error
});
const finalState = useMemo2(() => __spreadProps(__spreadValues({}, currentState), {
originalArgs,
reset
}), [currentState, originalArgs, reset]);
return useMemo2(() => [triggerMutation, finalState], [triggerMutation, finalState]);
};
}
}
// src/query/react/module.ts
var reactHooksModuleName = /* @__PURE__ */ Symbol();
var reactHooksModule = (_a = {}) => {
var _b = _a, {
batch = rrBatch,
hooks = {
useDispatch: rrUseDispatch,
useSelector: rrUseSelector,
useStore: rrUseStore
},
createSelector: createSelector2 = _createSelector,
unstable__sideEffectsInRender = false
} = _b, rest = __objRest(_b, [
"batch",
"hooks",
"createSelector",
"unstable__sideEffectsInRender"
]);
if (process.env.NODE_ENV !== "production") {
const hookNames = ["useDispatch", "useSelector", "useStore"];
let warned = false;
for (const hookName of hookNames) {
if (countObjectKeys(rest) > 0) {
if (rest[hookName]) {
if (!warned) {
console.warn("As of RTK 2.0, the hooks now need to be specified as one object, provided under a `hooks` key:\n`reactHooksModule({ hooks: { useDispatch, useSelector, useStore } })`");
warned = true;
}
}
hooks[hookName] = rest[hookName];
}
if (typeof hooks[hookName] !== "function") {
throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage3(36) : `When using custom hooks for context, all ${hookNames.length} hooks need to be provided: ${hookNames.join(", ")}.
Hook ${hookName} was either not provided or not a function.`);
}
}
}
return {
name: reactHooksModuleName,
init(api, {
serializeQueryArgs
}, context) {
const anyApi = api;
const {
buildQueryHooks,
buildMutationHook,
usePrefetch
} = buildHooks({
api,
moduleOptions: {
batch,
hooks,
unstable__sideEffectsInRender,
createSelector: createSelector2
},
serializeQueryArgs,
context
});
safeAssign(anyApi, {
usePrefetch
});
safeAssign(context, {
batch
});
return {
injectEndpoint(endpointName, definition) {
if (isQueryDefinition(definition)) {
const {
useQuery,
useLazyQuery,
useLazyQuerySubscription,
useQueryState,
useQuerySubscription
} = buildQueryHooks(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useQuery,
useLazyQuery,
useLazyQuerySubscription,
useQueryState,
useQuerySubscription
});
api[`use${capitalize(endpointName)}Query`] = useQuery;
api[`useLazy${capitalize(endpointName)}Query`] = useLazyQuery;
} else if (isMutationDefinition(definition)) {
const useMutation = buildMutationHook(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useMutation
});
api[`use${capitalize(endpointName)}Mutation`] = useMutation;
}
}
};
}
};
};
// src/query/react/index.ts
export * from "@reduxjs/toolkit/query";
// src/query/react/ApiProvider.tsx
import { configureStore, formatProdErrorMessage as _formatProdErrorMessage4 } from "@reduxjs/toolkit";
import { useContext } from "react";
import { useEffect as useEffect4 } from "react";
import * as React from "react";
import { Provider, ReactReduxContext } from "react-redux";
import { setupListeners } from "@reduxjs/toolkit/query";
function ApiProvider(props) {
const context = props.context || ReactReduxContext;
const existingContext = useContext(context);
if (existingContext) {
throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage4(35) : "Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.");
}
const [store] = React.useState(() => configureStore({
reducer: {
[props.api.reducerPath]: props.api.reducer
},
middleware: (gDM) => gDM().concat(props.api.middleware)
}));
useEffect4(() => props.setupListeners === false ? void 0 : setupListeners(store.dispatch, props.setupListeners), [props.setupListeners, store.dispatch]);
return /* @__PURE__ */ React.createElement(Provider, { store, context }, props.children);
}
// src/query/react/index.ts
var createApi = /* @__PURE__ */ buildCreateApi(coreModule(), reactHooksModule());
export {
ApiProvider,
UNINITIALIZED_VALUE,
createApi,
reactHooksModule,
reactHooksModuleName
};
//# sourceMappingURL=rtk-query-react.legacy-esm.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,610 @@
// src/query/react/index.ts
import { buildCreateApi, coreModule } from "@reduxjs/toolkit/query";
// src/query/react/module.ts
import { formatProdErrorMessage as _formatProdErrorMessage3 } from "@reduxjs/toolkit";
import { batch as rrBatch, useDispatch as rrUseDispatch, useSelector as rrUseSelector, useStore as rrUseStore } from "react-redux";
import { createSelector as _createSelector } from "reselect";
// src/query/endpointDefinitions.ts
function isQueryDefinition(e) {
return e.type === "query" /* query */;
}
function isMutationDefinition(e) {
return e.type === "mutation" /* mutation */;
}
// src/query/tsHelpers.ts
function safeAssign(target, ...args) {
return Object.assign(target, ...args);
}
// src/query/utils/capitalize.ts
function capitalize(str) {
return str.replace(str[0], str[0].toUpperCase());
}
// src/query/core/rtkImports.ts
import { createAction, createSlice, createSelector, createAsyncThunk, combineReducers, createNextState, isAnyOf, isAllOf, isAction, isPending, isRejected, isFulfilled, isRejectedWithValue, isAsyncThunkAction, prepareAutoBatched, SHOULD_AUTOBATCH, isPlainObject, nanoid } from "@reduxjs/toolkit";
// src/query/utils/countObjectKeys.ts
function countObjectKeys(obj) {
let count = 0;
for (const _key in obj) {
count++;
}
return count;
}
// src/query/react/buildHooks.ts
import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2 } from "@reduxjs/toolkit";
import { QueryStatus, skipToken } from "@reduxjs/toolkit/query";
import { useCallback, useDebugValue, useEffect as useEffect3, useLayoutEffect, useMemo as useMemo2, useRef as useRef3, useState } from "react";
import { shallowEqual as shallowEqual2 } from "react-redux";
// src/query/defaultSerializeQueryArgs.ts
var cache = WeakMap ? /* @__PURE__ */ new WeakMap() : void 0;
var defaultSerializeQueryArgs = ({
endpointName,
queryArgs
}) => {
let serialized = "";
const cached = cache?.get(queryArgs);
if (typeof cached === "string") {
serialized = cached;
} else {
const stringified = JSON.stringify(queryArgs, (key, value) => {
value = typeof value === "bigint" ? {
$bigint: value.toString()
} : value;
value = isPlainObject(value) ? Object.keys(value).sort().reduce((acc, key2) => {
acc[key2] = value[key2];
return acc;
}, {}) : value;
return value;
});
if (isPlainObject(queryArgs)) {
cache?.set(queryArgs, stringified);
}
serialized = stringified;
}
return `${endpointName}(${serialized})`;
};
// src/query/react/constants.ts
var UNINITIALIZED_VALUE = Symbol();
// src/query/react/useSerializedStableValue.ts
import { useEffect, useRef, useMemo } from "react";
function useStableQueryArgs(queryArgs, serialize, endpointDefinition, endpointName) {
const incoming = useMemo(() => ({
queryArgs,
serialized: typeof queryArgs == "object" ? serialize({
queryArgs,
endpointDefinition,
endpointName
}) : queryArgs
}), [queryArgs, serialize, endpointDefinition, endpointName]);
const cache2 = useRef(incoming);
useEffect(() => {
if (cache2.current.serialized !== incoming.serialized) {
cache2.current = incoming;
}
}, [incoming]);
return cache2.current.serialized === incoming.serialized ? cache2.current.queryArgs : queryArgs;
}
// src/query/react/useShallowStableValue.ts
import { useEffect as useEffect2, useRef as useRef2 } from "react";
import { shallowEqual } from "react-redux";
function useShallowStableValue(value) {
const cache2 = useRef2(value);
useEffect2(() => {
if (!shallowEqual(cache2.current, value)) {
cache2.current = value;
}
}, [value]);
return shallowEqual(cache2.current, value) ? cache2.current : value;
}
// src/query/react/buildHooks.ts
var canUseDOM = () => !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined");
var isDOM = /* @__PURE__ */ canUseDOM();
var isRunningInReactNative = () => typeof navigator !== "undefined" && navigator.product === "ReactNative";
var isReactNative = /* @__PURE__ */ isRunningInReactNative();
var getUseIsomorphicLayoutEffect = () => isDOM || isReactNative ? useLayoutEffect : useEffect3;
var useIsomorphicLayoutEffect = /* @__PURE__ */ getUseIsomorphicLayoutEffect();
var noPendingQueryStateSelector = (selected) => {
if (selected.isUninitialized) {
return {
...selected,
isUninitialized: false,
isFetching: true,
isLoading: selected.data !== void 0 ? false : true,
status: QueryStatus.pending
};
}
return selected;
};
function buildHooks({
api,
moduleOptions: {
batch,
hooks: {
useDispatch,
useSelector,
useStore
},
unstable__sideEffectsInRender,
createSelector: createSelector2
},
serializeQueryArgs,
context
}) {
const usePossiblyImmediateEffect = unstable__sideEffectsInRender ? (cb) => cb() : useEffect3;
return {
buildQueryHooks,
buildMutationHook,
usePrefetch
};
function queryStatePreSelector(currentState, lastResult, queryArgs) {
if (lastResult?.endpointName && currentState.isUninitialized) {
const {
endpointName
} = lastResult;
const endpointDefinition = context.endpointDefinitions[endpointName];
if (serializeQueryArgs({
queryArgs: lastResult.originalArgs,
endpointDefinition,
endpointName
}) === serializeQueryArgs({
queryArgs,
endpointDefinition,
endpointName
})) lastResult = void 0;
}
let data = currentState.isSuccess ? currentState.data : lastResult?.data;
if (data === void 0) data = currentState.data;
const hasData = data !== void 0;
const isFetching = currentState.isLoading;
const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;
const isSuccess = currentState.isSuccess || isFetching && hasData;
return {
...currentState,
data,
currentData: currentState.data,
isFetching,
isLoading,
isSuccess
};
}
function usePrefetch(endpointName, defaultOptions) {
const dispatch = useDispatch();
const stableDefaultOptions = useShallowStableValue(defaultOptions);
return useCallback((arg, options) => dispatch(api.util.prefetch(endpointName, arg, {
...stableDefaultOptions,
...options
})), [endpointName, dispatch, stableDefaultOptions]);
}
function buildQueryHooks(name) {
const useQuerySubscription = (arg, {
refetchOnReconnect,
refetchOnFocus,
refetchOnMountOrArgChange,
skip = false,
pollingInterval = 0,
skipPollingIfUnfocused = false
} = {}) => {
const {
initiate
} = api.endpoints[name];
const dispatch = useDispatch();
const subscriptionSelectorsRef = useRef3(void 0);
if (!subscriptionSelectorsRef.current) {
const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());
if (process.env.NODE_ENV !== "production") {
if (typeof returnedValue !== "object" || typeof returnedValue?.type === "string") {
throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage(37) : `Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
You must add the middleware for RTK-Query to function correctly!`);
}
}
subscriptionSelectorsRef.current = returnedValue;
}
const stableArg = useStableQueryArgs(
skip ? skipToken : arg,
// Even if the user provided a per-endpoint `serializeQueryArgs` with
// a consistent return value, _here_ we want to use the default behavior
// so we can tell if _anything_ actually changed. Otherwise, we can end up
// with a case where the query args did change but the serialization doesn't,
// and then we never try to initiate a refetch.
defaultSerializeQueryArgs,
context.endpointDefinitions[name],
name
);
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval,
skipPollingIfUnfocused
});
const lastRenderHadSubscription = useRef3(false);
const promiseRef = useRef3(void 0);
let {
queryCacheKey,
requestId
} = promiseRef.current || {};
let currentRenderHasSubscription = false;
if (queryCacheKey && requestId) {
currentRenderHasSubscription = subscriptionSelectorsRef.current.isRequestSubscribed(queryCacheKey, requestId);
}
const subscriptionRemoved = !currentRenderHasSubscription && lastRenderHadSubscription.current;
usePossiblyImmediateEffect(() => {
lastRenderHadSubscription.current = currentRenderHasSubscription;
});
usePossiblyImmediateEffect(() => {
if (subscriptionRemoved) {
promiseRef.current = void 0;
}
}, [subscriptionRemoved]);
usePossiblyImmediateEffect(() => {
const lastPromise = promiseRef.current;
if (typeof process !== "undefined" && process.env.NODE_ENV === "removeMeOnCompilation") {
console.log(subscriptionRemoved);
}
if (stableArg === skipToken) {
lastPromise?.unsubscribe();
promiseRef.current = void 0;
return;
}
const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions;
if (!lastPromise || lastPromise.arg !== stableArg) {
lastPromise?.unsubscribe();
const promise = dispatch(initiate(stableArg, {
subscriptionOptions: stableSubscriptionOptions,
forceRefetch: refetchOnMountOrArgChange
}));
promiseRef.current = promise;
} else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [dispatch, initiate, refetchOnMountOrArgChange, stableArg, stableSubscriptionOptions, subscriptionRemoved]);
useEffect3(() => {
return () => {
promiseRef.current?.unsubscribe();
promiseRef.current = void 0;
};
}, []);
return useMemo2(() => ({
/**
* A method to manually refetch data for the query
*/
refetch: () => {
if (!promiseRef.current) throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage2(38) : "Cannot refetch a query that has not been started yet.");
return promiseRef.current?.refetch();
}
}), []);
};
const useLazyQuerySubscription = ({
refetchOnReconnect,
refetchOnFocus,
pollingInterval = 0,
skipPollingIfUnfocused = false
} = {}) => {
const {
initiate
} = api.endpoints[name];
const dispatch = useDispatch();
const [arg, setArg] = useState(UNINITIALIZED_VALUE);
const promiseRef = useRef3(void 0);
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval,
skipPollingIfUnfocused
});
usePossiblyImmediateEffect(() => {
const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions;
if (stableSubscriptionOptions !== lastSubscriptionOptions) {
promiseRef.current?.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [stableSubscriptionOptions]);
const subscriptionOptionsRef = useRef3(stableSubscriptionOptions);
usePossiblyImmediateEffect(() => {
subscriptionOptionsRef.current = stableSubscriptionOptions;
}, [stableSubscriptionOptions]);
const trigger = useCallback(function(arg2, preferCacheValue = false) {
let promise;
batch(() => {
promiseRef.current?.unsubscribe();
promiseRef.current = promise = dispatch(initiate(arg2, {
subscriptionOptions: subscriptionOptionsRef.current,
forceRefetch: !preferCacheValue
}));
setArg(arg2);
});
return promise;
}, [dispatch, initiate]);
useEffect3(() => {
return () => {
promiseRef?.current?.unsubscribe();
};
}, []);
useEffect3(() => {
if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
trigger(arg, true);
}
}, [arg, trigger]);
return useMemo2(() => [trigger, arg], [trigger, arg]);
};
const useQueryState = (arg, {
skip = false,
selectFromResult
} = {}) => {
const {
select
} = api.endpoints[name];
const stableArg = useStableQueryArgs(skip ? skipToken : arg, serializeQueryArgs, context.endpointDefinitions[name], name);
const lastValue = useRef3(void 0);
const selectDefaultResult = useMemo2(() => createSelector2([select(stableArg), (_, lastResult) => lastResult, (_) => stableArg], queryStatePreSelector, {
memoizeOptions: {
resultEqualityCheck: shallowEqual2
}
}), [select, stableArg]);
const querySelector = useMemo2(() => selectFromResult ? createSelector2([selectDefaultResult], selectFromResult, {
devModeChecks: {
identityFunctionCheck: "never"
}
}) : selectDefaultResult, [selectDefaultResult, selectFromResult]);
const currentState = useSelector((state) => querySelector(state, lastValue.current), shallowEqual2);
const store = useStore();
const newLastValue = selectDefaultResult(store.getState(), lastValue.current);
useIsomorphicLayoutEffect(() => {
lastValue.current = newLastValue;
}, [newLastValue]);
return currentState;
};
return {
useQueryState,
useQuerySubscription,
useLazyQuerySubscription,
useLazyQuery(options) {
const [trigger, arg] = useLazyQuerySubscription(options);
const queryStateResults = useQueryState(arg, {
...options,
skip: arg === UNINITIALIZED_VALUE
});
const info = useMemo2(() => ({
lastArg: arg
}), [arg]);
return useMemo2(() => [trigger, queryStateResults, info], [trigger, queryStateResults, info]);
},
useQuery(arg, options) {
const querySubscriptionResults = useQuerySubscription(arg, options);
const queryStateResults = useQueryState(arg, {
selectFromResult: arg === skipToken || options?.skip ? void 0 : noPendingQueryStateSelector,
...options
});
const {
data,
status,
isLoading,
isSuccess,
isError,
error
} = queryStateResults;
useDebugValue({
data,
status,
isLoading,
isSuccess,
isError,
error
});
return useMemo2(() => ({
...queryStateResults,
...querySubscriptionResults
}), [queryStateResults, querySubscriptionResults]);
}
};
}
function buildMutationHook(name) {
return ({
selectFromResult,
fixedCacheKey
} = {}) => {
const {
select,
initiate
} = api.endpoints[name];
const dispatch = useDispatch();
const [promise, setPromise] = useState();
useEffect3(() => () => {
if (!promise?.arg.fixedCacheKey) {
promise?.reset();
}
}, [promise]);
const triggerMutation = useCallback(function(arg) {
const promise2 = dispatch(initiate(arg, {
fixedCacheKey
}));
setPromise(promise2);
return promise2;
}, [dispatch, initiate, fixedCacheKey]);
const {
requestId
} = promise || {};
const selectDefaultResult = useMemo2(() => select({
fixedCacheKey,
requestId: promise?.requestId
}), [fixedCacheKey, promise, select]);
const mutationSelector = useMemo2(() => selectFromResult ? createSelector2([selectDefaultResult], selectFromResult) : selectDefaultResult, [selectFromResult, selectDefaultResult]);
const currentState = useSelector(mutationSelector, shallowEqual2);
const originalArgs = fixedCacheKey == null ? promise?.arg.originalArgs : void 0;
const reset = useCallback(() => {
batch(() => {
if (promise) {
setPromise(void 0);
}
if (fixedCacheKey) {
dispatch(api.internalActions.removeMutationResult({
requestId,
fixedCacheKey
}));
}
});
}, [dispatch, fixedCacheKey, promise, requestId]);
const {
endpointName,
data,
status,
isLoading,
isSuccess,
isError,
error
} = currentState;
useDebugValue({
endpointName,
data,
status,
isLoading,
isSuccess,
isError,
error
});
const finalState = useMemo2(() => ({
...currentState,
originalArgs,
reset
}), [currentState, originalArgs, reset]);
return useMemo2(() => [triggerMutation, finalState], [triggerMutation, finalState]);
};
}
}
// src/query/react/module.ts
var reactHooksModuleName = /* @__PURE__ */ Symbol();
var reactHooksModule = ({
batch = rrBatch,
hooks = {
useDispatch: rrUseDispatch,
useSelector: rrUseSelector,
useStore: rrUseStore
},
createSelector: createSelector2 = _createSelector,
unstable__sideEffectsInRender = false,
...rest
} = {}) => {
if (process.env.NODE_ENV !== "production") {
const hookNames = ["useDispatch", "useSelector", "useStore"];
let warned = false;
for (const hookName of hookNames) {
if (countObjectKeys(rest) > 0) {
if (rest[hookName]) {
if (!warned) {
console.warn("As of RTK 2.0, the hooks now need to be specified as one object, provided under a `hooks` key:\n`reactHooksModule({ hooks: { useDispatch, useSelector, useStore } })`");
warned = true;
}
}
hooks[hookName] = rest[hookName];
}
if (typeof hooks[hookName] !== "function") {
throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage3(36) : `When using custom hooks for context, all ${hookNames.length} hooks need to be provided: ${hookNames.join(", ")}.
Hook ${hookName} was either not provided or not a function.`);
}
}
}
return {
name: reactHooksModuleName,
init(api, {
serializeQueryArgs
}, context) {
const anyApi = api;
const {
buildQueryHooks,
buildMutationHook,
usePrefetch
} = buildHooks({
api,
moduleOptions: {
batch,
hooks,
unstable__sideEffectsInRender,
createSelector: createSelector2
},
serializeQueryArgs,
context
});
safeAssign(anyApi, {
usePrefetch
});
safeAssign(context, {
batch
});
return {
injectEndpoint(endpointName, definition) {
if (isQueryDefinition(definition)) {
const {
useQuery,
useLazyQuery,
useLazyQuerySubscription,
useQueryState,
useQuerySubscription
} = buildQueryHooks(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useQuery,
useLazyQuery,
useLazyQuerySubscription,
useQueryState,
useQuerySubscription
});
api[`use${capitalize(endpointName)}Query`] = useQuery;
api[`useLazy${capitalize(endpointName)}Query`] = useLazyQuery;
} else if (isMutationDefinition(definition)) {
const useMutation = buildMutationHook(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useMutation
});
api[`use${capitalize(endpointName)}Mutation`] = useMutation;
}
}
};
}
};
};
// src/query/react/index.ts
export * from "@reduxjs/toolkit/query";
// src/query/react/ApiProvider.tsx
import { configureStore, formatProdErrorMessage as _formatProdErrorMessage4 } from "@reduxjs/toolkit";
import { useContext } from "react";
import { useEffect as useEffect4 } from "react";
import * as React from "react";
import { Provider, ReactReduxContext } from "react-redux";
import { setupListeners } from "@reduxjs/toolkit/query";
function ApiProvider(props) {
const context = props.context || ReactReduxContext;
const existingContext = useContext(context);
if (existingContext) {
throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage4(35) : "Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.");
}
const [store] = React.useState(() => configureStore({
reducer: {
[props.api.reducerPath]: props.api.reducer
},
middleware: (gDM) => gDM().concat(props.api.middleware)
}));
useEffect4(() => props.setupListeners === false ? void 0 : setupListeners(store.dispatch, props.setupListeners), [props.setupListeners, store.dispatch]);
return /* @__PURE__ */ React.createElement(Provider, { store, context }, props.children);
}
// src/query/react/index.ts
var createApi = /* @__PURE__ */ buildCreateApi(coreModule(), reactHooksModule());
export {
ApiProvider,
UNINITIALIZED_VALUE,
createApi,
reactHooksModule,
reactHooksModuleName
};
//# sourceMappingURL=rtk-query-react.modern.mjs.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,6 @@
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./redux-toolkit-react.production.min.cjs')
} else {
module.exports = require('./redux-toolkit-react.development.cjs')
}

View File

@@ -0,0 +1,55 @@
"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/react/index.ts
var react_exports = {};
__export(react_exports, {
createDynamicMiddleware: () => createDynamicMiddleware
});
module.exports = __toCommonJS(react_exports);
__reExport(react_exports, require("@reduxjs/toolkit"), module.exports);
// src/dynamicMiddleware/react/index.ts
var import_toolkit = require("@reduxjs/toolkit");
var import_react_redux = require("react-redux");
var createDynamicMiddleware = () => {
const instance = (0, import_toolkit.createDynamicMiddleware)();
const createDispatchWithMiddlewareHookFactory = (context = import_react_redux.ReactReduxContext) => {
const useDispatch = context === import_react_redux.ReactReduxContext ? import_react_redux.useDispatch : (0, import_react_redux.createDispatchHook)(context);
function createDispatchWithMiddlewareHook2(...middlewares) {
instance.addMiddleware(...middlewares);
return useDispatch;
}
createDispatchWithMiddlewareHook2.withTypes = () => createDispatchWithMiddlewareHook2;
return createDispatchWithMiddlewareHook2;
};
const createDispatchWithMiddlewareHook = createDispatchWithMiddlewareHookFactory();
return {
...instance,
createDispatchWithMiddlewareHookFactory,
createDispatchWithMiddlewareHook
};
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
createDynamicMiddleware,
...require("@reduxjs/toolkit")
});
//# sourceMappingURL=redux-toolkit-react.development.cjs.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/react/index.ts","../../../src/dynamicMiddleware/react/index.ts"],"sourcesContent":["// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from '@reduxjs/toolkit';\nexport * from '@reduxjs/toolkit';\nexport { createDynamicMiddleware } from '../dynamicMiddleware/react';\nexport type { CreateDispatchWithMiddlewareHook } from '../dynamicMiddleware/react/index';","import type { DynamicMiddlewareInstance, GetDispatch, GetState, MiddlewareApiConfig, TSHelpersExtractDispatchExtensions } from '@reduxjs/toolkit';\nimport { createDynamicMiddleware as cDM } from '@reduxjs/toolkit';\nimport type { Context } from 'react';\nimport type { ReactReduxContextValue } from 'react-redux';\nimport { createDispatchHook, ReactReduxContext, useDispatch as useDefaultDispatch } from 'react-redux';\nimport type { Action, Dispatch, Middleware, UnknownAction } from 'redux';\nexport type UseDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[] = [], State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = () => TSHelpersExtractDispatchExtensions<Middlewares> & DispatchType;\nexport type CreateDispatchWithMiddlewareHook<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = {\n <Middlewares extends [Middleware<any, State, DispatchType>, ...Middleware<any, State, DispatchType>[]]>(...middlewares: Middlewares): UseDispatchWithMiddlewareHook<Middlewares, State, DispatchType>;\n withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): CreateDispatchWithMiddlewareHook<GetState<MiddlewareConfig>, GetDispatch<MiddlewareConfig>>;\n};\ntype ActionFromDispatch<DispatchType extends Dispatch<Action>> = DispatchType extends Dispatch<infer Action> ? Action : never;\ntype ReactDynamicMiddlewareInstance<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = DynamicMiddlewareInstance<State, DispatchType> & {\n createDispatchWithMiddlewareHookFactory: (context?: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null>) => CreateDispatchWithMiddlewareHook<State, DispatchType>;\n createDispatchWithMiddlewareHook: CreateDispatchWithMiddlewareHook<State, DispatchType>;\n};\nexport const createDynamicMiddleware = <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>(): ReactDynamicMiddlewareInstance<State, DispatchType> => {\n const instance = cDM<State, DispatchType>();\n const createDispatchWithMiddlewareHookFactory = (\n // @ts-ignore\n context: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null> = ReactReduxContext) => {\n const useDispatch = context === ReactReduxContext ? useDefaultDispatch : createDispatchHook(context);\n function createDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[]>(...middlewares: Middlewares) {\n instance.addMiddleware(...middlewares);\n return useDispatch;\n }\n createDispatchWithMiddlewareHook.withTypes = () => createDispatchWithMiddlewareHook;\n return (createDispatchWithMiddlewareHook as CreateDispatchWithMiddlewareHook<State, DispatchType>);\n };\n const createDispatchWithMiddlewareHook = createDispatchWithMiddlewareHookFactory();\n return {\n ...instance,\n createDispatchWithMiddlewareHookFactory,\n createDispatchWithMiddlewareHook\n };\n};"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,0BAAc,6BAHd;;;ACCA,qBAA+C;AAG/C,yBAAyF;AAYlF,IAAM,0BAA0B,MAAgJ;AACrL,QAAM,eAAW,eAAAA,yBAAyB;AAC1C,QAAM,0CAA0C,CAEhD,UAA2F,yCAAsB;AAC/G,UAAM,cAAc,YAAY,uCAAoB,mBAAAC,kBAAqB,uCAAmB,OAAO;AACnG,aAASC,qCAAgG,aAA0B;AACjI,eAAS,cAAc,GAAG,WAAW;AACrC,aAAO;AAAA,IACT;AACA,IAAAA,kCAAiC,YAAY,MAAMA;AACnD,WAAQA;AAAA,EACV;AACA,QAAM,mCAAmC,wCAAwC;AACjF,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,IACA;AAAA,EACF;AACF;","names":["cDM","useDefaultDispatch","createDispatchWithMiddlewareHook"]}

View File

@@ -0,0 +1,2 @@
"use strict";var s=Object.defineProperty;var w=Object.getOwnPropertyDescriptor;var y=Object.getOwnPropertyNames;var M=Object.prototype.hasOwnProperty;var x=(t,e)=>{for(var a in e)s(t,a,{get:e[a],enumerable:!0})},d=(t,e,a,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of y(e))!M.call(t,i)&&i!==a&&s(t,i,{get:()=>e[i],enumerable:!(n=w(e,i))||n.enumerable});return t},r=(t,e,a)=>(d(t,e,"default"),a&&d(a,e,"default"));var m=t=>d(s({},"__esModule",{value:!0}),t);var o={};x(o,{createDynamicMiddleware:()=>D});module.exports=m(o);r(o,require("@reduxjs/toolkit"),module.exports);var h=require("@reduxjs/toolkit"),c=require("react-redux"),D=()=>{let t=(0,h.createDynamicMiddleware)(),e=(n=c.ReactReduxContext)=>{let i=n===c.ReactReduxContext?c.useDispatch:(0,c.createDispatchHook)(n);function p(...l){return t.addMiddleware(...l),i}return p.withTypes=()=>p,p},a=e();return{...t,createDispatchWithMiddlewareHookFactory:e,createDispatchWithMiddlewareHook:a}};0&&(module.exports={createDynamicMiddleware,...require("@reduxjs/toolkit")});
//# sourceMappingURL=redux-toolkit-react.production.min.cjs.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/react/index.ts","../../../src/dynamicMiddleware/react/index.ts"],"sourcesContent":["// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from '@reduxjs/toolkit';\nexport * from '@reduxjs/toolkit';\nexport { createDynamicMiddleware } from '../dynamicMiddleware/react';\nexport type { CreateDispatchWithMiddlewareHook } from '../dynamicMiddleware/react/index';","import type { DynamicMiddlewareInstance, GetDispatch, GetState, MiddlewareApiConfig, TSHelpersExtractDispatchExtensions } from '@reduxjs/toolkit';\nimport { createDynamicMiddleware as cDM } from '@reduxjs/toolkit';\nimport type { Context } from 'react';\nimport type { ReactReduxContextValue } from 'react-redux';\nimport { createDispatchHook, ReactReduxContext, useDispatch as useDefaultDispatch } from 'react-redux';\nimport type { Action, Dispatch, Middleware, UnknownAction } from 'redux';\nexport type UseDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[] = [], State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = () => TSHelpersExtractDispatchExtensions<Middlewares> & DispatchType;\nexport type CreateDispatchWithMiddlewareHook<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = {\n <Middlewares extends [Middleware<any, State, DispatchType>, ...Middleware<any, State, DispatchType>[]]>(...middlewares: Middlewares): UseDispatchWithMiddlewareHook<Middlewares, State, DispatchType>;\n withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): CreateDispatchWithMiddlewareHook<GetState<MiddlewareConfig>, GetDispatch<MiddlewareConfig>>;\n};\ntype ActionFromDispatch<DispatchType extends Dispatch<Action>> = DispatchType extends Dispatch<infer Action> ? Action : never;\ntype ReactDynamicMiddlewareInstance<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = DynamicMiddlewareInstance<State, DispatchType> & {\n createDispatchWithMiddlewareHookFactory: (context?: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null>) => CreateDispatchWithMiddlewareHook<State, DispatchType>;\n createDispatchWithMiddlewareHook: CreateDispatchWithMiddlewareHook<State, DispatchType>;\n};\nexport const createDynamicMiddleware = <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>(): ReactDynamicMiddlewareInstance<State, DispatchType> => {\n const instance = cDM<State, DispatchType>();\n const createDispatchWithMiddlewareHookFactory = (\n // @ts-ignore\n context: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null> = ReactReduxContext) => {\n const useDispatch = context === ReactReduxContext ? useDefaultDispatch : createDispatchHook(context);\n function createDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[]>(...middlewares: Middlewares) {\n instance.addMiddleware(...middlewares);\n return useDispatch;\n }\n createDispatchWithMiddlewareHook.withTypes = () => createDispatchWithMiddlewareHook;\n return (createDispatchWithMiddlewareHook as CreateDispatchWithMiddlewareHook<State, DispatchType>);\n };\n const createDispatchWithMiddlewareHook = createDispatchWithMiddlewareHookFactory();\n return {\n ...instance,\n createDispatchWithMiddlewareHookFactory,\n createDispatchWithMiddlewareHook\n };\n};"],"mappings":"2dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,6BAAAE,IAAA,eAAAC,EAAAH,GAGAI,EAAAJ,EAAc,4BAHd,gBCCA,IAAAK,EAA+C,4BAG/CC,EAAyF,uBAY5EC,EAA0B,IAAgJ,CACrL,IAAMC,KAAW,EAAAC,yBAAyB,EACpCC,EAA0C,CAEhDC,EAA2F,sBAAsB,CAC/G,IAAMC,EAAcD,IAAY,oBAAoB,EAAAE,eAAqB,sBAAmBF,CAAO,EACnG,SAASG,KAAgGC,EAA0B,CACjI,OAAAP,EAAS,cAAc,GAAGO,CAAW,EAC9BH,CACT,CACA,OAAAE,EAAiC,UAAY,IAAMA,EAC3CA,CACV,EACMA,EAAmCJ,EAAwC,EACjF,MAAO,CACL,GAAGF,EACH,wCAAAE,EACA,iCAAAI,CACF,CACF","names":["react_exports","__export","createDynamicMiddleware","__toCommonJS","__reExport","import_toolkit","import_react_redux","createDynamicMiddleware","instance","cDM","createDispatchWithMiddlewareHookFactory","context","useDispatch","useDefaultDispatch","createDispatchWithMiddlewareHook","middlewares"]}

22
node_modules/@reduxjs/toolkit/dist/react/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,22 @@
import { MiddlewareApiConfig, GetState, GetDispatch, TSHelpersExtractDispatchExtensions, DynamicMiddlewareInstance } from '@reduxjs/toolkit';
export * from '@reduxjs/toolkit';
import { Context } from 'react';
import { ReactReduxContextValue } from 'react-redux';
import { Dispatch, UnknownAction, Middleware, Action } from 'redux';
type UseDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[] = [], State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = () => TSHelpersExtractDispatchExtensions<Middlewares> & DispatchType;
type CreateDispatchWithMiddlewareHook<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = {
<Middlewares extends [
Middleware<any, State, DispatchType>,
...Middleware<any, State, DispatchType>[]
]>(...middlewares: Middlewares): UseDispatchWithMiddlewareHook<Middlewares, State, DispatchType>;
withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): CreateDispatchWithMiddlewareHook<GetState<MiddlewareConfig>, GetDispatch<MiddlewareConfig>>;
};
type ActionFromDispatch<DispatchType extends Dispatch<Action>> = DispatchType extends Dispatch<infer Action> ? Action : never;
type ReactDynamicMiddlewareInstance<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = DynamicMiddlewareInstance<State, DispatchType> & {
createDispatchWithMiddlewareHookFactory: (context?: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null>) => CreateDispatchWithMiddlewareHook<State, DispatchType>;
createDispatchWithMiddlewareHook: CreateDispatchWithMiddlewareHook<State, DispatchType>;
};
declare const createDynamicMiddleware: <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>() => ReactDynamicMiddlewareInstance<State, DispatchType>;
export { type CreateDispatchWithMiddlewareHook, createDynamicMiddleware };

View File

@@ -0,0 +1,2 @@
export*from"@reduxjs/toolkit";import{createDynamicMiddleware as p}from"@reduxjs/toolkit";import{createDispatchHook as d,ReactReduxContext as c,useDispatch as s}from"react-redux";var h=()=>{let t=p(),a=(i=c)=>{let o=i===c?s:d(i);function e(...r){return t.addMiddleware(...r),o}return e.withTypes=()=>e,e},n=a();return{...t,createDispatchWithMiddlewareHookFactory:a,createDispatchWithMiddlewareHook:n}};export{h as createDynamicMiddleware};
//# sourceMappingURL=redux-toolkit-react.browser.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/react/index.ts","../../src/dynamicMiddleware/react/index.ts"],"sourcesContent":["// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from '@reduxjs/toolkit';\nexport * from '@reduxjs/toolkit';\nexport { createDynamicMiddleware } from '../dynamicMiddleware/react';\nexport type { CreateDispatchWithMiddlewareHook } from '../dynamicMiddleware/react/index';","import type { DynamicMiddlewareInstance, GetDispatch, GetState, MiddlewareApiConfig, TSHelpersExtractDispatchExtensions } from '@reduxjs/toolkit';\nimport { createDynamicMiddleware as cDM } from '@reduxjs/toolkit';\nimport type { Context } from 'react';\nimport type { ReactReduxContextValue } from 'react-redux';\nimport { createDispatchHook, ReactReduxContext, useDispatch as useDefaultDispatch } from 'react-redux';\nimport type { Action, Dispatch, Middleware, UnknownAction } from 'redux';\nexport type UseDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[] = [], State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = () => TSHelpersExtractDispatchExtensions<Middlewares> & DispatchType;\nexport type CreateDispatchWithMiddlewareHook<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = {\n <Middlewares extends [Middleware<any, State, DispatchType>, ...Middleware<any, State, DispatchType>[]]>(...middlewares: Middlewares): UseDispatchWithMiddlewareHook<Middlewares, State, DispatchType>;\n withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): CreateDispatchWithMiddlewareHook<GetState<MiddlewareConfig>, GetDispatch<MiddlewareConfig>>;\n};\ntype ActionFromDispatch<DispatchType extends Dispatch<Action>> = DispatchType extends Dispatch<infer Action> ? Action : never;\ntype ReactDynamicMiddlewareInstance<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = DynamicMiddlewareInstance<State, DispatchType> & {\n createDispatchWithMiddlewareHookFactory: (context?: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null>) => CreateDispatchWithMiddlewareHook<State, DispatchType>;\n createDispatchWithMiddlewareHook: CreateDispatchWithMiddlewareHook<State, DispatchType>;\n};\nexport const createDynamicMiddleware = <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>(): ReactDynamicMiddlewareInstance<State, DispatchType> => {\n const instance = cDM<State, DispatchType>();\n const createDispatchWithMiddlewareHookFactory = (\n // @ts-ignore\n context: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null> = ReactReduxContext) => {\n const useDispatch = context === ReactReduxContext ? useDefaultDispatch : createDispatchHook(context);\n function createDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[]>(...middlewares: Middlewares) {\n instance.addMiddleware(...middlewares);\n return useDispatch;\n }\n createDispatchWithMiddlewareHook.withTypes = () => createDispatchWithMiddlewareHook;\n return (createDispatchWithMiddlewareHook as CreateDispatchWithMiddlewareHook<State, DispatchType>);\n };\n const createDispatchWithMiddlewareHook = createDispatchWithMiddlewareHookFactory();\n return {\n ...instance,\n createDispatchWithMiddlewareHookFactory,\n createDispatchWithMiddlewareHook\n };\n};"],"mappings":"AAGA,WAAc,mBCFd,OAAS,2BAA2BA,MAAW,mBAG/C,OAAS,sBAAAC,EAAoB,qBAAAC,EAAmB,eAAeC,MAA0B,cAYlF,IAAMC,EAA0B,IAAgJ,CACrL,IAAMC,EAAWL,EAAyB,EACpCM,EAA0C,CAEhDC,EAA2FL,IAAsB,CAC/G,IAAMM,EAAcD,IAAYL,EAAoBC,EAAqBF,EAAmBM,CAAO,EACnG,SAASE,KAAgGC,EAA0B,CACjI,OAAAL,EAAS,cAAc,GAAGK,CAAW,EAC9BF,CACT,CACA,OAAAC,EAAiC,UAAY,IAAMA,EAC3CA,CACV,EACMA,EAAmCH,EAAwC,EACjF,MAAO,CACL,GAAGD,EACH,wCAAAC,EACA,iCAAAG,CACF,CACF","names":["cDM","createDispatchHook","ReactReduxContext","useDefaultDispatch","createDynamicMiddleware","instance","createDispatchWithMiddlewareHookFactory","context","useDispatch","createDispatchWithMiddlewareHook","middlewares"]}

View File

@@ -0,0 +1,47 @@
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
// src/react/index.ts
export * from "@reduxjs/toolkit";
// src/dynamicMiddleware/react/index.ts
import { createDynamicMiddleware as cDM } from "@reduxjs/toolkit";
import { createDispatchHook, ReactReduxContext, useDispatch as useDefaultDispatch } from "react-redux";
var createDynamicMiddleware = () => {
const instance = cDM();
const createDispatchWithMiddlewareHookFactory = (context = ReactReduxContext) => {
const useDispatch = context === ReactReduxContext ? useDefaultDispatch : createDispatchHook(context);
function createDispatchWithMiddlewareHook2(...middlewares) {
instance.addMiddleware(...middlewares);
return useDispatch;
}
createDispatchWithMiddlewareHook2.withTypes = () => createDispatchWithMiddlewareHook2;
return createDispatchWithMiddlewareHook2;
};
const createDispatchWithMiddlewareHook = createDispatchWithMiddlewareHookFactory();
return __spreadProps(__spreadValues({}, instance), {
createDispatchWithMiddlewareHookFactory,
createDispatchWithMiddlewareHook
});
};
export {
createDynamicMiddleware
};
//# sourceMappingURL=redux-toolkit-react.legacy-esm.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/react/index.ts","../../src/dynamicMiddleware/react/index.ts"],"sourcesContent":["// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from '@reduxjs/toolkit';\nexport * from '@reduxjs/toolkit';\nexport { createDynamicMiddleware } from '../dynamicMiddleware/react';\nexport type { CreateDispatchWithMiddlewareHook } from '../dynamicMiddleware/react/index';","import type { DynamicMiddlewareInstance, GetDispatch, GetState, MiddlewareApiConfig, TSHelpersExtractDispatchExtensions } from '@reduxjs/toolkit';\nimport { createDynamicMiddleware as cDM } from '@reduxjs/toolkit';\nimport type { Context } from 'react';\nimport type { ReactReduxContextValue } from 'react-redux';\nimport { createDispatchHook, ReactReduxContext, useDispatch as useDefaultDispatch } from 'react-redux';\nimport type { Action, Dispatch, Middleware, UnknownAction } from 'redux';\nexport type UseDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[] = [], State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = () => TSHelpersExtractDispatchExtensions<Middlewares> & DispatchType;\nexport type CreateDispatchWithMiddlewareHook<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = {\n <Middlewares extends [Middleware<any, State, DispatchType>, ...Middleware<any, State, DispatchType>[]]>(...middlewares: Middlewares): UseDispatchWithMiddlewareHook<Middlewares, State, DispatchType>;\n withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): CreateDispatchWithMiddlewareHook<GetState<MiddlewareConfig>, GetDispatch<MiddlewareConfig>>;\n};\ntype ActionFromDispatch<DispatchType extends Dispatch<Action>> = DispatchType extends Dispatch<infer Action> ? Action : never;\ntype ReactDynamicMiddlewareInstance<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = DynamicMiddlewareInstance<State, DispatchType> & {\n createDispatchWithMiddlewareHookFactory: (context?: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null>) => CreateDispatchWithMiddlewareHook<State, DispatchType>;\n createDispatchWithMiddlewareHook: CreateDispatchWithMiddlewareHook<State, DispatchType>;\n};\nexport const createDynamicMiddleware = <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>(): ReactDynamicMiddlewareInstance<State, DispatchType> => {\n const instance = cDM<State, DispatchType>();\n const createDispatchWithMiddlewareHookFactory = (\n // @ts-ignore\n context: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null> = ReactReduxContext) => {\n const useDispatch = context === ReactReduxContext ? useDefaultDispatch : createDispatchHook(context);\n function createDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[]>(...middlewares: Middlewares) {\n instance.addMiddleware(...middlewares);\n return useDispatch;\n }\n createDispatchWithMiddlewareHook.withTypes = () => createDispatchWithMiddlewareHook;\n return (createDispatchWithMiddlewareHook as CreateDispatchWithMiddlewareHook<State, DispatchType>);\n };\n const createDispatchWithMiddlewareHook = createDispatchWithMiddlewareHookFactory();\n return {\n ...instance,\n createDispatchWithMiddlewareHookFactory,\n createDispatchWithMiddlewareHook\n };\n};"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAGA,cAAc;;;ACFd,SAAS,2BAA2B,WAAW;AAG/C,SAAS,oBAAoB,mBAAmB,eAAe,0BAA0B;AAYlF,IAAM,0BAA0B,MAAgJ;AACrL,QAAM,WAAW,IAAyB;AAC1C,QAAM,0CAA0C,CAEhD,UAA2F,sBAAsB;AAC/G,UAAM,cAAc,YAAY,oBAAoB,qBAAqB,mBAAmB,OAAO;AACnG,aAASA,qCAAgG,aAA0B;AACjI,eAAS,cAAc,GAAG,WAAW;AACrC,aAAO;AAAA,IACT;AACA,IAAAA,kCAAiC,YAAY,MAAMA;AACnD,WAAQA;AAAA,EACV;AACA,QAAM,mCAAmC,wCAAwC;AACjF,SAAO,iCACF,WADE;AAAA,IAEL;AAAA,IACA;AAAA,EACF;AACF;","names":["createDispatchWithMiddlewareHook"]}

View File

@@ -0,0 +1,28 @@
// src/react/index.ts
export * from "@reduxjs/toolkit";
// src/dynamicMiddleware/react/index.ts
import { createDynamicMiddleware as cDM } from "@reduxjs/toolkit";
import { createDispatchHook, ReactReduxContext, useDispatch as useDefaultDispatch } from "react-redux";
var createDynamicMiddleware = () => {
const instance = cDM();
const createDispatchWithMiddlewareHookFactory = (context = ReactReduxContext) => {
const useDispatch = context === ReactReduxContext ? useDefaultDispatch : createDispatchHook(context);
function createDispatchWithMiddlewareHook2(...middlewares) {
instance.addMiddleware(...middlewares);
return useDispatch;
}
createDispatchWithMiddlewareHook2.withTypes = () => createDispatchWithMiddlewareHook2;
return createDispatchWithMiddlewareHook2;
};
const createDispatchWithMiddlewareHook = createDispatchWithMiddlewareHookFactory();
return {
...instance,
createDispatchWithMiddlewareHookFactory,
createDispatchWithMiddlewareHook
};
};
export {
createDynamicMiddleware
};
//# sourceMappingURL=redux-toolkit-react.modern.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/react/index.ts","../../src/dynamicMiddleware/react/index.ts"],"sourcesContent":["// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from '@reduxjs/toolkit';\nexport * from '@reduxjs/toolkit';\nexport { createDynamicMiddleware } from '../dynamicMiddleware/react';\nexport type { CreateDispatchWithMiddlewareHook } from '../dynamicMiddleware/react/index';","import type { DynamicMiddlewareInstance, GetDispatch, GetState, MiddlewareApiConfig, TSHelpersExtractDispatchExtensions } from '@reduxjs/toolkit';\nimport { createDynamicMiddleware as cDM } from '@reduxjs/toolkit';\nimport type { Context } from 'react';\nimport type { ReactReduxContextValue } from 'react-redux';\nimport { createDispatchHook, ReactReduxContext, useDispatch as useDefaultDispatch } from 'react-redux';\nimport type { Action, Dispatch, Middleware, UnknownAction } from 'redux';\nexport type UseDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[] = [], State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = () => TSHelpersExtractDispatchExtensions<Middlewares> & DispatchType;\nexport type CreateDispatchWithMiddlewareHook<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = {\n <Middlewares extends [Middleware<any, State, DispatchType>, ...Middleware<any, State, DispatchType>[]]>(...middlewares: Middlewares): UseDispatchWithMiddlewareHook<Middlewares, State, DispatchType>;\n withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): CreateDispatchWithMiddlewareHook<GetState<MiddlewareConfig>, GetDispatch<MiddlewareConfig>>;\n};\ntype ActionFromDispatch<DispatchType extends Dispatch<Action>> = DispatchType extends Dispatch<infer Action> ? Action : never;\ntype ReactDynamicMiddlewareInstance<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = DynamicMiddlewareInstance<State, DispatchType> & {\n createDispatchWithMiddlewareHookFactory: (context?: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null>) => CreateDispatchWithMiddlewareHook<State, DispatchType>;\n createDispatchWithMiddlewareHook: CreateDispatchWithMiddlewareHook<State, DispatchType>;\n};\nexport const createDynamicMiddleware = <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>(): ReactDynamicMiddlewareInstance<State, DispatchType> => {\n const instance = cDM<State, DispatchType>();\n const createDispatchWithMiddlewareHookFactory = (\n // @ts-ignore\n context: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null> = ReactReduxContext) => {\n const useDispatch = context === ReactReduxContext ? useDefaultDispatch : createDispatchHook(context);\n function createDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[]>(...middlewares: Middlewares) {\n instance.addMiddleware(...middlewares);\n return useDispatch;\n }\n createDispatchWithMiddlewareHook.withTypes = () => createDispatchWithMiddlewareHook;\n return (createDispatchWithMiddlewareHook as CreateDispatchWithMiddlewareHook<State, DispatchType>);\n };\n const createDispatchWithMiddlewareHook = createDispatchWithMiddlewareHookFactory();\n return {\n ...instance,\n createDispatchWithMiddlewareHookFactory,\n createDispatchWithMiddlewareHook\n };\n};"],"mappings":";AAGA,cAAc;;;ACFd,SAAS,2BAA2B,WAAW;AAG/C,SAAS,oBAAoB,mBAAmB,eAAe,0BAA0B;AAYlF,IAAM,0BAA0B,MAAgJ;AACrL,QAAM,WAAW,IAAyB;AAC1C,QAAM,0CAA0C,CAEhD,UAA2F,sBAAsB;AAC/G,UAAM,cAAc,YAAY,oBAAoB,qBAAqB,mBAAmB,OAAO;AACnG,aAASA,qCAAgG,aAA0B;AACjI,eAAS,cAAc,GAAG,WAAW;AACrC,aAAO;AAAA,IACT;AACA,IAAAA,kCAAiC,YAAY,MAAMA;AACnD,WAAQA;AAAA,EACV;AACA,QAAM,mCAAmC,wCAAwC;AACjF,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,IACA;AAAA,EACF;AACF;","names":["createDispatchWithMiddlewareHook"]}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

16
node_modules/@reduxjs/toolkit/dist/uncheckedindexed.ts generated vendored Normal file
View File

@@ -0,0 +1,16 @@
// inlined from https://github.com/EskiMojo14/uncheckedindexed
// relies on remaining as a TS file, not .d.ts
type IfMaybeUndefined<T, True, False> = [undefined] extends [T] ? True : False
const testAccess = ({} as Record<string, 0>)['a']
export type IfUncheckedIndexedAccess<True, False> = IfMaybeUndefined<
typeof testAccess,
True,
False
>
export type UncheckedIndexedAccess<T> = IfUncheckedIndexedAccess<
T | undefined,
T
>

146
node_modules/@reduxjs/toolkit/package.json generated vendored Normal file
View File

@@ -0,0 +1,146 @@
{
"name": "@reduxjs/toolkit",
"version": "2.2.7",
"description": "The official, opinionated, batteries-included toolset for efficient Redux development",
"author": "Mark Erikson <mark@isquaredsoftware.com>",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/reduxjs/redux-toolkit.git"
},
"keywords": [
"redux",
"react",
"starter",
"toolkit",
"reducer",
"slice",
"immer",
"immutable",
"redux-toolkit"
],
"publishConfig": {
"access": "public"
},
"module": "dist/redux-toolkit.legacy-esm.js",
"main": "dist/cjs/index.js",
"types": "dist/index.d.ts",
"exports": {
"./package.json": "./package.json",
".": {
"types": "./dist/index.d.ts",
"import": "./dist/redux-toolkit.modern.mjs",
"default": "./dist/cjs/index.js"
},
"./react": {
"types": "./dist/react/index.d.ts",
"import": "./dist/react/redux-toolkit-react.modern.mjs",
"default": "./dist/react/cjs/index.js"
},
"./query": {
"types": "./dist/query/index.d.ts",
"import": "./dist/query/rtk-query.modern.mjs",
"default": "./dist/query/cjs/index.js"
},
"./query/react": {
"types": "./dist/query/react/index.d.ts",
"import": "./dist/query/react/rtk-query-react.modern.mjs",
"default": "./dist/query/react/cjs/index.js"
}
},
"devDependencies": {
"@arethetypeswrong/cli": "^0.13.5",
"@babel/core": "^7.24.8",
"@babel/helper-module-imports": "^7.24.7",
"@microsoft/api-extractor": "^7.13.2",
"@phryneas/ts-version": "^1.0.2",
"@size-limit/file": "^11.0.1",
"@size-limit/webpack": "^11.0.1",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^13.1.5",
"@types/babel__core": "^7.20.5",
"@types/babel__helper-module-imports": "^7.18.3",
"@types/json-stringify-safe": "^5.0.0",
"@types/nanoid": "^2.1.0",
"@types/node": "^20.11.0",
"@types/query-string": "^6.3.0",
"@types/react": "^18.0.12",
"@types/react-dom": "^18.0.5",
"@types/yargs": "^16.0.1",
"@typescript-eslint/eslint-plugin": "^6",
"@typescript-eslint/parser": "^6",
"axios": "^0.19.2",
"console-testing-library": "patch:console-testing-library@npm%3A0.6.1#~/.yarn/patches/console-testing-library-npm-0.6.1-4d9957d402.patch",
"esbuild": "^0.23.0",
"esbuild-extra": "^0.4.0",
"eslint": "^7.25.0",
"eslint-config-prettier": "^9.1.0",
"eslint-config-react-app": "^7.0.1",
"eslint-plugin-flowtype": "^5.7.2",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-prettier": "^5.1.3",
"eslint-plugin-react": "^7.23.2",
"eslint-plugin-react-hooks": "^4.2.0",
"fs-extra": "^9.1.0",
"invariant": "^2.2.4",
"jsdom": "^21.0.0",
"json-stringify-safe": "^5.0.1",
"msw": "^2.1.4",
"node-fetch": "^3.3.2",
"prettier": "^3.2.5",
"query-string": "^7.0.1",
"rimraf": "^3.0.2",
"size-limit": "^11.0.1",
"tslib": "^1.10.0",
"tsup": "^8.2.3",
"tsx": "^4.16.2",
"typescript": "^5.4.5",
"vite-tsconfig-paths": "^4.3.1",
"vitest": "^1.6.0",
"yargs": "^15.3.1"
},
"scripts": {
"clean": "rimraf dist",
"run-build": "tsup",
"build": "yarn clean && yarn run-build && tsx scripts/fixUniqueSymbolExports.mts",
"build-only": "yarn clean && yarn run-build",
"format": "prettier --write \"(src|examples)/**/*.{ts,tsx}\" \"**/*.md\"",
"format:check": "prettier --list-different \"(src|examples)/**/*.{ts,tsx}\" \"docs/*/**.md\"",
"lint": "eslint src examples",
"test": "vitest --typecheck --run ",
"test:watch": "vitest --watch",
"type-tests": "yarn tsc -p tsconfig.test.json --noEmit",
"prepack": "yarn build",
"size": "size-limit"
},
"files": [
"dist/",
"src/",
"query",
"react"
],
"dependencies": {
"immer": "^10.0.3",
"redux": "^5.0.1",
"redux-thunk": "^3.1.0",
"reselect": "^5.1.0"
},
"peerDependencies": {
"react": "^16.9.0 || ^17.0.0 || ^18",
"react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0"
},
"peerDependenciesMeta": {
"react": {
"optional": true
},
"react-redux": {
"optional": true
}
},
"sideEffects": false,
"bugs": {
"url": "https://github.com/reduxjs/redux-toolkit/issues"
},
"homepage": "https://redux-toolkit.js.org"
}

20
node_modules/@reduxjs/toolkit/query/package.json generated vendored Normal file
View File

@@ -0,0 +1,20 @@
{
"name": "@reduxjs/toolkit-query",
"version": "1.0.0",
"description": "",
"type": "module",
"module": "../dist/query/rtk-query.legacy-esm.js",
"main": "../dist/query/cjs/index.js",
"types": "./../dist/query/index.d.ts",
"exports": {
"./package.json": "./package.json",
".": {
"types": "./../dist/query/index.d.ts",
"import": "./../dist/query/rtk-query.modern.mjs",
"default": "./../dist/query/cjs/index.js"
}
},
"author": "Mark Erikson <mark@isquaredsoftware.com>",
"license": "MIT",
"sideEffects": false
}

20
node_modules/@reduxjs/toolkit/query/react/package.json generated vendored Normal file
View File

@@ -0,0 +1,20 @@
{
"name": "@reduxjs/toolkit-query-react",
"version": "1.0.0",
"description": "",
"type": "module",
"module": "../../dist/query/react/rtk-query-react.legacy-esm.js",
"main": "../../dist/query/react/cjs/index.js",
"types": "./../../dist/query/react/index.d.ts",
"exports": {
"./package.json": "./package.json",
".": {
"types": "./../../dist/query/react/index.d.ts",
"import": "./../../dist/query/react/rtk-query-react.modern.mjs",
"default": "./../../dist/query/react/cjs/index.js"
}
},
"author": "Mark Erikson <mark@isquaredsoftware.com>",
"license": "MIT",
"sideEffects": false
}

20
node_modules/@reduxjs/toolkit/react/package.json generated vendored Normal file
View File

@@ -0,0 +1,20 @@
{
"name": "@reduxjs/toolkit-react",
"version": "1.0.0",
"description": "",
"type": "module",
"module": "../dist/react/redux-toolkit-react.legacy-esm.js",
"main": "../dist/react/cjs/index.js",
"types": "./../dist/react/index.d.ts",
"exports": {
"./package.json": "./package.json",
".": {
"types": "./../dist/react/index.d.ts",
"import": "./../dist/react/redux-toolkit-react.modern.mjs",
"default": "./../dist/react/cjs/index.js"
}
},
"author": "Mark Erikson <mark@isquaredsoftware.com>",
"license": "MIT",
"sideEffects": false
}

View File

@@ -0,0 +1,34 @@
import type { Middleware } from 'redux'
import { isActionCreator as isRTKAction } from './createAction'
export interface ActionCreatorInvariantMiddlewareOptions {
/**
* The function to identify whether a value is an action creator.
* The default checks for a function with a static type property and match method.
*/
isActionCreator?: (action: unknown) => action is Function & { type?: unknown }
}
export function getMessage(type?: unknown) {
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.`
}
export function createActionCreatorInvariantMiddleware(
options: ActionCreatorInvariantMiddlewareOptions = {},
): Middleware {
if (process.env.NODE_ENV === 'production') {
return () => (next) => (action) => next(action)
}
const { isActionCreator = isRTKAction } = options
return () => (next) => (action) => {
if (isActionCreator(action)) {
console.warn(getMessage(action.type))
}
return next(action)
}
}

132
node_modules/@reduxjs/toolkit/src/autoBatchEnhancer.ts generated vendored Normal file
View File

@@ -0,0 +1,132 @@
import type { StoreEnhancer } from 'redux'
export const SHOULD_AUTOBATCH = 'RTK_autoBatch'
export const prepareAutoBatched =
<T>() =>
(payload: T): { payload: T; meta: unknown } => ({
payload,
meta: { [SHOULD_AUTOBATCH]: true },
})
const createQueueWithTimer = (timeout: number) => {
return (notify: () => void) => {
setTimeout(notify, timeout)
}
}
// requestAnimationFrame won't exist in SSR environments.
// Fall back to a vague approximation just to keep from erroring.
const rAF =
typeof window !== 'undefined' && window.requestAnimationFrame
? window.requestAnimationFrame
: createQueueWithTimer(10)
export type AutoBatchOptions =
| { type: 'tick' }
| { type: 'timer'; timeout: number }
| { type: 'raf' }
| { type: 'callback'; queueNotification: (notify: () => void) => void }
/**
* A Redux store enhancer that watches for "low-priority" actions, and delays
* notifying subscribers until either the queued callback executes or the
* next "standard-priority" action is dispatched.
*
* This allows dispatching multiple "low-priority" actions in a row with only
* a single subscriber notification to the UI after the sequence of actions
* is finished, thus improving UI re-render performance.
*
* Watches for actions with the `action.meta[SHOULD_AUTOBATCH]` attribute.
* This can be added to `action.meta` manually, or by using the
* `prepareAutoBatched` helper.
*
* By default, it will queue a notification for the end of the event loop tick.
* However, you can pass several other options to configure the behavior:
* - `{type: 'tick'}`: queues using `queueMicrotask`
* - `{type: 'timer', timeout: number}`: queues using `setTimeout`
* - `{type: 'raf'}`: queues using `requestAnimationFrame` (default)
* - `{type: 'callback', queueNotification: (notify: () => void) => void}`: lets you provide your own callback
*
*
*/
export const autoBatchEnhancer =
(options: AutoBatchOptions = { type: 'raf' }): StoreEnhancer =>
(next) =>
(...args) => {
const store = next(...args)
let notifying = true
let shouldNotifyAtEndOfTick = false
let notificationQueued = false
const listeners = new Set<() => void>()
const queueCallback =
options.type === 'tick'
? queueMicrotask
: options.type === 'raf'
? rAF
: options.type === 'callback'
? options.queueNotification
: createQueueWithTimer(options.timeout)
const notifyListeners = () => {
// We're running at the end of the event loop tick.
// Run the real listener callbacks to actually update the UI.
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(listener: () => void) {
// Each wrapped listener will only call the real listener if
// the `notifying` flag is currently active when it's called.
// This lets the base store work as normal, while the actual UI
// update becomes controlled by this enhancer.
const wrappedListener: typeof listener = () => notifying && listener()
const unsubscribe = store.subscribe(wrappedListener)
listeners.add(listener)
return () => {
unsubscribe()
listeners.delete(listener)
}
},
// Override the base `store.dispatch` method so that we can check actions
// for the `shouldAutoBatch` flag and determine if batching is active
dispatch(action: any) {
try {
// If the action does _not_ have the `shouldAutoBatch` flag,
// we resume/continue normal notify-after-each-dispatch behavior
notifying = !action?.meta?.[SHOULD_AUTOBATCH]
// If a `notifyListeners` microtask was queued, you can't cancel it.
// Instead, we set a flag so that it's a no-op when it does run
shouldNotifyAtEndOfTick = !notifying
if (shouldNotifyAtEndOfTick) {
// We've seen at least 1 action with `SHOULD_AUTOBATCH`. Try to queue
// a microtask to notify listeners at the end of the event loop tick.
// Make sure we only enqueue this _once_ per tick.
if (!notificationQueued) {
notificationQueued = true
queueCallback(notifyListeners)
}
}
// Go ahead and process the action as usual, including reducers.
// If normal notification behavior is enabled, the store will notify
// all of its own listeners, and the wrapper callbacks above will
// see `notifying` is true and pass on to the real listener callbacks.
// If we're "batching" behavior, then the wrapped callbacks will
// bail out, causing the base store notification behavior to be no-ops.
return store.dispatch(action)
} finally {
// Assume we're back to normal behavior after each action
notifying = true
}
},
})
}

433
node_modules/@reduxjs/toolkit/src/combineSlices.ts generated vendored Normal file
View File

@@ -0,0 +1,433 @@
import type { Reducer, StateFromReducersMapObject, UnknownAction } from 'redux'
import { combineReducers } from 'redux'
import { nanoid } from './nanoid'
import type {
Id,
NonUndefined,
Tail,
UnionToIntersection,
WithOptionalProp,
} from './tsHelpers'
import { emplace } from './utils'
type SliceLike<ReducerPath extends string, State> = {
reducerPath: ReducerPath
reducer: Reducer<State>
}
type AnySliceLike = SliceLike<string, any>
type SliceLikeReducerPath<A extends AnySliceLike> =
A extends SliceLike<infer ReducerPath, any> ? ReducerPath : never
type SliceLikeState<A extends AnySliceLike> =
A extends SliceLike<any, infer State> ? State : never
export type WithSlice<A extends AnySliceLike> = {
[Path in SliceLikeReducerPath<A>]: SliceLikeState<A>
}
type ReducerMap = Record<string, Reducer>
type ExistingSliceLike<DeclaredState> = {
[ReducerPath in keyof DeclaredState]: SliceLike<
ReducerPath & string,
NonUndefined<DeclaredState[ReducerPath]>
>
}[keyof DeclaredState]
export type InjectConfig = {
/**
* Allow replacing reducer with a different reference. Normally, an error will be thrown if a different reducer instance to the one already injected is used.
*/
overrideExisting?: boolean
}
/**
* A reducer that allows for slices/reducers to be injected after initialisation.
*/
export interface CombinedSliceReducer<
InitialState,
DeclaredState = InitialState,
> extends Reducer<DeclaredState, UnknownAction, Partial<DeclaredState>> {
/**
* Provide a type for slices that will be injected lazily.
*
* One way to do this would be with interface merging:
* ```ts
*
* export interface LazyLoadedSlices {}
*
* export const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
*
* // elsewhere
*
* declare module './reducer' {
* export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
* }
*
* const withBoolean = rootReducer.inject(booleanSlice);
*
* // elsewhere again
*
* declare module './reducer' {
* export interface LazyLoadedSlices {
* customName: CustomState
* }
* }
*
* const withCustom = rootReducer.inject({ reducerPath: "customName", reducer: customSlice.reducer })
* ```
*/
withLazyLoadedSlices<Lazy = {}>(): CombinedSliceReducer<
InitialState,
Id<DeclaredState & Partial<Lazy>>
>
/**
* Inject a slice.
*
* Accepts an individual slice, RTKQ API instance, or a "slice-like" { reducerPath, reducer } object.
*
* ```ts
* rootReducer.inject(booleanSlice)
* rootReducer.inject(baseApi)
* rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })
* ```
*
*/
inject<Sl extends Id<ExistingSliceLike<DeclaredState>>>(
slice: Sl,
config?: InjectConfig,
): CombinedSliceReducer<InitialState, Id<DeclaredState & WithSlice<Sl>>>
/**
* Inject a slice.
*
* Accepts an individual slice, RTKQ API instance, or a "slice-like" { reducerPath, reducer } object.
*
* ```ts
* rootReducer.inject(booleanSlice)
* rootReducer.inject(baseApi)
* rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })
* ```
*
*/
inject<ReducerPath extends string, State>(
slice: SliceLike<
ReducerPath,
State & (ReducerPath extends keyof DeclaredState ? never : State)
>,
config?: InjectConfig,
): CombinedSliceReducer<
InitialState,
Id<DeclaredState & WithSlice<SliceLike<ReducerPath, State>>>
>
/**
* Create a selector that guarantees that the slices injected will have a defined value when selector is run.
*
* ```ts
* const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
* // ^? boolean | undefined
*
* const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
* // if action hasn't been dispatched since slice was injected, this would usually be undefined
* // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
* return state.boolean;
* // ^? boolean
* })
* ```
*
* If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.
*
* ```ts
*
* export interface LazyLoadedSlices {};
*
* export const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
*
* export const rootReducer = combineSlices({ inner: innerReducer });
*
* export type RootState = ReturnType<typeof rootReducer>;
*
* // elsewhere
*
* declare module "./reducer.ts" {
* export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
* }
*
* const withBool = innerReducer.inject(booleanSlice);
*
* const selectBoolean = withBool.selector(
* (state) => state.boolean,
* (rootState: RootState) => state.inner
* );
* // now expects to be passed RootState instead of innerReducer state
*
* ```
*
* Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
*
* ```ts
* const injectedReducer = rootReducer.inject(booleanSlice);
* const selectBoolean = injectedReducer.selector((state) => {
* console.log(injectedReducer.selector.original(state).boolean) // possibly undefined
* return state.boolean
* })
* ```
*/
selector: {
/**
* Create a selector that guarantees that the slices injected will have a defined value when selector is run.
*
* ```ts
* const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
* // ^? boolean | undefined
*
* const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
* // if action hasn't been dispatched since slice was injected, this would usually be undefined
* // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
* return state.boolean;
* // ^? boolean
* })
* ```
*
* Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
*
* ```ts
* const injectedReducer = rootReducer.inject(booleanSlice);
* const selectBoolean = injectedReducer.selector((state) => {
* console.log(injectedReducer.selector.original(state).boolean) // undefined
* return state.boolean
* })
* ```
*/
<Selector extends (state: DeclaredState, ...args: any[]) => unknown>(
selectorFn: Selector,
): (
state: WithOptionalProp<
Parameters<Selector>[0],
Exclude<keyof DeclaredState, keyof InitialState>
>,
...args: Tail<Parameters<Selector>>
) => ReturnType<Selector>
/**
* Create a selector that guarantees that the slices injected will have a defined value when selector is run.
*
* ```ts
* const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
* // ^? boolean | undefined
*
* const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
* // if action hasn't been dispatched since slice was injected, this would usually be undefined
* // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
* return state.boolean;
* // ^? boolean
* })
* ```
*
* If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.
*
* ```ts
*
* interface LazyLoadedSlices {};
*
* const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
*
* const rootReducer = combineSlices({ inner: innerReducer });
*
* type RootState = ReturnType<typeof rootReducer>;
*
* // elsewhere
*
* declare module "./reducer.ts" {
* interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
* }
*
* const withBool = innerReducer.inject(booleanSlice);
*
* const selectBoolean = withBool.selector(
* (state) => state.boolean,
* (rootState: RootState) => state.inner
* );
* // now expects to be passed RootState instead of innerReducer state
*
* ```
*
* Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
*
* ```ts
* const injectedReducer = rootReducer.inject(booleanSlice);
* const selectBoolean = injectedReducer.selector((state) => {
* console.log(injectedReducer.selector.original(state).boolean) // possibly undefined
* return state.boolean
* })
* ```
*/
<
Selector extends (state: DeclaredState, ...args: any[]) => unknown,
RootState,
>(
selectorFn: Selector,
selectState: (
rootState: RootState,
...args: Tail<Parameters<Selector>>
) => WithOptionalProp<
Parameters<Selector>[0],
Exclude<keyof DeclaredState, keyof InitialState>
>,
): (
state: RootState,
...args: Tail<Parameters<Selector>>
) => ReturnType<Selector>
/**
* Returns the unproxied state. Useful for debugging.
* @param state state Proxy, that ensures injected reducers have value
* @returns original, unproxied state
* @throws if value passed is not a state Proxy
*/
original: (state: DeclaredState) => InitialState & Partial<DeclaredState>
}
}
type InitialState<Slices extends Array<AnySliceLike | ReducerMap>> =
UnionToIntersection<
Slices[number] extends infer Slice
? Slice extends AnySliceLike
? WithSlice<Slice>
: StateFromReducersMapObject<Slice>
: never
>
const isSliceLike = (
maybeSliceLike: AnySliceLike | ReducerMap,
): maybeSliceLike is AnySliceLike =>
'reducerPath' in maybeSliceLike &&
typeof maybeSliceLike.reducerPath === 'string'
const getReducers = (slices: Array<AnySliceLike | ReducerMap>) =>
slices.flatMap((sliceOrMap) =>
isSliceLike(sliceOrMap)
? [[sliceOrMap.reducerPath, sliceOrMap.reducer] as const]
: Object.entries(sliceOrMap),
)
const ORIGINAL_STATE = Symbol.for('rtk-state-proxy-original')
const isStateProxy = (value: any) => !!value && !!value[ORIGINAL_STATE]
const stateProxyMap = new WeakMap<object, object>()
const createStateProxy = <State extends object>(
state: State,
reducerMap: Partial<Record<string, Reducer>>,
) =>
emplace(stateProxyMap, state, {
insert: () =>
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 reducer = reducerMap[prop.toString()]
if (reducer) {
// ensure action type is random, to prevent reducer treating it differently
const reducerResult = reducer(undefined, { type: nanoid() })
if (typeof reducerResult === 'undefined') {
throw new Error(
`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.`,
)
}
return reducerResult
}
}
return result
},
}),
}) as State
const original = (state: any) => {
if (!isStateProxy(state)) {
throw new Error('original must be used on state Proxy')
}
return state[ORIGINAL_STATE]
}
const noopReducer: Reducer<Record<string, any>> = (state = {}) => state
export function combineSlices<Slices extends Array<AnySliceLike | ReducerMap>>(
...slices: Slices
): CombinedSliceReducer<Id<InitialState<Slices>>> {
const reducerMap = Object.fromEntries<Reducer>(getReducers(slices))
const getReducer = () =>
Object.keys(reducerMap).length ? combineReducers(reducerMap) : noopReducer
let reducer = getReducer()
function combinedReducer(
state: Record<string, unknown>,
action: UnknownAction,
) {
return reducer(state, action)
}
combinedReducer.withLazyLoadedSlices = () => combinedReducer
const inject = (
slice: AnySliceLike,
config: InjectConfig = {},
): typeof combinedReducer => {
const { reducerPath, reducer: reducerToInject } = slice
const currentReducer = reducerMap[reducerPath]
if (
!config.overrideExisting &&
currentReducer &&
currentReducer !== reducerToInject
) {
if (
typeof process !== 'undefined' &&
process.env.NODE_ENV === 'development'
) {
console.error(
`called \`inject\` to override already-existing reducer ${reducerPath} without specifying \`overrideExisting: true\``,
)
}
return combinedReducer
}
reducerMap[reducerPath] = reducerToInject
reducer = getReducer()
return combinedReducer
}
const selector = Object.assign(
function makeSelector<State extends object, RootState, Args extends any[]>(
selectorFn: (state: State, ...args: Args) => any,
selectState?: (rootState: RootState, ...args: Args) => State,
) {
return function selector(state: State, ...args: Args) {
return selectorFn(
createStateProxy(
selectState ? selectState(state as any, ...args) : state,
reducerMap,
),
...args,
)
}
},
{ original },
)
return Object.assign(combinedReducer, { inject, selector }) as any
}

230
node_modules/@reduxjs/toolkit/src/configureStore.ts generated vendored Normal file
View File

@@ -0,0 +1,230 @@
import type {
Reducer,
ReducersMapObject,
Middleware,
Action,
StoreEnhancer,
Store,
UnknownAction,
} from 'redux'
import {
applyMiddleware,
createStore,
compose,
combineReducers,
isPlainObject,
} from 'redux'
import type { DevToolsEnhancerOptions as DevToolsOptions } from './devtoolsExtension'
import { composeWithDevTools } from './devtoolsExtension'
import type {
ThunkMiddlewareFor,
GetDefaultMiddleware,
} from './getDefaultMiddleware'
import { buildGetDefaultMiddleware } from './getDefaultMiddleware'
import type {
ExtractDispatchExtensions,
ExtractStoreExtensions,
ExtractStateExtensions,
UnknownIfNonSpecific,
} from './tsHelpers'
import type { Tuple } from './utils'
import type { GetDefaultEnhancers } from './getDefaultEnhancers'
import { buildGetDefaultEnhancers } from './getDefaultEnhancers'
/**
* Options for `configureStore()`.
*
* @public
*/
export interface ConfigureStoreOptions<
S = any,
A extends Action = UnknownAction,
M extends Tuple<Middlewares<S>> = Tuple<Middlewares<S>>,
E extends Tuple<Enhancers> = Tuple<Enhancers>,
P = S,
> {
/**
* A single reducer function that will be used as the root reducer, or an
* object of slice reducers that will be passed to `combineReducers()`.
*/
reducer: Reducer<S, A, P> | ReducersMapObject<S, A, P>
/**
* An array of Redux middleware to install, or a callback receiving `getDefaultMiddleware` and returning a Tuple of middleware.
* If not supplied, defaults to the set of middleware returned by `getDefaultMiddleware()`.
*
* @example `middleware: (gDM) => gDM().concat(logger, apiMiddleware, yourCustomMiddleware)`
* @see https://redux-toolkit.js.org/api/getDefaultMiddleware#intended-usage
*/
middleware?: (getDefaultMiddleware: GetDefaultMiddleware<S>) => M
/**
* Whether to enable Redux DevTools integration. Defaults to `true`.
*
* Additional configuration can be done by passing Redux DevTools options
*/
devTools?: boolean | DevToolsOptions
/**
* The initial state, same as Redux's createStore.
* You may optionally specify it to hydrate the state
* from the server in universal apps, or to restore a previously serialized
* user session. If you use `combineReducers()` to produce the root reducer
* function (either directly or indirectly by passing an object as `reducer`),
* this must be an object with the same shape as the reducer map keys.
*/
// we infer here, and instead complain if the reducer doesn't match
preloadedState?: P
/**
* The store enhancers to apply. See Redux's `createStore()`.
* All enhancers will be included before the DevTools Extension enhancer.
* If you need to customize the order of enhancers, supply a callback
* function that will receive a `getDefaultEnhancers` function that returns a Tuple,
* and should return a Tuple of enhancers (such as `getDefaultEnhancers().concat(offline)`).
* If you only need to add middleware, you can use the `middleware` parameter instead.
*/
enhancers?: (getDefaultEnhancers: GetDefaultEnhancers<M>) => E
}
export type Middlewares<S> = ReadonlyArray<Middleware<{}, S>>
type Enhancers = ReadonlyArray<StoreEnhancer>
/**
* A Redux store returned by `configureStore()`. Supports dispatching
* side-effectful _thunks_ in addition to plain actions.
*
* @public
*/
export type EnhancedStore<
S = any,
A extends Action = UnknownAction,
E extends Enhancers = Enhancers,
> = ExtractStoreExtensions<E> &
Store<S, A, UnknownIfNonSpecific<ExtractStateExtensions<E>>>
/**
* A friendly abstraction over the standard Redux `createStore()` function.
*
* @param options The store configuration.
* @returns A configured Redux store.
*
* @public
*/
export function configureStore<
S = any,
A extends Action = UnknownAction,
M extends Tuple<Middlewares<S>> = Tuple<[ThunkMiddlewareFor<S>]>,
E extends Tuple<Enhancers> = Tuple<
[StoreEnhancer<{ dispatch: ExtractDispatchExtensions<M> }>, StoreEnhancer]
>,
P = S,
>(options: ConfigureStoreOptions<S, A, M, E, P>): EnhancedStore<S, A, E> {
const getDefaultMiddleware = buildGetDefaultMiddleware<S>()
const {
reducer = undefined,
middleware,
devTools = true,
preloadedState = undefined,
enhancers = undefined,
} = options || {}
let rootReducer: Reducer<S, A, P>
if (typeof reducer === 'function') {
rootReducer = reducer
} else if (isPlainObject(reducer)) {
rootReducer = combineReducers(reducer) as unknown as Reducer<S, A, P>
} else {
throw new Error(
'`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers',
)
}
if (
process.env.NODE_ENV !== 'production' &&
middleware &&
typeof middleware !== 'function'
) {
throw new Error('`middleware` field must be a callback')
}
let finalMiddleware: Tuple<Middlewares<S>>
if (typeof middleware === 'function') {
finalMiddleware = middleware(getDefaultMiddleware)
if (
process.env.NODE_ENV !== 'production' &&
!Array.isArray(finalMiddleware)
) {
throw new Error(
'when using a middleware builder function, an array of middleware must be returned',
)
}
} else {
finalMiddleware = getDefaultMiddleware()
}
if (
process.env.NODE_ENV !== 'production' &&
finalMiddleware.some((item: any) => typeof item !== 'function')
) {
throw new Error(
'each middleware provided to configureStore must be a function',
)
}
let finalCompose = compose
if (devTools) {
finalCompose = composeWithDevTools({
// Enable capture of stack traces for dispatched Redux actions
trace: process.env.NODE_ENV !== 'production',
...(typeof devTools === 'object' && devTools),
})
}
const middlewareEnhancer = applyMiddleware(...finalMiddleware)
const getDefaultEnhancers = buildGetDefaultEnhancers<M>(middlewareEnhancer)
if (
process.env.NODE_ENV !== 'production' &&
enhancers &&
typeof enhancers !== 'function'
) {
throw new Error('`enhancers` field must be a callback')
}
let storeEnhancers =
typeof enhancers === 'function'
? enhancers(getDefaultEnhancers)
: getDefaultEnhancers()
if (process.env.NODE_ENV !== 'production' && !Array.isArray(storeEnhancers)) {
throw new Error('`enhancers` callback must return an array')
}
if (
process.env.NODE_ENV !== 'production' &&
storeEnhancers.some((item: any) => typeof item !== 'function')
) {
throw new Error(
'each enhancer provided to configureStore must be a function',
)
}
if (
process.env.NODE_ENV !== 'production' &&
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: StoreEnhancer<any> = finalCompose(...storeEnhancers)
return createStore(rootReducer, preloadedState as P, composedEnhancer)
}

324
node_modules/@reduxjs/toolkit/src/createAction.ts generated vendored Normal file
View File

@@ -0,0 +1,324 @@
import { isAction } from 'redux'
import type {
IsUnknownOrNonInferrable,
IfMaybeUndefined,
IfVoid,
IsAny,
} from './tsHelpers'
import { hasMatchFunction } from './tsHelpers'
/**
* An action with a string type and an associated payload. This is the
* type of action returned by `createAction()` action creators.
*
* @template P The type of the action's payload.
* @template T the type used for the action type.
* @template M The type of the action's meta (optional)
* @template E The type of the action's error (optional)
*
* @public
*/
export type PayloadAction<
P = void,
T extends string = string,
M = never,
E = never,
> = {
payload: P
type: T
} & ([M] extends [never]
? {}
: {
meta: M
}) &
([E] extends [never]
? {}
: {
error: E
})
/**
* A "prepare" method to be used as the second parameter of `createAction`.
* Takes any number of arguments and returns a Flux Standard Action without
* type (will be added later) that *must* contain a payload (might be undefined).
*
* @public
*/
export type PrepareAction<P> =
| ((...args: any[]) => { payload: P })
| ((...args: any[]) => { payload: P; meta: any })
| ((...args: any[]) => { payload: P; error: any })
| ((...args: any[]) => { payload: P; meta: any; error: any })
/**
* Internal version of `ActionCreatorWithPreparedPayload`. Not to be used externally.
*
* @internal
*/
export type _ActionCreatorWithPreparedPayload<
PA extends PrepareAction<any> | void,
T extends string = string,
> =
PA extends PrepareAction<infer P>
? ActionCreatorWithPreparedPayload<
Parameters<PA>,
P,
T,
ReturnType<PA> extends {
error: infer E
}
? E
: never,
ReturnType<PA> extends {
meta: infer M
}
? M
: never
>
: void
/**
* Basic type for all action creators.
*
* @inheritdoc {redux#ActionCreator}
*/
export type BaseActionCreator<P, T extends string, M = never, E = never> = {
type: T
match: (action: unknown) => action is PayloadAction<P, T, M, E>
}
/**
* An action creator that takes multiple arguments that are passed
* to a `PrepareAction` method to create the final Action.
* @typeParam Args arguments for the action creator function
* @typeParam P `payload` type
* @typeParam T `type` name
* @typeParam E optional `error` type
* @typeParam M optional `meta` type
*
* @inheritdoc {redux#ActionCreator}
*
* @public
*/
export interface ActionCreatorWithPreparedPayload<
Args extends unknown[],
P,
T extends string = string,
E = never,
M = never,
> extends BaseActionCreator<P, T, M, E> {
/**
* Calling this {@link redux#ActionCreator} with `Args` will return
* an Action with a payload of type `P` and (depending on the `PrepareAction`
* method used) a `meta`- and `error` property of types `M` and `E` respectively.
*/
(...args: Args): PayloadAction<P, T, M, E>
}
/**
* An action creator of type `T` that takes an optional payload of type `P`.
*
* @inheritdoc {redux#ActionCreator}
*
* @public
*/
export interface ActionCreatorWithOptionalPayload<P, T extends string = string>
extends BaseActionCreator<P, T> {
/**
* Calling this {@link redux#ActionCreator} with an argument will
* return a {@link PayloadAction} of type `T` with a payload of `P`.
* Calling it without an argument will return a PayloadAction with a payload of `undefined`.
*/
(payload?: P): PayloadAction<P, T>
}
/**
* An action creator of type `T` that takes no payload.
*
* @inheritdoc {redux#ActionCreator}
*
* @public
*/
export interface ActionCreatorWithoutPayload<T extends string = string>
extends BaseActionCreator<undefined, T> {
/**
* Calling this {@link redux#ActionCreator} will
* return a {@link PayloadAction} of type `T` with a payload of `undefined`
*/
(noArgument: void): PayloadAction<undefined, T>
}
/**
* An action creator of type `T` that requires a payload of type P.
*
* @inheritdoc {redux#ActionCreator}
*
* @public
*/
export interface ActionCreatorWithPayload<P, T extends string = string>
extends BaseActionCreator<P, T> {
/**
* Calling this {@link redux#ActionCreator} with an argument will
* return a {@link PayloadAction} of type `T` with a payload of `P`
*/
(payload: P): PayloadAction<P, T>
}
/**
* An action creator of type `T` whose `payload` type could not be inferred. Accepts everything as `payload`.
*
* @inheritdoc {redux#ActionCreator}
*
* @public
*/
export interface ActionCreatorWithNonInferrablePayload<
T extends string = string,
> extends BaseActionCreator<unknown, T> {
/**
* Calling this {@link redux#ActionCreator} with an argument will
* return a {@link PayloadAction} of type `T` with a payload
* of exactly the type of the argument.
*/
<PT extends unknown>(payload: PT): PayloadAction<PT, T>
}
/**
* An action creator that produces actions with a `payload` attribute.
*
* @typeParam P the `payload` type
* @typeParam T the `type` of the resulting action
* @typeParam PA if the resulting action is preprocessed by a `prepare` method, the signature of said method.
*
* @public
*/
export type PayloadActionCreator<
P = void,
T extends string = string,
PA extends PrepareAction<P> | void = void,
> = IfPrepareActionMethodProvided<
PA,
_ActionCreatorWithPreparedPayload<PA, T>,
// else
IsAny<
P,
ActionCreatorWithPayload<any, T>,
IsUnknownOrNonInferrable<
P,
ActionCreatorWithNonInferrablePayload<T>,
// else
IfVoid<
P,
ActionCreatorWithoutPayload<T>,
// else
IfMaybeUndefined<
P,
ActionCreatorWithOptionalPayload<P, T>,
// else
ActionCreatorWithPayload<P, T>
>
>
>
>
>
/**
* A utility function to create an action creator for the given action type
* string. The action creator accepts a single argument, which will be included
* in the action object as a field called payload. The action creator function
* will also have its toString() overridden so that it returns the action type.
*
* @param type The action type to use for created actions.
* @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
* If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
*
* @public
*/
export function createAction<P = void, T extends string = string>(
type: T,
): PayloadActionCreator<P, T>
/**
* A utility function to create an action creator for the given action type
* string. The action creator accepts a single argument, which will be included
* in the action object as a field called payload. The action creator function
* will also have its toString() overridden so that it returns the action type.
*
* @param type The action type to use for created actions.
* @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
* If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
*
* @public
*/
export function createAction<
PA extends PrepareAction<any>,
T extends string = string,
>(
type: T,
prepareAction: PA,
): PayloadActionCreator<ReturnType<PA>['payload'], T, PA>
export function createAction(type: string, prepareAction?: Function): any {
function actionCreator(...args: any[]) {
if (prepareAction) {
let prepared = prepareAction(...args)
if (!prepared) {
throw new Error('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: unknown): action is PayloadAction =>
isAction(action) && action.type === type
return actionCreator
}
/**
* Returns true if value is an RTK-like action creator, with a static type property and match method.
*/
export function isActionCreator(
action: unknown,
): action is BaseActionCreator<unknown, string> & Function {
return (
typeof action === 'function' &&
'type' in action &&
// hasMatchFunction only wants Matchers but I don't see the point in rewriting it
hasMatchFunction(action as any)
)
}
/**
* Returns true if value is an action with a string type and valid Flux Standard Action keys.
*/
export function isFSA(action: unknown): action is {
type: string
payload?: unknown
error?: unknown
meta?: unknown
} {
return isAction(action) && Object.keys(action).every(isValidKey)
}
function isValidKey(key: string) {
return ['type', 'payload', 'error', 'meta'].indexOf(key) > -1
}
// helper types for more readable typings
type IfPrepareActionMethodProvided<
PA extends PrepareAction<any> | void,
True,
False,
> = PA extends (...args: any[]) => any ? True : False

746
node_modules/@reduxjs/toolkit/src/createAsyncThunk.ts generated vendored Normal file
View File

@@ -0,0 +1,746 @@
import type { Dispatch, UnknownAction } from 'redux'
import type { ThunkDispatch } from 'redux-thunk'
import type { ActionCreatorWithPreparedPayload } from './createAction'
import { createAction } from './createAction'
import { isAnyOf } from './matchers'
import { nanoid } from './nanoid'
import type {
FallbackIfUnknown,
Id,
IsAny,
IsUnknown,
SafePromise,
} from './tsHelpers'
export type BaseThunkAPI<
S,
E,
D extends Dispatch = Dispatch,
RejectedValue = unknown,
RejectedMeta = unknown,
FulfilledMeta = unknown,
> = {
dispatch: D
getState: () => S
extra: E
requestId: string
signal: AbortSignal
abort: (reason?: string) => void
rejectWithValue: IsUnknown<
RejectedMeta,
(value: RejectedValue) => RejectWithValue<RejectedValue, RejectedMeta>,
(
value: RejectedValue,
meta: RejectedMeta,
) => RejectWithValue<RejectedValue, RejectedMeta>
>
fulfillWithValue: IsUnknown<
FulfilledMeta,
<FulfilledValue>(value: FulfilledValue) => FulfilledValue,
<FulfilledValue>(
value: FulfilledValue,
meta: FulfilledMeta,
) => FulfillWithMeta<FulfilledValue, FulfilledMeta>
>
}
/**
* @public
*/
export interface SerializedError {
name?: string
message?: string
stack?: string
code?: string
}
const commonProperties: Array<keyof SerializedError> = [
'name',
'message',
'stack',
'code',
]
class RejectWithValue<Payload, RejectedMeta> {
/*
type-only property to distinguish between RejectWithValue and FulfillWithMeta
does not exist at runtime
*/
private readonly _type!: 'RejectWithValue'
constructor(
public readonly payload: Payload,
public readonly meta: RejectedMeta,
) {}
}
class FulfillWithMeta<Payload, FulfilledMeta> {
/*
type-only property to distinguish between RejectWithValue and FulfillWithMeta
does not exist at runtime
*/
private readonly _type!: 'FulfillWithMeta'
constructor(
public readonly payload: Payload,
public readonly meta: FulfilledMeta,
) {}
}
/**
* Serializes an error into a plain object.
* Reworked from https://github.com/sindresorhus/serialize-error
*
* @public
*/
export const miniSerializeError = (value: any): SerializedError => {
if (typeof value === 'object' && value !== null) {
const simpleError: SerializedError = {}
for (const property of commonProperties) {
if (typeof value[property] === 'string') {
simpleError[property] = value[property]
}
}
return simpleError
}
return { message: String(value) }
}
export type AsyncThunkConfig = {
state?: unknown
dispatch?: ThunkDispatch<unknown, unknown, UnknownAction>
extra?: unknown
rejectValue?: unknown
serializedErrorType?: unknown
pendingMeta?: unknown
fulfilledMeta?: unknown
rejectedMeta?: unknown
}
export type GetState<ThunkApiConfig> = ThunkApiConfig extends {
state: infer State
}
? State
: unknown
type GetExtra<ThunkApiConfig> = ThunkApiConfig extends { extra: infer Extra }
? Extra
: unknown
type GetDispatch<ThunkApiConfig> = ThunkApiConfig extends {
dispatch: infer Dispatch
}
? FallbackIfUnknown<
Dispatch,
ThunkDispatch<
GetState<ThunkApiConfig>,
GetExtra<ThunkApiConfig>,
UnknownAction
>
>
: ThunkDispatch<
GetState<ThunkApiConfig>,
GetExtra<ThunkApiConfig>,
UnknownAction
>
export type GetThunkAPI<ThunkApiConfig> = BaseThunkAPI<
GetState<ThunkApiConfig>,
GetExtra<ThunkApiConfig>,
GetDispatch<ThunkApiConfig>,
GetRejectValue<ThunkApiConfig>,
GetRejectedMeta<ThunkApiConfig>,
GetFulfilledMeta<ThunkApiConfig>
>
type GetRejectValue<ThunkApiConfig> = ThunkApiConfig extends {
rejectValue: infer RejectValue
}
? RejectValue
: unknown
type GetPendingMeta<ThunkApiConfig> = ThunkApiConfig extends {
pendingMeta: infer PendingMeta
}
? PendingMeta
: unknown
type GetFulfilledMeta<ThunkApiConfig> = ThunkApiConfig extends {
fulfilledMeta: infer FulfilledMeta
}
? FulfilledMeta
: unknown
type GetRejectedMeta<ThunkApiConfig> = ThunkApiConfig extends {
rejectedMeta: infer RejectedMeta
}
? RejectedMeta
: unknown
type GetSerializedErrorType<ThunkApiConfig> = ThunkApiConfig extends {
serializedErrorType: infer GetSerializedErrorType
}
? GetSerializedErrorType
: SerializedError
type MaybePromise<T> = T | Promise<T> | (T extends any ? Promise<T> : never)
/**
* A type describing the return value of the `payloadCreator` argument to `createAsyncThunk`.
* Might be useful for wrapping `createAsyncThunk` in custom abstractions.
*
* @public
*/
export type AsyncThunkPayloadCreatorReturnValue<
Returned,
ThunkApiConfig extends AsyncThunkConfig,
> = MaybePromise<
| IsUnknown<
GetFulfilledMeta<ThunkApiConfig>,
Returned,
FulfillWithMeta<Returned, GetFulfilledMeta<ThunkApiConfig>>
>
| RejectWithValue<
GetRejectValue<ThunkApiConfig>,
GetRejectedMeta<ThunkApiConfig>
>
>
/**
* A type describing the `payloadCreator` argument to `createAsyncThunk`.
* Might be useful for wrapping `createAsyncThunk` in custom abstractions.
*
* @public
*/
export type AsyncThunkPayloadCreator<
Returned,
ThunkArg = void,
ThunkApiConfig extends AsyncThunkConfig = {},
> = (
arg: ThunkArg,
thunkAPI: GetThunkAPI<ThunkApiConfig>,
) => AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig>
/**
* A ThunkAction created by `createAsyncThunk`.
* Dispatching it returns a Promise for either a
* fulfilled or rejected action.
* Also, the returned value contains an `abort()` method
* that allows the asyncAction to be cancelled from the outside.
*
* @public
*/
export type AsyncThunkAction<
Returned,
ThunkArg,
ThunkApiConfig extends AsyncThunkConfig,
> = (
dispatch: NonNullable<GetDispatch<ThunkApiConfig>>,
getState: () => GetState<ThunkApiConfig>,
extra: GetExtra<ThunkApiConfig>,
) => SafePromise<
| ReturnType<AsyncThunkFulfilledActionCreator<Returned, ThunkArg>>
| ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>>
> & {
abort: (reason?: string) => void
requestId: string
arg: ThunkArg
unwrap: () => Promise<Returned>
}
type AsyncThunkActionCreator<
Returned,
ThunkArg,
ThunkApiConfig extends AsyncThunkConfig,
> = IsAny<
ThunkArg,
// any handling
(arg: ThunkArg) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,
// unknown handling
unknown extends ThunkArg
? (arg: ThunkArg) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument not specified or specified as void or undefined
: [ThunkArg] extends [void] | [undefined]
? () => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains void
: [void] extends [ThunkArg] // make optional
? (
arg?: ThunkArg,
) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains undefined
: [undefined] extends [ThunkArg]
? WithStrictNullChecks<
// with strict nullChecks: make optional
(
arg?: ThunkArg,
) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,
// without strict null checks this will match everything, so don't make it optional
(
arg: ThunkArg,
) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>
> // default case: normal argument
: (
arg: ThunkArg,
) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>
>
/**
* Options object for `createAsyncThunk`.
*
* @public
*/
export type AsyncThunkOptions<
ThunkArg = void,
ThunkApiConfig extends AsyncThunkConfig = {},
> = {
/**
* A method to control whether the asyncThunk should be executed. Has access to the
* `arg`, `api.getState()` and `api.extra` arguments.
*
* @returns `false` if it should be skipped
*/
condition?(
arg: ThunkArg,
api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>,
): MaybePromise<boolean | undefined>
/**
* If `condition` returns `false`, the asyncThunk will be skipped.
* This option allows you to control whether a `rejected` action with `meta.condition == false`
* will be dispatched or not.
*
* @default `false`
*/
dispatchConditionRejection?: boolean
serializeError?: (x: unknown) => GetSerializedErrorType<ThunkApiConfig>
/**
* A function to use when generating the `requestId` for the request sequence.
*
* @default `nanoid`
*/
idGenerator?: (arg: ThunkArg) => string
} & IsUnknown<
GetPendingMeta<ThunkApiConfig>,
{
/**
* A method to generate additional properties to be added to `meta` of the pending action.
*
* Using this optional overload will not modify the types correctly, this overload is only in place to support JavaScript users.
* Please use the `ThunkApiConfig` parameter `pendingMeta` to get access to a correctly typed overload
*/
getPendingMeta?(
base: {
arg: ThunkArg
requestId: string
},
api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>,
): GetPendingMeta<ThunkApiConfig>
},
{
/**
* A method to generate additional properties to be added to `meta` of the pending action.
*/
getPendingMeta(
base: {
arg: ThunkArg
requestId: string
},
api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>,
): GetPendingMeta<ThunkApiConfig>
}
>
export type AsyncThunkPendingActionCreator<
ThunkArg,
ThunkApiConfig = {},
> = ActionCreatorWithPreparedPayload<
[string, ThunkArg, GetPendingMeta<ThunkApiConfig>?],
undefined,
string,
never,
{
arg: ThunkArg
requestId: string
requestStatus: 'pending'
} & GetPendingMeta<ThunkApiConfig>
>
export type AsyncThunkRejectedActionCreator<
ThunkArg,
ThunkApiConfig = {},
> = ActionCreatorWithPreparedPayload<
[
Error | null,
string,
ThunkArg,
GetRejectValue<ThunkApiConfig>?,
GetRejectedMeta<ThunkApiConfig>?,
],
GetRejectValue<ThunkApiConfig> | undefined,
string,
GetSerializedErrorType<ThunkApiConfig>,
{
arg: ThunkArg
requestId: string
requestStatus: 'rejected'
aborted: boolean
condition: boolean
} & (
| ({ rejectedWithValue: false } & {
[K in keyof GetRejectedMeta<ThunkApiConfig>]?: undefined
})
| ({ rejectedWithValue: true } & GetRejectedMeta<ThunkApiConfig>)
)
>
export type AsyncThunkFulfilledActionCreator<
Returned,
ThunkArg,
ThunkApiConfig = {},
> = ActionCreatorWithPreparedPayload<
[Returned, string, ThunkArg, GetFulfilledMeta<ThunkApiConfig>?],
Returned,
string,
never,
{
arg: ThunkArg
requestId: string
requestStatus: 'fulfilled'
} & GetFulfilledMeta<ThunkApiConfig>
>
/**
* A type describing the return value of `createAsyncThunk`.
* Might be useful for wrapping `createAsyncThunk` in custom abstractions.
*
* @public
*/
export type AsyncThunk<
Returned,
ThunkArg,
ThunkApiConfig extends AsyncThunkConfig,
> = AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig> & {
pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig>
rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>
fulfilled: AsyncThunkFulfilledActionCreator<
Returned,
ThunkArg,
ThunkApiConfig
>
// matchSettled?
settled: (
action: any,
) => action is ReturnType<
| AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>
| AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>
>
typePrefix: string
}
export type OverrideThunkApiConfigs<OldConfig, NewConfig> = Id<
NewConfig & Omit<OldConfig, keyof NewConfig>
>
type CreateAsyncThunk<CurriedThunkApiConfig extends AsyncThunkConfig> = {
/**
*
* @param typePrefix
* @param payloadCreator
* @param options
*
* @public
*/
// separate signature without `AsyncThunkConfig` for better inference
<Returned, ThunkArg = void>(
typePrefix: string,
payloadCreator: AsyncThunkPayloadCreator<
Returned,
ThunkArg,
CurriedThunkApiConfig
>,
options?: AsyncThunkOptions<ThunkArg, CurriedThunkApiConfig>,
): AsyncThunk<Returned, ThunkArg, CurriedThunkApiConfig>
/**
*
* @param typePrefix
* @param payloadCreator
* @param options
*
* @public
*/
<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig>(
typePrefix: string,
payloadCreator: AsyncThunkPayloadCreator<
Returned,
ThunkArg,
OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
>,
options?: AsyncThunkOptions<
ThunkArg,
OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
>,
): AsyncThunk<
Returned,
ThunkArg,
OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
>
withTypes<ThunkApiConfig extends AsyncThunkConfig>(): CreateAsyncThunk<
OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
>
}
export const createAsyncThunk = /* @__PURE__ */ (() => {
function createAsyncThunk<
Returned,
ThunkArg,
ThunkApiConfig extends AsyncThunkConfig,
>(
typePrefix: string,
payloadCreator: AsyncThunkPayloadCreator<
Returned,
ThunkArg,
ThunkApiConfig
>,
options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>,
): AsyncThunk<Returned, ThunkArg, ThunkApiConfig> {
type RejectedValue = GetRejectValue<ThunkApiConfig>
type PendingMeta = GetPendingMeta<ThunkApiConfig>
type FulfilledMeta = GetFulfilledMeta<ThunkApiConfig>
type RejectedMeta = GetRejectedMeta<ThunkApiConfig>
const fulfilled: AsyncThunkFulfilledActionCreator<
Returned,
ThunkArg,
ThunkApiConfig
> = createAction(
typePrefix + '/fulfilled',
(
payload: Returned,
requestId: string,
arg: ThunkArg,
meta?: FulfilledMeta,
) => ({
payload,
meta: {
...((meta as any) || {}),
arg,
requestId,
requestStatus: 'fulfilled' as const,
},
}),
)
const pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig> =
createAction(
typePrefix + '/pending',
(requestId: string, arg: ThunkArg, meta?: PendingMeta) => ({
payload: undefined,
meta: {
...((meta as any) || {}),
arg,
requestId,
requestStatus: 'pending' as const,
},
}),
)
const rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig> =
createAction(
typePrefix + '/rejected',
(
error: Error | null,
requestId: string,
arg: ThunkArg,
payload?: RejectedValue,
meta?: RejectedMeta,
) => ({
payload,
error: ((options && options.serializeError) || miniSerializeError)(
error || 'Rejected',
) as GetSerializedErrorType<ThunkApiConfig>,
meta: {
...((meta as any) || {}),
arg,
requestId,
rejectedWithValue: !!payload,
requestStatus: 'rejected' as const,
aborted: error?.name === 'AbortError',
condition: error?.name === 'ConditionError',
},
}),
)
function actionCreator(
arg: ThunkArg,
): AsyncThunkAction<Returned, ThunkArg, Required<ThunkApiConfig>> {
return (dispatch, getState, extra) => {
const requestId = options?.idGenerator
? options.idGenerator(arg)
: nanoid()
const abortController = new AbortController()
let abortHandler: (() => void) | undefined
let abortReason: string | undefined
function abort(reason?: string) {
abortReason = reason
abortController.abort()
}
const promise = (async function () {
let finalAction: ReturnType<typeof fulfilled | typeof rejected>
try {
let conditionResult = options?.condition?.(arg, { getState, extra })
if (isThenable(conditionResult)) {
conditionResult = await conditionResult
}
if (conditionResult === false || abortController.signal.aborted) {
// eslint-disable-next-line no-throw-literal
throw {
name: 'ConditionError',
message: 'Aborted due to condition callback returning false.',
}
}
const abortedPromise = new Promise<never>((_, reject) => {
abortHandler = () => {
reject({
name: 'AbortError',
message: abortReason || 'Aborted',
})
}
abortController.signal.addEventListener('abort', abortHandler)
})
dispatch(
pending(
requestId,
arg,
options?.getPendingMeta?.(
{ requestId, arg },
{ getState, extra },
),
) as any,
)
finalAction = await Promise.race([
abortedPromise,
Promise.resolve(
payloadCreator(arg, {
dispatch,
getState,
extra,
requestId,
signal: abortController.signal,
abort,
rejectWithValue: ((
value: RejectedValue,
meta?: RejectedMeta,
) => {
return new RejectWithValue(value, meta)
}) as any,
fulfillWithValue: ((value: unknown, meta?: FulfilledMeta) => {
return new FulfillWithMeta(value, meta)
}) as any,
}),
).then((result) => {
if (result instanceof RejectWithValue) {
throw result
}
if (result instanceof FulfillWithMeta) {
return fulfilled(result.payload, requestId, arg, result.meta)
}
return fulfilled(result as any, requestId, arg)
}),
])
} catch (err) {
finalAction =
err instanceof RejectWithValue
? rejected(null, requestId, arg, err.payload, err.meta)
: rejected(err as any, requestId, arg)
} finally {
if (abortHandler) {
abortController.signal.removeEventListener('abort', abortHandler)
}
}
// We dispatch the result action _after_ the catch, to avoid having any errors
// here get swallowed by the try/catch block,
// per https://twitter.com/dan_abramov/status/770914221638942720
// and https://github.com/reduxjs/redux-toolkit/blob/e85eb17b39a2118d859f7b7746e0f3fee523e089/docs/tutorials/advanced-tutorial.md#async-error-handling-logic-in-thunks
const skipDispatch =
options &&
!options.dispatchConditionRejection &&
rejected.match(finalAction) &&
(finalAction as any).meta.condition
if (!skipDispatch) {
dispatch(finalAction as any)
}
return finalAction
})()
return Object.assign(promise as SafePromise<any>, {
abort,
requestId,
arg,
unwrap() {
return promise.then<any>(unwrapResult)
},
})
}
}
return Object.assign(
actionCreator as AsyncThunkActionCreator<
Returned,
ThunkArg,
ThunkApiConfig
>,
{
pending,
rejected,
fulfilled,
settled: isAnyOf(rejected, fulfilled),
typePrefix,
},
)
}
createAsyncThunk.withTypes = () => createAsyncThunk
return createAsyncThunk as CreateAsyncThunk<AsyncThunkConfig>
})()
interface UnwrappableAction {
payload: any
meta?: any
error?: any
}
type UnwrappedActionPayload<T extends UnwrappableAction> = Exclude<
T,
{ error: any }
>['payload']
/**
* @public
*/
export function unwrapResult<R extends UnwrappableAction>(
action: R,
): UnwrappedActionPayload<R> {
if (action.meta && action.meta.rejectedWithValue) {
throw action.payload
}
if (action.error) {
throw action.error
}
return action.payload
}
type WithStrictNullChecks<True, False> = undefined extends boolean
? False
: True
function isThenable(value: any): value is PromiseLike<any> {
return (
value !== null &&
typeof value === 'object' &&
typeof value.then === 'function'
)
}

View File

@@ -0,0 +1,30 @@
import { current, isDraft } from 'immer'
import { createSelectorCreator, weakMapMemoize } from 'reselect'
export const createDraftSafeSelectorCreator: typeof createSelectorCreator = (
...args: unknown[]
) => {
const createSelector = (createSelectorCreator as any)(...args)
const createDraftSafeSelector = Object.assign(
(...args: unknown[]) => {
const selector = createSelector(...args)
const wrappedSelector = (value: unknown, ...rest: unknown[]) =>
selector(isDraft(value) ? current(value) : value, ...rest)
Object.assign(wrappedSelector, selector)
return wrappedSelector as any
},
{ withTypes: () => createDraftSafeSelector },
)
return createDraftSafeSelector
}
/**
* "Draft-Safe" version of `reselect`'s `createSelector`:
* If an `immer`-drafted object is passed into the resulting selector's first argument,
* the selector will act on the current draft value, instead of returning a cached value
* that might be possibly outdated if the draft has been modified since.
* @public
*/
export const createDraftSafeSelector =
/* @__PURE__ */
createDraftSafeSelectorCreator(weakMapMemoize)

221
node_modules/@reduxjs/toolkit/src/createReducer.ts generated vendored Normal file
View File

@@ -0,0 +1,221 @@
import type { Draft } from 'immer'
import { produce as createNextState, isDraft, isDraftable } from 'immer'
import type { Action, Reducer, UnknownAction } from 'redux'
import type { ActionReducerMapBuilder } from './mapBuilders'
import { executeReducerBuilderCallback } from './mapBuilders'
import type { NoInfer, TypeGuard } from './tsHelpers'
import { freezeDraftable } from './utils'
/**
* Defines a mapping from action types to corresponding action object shapes.
*
* @deprecated This should not be used manually - it is only used for internal
* inference purposes and should not have any further value.
* It might be removed in the future.
* @public
*/
export type Actions<T extends keyof any = string> = Record<T, Action>
export type ActionMatcherDescription<S, A extends Action> = {
matcher: TypeGuard<A>
reducer: CaseReducer<S, NoInfer<A>>
}
export type ReadonlyActionMatcherDescriptionCollection<S> = ReadonlyArray<
ActionMatcherDescription<S, any>
>
export type ActionMatcherDescriptionCollection<S> = Array<
ActionMatcherDescription<S, any>
>
/**
* A *case reducer* is a reducer function for a specific action type. Case
* reducers can be composed to full reducers using `createReducer()`.
*
* Unlike a normal Redux reducer, a case reducer is never called with an
* `undefined` state to determine the initial state. Instead, the initial
* state is explicitly specified as an argument to `createReducer()`.
*
* In addition, a case reducer can choose to mutate the passed-in `state`
* value directly instead of returning a new state. This does not actually
* cause the store state to be mutated directly; instead, thanks to
* [immer](https://github.com/mweststrate/immer), the mutations are
* translated to copy operations that result in a new state.
*
* @public
*/
export type CaseReducer<S = any, A extends Action = UnknownAction> = (
state: Draft<S>,
action: A,
) => NoInfer<S> | void | Draft<NoInfer<S>>
/**
* A mapping from action types to case reducers for `createReducer()`.
*
* @deprecated This should not be used manually - it is only used
* for internal inference purposes and using it manually
* would lead to type erasure.
* It might be removed in the future.
* @public
*/
export type CaseReducers<S, AS extends Actions> = {
[T in keyof AS]: AS[T] extends Action ? CaseReducer<S, AS[T]> : void
}
export type NotFunction<T> = T extends Function ? never : T
function isStateFunction<S>(x: unknown): x is () => S {
return typeof x === 'function'
}
export type ReducerWithInitialState<S extends NotFunction<any>> = Reducer<S> & {
getInitialState: () => S
}
/**
* A utility function that allows defining a reducer as a mapping from action
* type to *case reducer* functions that handle these action types. The
* reducer's initial state is passed as the first argument.
*
* @remarks
* The body of every case reducer is implicitly wrapped with a call to
* `produce()` from the [immer](https://github.com/mweststrate/immer) library.
* This means that rather than returning a new state object, you can also
* mutate the passed-in state object directly; these mutations will then be
* automatically and efficiently translated into copies, giving you both
* convenience and immutability.
*
* @overloadSummary
* This function accepts a callback that receives a `builder` object as its argument.
* That builder provides `addCase`, `addMatcher` and `addDefaultCase` functions that may be
* called to define what actions this reducer will handle.
*
* @param initialState - `State | (() => State)`: The initial state that should be used when the reducer is called the first time. This may also be a "lazy initializer" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.
* @param builderCallback - `(builder: Builder) => void` A callback that receives a *builder* object to define
* case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.
* @example
```ts
import {
createAction,
createReducer,
UnknownAction,
PayloadAction,
} from "@reduxjs/toolkit";
const increment = createAction<number>("increment");
const decrement = createAction<number>("decrement");
function isActionWithNumberPayload(
action: UnknownAction
): action is PayloadAction<number> {
return typeof action.payload === "number";
}
const reducer = createReducer(
{
counter: 0,
sumOfNumberPayloads: 0,
unhandledActions: 0,
},
(builder) => {
builder
.addCase(increment, (state, action) => {
// action is inferred correctly here
state.counter += action.payload;
})
// You can chain calls, or have separate `builder.addCase()` lines each time
.addCase(decrement, (state, action) => {
state.counter -= action.payload;
})
// You can apply a "matcher function" to incoming actions
.addMatcher(isActionWithNumberPayload, (state, action) => {})
// and provide a default case if no other handlers matched
.addDefaultCase((state, action) => {});
}
);
```
* @public
*/
export function createReducer<S extends NotFunction<any>>(
initialState: S | (() => S),
mapOrBuilderCallback: (builder: ActionReducerMapBuilder<S>) => void,
): ReducerWithInitialState<S> {
if (process.env.NODE_ENV !== 'production') {
if (typeof mapOrBuilderCallback === 'object') {
throw new Error(
"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)
// Ensure the initial state gets frozen either way (if draftable)
let getInitialState: () => S
if (isStateFunction(initialState)) {
getInitialState = () => freezeDraftable(initialState())
} else {
const frozenInitialState = freezeDraftable(initialState)
getInitialState = () => frozenInitialState
}
function reducer(state = getInitialState(), action: any): S {
let caseReducers = [
actionsMap[action.type],
...finalActionMatchers
.filter(({ matcher }) => matcher(action))
.map(({ reducer }) => reducer),
]
if (caseReducers.filter((cr) => !!cr).length === 0) {
caseReducers = [finalDefaultCaseReducer]
}
return caseReducers.reduce((previousState, caseReducer): S => {
if (caseReducer) {
if (isDraft(previousState)) {
// If it's already a draft, we must already be inside a `createNextState` call,
// likely because this is being wrapped in `createReducer`, `createSlice`, or nested
// inside an existing draft. It's safe to just pass the draft to the mutator.
const draft = previousState as Draft<S> // We can assume this is already a draft
const result = caseReducer(draft, action)
if (result === undefined) {
return previousState
}
return result as S
} else if (!isDraftable(previousState)) {
// If state is not draftable (ex: a primitive, such as 0), we want to directly
// return the caseReducer func and not wrap it with produce.
const result = caseReducer(previousState as any, action)
if (result === undefined) {
if (previousState === null) {
return previousState
}
throw Error(
'A case reducer on a non-draftable value must not return undefined',
)
}
return result as S
} else {
// @ts-ignore createNextState() produces an Immutable<Draft<S>> rather
// than an Immutable<S>, and TypeScript cannot find out how to reconcile
// these two types.
return createNextState(previousState, (draft: Draft<S>) => {
return caseReducer(draft, action)
})
}
}
return previousState
}, state)
}
reducer.getInitialState = getInitialState
return reducer as ReducerWithInitialState<S>
}

1075
node_modules/@reduxjs/toolkit/src/createSlice.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

241
node_modules/@reduxjs/toolkit/src/devtoolsExtension.ts generated vendored Normal file
View File

@@ -0,0 +1,241 @@
import type { Action, ActionCreator, StoreEnhancer } from 'redux'
import { compose } from 'redux'
/**
* @public
*/
export interface DevToolsEnhancerOptions {
/**
* the instance name to be showed on the monitor page. Default value is `document.title`.
* If not specified and there's no document title, it will consist of `tabId` and `instanceId`.
*/
name?: string
/**
* action creators functions to be available in the Dispatcher.
*/
actionCreators?: ActionCreator<any>[] | { [key: string]: ActionCreator<any> }
/**
* if more than one action is dispatched in the indicated interval, all new actions will be collected and sent at once.
* It is the joint between performance and speed. When set to `0`, all actions will be sent instantly.
* Set it to a higher value when experiencing perf issues (also `maxAge` to a lower value).
*
* @default 500 ms.
*/
latency?: number
/**
* (> 1) - maximum allowed actions to be stored in the history tree. The oldest actions are removed once maxAge is reached. It's critical for performance.
*
* @default 50
*/
maxAge?: number
/**
* Customizes how actions and state are serialized and deserialized. Can be a boolean or object. If given a boolean, the behavior is the same as if you
* were to pass an object and specify `options` as a boolean. Giving an object allows fine-grained customization using the `replacer` and `reviver`
* functions.
*/
serialize?:
| boolean
| {
/**
* - `undefined` - will use regular `JSON.stringify` to send data (it's the fast mode).
* - `false` - will handle also circular references.
* - `true` - will handle also date, regex, undefined, error objects, symbols, maps, sets and functions.
* - object, which contains `date`, `regex`, `undefined`, `error`, `symbol`, `map`, `set` and `function` keys.
* For each of them you can indicate if to include (by setting as `true`).
* For `function` key you can also specify a custom function which handles serialization.
* See [`jsan`](https://github.com/kolodny/jsan) for more details.
*/
options?:
| undefined
| boolean
| {
date?: true
regex?: true
undefined?: true
error?: true
symbol?: true
map?: true
set?: true
function?: true | ((fn: (...args: any[]) => any) => string)
}
/**
* [JSON replacer function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) used for both actions and states stringify.
* In addition, you can specify a data type by adding a [`__serializedType__`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/helpers/index.js#L4)
* key. So you can deserialize it back while importing or persisting data.
* Moreover, it will also [show a nice preview showing the provided custom type](https://cloud.githubusercontent.com/assets/7957859/21814330/a17d556a-d761-11e6-85ef-159dd12f36c5.png):
*/
replacer?: (key: string, value: unknown) => any
/**
* [JSON `reviver` function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter)
* used for parsing the imported actions and states. See [`remotedev-serialize`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/immutable/serialize.js#L8-L41)
* as an example on how to serialize special data types and get them back.
*/
reviver?: (key: string, value: unknown) => any
/**
* Automatically serialize/deserialize immutablejs via [remotedev-serialize](https://github.com/zalmoxisus/remotedev-serialize).
* Just pass the Immutable library. It will support all ImmutableJS structures. You can even export them into a file and get them back.
* The only exception is `Record` class, for which you should pass this in addition the references to your classes in `refs`.
*/
immutable?: any
/**
* ImmutableJS `Record` classes used to make possible restore its instances back when importing, persisting...
*/
refs?: any
}
/**
* function which takes `action` object and id number as arguments, and should return `action` object back.
*/
actionSanitizer?: <A extends Action>(action: A, id: number) => A
/**
* function which takes `state` object and index as arguments, and should return `state` object back.
*/
stateSanitizer?: <S>(state: S, index: number) => S
/**
* *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).
* If `actionsAllowlist` specified, `actionsDenylist` is ignored.
*/
actionsDenylist?: string | string[]
/**
* *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).
* If `actionsAllowlist` specified, `actionsDenylist` is ignored.
*/
actionsAllowlist?: string | string[]
/**
* called for every action before sending, takes `state` and `action` object, and returns `true` in case it allows sending the current data to the monitor.
* Use it as a more advanced version of `actionsDenylist`/`actionsAllowlist` parameters.
*/
predicate?: <S, A extends Action>(state: S, action: A) => boolean
/**
* if specified as `false`, it will not record the changes till clicking on `Start recording` button.
* Available only for Redux enhancer, for others use `autoPause`.
*
* @default true
*/
shouldRecordChanges?: boolean
/**
* if specified, whenever clicking on `Pause recording` button and there are actions in the history log, will add this action type.
* If not specified, will commit when paused. Available only for Redux enhancer.
*
* @default "@@PAUSED""
*/
pauseActionType?: string
/**
* auto pauses when the extensions window is not opened, and so has zero impact on your app when not in use.
* Not available for Redux enhancer (as it already does it but storing the data to be sent).
*
* @default false
*/
autoPause?: boolean
/**
* if specified as `true`, it will not allow any non-monitor actions to be dispatched till clicking on `Unlock changes` button.
* Available only for Redux enhancer.
*
* @default false
*/
shouldStartLocked?: boolean
/**
* if set to `false`, will not recompute the states on hot reloading (or on replacing the reducers). Available only for Redux enhancer.
*
* @default true
*/
shouldHotReload?: boolean
/**
* if specified as `true`, whenever there's an exception in reducers, the monitors will show the error message, and next actions will not be dispatched.
*
* @default false
*/
shouldCatchErrors?: boolean
/**
* If you want to restrict the extension, specify the features you allow.
* If not specified, all of the features are enabled. When set as an object, only those included as `true` will be allowed.
* Note that except `true`/`false`, `import` and `export` can be set as `custom` (which is by default for Redux enhancer), meaning that the importing/exporting occurs on the client side.
* Otherwise, you'll get/set the data right from the monitor part.
*/
features?: {
/**
* start/pause recording of dispatched actions
*/
pause?: boolean
/**
* lock/unlock dispatching actions and side effects
*/
lock?: boolean
/**
* persist states on page reloading
*/
persist?: boolean
/**
* export history of actions in a file
*/
export?: boolean | 'custom'
/**
* import history of actions from a file
*/
import?: boolean | 'custom'
/**
* jump back and forth (time travelling)
*/
jump?: boolean
/**
* skip (cancel) actions
*/
skip?: boolean
/**
* drag and drop actions in the history list
*/
reorder?: boolean
/**
* dispatch custom actions or action creators
*/
dispatch?: boolean
/**
* generate tests for the selected actions
*/
test?: boolean
}
/**
* Set to true or a stacktrace-returning function to record call stack traces for dispatched actions.
* Defaults to false.
*/
trace?: boolean | (<A extends Action>(action: A) => string)
/**
* The maximum number of stack trace entries to record per action. Defaults to 10.
*/
traceLimit?: number
}
type Compose = typeof compose
interface ComposeWithDevTools {
(options: DevToolsEnhancerOptions): Compose
<StoreExt extends {}>(
...funcs: StoreEnhancer<StoreExt>[]
): StoreEnhancer<StoreExt>
}
/**
* @public
*/
export const composeWithDevTools: ComposeWithDevTools =
typeof window !== 'undefined' &&
(window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
? (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
: function () {
if (arguments.length === 0) return undefined
if (typeof arguments[0] === 'object') return compose
return compose.apply(null, arguments as any as Function[])
}
/**
* @public
*/
export const devToolsEnhancer: {
(options: DevToolsEnhancerOptions): StoreEnhancer<any>
} =
typeof window !== 'undefined' && (window as any).__REDUX_DEVTOOLS_EXTENSION__
? (window as any).__REDUX_DEVTOOLS_EXTENSION__
: function () {
return function (noop) {
return noop
}
}

View File

@@ -0,0 +1,98 @@
import type { Dispatch, Middleware, UnknownAction } from 'redux'
import { compose } from 'redux'
import { createAction } from '../createAction'
import { isAllOf } from '../matchers'
import { nanoid } from '../nanoid'
import { emplace, find } from '../utils'
import type {
AddMiddleware,
DynamicMiddleware,
DynamicMiddlewareInstance,
MiddlewareEntry,
WithMiddleware,
} from './types'
export type {
DynamicMiddlewareInstance,
GetDispatchType as GetDispatch,
MiddlewareApiConfig,
} from './types'
const createMiddlewareEntry = <
State = any,
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
>(
middleware: Middleware<any, State, DispatchType>,
): MiddlewareEntry<State, DispatchType> => ({
id: nanoid(),
middleware,
applied: new Map(),
})
const matchInstance =
(instanceId: string) =>
(action: any): action is { meta: { instanceId: string } } =>
action?.meta?.instanceId === instanceId
export const createDynamicMiddleware = <
State = any,
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
>(): DynamicMiddlewareInstance<State, DispatchType> => {
const instanceId = nanoid()
const middlewareMap = new Map<string, MiddlewareEntry<State, DispatchType>>()
const withMiddleware = Object.assign(
createAction(
'dynamicMiddleware/add',
(...middlewares: Middleware<any, State, DispatchType>[]) => ({
payload: middlewares,
meta: {
instanceId,
},
}),
),
{ withTypes: () => withMiddleware },
) as WithMiddleware<State, DispatchType>
const addMiddleware = Object.assign(
function addMiddleware(
...middlewares: Middleware<any, State, DispatchType>[]
) {
middlewares.forEach((middleware) => {
let entry = find(
Array.from(middlewareMap.values()),
(entry) => entry.middleware === middleware,
)
if (!entry) {
entry = createMiddlewareEntry(middleware)
}
middlewareMap.set(entry.id, entry)
})
},
{ withTypes: () => addMiddleware },
) as AddMiddleware<State, DispatchType>
const getFinalMiddleware: Middleware<{}, State, DispatchType> = (api) => {
const appliedMiddleware = Array.from(middlewareMap.values()).map((entry) =>
emplace(entry.applied, api, { insert: () => entry.middleware(api) }),
)
return compose(...appliedMiddleware)
}
const isWithMiddleware = isAllOf(withMiddleware, matchInstance(instanceId))
const middleware: DynamicMiddleware<State, DispatchType> =
(api) => (next) => (action) => {
if (isWithMiddleware(action)) {
addMiddleware(...action.payload)
return api.dispatch
}
return getFinalMiddleware(api)(next)(action)
}
return {
middleware,
addMiddleware,
withMiddleware,
instanceId,
}
}

View File

@@ -0,0 +1,101 @@
import type {
DynamicMiddlewareInstance,
GetDispatch,
GetState,
MiddlewareApiConfig,
TSHelpersExtractDispatchExtensions,
} from '@reduxjs/toolkit'
import { createDynamicMiddleware as cDM } from '@reduxjs/toolkit'
import type { Context } from 'react'
import type { ReactReduxContextValue } from 'react-redux'
import {
createDispatchHook,
ReactReduxContext,
useDispatch as useDefaultDispatch,
} from 'react-redux'
import type { Action, Dispatch, Middleware, UnknownAction } from 'redux'
export type UseDispatchWithMiddlewareHook<
Middlewares extends Middleware<any, State, DispatchType>[] = [],
State = any,
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
> = () => TSHelpersExtractDispatchExtensions<Middlewares> & DispatchType
export type CreateDispatchWithMiddlewareHook<
State = any,
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
> = {
<
Middlewares extends [
Middleware<any, State, DispatchType>,
...Middleware<any, State, DispatchType>[],
],
>(
...middlewares: Middlewares
): UseDispatchWithMiddlewareHook<Middlewares, State, DispatchType>
withTypes<
MiddlewareConfig extends MiddlewareApiConfig,
>(): CreateDispatchWithMiddlewareHook<
GetState<MiddlewareConfig>,
GetDispatch<MiddlewareConfig>
>
}
type ActionFromDispatch<DispatchType extends Dispatch<Action>> =
DispatchType extends Dispatch<infer Action> ? Action : never
type ReactDynamicMiddlewareInstance<
State = any,
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
> = DynamicMiddlewareInstance<State, DispatchType> & {
createDispatchWithMiddlewareHookFactory: (
context?: Context<ReactReduxContextValue<
State,
ActionFromDispatch<DispatchType>
> | null>,
) => CreateDispatchWithMiddlewareHook<State, DispatchType>
createDispatchWithMiddlewareHook: CreateDispatchWithMiddlewareHook<
State,
DispatchType
>
}
export const createDynamicMiddleware = <
State = any,
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
>(): ReactDynamicMiddlewareInstance<State, DispatchType> => {
const instance = cDM<State, DispatchType>()
const createDispatchWithMiddlewareHookFactory = (
// @ts-ignore
context: Context<ReactReduxContextValue<
State,
ActionFromDispatch<DispatchType>
> | null> = ReactReduxContext,
) => {
const useDispatch =
context === ReactReduxContext
? useDefaultDispatch
: createDispatchHook(context)
function createDispatchWithMiddlewareHook<
Middlewares extends Middleware<any, State, DispatchType>[],
>(...middlewares: Middlewares) {
instance.addMiddleware(...middlewares)
return useDispatch
}
createDispatchWithMiddlewareHook.withTypes = () =>
createDispatchWithMiddlewareHook
return createDispatchWithMiddlewareHook as CreateDispatchWithMiddlewareHook<
State,
DispatchType
>
}
const createDispatchWithMiddlewareHook =
createDispatchWithMiddlewareHookFactory()
return {
...instance,
createDispatchWithMiddlewareHookFactory,
createDispatchWithMiddlewareHook,
}
}

View File

@@ -0,0 +1,95 @@
import type { Action, Middleware, UnknownAction } from 'redux'
import type { ThunkDispatch } from 'redux-thunk'
import { configureStore } from '../../configureStore'
import { createDynamicMiddleware } from '../index'
const untypedInstance = createDynamicMiddleware()
interface AppDispatch extends ThunkDispatch<number, undefined, UnknownAction> {
(n: 1): 1
}
const typedInstance = createDynamicMiddleware<number, AppDispatch>()
declare const staticMiddleware: Middleware<(n: 1) => 1>
const store = configureStore({
reducer: () => 0,
middleware: (gDM) =>
gDM().prepend(typedInstance.middleware).concat(staticMiddleware),
})
declare const compatibleMiddleware: Middleware<{}, number, AppDispatch>
declare const incompatibleMiddleware: Middleware<{}, string, AppDispatch>
declare const addedMiddleware: Middleware<(n: 2) => 2>
describe('type tests', () => {
test('instance typed at creation ensures middleware compatibility with store', () => {
const store = configureStore({
reducer: () => '',
// @ts-expect-error
middleware: (gDM) => gDM().prepend(typedInstance.middleware),
})
})
test('instance typed at creation enforces correct middleware type', () => {
typedInstance.addMiddleware(
compatibleMiddleware,
// @ts-expect-error
incompatibleMiddleware,
)
const dispatch = store.dispatch(
typedInstance.withMiddleware(
compatibleMiddleware,
// @ts-expect-error
incompatibleMiddleware,
),
)
})
test('withTypes() enforces correct middleware type', () => {
const addMiddleware = untypedInstance.addMiddleware.withTypes<{
state: number
dispatch: AppDispatch
}>()
addMiddleware(
compatibleMiddleware,
// @ts-expect-error
incompatibleMiddleware,
)
const withMiddleware = untypedInstance.withMiddleware.withTypes<{
state: number
dispatch: AppDispatch
}>()
const dispatch = store.dispatch(
withMiddleware(
compatibleMiddleware,
// @ts-expect-error
incompatibleMiddleware,
),
)
})
test('withMiddleware returns typed dispatch, with any applicable extensions', () => {
const dispatch = store.dispatch(
typedInstance.withMiddleware(addedMiddleware),
)
// standard
expectTypeOf(dispatch({ type: 'foo' })).toEqualTypeOf<Action<string>>()
// thunk
expectTypeOf(dispatch(() => 'foo')).toBeString()
// static
expectTypeOf(dispatch(1)).toEqualTypeOf<1>()
// added
expectTypeOf(dispatch(2)).toEqualTypeOf<2>()
})
})

View File

@@ -0,0 +1,74 @@
import type { Middleware } from 'redux'
import { createDynamicMiddleware } from '../index'
import { configureStore } from '../../configureStore'
import type { BaseActionCreator, PayloadAction } from '../../createAction'
import { createAction } from '../../createAction'
import { isAllOf } from '../../matchers'
const probeType = 'probeableMW/probe'
export interface ProbeMiddleware
extends BaseActionCreator<number, typeof probeType> {
<Id extends number>(id: Id): PayloadAction<Id, typeof probeType>
}
export const probeMiddleware = createAction(probeType) as ProbeMiddleware
const matchId =
<Id extends number>(id: Id) =>
(action: any): action is PayloadAction<Id> =>
action.payload === id
export const makeProbeableMiddleware = <Id extends number>(
id: Id,
): Middleware<{
(action: PayloadAction<Id, typeof probeType>): Id
}> => {
const isMiddlewareAction = isAllOf(probeMiddleware, matchId(id))
return (api) => (next) => (action) => {
if (isMiddlewareAction(action)) {
return id
}
return next(action)
}
}
const staticMiddleware = makeProbeableMiddleware(1)
describe('createDynamicMiddleware', () => {
it('allows injecting middleware after store instantiation', () => {
const dynamicInstance = createDynamicMiddleware()
const store = configureStore({
reducer: () => 0,
middleware: (gDM) =>
gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),
})
// normal, pre-inject
expect(store.dispatch(probeMiddleware(2))).toEqual(probeMiddleware(2))
// static
expect(store.dispatch(probeMiddleware(1))).toBe(1)
// inject
dynamicInstance.addMiddleware(makeProbeableMiddleware(2))
// injected
expect(store.dispatch(probeMiddleware(2))).toBe(2)
})
it('returns dispatch when withMiddleware is dispatched', () => {
const dynamicInstance = createDynamicMiddleware()
const store = configureStore({
reducer: () => 0,
middleware: (gDM) => gDM().prepend(dynamicInstance.middleware),
})
// normal, pre-inject
expect(store.dispatch(probeMiddleware(2))).toEqual(probeMiddleware(2))
const dispatch = store.dispatch(
dynamicInstance.withMiddleware(makeProbeableMiddleware(2)),
)
expect(dispatch).toEqual(expect.any(Function))
expect(dispatch(probeMiddleware(2))).toBe(2)
})
})

View File

@@ -0,0 +1,81 @@
import type { Context } from 'react'
import type { ReactReduxContextValue } from 'react-redux'
import type { Action, Middleware, UnknownAction } from 'redux'
import type { ThunkDispatch } from 'redux-thunk'
import { createDynamicMiddleware } from '../react'
interface AppDispatch extends ThunkDispatch<number, undefined, UnknownAction> {
(n: 1): 1
}
const untypedInstance = createDynamicMiddleware()
const typedInstance = createDynamicMiddleware<number, AppDispatch>()
declare const compatibleMiddleware: Middleware<{}, number, AppDispatch>
declare const incompatibleMiddleware: Middleware<{}, string, AppDispatch>
declare const customContext: Context<ReactReduxContextValue | null>
declare const addedMiddleware: Middleware<(n: 2) => 2>
describe('type tests', () => {
test('instance typed at creation enforces correct middleware type', () => {
const useDispatch = typedInstance.createDispatchWithMiddlewareHook(
compatibleMiddleware,
// @ts-expect-error
incompatibleMiddleware,
)
const createDispatchWithMiddlewareHook =
typedInstance.createDispatchWithMiddlewareHookFactory(customContext)
const useDispatchWithContext = createDispatchWithMiddlewareHook(
compatibleMiddleware,
// @ts-expect-error
incompatibleMiddleware,
)
})
test('withTypes() enforces correct middleware type', () => {
const createDispatchWithMiddlewareHook =
untypedInstance.createDispatchWithMiddlewareHook.withTypes<{
state: number
dispatch: AppDispatch
}>()
const useDispatch = createDispatchWithMiddlewareHook(
compatibleMiddleware,
// @ts-expect-error
incompatibleMiddleware,
)
const createCustomDispatchWithMiddlewareHook = untypedInstance
.createDispatchWithMiddlewareHookFactory(customContext)
.withTypes<{
state: number
dispatch: AppDispatch
}>()
const useCustomDispatch = createCustomDispatchWithMiddlewareHook(
compatibleMiddleware,
// @ts-expect-error
incompatibleMiddleware,
)
})
test('useDispatchWithMW returns typed dispatch, with any applicable extensions', () => {
const useDispatchWithMW =
typedInstance.createDispatchWithMiddlewareHook(addedMiddleware)
const dispatch = useDispatchWithMW()
// standard
expectTypeOf(dispatch({ type: 'foo' })).toEqualTypeOf<Action<string>>()
// thunk
expectTypeOf(dispatch(() => 'foo')).toBeString()
// static
expectTypeOf(dispatch(1)).toEqualTypeOf<1>()
// added
expectTypeOf(dispatch(2)).toEqualTypeOf<2>()
})
})

View File

@@ -0,0 +1,101 @@
import * as React from 'react'
import { createDynamicMiddleware } from '../react'
import { configureStore } from '../../configureStore'
import { makeProbeableMiddleware, probeMiddleware } from './index.test'
import { render } from '@testing-library/react'
import type { Dispatch } from 'redux'
import type { ReactReduxContextValue } from 'react-redux'
import { Provider } from 'react-redux'
const staticMiddleware = makeProbeableMiddleware(1)
describe('createReactDynamicMiddleware', () => {
describe('createDispatchWithMiddlewareHook', () => {
it('injects middleware upon creation', () => {
const dynamicInstance = createDynamicMiddleware()
const store = configureStore({
reducer: () => 0,
middleware: (gDM) =>
gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),
})
// normal, pre-inject
expect(store.dispatch(probeMiddleware(2))).toEqual(probeMiddleware(2))
// static
expect(store.dispatch(probeMiddleware(1))).toBe(1)
const useDispatch = dynamicInstance.createDispatchWithMiddlewareHook(
makeProbeableMiddleware(2),
)
// injected
expect(store.dispatch(probeMiddleware(2))).toBe(2)
})
it('returns dispatch', () => {
const dynamicInstance = createDynamicMiddleware()
const store = configureStore({
reducer: () => 0,
middleware: (gDM) =>
gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),
})
const useDispatch = dynamicInstance.createDispatchWithMiddlewareHook(
makeProbeableMiddleware(2),
)
let dispatch: Dispatch | undefined
function Component() {
dispatch = useDispatch()
return null
}
render(<Component />, {
wrapper: ({ children }) => (
<Provider store={store}>{children}</Provider>
),
})
expect(dispatch).toBe(store.dispatch)
})
})
describe('createDispatchWithMiddlewareHookFactory', () => {
it('returns the correct store dispatch', () => {
const dynamicInstance = createDynamicMiddleware()
const store = configureStore({
reducer: () => 0,
middleware: (gDM) =>
gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),
})
const store2 = configureStore({
reducer: () => '',
middleware: (gDM) =>
gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),
})
const context = React.createContext<ReactReduxContextValue | null>(null)
const createDispatchWithMiddlewareHook =
dynamicInstance.createDispatchWithMiddlewareHookFactory(context)
const useDispatch = createDispatchWithMiddlewareHook(
makeProbeableMiddleware(2),
)
let dispatch: Dispatch | undefined
function Component() {
dispatch = useDispatch()
return null
}
render(<Component />, {
wrapper: ({ children }) => (
<Provider store={store}>
<Provider context={context} store={store2}>
{children}
</Provider>
</Provider>
),
})
expect(dispatch).toBe(store2.dispatch)
})
})
})

View File

@@ -0,0 +1,83 @@
import type { Dispatch, Middleware, MiddlewareAPI, UnknownAction } from 'redux'
import type { BaseActionCreator, PayloadAction } from '../createAction'
import type { GetState } from '../createAsyncThunk'
import type { ExtractDispatchExtensions, FallbackIfUnknown } from '../tsHelpers'
export type GetMiddlewareApi<MiddlewareApiConfig> = MiddlewareAPI<
GetDispatchType<MiddlewareApiConfig>,
GetState<MiddlewareApiConfig>
>
export type MiddlewareApiConfig = {
state?: unknown
dispatch?: Dispatch
}
// TODO: consolidate with cAT helpers?
export type GetDispatchType<MiddlewareApiConfig> = MiddlewareApiConfig extends {
dispatch: infer DispatchType
}
? FallbackIfUnknown<DispatchType, Dispatch>
: Dispatch
export type AddMiddleware<
State = any,
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
> = {
(...middlewares: Middleware<any, State, DispatchType>[]): void
withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): AddMiddleware<
GetState<MiddlewareConfig>,
GetDispatchType<MiddlewareConfig>
>
}
export type WithMiddleware<
State = any,
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
> = BaseActionCreator<
Middleware<any, State, DispatchType>[],
'dynamicMiddleware/add',
{ instanceId: string }
> & {
<Middlewares extends Middleware<any, State, DispatchType>[]>(
...middlewares: Middlewares
): PayloadAction<Middlewares, 'dynamicMiddleware/add', { instanceId: string }>
withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): WithMiddleware<
GetState<MiddlewareConfig>,
GetDispatchType<MiddlewareConfig>
>
}
export interface DynamicDispatch {
// return a version of dispatch that knows about middleware
<Middlewares extends Middleware<any>[]>(
action: PayloadAction<Middlewares, 'dynamicMiddleware/add'>,
): ExtractDispatchExtensions<Middlewares> & this
}
export type MiddlewareEntry<
State = unknown,
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
> = {
id: string
middleware: Middleware<any, State, DispatchType>
applied: Map<
MiddlewareAPI<DispatchType, State>,
ReturnType<Middleware<any, State, DispatchType>>
>
}
export type DynamicMiddleware<
State = unknown,
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
> = Middleware<DynamicDispatch, State, DispatchType>
export type DynamicMiddlewareInstance<
State = unknown,
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
> = {
middleware: DynamicMiddleware<State, DispatchType>
addMiddleware: AddMiddleware<State, DispatchType>
withMiddleware: WithMiddleware<State, DispatchType>
instanceId: string
}

View File

@@ -0,0 +1,47 @@
import type { EntityAdapter, EntityId, EntityAdapterOptions } from './models'
import { createInitialStateFactory } from './entity_state'
import { createSelectorsFactory } from './state_selectors'
import { createSortedStateAdapter } from './sorted_state_adapter'
import { createUnsortedStateAdapter } from './unsorted_state_adapter'
import type { WithRequiredProp } from '../tsHelpers'
export function createEntityAdapter<T, Id extends EntityId>(
options: WithRequiredProp<EntityAdapterOptions<T, Id>, 'selectId'>,
): EntityAdapter<T, Id>
export function createEntityAdapter<T extends { id: EntityId }>(
options?: Omit<EntityAdapterOptions<T, T['id']>, 'selectId'>,
): EntityAdapter<T, T['id']>
/**
*
* @param options
*
* @public
*/
export function createEntityAdapter<T>(
options: EntityAdapterOptions<T, EntityId> = {},
): EntityAdapter<T, EntityId> {
const {
selectId,
sortComparer,
}: Required<EntityAdapterOptions<T, EntityId>> = {
sortComparer: false,
selectId: (instance: any) => instance.id,
...options,
}
const stateAdapter = sortComparer
? createSortedStateAdapter(selectId, sortComparer)
: createUnsortedStateAdapter(selectId)
const stateFactory = createInitialStateFactory(stateAdapter)
const selectorsFactory = createSelectorsFactory<T, EntityId>()
return {
selectId,
sortComparer,
...stateFactory,
...selectorsFactory,
...stateAdapter,
}
}

View File

@@ -0,0 +1,38 @@
import type {
EntityId,
EntityState,
EntityStateAdapter,
EntityStateFactory,
} from './models'
export function getInitialEntityState<T, Id extends EntityId>(): EntityState<
T,
Id
> {
return {
ids: [],
entities: {} as Record<Id, T>,
}
}
export function createInitialStateFactory<T, Id extends EntityId>(
stateAdapter: EntityStateAdapter<T, Id>,
): EntityStateFactory<T, Id> {
function getInitialState(
state?: undefined,
entities?: readonly T[] | Record<Id, T>,
): EntityState<T, Id>
function getInitialState<S extends object>(
additionalState: S,
entities?: readonly T[] | Record<Id, T>,
): EntityState<T, Id> & S
function getInitialState(
additionalState: any = {},
entities?: readonly T[] | Record<Id, T>,
): any {
const state = Object.assign(getInitialEntityState(), additionalState)
return entities ? stateAdapter.setAll(state, entities) : state
}
return { getInitialState }
}

8
node_modules/@reduxjs/toolkit/src/entities/index.ts generated vendored Normal file
View File

@@ -0,0 +1,8 @@
export { createEntityAdapter } from './create_adapter'
export type {
EntityState,
EntityAdapter,
Update,
IdSelector,
Comparer,
} from './models'

198
node_modules/@reduxjs/toolkit/src/entities/models.ts generated vendored Normal file
View File

@@ -0,0 +1,198 @@
import type { Draft } from 'immer'
import type { PayloadAction } from '../createAction'
import type { CastAny, Id } from '../tsHelpers'
import type { UncheckedIndexedAccess } from '../uncheckedindexed.js'
import type { GetSelectorsOptions } from './state_selectors'
/**
* @public
*/
export type EntityId = number | string
/**
* @public
*/
export type Comparer<T> = (a: T, b: T) => number
/**
* @public
*/
export type IdSelector<T, Id extends EntityId> = (model: T) => Id
/**
* @public
*/
export type Update<T, Id extends EntityId> = { id: Id; changes: Partial<T> }
/**
* @public
*/
export interface EntityState<T, Id extends EntityId> {
ids: Id[]
entities: Record<Id, T>
}
/**
* @public
*/
export interface EntityAdapterOptions<T, Id extends EntityId> {
selectId?: IdSelector<T, Id>
sortComparer?: false | Comparer<T>
}
export type PreventAny<S, T, Id extends EntityId> = CastAny<
S,
EntityState<T, Id>
>
export type DraftableEntityState<T, Id extends EntityId> =
| EntityState<T, Id>
| Draft<EntityState<T, Id>>
/**
* @public
*/
export interface EntityStateAdapter<T, Id extends EntityId> {
addOne<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
entity: T,
): S
addOne<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
action: PayloadAction<T>,
): S
addMany<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
entities: readonly T[] | Record<Id, T>,
): S
addMany<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
entities: PayloadAction<readonly T[] | Record<Id, T>>,
): S
setOne<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
entity: T,
): S
setOne<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
action: PayloadAction<T>,
): S
setMany<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
entities: readonly T[] | Record<Id, T>,
): S
setMany<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
entities: PayloadAction<readonly T[] | Record<Id, T>>,
): S
setAll<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
entities: readonly T[] | Record<Id, T>,
): S
setAll<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
entities: PayloadAction<readonly T[] | Record<Id, T>>,
): S
removeOne<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
key: Id,
): S
removeOne<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
key: PayloadAction<Id>,
): S
removeMany<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
keys: readonly Id[],
): S
removeMany<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
keys: PayloadAction<readonly Id[]>,
): S
removeAll<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
): S
updateOne<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
update: Update<T, Id>,
): S
updateOne<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
update: PayloadAction<Update<T, Id>>,
): S
updateMany<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
updates: ReadonlyArray<Update<T, Id>>,
): S
updateMany<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
updates: PayloadAction<ReadonlyArray<Update<T, Id>>>,
): S
upsertOne<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
entity: T,
): S
upsertOne<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
entity: PayloadAction<T>,
): S
upsertMany<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
entities: readonly T[] | Record<Id, T>,
): S
upsertMany<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
entities: PayloadAction<readonly T[] | Record<Id, T>>,
): S
}
/**
* @public
*/
export interface EntitySelectors<T, V, IdType extends EntityId> {
selectIds: (state: V) => IdType[]
selectEntities: (state: V) => Record<IdType, T>
selectAll: (state: V) => T[]
selectTotal: (state: V) => number
selectById: (state: V, id: IdType) => Id<UncheckedIndexedAccess<T>>
}
/**
* @public
*/
export interface EntityStateFactory<T, Id extends EntityId> {
getInitialState(
state?: undefined,
entities?: Record<Id, T> | readonly T[],
): EntityState<T, Id>
getInitialState<S extends object>(
state: S,
entities?: Record<Id, T> | readonly T[],
): EntityState<T, Id> & S
}
/**
* @public
*/
export interface EntityAdapter<T, Id extends EntityId>
extends EntityStateAdapter<T, Id>,
EntityStateFactory<T, Id>,
Required<EntityAdapterOptions<T, Id>> {
getSelectors(
selectState?: undefined,
options?: GetSelectorsOptions,
): EntitySelectors<T, EntityState<T, Id>, Id>
getSelectors<V>(
selectState: (state: V) => EntityState<T, Id>,
options?: GetSelectorsOptions,
): EntitySelectors<T, V, Id>
}

View File

@@ -0,0 +1,256 @@
import type {
IdSelector,
Comparer,
EntityStateAdapter,
Update,
EntityId,
DraftableEntityState,
} from './models'
import { createStateOperator } from './state_adapter'
import { createUnsortedStateAdapter } from './unsorted_state_adapter'
import {
selectIdValue,
ensureEntitiesArray,
splitAddedUpdatedEntities,
getCurrent,
} from './utils'
// Borrowed from Replay
export function findInsertIndex<T>(
sortedItems: T[],
item: T,
comparisonFunction: Comparer<T>,
): number {
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
}
export function insert<T>(
sortedItems: T[],
item: T,
comparisonFunction: Comparer<T>,
): T[] {
const insertAtIndex = findInsertIndex(sortedItems, item, comparisonFunction)
sortedItems.splice(insertAtIndex, 0, item)
return sortedItems
}
export function createSortedStateAdapter<T, Id extends EntityId>(
selectId: IdSelector<T, Id>,
comparer: Comparer<T>,
): EntityStateAdapter<T, Id> {
type R = DraftableEntityState<T, Id>
const { removeOne, removeMany, removeAll } =
createUnsortedStateAdapter(selectId)
function addOneMutably(entity: T, state: R): void {
return addManyMutably([entity], state)
}
function addManyMutably(
newEntities: readonly T[] | Record<Id, T>,
state: R,
existingIds?: Id[],
): void {
newEntities = ensureEntitiesArray(newEntities)
const existingKeys = new Set<Id>(existingIds ?? getCurrent(state.ids))
const models = newEntities.filter(
(model) => !existingKeys.has(selectIdValue(model, selectId)),
)
if (models.length !== 0) {
mergeFunction(state, models)
}
}
function setOneMutably(entity: T, state: R): void {
return setManyMutably([entity], state)
}
function setManyMutably(
newEntities: readonly T[] | Record<Id, T>,
state: R,
): void {
newEntities = ensureEntitiesArray(newEntities)
if (newEntities.length !== 0) {
for (const item of newEntities) {
delete (state.entities as Record<Id, T>)[selectId(item)]
}
mergeFunction(state, newEntities)
}
}
function setAllMutably(
newEntities: readonly T[] | Record<Id, T>,
state: R,
): void {
newEntities = ensureEntitiesArray(newEntities)
state.entities = {} as Record<Id, T>
state.ids = []
addManyMutably(newEntities, state, [])
}
function updateOneMutably(update: Update<T, Id>, state: R): void {
return updateManyMutably([update], state)
}
function updateManyMutably(
updates: ReadonlyArray<Update<T, Id>>,
state: R,
): void {
let appliedUpdates = false
let replacedIds = false
for (let update of updates) {
const entity: T | undefined = (state.entities as Record<Id, T>)[update.id]
if (!entity) {
continue
}
appliedUpdates = true
Object.assign(entity, update.changes)
const newId = selectId(entity)
if (update.id !== newId) {
// We do support the case where updates can change an item's ID.
// This makes things trickier - go ahead and swap the IDs in state now.
replacedIds = true
delete (state.entities as Record<Id, T>)[update.id]
const oldIndex = (state.ids as Id[]).indexOf(update.id)
state.ids[oldIndex] = newId
;(state.entities as Record<Id, T>)[newId] = entity
}
}
if (appliedUpdates) {
mergeFunction(state, [], appliedUpdates, replacedIds)
}
}
function upsertOneMutably(entity: T, state: R): void {
return upsertManyMutably([entity], state)
}
function upsertManyMutably(
newEntities: readonly T[] | Record<Id, T>,
state: R,
): void {
const [added, updated, existingIdsArray] = splitAddedUpdatedEntities<T, Id>(
newEntities,
selectId,
state,
)
if (updated.length) {
updateManyMutably(updated, state)
}
if (added.length) {
addManyMutably(added, state, existingIdsArray)
}
}
function areArraysEqual(a: readonly unknown[], b: readonly unknown[]) {
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
}
type MergeFunction = (
state: R,
addedItems: readonly T[],
appliedUpdates?: boolean,
replacedIds?: boolean,
) => void
const mergeFunction: MergeFunction = (
state,
addedItems,
appliedUpdates,
replacedIds,
) => {
const currentEntities = getCurrent(state.entities)
const currentIds = getCurrent(state.ids)
const stateEntities = state.entities as Record<Id, T>
let ids: Iterable<Id> = currentIds
if (replacedIds) {
ids = new Set(currentIds)
}
let sortedEntities: T[] = []
for (const id of ids) {
const entity = currentEntities[id]
if (entity) {
sortedEntities.push(entity)
}
}
const wasPreviouslyEmpty = sortedEntities.length === 0
// Insert/overwrite all new/updated
for (const item of addedItems) {
stateEntities[selectId(item)] = item
if (!wasPreviouslyEmpty) {
// Binary search insertion generally requires fewer comparisons
insert(sortedEntities, item, comparer)
}
}
if (wasPreviouslyEmpty) {
// All we have is the incoming values, sort them
sortedEntities = addedItems.slice().sort(comparer)
} else if (appliedUpdates) {
// We should have a _mostly_-sorted array already
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),
}
}

View File

@@ -0,0 +1,58 @@
import { produce as createNextState, isDraft } from 'immer'
import type { Draft } from 'immer'
import type { EntityId, DraftableEntityState, PreventAny } from './models'
import type { PayloadAction } from '../createAction'
import { isFSA } from '../createAction'
export const isDraftTyped = isDraft as <T>(
value: T | Draft<T>,
) => value is Draft<T>
export function createSingleArgumentStateOperator<T, Id extends EntityId>(
mutator: (state: DraftableEntityState<T, Id>) => void,
) {
const operator = createStateOperator(
(_: undefined, state: DraftableEntityState<T, Id>) => mutator(state),
)
return function operation<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
): S {
return operator(state as S, undefined)
}
}
export function createStateOperator<T, Id extends EntityId, R>(
mutator: (arg: R, state: DraftableEntityState<T, Id>) => void,
) {
return function operation<S extends DraftableEntityState<T, Id>>(
state: S,
arg: R | PayloadAction<R>,
): S {
function isPayloadActionArgument(
arg: R | PayloadAction<R>,
): arg is PayloadAction<R> {
return isFSA(arg)
}
const runMutator = (draft: DraftableEntityState<T, Id>) => {
if (isPayloadActionArgument(arg)) {
mutator(arg.payload, draft)
} else {
mutator(arg, draft)
}
}
if (isDraftTyped<DraftableEntityState<T, Id>>(state)) {
// we must already be inside a `createNextState` call, likely because
// this is being wrapped in `createReducer` or `createSlice`.
// It's safe to just pass the draft to the mutator.
runMutator(state)
// since it's a draft, we'll just return it
return state
}
return createNextState(state, runMutator)
}
}

View File

@@ -0,0 +1,77 @@
import type { CreateSelectorFunction, Selector } from 'reselect'
import { createDraftSafeSelector } from '../createDraftSafeSelector'
import type { EntityId, EntitySelectors, EntityState } from './models'
type AnyFunction = (...args: any) => any
type AnyCreateSelectorFunction = CreateSelectorFunction<
<F extends AnyFunction>(f: F) => F,
<F extends AnyFunction>(f: F) => F
>
export type GetSelectorsOptions = {
createSelector?: AnyCreateSelectorFunction
}
export function createSelectorsFactory<T, Id extends EntityId>() {
function getSelectors(
selectState?: undefined,
options?: GetSelectorsOptions,
): EntitySelectors<T, EntityState<T, Id>, Id>
function getSelectors<V>(
selectState: (state: V) => EntityState<T, Id>,
options?: GetSelectorsOptions,
): EntitySelectors<T, V, Id>
function getSelectors<V>(
selectState?: (state: V) => EntityState<T, Id>,
options: GetSelectorsOptions = {},
): EntitySelectors<T, any, Id> {
const {
createSelector = createDraftSafeSelector as AnyCreateSelectorFunction,
} = options
const selectIds = (state: EntityState<T, Id>) => state.ids
const selectEntities = (state: EntityState<T, Id>) => state.entities
const selectAll = createSelector(
selectIds,
selectEntities,
(ids, entities): T[] => ids.map((id) => entities[id]!),
)
const selectId = (_: unknown, id: Id) => id
const selectById = (entities: Record<Id, T>, id: Id) => entities[id]
const selectTotal = createSelector(selectIds, (ids) => ids.length)
if (!selectState) {
return {
selectIds,
selectEntities,
selectAll,
selectTotal,
selectById: createSelector(selectEntities, selectId, selectById),
}
}
const selectGlobalizedEntities = createSelector(
selectState as Selector<V, EntityState<T, Id>>,
selectEntities,
)
return {
selectIds: createSelector(selectState, selectIds),
selectEntities: selectGlobalizedEntities,
selectAll: createSelector(selectState, selectAll),
selectTotal: createSelector(selectState, selectTotal),
selectById: createSelector(
selectGlobalizedEntities,
selectId,
selectById,
),
}
}
return { getSelectors }
}

View File

@@ -0,0 +1,59 @@
import { createEntityAdapter, createSlice } from '../..'
import type {
PayloadAction,
Slice,
SliceCaseReducers,
UnknownAction,
} from '../..'
import type { EntityId, EntityState, IdSelector } from '../models'
import type { BookModel } from './fixtures/book'
describe('Entity Slice Enhancer', () => {
let slice: Slice<EntityState<BookModel, BookModel['id']>>
beforeEach(() => {
const indieSlice = entitySliceEnhancer({
name: 'book',
selectId: (book: BookModel) => book.id,
})
slice = indieSlice
})
it('exposes oneAdded', () => {
const book = {
id: '0',
title: 'Der Steppenwolf',
author: 'Herman Hesse',
}
const action = slice.actions.oneAdded(book)
const oneAdded = slice.reducer(undefined, action as UnknownAction)
expect(oneAdded.entities['0']).toBe(book)
})
})
interface EntitySliceArgs<T, Id extends EntityId> {
name: string
selectId: IdSelector<T, Id>
modelReducer?: SliceCaseReducers<T>
}
function entitySliceEnhancer<T, Id extends EntityId>({
name,
selectId,
modelReducer,
}: EntitySliceArgs<T, Id>) {
const modelAdapter = createEntityAdapter({
selectId,
})
return createSlice({
name,
initialState: modelAdapter.getInitialState(),
reducers: {
oneAdded(state, action: PayloadAction<T>) {
modelAdapter.addOne(state, action.payload)
},
...modelReducer,
},
})
}

View File

@@ -0,0 +1,104 @@
import type { EntityAdapter } from '../index'
import { createEntityAdapter } from '../index'
import type { PayloadAction } from '../../createAction'
import { createAction } from '../../createAction'
import { createSlice } from '../../createSlice'
import type { BookModel } from './fixtures/book'
describe('Entity State', () => {
let adapter: EntityAdapter<BookModel, string>
beforeEach(() => {
adapter = createEntityAdapter({
selectId: (book: BookModel) => book.id,
})
})
it('should let you get the initial state', () => {
const initialState = adapter.getInitialState()
expect(initialState).toEqual({
ids: [],
entities: {},
})
})
it('should let you provide additional initial state properties', () => {
const additionalProperties = { isHydrated: true }
const initialState = adapter.getInitialState(additionalProperties)
expect(initialState).toEqual({
...additionalProperties,
ids: [],
entities: {},
})
})
it('should let you provide initial entities', () => {
const book1: BookModel = { id: 'a', title: 'First' }
const initialState = adapter.getInitialState(undefined, [book1])
expect(initialState).toEqual({
ids: [book1.id],
entities: { [book1.id]: book1 },
})
const additionalProperties = { isHydrated: true }
const initialState2 = adapter.getInitialState(additionalProperties, [book1])
expect(initialState2).toEqual({
...additionalProperties,
ids: [book1.id],
entities: { [book1.id]: book1 },
})
})
it('should allow methods to be passed as reducers', () => {
const upsertBook = createAction<BookModel>('otherBooks/upsert')
const booksSlice = createSlice({
name: 'books',
initialState: adapter.getInitialState(),
reducers: {
addOne: adapter.addOne,
removeOne(state, action: PayloadAction<string>) {
// TODO The nested `produce` calls don't mutate `state` here as I would have expected.
// TODO (note that `state` here is actually an Immer Draft<S>, from `createReducer`)
// TODO However, this works if we _return_ the new plain result value instead
// TODO See https://github.com/immerjs/immer/issues/533
const result = adapter.removeOne(state, action)
return result
},
},
extraReducers: (builder) => {
builder.addCase(upsertBook, (state, action) => {
return adapter.upsertOne(state, action)
})
},
})
const { addOne, removeOne } = booksSlice.actions
const { reducer } = booksSlice
const selectors = adapter.getSelectors()
const book1: BookModel = { id: 'a', title: 'First' }
const book1a: BookModel = { id: 'a', title: 'Second' }
const afterAddOne = reducer(undefined, addOne(book1))
expect(afterAddOne.entities[book1.id]).toBe(book1)
const afterRemoveOne = reducer(afterAddOne, removeOne(book1.id))
expect(afterRemoveOne.entities[book1.id]).toBeUndefined()
expect(selectors.selectTotal(afterRemoveOne)).toBe(0)
const afterUpsertFirst = reducer(afterRemoveOne, upsertBook(book1))
const afterUpsertSecond = reducer(afterUpsertFirst, upsertBook(book1a))
expect(afterUpsertSecond.entities[book1.id]).toEqual(book1a)
expect(selectors.selectTotal(afterUpsertSecond)).toBe(1)
})
})

View File

@@ -0,0 +1,26 @@
export interface BookModel {
id: string
title: string
author?: string
}
export const AClockworkOrange: BookModel = Object.freeze({
id: 'aco',
title: 'A Clockwork Orange',
})
export const AnimalFarm: BookModel = Object.freeze({
id: 'af',
title: 'Animal Farm',
})
export const TheGreatGatsby: BookModel = Object.freeze({
id: 'tgg',
title: 'The Great Gatsby',
})
export const TheHobbit: BookModel = Object.freeze({
id: 'th',
title: 'The Hobbit',
author: 'J. R. R. Tolkien',
})

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,61 @@
import type { EntityAdapter } from '../index'
import { createEntityAdapter } from '../index'
import type { PayloadAction } from '../../createAction'
import { configureStore } from '../../configureStore'
import { createSlice } from '../../createSlice'
import type { BookModel } from './fixtures/book'
describe('createStateOperator', () => {
let adapter: EntityAdapter<BookModel, string>
beforeEach(() => {
adapter = createEntityAdapter({
selectId: (book: BookModel) => book.id,
})
})
it('Correctly mutates a draft state when inside `createNextState', () => {
const booksSlice = createSlice({
name: 'books',
initialState: adapter.getInitialState(),
reducers: {
// We should be able to call an adapter method as a mutating helper in a larger reducer
addOne(state, action: PayloadAction<BookModel>) {
// Originally, having nested `produce` calls don't mutate `state` here as I would have expected.
// (note that `state` here is actually an Immer Draft<S>, from `createReducer`)
// One woarkound was to return the new plain result value instead
// See https://github.com/immerjs/immer/issues/533
// However, after tweaking `createStateOperator` to check if the argument is a draft,
// we can just treat the operator as strictly mutating, without returning a result,
// and the result should be correct.
const result = adapter.addOne(state, action)
expect(result.ids.length).toBe(1)
//Deliberately _don't_ return result
},
// We should also be able to pass them individually as case reducers
addAnother: adapter.addOne,
},
})
const { addOne, addAnother } = booksSlice.actions
const store = configureStore({
reducer: {
books: booksSlice.reducer,
},
})
const book1: BookModel = { id: 'a', title: 'First' }
store.dispatch(addOne(book1))
const state1 = store.getState()
expect(state1.books.ids.length).toBe(1)
expect(state1.books.entities['a']).toBe(book1)
const book2: BookModel = { id: 'b', title: 'Second' }
store.dispatch(addAnother(book2))
const state2 = store.getState()
expect(state2.books.ids.length).toBe(2)
expect(state2.books.entities['b']).toBe(book2)
})
})

View File

@@ -0,0 +1,154 @@
import { createDraftSafeSelectorCreator } from '../../createDraftSafeSelector'
import type { EntityAdapter, EntityState } from '../index'
import { createEntityAdapter } from '../index'
import type { EntitySelectors } from '../models'
import type { BookModel } from './fixtures/book'
import { AClockworkOrange, AnimalFarm, TheGreatGatsby } from './fixtures/book'
import type { Selector } from 'reselect'
import { createSelector, weakMapMemoize } from 'reselect'
import { vi } from 'vitest'
describe('Entity State Selectors', () => {
describe('Composed Selectors', () => {
interface State {
books: EntityState<BookModel, string>
}
let adapter: EntityAdapter<BookModel, string>
let selectors: EntitySelectors<BookModel, State, string>
let state: State
beforeEach(() => {
adapter = createEntityAdapter({
selectId: (book: BookModel) => book.id,
})
state = {
books: adapter.setAll(adapter.getInitialState(), [
AClockworkOrange,
AnimalFarm,
TheGreatGatsby,
]),
}
selectors = adapter.getSelectors((state: State) => state.books)
})
it('should create a selector for selecting the ids', () => {
const ids = selectors.selectIds(state)
expect(ids).toEqual(state.books.ids)
})
it('should create a selector for selecting the entities', () => {
const entities = selectors.selectEntities(state)
expect(entities).toEqual(state.books.entities)
})
it('should create a selector for selecting the list of models', () => {
const models = selectors.selectAll(state)
expect(models).toEqual([AClockworkOrange, AnimalFarm, TheGreatGatsby])
})
it('should create a selector for selecting the count of models', () => {
const total = selectors.selectTotal(state)
expect(total).toEqual(3)
})
it('should create a selector for selecting a single item by ID', () => {
const first = selectors.selectById(state, AClockworkOrange.id)
expect(first).toBe(AClockworkOrange)
const second = selectors.selectById(state, AnimalFarm.id)
expect(second).toBe(AnimalFarm)
})
})
describe('Uncomposed Selectors', () => {
type State = EntityState<BookModel, string>
let adapter: EntityAdapter<BookModel, string>
let selectors: EntitySelectors<
BookModel,
EntityState<BookModel, string>,
string
>
let state: State
beforeEach(() => {
adapter = createEntityAdapter({
selectId: (book: BookModel) => book.id,
})
state = adapter.setAll(adapter.getInitialState(), [
AClockworkOrange,
AnimalFarm,
TheGreatGatsby,
])
selectors = adapter.getSelectors()
})
it('should create a selector for selecting the ids', () => {
const ids = selectors.selectIds(state)
expect(ids).toEqual(state.ids)
})
it('should create a selector for selecting the entities', () => {
const entities = selectors.selectEntities(state)
expect(entities).toEqual(state.entities)
})
it('should type single entity from Dictionary as entity type or undefined', () => {
expectType<
Selector<EntityState<BookModel, string>, BookModel | undefined>
>(createSelector(selectors.selectEntities, (entities) => entities[0]))
})
it('should create a selector for selecting the list of models', () => {
const models = selectors.selectAll(state)
expect(models).toEqual([AClockworkOrange, AnimalFarm, TheGreatGatsby])
})
it('should create a selector for selecting the count of models', () => {
const total = selectors.selectTotal(state)
expect(total).toEqual(3)
})
it('should create a selector for selecting a single item by ID', () => {
const first = selectors.selectById(state, AClockworkOrange.id)
expect(first).toBe(AClockworkOrange)
const second = selectors.selectById(state, AnimalFarm.id)
expect(second).toBe(AnimalFarm)
})
})
describe('custom createSelector instance', () => {
it('should use the custom createSelector function if provided', () => {
const memoizeSpy = vi.fn(
// test that we're allowed to pass memoizers with different options, as long as they're optional
<F extends (...args: any[]) => any>(fn: F, param?: boolean) => fn,
)
const createCustomSelector = createDraftSafeSelectorCreator(memoizeSpy)
const adapter = createEntityAdapter({
selectId: (book: BookModel) => book.id,
})
adapter.getSelectors(undefined, { createSelector: createCustomSelector })
expect(memoizeSpy).toHaveBeenCalled()
memoizeSpy.mockClear()
})
})
})
function expectType<T>(t: T) {
return t
}

View File

@@ -0,0 +1,717 @@
import type { EntityAdapter, EntityState } from '../models'
import { createEntityAdapter } from '../create_adapter'
import type { BookModel } from './fixtures/book'
import {
TheGreatGatsby,
AClockworkOrange,
AnimalFarm,
TheHobbit,
} from './fixtures/book'
import { createNextState } from '../..'
describe('Unsorted State Adapter', () => {
let adapter: EntityAdapter<BookModel, string>
let state: EntityState<BookModel, string>
beforeAll(() => {
//eslint-disable-next-line
Object.defineProperty(Array.prototype, 'unwantedField', {
enumerable: true,
configurable: true,
value: 'This should not appear anywhere',
})
})
afterAll(() => {
delete (Array.prototype as any).unwantedField
})
beforeEach(() => {
adapter = createEntityAdapter({
selectId: (book: BookModel) => book.id,
})
state = { ids: [], entities: {} }
})
it('should let you add one entity to the state', () => {
const withOneEntity = adapter.addOne(state, TheGreatGatsby)
expect(withOneEntity).toEqual({
ids: [TheGreatGatsby.id],
entities: {
[TheGreatGatsby.id]: TheGreatGatsby,
},
})
})
it('should not change state if you attempt to re-add an entity', () => {
const withOneEntity = adapter.addOne(state, TheGreatGatsby)
const readded = adapter.addOne(withOneEntity, TheGreatGatsby)
expect(readded).toBe(withOneEntity)
})
it('should let you add many entities to the state', () => {
const withOneEntity = adapter.addOne(state, TheGreatGatsby)
const withManyMore = adapter.addMany(withOneEntity, [
AClockworkOrange,
AnimalFarm,
])
expect(withManyMore).toEqual({
ids: [TheGreatGatsby.id, AClockworkOrange.id, AnimalFarm.id],
entities: {
[TheGreatGatsby.id]: TheGreatGatsby,
[AClockworkOrange.id]: AClockworkOrange,
[AnimalFarm.id]: AnimalFarm,
},
})
})
it('should let you add many entities to the state from a dictionary', () => {
const withOneEntity = adapter.addOne(state, TheGreatGatsby)
const withManyMore = adapter.addMany(withOneEntity, {
[AClockworkOrange.id]: AClockworkOrange,
[AnimalFarm.id]: AnimalFarm,
})
expect(withManyMore).toEqual({
ids: [TheGreatGatsby.id, AClockworkOrange.id, AnimalFarm.id],
entities: {
[TheGreatGatsby.id]: TheGreatGatsby,
[AClockworkOrange.id]: AClockworkOrange,
[AnimalFarm.id]: AnimalFarm,
},
})
})
it('should remove existing and add new ones on setAll', () => {
const withOneEntity = adapter.addOne(state, TheGreatGatsby)
const withAll = adapter.setAll(withOneEntity, [
AClockworkOrange,
AnimalFarm,
])
expect(withAll).toEqual({
ids: [AClockworkOrange.id, AnimalFarm.id],
entities: {
[AClockworkOrange.id]: AClockworkOrange,
[AnimalFarm.id]: AnimalFarm,
},
})
})
it('should remove existing and add new ones on setAll when passing in a dictionary', () => {
const withOneEntity = adapter.addOne(state, TheGreatGatsby)
const withAll = adapter.setAll(withOneEntity, {
[AClockworkOrange.id]: AClockworkOrange,
[AnimalFarm.id]: AnimalFarm,
})
expect(withAll).toEqual({
ids: [AClockworkOrange.id, AnimalFarm.id],
entities: {
[AClockworkOrange.id]: AClockworkOrange,
[AnimalFarm.id]: AnimalFarm,
},
})
})
it('should let you add remove an entity from the state', () => {
const withOneEntity = adapter.addOne(state, TheGreatGatsby)
const withoutOne = adapter.removeOne(withOneEntity, TheGreatGatsby.id)
expect(withoutOne).toEqual({
ids: [],
entities: {},
})
})
it('should let you remove many entities by id from the state', () => {
const withAll = adapter.setAll(state, [
TheGreatGatsby,
AClockworkOrange,
AnimalFarm,
])
const withoutMany = adapter.removeMany(withAll, [
TheGreatGatsby.id,
AClockworkOrange.id,
])
expect(withoutMany).toEqual({
ids: [AnimalFarm.id],
entities: {
[AnimalFarm.id]: AnimalFarm,
},
})
})
it('should let you remove all entities from the state', () => {
const withAll = adapter.setAll(state, [
TheGreatGatsby,
AClockworkOrange,
AnimalFarm,
])
const withoutAll = adapter.removeAll(withAll)
expect(withoutAll).toEqual({
ids: [],
entities: {},
})
})
it('should let you update an entity in the state', () => {
const withOne = adapter.addOne(state, TheGreatGatsby)
const changes = { title: 'A New Hope' }
const withUpdates = adapter.updateOne(withOne, {
id: TheGreatGatsby.id,
changes,
})
expect(withUpdates).toEqual({
ids: [TheGreatGatsby.id],
entities: {
[TheGreatGatsby.id]: {
...TheGreatGatsby,
...changes,
},
},
})
})
it('should not change state if you attempt to update an entity that has not been added', () => {
const withUpdates = adapter.updateOne(state, {
id: TheGreatGatsby.id,
changes: { title: 'A New Title' },
})
expect(withUpdates).toBe(state)
})
it('should not change ids state if you attempt to update an entity that has already been added', () => {
const withOne = adapter.addOne(state, TheGreatGatsby)
const changes = { title: 'A New Hope' }
const withUpdates = adapter.updateOne(withOne, {
id: TheGreatGatsby.id,
changes,
})
expect(withOne.ids).toBe(withUpdates.ids)
})
it('should let you update the id of entity', () => {
const withOne = adapter.addOne(state, TheGreatGatsby)
const changes = { id: 'A New Id' }
const withUpdates = adapter.updateOne(withOne, {
id: TheGreatGatsby.id,
changes,
})
expect(withUpdates).toEqual({
ids: [changes.id],
entities: {
[changes.id]: {
...TheGreatGatsby,
...changes,
},
},
})
})
it('should let you update many entities by id in the state', () => {
const firstChange = { title: 'First Change' }
const secondChange = { title: 'Second Change' }
const withMany = adapter.setAll(state, [TheGreatGatsby, AClockworkOrange])
const withUpdates = adapter.updateMany(withMany, [
{ id: TheGreatGatsby.id, changes: firstChange },
{ id: AClockworkOrange.id, changes: secondChange },
])
expect(withUpdates).toEqual({
ids: [TheGreatGatsby.id, AClockworkOrange.id],
entities: {
[TheGreatGatsby.id]: {
...TheGreatGatsby,
...firstChange,
},
[AClockworkOrange.id]: {
...AClockworkOrange,
...secondChange,
},
},
})
})
it("doesn't break when multiple renames of one item occur", () => {
const withA = adapter.addOne(state, { id: 'a', title: 'First' })
const withUpdates = adapter.updateMany(withA, [
{ id: 'a', changes: { id: 'b' } },
{ id: 'a', changes: { id: 'c' } },
])
const { ids, entities } = withUpdates
/*
Original code failed with a mish-mash of values, like:
{
ids: [ 'c' ],
entities: { b: { id: 'b', title: 'First' }, c: { id: 'c' } }
}
We now expect that only 'c' will be left:
{
ids: [ 'c' ],
entities: { c: { id: 'c', title: 'First' } }
}
*/
expect(ids.length).toBe(1)
expect(ids).toEqual(['c'])
expect(entities.a).toBeFalsy()
expect(entities.b).toBeFalsy()
expect(entities.c).toBeTruthy()
})
it('should let you add one entity to the state with upsert()', () => {
const withOneEntity = adapter.upsertOne(state, TheGreatGatsby)
expect(withOneEntity).toEqual({
ids: [TheGreatGatsby.id],
entities: {
[TheGreatGatsby.id]: TheGreatGatsby,
},
})
})
it('should let you update an entity in the state with upsert()', () => {
const withOne = adapter.addOne(state, TheGreatGatsby)
const changes = { title: 'A New Hope' }
const withUpdates = adapter.upsertOne(withOne, {
...TheGreatGatsby,
...changes,
})
expect(withUpdates).toEqual({
ids: [TheGreatGatsby.id],
entities: {
[TheGreatGatsby.id]: {
...TheGreatGatsby,
...changes,
},
},
})
})
it('should let you upsert many entities in the state', () => {
const firstChange = { title: 'First Change' }
const withMany = adapter.setAll(state, [TheGreatGatsby])
const withUpserts = adapter.upsertMany(withMany, [
{ ...TheGreatGatsby, ...firstChange },
AClockworkOrange,
])
expect(withUpserts).toEqual({
ids: [TheGreatGatsby.id, AClockworkOrange.id],
entities: {
[TheGreatGatsby.id]: {
...TheGreatGatsby,
...firstChange,
},
[AClockworkOrange.id]: AClockworkOrange,
},
})
})
it('should let you upsert many entities in the state when passing in a dictionary', () => {
const firstChange = { title: 'Zack' }
const withMany = adapter.setAll(state, [TheGreatGatsby])
const withUpserts = adapter.upsertMany(withMany, {
[TheGreatGatsby.id]: { ...TheGreatGatsby, ...firstChange },
[AClockworkOrange.id]: AClockworkOrange,
})
expect(withUpserts).toEqual({
ids: [TheGreatGatsby.id, AClockworkOrange.id],
entities: {
[TheGreatGatsby.id]: {
...TheGreatGatsby,
...firstChange,
},
[AClockworkOrange.id]: AClockworkOrange,
},
})
})
it('should let you add a new entity in the state with setOne()', () => {
const withOne = adapter.setOne(state, TheGreatGatsby)
expect(withOne).toEqual({
ids: [TheGreatGatsby.id],
entities: {
[TheGreatGatsby.id]: TheGreatGatsby,
},
})
})
it('should let you replace an entity in the state with setOne()', () => {
let withOne = adapter.setOne(state, TheHobbit)
const changeWithoutAuthor = { id: TheHobbit.id, title: 'Silmarillion' }
withOne = adapter.setOne(withOne, changeWithoutAuthor)
expect(withOne).toEqual({
ids: [TheHobbit.id],
entities: {
[TheHobbit.id]: changeWithoutAuthor,
},
})
})
it('should let you set many entities in the state', () => {
const changeWithoutAuthor = { id: TheHobbit.id, title: 'Silmarillion' }
const withMany = adapter.setAll(state, [TheHobbit])
const withSetMany = adapter.setMany(withMany, [
changeWithoutAuthor,
AClockworkOrange,
])
expect(withSetMany).toEqual({
ids: [TheHobbit.id, AClockworkOrange.id],
entities: {
[TheHobbit.id]: changeWithoutAuthor,
[AClockworkOrange.id]: AClockworkOrange,
},
})
})
it('should let you set many entities in the state when passing in a dictionary', () => {
const changeWithoutAuthor = { id: TheHobbit.id, title: 'Silmarillion' }
const withMany = adapter.setAll(state, [TheHobbit])
const withSetMany = adapter.setMany(withMany, {
[TheHobbit.id]: changeWithoutAuthor,
[AClockworkOrange.id]: AClockworkOrange,
})
expect(withSetMany).toEqual({
ids: [TheHobbit.id, AClockworkOrange.id],
entities: {
[TheHobbit.id]: changeWithoutAuthor,
[AClockworkOrange.id]: AClockworkOrange,
},
})
})
it("only returns one entry for that id in the id's array", () => {
const book1: BookModel = { id: 'a', title: 'First' }
const book2: BookModel = { id: 'b', title: 'Second' }
const initialState = adapter.getInitialState()
const withItems = adapter.addMany(initialState, [book1, book2])
expect(withItems.ids).toEqual(['a', 'b'])
const withUpdate = adapter.updateOne(withItems, {
id: 'a',
changes: { id: 'b' },
})
expect(withUpdate.ids).toEqual(['b'])
expect(withUpdate.entities['b']!.title).toBe(book1.title)
})
describe('can be used mutably when wrapped in createNextState', () => {
test('removeAll', () => {
const withTwo = adapter.addMany(state, [TheGreatGatsby, AnimalFarm])
const result = createNextState(withTwo, (draft) => {
adapter.removeAll(draft)
})
expect(result).toEqual({
entities: {},
ids: [],
})
})
test('addOne', () => {
const result = createNextState(state, (draft) => {
adapter.addOne(draft, TheGreatGatsby)
})
expect(result).toEqual({
entities: {
tgg: {
id: 'tgg',
title: 'The Great Gatsby',
},
},
ids: ['tgg'],
})
})
test('addMany', () => {
const result = createNextState(state, (draft) => {
adapter.addMany(draft, [TheGreatGatsby, AnimalFarm])
})
expect(result).toEqual({
entities: {
af: {
id: 'af',
title: 'Animal Farm',
},
tgg: {
id: 'tgg',
title: 'The Great Gatsby',
},
},
ids: ['tgg', 'af'],
})
})
test('setAll', () => {
const result = createNextState(state, (draft) => {
adapter.setAll(draft, [TheGreatGatsby, AnimalFarm])
})
expect(result).toEqual({
entities: {
af: {
id: 'af',
title: 'Animal Farm',
},
tgg: {
id: 'tgg',
title: 'The Great Gatsby',
},
},
ids: ['tgg', 'af'],
})
})
test('updateOne', () => {
const withOne = adapter.addOne(state, TheGreatGatsby)
const changes = { title: 'A New Hope' }
const result = createNextState(withOne, (draft) => {
adapter.updateOne(draft, {
id: TheGreatGatsby.id,
changes,
})
})
expect(result).toEqual({
entities: {
tgg: {
id: 'tgg',
title: 'A New Hope',
},
},
ids: ['tgg'],
})
})
test('updateMany', () => {
const firstChange = { title: 'First Change' }
const secondChange = { title: 'Second Change' }
const thirdChange = { title: 'Third Change' }
const fourthChange = { author: 'Fourth Change' }
const withMany = adapter.setAll(state, [
TheGreatGatsby,
AClockworkOrange,
TheHobbit,
])
const result = createNextState(withMany, (draft) => {
adapter.updateMany(draft, [
{ id: TheHobbit.id, changes: firstChange },
{ id: TheGreatGatsby.id, changes: secondChange },
{ id: AClockworkOrange.id, changes: thirdChange },
{ id: TheHobbit.id, changes: fourthChange },
])
})
expect(result).toEqual({
entities: {
aco: {
id: 'aco',
title: 'Third Change',
},
tgg: {
id: 'tgg',
title: 'Second Change',
},
th: {
author: 'Fourth Change',
id: 'th',
title: 'First Change',
},
},
ids: ['tgg', 'aco', 'th'],
})
})
test('upsertOne (insert)', () => {
const result = createNextState(state, (draft) => {
adapter.upsertOne(draft, TheGreatGatsby)
})
expect(result).toEqual({
entities: {
tgg: {
id: 'tgg',
title: 'The Great Gatsby',
},
},
ids: ['tgg'],
})
})
test('upsertOne (update)', () => {
const withOne = adapter.upsertOne(state, TheGreatGatsby)
const result = createNextState(withOne, (draft) => {
adapter.upsertOne(draft, {
id: TheGreatGatsby.id,
title: 'A New Hope',
})
})
expect(result).toEqual({
entities: {
tgg: {
id: 'tgg',
title: 'A New Hope',
},
},
ids: ['tgg'],
})
})
test('upsertMany', () => {
const withOne = adapter.upsertOne(state, TheGreatGatsby)
const result = createNextState(withOne, (draft) => {
adapter.upsertMany(draft, [
{
id: TheGreatGatsby.id,
title: 'A New Hope',
},
AnimalFarm,
])
})
expect(result).toEqual({
entities: {
af: {
id: 'af',
title: 'Animal Farm',
},
tgg: {
id: 'tgg',
title: 'A New Hope',
},
},
ids: ['tgg', 'af'],
})
})
test('setOne (insert)', () => {
const result = createNextState(state, (draft) => {
adapter.setOne(draft, TheGreatGatsby)
})
expect(result).toEqual({
entities: {
tgg: {
id: 'tgg',
title: 'The Great Gatsby',
},
},
ids: ['tgg'],
})
})
test('setOne (update)', () => {
const withOne = adapter.setOne(state, TheHobbit)
const result = createNextState(withOne, (draft) => {
adapter.setOne(draft, {
id: TheHobbit.id,
title: 'Silmarillion',
})
})
expect(result).toEqual({
entities: {
th: {
id: 'th',
title: 'Silmarillion',
},
},
ids: ['th'],
})
})
test('setMany', () => {
const withOne = adapter.setOne(state, TheHobbit)
const result = createNextState(withOne, (draft) => {
adapter.setMany(draft, [
{
id: TheHobbit.id,
title: 'Silmarillion',
},
AnimalFarm,
])
})
expect(result).toEqual({
entities: {
af: {
id: 'af',
title: 'Animal Farm',
},
th: {
id: 'th',
title: 'Silmarillion',
},
},
ids: ['th', 'af'],
})
})
test('removeOne', () => {
const withTwo = adapter.addMany(state, [TheGreatGatsby, AnimalFarm])
const result = createNextState(withTwo, (draft) => {
adapter.removeOne(draft, TheGreatGatsby.id)
})
expect(result).toEqual({
entities: {
af: {
id: 'af',
title: 'Animal Farm',
},
},
ids: ['af'],
})
})
test('removeMany', () => {
const withThree = adapter.addMany(state, [
TheGreatGatsby,
AnimalFarm,
AClockworkOrange,
])
const result = createNextState(withThree, (draft) => {
adapter.removeMany(draft, [TheGreatGatsby.id, AnimalFarm.id])
})
expect(result).toEqual({
entities: {
aco: {
id: 'aco',
title: 'A Clockwork Orange',
},
},
ids: ['aco'],
})
})
})
})

View File

@@ -0,0 +1,66 @@
import { vi } from 'vitest'
import { AClockworkOrange } from './fixtures/book'
describe('Entity utils', () => {
describe(`selectIdValue()`, () => {
const OLD_ENV = process.env
beforeEach(() => {
vi.resetModules() // this is important - it clears the cache
process.env = { ...OLD_ENV, NODE_ENV: 'development' }
})
afterEach(() => {
process.env = OLD_ENV
vi.resetAllMocks()
})
it('should not warn when key does exist', async () => {
const { selectIdValue } = await import('../utils')
const spy = vi.spyOn(console, 'warn')
selectIdValue(AClockworkOrange, (book: any) => book.id)
expect(spy).not.toHaveBeenCalled()
})
it('should warn when key does not exist in dev mode', async () => {
const { selectIdValue } = await import('../utils')
const spy = vi.spyOn(console, 'warn')
selectIdValue(AClockworkOrange, (book: any) => book.foo)
expect(spy).toHaveBeenCalled()
})
it('should warn when key is undefined in dev mode', async () => {
const { selectIdValue } = await import('../utils')
const spy = vi.spyOn(console, 'warn')
const undefinedAClockworkOrange = { ...AClockworkOrange, id: undefined }
selectIdValue(undefinedAClockworkOrange, (book: any) => book.id)
expect(spy).toHaveBeenCalled()
})
it('should not warn when key does not exist in prod mode', async () => {
process.env.NODE_ENV = 'production'
const { selectIdValue } = await import('../utils')
const spy = vi.spyOn(console, 'warn')
selectIdValue(AClockworkOrange, (book: any) => book.foo)
expect(spy).not.toHaveBeenCalled()
})
it('should not warn when key is undefined in prod mode', async () => {
process.env.NODE_ENV = 'production'
const { selectIdValue } = await import('../utils')
const spy = vi.spyOn(console, 'warn')
const undefinedAClockworkOrange = { ...AClockworkOrange, id: undefined }
selectIdValue(undefinedAClockworkOrange, (book: any) => book.id)
expect(spy).not.toHaveBeenCalled()
})
})
})

View File

@@ -0,0 +1,204 @@
import type { Draft } from 'immer'
import type {
EntityStateAdapter,
IdSelector,
Update,
EntityId,
DraftableEntityState,
} from './models'
import {
createStateOperator,
createSingleArgumentStateOperator,
} from './state_adapter'
import {
selectIdValue,
ensureEntitiesArray,
splitAddedUpdatedEntities,
} from './utils'
export function createUnsortedStateAdapter<T, Id extends EntityId>(
selectId: IdSelector<T, Id>,
): EntityStateAdapter<T, Id> {
type R = DraftableEntityState<T, Id>
function addOneMutably(entity: T, state: R): void {
const key = selectIdValue(entity, selectId)
if (key in state.entities) {
return
}
state.ids.push(key as Id & Draft<Id>)
;(state.entities as Record<Id, T>)[key] = entity
}
function addManyMutably(
newEntities: readonly T[] | Record<Id, T>,
state: R,
): void {
newEntities = ensureEntitiesArray(newEntities)
for (const entity of newEntities) {
addOneMutably(entity, state)
}
}
function setOneMutably(entity: T, state: R): void {
const key = selectIdValue(entity, selectId)
if (!(key in state.entities)) {
state.ids.push(key as Id & Draft<Id>)
}
;(state.entities as Record<Id, T>)[key] = entity
}
function setManyMutably(
newEntities: readonly T[] | Record<Id, T>,
state: R,
): void {
newEntities = ensureEntitiesArray(newEntities)
for (const entity of newEntities) {
setOneMutably(entity, state)
}
}
function setAllMutably(
newEntities: readonly T[] | Record<Id, T>,
state: R,
): void {
newEntities = ensureEntitiesArray(newEntities)
state.ids = []
state.entities = {} as Record<Id, T>
addManyMutably(newEntities, state)
}
function removeOneMutably(key: Id, state: R): void {
return removeManyMutably([key], state)
}
function removeManyMutably(keys: readonly Id[], state: R): void {
let didMutate = false
keys.forEach((key) => {
if (key in state.entities) {
delete (state.entities as Record<Id, T>)[key]
didMutate = true
}
})
if (didMutate) {
state.ids = (state.ids as Id[]).filter((id) => id in state.entities) as
| Id[]
| Draft<Id[]>
}
}
function removeAllMutably(state: R): void {
Object.assign(state, {
ids: [],
entities: {},
})
}
function takeNewKey(
keys: { [id: string]: Id },
update: Update<T, Id>,
state: R,
): boolean {
const original: T | undefined = (state.entities as Record<Id, T>)[update.id]
if (original === undefined) {
return false
}
const updated: T = Object.assign({}, original, update.changes)
const newKey = selectIdValue(updated, selectId)
const hasNewKey = newKey !== update.id
if (hasNewKey) {
keys[update.id] = newKey
delete (state.entities as Record<Id, T>)[update.id]
}
;(state.entities as Record<Id, T>)[newKey] = updated
return hasNewKey
}
function updateOneMutably(update: Update<T, Id>, state: R): void {
return updateManyMutably([update], state)
}
function updateManyMutably(
updates: ReadonlyArray<Update<T, Id>>,
state: R,
): void {
const newKeys: { [id: string]: Id } = {}
const updatesPerEntity: { [id: string]: Update<T, Id> } = {}
updates.forEach((update) => {
// Only apply updates to entities that currently exist
if (update.id in state.entities) {
// If there are multiple updates to one entity, merge them together
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 as T, selectId),
)
}
}
}
function upsertOneMutably(entity: T, state: R): void {
return upsertManyMutably([entity], state)
}
function upsertManyMutably(
newEntities: readonly T[] | Record<Id, T>,
state: R,
): void {
const [added, updated] = splitAddedUpdatedEntities<T, Id>(
newEntities,
selectId,
state,
)
updateManyMutably(updated, state)
addManyMutably(added, 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),
}
}

66
node_modules/@reduxjs/toolkit/src/entities/utils.ts generated vendored Normal file
View File

@@ -0,0 +1,66 @@
import type { Draft } from 'immer'
import { current, isDraft } from 'immer'
import type {
DraftableEntityState,
EntityId,
IdSelector,
Update,
} from './models'
export function selectIdValue<T, Id extends EntityId>(
entity: T,
selectId: IdSelector<T, Id>,
) {
const key = selectId(entity)
if (process.env.NODE_ENV !== 'production' && key === undefined) {
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
}
export function ensureEntitiesArray<T, Id extends EntityId>(
entities: readonly T[] | Record<Id, T>,
): readonly T[] {
if (!Array.isArray(entities)) {
entities = Object.values(entities)
}
return entities
}
export function getCurrent<T>(value: T | Draft<T>): T {
return (isDraft(value) ? current(value) : value) as T
}
export function splitAddedUpdatedEntities<T, Id extends EntityId>(
newEntities: readonly T[] | Record<Id, T>,
selectId: IdSelector<T, Id>,
state: DraftableEntityState<T, Id>,
): [T[], Update<T, Id>[], Id[]] {
newEntities = ensureEntitiesArray(newEntities)
const existingIdsArray = getCurrent(state.ids)
const existingIds = new Set<Id>(existingIdsArray)
const added: T[] = []
const updated: Update<T, Id>[] = []
for (const entity of newEntities) {
const id = selectIdValue(entity, selectId)
if (existingIds.has(id)) {
updated.push({ id, changes: entity })
} else {
added.push(entity)
}
}
return [added, updated, existingIdsArray]
}

View File

@@ -0,0 +1,13 @@
/**
* Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js
*
* Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes
* during build.
* @param {number} code
*/
export function formatProdErrorMessage(code: number) {
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. '
)
}

View File

@@ -0,0 +1,31 @@
import type { StoreEnhancer } from 'redux'
import type { AutoBatchOptions } from './autoBatchEnhancer'
import { autoBatchEnhancer } from './autoBatchEnhancer'
import { Tuple } from './utils'
import type { Middlewares } from './configureStore'
import type { ExtractDispatchExtensions } from './tsHelpers'
type GetDefaultEnhancersOptions = {
autoBatch?: boolean | AutoBatchOptions
}
export type GetDefaultEnhancers<M extends Middlewares<any>> = (
options?: GetDefaultEnhancersOptions,
) => Tuple<[StoreEnhancer<{ dispatch: ExtractDispatchExtensions<M> }>]>
export const buildGetDefaultEnhancers = <M extends Middlewares<any>>(
middlewareEnhancer: StoreEnhancer<{ dispatch: ExtractDispatchExtensions<M> }>,
): GetDefaultEnhancers<M> =>
function getDefaultEnhancers(options) {
const { autoBatch = true } = options ?? {}
let enhancerArray = new Tuple<StoreEnhancer[]>(middlewareEnhancer)
if (autoBatch) {
enhancerArray.push(
autoBatchEnhancer(
typeof autoBatch === 'object' ? autoBatch : undefined,
),
)
}
return enhancerArray as any
}

View File

@@ -0,0 +1,113 @@
import type { Middleware, UnknownAction } from 'redux'
import type { ThunkMiddleware } from 'redux-thunk'
import { thunk as thunkMiddleware, withExtraArgument } from 'redux-thunk'
import type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware'
import { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware'
import type { ImmutableStateInvariantMiddlewareOptions } from './immutableStateInvariantMiddleware'
/* PROD_START_REMOVE_UMD */
import { createImmutableStateInvariantMiddleware } from './immutableStateInvariantMiddleware'
/* PROD_STOP_REMOVE_UMD */
import type { SerializableStateInvariantMiddlewareOptions } from './serializableStateInvariantMiddleware'
import { createSerializableStateInvariantMiddleware } from './serializableStateInvariantMiddleware'
import type { ExcludeFromTuple } from './tsHelpers'
import { Tuple } from './utils'
function isBoolean(x: any): x is boolean {
return typeof x === 'boolean'
}
interface ThunkOptions<E = any> {
extraArgument: E
}
interface GetDefaultMiddlewareOptions {
thunk?: boolean | ThunkOptions
immutableCheck?: boolean | ImmutableStateInvariantMiddlewareOptions
serializableCheck?: boolean | SerializableStateInvariantMiddlewareOptions
actionCreatorCheck?: boolean | ActionCreatorInvariantMiddlewareOptions
}
export type ThunkMiddlewareFor<
S,
O extends GetDefaultMiddlewareOptions = {},
> = O extends {
thunk: false
}
? never
: O extends { thunk: { extraArgument: infer E } }
? ThunkMiddleware<S, UnknownAction, E>
: ThunkMiddleware<S, UnknownAction>
export type GetDefaultMiddleware<S = any> = <
O extends GetDefaultMiddlewareOptions = {
thunk: true
immutableCheck: true
serializableCheck: true
actionCreatorCheck: true
},
>(
options?: O,
) => Tuple<ExcludeFromTuple<[ThunkMiddlewareFor<S, O>], never>>
export const buildGetDefaultMiddleware = <S = any>(): GetDefaultMiddleware<S> =>
function getDefaultMiddleware(options) {
const {
thunk = true,
immutableCheck = true,
serializableCheck = true,
actionCreatorCheck = true,
} = options ?? {}
let middlewareArray = new Tuple<Middleware[]>()
if (thunk) {
if (isBoolean(thunk)) {
middlewareArray.push(thunkMiddleware)
} else {
middlewareArray.push(withExtraArgument(thunk.extraArgument))
}
}
if (process.env.NODE_ENV !== 'production') {
if (immutableCheck) {
/* PROD_START_REMOVE_UMD */
let immutableOptions: ImmutableStateInvariantMiddlewareOptions = {}
if (!isBoolean(immutableCheck)) {
immutableOptions = immutableCheck
}
middlewareArray.unshift(
createImmutableStateInvariantMiddleware(immutableOptions),
)
/* PROD_STOP_REMOVE_UMD */
}
if (serializableCheck) {
let serializableOptions: SerializableStateInvariantMiddlewareOptions =
{}
if (!isBoolean(serializableCheck)) {
serializableOptions = serializableCheck
}
middlewareArray.push(
createSerializableStateInvariantMiddleware(serializableOptions),
)
}
if (actionCreatorCheck) {
let actionCreatorOptions: ActionCreatorInvariantMiddlewareOptions = {}
if (!isBoolean(actionCreatorCheck)) {
actionCreatorOptions = actionCreatorCheck
}
middlewareArray.unshift(
createActionCreatorInvariantMiddleware(actionCreatorOptions),
)
}
}
return middlewareArray as any
}

View File

@@ -0,0 +1,263 @@
import type { Middleware } from 'redux'
import type { IgnorePaths } from './serializableStateInvariantMiddleware'
import { getTimeMeasureUtils } from './utils'
type EntryProcessor = (key: string, value: any) => any
/**
* The default `isImmutable` function.
*
* @public
*/
export function isImmutableDefault(value: unknown): boolean {
return typeof value !== 'object' || value == null || Object.isFrozen(value)
}
export function trackForMutations(
isImmutable: IsImmutableFunc,
ignorePaths: IgnorePaths | undefined,
obj: any,
) {
const trackedProperties = trackProperties(isImmutable, ignorePaths, obj)
return {
detectMutations() {
return detectMutations(isImmutable, ignorePaths, trackedProperties, obj)
},
}
}
interface TrackedProperty {
value: any
children: Record<string, any>
}
function trackProperties(
isImmutable: IsImmutableFunc,
ignorePaths: IgnorePaths = [],
obj: Record<string, any>,
path: string = '',
checkedObjects: Set<Record<string, any>> = new Set(),
) {
const tracked: Partial<TrackedProperty> = { value: obj }
if (!isImmutable(obj) && !checkedObjects.has(obj)) {
checkedObjects.add(obj)
tracked.children = {}
for (const key in obj) {
const childPath = path ? path + '.' + key : key
if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) {
continue
}
tracked.children[key] = trackProperties(
isImmutable,
ignorePaths,
obj[key],
childPath,
)
}
}
return tracked as TrackedProperty
}
function detectMutations(
isImmutable: IsImmutableFunc,
ignoredPaths: IgnorePaths = [],
trackedProperty: TrackedProperty,
obj: any,
sameParentRef: boolean = false,
path: string = '',
): { wasMutated: boolean; path?: string } {
const prevObj = trackedProperty ? trackedProperty.value : undefined
const sameRef = prevObj === obj
if (sameParentRef && !sameRef && !Number.isNaN(obj)) {
return { wasMutated: true, path }
}
if (isImmutable(prevObj) || isImmutable(obj)) {
return { wasMutated: false }
}
// Gather all keys from prev (tracked) and after objs
const keysToDetect: Record<string, boolean> = {}
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 }
}
type IsImmutableFunc = (value: any) => boolean
/**
* Options for `createImmutableStateInvariantMiddleware()`.
*
* @public
*/
export interface ImmutableStateInvariantMiddlewareOptions {
/**
Callback function to check if a value is considered to be immutable.
This function is applied recursively to every value contained in the state.
The default implementation will return true for primitive types
(like numbers, strings, booleans, null and undefined).
*/
isImmutable?: IsImmutableFunc
/**
An array of dot-separated path strings that match named nodes from
the root state to ignore when checking for immutability.
Defaults to undefined
*/
ignoredPaths?: IgnorePaths
/** Print a warning if checks take longer than N ms. Default: 32ms */
warnAfter?: number
}
/**
* Creates a middleware that checks whether any state was mutated in between
* dispatches or during a dispatch. If any mutations are detected, an error is
* thrown.
*
* @param options Middleware options.
*
* @public
*/
export function createImmutableStateInvariantMiddleware(
options: ImmutableStateInvariantMiddlewareOptions = {},
): Middleware {
if (process.env.NODE_ENV === 'production') {
return () => (next) => (action) => next(action)
} else {
function stringify(
obj: any,
serializer?: EntryProcessor,
indent?: string | number,
decycler?: EntryProcessor,
): string {
return JSON.stringify(obj, getSerialize(serializer, decycler), indent)
}
function getSerialize(
serializer?: EntryProcessor,
decycler?: EntryProcessor,
): EntryProcessor {
let stack: any[] = [],
keys: any[] = []
if (!decycler)
decycler = function (_: string, value: any) {
if (stack[0] === value) return '[Circular ~]'
return (
'[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']'
)
}
return function (this: any, key: string, value: any) {
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)
}
}
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()
// Track before potentially not meeting the invariant
tracker = track(state)
if (result.wasMutated) {
throw new Error(
`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()
// Track before potentially not meeting the invariant
tracker = track(state)
if (result.wasMutated) {
throw new Error(
`A state mutation was detected inside a dispatch, in the path: ${
result.path || ''
}. Take a look at the reducer(s) handling the action ${stringify(
action,
)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`,
)
}
})
measureUtils.warnIfExceeded()
return dispatchedAction
}
}
}
}

214
node_modules/@reduxjs/toolkit/src/index.ts generated vendored Normal file
View File

@@ -0,0 +1,214 @@
// This must remain here so that the `mangleErrors.cjs` build script
// does not have to import this into each source file it rewrites.
import { formatProdErrorMessage } from './formatProdErrorMessage'
export * from 'redux'
export {
produce as createNextState,
current,
freeze,
original,
isDraft,
} from 'immer'
export type { Draft } from 'immer'
export {
createSelector,
createSelectorCreator,
lruMemoize,
weakMapMemoize,
} from 'reselect'
export type { Selector, OutputSelector } from 'reselect'
export {
createDraftSafeSelector,
createDraftSafeSelectorCreator,
} from './createDraftSafeSelector'
export type { ThunkAction, ThunkDispatch, ThunkMiddleware } from 'redux-thunk'
export {
// js
configureStore,
} from './configureStore'
export type {
// types
ConfigureStoreOptions,
EnhancedStore,
} from './configureStore'
export type { DevToolsEnhancerOptions } from './devtoolsExtension'
export {
// js
createAction,
isActionCreator,
isFSA as isFluxStandardAction,
} from './createAction'
export type {
// types
PayloadAction,
PayloadActionCreator,
ActionCreatorWithNonInferrablePayload,
ActionCreatorWithOptionalPayload,
ActionCreatorWithPayload,
ActionCreatorWithoutPayload,
ActionCreatorWithPreparedPayload,
PrepareAction,
} from './createAction'
export {
// js
createReducer,
} from './createReducer'
export type {
// types
Actions,
CaseReducer,
CaseReducers,
} from './createReducer'
export {
// js
createSlice,
buildCreateSlice,
asyncThunkCreator,
ReducerType,
} from './createSlice'
export type {
// types
CreateSliceOptions,
Slice,
CaseReducerActions,
SliceCaseReducers,
ValidateSliceCaseReducers,
CaseReducerWithPrepare,
ReducerCreators,
SliceSelectors,
} from './createSlice'
export type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware'
export { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware'
export {
// js
createImmutableStateInvariantMiddleware,
isImmutableDefault,
} from './immutableStateInvariantMiddleware'
export type {
// types
ImmutableStateInvariantMiddlewareOptions,
} from './immutableStateInvariantMiddleware'
export {
// js
createSerializableStateInvariantMiddleware,
findNonSerializableValue,
isPlain,
} from './serializableStateInvariantMiddleware'
export type {
// types
SerializableStateInvariantMiddlewareOptions,
} from './serializableStateInvariantMiddleware'
export type {
// types
ActionReducerMapBuilder,
} from './mapBuilders'
export { Tuple } from './utils'
export { createEntityAdapter } from './entities/create_adapter'
export type {
EntityState,
EntityAdapter,
EntitySelectors,
EntityStateAdapter,
EntityId,
Update,
IdSelector,
Comparer,
} from './entities/models'
export {
createAsyncThunk,
unwrapResult,
miniSerializeError,
} from './createAsyncThunk'
export type {
AsyncThunk,
AsyncThunkOptions,
AsyncThunkAction,
AsyncThunkPayloadCreatorReturnValue,
AsyncThunkPayloadCreator,
GetState,
GetThunkAPI,
SerializedError,
} from './createAsyncThunk'
export {
// js
isAllOf,
isAnyOf,
isPending,
isRejected,
isFulfilled,
isAsyncThunkAction,
isRejectedWithValue,
} from './matchers'
export type {
// types
ActionMatchingAllOf,
ActionMatchingAnyOf,
} from './matchers'
export { nanoid } from './nanoid'
export type {
ListenerEffect,
ListenerMiddleware,
ListenerEffectAPI,
ListenerMiddlewareInstance,
CreateListenerMiddlewareOptions,
ListenerErrorHandler,
TypedStartListening,
TypedAddListener,
TypedStopListening,
TypedRemoveListener,
UnsubscribeListener,
UnsubscribeListenerOptions,
ForkedTaskExecutor,
ForkedTask,
ForkedTaskAPI,
AsyncTaskExecutor,
SyncTaskExecutor,
TaskCancelled,
TaskRejected,
TaskResolved,
TaskResult,
} from './listenerMiddleware/index'
export type { AnyListenerPredicate } from './listenerMiddleware/types'
export {
createListenerMiddleware,
addListener,
removeListener,
clearAllListeners,
TaskAbortError,
} from './listenerMiddleware/index'
export type {
AddMiddleware,
DynamicDispatch,
DynamicMiddlewareInstance,
GetDispatchType as GetDispatch,
MiddlewareApiConfig,
} from './dynamicMiddleware/types'
export { createDynamicMiddleware } from './dynamicMiddleware/index'
export {
SHOULD_AUTOBATCH,
prepareAutoBatched,
autoBatchEnhancer,
} from './autoBatchEnhancer'
export type { AutoBatchOptions } from './autoBatchEnhancer'
export { combineSlices } from './combineSlices'
export type { CombinedSliceReducer, WithSlice } from './combineSlices'
export type {
ExtractDispatchExtensions as TSHelpersExtractDispatchExtensions,
SafePromise,
} from './tsHelpers'
export { formatProdErrorMessage } from './formatProdErrorMessage'

View File

@@ -0,0 +1,20 @@
import type { SerializedError } from '@reduxjs/toolkit'
const task = 'task'
const listener = 'listener'
const completed = 'completed'
const cancelled = 'cancelled'
/* TaskAbortError error codes */
export const taskCancelled = `task-${cancelled}` as const
export const taskCompleted = `task-${completed}` as const
export const listenerCancelled = `${listener}-${cancelled}` as const
export const listenerCompleted = `${listener}-${completed}` as const
export class TaskAbortError implements SerializedError {
name = 'TaskAbortError'
message: string
constructor(public code: string | undefined) {
this.message = `${task} ${cancelled} (reason: ${code})`
}
}

View File

@@ -0,0 +1,543 @@
import type { Action, Dispatch, MiddlewareAPI, UnknownAction } from 'redux'
import { isAction } from 'redux'
import type { ThunkDispatch } from 'redux-thunk'
import { createAction } from '../createAction'
import { nanoid } from '../nanoid'
import { find } from '../utils'
import {
TaskAbortError,
listenerCancelled,
listenerCompleted,
taskCancelled,
taskCompleted,
} from './exceptions'
import {
createDelay,
createPause,
raceWithSignal,
runTask,
validateActive,
} from './task'
import type {
AbortSignalWithReason,
AddListenerOverloads,
AnyListenerPredicate,
CreateListenerMiddlewareOptions,
FallbackAddListenerOptions,
ForkOptions,
ForkedTask,
ForkedTaskExecutor,
ListenerEntry,
ListenerErrorHandler,
ListenerErrorInfo,
ListenerMiddleware,
ListenerMiddlewareInstance,
TakePattern,
TaskResult,
TypedAddListener,
TypedCreateListenerEntry,
TypedRemoveListener,
UnsubscribeListener,
UnsubscribeListenerOptions,
} from './types'
import {
abortControllerWithReason,
addAbortSignalListener,
assertFunction,
catchRejection,
noop,
} from './utils'
export { TaskAbortError } from './exceptions'
export type {
AsyncTaskExecutor,
CreateListenerMiddlewareOptions,
ForkedTask,
ForkedTaskAPI,
ForkedTaskExecutor,
ListenerEffect,
ListenerEffectAPI,
ListenerErrorHandler,
ListenerMiddleware,
ListenerMiddlewareInstance,
SyncTaskExecutor,
TaskCancelled,
TaskRejected,
TaskResolved,
TaskResult,
TypedAddListener,
TypedRemoveListener,
TypedStartListening,
TypedStopListening,
UnsubscribeListener,
UnsubscribeListenerOptions,
} from './types'
//Overly-aggressive byte-shaving
const { assign } = Object
/**
* @internal
*/
const INTERNAL_NIL_TOKEN = {} as const
const alm = 'listenerMiddleware' as const
const createFork = (
parentAbortSignal: AbortSignalWithReason<unknown>,
parentBlockingPromises: Promise<any>[],
) => {
const linkControllers = (controller: AbortController) =>
addAbortSignalListener(parentAbortSignal, () =>
abortControllerWithReason(controller, parentAbortSignal.reason),
)
return <T>(
taskExecutor: ForkedTaskExecutor<T>,
opts?: ForkOptions,
): ForkedTask<T> => {
assertFunction(taskExecutor, 'taskExecutor')
const childAbortController = new AbortController()
linkControllers(childAbortController)
const result = runTask<T>(
async (): Promise<T> => {
validateActive(parentAbortSignal)
validateActive(childAbortController.signal)
const result = (await taskExecutor({
pause: createPause(childAbortController.signal),
delay: createDelay(childAbortController.signal),
signal: childAbortController.signal,
})) as T
validateActive(childAbortController.signal)
return result
},
() => abortControllerWithReason(childAbortController, taskCompleted),
)
if (opts?.autoJoin) {
parentBlockingPromises.push(result.catch(noop))
}
return {
result: createPause<TaskResult<T>>(parentAbortSignal)(result),
cancel() {
abortControllerWithReason(childAbortController, taskCancelled)
},
}
}
}
const createTakePattern = <S>(
startListening: AddListenerOverloads<UnsubscribeListener, S, Dispatch>,
signal: AbortSignal,
): TakePattern<S> => {
/**
* A function that takes a ListenerPredicate and an optional timeout,
* and resolves when either the predicate returns `true` based on an action
* state combination or when the timeout expires.
* If the parent listener is canceled while waiting, this will throw a
* TaskAbortError.
*/
const take = async <P extends AnyListenerPredicate<S>>(
predicate: P,
timeout: number | undefined,
) => {
validateActive(signal)
// Placeholder unsubscribe function until the listener is added
let unsubscribe: UnsubscribeListener = () => {}
const tuplePromise = new Promise<[Action, S, S]>((resolve, reject) => {
// Inside the Promise, we synchronously add the listener.
let stopListening = startListening({
predicate: predicate as any,
effect: (action, listenerApi): void => {
// One-shot listener that cleans up as soon as the predicate passes
listenerApi.unsubscribe()
// Resolve the promise with the same arguments the predicate saw
resolve([
action,
listenerApi.getState(),
listenerApi.getOriginalState(),
])
},
})
unsubscribe = () => {
stopListening()
reject()
}
})
const promises: (Promise<null> | Promise<[Action, S, S]>)[] = [tuplePromise]
if (timeout != null) {
promises.push(
new Promise<null>((resolve) => setTimeout(resolve, timeout, null)),
)
}
try {
const output = await raceWithSignal(signal, Promise.race(promises))
validateActive(signal)
return output
} finally {
// Always clean up the listener
unsubscribe()
}
}
return ((predicate: AnyListenerPredicate<S>, timeout: number | undefined) =>
catchRejection(take(predicate, timeout))) as TakePattern<S>
}
const getListenerEntryPropsFrom = (options: FallbackAddListenerOptions) => {
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) {
// pass
} else {
throw new Error(
'Creating or removing a listener requires one of the known fields for matching an action',
)
}
assertFunction(effect, 'options.listener')
return { predicate, type, effect }
}
/** Accepts the possible options for creating a listener, and returns a formatted listener entry */
export const createListenerEntry: TypedCreateListenerEntry<unknown> =
/* @__PURE__ */ assign(
(options: FallbackAddListenerOptions) => {
const { type, predicate, effect } = getListenerEntryPropsFrom(options)
const id = nanoid()
const entry: ListenerEntry<unknown> = {
id,
effect,
type,
predicate,
pending: new Set<AbortController>(),
unsubscribe: () => {
throw new Error('Unsubscribe not initialized')
},
}
return entry
},
{ withTypes: () => createListenerEntry },
) as unknown as TypedCreateListenerEntry<unknown>
const cancelActiveListeners = (
entry: ListenerEntry<unknown, Dispatch<UnknownAction>>,
) => {
entry.pending.forEach((controller) => {
abortControllerWithReason(controller, listenerCancelled)
})
}
const createClearListenerMiddleware = (
listenerMap: Map<string, ListenerEntry>,
) => {
return () => {
listenerMap.forEach(cancelActiveListeners)
listenerMap.clear()
}
}
/**
* Safely reports errors to the `errorHandler` provided.
* Errors that occur inside `errorHandler` are notified in a new task.
* Inspired by [rxjs reportUnhandledError](https://github.com/ReactiveX/rxjs/blob/6fafcf53dc9e557439b25debaeadfd224b245a66/src/internal/util/reportUnhandledError.ts)
* @param errorHandler
* @param errorToNotify
*/
const safelyNotifyError = (
errorHandler: ListenerErrorHandler,
errorToNotify: unknown,
errorInfo: ListenerErrorInfo,
): void => {
try {
errorHandler(errorToNotify, errorInfo)
} catch (errorHandlerError) {
// We cannot let an error raised here block the listener queue.
// The error raised here will be picked up by `window.onerror`, `process.on('error')` etc...
setTimeout(() => {
throw errorHandlerError
}, 0)
}
}
/**
* @public
*/
export const addListener = /* @__PURE__ */ assign(
/* @__PURE__ */ createAction(`${alm}/add`),
{
withTypes: () => addListener,
},
) as unknown as TypedAddListener<unknown>
/**
* @public
*/
export const clearAllListeners = /* @__PURE__ */ createAction(
`${alm}/removeAll`,
)
/**
* @public
*/
export const removeListener = /* @__PURE__ */ assign(
/* @__PURE__ */ createAction(`${alm}/remove`),
{
withTypes: () => removeListener,
},
) as unknown as TypedRemoveListener<unknown>
const defaultErrorHandler: ListenerErrorHandler = (...args: unknown[]) => {
console.error(`${alm}/error`, ...args)
}
/**
* @public
*/
export const createListenerMiddleware = <
StateType = unknown,
DispatchType extends Dispatch<Action> = ThunkDispatch<
StateType,
unknown,
UnknownAction
>,
ExtraArgument = unknown,
>(
middlewareOptions: CreateListenerMiddlewareOptions<ExtraArgument> = {},
) => {
const listenerMap = new Map<string, ListenerEntry>()
const { extra, onError = defaultErrorHandler } = middlewareOptions
assertFunction(onError, 'onError')
const insertEntry = (entry: ListenerEntry) => {
entry.unsubscribe = () => listenerMap.delete(entry!.id)
listenerMap.set(entry.id, entry)
return (cancelOptions?: UnsubscribeListenerOptions) => {
entry.unsubscribe()
if (cancelOptions?.cancelActive) {
cancelActiveListeners(entry)
}
}
}
const startListening = ((options: FallbackAddListenerOptions) => {
let entry = find(
Array.from(listenerMap.values()),
(existingEntry) => existingEntry.effect === options.effect,
)
if (!entry) {
entry = createListenerEntry(options as any)
}
return insertEntry(entry)
}) as AddListenerOverloads<any>
assign(startListening, {
withTypes: () => startListening,
})
const stopListening = (
options: FallbackAddListenerOptions & UnsubscribeListenerOptions,
): boolean => {
const { type, effect, predicate } = getListenerEntryPropsFrom(options)
const entry = find(Array.from(listenerMap.values()), (entry) => {
const matchPredicateOrType =
typeof type === 'string'
? entry.type === type
: entry.predicate === predicate
return matchPredicateOrType && entry.effect === effect
})
if (entry) {
entry.unsubscribe()
if (options.cancelActive) {
cancelActiveListeners(entry)
}
}
return !!entry
}
assign(stopListening, {
withTypes: () => stopListening,
})
const notifyListener = async (
entry: ListenerEntry<unknown, Dispatch<UnknownAction>>,
action: unknown,
api: MiddlewareAPI,
getOriginalState: () => StateType,
) => {
const internalTaskController = new AbortController()
const take = createTakePattern(
startListening as AddListenerOverloads<any>,
internalTaskController.signal,
)
const autoJoinPromises: Promise<any>[] = []
try {
entry.pending.add(internalTaskController)
await Promise.resolve(
entry.effect(
action,
// Use assign() rather than ... to avoid extra helper functions added to bundle
assign({}, api, {
getOriginalState,
condition: (
predicate: AnyListenerPredicate<any>,
timeout?: number,
) => take(predicate, timeout).then(Boolean),
take,
delay: createDelay(internalTaskController.signal),
pause: createPause<any>(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) {
abortControllerWithReason(controller, listenerCancelled)
set.delete(controller)
}
})
},
cancel: () => {
abortControllerWithReason(
internalTaskController,
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)
abortControllerWithReason(internalTaskController, listenerCompleted) // Notify that the task has completed
entry.pending.delete(internalTaskController)
}
}
const clearListenerMiddleware = createClearListenerMiddleware(listenerMap)
const middleware: ListenerMiddleware<
StateType,
DispatchType,
ExtraArgument
> = (api) => (next) => (action) => {
if (!isAction(action)) {
// we only want to notify listeners for action objects
return next(action)
}
if (addListener.match(action)) {
return startListening(action.payload as any)
}
if (clearAllListeners.match(action)) {
clearListenerMiddleware()
return
}
if (removeListener.match(action)) {
return stopListening(action.payload)
}
// Need to get this state _before_ the reducer processes the action
let originalState: StateType | typeof INTERNAL_NIL_TOKEN = api.getState()
// `getOriginalState` can only be called synchronously.
// @see https://github.com/reduxjs/redux-toolkit/discussions/1648#discussioncomment-1932820
const getOriginalState = (): StateType => {
if (originalState === INTERNAL_NIL_TOKEN) {
throw new Error(
`${alm}: getOriginalState can only be called synchronously`,
)
}
return originalState as StateType
}
let result: unknown
try {
// Actually forward the action to the reducer before we handle listeners
result = next(action)
if (listenerMap.size > 0) {
const currentState = api.getState()
// Work around ESBuild+TS transpilation issue
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 {
// Remove `originalState` store from this scope.
originalState = INTERNAL_NIL_TOKEN
}
return result
}
return {
middleware,
startListening,
stopListening,
clearListeners: clearListenerMiddleware,
} as ListenerMiddlewareInstance<StateType, DispatchType, ExtraArgument>
}

View File

@@ -0,0 +1,101 @@
import { TaskAbortError } from './exceptions'
import type { AbortSignalWithReason, TaskResult } from './types'
import { addAbortSignalListener, catchRejection, noop } from './utils'
/**
* Synchronously raises {@link TaskAbortError} if the task tied to the input `signal` has been cancelled.
* @param signal
* @param reason
* @see {TaskAbortError}
*/
export const validateActive = (signal: AbortSignal): void => {
if (signal.aborted) {
const { reason } = signal as AbortSignalWithReason<string>
throw new TaskAbortError(reason)
}
}
/**
* Generates a race between the promise(s) and the AbortSignal
* This avoids `Promise.race()`-related memory leaks:
* https://github.com/nodejs/node/issues/17469#issuecomment-349794909
*/
export function raceWithSignal<T>(
signal: AbortSignalWithReason<string>,
promise: Promise<T>,
): Promise<T> {
let cleanup = noop
return new Promise<T>((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(() => {
// after this point, replace `cleanup` with a noop, so there is no reference to `signal` any more
cleanup = noop
})
}
/**
* Runs a task and returns promise that resolves to {@link TaskResult}.
* Second argument is an optional `cleanUp` function that always runs after task.
*
* **Note:** `runTask` runs the executor in the next microtask.
* @returns
*/
export const runTask = async <T>(
task: () => Promise<T>,
cleanUp?: () => void,
): Promise<TaskResult<T>> => {
try {
await Promise.resolve()
const value = await task()
return {
status: 'ok',
value,
}
} catch (error: any) {
return {
status: error instanceof TaskAbortError ? 'cancelled' : 'rejected',
error,
}
} finally {
cleanUp?.()
}
}
/**
* Given an input `AbortSignal` and a promise returns another promise that resolves
* as soon the input promise is provided or rejects as soon as
* `AbortSignal.abort` is `true`.
* @param signal
* @returns
*/
export const createPause = <T>(signal: AbortSignal) => {
return (promise: Promise<T>): Promise<T> => {
return catchRejection(
raceWithSignal(signal, promise).then((output) => {
validateActive(signal)
return output
}),
)
}
}
/**
* Given an input `AbortSignal` and `timeoutMs` returns a promise that resolves
* after `timeoutMs` or rejects as soon as `AbortSignal.abort` is `true`.
* @param signal
* @returns
*/
export const createDelay = (signal: AbortSignal) => {
const pause = createPause<void>(signal)
return (timeoutMs: number): Promise<void> => {
return pause(new Promise<void>((resolve) => setTimeout(resolve, timeoutMs)))
}
}

View File

@@ -0,0 +1,365 @@
import {
configureStore,
createAction,
createSlice,
isAnyOf,
} from '@reduxjs/toolkit'
import { vi } from 'vitest'
import type { PayloadAction } from '@reduxjs/toolkit'
import { createListenerMiddleware, TaskAbortError } from '../index'
import type { TypedAddListener } from '../index'
describe('Saga-style Effects Scenarios', () => {
interface CounterState {
value: number
}
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 } as CounterState,
reducers: {
increment(state) {
state.value += 1
},
decrement(state) {
state.value -= 1
},
// Use the PayloadAction type to declare the contents of `action.payload`
incrementByAmount: (state, action: PayloadAction<number>) => {
state.value += action.payload
},
},
})
const { increment, decrement, incrementByAmount } = counterSlice.actions
let { reducer } = counterSlice
let listenerMiddleware = createListenerMiddleware<CounterState>()
let { middleware, startListening, stopListening } = listenerMiddleware
let store = configureStore({
reducer,
middleware: (gDM) => gDM().prepend(middleware),
})
const testAction1 = createAction<string>('testAction1')
type TestAction1 = ReturnType<typeof testAction1>
const testAction2 = createAction<string>('testAction2')
type TestAction2 = ReturnType<typeof testAction2>
const testAction3 = createAction<string>('testAction3')
type TestAction3 = ReturnType<typeof testAction3>
type RootState = ReturnType<typeof store.getState>
function delay(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
beforeAll(() => {
const noop = () => {}
vi.spyOn(console, 'error').mockImplementation(noop)
})
beforeEach(() => {
listenerMiddleware = createListenerMiddleware<CounterState>()
middleware = listenerMiddleware.middleware
startListening = listenerMiddleware.startListening
store = configureStore({
reducer,
middleware: (gDM) => gDM().prepend(middleware),
})
})
test('throttle', async () => {
// Ignore incoming actions for a given period of time while processing a task.
// Ref: https://redux-saga.js.org/docs/api#throttlems-pattern-saga-args
let listenerCalls = 0
let workPerformed = 0
startListening({
actionCreator: increment,
effect: (action, listenerApi) => {
listenerCalls++
// Stop listening until further notice
listenerApi.unsubscribe()
// Queue to start listening again after a delay
setTimeout(listenerApi.subscribe, 15)
workPerformed++
},
})
// Dispatch 3 actions. First triggers listener, next two ignored.
store.dispatch(increment())
store.dispatch(increment())
store.dispatch(increment())
// Wait for resubscription
await delay(25)
// Dispatch 2 more actions, first triggers, second ignored
store.dispatch(increment())
store.dispatch(increment())
// Wait for work
await delay(5)
// Both listener calls completed
expect(listenerCalls).toBe(2)
expect(workPerformed).toBe(2)
})
test('debounce / takeLatest', async () => {
// Repeated calls cancel previous ones, no work performed
// until the specified delay elapses without another call
// NOTE: This is also basically identical to `takeLatest`.
// Ref: https://redux-saga.js.org/docs/api#debouncems-pattern-saga-args
// Ref: https://redux-saga.js.org/docs/api#takelatestpattern-saga-args
let listenerCalls = 0
let workPerformed = 0
startListening({
actionCreator: increment,
effect: async (action, listenerApi) => {
listenerCalls++
// Cancel any in-progress instances of this listener
listenerApi.cancelActiveListeners()
// Delay before starting actual work
await listenerApi.delay(15)
workPerformed++
},
})
// First action, listener 1 starts, nothing to cancel
store.dispatch(increment())
// Second action, listener 2 starts, cancels 1
store.dispatch(increment())
// Third action, listener 3 starts, cancels 2
store.dispatch(increment())
// 3 listeners started, third is still paused
expect(listenerCalls).toBe(3)
expect(workPerformed).toBe(0)
await delay(25)
// All 3 started
expect(listenerCalls).toBe(3)
// First two canceled, `delay()` threw JobCanceled and skipped work.
// Third actually completed.
expect(workPerformed).toBe(1)
})
test('takeEvery', async () => {
// Runs the listener on every action match
// Ref: https://redux-saga.js.org/docs/api#takeeverypattern-saga-args
// NOTE: This is already the default behavior - nothing special here!
let listenerCalls = 0
startListening({
actionCreator: increment,
effect: (action, listenerApi) => {
listenerCalls++
},
})
store.dispatch(increment())
expect(listenerCalls).toBe(1)
store.dispatch(increment())
expect(listenerCalls).toBe(2)
})
test('takeLeading', async () => {
// Starts listener on first action, ignores others until task completes
// Ref: https://redux-saga.js.org/docs/api#takeleadingpattern-saga-args
let listenerCalls = 0
let workPerformed = 0
startListening({
actionCreator: increment,
effect: async (action, listenerApi) => {
listenerCalls++
// Stop listening for this action
listenerApi.unsubscribe()
// Pretend we're doing expensive work
await listenerApi.delay(25)
workPerformed++
// Re-enable the listener
listenerApi.subscribe()
},
})
// First action starts the listener, which unsubscribes
store.dispatch(increment())
// Second action is ignored
store.dispatch(increment())
// One instance in progress, but not complete
expect(listenerCalls).toBe(1)
expect(workPerformed).toBe(0)
await delay(5)
// In-progress listener not done yet
store.dispatch(increment())
// No changes in status
expect(listenerCalls).toBe(1)
expect(workPerformed).toBe(0)
await delay(50)
// Work finished, should have resubscribed
expect(workPerformed).toBe(1)
// Listener is re-subscribed, will trigger again
store.dispatch(increment())
expect(listenerCalls).toBe(2)
expect(workPerformed).toBe(1)
await delay(50)
expect(workPerformed).toBe(2)
})
test('fork + join', async () => {
// fork starts a child job, join waits for the child to complete and return a value
// Ref: https://redux-saga.js.org/docs/api#forkfn-args
// Ref: https://redux-saga.js.org/docs/api#jointask
let childResult = 0
startListening({
actionCreator: increment,
effect: async (_, listenerApi) => {
const childOutput = 42
// Spawn a child job and start it immediately
const result = await listenerApi.fork(async () => {
// Artificially wait a bit inside the child
await listenerApi.delay(5)
// Complete the child by returning an Outcome-wrapped value
return childOutput
}).result
// Unwrap the child result in the listener
if (result.status === 'ok') {
childResult = result.value
}
},
})
store.dispatch(increment())
await delay(10)
expect(childResult).toBe(42)
})
test('fork + cancel', async () => {
// fork starts a child job, cancel will raise an exception if the
// child is paused in the middle of an effect
// Ref: https://redux-saga.js.org/docs/api#forkfn-args
let childResult = 0
let listenerCompleted = false
startListening({
actionCreator: increment,
effect: async (action, listenerApi) => {
// Spawn a child job and start it immediately
const forkedTask = listenerApi.fork(async () => {
// Artificially wait a bit inside the child
await listenerApi.delay(15)
// Complete the child by returning an Outcome-wrapped value
childResult = 42
return 0
})
await listenerApi.delay(5)
forkedTask.cancel()
listenerCompleted = true
},
})
// Starts listener, which starts child
store.dispatch(increment())
// Wait for child to have maybe completed
await delay(20)
// Listener finished, but the child was canceled and threw an exception, so it never finished
expect(listenerCompleted).toBe(true)
expect(childResult).toBe(0)
})
test('canceled', async () => {
// canceled allows checking if the current task was canceled
// Ref: https://redux-saga.js.org/docs/api#cancelled
let canceledAndCaught = false
let canceledCheck = false
startListening({
matcher: isAnyOf(increment, decrement, incrementByAmount),
effect: async (action, listenerApi) => {
if (increment.match(action)) {
// Have this branch wait around to be canceled by the other
try {
await listenerApi.delay(10)
} catch (err) {
// Can check cancelation based on the exception and its reason
if (err instanceof TaskAbortError) {
canceledAndCaught = true
}
}
} else if (incrementByAmount.match(action)) {
// do a non-cancelation-aware wait
await delay(15)
if (listenerApi.signal.aborted) {
canceledCheck = true
}
} else if (decrement.match(action)) {
listenerApi.cancelActiveListeners()
}
},
})
// Start first branch
store.dispatch(increment())
// Cancel first listener
store.dispatch(decrement())
// Have to wait for the delay to resolve
// TODO Can we make ``Job.delay()` be a race?
await delay(15)
expect(canceledAndCaught).toBe(true)
// Start second branch
store.dispatch(incrementByAmount(42))
// Cancel second listener, although it won't know about that until later
store.dispatch(decrement())
expect(canceledCheck).toBe(false)
await delay(20)
expect(canceledCheck).toBe(true)
})
})

View File

@@ -0,0 +1,530 @@
import type { EnhancedStore } from '@reduxjs/toolkit'
import { configureStore, createSlice, createAction } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'
import type {
AbortSignalWithReason,
ForkedTaskExecutor,
TaskResult,
} from '../types'
import { createListenerMiddleware, TaskAbortError } from '../index'
import {
listenerCancelled,
listenerCompleted,
taskCancelled,
taskCompleted,
} from '../exceptions'
function delay(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
// @see https://deno.land/std@0.95.0/async/deferred.ts (MIT)
export interface Deferred<T> extends Promise<T> {
resolve(value?: T | PromiseLike<T>): void
reject(reason?: any): void
}
/** Creates a Promise with the `reject` and `resolve` functions
* placed as methods on the promise object itself. It allows you to do:
*
* const p = deferred<number>();
* // ...
* p.resolve(42);
*/
export function deferred<T>(): Deferred<T> {
let methods
const promise = new Promise<T>((resolve, reject): void => {
methods = { resolve, reject }
})
return Object.assign(promise, methods) as Deferred<T>
}
interface CounterSlice {
value: number
}
describe('fork', () => {
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 } as CounterSlice,
reducers: {
increment(state) {
state.value += 1
},
decrement(state) {
state.value -= 1
},
// Use the PayloadAction type to declare the contents of `action.payload`
incrementByAmount: (state, action: PayloadAction<number>) => {
state.value += action.payload
},
},
})
const { increment, decrement, incrementByAmount } = counterSlice.actions
let listenerMiddleware = createListenerMiddleware()
let { middleware, startListening, stopListening } = listenerMiddleware
let store = configureStore({
reducer: counterSlice.reducer,
middleware: (gDM) => gDM().prepend(middleware),
})
beforeEach(() => {
listenerMiddleware = createListenerMiddleware()
middleware = listenerMiddleware.middleware
startListening = listenerMiddleware.startListening
stopListening = listenerMiddleware.stopListening
store = configureStore({
reducer: counterSlice.reducer,
middleware: (gDM) => gDM().prepend(middleware),
})
})
it('runs executors in the next microtask', async () => {
let hasRunSyncExector = false
let hasRunAsyncExecutor = false
startListening({
actionCreator: increment,
effect: async (_, listenerApi) => {
listenerApi.fork(() => {
hasRunSyncExector = true
})
listenerApi.fork(async () => {
hasRunAsyncExecutor = true
})
},
})
store.dispatch(increment())
expect(hasRunSyncExector).toBe(false)
expect(hasRunAsyncExecutor).toBe(false)
await Promise.resolve()
expect(hasRunSyncExector).toBe(true)
expect(hasRunAsyncExecutor).toBe(true)
})
test('forkedTask.result rejects TaskAbortError if listener is cancelled', async () => {
const deferredForkedTaskError = deferred()
startListening({
actionCreator: increment,
async effect(_, listenerApi) {
listenerApi.cancelActiveListeners()
listenerApi
.fork(async () => {
await delay(10)
throw new Error('unreachable code')
})
.result.then(
deferredForkedTaskError.resolve,
deferredForkedTaskError.resolve,
)
},
})
store.dispatch(increment())
store.dispatch(increment())
expect(await deferredForkedTaskError).toEqual(
new TaskAbortError(listenerCancelled),
)
})
it('synchronously throws TypeError error if the provided executor is not a function', () => {
const invalidExecutors = [null, {}, undefined, 1]
startListening({
predicate: () => true,
effect: async (_, listenerApi) => {
invalidExecutors.forEach((invalidExecutor) => {
let caughtError
try {
listenerApi.fork(invalidExecutor as any)
} catch (err) {
caughtError = err
}
expect(caughtError).toBeInstanceOf(TypeError)
})
},
})
store.dispatch(increment())
expect.assertions(invalidExecutors.length)
})
it('does not run an executor if the task is synchronously cancelled', async () => {
const storeStateAfter = deferred()
startListening({
actionCreator: increment,
effect: async (action, listenerApi) => {
const forkedTask = listenerApi.fork(() => {
listenerApi.dispatch(decrement())
listenerApi.dispatch(decrement())
listenerApi.dispatch(decrement())
})
forkedTask.cancel()
const result = await forkedTask.result
storeStateAfter.resolve(listenerApi.getState())
},
})
store.dispatch(increment())
expect(storeStateAfter).resolves.toEqual({ value: 1 })
})
it.each<{
desc: string
executor: ForkedTaskExecutor<any>
cancelAfterMs?: number
expected: TaskResult<any>
}>([
{
desc: 'sync exec - success',
executor: () => 42,
expected: { status: 'ok', value: 42 },
},
{
desc: 'sync exec - error',
executor: () => {
throw new Error('2020')
},
expected: { status: 'rejected', error: new Error('2020') },
},
{
desc: 'sync exec - sync cancel',
executor: () => 42,
cancelAfterMs: -1,
expected: {
status: 'cancelled',
error: new TaskAbortError(taskCancelled),
},
},
{
desc: 'sync exec - async cancel',
executor: () => 42,
cancelAfterMs: 0,
expected: { status: 'ok', value: 42 },
},
{
desc: 'async exec - async cancel',
executor: async (forkApi) => {
await forkApi.delay(100)
throw new Error('2020')
},
cancelAfterMs: 10,
expected: {
status: 'cancelled',
error: new TaskAbortError(taskCancelled),
},
},
{
desc: 'async exec - success',
executor: async () => {
await delay(20)
return Promise.resolve(21)
},
expected: { status: 'ok', value: 21 },
},
{
desc: 'async exec - error',
executor: async () => {
await Promise.resolve()
throw new Error('2020')
},
expected: { status: 'rejected', error: new Error('2020') },
},
{
desc: 'async exec - success with forkApi.pause',
executor: async (forkApi) => {
return forkApi.pause(Promise.resolve(2))
},
expected: { status: 'ok', value: 2 },
},
{
desc: 'async exec - error with forkApi.pause',
executor: async (forkApi) => {
return forkApi.pause(Promise.reject(22))
},
expected: { status: 'rejected', error: 22 },
},
{
desc: 'async exec - success with forkApi.delay',
executor: async (forkApi) => {
await forkApi.delay(10)
return 5
},
expected: { status: 'ok', value: 5 },
},
])('%# - %j', async ({ executor, expected, cancelAfterMs }) => {
let deferredResult = deferred()
let forkedTask: any = {}
startListening({
predicate: () => true,
effect: async (_, listenerApi) => {
forkedTask = listenerApi.fork(executor)
deferredResult.resolve(await forkedTask.result)
},
})
store.dispatch({ type: '' })
if (typeof cancelAfterMs === 'number') {
if (cancelAfterMs < 0) {
forkedTask.cancel()
} else {
await delay(cancelAfterMs)
forkedTask.cancel()
}
}
const result = await deferredResult
expect(result).toEqual(expected)
})
describe('forkAPI', () => {
test('forkApi.delay rejects as soon as the task is cancelled', async () => {
let deferredResult = deferred()
startListening({
actionCreator: increment,
effect: async (_, listenerApi) => {
const forkedTask = listenerApi.fork(async (forkApi) => {
await forkApi.delay(100)
return 4
})
await listenerApi.delay(10)
forkedTask.cancel()
deferredResult.resolve(await forkedTask.result)
},
})
store.dispatch(increment())
expect(await deferredResult).toEqual({
status: 'cancelled',
error: new TaskAbortError(taskCancelled),
})
})
test('forkApi.delay rejects as soon as the parent listener is cancelled', async () => {
let deferredResult = deferred()
startListening({
actionCreator: increment,
effect: async (_, listenerApi) => {
listenerApi.cancelActiveListeners()
await listenerApi.fork(async (forkApi) => {
await forkApi
.delay(100)
.then(deferredResult.resolve, deferredResult.resolve)
return 4
}).result
deferredResult.resolve(new Error('unreachable'))
},
})
store.dispatch(increment())
await Promise.resolve()
store.dispatch(increment())
expect(await deferredResult).toEqual(
new TaskAbortError(listenerCancelled),
)
})
it.each([
{
autoJoin: true,
expectedAbortReason: taskCompleted,
cancelListener: false,
},
{
autoJoin: false,
expectedAbortReason: listenerCompleted,
cancelListener: false,
},
{
autoJoin: true,
expectedAbortReason: listenerCancelled,
cancelListener: true,
},
{
autoJoin: false,
expectedAbortReason: listenerCancelled,
cancelListener: true,
},
])(
'signal is $expectedAbortReason when autoJoin: $autoJoin, cancelListener: $cancelListener',
async ({ autoJoin, cancelListener, expectedAbortReason }) => {
let deferredResult = deferred()
const unsubscribe = startListening({
actionCreator: increment,
async effect(_, listenerApi) {
listenerApi.fork(
async (forkApi) => {
forkApi.signal.addEventListener('abort', () => {
deferredResult.resolve(
(forkApi.signal as AbortSignalWithReason<unknown>).reason,
)
})
await forkApi.delay(10)
},
{ autoJoin },
)
},
})
store.dispatch(increment())
// let task start
await Promise.resolve()
if (cancelListener) unsubscribe({ cancelActive: true })
expect(await deferredResult).toBe(expectedAbortReason)
},
)
test('fork.delay does not trigger unhandledRejections for completed or cancelled tasks', async () => {
let deferredCompletedEvt = deferred()
let deferredCancelledEvt = deferred()
// Unfortunately we cannot test declaratively unhandleRejections in jest: https://github.com/facebook/jest/issues/5620
// This test just fails if an `unhandledRejection` occurs.
startListening({
actionCreator: increment,
effect: async (_, listenerApi) => {
const completedTask = listenerApi.fork(async (forkApi) => {
forkApi.signal.addEventListener(
'abort',
deferredCompletedEvt.resolve,
{ once: true },
)
forkApi.delay(100) // missing await
return 4
})
deferredCompletedEvt.resolve(await completedTask.result)
const godotPauseTrigger = deferred()
const cancelledTask = listenerApi.fork(async (forkApi) => {
forkApi.signal.addEventListener(
'abort',
deferredCompletedEvt.resolve,
{ once: true },
)
forkApi.delay(1_000) // missing await
await forkApi.pause(godotPauseTrigger)
return 4
})
await Promise.resolve()
cancelledTask.cancel()
deferredCancelledEvt.resolve(await cancelledTask.result)
},
})
store.dispatch(increment())
expect(await deferredCompletedEvt).toBeDefined()
expect(await deferredCancelledEvt).toBeDefined()
})
})
test('forkApi.pause rejects if task is cancelled', async () => {
let deferredResult = deferred()
startListening({
actionCreator: increment,
effect: async (_, listenerApi) => {
const forkedTask = listenerApi.fork(async (forkApi) => {
await forkApi.pause(delay(1_000))
return 4
})
await Promise.resolve()
forkedTask.cancel()
deferredResult.resolve(await forkedTask.result)
},
})
store.dispatch(increment())
expect(await deferredResult).toEqual({
status: 'cancelled',
error: new TaskAbortError(taskCancelled),
})
})
test('forkApi.pause rejects as soon as the parent listener is cancelled', async () => {
let deferredResult = deferred()
startListening({
actionCreator: increment,
effect: async (_, listenerApi) => {
listenerApi.cancelActiveListeners()
const forkedTask = listenerApi.fork(async (forkApi) => {
await forkApi
.pause(delay(100))
.then(deferredResult.resolve, deferredResult.resolve)
return 4
})
await forkedTask.result
deferredResult.resolve(new Error('unreachable'))
},
})
store.dispatch(increment())
await Promise.resolve()
store.dispatch(increment())
expect(await deferredResult).toEqual(new TaskAbortError(listenerCancelled))
})
test('forkApi.pause rejects if listener is cancelled', async () => {
const incrementByInListener = createAction<number>('incrementByInListener')
startListening({
actionCreator: incrementByInListener,
async effect({ payload: amountToIncrement }, listenerApi) {
listenerApi.cancelActiveListeners()
await listenerApi.fork(async (forkApi) => {
await forkApi.pause(delay(10))
listenerApi.dispatch(incrementByAmount(amountToIncrement))
}).result
listenerApi.dispatch(incrementByAmount(2 * amountToIncrement))
},
})
store.dispatch(incrementByInListener(10))
store.dispatch(incrementByInListener(100))
await delay(50)
expect(store.getState().value).toEqual(300)
})
})

View File

@@ -0,0 +1,540 @@
import { createListenerEntry } from '@internal/listenerMiddleware'
import type {
Action,
PayloadAction,
TypedAddListener,
TypedStartListening,
UnknownAction,
UnsubscribeListener,
} from '@reduxjs/toolkit'
import {
addListener,
configureStore,
createAction,
createListenerMiddleware,
createSlice,
isFluxStandardAction,
} from '@reduxjs/toolkit'
const listenerMiddleware = createListenerMiddleware()
const { startListening } = listenerMiddleware
const addTypedListenerAction = addListener as TypedAddListener<CounterState>
interface CounterState {
value: number
}
const testAction1 = createAction<string>('testAction1')
const testAction2 = createAction<string>('testAction2')
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 } as CounterState,
reducers: {
increment(state) {
state.value += 1
},
decrement(state) {
state.value -= 1
},
// Use the PayloadAction type to declare the contents of `action.payload`
incrementByAmount: (state, action: PayloadAction<number>) => {
state.value += action.payload
},
},
})
const { increment, decrement, incrementByAmount } = counterSlice.actions
describe('type tests', () => {
const store = configureStore({
reducer: () => 42,
middleware: (gDM) => gDM().prepend(createListenerMiddleware().middleware),
})
test('Allows passing an extra argument on middleware creation', () => {
const originalExtra = 42
const listenerMiddleware = createListenerMiddleware({
extra: originalExtra,
})
const store = configureStore({
reducer: counterSlice.reducer,
middleware: (gDM) => gDM().prepend(listenerMiddleware.middleware),
})
let foundExtra: number | null = null
const typedAddListener =
listenerMiddleware.startListening as TypedStartListening<
CounterState,
typeof store.dispatch,
typeof originalExtra
>
typedAddListener({
matcher: (action): action is Action => true,
effect: (action, listenerApi) => {
foundExtra = listenerApi.extra
expectTypeOf(listenerApi.extra).toMatchTypeOf(originalExtra)
},
})
store.dispatch(testAction1('a'))
expect(foundExtra).toBe(originalExtra)
})
test('unsubscribing via callback from dispatch', () => {
const unsubscribe = store.dispatch(
addListener({
actionCreator: testAction1,
effect: () => {},
}),
)
expectTypeOf(unsubscribe).toEqualTypeOf<UnsubscribeListener>()
store.dispatch(testAction1('a'))
unsubscribe()
store.dispatch(testAction2('b'))
store.dispatch(testAction1('c'))
})
test('take resolves to `[A, CurrentState, PreviousState] | null` if a possibly undefined timeout parameter is provided', () => {
type ExpectedTakeResultType =
| readonly [ReturnType<typeof increment>, CounterState, CounterState]
| null
let timeout: number | undefined = undefined
let done = false
const startAppListening =
startListening as TypedStartListening<CounterState>
startAppListening({
predicate: incrementByAmount.match,
effect: async (_, listenerApi) => {
let takeResult = await listenerApi.take(increment.match, timeout)
timeout = 1
takeResult = await listenerApi.take(increment.match, timeout)
expect(takeResult).toBeNull()
expectTypeOf(takeResult).toMatchTypeOf<ExpectedTakeResultType>()
done = true
},
})
expect(done).toBe(true)
})
test('State args default to unknown', () => {
createListenerEntry({
predicate: (
action,
currentState,
previousState,
): action is UnknownAction => {
expectTypeOf(currentState).toBeUnknown()
expectTypeOf(previousState).toBeUnknown()
return true
},
effect: (action, listenerApi) => {
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toBeUnknown()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = getState()
expectTypeOf(thunkState).toBeUnknown()
})
},
})
startListening({
predicate: (
action,
currentState,
previousState,
): action is UnknownAction => {
expectTypeOf(currentState).toBeUnknown()
expectTypeOf(previousState).toBeUnknown()
return true
},
effect: (action, listenerApi) => {},
})
startListening({
matcher: increment.match,
effect: (action, listenerApi) => {
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toBeUnknown()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = getState()
expectTypeOf(thunkState).toBeUnknown()
})
},
})
store.dispatch(
addListener({
predicate: (
action,
currentState,
previousState,
): action is UnknownAction => {
expectTypeOf(currentState).toBeUnknown()
expectTypeOf(previousState).toBeUnknown()
return true
},
effect: (action, listenerApi) => {
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toBeUnknown()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = getState()
expectTypeOf(thunkState).toBeUnknown()
})
},
}),
)
store.dispatch(
addListener({
matcher: increment.match,
effect: (action, listenerApi) => {
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toBeUnknown()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = getState()
expectTypeOf(thunkState).toBeUnknown()
})
},
}),
)
})
test('Action type is inferred from args', () => {
startListening({
type: 'abcd',
effect: (action, listenerApi) => {
expectTypeOf(action).toEqualTypeOf<{ type: 'abcd' }>()
},
})
startListening({
actionCreator: incrementByAmount,
effect: (action, listenerApi) => {
expectTypeOf(action).toMatchTypeOf<PayloadAction<number>>()
},
})
startListening({
matcher: incrementByAmount.match,
effect: (action, listenerApi) => {
expectTypeOf(action).toMatchTypeOf<PayloadAction<number>>()
},
})
startListening({
predicate: (
action,
currentState,
previousState,
): action is PayloadAction<number> => {
return (
isFluxStandardAction(action) && typeof action.payload === 'boolean'
)
},
effect: (action, listenerApi) => {
expectTypeOf(action).toEqualTypeOf<PayloadAction<number>>()
},
})
startListening({
predicate: (action, currentState) => {
return (
isFluxStandardAction(action) && typeof action.payload === 'number'
)
},
effect: (action, listenerApi) => {
expectTypeOf(action).toEqualTypeOf<UnknownAction>()
},
})
store.dispatch(
addListener({
type: 'abcd',
effect: (action, listenerApi) => {
expectTypeOf(action).toEqualTypeOf<{ type: 'abcd' }>()
},
}),
)
store.dispatch(
addListener({
actionCreator: incrementByAmount,
effect: (action, listenerApi) => {
expectTypeOf(action).toMatchTypeOf<PayloadAction<number>>()
},
}),
)
store.dispatch(
addListener({
matcher: incrementByAmount.match,
effect: (action, listenerApi) => {
expectTypeOf(action).toMatchTypeOf<PayloadAction<number>>()
},
}),
)
})
test('Can create a pre-typed middleware', () => {
const typedMiddleware = createListenerMiddleware<CounterState>()
typedMiddleware.startListening({
predicate: (
action,
currentState,
previousState,
): action is UnknownAction => {
expectTypeOf(currentState).not.toBeAny()
expectTypeOf(previousState).not.toBeAny()
expectTypeOf(currentState).toEqualTypeOf<CounterState>()
expectTypeOf(previousState).toEqualTypeOf<CounterState>()
return true
},
effect: (action, listenerApi) => {
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = listenerApi.getState()
expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
})
},
})
// Can pass a predicate function with fewer args
typedMiddleware.startListening({
predicate: (action, currentState): action is PayloadAction<number> => {
expectTypeOf(currentState).not.toBeAny()
expectTypeOf(currentState).toEqualTypeOf<CounterState>()
return true
},
effect: (action, listenerApi) => {
expectTypeOf(action).toEqualTypeOf<PayloadAction<number>>()
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = listenerApi.getState()
expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
})
},
})
typedMiddleware.startListening({
actionCreator: incrementByAmount,
effect: (action, listenerApi) => {
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = listenerApi.getState()
expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
})
},
})
store.dispatch(
addTypedListenerAction({
predicate: (
action,
currentState,
previousState,
): action is ReturnType<typeof incrementByAmount> => {
expectTypeOf(currentState).not.toBeAny()
expectTypeOf(previousState).not.toBeAny()
expectTypeOf(currentState).toEqualTypeOf<CounterState>()
expectTypeOf(previousState).toEqualTypeOf<CounterState>()
return true
},
effect: (action, listenerApi) => {
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = listenerApi.getState()
expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
})
},
}),
)
store.dispatch(
addTypedListenerAction({
predicate: (
action,
currentState,
previousState,
): action is UnknownAction => {
expectTypeOf(currentState).not.toBeAny()
expectTypeOf(previousState).not.toBeAny()
expectTypeOf(currentState).toEqualTypeOf<CounterState>()
expectTypeOf(previousState).toEqualTypeOf<CounterState>()
return true
},
effect: (action, listenerApi) => {
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = listenerApi.getState()
expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
})
},
}),
)
})
test('Can create pre-typed versions of startListening and addListener', () => {
const typedAddListener = startListening as TypedStartListening<CounterState>
const typedAddListenerAction = addListener as TypedAddListener<CounterState>
typedAddListener({
predicate: (
action,
currentState,
previousState,
): action is UnknownAction => {
expectTypeOf(currentState).not.toBeAny()
expectTypeOf(previousState).not.toBeAny()
expectTypeOf(currentState).toEqualTypeOf<CounterState>()
expectTypeOf(previousState).toEqualTypeOf<CounterState>()
return true
},
effect: (action, listenerApi) => {
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = listenerApi.getState()
expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
})
},
})
typedAddListener({
matcher: incrementByAmount.match,
effect: (action, listenerApi) => {
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = listenerApi.getState()
expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
})
},
})
store.dispatch(
typedAddListenerAction({
predicate: (
action,
currentState,
previousState,
): action is UnknownAction => {
expectTypeOf(currentState).not.toBeAny()
expectTypeOf(previousState).not.toBeAny()
expectTypeOf(currentState).toEqualTypeOf<CounterState>()
expectTypeOf(previousState).toEqualTypeOf<CounterState>()
return true
},
effect: (action, listenerApi) => {
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = listenerApi.getState()
expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
})
},
}),
)
store.dispatch(
typedAddListenerAction({
matcher: incrementByAmount.match,
effect: (action, listenerApi) => {
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = listenerApi.getState()
expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
})
},
}),
)
})
})

Some files were not shown because too many files have changed in this diff Show More