Convert redux-devtools-instrument to TypeScript

This commit is contained in:
Nathan Bierema 2020-05-15 00:10:54 -04:00
parent 93d6bc4350
commit 3b9d9443fb
10 changed files with 689 additions and 307 deletions

View File

@ -1,3 +1,9 @@
{ {
"presets": ["@babel/preset-env"] "presets": [
"@babel/env",
"@babel/typescript"
],
"plugins": [
"@babel/proposal-class-properties"
]
} }

View File

@ -0,0 +1 @@
lib

View File

@ -0,0 +1,21 @@
module.exports = {
extends: '../../.eslintrc',
overrides: [
{
files: ['*.ts'],
extends: '../../eslintrc.ts.base.json',
parserOptions: {
tsconfigRootDir: __dirname,
project: ['./tsconfig.json']
}
},
{
files: ['test/*.ts'],
extends: '../../eslintrc.ts.jest.base.json',
parserOptions: {
tsconfigRootDir: __dirname,
project: ['./test/tsconfig.json']
}
}
]
};

View File

@ -0,0 +1 @@
lib

View File

@ -3,10 +3,17 @@
"version": "1.9.6", "version": "1.9.6",
"description": "Redux DevTools instrumentation", "description": "Redux DevTools instrumentation",
"main": "lib/instrument.js", "main": "lib/instrument.js",
"types": "lib/instrument.d.ts",
"scripts": { "scripts": {
"type-check": "tsc --noEmit",
"type-check:watch": "npm run type-check -- --watch",
"clean": "rimraf lib", "clean": "rimraf lib",
"build": "babel src --out-dir lib", "build": "npm run build:types && npm run build:js",
"test": "jest", "build:types": "tsc --emitDeclarationOnly",
"build:js": "babel src --out-dir lib --extensions \".ts\" --source-maps inline",
"lint": "eslint . --ext .js,.ts",
"lint:fix": "eslint . --ext .js,.ts --fix",
"test": "tsc --project test/tsconfig.json --noEmit && jest",
"prepare": "npm run build", "prepare": "npm run build",
"prepublishOnly": "npm run test && npm run clean && npm run build" "prepublishOnly": "npm run test && npm run clean && npm run build"
}, },
@ -35,16 +42,26 @@
"devDependencies": { "devDependencies": {
"@babel/cli": "^7.2.3", "@babel/cli": "^7.2.3",
"@babel/core": "^7.2.2", "@babel/core": "^7.2.2",
"@babel/plugin-proposal-class-properties": "^7.3.0",
"@babel/preset-env": "^7.3.1", "@babel/preset-env": "^7.3.1",
"@babel/preset-typescript": "^7.9.0",
"@types/jest": "^25.2.1",
"@types/lodash": "^4.2.0",
"@typescript-eslint/eslint-plugin": "^2.31.0",
"@typescript-eslint/parser": "^2.31.0",
"babel-loader": "^8.0.5", "babel-loader": "^8.0.5",
"expect": "^1.6.0", "expect": "^1.6.0",
"jest": "^24.1.0", "jest": "^24.1.0",
"redux": "^4.0.0", "redux": "^4.0.5",
"rimraf": "^2.3.4", "rimraf": "^2.3.4",
"rxjs": "^5.0.0-beta.6" "rxjs": "^5.0.0-beta.6",
"typescript": "^3.8.3"
}, },
"dependencies": { "dependencies": {
"lodash": "^4.2.0", "lodash": "^4.2.0",
"symbol-observable": "^1.0.2" "symbol-observable": "^1.0.2"
},
"peerDependencies": {
"redux": "^4.0.5"
} }
} }

View File

