Files
react-native/packages/dev-middleware
Cedric van Putten 3f41fb5d5b feature(dev-middleware): add custom message handlers to extend CDP capabilities (#43291)
Summary:
This is a proposal for the `react-native/dev-middleware` package, to allow implementers to extend the CDP capabilities of the `InspectorProxy`. It's unfortunately needed until we can move to the native Hermes CDP layer.

At Expo, we extend the CDP capabilities of this `InspectorProxy` by injecting functionality on the device level. This proposed API does the same, but without having to overwrite internal functions of both the `InspectorProxy` and `InspectorDevice`.

A good example of this is the network inspector's capabilities. This currently works through the inspection proxy, and roughly like:
- Handle any incoming `Expo(Network.receivedResponseBody)` from the _**device**_, store it, and stop event from propagating
- Handle the incoming `Network.getResponseBody` from the _**debugger**_, return the data, and stop event from propagating.

This API brings back that capability in a more structured way.

## API:

```ts
import { createDevMiddleware } from 'react-native/dev-middleware';

const { middleware, websocketEndpoints } = createDevMiddleware({
  unstable_customInspectorMessageHandler: ({ page, deviceInfo, debuggerInfo }) => {
    // Do not enable handler for page other than "SOMETHING", or for vscode debugging
    // Can also include `page.capabilities` to determine if handler is required
    if (page.title !== 'SOMETHING' || debuggerInfo.userAgent?.includes('vscode')) {
      return null;
    }

    return {
      handleDeviceMessage(message) {
        if (message.type === 'CDP_MESSAGE') {
          // Do something and stop message from propagating with return `true`
          return true;
        }
      },
      handleDebuggerMessage(message) {
        if (message.type === 'CDP_MESSAGE') {
          // Do something and stop message from propagating with return `true`
          return true;
        }
      },
    };
  },
});
```

## Changelog:

<!-- Help reviewers and the release process by writing your own changelog entry.

Pick one each for the category and type tags:

For more details, see:
https://reactnative.dev/contributing/changelogs-in-pull-requests
-->

[GENERAL] [ADDED] - Add inspector proxy device message middleware API

Pull Request resolved: https://github.com/facebook/react-native/pull/43291

Test Plan: See added tests and code above

Reviewed By: huntie

Differential Revision: D54804503

Pulled By: motiz88

fbshipit-source-id: ae918dcd5b7e76d3fb31db4c84717567ae60fa96
2024-03-12 09:58:51 -07:00
..

@react-native/dev-middleware

npm package

Dev server middleware supporting core React Native development features. This package is preconfigured in all React Native projects.

Usage

Middleware can be attached to a dev server (e.g. Metro) using the createDevMiddleware API.

import { createDevMiddleware } from '@react-native/dev-middleware';

function myDevServerImpl(args) {
  ...

  const {middleware, websocketEndpoints} = createDevMiddleware({
    projectRoot: metroConfig.projectRoot,
    serverBaseUrl: `http://${args.host}:${args.port}`,
    logger,
  });

  await Metro.runServer(metroConfig, {
    host: args.host,
    ...,
    unstable_extraMiddleware: [
      middleware,
      // Optionally extend with additional HTTP middleware
    ],
    websocketEndpoints: {
      ...websocketEndpoints,
      // Optionally extend with additional WebSocket endpoints
    },
  });
}

Included middleware

@react-native/dev-middleware is designed for integrators such as @expo/dev-server and @react-native/community-cli-plugin. It provides a common default implementation for core React Native dev server responsibilities.

We intend to keep this to a narrow set of functionality, based around:

  • Debugging — The Chrome DevTools protocol (CDP) endpoints supported by React Native, including the Inspector Proxy, which facilitates connections with multiple devices.
  • Dev actions — Endpoints implementing core Dev Menu actions, e.g. reloading the app, opening the debugger frontend.

HTTP endpoints

DevMiddlewareAPI.middleware

These are exposed as a connect middleware handler, assignable to Metro.runServer or other compatible HTTP servers.

GET /json/list, /json (CDP)

Returns the list of available WebSocket targets for all connected React Native app sessions.

GET /json/version (CDP)

Returns version metadata used by Chrome DevTools.

GET /debugger-frontend

Subpaths of this endpoint are reserved to serve the JavaScript debugger frontend.

POST /open-debugger

Open the JavaScript debugger for a given CDP target (direct Hermes debugging).

Example
curl -X POST 'http://localhost:8081/open-debugger?appId=com.meta.RNTester'

WebSocket endpoints

DevMiddlewareAPI.websocketEndpoints

/inspector/device

WebSocket handler for registering device connections.

/inspector/debug

WebSocket handler that proxies CDP messages to/from the corresponding device.

Contributing

Changes to this package can be made locally and tested against the rn-tester app, per the Contributing guide. During development, this package is automatically run from source with no build step.