Refactor serverBaseUrl from string to URL object (#55285)

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

Changelog: [GENERAL] [CHANGED] - `createDevMiddleware` now accepts `string | URL` for `serverBaseUrl`

Replaces the serverBaseUrl string type with a native URL object across the Metro CLI and Gateway packages.

This change improves type safety and makes URL manipulation more robust by leveraging the built-in URL API instead of string concatenation.

The public createDevMiddleware API has been updated to accept either a string or URL for the serverBaseUrl option.
Internally within the dev-middleware package, the internal APIs (InspectorProxy, openDebuggerMiddleware, getDevToolsFrontendUrl) use URL objects instead of strings.
https://www.npmjs.com/package/react-native/dev-middleware

Reviewed By: vzaidman

Differential Revision: D90987090

fbshipit-source-id: ec5b8faa4ed5c24b489c3d63f7b6030073be5403
This commit is contained in:
Emily Brown authored and meta-codesync[bot] committed 2026-02-06 07:08:58 -08:00
1 parent 678f7a9cfb
commit 10709f427d
9 files changed
+89 -25

No files matched your search

+1 -1
View File
@@ -16,7 +16,7 @@ function myDevServerImpl(args) {
const {middleware, websocketEndpoints} = createDevMiddleware({
projectRoot: metroConfig.projectRoot,
serverBaseUrl: `http://${args.host}:${args.port}`,
serverBaseUrl: new URL(`http://${args.host}:${args.port}`),
logger,
});
@@ -13,7 +13,7 @@ import getDevToolsFrontendUrl from '../utils/getDevToolsFrontendUrl';
describe('getDevToolsFrontendUrl', () => {
const webSocketDebuggerUrl =
'ws://localhost:8081/inspector/debug?device=1a9372c&page=-1';
const devServerUrl = 'http://localhost:8081';
const devServerUrl = new URL('http://localhost:8081');
const experiments = {
enableNetworkInspector: false,
@@ -13,6 +13,7 @@ import type {BrowserLauncher} from './types/BrowserLauncher';
import type {EventReporter, ReportableEvent} from './types/EventReporter';
import type {Experiments, ExperimentsConfig} from './types/Experiments';
import type {Logger} from './types/Logger';
import type {ReadonlyURL} from './types/ReadonlyURL';
import type {NextHandleFunction} from 'connect';
import InspectorProxy from './inspector-proxy/InspectorProxy';
@@ -28,7 +29,7 @@ type Options = Readonly<{
* The base URL to the dev server, as reachable from the machine on which
* dev-middleware is hosted. Typically `http://localhost:${metroPort}`.
*/
serverBaseUrl: string,
serverBaseUrl: string | ReadonlyURL,
logger?: Logger,
@@ -85,6 +86,8 @@ export default function createDevMiddleware({
unstable_customInspectorMessageHandler,
unstable_trackInspectorProxyEventLoopPerf = false,
}: Options): DevMiddlewareAPI {
const normalizedServerBaseUrl: ReadonlyURL = new URL(serverBaseUrl);
const experiments = getExperiments(experimentConfig);
const eventReporter = createWrappedEventReporter(
unstable_eventReporter,
@@ -93,7 +96,7 @@ export default function createDevMiddleware({
);
const inspectorProxy = new InspectorProxy(
serverBaseUrl,
normalizedServerBaseUrl,
eventReporter,
experiments,
logger,
@@ -105,7 +108,7 @@ export default function createDevMiddleware({
.use(
'/open-debugger',
openDebuggerMiddleware({
serverBaseUrl,
serverBaseUrl: normalizedServerBaseUrl,
inspectorProxy,
browserLauncher: unstable_browserLauncher,
eventReporter,
@@ -19,6 +19,7 @@ export type {
CreateCustomMessageHandlerFn,
} from './inspector-proxy/CustomMessageHandler';
export type {Logger} from './types/Logger';
export type {ReadonlyURL} from './types/ReadonlyURL';
export {default as unstable_DefaultBrowserLauncher} from './utils/DefaultBrowserLauncher';
export {default as createDevMiddleware} from './createDevMiddleware';
@@ -10,6 +10,7 @@
import type {EventReporter} from '../types/EventReporter';
import type {Experiments} from '../types/Experiments';
import type {ReadonlyURL} from '../types/ReadonlyURL';
import type {
CDPClientMessage,
CDPRequest,
@@ -63,7 +64,7 @@ type DebuggerConnection = {
pageId: string,
userAgent: string | null,
customHandler: ?CustomMessageHandler,
debuggerRelativeBaseUrl: URL,
debuggerRelativeBaseUrl: ReadonlyURL,
// Session ID assigned by the proxy for multi-debugger support
sessionId: string,
};
@@ -77,8 +78,8 @@ export type DeviceOptions = Readonly<{
socket: WS,
eventReporter: ?EventReporter,
createMessageMiddleware: ?CreateCustomMessageHandlerFn,
deviceRelativeBaseUrl: URL,
serverRelativeBaseUrl: URL,
deviceRelativeBaseUrl: ReadonlyURL,
serverRelativeBaseUrl: ReadonlyURL,
isProfilingBuild: boolean,
experiments: Experiments,
}>;
@@ -129,10 +130,10 @@ export default class Device {
// A base HTTP(S) URL to this server, reachable from the device. Derived from
// the http request that created the connection.
#deviceRelativeBaseUrl: URL;
#deviceRelativeBaseUrl: ReadonlyURL;
// A base HTTP(S) URL to the server, relative to this server.
#serverRelativeBaseUrl: URL;
#serverRelativeBaseUrl: ReadonlyURL;
// Logging reporting batches of cdp messages
#cdpDebugLogging: CdpDebugLogging;
@@ -339,7 +340,7 @@ export default class Device {
debuggerRelativeBaseUrl,
userAgent,
}: Readonly<{
debuggerRelativeBaseUrl: URL,
debuggerRelativeBaseUrl: ReadonlyURL,
userAgent: string | null,
}>,
) {
@@ -11,6 +11,7 @@
import type {DebuggerSessionIDs, EventReporter} from '../types/EventReporter';
import type {Experiments} from '../types/Experiments';
import type {Logger} from '../types/Logger';
import type {ReadonlyURL} from '../types/ReadonlyURL';
import type {CreateCustomMessageHandlerFn} from './CustomMessageHandler';
import type {DeviceOptions} from './Device';
import type {
@@ -63,7 +64,7 @@ const INTERNAL_ERROR_MESSAGES = {
};
export type GetPageDescriptionsConfig = {
requestorRelativeBaseUrl: URL,
requestorRelativeBaseUrl: ReadonlyURL,
logNoPagesForConnectedDevice?: boolean,
};
@@ -82,7 +83,7 @@ export interface InspectorProxyQueries {
*/
export default class InspectorProxy implements InspectorProxyQueries {
// The base URL to the dev server from the dev-middleware host.
#serverBaseUrl: URL;
#serverBaseUrl: ReadonlyURL;
// Maps device ID to Device instance.
#devices: Map<string, Device>;
@@ -104,14 +105,14 @@ export default class InspectorProxy implements InspectorProxyQueries {
#eventLoopPerfTracker: EventLoopPerfTracker;
constructor(
serverBaseUrl: string,
serverBaseUrl: ReadonlyURL,
eventReporter: ?EventReporter,
experiments: Experiments,
logger?: Logger,
customMessageHandler: ?CreateCustomMessageHandlerFn,
trackEventLoopPerf?: boolean = false,
) {
this.#serverBaseUrl = new URL(serverBaseUrl);
this.#serverBaseUrl = serverBaseUrl;
this.#devices = new Map();
this.#eventReporter = eventReporter;
this.#experiments = experiments;
@@ -244,7 +245,7 @@ export default class InspectorProxy implements InspectorProxyQueries {
deviceId: string,
device: Device,
page: Page,
requestorRelativeBaseUrl: URL,
requestorRelativeBaseUrl: ReadonlyURL,
): PageDescription {
const {host, protocol} = requestorRelativeBaseUrl;
const webSocketScheme = protocol === 'https:' ? 'wss' : 'ws';
@@ -254,7 +255,7 @@ export default class InspectorProxy implements InspectorProxyQueries {
const devtoolsFrontendUrl = getDevToolsFrontendUrl(
this.#experiments,
webSocketDebuggerUrl,
this.#serverBaseUrl.origin,
new URL(this.#serverBaseUrl),
{
relative: true,
useFuseboxEntryPoint: page.capabilities.prefersFuseboxFrontend,
@@ -17,6 +17,7 @@ import type {
import type {EventReporter} from '../types/EventReporter';
import type {Experiments} from '../types/Experiments';
import type {Logger} from '../types/Logger';
import type {ReadonlyURL} from '../types/ReadonlyURL';
import type {NextHandleFunction} from 'connect';
import type {IncomingMessage, ServerResponse} from 'http';
@@ -27,7 +28,7 @@ const LEGACY_SYNTHETIC_PAGE_TITLE =
'React Native Experimental (Improved Chrome Reloads)';
type Options = Readonly<{
serverBaseUrl: string,
serverBaseUrl: ReadonlyURL,
logger?: Logger,
browserLauncher: BrowserLauncher,
eventReporter?: EventReporter,
@@ -88,7 +89,9 @@ export default function openDebuggerMiddleware({
} = Object.fromEntries(searchParams);
const targets = inspectorProxy
.getPageDescriptions({requestorRelativeBaseUrl: new URL(serverBaseUrl)})
.getPageDescriptions({
requestorRelativeBaseUrl: serverBaseUrl,
})
.filter(app => {
const betterReloadingSupport =
app.title === LEGACY_SYNTHETIC_PAGE_TITLE ||
@@ -162,7 +165,7 @@ export default function openDebuggerMiddleware({
const frontendUrl = getDevToolsFrontendUrl(
experiments,
target.webSocketDebuggerUrl,
serverBaseUrl,
new URL(serverBaseUrl),
{
launchId: query.launchId,
telemetryInfo: query.telemetryInfo,
@@ -220,7 +223,7 @@ export default function openDebuggerMiddleware({
Location: getDevToolsFrontendUrl(
experiments,
target.webSocketDebuggerUrl,
serverBaseUrl,
new URL(serverBaseUrl),
{
relative: true,
launchId: query.launchId,
@@ -0,0 +1,54 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
/**
* A readonly view of URLSearchParams that only exposes read operations.
*/
export interface ReadonlyURLSearchParams {
get(name: string): string | null;
getAll(name: string): Array<string>;
has(name: string, value?: string): boolean;
+size: number;
entries(): Iterator<[string, string]>;
keys(): Iterator<string>;
values(): Iterator<string>;
forEach<This>(
callback: (
this: This,
value: string,
name: string,
params: URLSearchParams,
) => mixed,
thisArg: This,
): void;
toString(): string;
@@iterator(): Iterator<[string, string]>;
}
/**
* A readonly view of URL that prevents mutation of URL properties.
* Used for URLs passed between module boundaries.
*/
export interface ReadonlyURL {
+hash: string;
+host: string;
+hostname: string;
+href: string;
+origin: string;
+password: string;
+pathname: string;
+port: string;
+protocol: string;
+search: string;
+searchParams: ReadonlyURLSearchParams;
+username: string;
toString(): string;
toJSON(): string;
}
@@ -9,6 +9,7 @@
*/
import type {Experiments} from '../types/Experiments';
import type {ReadonlyURL} from '../types/ReadonlyURL';
/**
* Get the DevTools frontend URL to debug a given React Native CDP target.
@@ -16,7 +17,7 @@ import type {Experiments} from '../types/Experiments';
export default function getDevToolsFrontendUrl(
experiments: Experiments,
webSocketDebuggerUrl: string,
devServerUrl: string,
devServerUrl: ReadonlyURL,
options?: Readonly<{
relative?: boolean,
launchId?: string,
@@ -33,7 +34,7 @@ export default function getDevToolsFrontendUrl(
});
const appUrl =
(options?.relative === true ? '' : devServerUrl) +
(options?.relative === true ? '' : devServerUrl.origin) +
'/debugger-frontend/' +
(options?.useFuseboxEntryPoint === true
? 'rn_fusebox.html'
@@ -67,13 +68,13 @@ function getWsParam({
devServerUrl,
}: Readonly<{
webSocketDebuggerUrl: string,
devServerUrl: string,
devServerUrl: ReadonlyURL,
}>): {
key: string,
value: string,
} {
const wsUrl = new URL(webSocketDebuggerUrl);
const serverHost = new URL(devServerUrl).host;
const serverHost = devServerUrl.host;
let value;
if (wsUrl.host === serverHost) {
// Use a path-absolute (host-relative) URL if the WS server and frontend