@ -2,6 +2,15 @@ import difference from 'lodash/difference';
import union from 'lodash/union'; import union from 'lodash/union';
import isPlainObject from 'lodash/isPlainObject'; import isPlainObject from 'lodash/isPlainObject';
import $$observable from 'symbol-observable'; import $$observable from 'symbol-observable';
import {
Action,
Observable,
PreloadedState,
Reducer,
Store,
StoreEnhancer,
StoreEnhancerStoreCreator
} from 'redux';
export const ActionTypes = { export const ActionTypes = {
PERFORM_ACTION: 'PERFORM_ACTION', PERFORM_ACTION: 'PERFORM_ACTION',
@ -17,13 +26,15 @@ export const ActionTypes = {
IMPORT_STATE: 'IMPORT_STATE', IMPORT_STATE: 'IMPORT_STATE',
LOCK_CHANGES: 'LOCK_CHANGES', LOCK_CHANGES: 'LOCK_CHANGES',
PAUSE_RECORDING: 'PAUSE_RECORDING' PAUSE_RECORDING: 'PAUSE_RECORDING'
}; } as const;
const isChrome = const isChrome =
typeof window === 'object' && typeof window === 'object' &&
(typeof window.chrome !== 'undefined' || (typeof (window as typeof window & { chrome: unknown }).chrome !==
'undefined' ||
(typeof window.process !== 'undefined' && (typeof window.process !== 'undefined' &&
window.process.type === 'renderer')); (window.process as typeof window.process & { type: unknown }).type ===
'renderer'));
const isChromeOrNode = const isChromeOrNode =
isChrome || isChrome ||
@ -31,11 +42,102 @@ const isChromeOrNode =
process.release && process.release &&
process.release.name === 'node'); process.release.name === 'node');
export interface PerformAction<A extends Action<unknown>> {
type: typeof ActionTypes.PERFORM_ACTION;
action: A;
timestamp: number;
stack: string | undefined;
}
interface ResetAction {
type: typeof ActionTypes.RESET;
timestamp: number;
}
interface RollbackAction {
type: typeof ActionTypes.ROLLBACK;
timestamp: number;
}
interface CommitAction {
type: typeof ActionTypes.COMMIT;
timestamp: number;
}
interface SweepAction {
type: typeof ActionTypes.SWEEP;
}
interface ToggleAction {
type: typeof ActionTypes.TOGGLE_ACTION;
id: number;
}
interface SetActionsActiveAction {
type: typeof ActionTypes.SET_ACTIONS_ACTIVE;
start: number;
end: number;
active: boolean;
}
interface ReorderAction {
type: typeof ActionTypes.REORDER_ACTION;
actionId: number;
beforeActionId: number;
}
interface JumpToStateAction {
type: typeof ActionTypes.JUMP_TO_STATE;
index: number;
}
interface JumpToActionAction {
type: typeof ActionTypes.JUMP_TO_ACTION;
actionId: number;
}
interface ImportStateAction<S, A extends Action<unknown>> {
type: typeof ActionTypes.IMPORT_STATE;
nextLiftedState: LiftedState<S, A> | readonly A[];
preloadedState?: S;
noRecompute: boolean | undefined;
}
interface LockChangesAction {
type: typeof ActionTypes.LOCK_CHANGES;
status: boolean;
}
interface PauseRecordingAction {
type: typeof ActionTypes.PAUSE_RECORDING;
status: boolean;
}
export type LiftedAction<S, A extends Action<unknown>> =
| PerformAction<A>
| ResetAction
| RollbackAction
| CommitAction
| SweepAction
| ToggleAction
| SetActionsActiveAction
| ReorderAction
| JumpToStateAction
| JumpToActionAction
| ImportStateAction<S, A>
| LockChangesAction
| PauseRecordingAction;
/** /**
* Action creators to change the History state. * Action creators to change the History state.
*/ */
export const ActionCreators = { export const ActionCreators = {
performAction(action, trace, traceLimit, toExcludeFromTrace) { performAction<A extends Action<unknown>>(
action: A,
trace?: ((action: A) => string | undefined) | boolean,
traceLimit?: number,
toExcludeFromTrace?: Function
): PerformAction<A> {
if (!isPlainObject(action)) { if (!isPlainObject(action)) {
throw new Error( throw new Error(
'Actions must be plain objects. ' + 'Actions must be plain objects. ' +
@ -60,7 +162,7 @@ export const ActionCreators = {
let prevStackTraceLimit; let prevStackTraceLimit;
if (Error.captureStackTrace && isChromeOrNode) { if (Error.captureStackTrace && isChromeOrNode) {
// avoid error-polyfill // avoid error-polyfill
if (Error.stackTraceLimit < traceLimit) { if (traceLimit && Error.stackTraceLimit < traceLimit) {
prevStackTraceLimit = Error.stackTraceLimit; prevStackTraceLimit = Error.stackTraceLimit;
Error.stackTraceLimit = traceLimit; Error.stackTraceLimit = traceLimit;
} }
@ -73,20 +175,24 @@ export const ActionCreators = {
if ( if (
extraFrames || extraFrames ||
typeof Error.stackTraceLimit !== 'number' || typeof Error.stackTraceLimit !== 'number' ||
Error.stackTraceLimit > traceLimit (traceLimit && Error.stackTraceLimit > traceLimit)
) { ) {
if (stack != null) {
const frames = stack.split('\n'); const frames = stack.split('\n');
if (frames.length > traceLimit) { if (traceLimit && frames.length > traceLimit) {
stack = frames stack = frames
.slice( .slice(
0, 0,
traceLimit + extraFrames + (frames[0] === 'Error' ? 1 : 0) traceLimit +
extraFrames +
(frames[0].startsWith('Error') ? 1 : 0)
) )
.join('\n'); .join('\n');
} }
} }
} }
} }
}
return { return {
type: ActionTypes.PERFORM_ACTION, type: ActionTypes.PERFORM_ACTION,
@ -96,51 +202,58 @@ export const ActionCreators = {
}; };
}, },
reset() { reset(): ResetAction {
return { type: ActionTypes.RESET, timestamp: Date.now() }; return { type: ActionTypes.RESET, timestamp: Date.now() };
}, },
rollback() { rollback(): RollbackAction {
return { type: ActionTypes.ROLLBACK, timestamp: Date.now() }; return { type: ActionTypes.ROLLBACK, timestamp: Date.now() };
}, },
commit() { commit(): CommitAction {
return { type: ActionTypes.COMMIT, timestamp: Date.now() }; return { type: ActionTypes.COMMIT, timestamp: Date.now() };
}, },
sweep() { sweep(): SweepAction {
return { type: ActionTypes.SWEEP }; return { type: ActionTypes.SWEEP };
}, },
toggleAction(id) { toggleAction(id: number): ToggleAction {
return { type: ActionTypes.TOGGLE_ACTION, id }; return { type: ActionTypes.TOGGLE_ACTION, id };
}, },
setActionsActive(start, end, active = true) { setActionsActive(
start: number,
end: number,
active = true
): SetActionsActiveAction {
return { type: ActionTypes.SET_ACTIONS_ACTIVE, start, end, active }; return { type: ActionTypes.SET_ACTIONS_ACTIVE, start, end, active };
}, },
reorderAction(actionId, beforeActionId) { reorderAction(actionId: number, beforeActionId: number): ReorderAction {
return { type: ActionTypes.REORDER_ACTION, actionId, beforeActionId }; return { type: ActionTypes.REORDER_ACTION, actionId, beforeActionId };
}, },
jumpToState(index) { jumpToState(index: number): JumpToStateAction {
return { type: ActionTypes.JUMP_TO_STATE, index }; return { type: ActionTypes.JUMP_TO_STATE, index };
}, },
jumpToAction(actionId) { jumpToAction(actionId: number): JumpToActionAction {
return { type: ActionTypes.JUMP_TO_ACTION, actionId }; return { type: ActionTypes.JUMP_TO_ACTION, actionId };
}, },
importState(nextLiftedState, noRecompute) { importState<S, A extends Action<unknown>>(
nextLiftedState: LiftedState<S, A> | readonly A[],
noRecompute?: boolean
): ImportStateAction<S, A> {
return { type: ActionTypes.IMPORT_STATE, nextLiftedState, noRecompute }; return { type: ActionTypes.IMPORT_STATE, nextLiftedState, noRecompute };
}, },
lockChanges(status) { lockChanges(status: boolean): LockChangesAction {
return { type: ActionTypes.LOCK_CHANGES, status }; return { type: ActionTypes.LOCK_CHANGES, status };
}, },
pauseRecording(status) { pauseRecording(status: boolean): PauseRecordingAction {
return { type: ActionTypes.PAUSE_RECORDING, status }; return { type: ActionTypes.PAUSE_RECORDING, status };
} }
}; };
@ -150,7 +263,11 @@ export const INIT_ACTION = { type: '@@INIT' };
/** /**
* Computes the next entry with exceptions catching. * Computes the next entry with exceptions catching.
*/ */
function computeWithTryCatch(reducer, action, state) { function computeWithTryCatch<S, A extends Action<unknown>>(
reducer: Reducer<S, A>,
action: A,
state: S
) {
let nextState = state; let nextState = state;
let nextError; let nextError;
try { try {
@ -176,7 +293,12 @@ function computeWithTryCatch(reducer, action, state) {
/** /**
* Computes the next entry in the log by applying an action. * Computes the next entry in the log by applying an action.
*/ */
function computeNextEntry(reducer, action, state, shouldCatchErrors) { function computeNextEntry<S, A extends Action<unknown>>(
reducer: Reducer<S, A>,
action: A,
state: S,
shouldCatchErrors: boolean | undefined
) {
if (!shouldCatchErrors) { if (!shouldCatchErrors) {
return { state: reducer(state, action) }; return { state: reducer(state, action) };
} }
@ -186,15 +308,15 @@ function computeNextEntry(reducer, action, state, shouldCatchErrors) {
/** /**
* Runs the reducer on invalidated actions to get a fresh computation log. * Runs the reducer on invalidated actions to get a fresh computation log.
*/ */
function recomputeStates( function recomputeStates<S, A extends Action<unknown>>(
computedStates, computedStates: { state: S; error?: string }[],
minInvalidatedStateIndex, minInvalidatedStateIndex: number,
reducer, reducer: Reducer<S, A>,
committedState, committedState: S,
actionsById, actionsById: { [actionId: number]: PerformAction<A> },
stagedActionIds, stagedActionIds: number[],
skippedActionIds, skippedActionIds: number[],
shouldCatchErrors shouldCatchErrors: boolean | undefined
) { ) {
// Optimization: exit early and return the same reference // Optimization: exit early and return the same reference
// if we know nothing could have changed. // if we know nothing could have changed.
@ -215,7 +337,7 @@ function recomputeStates(
const previousEntry = nextComputedStates[i - 1]; const previousEntry = nextComputedStates[i - 1];
const previousState = previousEntry ? previousEntry.state : committedState; const previousState = previousEntry ? previousEntry.state : committedState;
const shouldSkip = skippedActionIds.indexOf(actionId) > -1; const shouldSkip = skippedActionIds.includes(actionId);
let entry; let entry;
if (shouldSkip) { if (shouldSkip) {
entry = previousEntry; entry = previousEntry;
@ -243,8 +365,13 @@ function recomputeStates(
/** /**
* Lifts an app's action into an action on the lifted store. * Lifts an app's action into an action on the lifted store.
*/ */
export function liftAction(action, trace, traceLimit, toExcludeFromTrace) { export function liftAction<A extends Action<unknown>>(
return ActionCreators.performAction( action: A,
trace?: ((action: A) => string | undefined) | boolean,
traceLimit?: number,
toExcludeFromTrace?: Function
): PerformAction<A> {
return ActionCreators.performAction<A>(
action, action,
trace, trace,
traceLimit, traceLimit,
@ -252,22 +379,41 @@ export function liftAction(action, trace, traceLimit, toExcludeFromTrace) {
); );
} }
export interface LiftedState<S, A extends Action<unknown>> {
monitorState: unknown;
nextActionId: number;
actionsById: { [actionId: number]: PerformAction<A> };
stagedActionIds: number[];
skippedActionIds: number[];
committedState: S;
currentStateIndex: number;
computedStates: { state: S; error?: string }[];
isLocked: boolean;
isPaused: boolean;
}
function isArray<S, A extends Action<unknown>>(
nextLiftedState: LiftedState<S, A> | readonly A[]
): nextLiftedState is readonly A[] {
return Array.isArray(nextLiftedState);
}
/** /**
* Creates a history state reducer from an app's reducer. * Creates a history state reducer from an app's reducer.
*/ */
export function liftReducerWith( export function liftReducerWith<S, A extends Action<unknown>>(
reducer, reducer: Reducer<S, A>,
initialCommittedState, initialCommittedState: PreloadedState<S> | undefined,
monitorReducer, monitorReducer: Reducer<unknown, Action<unknown>>,
options options: Options<S, A>
) { ): Reducer<LiftedState<S, A>, LiftedAction<S, A>> {
const initialLiftedState = { const initialLiftedState: LiftedState<S, A> = {
monitorState: monitorReducer(undefined, {}), monitorState: monitorReducer(undefined, {} as Action<unknown>),
nextActionId: 1, nextActionId: 1,
actionsById: { 0: liftAction(INIT_ACTION) }, actionsById: { 0: liftAction<A>(INIT_ACTION as A) },
stagedActionIds: [0], stagedActionIds: [0],
skippedActionIds: [], skippedActionIds: [],
committedState: initialCommittedState, committedState: initialCommittedState as S,
currentStateIndex: 0, currentStateIndex: 0,
computedStates: [], computedStates: [],
isLocked: options.shouldStartLocked === true, isLocked: options.shouldStartLocked === true,
@ -277,7 +423,10 @@ export function liftReducerWith(
/** /**
* Manages how the history actions modify the history state. * Manages how the history actions modify the history state.
*/ */
return (liftedState, liftedAction) => { return (
liftedState: LiftedState<S, A> | undefined,
liftedAction: LiftedAction<S, A>
): LiftedState<S, A> => {
let { let {
monitorState, monitorState,
actionsById, actionsById,
@ -296,7 +445,7 @@ export function liftReducerWith(
actionsById = { ...actionsById }; actionsById = { ...actionsById };
} }
function commitExcessActions(n) { function commitExcessActions(n: number) {
// Auto-commits n-number of excess actions. // Auto-commits n-number of excess actions.
let excess = n; let excess = n;
let idsToDelete = stagedActionIds.slice(1, excess + 1); let idsToDelete = stagedActionIds.slice(1, excess + 1);
@ -313,7 +462,7 @@ export function liftReducerWith(
} }
skippedActionIds = skippedActionIds.filter( skippedActionIds = skippedActionIds.filter(
id => idsToDelete.indexOf(id) === -1 id => !idsToDelete.includes(id)
); );
stagedActionIds = [0, ...stagedActionIds.slice(excess + 1)]; stagedActionIds = [0, ...stagedActionIds.slice(excess + 1)];
committedState = computedStates[excess].state; committedState = computedStates[excess].state;
@ -322,7 +471,7 @@ export function liftReducerWith(
currentStateIndex > excess ? currentStateIndex - excess : 0; currentStateIndex > excess ? currentStateIndex - excess : 0;
} }
function computePausedAction(shouldInit) { function computePausedAction(shouldInit?: boolean): LiftedState<S, A> {
let computedState; let computedState;
if (shouldInit) { if (shouldInit) {
computedState = computedStates[currentStateIndex]; computedState = computedStates[currentStateIndex];
@ -330,7 +479,7 @@ export function liftReducerWith(
} else { } else {
computedState = computeNextEntry( computedState = computeNextEntry(
reducer, reducer,
liftedAction.action, (liftedAction as PerformAction<A>).action,
computedStates[currentStateIndex].state, computedStates[currentStateIndex].state,
false false
); );
@ -338,7 +487,7 @@ export function liftReducerWith(
if (!options.pauseActionType || nextActionId === 1) { if (!options.pauseActionType || nextActionId === 1) {
return { return {
monitorState, monitorState,
actionsById: { 0: liftAction(INIT_ACTION) }, actionsById: { 0: liftAction<A>(INIT_ACTION as A) },
nextActionId: 1, nextActionId: 1,
stagedActionIds: [0], stagedActionIds: [0],
skippedActionIds: [], skippedActionIds: [],
@ -360,7 +509,9 @@ export function liftReducerWith(
monitorState, monitorState,
actionsById: { actionsById: {
...actionsById, ...actionsById,
[nextActionId - 1]: liftAction({ type: options.pauseActionType }) [nextActionId - 1]: liftAction<A>({
type: options.pauseActionType
} as A)
}, },
nextActionId, nextActionId,
stagedActionIds, stagedActionIds,
@ -376,7 +527,7 @@ export function liftReducerWith(
}; };
} }
// By default, agressively recompute every state whatever happens. // By default, aggressively recompute every state whatever happens.
// This has O(n) performance, so we'll override this to a sensible // This has O(n) performance, so we'll override this to a sensible
// value whenever we feel like we don't have to recompute the states. // value whenever we feel like we don't have to recompute the states.
let minInvalidatedStateIndex = 0; let minInvalidatedStateIndex = 0;
@ -388,13 +539,13 @@ export function liftReducerWith(
if (/^@@redux\/(INIT|REPLACE)/.test(liftedAction.type)) { if (/^@@redux\/(INIT|REPLACE)/.test(liftedAction.type)) {
if (options.shouldHotReload === false) { if (options.shouldHotReload === false) {
actionsById = { 0: liftAction(INIT_ACTION) }; actionsById = { 0: liftAction<A>(INIT_ACTION as A) };
nextActionId = 1; nextActionId = 1;
stagedActionIds = [0]; stagedActionIds = [0];
skippedActionIds = []; skippedActionIds = [];
committedState = committedState =
computedStates.length === 0 computedStates.length === 0
? initialCommittedState ? (initialCommittedState as S)
: computedStates[currentStateIndex].state; : computedStates[currentStateIndex].state;
currentStateIndex = 0; currentStateIndex = 0;
computedStates = []; computedStates = [];
@ -405,7 +556,7 @@ export function liftReducerWith(
if (maxAge && stagedActionIds.length > maxAge) { if (maxAge && stagedActionIds.length > maxAge) {
// States must be recomputed before committing excess. // States must be recomputed before committing excess.
computedStates = recomputeStates( computedStates = recomputeStates<S, A>(
computedStates, computedStates,
minInvalidatedStateIndex, minInvalidatedStateIndex,
reducer, reducer,
@ -446,11 +597,11 @@ export function liftReducerWith(
} }
case ActionTypes.RESET: { case ActionTypes.RESET: {
// Get back to the state the store was created with. // Get back to the state the store was created with.
actionsById = { 0: liftAction(INIT_ACTION) }; actionsById = { 0: liftAction<A>(INIT_ACTION as A) };
nextActionId = 1; nextActionId = 1;
stagedActionIds = [0]; stagedActionIds = [0];
skippedActionIds = []; skippedActionIds = [];
committedState = initialCommittedState; committedState = initialCommittedState as S;
currentStateIndex = 0; currentStateIndex = 0;
computedStates = []; computedStates = [];
break; break;
@ -458,7 +609,7 @@ export function liftReducerWith(
case ActionTypes.COMMIT: { case ActionTypes.COMMIT: {
// Consider the last committed state the new starting point. // Consider the last committed state the new starting point.
// Squash any staged actions into a single committed state. // Squash any staged actions into a single committed state.
actionsById = { 0: liftAction(INIT_ACTION) }; actionsById = { 0: liftAction<A>(INIT_ACTION as A) };
nextActionId = 1; nextActionId = 1;
stagedActionIds = [0]; stagedActionIds = [0];
skippedActionIds = []; skippedActionIds = [];
@ -470,7 +621,7 @@ export function liftReducerWith(
case ActionTypes.ROLLBACK: { case ActionTypes.ROLLBACK: {
// Forget about any staged actions. // Forget about any staged actions.
// Start again from the last committed state. // Start again from the last committed state.
actionsById = { 0: liftAction(INIT_ACTION) }; actionsById = { 0: liftAction<A>(INIT_ACTION as A) };
nextActionId = 1; nextActionId = 1;
stagedActionIds = [0]; stagedActionIds = [0];
skippedActionIds = []; skippedActionIds = [];
@ -571,19 +722,19 @@ export function liftReducerWith(
break; break;
} }
case ActionTypes.IMPORT_STATE: { case ActionTypes.IMPORT_STATE: {
if (Array.isArray(liftedAction.nextLiftedState)) { if (isArray(liftedAction.nextLiftedState)) {
// recompute array of actions // recompute array of actions
actionsById = { 0: liftAction(INIT_ACTION) }; actionsById = { 0: liftAction<A>(INIT_ACTION as A) };
nextActionId = 1; nextActionId = 1;
stagedActionIds = [0]; stagedActionIds = [0];
skippedActionIds = []; skippedActionIds = [];
currentStateIndex = liftedAction.nextLiftedState.length; currentStateIndex = liftedAction.nextLiftedState.length;
computedStates = []; computedStates = [];
committedState = liftedAction.preloadedState; committedState = liftedAction.preloadedState as S;
minInvalidatedStateIndex = 0; minInvalidatedStateIndex = 0;
// iterate through actions // iterate through actions
liftedAction.nextLiftedState.forEach(action => { liftedAction.nextLiftedState.forEach(action => {
actionsById[nextActionId] = liftAction( actionsById[nextActionId] = liftAction<A>(
action, action,
options.trace || options.shouldIncludeCallstack options.trace || options.shouldIncludeCallstack
); );
@ -621,7 +772,7 @@ export function liftReducerWith(
return computePausedAction(true); return computePausedAction(true);
} }
// Commit when unpausing // Commit when unpausing
actionsById = { 0: liftAction(INIT_ACTION) }; actionsById = { 0: liftAction<A>(INIT_ACTION as A) };
nextActionId = 1; nextActionId = 1;
stagedActionIds = [0]; stagedActionIds = [0];
skippedActionIds = []; skippedActionIds = [];
@ -668,34 +819,64 @@ export function liftReducerWith(
/** /**
* Provides an app's view into the state of the lifted store. * Provides an app's view into the state of the lifted store.
*/ */
export function unliftState(liftedState) { export function unliftState<S, A extends Action<unknown>, NextStateExt>(
liftedState: LiftedState<S, A> & NextStateExt
) {
const { computedStates, currentStateIndex } = liftedState; const { computedStates, currentStateIndex } = liftedState;
const { state } = computedStates[currentStateIndex]; const { state } = computedStates[currentStateIndex];
return state; return state;
} }
export type LiftedStore<S, A extends Action<unknown>> = Store<
LiftedState<S, A>,
LiftedAction<S, A>
>;
export type InstrumentExt<S, A extends Action<unknown>> = {
liftedStore: LiftedStore<S, A>;
};
export type EnhancedStore<S, A extends Action<unknown>> = Store<S, A> &
InstrumentExt<S, A>;
/** /**
* Provides an app's view into the lifted store. * Provides an app's view into the lifted store.
*/ */
export function unliftStore(liftedStore, liftReducer, options) { export function unliftStore<
let lastDefinedState; S,
A extends Action<unknown>,
NextExt,
NextStateExt
>(
liftedStore: Store<LiftedState<S, A> & NextStateExt, LiftedAction<S, A>> &
NextExt,
liftReducer: (
r: Reducer<S, A>
) => Reducer<LiftedState<S, A>, LiftedAction<S, A>>,
options: Options<S, A>
): Store<S & NextStateExt, A> &
NextExt & {
liftedStore: Store<LiftedState<S, A> & NextStateExt, LiftedAction<S, A>>;
} {
let lastDefinedState: S & NextStateExt;
const trace = options.trace || options.shouldIncludeCallstack; const trace = options.trace || options.shouldIncludeCallstack;
const traceLimit = options.traceLimit || 10; const traceLimit = options.traceLimit || 10;
function getState() { function getState(): S & NextStateExt {
const state = unliftState(liftedStore.getState()); const state = unliftState<S, A, NextStateExt>(liftedStore.getState()) as S &
NextStateExt;
if (state !== undefined) { if (state !== undefined) {
lastDefinedState = state; lastDefinedState = state;
} }
return lastDefinedState; return lastDefinedState;
} }
function dispatch(action) { function dispatch<T extends A>(action: T): T {
liftedStore.dispatch(liftAction(action, trace, traceLimit, dispatch)); liftedStore.dispatch(liftAction<A>(action, trace, traceLimit, dispatch));
return action; return action;
} }
return { return ({
...liftedStore, ...liftedStore,
liftedStore, liftedStore,
@ -704,13 +885,20 @@ export function unliftStore(liftedStore, liftReducer, options) {
getState, getState,
replaceReducer(nextReducer) { replaceReducer(nextReducer: Reducer<S & NextStateExt, A>) {
liftedStore.replaceReducer(liftReducer(nextReducer)); liftedStore.replaceReducer(
(liftReducer(
(nextReducer as unknown) as Reducer<S, A>
) as unknown) as Reducer<
LiftedState<S, A> & NextStateExt,
LiftedAction<S, A>
>
);
}, },
[$$observable]() { [$$observable](): Observable<S> {
return { return {
...liftedStore[$$observable](), ...(liftedStore as any)[$$observable](),
subscribe(observer) { subscribe(observer) {
if (typeof observer !== 'object') { if (typeof observer !== 'object') {
throw new TypeError('Expected the observer to be an object.'); throw new TypeError('Expected the observer to be an object.');
@ -725,16 +913,43 @@ export function unliftStore(liftedStore, liftReducer, options) {
observeState(); observeState();
const unsubscribe = liftedStore.subscribe(observeState); const unsubscribe = liftedStore.subscribe(observeState);
return { unsubscribe }; return { unsubscribe };
},
[$$observable]() {
return this;
} }
}; };
} }
} as unknown) as Store<S & NextStateExt, A> &
NextExt & {
liftedStore: Store<LiftedState<S, A> & NextStateExt, LiftedAction<S, A>>;
}; };
} }
export interface Options<S, A extends Action<unknown>> {
maxAge?:
| number
| ((
currentLiftedAction: LiftedAction<S, A>,
previousLiftedState: LiftedState<S, A> | undefined
) => number);
shouldCatchErrors?: boolean;
shouldRecordChanges?: boolean;
pauseActionType?: unknown;
shouldStartLocked?: boolean;
shouldHotReload?: boolean;
trace?: boolean | ((action: A) => string | undefined);
traceLimit?: number;
shouldIncludeCallstack?: boolean;
}
/** /**
* Redux instrumentation store enhancer. * Redux instrumentation store enhancer.
*/ */
export default function instrument(monitorReducer = () => null, options = {}) { export default function instrument<OptionsS, OptionsA extends Action<unknown>>(
monitorReducer: Reducer<unknown, Action<unknown>> = () => null,
options: Options<OptionsS, OptionsA> = {}
): StoreEnhancer<InstrumentExt<any, any>> {
if (typeof options.maxAge === 'number' && options.maxAge < 2) { if (typeof options.maxAge === 'number' && options.maxAge < 2) {
throw new Error( throw new Error(
'DevTools.instrument({ maxAge }) option, if specified, ' + 'DevTools.instrument({ maxAge }) option, if specified, ' +
@ -742,10 +957,15 @@ export default function instrument(monitorReducer = () => null, options = {}) {
); );
} }
return createStore => (reducer, initialState, enhancer) => { return <NextExt, NextStateExt>(
function liftReducer(r) { createStore: StoreEnhancerStoreCreator<NextExt, NextStateExt>
) => <S, A extends Action<unknown>>(
reducer: Reducer<S, A>,
initialState?: PreloadedState<S>
) => {
function liftReducer(r: Reducer<S, A>) {
if (typeof r !== 'function') { if (typeof r !== 'function') {
if (r && typeof r.default === 'function') { if (r && typeof (r as { default: unknown }).default === 'function') {
throw new Error( throw new Error(
'Expected the reducer to be a function. ' + 'Expected the reducer to be a function. ' +
'Instead got an object with a "default" field. ' + 'Instead got an object with a "default" field. ' +
@ -755,17 +975,34 @@ export default function instrument(monitorReducer = () => null, options = {}) {
} }
throw new Error('Expected the reducer to be a function.'); throw new Error('Expected the reducer to be a function.');
} }
return liftReducerWith(r, initialState, monitorReducer, options); return liftReducerWith<S, A>(
r,
initialState,
monitorReducer,
(options as unknown) as Options<S, A>
);
} }
const liftedStore = createStore(liftReducer(reducer), enhancer); const liftedStore = createStore(liftReducer(reducer));
if (liftedStore.liftedStore) { if (
(liftedStore as Store<
LiftedState<S, A> & NextStateExt,
LiftedAction<S, A>
> &
NextExt & {
liftedStore: Store<LiftedState<S, A>, LiftedAction<S, A>>;
}).liftedStore
) {
throw new Error( throw new Error(
'DevTools instrumentation should not be applied more than once. ' + 'DevTools instrumentation should not be applied more than once. ' +
'Check your store configuration.' 'Check your store configuration.'
); );
} }
return unliftStore(liftedStore, liftReducer, options); return unliftStore<S, A, NextExt, NextStateExt>(
liftedStore,
liftReducer,
(options as unknown) as Options<S, A>
);
}; };
} }

View File

@ -0,0 +1,4 @@
{
"extends": "../../../tsconfig.base.json",
"include": ["../src", "."]
}

View File

@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "lib"
},
"include": ["src"]
}

View File

@ -2598,6 +2598,24 @@
"@types/istanbul-lib-coverage" "*" "@types/istanbul-lib-coverage" "*"
"@types/istanbul-lib-report" "*" "@types/istanbul-lib-report" "*"
"@types/jest@^25.2.1":
version "25.2.1"
resolved "https://registry.yarnpkg.com/@types/jest/-/jest-25.2.1.tgz#9544cd438607955381c1bdbdb97767a249297db5"
integrity sha512-msra1bCaAeEdkSyA0CZ6gW1ukMIvZ5YoJkdXw/qhQdsuuDlFTcEUrUw8CLCPt2rVRUfXlClVvK2gvPs9IokZaA==
dependencies:
jest-diff "^25.2.1"
pretty-format "^25.2.1"
"@types/json-schema@^7.0.3":
version "7.0.4"
resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.4.tgz#38fd73ddfd9b55abb1e1b2ed578cb55bd7b7d339"
integrity sha512-8+KAKzEvSUdeo+kmqnKrqgeE+LcA0tjYWFY7RPProVYwnqDjukzO+3b6dLD56rYX5TdWejnEOLJYOIeh4CXKuA==
"@types/lodash@^4.2.0":
version "4.14.150"
resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.150.tgz#649fe44684c3f1fcb6164d943c5a61977e8cf0bd"
integrity sha512-kMNLM5JBcasgYscD9x/Gvr6lTAv2NVgsKtet/hm93qMyf/D1pt+7jeEZklKJKxMVmXjxbRVQQGfqDSfipYCO6w==
"@types/minimatch@*": "@types/minimatch@*":
version "3.0.3" version "3.0.3"
resolved "https://registry.yarnpkg.com/@types/minimatch/-/minimatch-3.0.3.tgz#3dca0e3f33b200fc7d1139c0cd96c1268cadfd9d" resolved "https://registry.yarnpkg.com/@types/minimatch/-/minimatch-3.0.3.tgz#3dca0e3f33b200fc7d1139c0cd96c1268cadfd9d"
@ -14091,7 +14109,7 @@ redux@^3.0.5, redux@^3.6.0:
loose-envify "^1.1.0" loose-envify "^1.1.0"
symbol-observable "^1.0.3" symbol-observable "^1.0.3"
redux@^4.0.0, redux@^4.0.1: redux@^4.0.0, redux@^4.0.1, redux@^4.0.5:
version "4.0.5" version "4.0.5"
resolved "https://registry.yarnpkg.com/redux/-/redux-4.0.5.tgz#4db5de5816e17891de8a80c424232d06f051d93f" resolved "https://registry.yarnpkg.com/redux/-/redux-4.0.5.tgz#4db5de5816e17891de8a80c424232d06f051d93f"
integrity sha512-VSz1uMAH24DM6MF72vcojpYPtrTUu3ByVWfPL1nPfVRb5mZVTve5GnNCUV53QM/BZ66xfWrm0CTWoM+Xlz8V1w== integrity sha512-VSz1uMAH24DM6MF72vcojpYPtrTUu3ByVWfPL1nPfVRb5mZVTve5GnNCUV53QM/BZ66xfWrm0CTWoM+Xlz8V1w==