| 1 |
import type { Middleware } from 'redux' |
| 2 |
import type { IgnorePaths } from './serializableStateInvariantMiddleware' |
| 3 |
import { getTimeMeasureUtils } from './utils' |
| 4 |
|
| 5 |
type EntryProcessor = (key: string, value: any) => any |
| 6 |
|
| 7 |
/** |
| 8 |
* The default `isImmutable` function. |
| 9 |
* |
| 10 |
* @public |
| 11 |
*/ |
| 12 |
export function isImmutableDefault(value: unknown): boolean { |
| 13 |
return typeof value !== 'object' || value == null || Object.isFrozen(value) |
| 14 |
} |
| 15 |
|
| 16 |
export function trackForMutations( |
| 17 |
isImmutable: IsImmutableFunc, |
| 18 |
ignorePaths: IgnorePaths | undefined, |
| 19 |
obj: any, |
| 20 |
) { |
| 21 |
const trackedProperties = trackProperties(isImmutable, ignorePaths, obj) |
| 22 |
return { |
| 23 |
detectMutations() { |
| 24 |
return detectMutations(isImmutable, ignorePaths, trackedProperties, obj) |
| 25 |
}, |
| 26 |
} |
| 27 |
} |
| 28 |
|
| 29 |
interface TrackedProperty { |
| 30 |
value: any |
| 31 |
children: Record<string, any> |
| 32 |
} |
| 33 |
|
| 34 |
function trackProperties( |
| 35 |
isImmutable: IsImmutableFunc, |
| 36 |
ignorePaths: IgnorePaths = [], |
| 37 |
obj: Record<string, any>, |
| 38 |
path: string = '', |
| 39 |
checkedObjects: Set<Record<string, any>> = new Set(), |
| 40 |
) { |
| 41 |
const tracked: Partial<TrackedProperty> = { value: obj } |
| 42 |
|
| 43 |
if (!isImmutable(obj) && !checkedObjects.has(obj)) { |
| 44 |
checkedObjects.add(obj) |
| 45 |
tracked.children = {} |
| 46 |
|
| 47 |
for (const key in obj) { |
| 48 |
const childPath = path ? path + '.' + key : key |
| 49 |
if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) { |
| 50 |
continue |
| 51 |
} |
| 52 |
|
| 53 |
tracked.children[key] = trackProperties( |
| 54 |
isImmutable, |
| 55 |
ignorePaths, |
| 56 |
obj[key], |
| 57 |
childPath, |
| 58 |
) |
| 59 |
} |
| 60 |
} |
| 61 |
return tracked as TrackedProperty |
| 62 |
} |
| 63 |
|
| 64 |
function detectMutations( |
| 65 |
isImmutable: IsImmutableFunc, |
| 66 |
ignoredPaths: IgnorePaths = [], |
| 67 |
trackedProperty: TrackedProperty, |
| 68 |
obj: any, |
| 69 |
sameParentRef: boolean = false, |
| 70 |
path: string = '', |
| 71 |
): { wasMutated: boolean; path?: string } { |
| 72 |
const prevObj = trackedProperty ? trackedProperty.value : undefined |
| 73 |
|
| 74 |
const sameRef = prevObj === obj |
| 75 |
|
| 76 |
if (sameParentRef && !sameRef && !Number.isNaN(obj)) { |
| 77 |
return { wasMutated: true, path } |
| 78 |
} |
| 79 |
|
| 80 |
if (isImmutable(prevObj) || isImmutable(obj)) { |
| 81 |
return { wasMutated: false } |
| 82 |
} |
| 83 |
|
| 84 |
// Gather all keys from prev (tracked) and after objs |
| 85 |
const keysToDetect: Record<string, boolean> = {} |
| 86 |
for (let key in trackedProperty.children) { |
| 87 |
keysToDetect[key] = true |
| 88 |
} |
| 89 |
for (let key in obj) { |
| 90 |
keysToDetect[key] = true |
| 91 |
} |
| 92 |
|
| 93 |
const hasIgnoredPaths = ignoredPaths.length > 0 |
| 94 |
|
| 95 |
for (let key in keysToDetect) { |
| 96 |
const nestedPath = path ? path + '.' + key : key |
| 97 |
|
| 98 |
if (hasIgnoredPaths) { |
| 99 |
const hasMatches = ignoredPaths.some((ignored) => { |
| 100 |
if (ignored instanceof RegExp) { |
| 101 |
return ignored.test(nestedPath) |
| 102 |
} |
| 103 |
return nestedPath === ignored |
| 104 |
}) |
| 105 |
if (hasMatches) { |
| 106 |
continue |
| 107 |
} |
| 108 |
} |
| 109 |
|
| 110 |
const result = detectMutations( |
| 111 |
isImmutable, |
| 112 |
ignoredPaths, |
| 113 |
trackedProperty.children[key], |
| 114 |
obj[key], |
| 115 |
sameRef, |
| 116 |
nestedPath, |
| 117 |
) |
| 118 |
|
| 119 |
if (result.wasMutated) { |
| 120 |
return result |
| 121 |
} |
| 122 |
} |
| 123 |
return { wasMutated: false } |
| 124 |
} |
| 125 |
|
| 126 |
type IsImmutableFunc = (value: any) => boolean |
| 127 |
|
| 128 |
/** |
| 129 |
* Options for `createImmutableStateInvariantMiddleware()`. |
| 130 |
* |
| 131 |
* @public |
| 132 |
*/ |
| 133 |
export interface ImmutableStateInvariantMiddlewareOptions { |
| 134 |
/** |
| 135 |
Callback function to check if a value is considered to be immutable. |
| 136 |
This function is applied recursively to every value contained in the state. |
| 137 |
The default implementation will return true for primitive types |
| 138 |
(like numbers, strings, booleans, null and undefined). |
| 139 |
*/ |
| 140 |
isImmutable?: IsImmutableFunc |
| 141 |
/** |
| 142 |
An array of dot-separated path strings that match named nodes from |
| 143 |
the root state to ignore when checking for immutability. |
| 144 |
Defaults to undefined |
| 145 |
*/ |
| 146 |
ignoredPaths?: IgnorePaths |
| 147 |
/** Print a warning if checks take longer than N ms. Default: 32ms */ |
| 148 |
warnAfter?: number |
| 149 |
} |
| 150 |
|
| 151 |
/** |
| 152 |
* Creates a middleware that checks whether any state was mutated in between |
| 153 |
* dispatches or during a dispatch. If any mutations are detected, an error is |
| 154 |
* thrown. |
| 155 |
* |
| 156 |
* @param options Middleware options. |
| 157 |
* |
| 158 |
* @public |
| 159 |
*/ |
| 160 |
export function createImmutableStateInvariantMiddleware( |
| 161 |
options: ImmutableStateInvariantMiddlewareOptions = {}, |
| 162 |
): Middleware { |
| 163 |
if (process.env.NODE_ENV === 'production') { |
| 164 |
return () => (next) => (action) => next(action) |
| 165 |
} else { |
| 166 |
function stringify( |
| 167 |
obj: any, |
| 168 |
serializer?: EntryProcessor, |
| 169 |
indent?: string | number, |
| 170 |
decycler?: EntryProcessor, |
| 171 |
): string { |
| 172 |
return JSON.stringify(obj, getSerialize(serializer, decycler), indent) |
| 173 |
} |
| 174 |
|
| 175 |
function getSerialize( |
| 176 |
serializer?: EntryProcessor, |
| 177 |
decycler?: EntryProcessor, |
| 178 |
): EntryProcessor { |
| 179 |
let stack: any[] = [], |
| 180 |
keys: any[] = [] |
| 181 |
|
| 182 |
if (!decycler) |
| 183 |
decycler = function (_: string, value: any) { |
| 184 |
if (stack[0] === value) return '[Circular ~]' |
| 185 |
return ( |
| 186 |
'[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']' |
| 187 |
) |
| 188 |
} |
| 189 |
|
| 190 |
return function (this: any, key: string, value: any) { |
| 191 |
if (stack.length > 0) { |
| 192 |
var thisPos = stack.indexOf(this) |
| 193 |
~thisPos ? stack.splice(thisPos + 1) : stack.push(this) |
| 194 |
~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key) |
| 195 |
if (~stack.indexOf(value)) value = decycler!.call(this, key, value) |
| 196 |
} else stack.push(value) |
| 197 |
|
| 198 |
return serializer == null ? value : serializer.call(this, key, value) |
| 199 |
} |
| 200 |
} |
| 201 |
|
| 202 |
let { |
| 203 |
isImmutable = isImmutableDefault, |
| 204 |
ignoredPaths, |
| 205 |
warnAfter = 32, |
| 206 |
} = options |
| 207 |
|
| 208 |
const track = trackForMutations.bind(null, isImmutable, ignoredPaths) |
| 209 |
|
| 210 |
return ({ getState }) => { |
| 211 |
let state = getState() |
| 212 |
let tracker = track(state) |
| 213 |
|
| 214 |
let result |
| 215 |
return (next) => (action) => { |
| 216 |
const measureUtils = getTimeMeasureUtils( |
| 217 |
warnAfter, |
| 218 |
'ImmutableStateInvariantMiddleware', |
| 219 |
) |
| 220 |
|
| 221 |
measureUtils.measureTime(() => { |
| 222 |
state = getState() |
| 223 |
|
| 224 |
result = tracker.detectMutations() |
| 225 |
// Track before potentially not meeting the invariant |
| 226 |
tracker = track(state) |
| 227 |
|
| 228 |
if (result.wasMutated) { |
| 229 |
throw new Error( |
| 230 |
`A state mutation was detected between dispatches, in the path '${ |
| 231 |
result.path || '' |
| 232 |
}'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`, |
| 233 |
) |
| 234 |
} |
| 235 |
}) |
| 236 |
|
| 237 |
const dispatchedAction = next(action) |
| 238 |
|
| 239 |
measureUtils.measureTime(() => { |
| 240 |
state = getState() |
| 241 |
|
| 242 |
result = tracker.detectMutations() |
| 243 |
// Track before potentially not meeting the invariant |
| 244 |
tracker = track(state) |
| 245 |
|
| 246 |
if (result.wasMutated) { |
| 247 |
throw new Error( |
| 248 |
`A state mutation was detected inside a dispatch, in the path: ${ |
| 249 |
result.path || '' |
| 250 |
}. Take a look at the reducer(s) handling the action ${stringify( |
| 251 |
action, |
| 252 |
)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`, |
| 253 |
) |
| 254 |
} |
| 255 |
}) |
| 256 |
|
| 257 |
measureUtils.warnIfExceeded() |
| 258 |
|
| 259 |
return dispatchedAction |
| 260 |
} |
| 261 |
} |
| 262 |
} |
| 263 |
} |