Skip to content

Commit

Permalink
Add @redux-devtools/remote (#928)
Browse files Browse the repository at this point in the history
  • Loading branch information
Methuselah96 authored Oct 28, 2021
1 parent d807663 commit 9a130ce
Show file tree
Hide file tree
Showing 114 changed files with 5,304 additions and 40 deletions.
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ coverage
node_modules
__snapshots__
.yarn/*
storybook-static
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ dev
.yarn/*
.pnp.*
**/demo/public/**
storybook-static
23 changes: 1 addition & 22 deletions extension/src/app/api/filters.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import mapValues from 'lodash/mapValues';
import { Config } from '../../browser/extension/inject/pageScript';
import { Action } from 'redux';
import { LiftedState, PerformAction } from '@redux-devtools/instrument';
import { LocalFilter } from '@redux-devtools/utils/lib/filters';

export type FilterStateValue =
| 'DO_NOT_FILTER'
Expand All @@ -14,27 +14,6 @@ export const FilterState: { [K in FilterStateValue]: FilterStateValue } = {
ALLOWLIST_SPECIFIC: 'ALLOWLIST_SPECIFIC',
};

function isArray(arg: unknown): arg is readonly unknown[] {
return Array.isArray(arg);
}

interface LocalFilter {
readonly allowlist: string | undefined;
readonly denylist: string | undefined;
}

export function getLocalFilter(config: Config): LocalFilter | undefined {
const denylist = config.actionsDenylist ?? config.actionsBlacklist;
const allowlist = config.actionsAllowlist ?? config.actionsWhitelist;
if (denylist || allowlist) {
return {
allowlist: isArray(allowlist) ? allowlist.join('|') : allowlist,
denylist: isArray(denylist) ? denylist.join('|') : denylist,
};
}
return undefined;
}

export const noFiltersApplied = (localFilter: LocalFilter | undefined) =>
// !predicate &&
!localFilter &&
Expand Down
3 changes: 2 additions & 1 deletion extension/src/app/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import jsan, { Options } from 'jsan';
import throttle from 'lodash/throttle';
import serializeImmutable from '@redux-devtools/serialize/lib/immutable/serialize';
import { getActionsArray } from '@redux-devtools/utils';
import { getLocalFilter, isFiltered, PartialLiftedState } from './filters';
import { getLocalFilter } from '@redux-devtools/utils/lib/filters';
import { isFiltered, PartialLiftedState } from './filters';
import importState from './importState';
import generateId from './generateInstanceId';
import { Config } from '../../browser/extension/inject/pageScript';
Expand Down
2 changes: 1 addition & 1 deletion extension/src/browser/extension/inject/pageScript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import { isAllowed, Options } from '../options/syncOptions';
import Monitor from '../../../app/service/Monitor';
import {
noFiltersApplied,
getLocalFilter,
isFiltered,
filterState,
startingFrom,
Expand Down Expand Up @@ -52,6 +51,7 @@ import {
} from '@redux-devtools/app/lib/actions';
import { ContentScriptToPageScriptMessage } from './contentScript';
import { Features } from '@redux-devtools/app/lib/reducers/instances';
import { getLocalFilter } from '@redux-devtools/utils/lib/filters';

type EnhancedStoreWithInitialDispatch<
S,
Expand Down
3 changes: 3 additions & 0 deletions packages/redux-devtools-remote/.babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"presets": ["@babel/preset-env", "@babel/preset-typescript"]
}
2 changes: 2 additions & 0 deletions packages/redux-devtools-remote/.eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
examples
lib
7 changes: 7 additions & 0 deletions packages/redux-devtools-remote/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
extends: '../../eslintrc.ts.base.json',
parserOptions: {
tsconfigRootDir: __dirname,
project: ['./tsconfig.json'],
},
};
21 changes: 21 additions & 0 deletions packages/redux-devtools-remote/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2015 Mihail Diordiev

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.
199 changes: 199 additions & 0 deletions packages/redux-devtools-remote/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
# Remote Redux DevTools

![Demo](demo.gif)

Use [Redux DevTools](https://github.com/reduxjs/redux-devtools) remotely for React Native, hybrid, desktop and server side Redux apps.

### Installation

```
yarn add @redux-devtools/remote
```

### Usage

There are 2 ways of usage depending if you're using other store enhancers (middlewares) or not.

#### Add DevTools enhancer to your store

If you have a basic [store](http://redux.js.org/docs/api/createStore.html) as described in the official [redux-docs](http://redux.js.org/index.html), simply replace:

```javascript
import { createStore } from 'redux';
const store = createStore(reducer);
```

with

```javascript
import { createStore } from 'redux';
import devToolsEnhancer from '@redux-devtools/remote';
const store = createStore(reducer, devToolsEnhancer());
// or const store = createStore(reducer, preloadedState, devToolsEnhancer());
```

> Note: passing enhancer as last argument requires redux@>=3.1.0
#### When to use DevTools compose helper

If you setup your store with [middlewares and enhancers](http://redux.js.org/docs/api/applyMiddleware.html) like [redux-saga](https://github.com/redux-saga/redux-saga) and similar, it is crucial to use `composeWithDevTools` export. Otherwise, actions dispatched from Redux DevTools will not flow to your middlewares.

In that case change this:

```javascript
import { createStore, applyMiddleware, compose } from 'redux';

const store = createStore(
reducer,
preloadedState,
compose(
applyMiddleware(...middleware)
// other store enhancers if any
)
);
```

to:

```javascript
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from '@redux-devtools/remote';

const store = createStore(
reducer,
/* preloadedState, */ composeWithDevTools(
applyMiddleware(...middleware)
// other store enhancers if any
)
);
```

or with devTools' options:

```javascript
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from '@redux-devtools/remote';

