diff --git a/docs/api/getDefaultMiddleware.md b/docs/api/getDefaultMiddleware.md index adf9c42448..28f6e4c6dd 100644 --- a/docs/api/getDefaultMiddleware.md +++ b/docs/api/getDefaultMiddleware.md @@ -55,12 +55,15 @@ One of the goals of Redux Toolkit is to provide opinionated defaults and prevent `getDefaultMiddleware` includes some middleware that are added **in development builds of your app only** to provide runtime checks for two common issues: -- [`redux-immutable-state-invariant`](https://github.com/leoasis/redux-immutable-state-invariant): deeply compares +- [`immutable-state-invariant`](./otherExports.md#createimmutablestateinvariantmiddleware): deeply compares state values for mutations. It can detect mutations in reducers during a dispatch, and also mutations that occur between dispatches (such as in a component or a selector). When a mutation is detected, it will throw an error and indicate the key path for where the mutated value was detected in the state tree. + + Forked from [`redux-immutable-state-invariant`](https://github.com/leoasis/redux-immutable-state-invariant) + - [`serializable-state-invariant-middleware`](./otherExports.md#createserializablestateinvariantmiddleware): a custom middleware created specifically for use in Redux Toolkit. Similar in - concept to `redux-immutable-state-invariant`, but deeply checks your state tree and your actions for non-serializable values + concept to `immutable-state-invariant`, but deeply checks your state tree and your actions for non-serializable values such as functions, Promises, Symbols, and other non-plain-JS-data values. When a non-serializable value is detected, a console error will be printed with the key path for where the non-serializable value was detected. diff --git a/docs/api/otherExports.md b/docs/api/otherExports.md index 6176129865..80a84426cc 100644 --- a/docs/api/otherExports.md +++ b/docs/api/otherExports.md @@ -11,6 +11,56 @@ Redux Toolkit exports some of its internal utilities, and re-exports additional ## Internal Exports +### `createImmutalStateInvariantMiddleware` + +Creates an instance of the `immutable-state-invariant` middleware described in [`getDefaultMiddleware`](./getDefaultMiddleware.md). + +Accepts a single configuration object parameter, with the following options: + +```ts +function createImmutableStateInvariantMiddleware({ + // The 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?: (value: any) => boolean + // 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?: string[] +}) +``` + +Example: + +```js +import { + createSlice, + configureStore, + createImmutableStateInvariantMiddleware +} from '@reduxjs/toolkit' + +const exampleSlice = createSlice({ + name: 'example', + initialState: { + user: 'will track changes', + ignoredPath: 'single level', + ignoredNested: { + one: 'one', + two: 'two' + } + }, + reducers: {} +}) + +const immutableInvariantMiddleware = createImmutableStateInvariantMiddleware({ + ignoredPaths: ['ignoredPath', 'ignoredNested.one', 'ignoredNested.two'] +}) + +const store = configureStore({ + reducer: exampleSlice.reducer, + middleware: [immutableInvariantMiddleware] +}) +``` + ### `createSerializableStateInvariantMiddleware` Creates an instance of the `serializable-state-invariant` middleware described in [`getDefaultMiddleware`](./getDefaultMiddleware.md). diff --git a/package-lock.json b/package-lock.json index b7eab20c3d..5dc019e0ee 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1278,6 +1278,12 @@ "@types/node": "*" } }, + "@types/invariant": { + "version": "2.2.31", + "resolved": "https://registry.npmjs.org/@types/invariant/-/invariant-2.2.31.tgz", + "integrity": "sha512-jMlgg9pIURvy9jgBHCjQp/CyBjYHUwj91etVcDdXkFl2CwTFiQlB+8tcsMeXpXf2PFE5X2pjk4Gm43hQSMHAdA==", + "dev": true + }, "@types/istanbul-lib-coverage": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.1.tgz", @@ -1324,6 +1330,12 @@ "integrity": "sha512-Il2DtDVRGDcqjDtE+rF8iqg1CArehSK84HZJCT7AMITlyXRBpuPhqGLDQMowraqqu1coEaimg4ZOqggt6L6L+A==", "dev": true }, + "@types/json-stringify-safe": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@types/json-stringify-safe/-/json-stringify-safe-5.0.0.tgz", + "integrity": "sha512-UUA1sH0RSRROdInuDOA1yoRzbi5xVFD1RHCoOvNRPTNwR8zBkJ/84PZ6NhKVDtKp0FTeIccJCdQz1X2aJPr4uw==", + "dev": true + }, "@types/minimatch": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.3.tgz", @@ -3681,25 +3693,29 @@ "dependencies": { "abbrev": { "version": "1.1.1", - "bundled": true, + "resolved": false, + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==", "dev": true, "optional": true }, "ansi-regex": { "version": "2.1.1", - "bundled": true, + "resolved": false, + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", "dev": true, "optional": true }, "aproba": { "version": "1.2.0", - "bundled": true, + "resolved": false, + "integrity": "sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw==", "dev": true, "optional": true }, "are-we-there-yet": { "version": "1.1.5", - "bundled": true, + "resolved": false, + "integrity": "sha512-5hYdAkZlcG8tOLujVDTgCT+uPX0VnpAH28gWsLfzpXYm7wP6mp5Q/gYyR7YQ0cKVJcXJnl3j2kpBan13PtQf6w==", "dev": true, "optional": true, "requires": { @@ -3709,13 +3725,15 @@ }, "balanced-match": { "version": "1.0.0", - "bundled": true, + "resolved": false, + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", "dev": true, "optional": true }, "brace-expansion": { "version": "1.1.11", - "bundled": true, + "resolved": false, + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", "dev": true, "optional": true, "requires": { @@ -3725,37 +3743,43 @@ }, "chownr": { "version": "1.1.1", - "bundled": true, + "resolved": false, + "integrity": "sha512-j38EvO5+LHX84jlo6h4UzmOwi0UgW61WRyPtJz4qaadK5eY3BTS5TY/S1Stc3Uk2lIM6TPevAlULiEJwie860g==", "dev": true, "optional": true }, "code-point-at": { "version": "1.1.0", - "bundled": true, + "resolved": false, + "integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=", "dev": true, "optional": true }, "concat-map": { "version": "0.0.1", - "bundled": true, + "resolved": false, + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", "dev": true, "optional": true }, "console-control-strings": { "version": "1.1.0", - "bundled": true, + "resolved": false, + "integrity": "sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4=", "dev": true, "optional": true }, "core-util-is": { "version": "1.0.2", - "bundled": true, + "resolved": false, + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", "dev": true, "optional": true }, "debug": { "version": "4.1.1", - "bundled": true, + "resolved": false, + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", "dev": true, "optional": true, "requires": { @@ -3764,25 +3788,29 @@ }, "deep-extend": { "version": "0.6.0", - "bundled": true, + "resolved": false, + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", "dev": true, "optional": true }, "delegates": { "version": "1.0.0", - "bundled": true, + "resolved": false, + "integrity": "sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o=", "dev": true, "optional": true }, "detect-libc": { "version": "1.0.3", - "bundled": true, + "resolved": false, + "integrity": "sha1-+hN8S9aY7fVc1c0CrFWfkaTEups=", "dev": true, "optional": true }, "fs-minipass": { "version": "1.2.5", - "bundled": true, + "resolved": false, + "integrity": "sha512-JhBl0skXjUPCFH7x6x61gQxrKyXsxB5gcgePLZCwfyCGGsTISMoIeObbrvVeP6Xmyaudw4TT43qV2Gz+iyd2oQ==", "dev": true, "optional": true, "requires": { @@ -3791,13 +3819,15 @@ }, "fs.realpath": { "version": "1.0.0", - "bundled": true, + "resolved": false, + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", "dev": true, "optional": true }, "gauge": { "version": "2.7.4", - "bundled": true, + "resolved": false, + "integrity": "sha1-LANAXHU4w51+s3sxcCLjJfsBi/c=", "dev": true, "optional": true, "requires": { @@ -3813,7 +3843,8 @@ }, "glob": { "version": "7.1.3", - "bundled": true, + "resolved": false, + "integrity": "sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ==", "dev": true, "optional": true, "requires": { @@ -3827,13 +3858,15 @@ }, "has-unicode": { "version": "2.0.1", - "bundled": true, + "resolved": false, + "integrity": "sha1-4Ob+aijPUROIVeCG0Wkedx3iqLk=", "dev": true, "optional": true }, "iconv-lite": { "version": "0.4.24", - "bundled": true, + "resolved": false, + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", "dev": true, "optional": true, "requires": { @@ -3842,7 +3875,8 @@ }, "ignore-walk": { "version": "3.0.1", - "bundled": true, + "resolved": false, + "integrity": "sha512-DTVlMx3IYPe0/JJcYP7Gxg7ttZZu3IInhuEhbchuqneY9wWe5Ojy2mXLBaQFUQmo0AW2r3qG7m1mg86js+gnlQ==", "dev": true, "optional": true, "requires": { @@ -3851,7 +3885,8 @@ }, "inflight": { "version": "1.0.6", - "bundled": true, + "resolved": false, + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", "dev": true, "optional": true, "requires": { @@ -3861,19 +3896,22 @@ }, "inherits": { "version": "2.0.3", - "bundled": true, + "resolved": false, + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", "dev": true, "optional": true }, "ini": { "version": "1.3.5", - "bundled": true, + "resolved": false, + "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==", "dev": true, "optional": true }, "is-fullwidth-code-point": { "version": "1.0.0", - "bundled": true, + "resolved": false, + "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", "dev": true, "optional": true, "requires": { @@ -3882,13 +3920,15 @@ }, "isarray": { "version": "1.0.0", - "bundled": true, + "resolved": false, + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", "dev": true, "optional": true }, "minimatch": { "version": "3.0.4", - "bundled": true, + "resolved": false, + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", "dev": true, "optional": true, "requires": { @@ -3897,13 +3937,15 @@ }, "minimist": { "version": "0.0.8", - "bundled": true, + "resolved": false, + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", "dev": true, "optional": true }, "minipass": { "version": "2.3.5", - "bundled": true, + "resolved": false, + "integrity": "sha512-Gi1W4k059gyRbyVUZQ4mEqLm0YIUiGYfvxhF6SIlk3ui1WVxMTGfGdQ2SInh3PDrRTVvPKgULkpJtT4RH10+VA==", "dev": true, "optional": true, "requires": { @@ -3913,7 +3955,8 @@ }, "minizlib": { "version": "1.2.1", - "bundled": true, + "resolved": false, + "integrity": "sha512-7+4oTUOWKg7AuL3vloEWekXY2/D20cevzsrNT2kGWm+39J9hGTCBv8VI5Pm5lXZ/o3/mdR4f8rflAPhnQb8mPA==", "dev": true, "optional": true, "requires": { @@ -3922,7 +3965,8 @@ }, "mkdirp": { "version": "0.5.1", - "bundled": true, + "resolved": false, + "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", "dev": true, "optional": true, "requires": { @@ -3931,13 +3975,15 @@ }, "ms": { "version": "2.1.1", - "bundled": true, + "resolved": false, + "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", "dev": true, "optional": true }, "needle": { "version": "2.3.0", - "bundled": true, + "resolved": false, + "integrity": "sha512-QBZu7aAFR0522EyaXZM0FZ9GLpq6lvQ3uq8gteiDUp7wKdy0lSd2hPlgFwVuW1CBkfEs9PfDQsQzZghLs/psdg==", "dev": true, "optional": true, "requires": { @@ -3948,7 +3994,8 @@ }, "node-pre-gyp": { "version": "0.12.0", - "bundled": true, + "resolved": false, + "integrity": "sha512-4KghwV8vH5k+g2ylT+sLTjy5wmUOb9vPhnM8NHvRf9dHmnW/CndrFXy2aRPaPST6dugXSdHXfeaHQm77PIz/1A==", "dev": true, "optional": true, "requires": { @@ -3966,7 +4013,8 @@ }, "nopt": { "version": "4.0.1", - "bundled": true, + "resolved": false, + "integrity": "sha1-0NRoWv1UFRk8jHUFYC0NF81kR00=", "dev": true, "optional": true, "requires": { @@ -3976,13 +4024,15 @@ }, "npm-bundled": { "version": "1.0.6", - "bundled": true, + "resolved": false, + "integrity": "sha512-8/JCaftHwbd//k6y2rEWp6k1wxVfpFzB6t1p825+cUb7Ym2XQfhwIC5KwhrvzZRJu+LtDE585zVaS32+CGtf0g==", "dev": true, "optional": true }, "npm-packlist": { "version": "1.4.1", - "bundled": true, + "resolved": false, + "integrity": "sha512-+TcdO7HJJ8peiiYhvPxsEDhF3PJFGUGRcFsGve3vxvxdcpO2Z4Z7rkosRM0kWj6LfbK/P0gu3dzk5RU1ffvFcw==", "dev": true, "optional": true, "requires": { @@ -3992,7 +4042,8 @@ }, "npmlog": { "version": "4.1.2", - "bundled": true, + "resolved": false, + "integrity": "sha512-2uUqazuKlTaSI/dC8AzicUck7+IrEaOnN/e0jd3Xtt1KcGpwx30v50mL7oPyr/h9bL3E4aZccVwpwP+5W9Vjkg==", "dev": true, "optional": true, "requires": { @@ -4004,19 +4055,22 @@ }, "number-is-nan": { "version": "1.0.1", - "bundled": true, + "resolved": false, + "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", "dev": true, "optional": true }, "object-assign": { "version": "4.1.1", - "bundled": true, + "resolved": false, + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", "dev": true, "optional": true }, "once": { "version": "1.4.0", - "bundled": true, + "resolved": false, + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", "dev": true, "optional": true, "requires": { @@ -4025,19 +4079,22 @@ }, "os-homedir": { "version": "1.0.2", - "bundled": true, + "resolved": false, + "integrity": "sha1-/7xJiDNuDoM94MFox+8VISGqf7M=", "dev": true, "optional": true }, "os-tmpdir": { "version": "1.0.2", - "bundled": true, + "resolved": false, + "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=", "dev": true, "optional": true }, "osenv": { "version": "0.1.5", - "bundled": true, + "resolved": false, + "integrity": "sha512-0CWcCECdMVc2Rw3U5w9ZjqX6ga6ubk1xDVKxtBQPK7wis/0F2r9T6k4ydGYhecl7YUBxBVxhL5oisPsNxAPe2g==", "dev": true, "optional": true, "requires": { @@ -4047,19 +4104,22 @@ }, "path-is-absolute": { "version": "1.0.1", - "bundled": true, + "resolved": false, + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", "dev": true, "optional": true }, "process-nextick-args": { "version": "2.0.0", - "bundled": true, + "resolved": false, + "integrity": "sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw==", "dev": true, "optional": true }, "rc": { "version": "1.2.8", - "bundled": true, + "resolved": false, + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", "dev": true, "optional": true, "requires": { @@ -4071,7 +4131,8 @@ "dependencies": { "minimist": { "version": "1.2.0", - "bundled": true, + "resolved": false, + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", "dev": true, "optional": true } @@ -4079,7 +4140,8 @@ }, "readable-stream": { "version": "2.3.6", - "bundled": true, + "resolved": false, + "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", "dev": true, "optional": true, "requires": { @@ -4094,7 +4156,8 @@ }, "rimraf": { "version": "2.6.3", - "bundled": true, + "resolved": false, + "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", "dev": true, "optional": true, "requires": { @@ -4103,43 +4166,50 @@ }, "safe-buffer": { "version": "5.1.2", - "bundled": true, + "resolved": false, + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", "dev": true, "optional": true }, "safer-buffer": { "version": "2.1.2", - "bundled": true, + "resolved": false, + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", "dev": true, "optional": true }, "sax": { "version": "1.2.4", - "bundled": true, + "resolved": false, + "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==", "dev": true, "optional": true }, "semver": { "version": "5.7.0", - "bundled": true, + "resolved": false, + "integrity": "sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA==", "dev": true, "optional": true }, "set-blocking": { "version": "2.0.0", - "bundled": true, + "resolved": false, + "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", "dev": true, "optional": true }, "signal-exit": { "version": "3.0.2", - "bundled": true, + "resolved": false, + "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=", "dev": true, "optional": true }, "string-width": { "version": "1.0.2", - "bundled": true, + "resolved": false, + "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", "dev": true, "optional": true, "requires": { @@ -4150,7 +4220,8 @@ }, "string_decoder": { "version": "1.1.1", - "bundled": true, + "resolved": false, + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "dev": true, "optional": true, "requires": { @@ -4159,7 +4230,8 @@ }, "strip-ansi": { "version": "3.0.1", - "bundled": true, + "resolved": false, + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", "dev": true, "optional": true, "requires": { @@ -4168,13 +4240,15 @@ }, "strip-json-comments": { "version": "2.0.1", - "bundled": true, + "resolved": false, + "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=", "dev": true, "optional": true }, "tar": { "version": "4.4.8", - "bundled": true, + "resolved": false, + "integrity": "sha512-LzHF64s5chPQQS0IYBn9IN5h3i98c12bo4NCO7e0sGM2llXQ3p2FGC5sdENN4cTW48O915Sh+x+EXx7XW96xYQ==", "dev": true, "optional": true, "requires": { @@ -4189,13 +4263,15 @@ }, "util-deprecate": { "version": "1.0.2", - "bundled": true, + "resolved": false, + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", "dev": true, "optional": true }, "wide-align": { "version": "1.1.3", - "bundled": true, + "resolved": false, + "integrity": "sha512-QGkOQc8XL6Bt5PwnsExKBPuMKBxnGxWWW3fU55Xt4feHozMUhdUMaBCk290qpm/wG5u/RSKzwdAC4i51YigihA==", "dev": true, "optional": true, "requires": { @@ -4204,13 +4280,15 @@ }, "wrappy": { "version": "1.0.2", - "bundled": true, + "resolved": false, + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", "dev": true, "optional": true }, "yallist": { "version": "3.0.3", - "bundled": true, + "resolved": false, + "integrity": "sha512-S+Zk8DEWE6oKpV+vI3qWkaK+jSbIK86pCwe2IF/xwIpQ8jEuxpw9NyaGjmp9+BoJv5FV2piqCDcoCtStppiq2A==", "dev": true, "optional": true } diff --git a/package.json b/package.json index d0afc996e1..923f17f8de 100644 --- a/package.json +++ b/package.json @@ -24,11 +24,15 @@ "license": "MIT", "devDependencies": { "@microsoft/api-extractor": "^7.7.0", + "@types/invariant": "^2.2.31", "@types/jest": "^24.0.11", + "@types/json-stringify-safe": "^5.0.0", "@types/node": "^10.14.4", "@types/redux-immutable-state-invariant": "^2.1.1", "console-testing-library": "^0.3.1", "eslint-config-react-app": "^5.0.1", + "invariant": "^2.2.4", + "json-stringify-safe": "^5.0.1", "prettier": "^1.18.2", "react": "^16.8.6", "rollup-plugin-strip-code": "^0.2.6", diff --git a/src/getDefaultMiddleware.ts b/src/getDefaultMiddleware.ts index c213506321..5efcf717df 100644 --- a/src/getDefaultMiddleware.ts +++ b/src/getDefaultMiddleware.ts @@ -1,8 +1,11 @@ import { Middleware, AnyAction } from 'redux' import thunkMiddleware, { ThunkMiddleware } from 'redux-thunk' -/* PROD_START_REMOVE_UMD */ -import createImmutableStateInvariantMiddleware from 'redux-immutable-state-invariant' -/* PROD_STOP_REMOVE_UMD */ +import { + /* PROD_START_REMOVE_UMD */ + createImmutableStateInvariantMiddleware, + /* PROD_STOP_REMOVE_UMD */ + ImmutableStateInvariantMiddlewareOptions +} from './immutableStateInvariantMiddleware' import { createSerializableStateInvariantMiddleware, @@ -17,11 +20,6 @@ interface ThunkOptions { extraArgument: E } -interface ImmutableStateInvariantMiddlewareOptions { - isImmutable?: (value: any) => boolean - ignore?: string[] -} - interface GetDefaultMiddlewareOptions { thunk?: boolean | ThunkOptions immutableCheck?: boolean | ImmutableStateInvariantMiddlewareOptions diff --git a/src/immutableStateInvariantMiddleware.test.ts b/src/immutableStateInvariantMiddleware.test.ts new file mode 100644 index 0000000000..38763d6528 --- /dev/null +++ b/src/immutableStateInvariantMiddleware.test.ts @@ -0,0 +1,446 @@ +import { Store, MiddlewareAPI, Dispatch } from 'redux' +import { + createImmutableStateInvariantMiddleware, + isImmutableDefault, + trackForMutations, + ImmutableStateInvariantMiddlewareOptions +} from './immutableStateInvariantMiddleware' + +describe('createImmutableStateInvariantMiddleware', () => { + let state: { foo: { bar: number[]; baz: string } } + const getState: Store['getState'] = () => state + + function middleware(options: ImmutableStateInvariantMiddlewareOptions = {}) { + return createImmutableStateInvariantMiddleware(options)({ + getState + } as MiddlewareAPI) + } + + beforeEach(() => { + state = { foo: { bar: [2, 3, 4], baz: 'baz' } } + }) + + it('sends the action through the middleware chain', () => { + const next: Dispatch = action => ({ ...action, returned: true }) + const dispatch = middleware()(next) + + expect(dispatch({ type: 'SOME_ACTION' })).toEqual({ + type: 'SOME_ACTION', + returned: true + }) + }) + + it('throws if mutating inside the dispatch', () => { + const next: Dispatch = action => { + state.foo.bar.push(5) + return action + } + + const dispatch = middleware()(next) + + expect(() => { + dispatch({ type: 'SOME_ACTION' }) + }).toThrow(new RegExp('foo\\.bar\\.3')) + }) + + it('throws if mutating between dispatches', () => { + const next: Dispatch = action => action + + const dispatch = middleware()(next) + + dispatch({ type: 'SOME_ACTION' }) + state.foo.bar.push(5) + expect(() => { + dispatch({ type: 'SOME_OTHER_ACTION' }) + }).toThrow(new RegExp('foo\\.bar\\.3')) + }) + + it('does not throw if not mutating inside the dispatch', () => { + const next: Dispatch = action => { + state = { ...state, foo: { ...state.foo, baz: 'changed!' } } + return action + } + + const dispatch = middleware()(next) + + expect(() => { + dispatch({ type: 'SOME_ACTION' }) + }).not.toThrow() + }) + + it('does not throw if not mutating between dispatches', () => { + const next: Dispatch = action => action + + const dispatch = middleware()(next) + + dispatch({ type: 'SOME_ACTION' }) + state = { ...state, foo: { ...state.foo, baz: 'changed!' } } + expect(() => { + dispatch({ type: 'SOME_OTHER_ACTION' }) + }).not.toThrow() + }) + + it('works correctly with circular references', () => { + const next: Dispatch = action => action + + const dispatch = middleware()(next) + + let x: any = {} + let y: any = {} + x.y = y + y.x = x + + expect(() => { + dispatch({ type: 'SOME_ACTION', x }) + }).not.toThrow() + }) + + it('respects "isImmutable" option', function() { + const isImmutable = (value: any) => true + const next: Dispatch = action => { + state.foo.bar.push(5) + return action + } + + const dispatch = middleware({ isImmutable })(next) + + expect(() => { + dispatch({ type: 'SOME_ACTION' }) + }).not.toThrow() + }) + + it('respects "ignore" option', () => { + const next: Dispatch = action => { + state.foo.bar.push(5) + return action + } + + const dispatch = middleware({ ignoredPaths: ['foo.bar'] })(next) + + expect(() => { + dispatch({ type: 'SOME_ACTION' }) + }).not.toThrow() + }) +}) + +describe('trackForMutations', () => { + function testCasesForMutation(spec: any) { + it('returns true and the mutated path', () => { + const state = spec.getState() + const options = spec.middlewareOptions || {} + const { isImmutable = isImmutableDefault, ignoredPaths } = options + const tracker = trackForMutations(isImmutable, ignoredPaths, state) + const newState = spec.fn(state) + + expect(tracker.detectMutations()).toEqual({ + wasMutated: true, + path: spec.path + }) + }) + } + + function testCasesForNonMutation(spec: any) { + it('returns false', () => { + const state = spec.getState() + const options = spec.middlewareOptions || {} + const { isImmutable = isImmutableDefault, ignoredPaths } = options + const tracker = trackForMutations(isImmutable, ignoredPaths, state) + const newState = spec.fn(state) + + expect(tracker.detectMutations()).toEqual({ wasMutated: false }) + }) + } + + interface TestConfig { + getState: Store['getState'] + fn: (s: any) => typeof s | object + middlewareOptions?: ImmutableStateInvariantMiddlewareOptions + path?: string[] + } + + const mutations: Record = { + 'adding to nested array': { + getState: () => ({ + foo: { + bar: [2, 3, 4], + baz: 'baz' + }, + stuff: [] + }), + fn: s => { + s.foo.bar.push(5) + return s + }, + path: ['foo', 'bar', '3'] + }, + 'adding to nested array and setting new root object': { + getState: () => ({ + foo: { + bar: [2, 3, 4], + baz: 'baz' + }, + stuff: [] + }), + fn: s => { + s.foo.bar.push(5) + return { ...s } + }, + path: ['foo', 'bar', '3'] + }, + 'changing nested string': { + getState: () => ({ + foo: { + bar: [2, 3, 4], + baz: 'baz' + }, + stuff: [] + }), + fn: s => { + s.foo.baz = 'changed!' + return s + }, + path: ['foo', 'baz'] + }, + 'removing nested state': { + getState: () => ({ + foo: { + bar: [2, 3, 4], + baz: 'baz' + }, + stuff: [] + }), + fn: s => { + delete s.foo + return s + }, + path: ['foo'] + }, + 'adding to array': { + getState: () => ({ + foo: { + bar: [2, 3, 4], + baz: 'baz' + }, + stuff: [] + }), + fn: s => { + s.stuff.push(1) + return s + }, + path: ['stuff', '0'] + }, + 'adding object to array': { + getState: () => ({ + stuff: [] + }), + fn: s => { + s.stuff.push({ foo: 1, bar: 2 }) + return s + }, + path: ['stuff', '0'] + }, + 'mutating previous state and returning new state': { + getState: () => ({ counter: 0 }), + fn: s => { + s.mutation = true + return { ...s, counter: s.counter + 1 } + }, + path: ['mutation'] + }, + 'mutating previous state with non immutable type and returning new state': { + getState: () => ({ counter: 0 }), + fn: s => { + s.mutation = [1, 2, 3] + return { ...s, counter: s.counter + 1 } + }, + path: ['mutation'] + }, + 'mutating previous state with non immutable type and returning new state without that property': { + getState: () => ({ counter: 0 }), + fn: s => { + s.mutation = [1, 2, 3] + return { counter: s.counter + 1 } + }, + path: ['mutation'] + }, + 'mutating previous state with non immutable type and returning new simple state': { + getState: () => ({ counter: 0 }), + fn: s => { + s.mutation = [1, 2, 3] + return 1 + }, + path: ['mutation'] + }, + 'mutating previous state by deleting property and returning new state without that property': { + getState: () => ({ counter: 0, toBeDeleted: true }), + fn: s => { + delete s.toBeDeleted + return { counter: s.counter + 1 } + }, + path: ['toBeDeleted'] + }, + 'mutating previous state by deleting nested property': { + getState: () => ({ nested: { counter: 0, toBeDeleted: true }, foo: 1 }), + fn: s => { + delete s.nested.toBeDeleted + return { nested: { counter: s.counter + 1 } } + }, + path: ['nested', 'toBeDeleted'] + }, + 'update reference': { + getState: () => ({ foo: {} }), + fn: s => { + s.foo = {} + return s + }, + path: ['foo'] + }, + 'cannot ignore root state': { + getState: () => ({ foo: {} }), + fn: s => { + s.foo = {} + return s + }, + middlewareOptions: { + ignoredPaths: [''] + }, + path: ['foo'] + }, + 'catching state mutation in non-ignored branch': { + getState: () => ({ + foo: { + bar: [1, 2] + }, + boo: { + yah: [1, 2] + } + }), + fn: s => { + s.foo.bar.push(3) + s.boo.yah.push(3) + return s + }, + middlewareOptions: { + ignoredPaths: ['foo'] + }, + path: ['boo', 'yah', '2'] + } + } + + Object.keys(mutations).forEach(mutationDesc => { + describe(mutationDesc, () => { + testCasesForMutation(mutations[mutationDesc]) + }) + }) + + const nonMutations: Record = { + 'not doing anything': { + getState: () => ({ a: 1, b: 2 }), + fn: s => s + }, + 'from undefined to something': { + getState: () => undefined, + fn: s => ({ foo: 'bar' }) + }, + 'returning same state': { + getState: () => ({ + foo: { + bar: [2, 3, 4], + baz: 'baz' + }, + stuff: [] + }), + fn: s => s + }, + 'returning a new state object with nested new string': { + getState: () => ({ + foo: { + bar: [2, 3, 4], + baz: 'baz' + }, + stuff: [] + }), + fn: s => { + return { ...s, foo: { ...s.foo, baz: 'changed!' } } + } + }, + 'returning a new state object with nested new array': { + getState: () => ({ + foo: { + bar: [2, 3, 4], + baz: 'baz' + }, + stuff: [] + }), + fn: s => { + return { ...s, foo: { ...s.foo, bar: [...s.foo.bar, 5] } } + } + }, + 'removing nested state': { + getState: () => ({ + foo: { + bar: [2, 3, 4], + baz: 'baz' + }, + stuff: [] + }), + fn: s => { + return { ...s, foo: {} } + } + }, + 'having a NaN in the state': { + getState: () => ({ a: NaN, b: Number.NaN }), + fn: s => s + }, + 'ignoring branches from mutation detection': { + getState: () => ({ + foo: { + bar: 'bar' + } + }), + fn: s => { + s.foo.bar = 'baz' + return s + }, + middlewareOptions: { + ignoredPaths: ['foo'] + } + }, + 'ignoring nested branches from mutation detection': { + getState: () => ({ + foo: { + bar: [1, 2], + boo: { + yah: [1, 2] + } + } + }), + fn: s => { + s.foo.bar.push(3) + s.foo.boo.yah.push(3) + return s + }, + middlewareOptions: { + ignoredPaths: ['foo.bar', 'foo.boo.yah'] + } + }, + 'ignoring nested array indices from mutation detection': { + getState: () => ({ + stuff: [{ a: 1 }, { a: 2 }] + }), + fn: s => { + s.stuff[1].a = 3 + return s + }, + middlewareOptions: { + ignoredPaths: ['stuff.1'] + } + } + } + + Object.keys(nonMutations).forEach(nonMutationDesc => { + describe(nonMutationDesc, () => { + testCasesForNonMutation(nonMutations[nonMutationDesc]) + }) + }) +}) diff --git a/src/immutableStateInvariantMiddleware.ts b/src/immutableStateInvariantMiddleware.ts new file mode 100644 index 0000000000..d7fc58731e --- /dev/null +++ b/src/immutableStateInvariantMiddleware.ts @@ -0,0 +1,175 @@ +import invariant from 'invariant' +import stringify from 'json-stringify-safe' +import { Middleware } from 'redux' + +const BETWEEN_DISPATCHES_MESSAGE = [ + 'A state mutation was detected between dispatches, in the path `%s`.', + 'This may cause incorrect behavior.', + '(http://redux.js.org/docs/Troubleshooting.html#never-mutate-reducer-arguments)' +].join(' ') + +const INSIDE_DISPATCH_MESSAGE = [ + 'A state mutation was detected inside a dispatch, in the path: `%s`.', + 'Take a look at the reducer(s) handling the action %s.', + '(http://redux.js.org/docs/Troubleshooting.html#never-mutate-reducer-arguments)' +].join(' ') + +export function isImmutableDefault(value: unknown): boolean { + return ( + typeof value !== 'object' || value === null || typeof value === 'undefined' + ) +} + +export function trackForMutations( + isImmutable: IsImmutableFunc, + ingorePaths: string[] | undefined, + obj: any +) { + const trackedProperties = trackProperties(isImmutable, ingorePaths, obj) + return { + detectMutations() { + return detectMutations(isImmutable, ingorePaths, trackedProperties, obj) + } + } +} + +interface TrackedProperty { + value: any + children: Record +} + +function trackProperties( + isImmutable: IsImmutableFunc, + ignorePaths: IgnorePaths = [], + obj: Record, + path: string[] = [] +) { + const tracked: Partial = { value: obj } + + if (!isImmutable(obj)) { + tracked.children = {} + + for (const key in obj) { + const childPath = path.concat(key) + if ( + ignorePaths.length && + ignorePaths.indexOf(childPath.join('.')) !== -1 + ) { + continue + } + + tracked.children[key] = trackProperties( + isImmutable, + ignorePaths, + obj[key], + childPath + ) + } + } + return tracked as TrackedProperty +} + +type IgnorePaths = string[] + +function detectMutations( + isImmutable: IsImmutableFunc, + ignorePaths: 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 = {} + Object.keys(trackedProperty.children).forEach(key => { + keysToDetect[key] = true + }) + Object.keys(obj).forEach(key => { + keysToDetect[key] = true + }) + + const keys = Object.keys(keysToDetect) + for (let i = 0; i < keys.length; i++) { + const key = keys[i] + const childPath = path.concat(key) + if (ignorePaths.length && ignorePaths.indexOf(childPath.join('.')) !== -1) { + continue + } + + const result = detectMutations( + isImmutable, + ignorePaths, + trackedProperty.children[key], + obj[key], + sameRef, + childPath + ) + + if (result.wasMutated) { + return result + } + } + return { wasMutated: false } +} + +type IsImmutableFunc = (value: any) => boolean +export interface ImmutableStateInvariantMiddlewareOptions { + isImmutable?: IsImmutableFunc + ignoredPaths?: string[] +} + +export function createImmutableStateInvariantMiddleware( + options: ImmutableStateInvariantMiddlewareOptions = {} +): Middleware { + const { isImmutable = isImmutableDefault, ignoredPaths } = options + const track = trackForMutations.bind(null, isImmutable, ignoredPaths) + + return ({ getState }) => { + let state = getState() + let tracker = track(state) + + let result + return next => action => { + state = getState() + + result = tracker.detectMutations() + // Track before potentially not meeting the invariant + tracker = track(state) + + invariant( + !result.wasMutated, + BETWEEN_DISPATCHES_MESSAGE, + (result.path || []).join('.') + ) + + const dispatchedAction = next(action) + state = getState() + + result = tracker.detectMutations() + // Track before potentially not meeting the invariant + tracker = track(state) + + result.wasMutated && + invariant( + !result.wasMutated, + INSIDE_DISPATCH_MESSAGE, + (result.path || []).join('.'), + stringify(action) + ) + + return dispatchedAction + } + } +}