[react-devtools-cdt-mcp] Throw on import from unsupported environment (#36975)

This add an additional validation that the package is imported in a
browser-like environment. If not, we should be explicit with the user
and throw an error.
This commit is contained in:
Ruslan Lesiutin
2026-07-16 14:42:37 +01:00
committed by GitHub
parent 114e368014
commit 3bbc18fa9c
2 changed files with 38 additions and 1 deletions
@@ -94,6 +94,30 @@ describe('react-devtools-cdt-mcp', () => {
expect(globalThis.__dtmcp).toBeUndefined();
});
it('throws when the auto entry is imported outside an event target', () => {
const originalAddEventListener = globalThis.addEventListener;
const originalRemoveEventListener = globalThis.removeEventListener;
unregister();
delete globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__;
jest.resetModules();
try {
// $FlowFixMe[cannot-write]
globalThis.addEventListener = undefined;
// $FlowFixMe[cannot-write]
globalThis.removeEventListener = undefined;
expect(() => require('../index')).toThrow(
'react-devtools-cdt-mcp must be imported in a browser-like environment',
);
expect(globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__).toBeUndefined();
} finally {
globalThis.addEventListener = originalAddEventListener;
globalThis.removeEventListener = originalRemoveEventListener;
}
});
it('builds a "react" tool group exposing every facade tool', () => {
expect(toolGroup.name).toBe('react');
expect(typeof toolGroup.description).toBe('string');
+14 -1
View File
@@ -11,6 +11,19 @@ import {register} from './DevToolsCdtMcp';
// Side effect: install the facade (before React) and register the React tool
// group for chrome-devtools-mcp. Import this module before React.
register();
if (
typeof window !== 'undefined' &&
typeof window.addEventListener === 'function' &&
typeof window.removeEventListener === 'function'
) {
register();
} else {
// eslint-disable-next-line react-internal/prod-error-codes
throw new Error(
'react-devtools-cdt-mcp must be imported in a browser-like environment ' +
'before React initializes. Use a client-only entry point, or the manual ' +
'entry point for custom targets.',
);
}
export * from './DevToolsCdtMcp';