const composeEnhancers = composeWithDevTools({ realtime: true, port: 8000 });
const store = createStore(
reducer,
/* preloadedState, */ composeEnhancers(
applyMiddleware(...middleware)
// other store enhancers if any
)
);
```

### Enabling

In order not to allow it in production by default, the enhancer will have effect only when `process.env.NODE_ENV === 'development'`.

For Webpack you should add it as following (`webpack.config.dev.js`):

```js
// ...
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
})
],
// ...
```

In case you don't set `NODE_ENV`, you can set `realtime` parameter to `true` or to other global variable to turn it off in production:

```js
const store = createStore(reducer, devToolsEnhancer({ realtime: true }));
```

### Monitoring

Use one of our monitor apps to inspect and dispatch actions:

- [redux-devtools-extension](https://github.com/reduxjs/redux-devtools/tree/main/extension) - Click "Remote" button (or press [`Cmd+Ctrl+Arrow up`](https://github.com/zalmoxisus/redux-devtools-extension#keyboard-shortcuts)) to open remote monitoring.
- [remotedev-rn-debugger](https://github.com/jhen0409/remotedev-rn-debugger) - Used in React Native debugger as a dock monitor.
- [atom-redux-devtools](https://github.com/zalmoxisus/atom-redux-devtools) - Used in Atom editor.
- [redux-dispatch-cli](https://github.com/jhen0409/redux-dispatch-cli) - A CLI tool for Redux remote dispatch.
- [vscode-redux-devtools](https://github.com/jkzing/vscode-redux-devtools) - Used in Visual Studio Code.

Use [@redux-devtools/app](https://github.com/reduxjs/redux-devtools/tree/main/packages/redux-devtools-app) to create your own monitor app.

### Communicate via local server

Use [@redux-devtools/cli](https://github.com/reduxjs/redux-devtools/tree/main/packages/redux-devtools-cli).
You can import it in your `server.js` script and start remotedev server together with your development server:

```js
var reduxDevTools = require('@redux-devtools/cli');
reduxDevTools({ hostname: 'localhost', port: 8000 });
```

See [@redux-devtools/cli](https://github.com/reduxjs/redux-devtools/tree/main/packages/redux-devtools-cli) for more details.
For React Native you can use [remotedev-rn-debugger](https://github.com/jhen0409/remotedev-rn-debugger), which already include `@redux-devtools/cli`.

### Parameters

| Name | Description |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name` | _String_ representing the instance name to be shown on the remote monitor. |
| `realtime` | _Boolean_ specifies whether to allow remote monitoring. By default is `process.env.NODE_ENV === 'development'`. |
| `hostname` | _String_ used to specify host for [@redux-devtools/cli](https://github.com/reduxjs/redux-devtools/tree/main/packages/redux-devtools-cli). If `port` is specified, default value is `localhost`. |
| `port` | _Number_ used to specify host's port for [@redux-devtools/cli](https://github.com/reduxjs/redux-devtools/tree/main/packages/redux-devtools-cli). |
| `secure` | _Boolean_ specifies whether to use `https` protocol for [@redux-devtools/cli](https://github.com/reduxjs/redux-devtools/tree/main/packages/redux-devtools-cli). |
| `maxAge` | _Number_ of maximum allowed actions to be stored on the history tree, the oldest actions are removed once maxAge is reached. Default is `30`. |
| `actionsBlacklist` | _array_ of actions to be hidden in DevTools. Overwrites corresponding global setting in the options page. See the example bellow. |
| `actionsWhitelist` | _array_ of actions to be shown. All other actions will be hidden in DevTools. |
| `actionSanitizer` | _Function_ which takes action object and id number as arguments, and should return action object back. See the example bellow. |
| `stateSanitizer` | _Function_ which takes state object and index as arguments, and should return state object back. See the example bellow. |
| `startOn` | _String_ or _Array of strings_ indicating an action or a list of actions, which should start remote monitoring (when `realtime` is `false`). |
| `stopOn` | _String_ or _Array of strings_ indicating an action or a list of actions, which should stop remote monitoring. |
| `sendOn` | _String_ or _Array of strings_ indicating an action or a list of actions, which should trigger sending the history to the monitor (without starting it). _Note_: when using it, add a `fetch` polyfill if needed. |
| `sendOnError` | _Numeric_ code: `0` - disabled (default), `1` - send all uncaught exception messages, `2` - send only reducers error messages. |
| `sendTo` | _String_ url of the monitor to send the history when `sendOn` is triggered. By default is `${secure ? 'https' : 'http'}://${hostname}:${port}`. |
| `actionCreators` | _Array_ or _Object_ of action creators to dispatch remotely. See [the example](https://github.com/zalmoxisus/remote-redux-devtools/commit/b54652930dfd4e057991df8471c343957fd7bff7). |
| `shouldHotReload` | _Boolean_ - if set to `false`, will not recompute the states on hot reloading (or on replacing the reducers). Default to `true`. |
| `shouldRecordChanges` | _Boolean_ - if specified as `false`, it will not record the changes till clicked on "Start recording" button on the monitor app. Default is `true`. |
| `shouldStartLocked` | _Boolean_ - if specified as `true`, it will not allow any non-monitor actions to be dispatched till `lockChanges(false)` is dispatched. Default is `false`. |
| `id` | _String_ to identify the instance when sending the history triggered by `sendOn`. You can use, for example, user id here, to know who sent the data. |
| `suppressConnectErrors` | _Boolean_ - if set to `false`, all socket errors thrown while trying to connect will be printed to the console, regardless of if they've been thrown before. This is primarily for suppressing `SocketProtocolError` errors, which get repeatedly thrown when trying to make a connection. Default is `true`. |

All parameters are optional. You have to provide at least `port` property to use `localhost` instead of `remotedev.io` server.

Example:

```js
export default function configureStore(preloadedState) {
const store = createStore(
reducer,
preloadedState,
devToolsEnhancer({
name: 'Android app',
realtime: true,
hostname: 'localhost',
port: 8000,
maxAge: 30,
actionsBlacklist: ['EFFECT_RESOLVED'],
actionSanitizer: (action) =>
action.type === 'FILE_DOWNLOAD_SUCCESS' && action.data
? { ...action, data: '<<LONG_BLOB>>' }
: action,
stateSanitizer: (state) =>
state.data ? { ...state, data: '<<LONG_BLOB>>' } : state,
})
);
return store;
}
```

### Demo

- [Toggle monitoring](http://zalmoxisus.github.io/monitoring/)

### Examples

- [Web](https://github.com/reduxjs/redux-devtools/tree/main/packages/redux-devtools-remote/examples)
- [React Native](https://github.com/chentsulin/react-native-counter-ios-android)

### License

MIT
Binary file added packages/redux-devtools-remote/demo.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
36 changes: 36 additions & 0 deletions packages/redux-devtools-remote/examples/buildAll.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* Runs an ordered set of commands within each of the build directories.
*/

import fs from 'fs';
import path from 'path';
import { spawnSync } from 'child_process';

var exampleDirs = fs.readdirSync(__dirname).filter((file) => {
return fs.statSync(path.join(__dirname, file)).isDirectory();
});

// Ordering is important here. `npm install` must come first.
var cmdArgs = [
{ cmd: 'npm', args: ['install'] },
{ cmd: 'webpack', args: ['index.js'] },
];

for (const dir of exampleDirs) {
for (const cmdArg of cmdArgs) {
// declare opts in this scope to avoid https://github.com/joyent/node/issues/9158
const opts = {
cwd: path.join(__dirname, dir),
stdio: 'inherit',
};
let result = {};
if (process.platform === 'win32') {
result = spawnSync(cmdArg.cmd + '.cmd', cmdArg.args, opts);
} else {
result = spawnSync(cmdArg.cmd, cmdArg.args, opts);
}
if (result.status !== 0) {
throw new Error('Building examples exited with non-zero');
}
}
}
3 changes: 3 additions & 0 deletions packages/redux-devtools-remote/examples/counter/.babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"presets": ["es2015", "stage-0", "react"]
}
34 changes: 34 additions & 0 deletions packages/redux-devtools-remote/examples/counter/actions/counter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
export const INCREMENT_COUNTER = 'INCREMENT_COUNTER';
export const DECREMENT_COUNTER = 'DECREMENT_COUNTER';

export function increment() {
return {
type: INCREMENT_COUNTER,
};
}

export function decrement() {
return {
type: DECREMENT_COUNTER,
};
}

export function incrementIfOdd() {
return (dispatch, getState) => {
const { counter } = getState();

if (counter % 2 === 0) {
return;
}

dispatch(increment());
};
}

export function incrementAsync(delay = 1000) {
return (dispatch) => {
setTimeout(() => {
dispatch(increment());
}, delay);
};
}
Loading

0 comments on commit 9a130ce

Please sign in to comment.