diff --git a/packages/react-native/Libraries/Core/setUpReactDevTools.js b/packages/react-native/Libraries/Core/setUpReactDevTools.js index e25f0a44c98..9bdf66b3018 100644 --- a/packages/react-native/Libraries/Core/setUpReactDevTools.js +++ b/packages/react-native/Libraries/Core/setUpReactDevTools.js @@ -143,10 +143,7 @@ if (__DEV__) { // Get hostname from development server (packager) const devServer = getDevServer(); const host = devServer.bundleLoadedFromServer - ? devServer.url - .replace(/https?:\/\//, '') - .replace(/\/$/, '') - .split(':')[0] + ? guessHostFromDevServerUrl(devServer.url) : 'localhost'; // Read the optional global variable for backward compatibility. @@ -259,3 +256,23 @@ function readReloadAndProfileConfig( onReloadAndProfileFlagsReset, }; } + +/** + * This is a bad, no good, broken hack to get the host from a dev server URL for the purposes + * of connecting to the legacy React DevTools socket (for the standalone react-devtools package). + * It has too many bugs to list. Please don't use it in new code. + * + * The correct implementation would just be `return new URL(url).host`, but React Native does not + * ship with a spec-compliant `URL` class yet. Alternatively, this can be deleted when we delete + * `connectToWSBasedReactDevToolsFrontend`. + */ +function guessHostFromDevServerUrl(url: string): string { + const hopefullyHostAndPort = url + .replace(/https?:\/\//, '') + .replace(/\/$/, ''); + // IPv6 addresses contain colons, so the split(':') below will return garbage. + if (hopefullyHostAndPort.includes(']')) { + return hopefullyHostAndPort.split(']')[0] + ']'; + } + return hopefullyHostAndPort.split(':')[0]; +}