nDev,
    } = require('internal-test-utils'));
    container = document.createElement('div');
    root = ReactDOMClient.createRoot(container);
    attachedListener = null;
    renderedName = null;
    Inner = class extends React.Component {
      getName() {
        return this.props.name;
      }
      render() {
        attachedListener = this.props.onClick;
        renderedName = this.props.name;
        return <div className={this.props.name} />;
      }
    };
  });

  function runTest(element, expecte

).toBe(expectedClassName);
  }

  it('preserves the name of the class for use in error messages', () => {
    class Foo extends React.Component {}
    expect(Foo.name).toBe('Foo');
  });

  it('throws if no render function is defined', () => {
    class Fo

dTag, expectedClassName) {
    ReactDOM.flushSync(() => root.render(element));
    expect(container.firstChild).not.toBeNull();
    expect(container.firstChild.tagName).toBe(expectedTag);
    expect(container.firstChild.className


ct-dom/client');
    ({act, assertConsoleErrorDev} = require('internal-test-utils'));
    ComponentClass = class extends React.Component {
      render() {
        return React.createElement('div', null, this.props.children);
      }
    };
  });

  it('warns for keys for arrays of elements in rest args', async () => {
    const root = ReactDOMClient.createRoot(document.createElement('div'));
    await act(() =>
      root.render(
        React.createElement(ComponentClass, null, [
          React.createEle

`ComponentClass`. See https://react.dev/link/warning-keys for more information.\n' +
        '    in ComponentClass (at **)',
    ]);
  });

  it('warns for keys for arrays of elements with owner info', async () => {
    class InnerClass extends React.Comp

ment(ComponentClass),
          React.createElement(ComponentClass),
        ]),
      ),
    );
    assertConsoleErrorDev([
      'Each child in a list should have a unique "key" prop.\n\n' +
        'Check the render method of


ct-core
 */

'use strict';

// TODO: All these warnings should become static errors using Flow instead
// of dynamic errors when using JSX with Flow.
let act;
let React;
let ReactDOMClient;
let assertConsoleErrorDev;

describe('ReactJSXElementValidator', () => {
  let Component;
  let RequiredPropComponent;

  beforeEach(() => {
    jest.resetModules();

    ({act, assertConsoleErrorDev} = require('internal-test-utils'));
    React = require('react');
    ReactDOMClient = require('react-dom/client');

    C

props.prop}</span>;
      }
    };
    RequiredPropComponent.displayName = 'RequiredPropComponent';
  });

  it('warns for keys for arrays of elements in children position', async () => {
    const container = document.createElement('div');
    const root

omponent = class extends React.Component {
      render() {
        return <div>{this.props.children}</div>;
      }
    };

    RequiredPropComponent = class extends React.Component {
      render() {
        return <span>{this.


iates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import type {Dispatcher} from 'react-reconciler/src/ReactInternalTypes';
import type {AsyncDispatcher} from 'react-reconciler/src/ReactInternalTypes';
import type {Transition} from './ReactStartTransition';
import type {GestureProvider, GestureOptions} from 'shared/ReactTypes';

import {enableGestureTransition} from 'shared/ReactFeatureFlags';

type onStart

ntDispatcher for Hooks
  A: null | AsyncDispatcher, // ReactCurrentCache for Cache
  T: null | Transition, // ReactCurrentBatchConfig for Transitions
  S: null | onStartTransitionFinish,
  G: null | onStartGestureTransitionFinish,

  // DEV-only

  // Reac

TransitionFinish = (Transition, mixed) => void;
type onStartGestureTransitionFinish = (
  Transition,
  GestureProvider,
  ?GestureOptions,
) => () => void;

export type SharedStateClient = {
  H: null | Dispatcher, // ReactCurre


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import {enableTaint} from 'shared/ReactFeatureFlags';

import getPrototypeOf from 'shared/getPrototypeOf';

import binaryToComparableString from 'shared/binaryToComparableString';

import ReactSharedInternals from './ReactSharedInternalsServer';
const {
  TaintRegistryObjects,
  TaintRegistryValues,
  TaintRegistryByteLengths,
  TaintRegistryPendingRequests,
} = ReactSharedInternals;

interface Reference {}

nent or Action closure. ' +
  'This would leak it to the client.';

function cleanup(entryValue: string | bigint): void {
  const entry = TaintRegistryValues.get(entryValue);
  if (entry !== undefined) {
    TaintRegistryPendingRequests.forEach(function (r

// This is the shared constructor of all typed arrays.
const TypedArrayConstructor = getPrototypeOf(Uint32Array.prototype).constructor;

const defaultMessage =
  'A tainted value was attempted to be serialized to a Client Compo


import type {
  Wakeable,
  Thenable,
  FulfilledThenable,
  RejectedThenable,
  ReactDebugInfo,
  ReactIOInfo,
} from 'shared/ReactTypes';

import {enableAsyncDebugInfo} from 'shared/ReactFeatureFlags';

import {REACT_LAZY_TYPE} from 'shared/ReactSymbols';

import noop from 'shared/noop';

const Uninitialized = -1;
const Pending = 0;
const Resolved = 1;
const Rejected = 2;

type UninitializedPayload<T> = {
  _status: -1,
  _result: () => Thenable<{default: T, ...}>,
  _ioInfo?: ReactIOInfo, // DEV-only
};

yload = {
  _status: 2,
  _result: mixed,
  _ioInfo?: ReactIOInfo, // DEV-only
};

type Payload<T> =
  | UninitializedPayload<T>
  | PendingPayload
  | ResolvedPayload<T>
  | RejectedPayload;

export type LazyComponent<T, P> = {
  $$typeof: symbol | number

type PendingPayload = {
  _status: 0,
  _result: Wakeable,
  _ioInfo?: ReactIOInfo, // DEV-only
};

type ResolvedPayload<T> = {
  _status: 1,
  _result: {default: T, ...},
  _ioInfo?: ReactIOInfo, // DEV-only
};

type RejectedPa


Client = require('react-dom/client');
    ({act, assertConsoleErrorDev} = require('internal-test-utils'));
  });

  // TODO: This behavior creates a runtime dependency on propTypes. We should
  // ensure that this is not required for ES6 classes with Flow.

  // @gate !disableLegacyContext
  it('should filter out context not in contextTypes', async () => {
    class Component extends React.Component {
      render() {
        return <div />;
      }
    }
    Component.contextTypes = {
      foo: PropTypes.

er() {
        return <Component ref={this.childRef} />;
      }
    }
    ComponentInFooBarContext.childContextTypes = {
      foo: PropTypes.string,
      bar: PropTypes.number,
    };

    let instance;
    const container = document.createElement('div'

string,
    };

    class ComponentInFooBarContext extends React.Component {
      childRef = React.createRef();

      getChildContext() {
        return {
          foo: 'abc',
          bar: 123,
        };
      }

      rend


 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.
 *
 * @emails react-core
 */

'use strict';

let React;
let ReactDOM;
let ReactDOMClient;
let assertConsoleErrorDev;

describe('ReactCreateRef', () => {
  beforeEach(() => {
    jest.resetModules();

    React = require('react');
    ReactDOM = require('react-dom');
    ReactDOMClient = require('react-dom/client');
    ({assertConsoleErrorDev} = re

     render() {
        return null;
      }
    }

    const root = ReactDOMClient.createRoot(document.createElement('div'));
    ReactDOM.flushSync(() => {
      root.render(
        <Wrapper>
          <div ref={{}} />
        </Wrapper>,
      );
    }

quire('internal-test-utils'));
  });

  it('should warn in dev if an invalid ref object is provided', () => {
    function Wrapper({children}) {
      return children;
    }

    class ExampleComponent extends React.Component {


 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
 */

export {default as __SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE} from './ReactSharedInternalsServer';

import {forEach, map, count, toArray, only} from './ReactChildren';
import {captureOwnerStack as captureOwnerStackImpl} from './ReactOwnerStack';
import {
  REACT_ACTIVITY_TYPE,
  REACT_FRAGMENT_TYPE,
  REACT_PR

JSXElement';
import {createRef} from './ReactCreateRef';
import {use, useId, useCallback, useDebugValue, useMemo} from './ReactHooks';
import {forwardRef} from './ReactForwardRef';
import {lazy} from './ReactLazy';
import {memo} from './ReactMemo';
import

OFILER_TYPE,
  REACT_STRICT_MODE_TYPE,
  REACT_SUSPENSE_TYPE,
  REACT_SUSPENSE_LIST_TYPE,
  REACT_VIEW_TRANSITION_TYPE,
} from 'shared/ReactSymbols';
import {
  cloneElement,
  createElement,
  isValidElement,
} from './jsx/React


**
 * 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
 */

export interface Reference {}

export type TaintEntry = {
  message: string,
  count: number,
};

export const TaintRegistryObjects: WeakMap<Reference, string> = new WeakMap();
export const TaintRegistryValues: Map<string | bigint, TaintEntry> = new Map();
// Byte lengths of all binary values we've ever seen

emoved from any global caches.
// No future requests can get a handle on it but any ongoing requests can still have
// a handle on it. It's still tainted until that happens.
export type RequestCleanupQueue = Array<string | bigint>;
export const TaintRegist

. We don't both refcounting this.
// We expect to see only a few lengths here such as the length of token.
export const TaintRegistryByteLengths: Set<number> = new Set();

// When a value is finalized, it means that it has been r


ortalContainer = document.createElement('div');

    const simpleChild = ;
    const reactPortal = ReactDOM.createPortal(simpleChild, portalContainer);

    const parentInstance =
{reactPortal}
;
    React.Children.forEach(parentInstance.props.children, callback, context);
    expect(callback).toHaveBeenCalledWith(reactPortal, 0);
    callback.mockClear();
    const mappedChildren = React.Children.map(
      parentInstance.props.children,
      callback,
      context,
    );

k = jest.fn().mockImplementation(function (kid, index) {
      expect(this).toBe(context);
      return kid;
    });

    const simpleKid = <span />;
    const instance = <div>{simpleKid}</div>;
    React.Children.forEach(instance.props.children, callback,

    expect(callback).toHaveBeenCalledWith(reactPortal, 0);
    expect(mappedChildren[0]).toEqual(reactPortal);
  });

  it('should treat single arrayless child as being in array', () => {
    const context = {};
    const callbac


e
// certain that we are testing the runtime behavior, as opposed to the Babel
// transform that we use in our tests configuration.
describe('ReactJSXRuntime', () => {
  beforeEach(() => {
    jest.resetModules();

    React = require('react');
    JSXRuntime = require('react/jsx-runtime');
    JSXDEVRuntime = require('react/jsx-dev-runtime');
    ReactDOMClient = require('react-dom/client');
    ({act, assertConsoleErrorDev} = require('internal-test-utils'));
  });

  it('allows static methods to be called

omeReturnValue';

    const element = JSXRuntime.jsx(StaticMethodComponentClass, {});
    expect(element.type.someStaticMethod()).toBe('someReturnValue');
  });

  it('is indistinguishable from a plain object', () => {
    const element = JSXRuntime.jsx('d

 using the type property', () => {
    class StaticMethodComponentClass extends React.Component {
      render() {
        return JSXRuntime.jsx('div', {});
      }
    }
    StaticMethodComponentClass.someStaticMethod = () => 's


   ({act, assertConsoleErrorDev} = require('internal-test-utils'));

    React = require('react');
    ReactDOMClient = require('react-dom/client');

    // NOTE: We're explicitly not using JSX here. This is intended to test
    // classic JS without JSX.
    ComponentClass = class extends React.Component {
      render() {
        return React.createElement('div');
      }
    };
  });

  it('should clone a DOM component with new props', async () => {
    let div;
    class Grandparent extends React.Compon

        return (
          <div className="parent">
            {React.cloneElement(this.props.child, {className: 'xyz'})}
          </div>
        );
      }
    }

    const root = ReactDOMClient.createRoot(document.createElement('div'));
    await act((

ent {
      render() {
        return (
          <Parent
            child={<div ref={node => (div = node)} className="child" />}
          />
        );
      }
    }
    class Parent extends React.Component {
      render() {


ct-core
 */

'use strict';

import {patchMessageChannel} from '../../../../scripts/jest/patchMessageChannel';

describe('ReactMismatchedVersions-test', () => {
  // Polyfills for test environment
  global.ReadableStream =
    require('web-streams-polyfill/ponyfill/es6').ReadableStream;
  global.TextEncoder = require('util').TextEncoder;

  let React;
  let actualReactVersion;

  beforeEach(() => {
    jest.resetModules();

    patchMessageChannel();

    jest.mock('react', () => {
      const actualReact =

ReactVersion = React.__actualVersion;
  });

  it('importing "react-dom/client" throws if version does not match React version', async () => {
    expect(() => require('react-dom/client')).toThrow(
      'Incompatible React versions: The "react" and "react

jest.requireActual('react');
      return {
        ...actualReact,
        version: '18.0.0-whoa-this-aint-the-right-react',
        __actualVersion: actualReact.version,
      };
    });
    React = require('react');
    actual


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @emails react-core
 */

'use strict';

let React;
let ReactDOMClient;
let ReactFeatureFlags;
let act;
let container;
let assertConsoleErrorDev;

function loadModules({
  enableProfilerTimer = true,
  enableProfilerCommitHooks = true,
  enableProfilerNestedUpdatePhase = true,
} = {}) {
  ReactFeatureFlags = require('shared/ReactFeatureFlags');

  ReactFeatureFlags.enableProfilerTimer = enableProfilerTimer;
  ReactFeatu

;
  const InternalTestUtils = require('internal-test-utils');
  act = InternalTestUtils.act;
  assertConsoleErrorDev = InternalTestUtils.assertConsoleErrorDev;
}

describe('Profiler', () => {
  beforeEach(() => {
    container = document.createElement('div

reFlags.enableProfilerCommitHooks = enableProfilerCommitHooks;
  ReactFeatureFlags.enableProfilerNestedUpdatePhase =
    enableProfilerNestedUpdatePhase;

  React = require('react');
  ReactDOMClient = require('react-dom/client')


]);
    expect(callback).toHaveBeenCalledTimes(1);
  });

  // @gate !__DEV__
  it('does not record times for components outside of Profiler tree', async () => {
    // Mock the Scheduler module so we can track how many times the current
    // time is read
    jest.mock('scheduler', obj => {
      const ActualScheduler = jest.requireActual('scheduler/unstable_mock');
      return {
        ...ActualScheduler,
        unstable_now: function mockUnstableNow() {
          ActualScheduler.log('read current tim

learLog();

    await act(() => {
      ReactNoop.render(
        <div>
          <AdvanceTime />
          <AdvanceTime />
          <AdvanceTime />
          <AdvanceTime />
          <AdvanceTime />
        </div>,
      );
    });

    // Restore origi

e');
          return ActualScheduler.unstable_now();
        },
      };
    });

    jest.resetModules();

    loadModules();

    // Clear yields in case the current time is read during initialization.
    Scheduler.unstable_c


mponent;

var _react = _interopRequireWildcard(require("react"));

var _jsxFileName = "";

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cac

var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, ne

he && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) {


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @emails react-core
 */

'use strict';

let act;
let assertConsoleErrorDev;
let React;
let ReactDOMClient;

describe('ReactPureComponent', () => {
  beforeEach(() => {
    ({act, assertConsoleErrorDev} = require('internal-test-utils'));

    React = require('react');
    ReactDOMClient = require('react-dom/client');
  });

  it('should render', async () => {
    let renders = 0;
    class Component extends React.PureCo

createElement('div');
    const root = ReactDOMClient.createRoot(container);
    let text;
    const componentRef = React.createRef();

    text = ['porcini'];
    await act(() => {
      root.render(<Component ref={componentRef} text={text} />);
    });

mponent {
      constructor() {
        super();
        this.state = {type: 'mushrooms'};
      }
      render() {
        renders++;
        return <div>{this.props.text[0]}</div>;
      }
    }

    const container = document.


iates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @emails react-core
 */

'use strict';

let React;
let ReactTestRenderer;
let act;
let assertConsoleWarnDev;
let useState;
let useTransition;

const SUSPICIOUS_NUMBER_OF_FIBERS_UPDATED = 10;

describe('ReactStartTransition', () => {
  beforeEach(() => {
    jest.resetModules();
    React = require('react');
    ReactTestRenderer = require('react-test-renderer');
    ({

() => {
    const subs = new Set();
    const useUserSpaceSubscription = () => {
      const setState = useState(0)[1];
      subs.add(setState);
    };

    let triggerHookTransition;

    const Component = ({level}) => {
      useUserSpaceSubscription();

act, assertConsoleWarnDev} = require('internal-test-utils'));
    useState = React.useState;
    useTransition = React.useTransition;
  });

  it('Warns if a suspicious number of fibers are updated inside startTransition', async


     <React.StrictMode>
        <Foo />
      </React.StrictMode>,
    );
    assertConsoleErrorDev([
      'Invalid ARIA attribute `ariaTypo`. ' +
        'ARIA attributes follow the pattern aria-* and must be lowercase.\n' +
        '    in div (at **)\n' +
        '    in Foo (at **)',
    ]);
  });

  // @gate __DEV__
  // @gate !disableLegacyMode
  it('should invoke only precommit lifecycle methods twice in legacy roots', async () => {
    let log = [];
    let shouldComponentUpdate = false;
    class

    log.push('constructor');
      }
      componentDidMount() {
        log.push('componentDidMount');
      }
      componentDidUpdate() {
        log.push('componentDidUpdate');
      }
      componentWillUnmount() {
        log.push('componentWillUnmou

ClassComponent extends React.Component {
      state = {};
      static getDerivedStateFromProps() {
        log.push('getDerivedStateFromProps');
        return null;
      }
      constructor(props) {
        super(props);


ource code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @emails react-core
 * @jest-environment node
 */

'use strict';

// NOTE: Intentionally using the dynamic version of the `gate` pragma to opt out
// the negative test behavior. If this test happens to pass when running
// against files source, that's fine. But all we care about is the behavior of
// the build artifacts.
// TODO: The experimental builds have a different version at runtim

for feature detection. Consider
// some other way of handling that.
test('ReactVersion matches package.json', () => {
  if (gate(flags => flags.build && flags.stable && !flags.www)) {
    const React = require('react');
    const packageJSON = require('rea

e than
// the package.json because DevTools uses it


eact');
    ReactNoop = require('react-noop-renderer');

    const InternalTestUtils = require('internal-test-utils');
    waitForAll = InternalTestUtils.waitForAll;
    assertConsoleErrorDev = InternalTestUtils.assertConsoleErrorDev;
  });

  it('should update refs when switching between children', async () => {
    function FunctionComponent({forwardedRef, setRefOnDiv}) {
      return (

First

          <span ref={setRefOnDiv ?

createRef();

    ReactNoop.render(<RefForwardingComponent ref={ref} setRefOnDiv={true} />);
    await waitForAll([]);
    expect(ref.current.type).toBe('div');

    ReactNoop.render(<RefForwardingComponent ref={ref} setRefOnDiv={false} />);
    await wait

null : forwardedRef}>Second</span>
        </section>
      );
    }

    const RefForwardingComponent = React.forwardRef((props, ref) => (
      <FunctionComponent {...props} forwardedRef={ref} />
    ));

    const ref = React.


(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
 */
import {REACT_FRAGMENT_TYPE} from 'shared/ReactSymbols';
import {
  jsxProd,
  jsxProdSignatureRunningInDevWithDynamicChildren,
  jsxProdSignatureRunningInDevWithStaticChildren,
  jsxDEV as _jsxDEV,
} from './ReactJSXElement';

const jsx: any = __DEV__
  ? jsxProdSignatureRunningInDevWithDynamicChildren
  : jsxProd;
// we ma

tage of static children.
// for now we can ship identical prod functions
const jsxs: any = __DEV__
  ? jsxProdSignatureRunningInDevWithStaticChildren
  : jsxProd;

const jsxDEV: any = __DEV__ ? _jsxDEV : undefined;

export {REACT_FRAGMENT_TYPE as Fragment,

y want to special case jsxs internally to take advan


ionString,
} = require('react-devtools-extensions/utils');
const {resolveFeatureFlags} = require('react-devtools-shared/buildUtils');

const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
  console.error('NODE_ENV not set');
  process.exit(1);
}

const builtModulesDir = resolve(
  __dirname,
  '..',
  '..',
  'build',
  'oss-experimental',
);

const __DEV__ = NODE_ENV === 'development';

const DEVTOOLS_VERSION = getVersionString();

const EDITOR_URL = process.env.EDITOR_URL || null;
const LOGGING_URL = p

l.config.js',
  ),
};

module.exports = {
  mode: __DEV__ ? 'development' : 'production',
  devtool: __DEV__ ? 'eval-cheap-module-source-map' : 'source-map',
  target: 'electron-main',
  entry: {
    standalone: './src/standalone.js',
  },
  output: {

rocess.env.LOGGING_URL || null;

const featureFlagTarget =
  process.env.FEATURE_FLAG_TARGET || 'core/standalone-oss';

const babelOptions = {
  configFile: resolve(
    __dirname,
    '..',
    'react-devtools-shared',
    'babe


import {existsSync} from 'fs';
import {basename, join, isAbsolute} from 'path';
import {execSync, spawn} from 'child_process';
import {parse} from 'shell-quote';

function isTerminalEditor(editor: string): boolean {
  switch (editor) {
    case 'vim':
    case 'emacs':
    case 'nano':
      return true;
    default:
      return false;
  }
}

// Map from full process name to binary that starts the process
// We can't just re-use full process name, because it will spawn a new instance
// of the app every ti

xt.app/Contents/MacOS/Sublime Text':
    '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl',
  '/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2':
    '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl',
  '/Appli

me
const COMMON_EDITORS = {
  '/Applications/Atom.app/Contents/MacOS/Atom': 'atom',
  '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta':
    '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta',
  '/Applications/Sublime Te


iates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

/**
 * The implementation of this plugin is based on similar webpack plugin in Angular CLI
 * https://github.com/angular/angular-cli/blob/16d8c552e99bfe65ded9e843e917dbb95eb8ec01/packages/angular_devkit/build_angular/src/tools/webpack/plugins/devtools-ignore-plugin.ts
 * and devtools-ignore-webpack-plugin
 * https://github.com/mondaychen/devtools-ignore-webpack-plugin/

;

class SourceMapIgnoreListPlugin {
  constructor({shouldIgnoreSource}) {
    this.shouldIgnoreSource = shouldIgnoreSource;
  }

  apply(compiler) {
    const {RawSource} = compiler.webpack.sources;

    compiler.hooks.compilation.tap(PLUGIN_NAME, compila

blob/d15274e4d2fdb74f73aa644f14773a5523823999/src/index.ts
 * which both are licensed under MIT
 */

const {Compilation} = require('webpack');

const IGNORE_LIST = 'ignoreList';
const PLUGIN_NAME = 'source-map-ignore-list-plugin'


**
 * 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.
 *
 */

const {resolve} = require('path');

function resolveFeatureFlags(target) {
  let flagsPath;
  switch (target) {
    case 'inline':
    case 'shell':
    case 'fusebox':
      flagsPath = 'DevToolsFeatureFlags.default';
      break;
    case 'core/backend-oss':
    case 'core/standalone-oss':
      flagsPath = 'DevToo

tension-oss';
      break;
    case 'extension-fb':
      flagsPath = 'DevToolsFeatureFlags.extension-fb';
      break;
    default:
      console.error(`Invalid target "${target}"`);
      process.exit(1);
  }

  return resolve(__dirname, 'src/config/', f

lsFeatureFlags.core-oss';
      break;
    case 'core/backend-fb':
    case 'core/standalone-fb':
      flagsPath = 'DevToolsFeatureFlags.core-fb';
      break;
    case 'extension-oss':
      flagsPath = 'DevToolsFeatureFlags.ex


iates.
 *
 * 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
 */

import {__PERFORMANCE_PROFILE__} from './constants';

const supportsUserTiming =
  typeof performance !== 'undefined' &&
  // $FlowFixMe[method-unbinding]
  typeof performance.mark === 'function' &&
  // $FlowFixMe[method-unbinding]
  typeof performance.clearMarks === 'function';

const supportsPerformanceNow =
  // $FlowFixMe[method-unbinding]

ing): void {
  if (supportsUserTiming) {
    performance.mark(markName + '-end');
    performance.measure(markName, markName + '-start', markName + '-end');
    performance.clearMarks(markName + '-start');
    performance.clearMarks(markName + '-end');
  }

  typeof performance !== 'undefined' && typeof performance.now === 'function';

function mark(markName: string): void {
  if (supportsUserTiming) {
    performance.mark(markName + '-start');
  }
}

function measure(markName: str


import {hydrate, fillInPath} from 'react-devtools-shared/src/hydration';
import {backendToFrontendSerializedElementMapper} from 'react-devtools-shared/src/utils';
import Store from 'react-devtools-shared/src/devtools/store';
import TimeoutError from 'react-devtools-shared/src/errors/TimeoutError';
import ElementPollingCancellationError from 'react-devtools-shared/src/errors/ElementPollingCancellationError';

import type {
  InspectedElement as InspectedElementBackend,
  InspectedElementPayload,
  Serialized

ment as InspectedElementFrontend,
  SerializedAsyncInfo as SerializedAsyncInfoFrontend,
} from 'react-devtools-shared/src/frontend/types';
import type {InspectedElementPath} from 'react-devtools-shared/src/frontend/types';

export function clearErrorsAndWa

AsyncInfo as SerializedAsyncInfoBackend,
} from 'react-devtools-shared/src/backend/types';
import type {
  BackendEvents,
  FrontendBridge,
} from 'react-devtools-shared/src/bridge';
import type {
  DehydratedData,
  InspectedEle


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @emails react-core
 */

'use strict';

describe('ReactStrictMode', () => {
  let React;
  let ReactDOMClient;
  let act;

  beforeEach(() => {
    jest.resetModules();
    React = require('react');
    ReactDOMClient = require('react-dom/client');

    act = require('internal-test-utils').act;
  });

  describe('levels', () => {
    let log;

    beforeEach(() => {
      log = [];
    });

    function Component({labe

Effect mount`);
        return () => log.push(`${label}: useLayoutEffect unmount`);
      });

      log.push(`${label}: render`);

      return null;
    }

    it('should default to not strict', async () => {
      await act(() => {
        const contain

l}) {
      React.useEffect(() => {
        log.push(`${label}: useEffect mount`);
        return () => log.push(`${label}: useEffect unmount`);
      });

      React.useLayoutEffect(() => {
        log.push(`${label}: useLayout


ct-core
 */

'use strict';

describe('forwardRef', () => {
  let React;
  let ReactNoop;
  let Scheduler;
  let waitForAll;

  beforeEach(() => {
    jest.resetModules();

    React = require('react');
    ReactNoop = require('react-noop-renderer');
    Scheduler = require('scheduler');

    const InternalTestUtils = require('internal-test-utils');
    waitForAll = InternalTestUtils.waitForAll;
  });

  it('should work without a ref to be forwarded', async () => {
    class Child extends React.Component {

t.forwardRef((props, ref) => (
      <Wrapper {...props} forwardedRef={ref} />
    ));

    ReactNoop.render(<RefForwardingComponent value={123} />);
    await waitForAll([123]);
  });

  it('should forward a ref for a single child', async () => {
    clas

     render() {
        Scheduler.log(this.props.value);
        return null;
      }
    }

    function Wrapper(props) {
      return <Child {...props} ref={props.forwardedRef} />;
    }

    const RefForwardingComponent = Reac


EV__ && console.createTask
    ? // eslint-disable-next-line react-internal/no-production-logging
      console.createTask
    : () => null;

function getTaskName(type) {
  if (type === REACT_FRAGMENT_TYPE) {
    return '<>';
  }
  if (
    typeof type === 'object' &&
    type !== null &&
    type.$$typeof === REACT_LAZY_TYPE
  ) {
    // We don't want to eagerly initialize the initializer in DEV mode so we can't
    // call it to extract the type so we don't know the type of this component.
    return '<..

nternals.A;
    if (dispatcher === null) {
      return null;
    }
    return dispatcher.getOwner();
  }
  return null;
}

// v8 (Chromium, Node.js) defaults to 10
// SpiderMonkey (Firefox) does not support Error.stackTraceLimit
// JSC (Safari) defaults t

.>';
  }
  try {
    const name = getComponentNameFromType(type);
    return name ? '<' + name + '>' : '<...>';
  } catch (x) {
    return '<...>';
  }
}

function getOwner() {
  if (__DEV__) {
    const dispatcher = ReactSharedI


act-devtools-shared/src/backend';
import {__DEBUG__} from 'react-devtools-shared/src/constants';
import setupNativeStyleEditor from 'react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor';
import {
  getDefaultComponentFilters,
  getIsReloadAndProfileSupported,
} from 'react-devtools-shared/src/utils';

import type {BackendBridge} from 'react-devtools-shared/src/bridge';
import type {
  ComponentFilter,
  Wall,
} from 'react-devtools-shared/src/frontend/types';
import type {
  DevToolsH

Options = {
  host?: string,
  nativeStyleEditorValidAttributes?: $ReadOnlyArray<string>,
  path?: string,
  port?: number,
  useHttps?: boolean,
  resolveRNStyle?: ResolveNativeStyle,
  retryConnectionDelay?: number,
  isAppActive?: () => boolean,
  webso

ook,
  DevToolsHookSettings,
  ProfilingSettings,
} from 'react-devtools-shared/src/backend/types';
import type {ResolveNativeStyle} from 'react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor';

type Connect


quire('../react-devtools-extensions/chrome/manifest.json');
const firefoxManifest = require('../react-devtools-extensions/firefox/manifest.json');

const minChromeVersion = parseInt(chromeManifest.minimum_chrome_version, 10);
const minFirefoxVersion = parseInt(
  firefoxManifest.browser_specific_settings.gecko.strict_min_version,
  10,
);
validateVersion(minChromeVersion);
validateVersion(minFirefoxVersion);

function validateVersion(version) {
  if (version > 0 && version < 200) {
    return;
  }
  throw n

nChromeVersion.toString();
    targets.firefox = minFirefoxVersion.toString();

    let additionalTargets = process.env.BABEL_CONFIG_ADDITIONAL_TARGETS;
    if (additionalTargets) {
      additionalTargets = JSON.parse(additionalTargets);
      for (const

ew Error('Suspicious browser version in manifest: ' + version);
}

module.exports = api => {
  const isTest = api.env('test');
  const targets = {};
  if (isTest) {
    targets.node = 'current';
  } else {
    targets.chrome = mi


iates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import type {
  ReactRenderer,
  RendererInterface,
  DevToolsHook,
  RendererID,
  ProfilingSettings,
} from 'react-devtools-shared/src/backend/types';
import type {ComponentFilter} from 'react-devtools-shared/src/frontend/types';

import {attach as attachFlight} from 'react-devtools-shared/src/backend/flight/renderer';
import {attach as attachFiber} from

 the backend that is compatible with all older React versions
function isMatchingRender(version: string): boolean {
  return !hasAssignedBackend(version);
}

export default function attachRenderer(
  hook: DevToolsHook,
  id: RendererID,
  renderer: ReactR

'react-devtools-shared/src/backend/fiber/renderer';
import {attach as attachLegacy} from 'react-devtools-shared/src/backend/legacy/renderer';
import {hasAssignedBackend} from 'react-devtools-shared/src/backend/utils';

// this is


ls-shared/src/devtools/store';
import {getSavedComponentFilters} from 'react-devtools-shared/src/utils';
import {registerDevToolsEventLogger} from 'react-devtools-shared/src/registerDevToolsEventLogger';
import {Server} from 'ws';
import {join} from 'path';
import {readFileSync} from 'fs';
import DevTools from 'react-devtools-shared/src/devtools/views/DevTools';
import {doesFilePathExist, launchEditor} from './editor';
import {
  __DEBUG__,
  LOCAL_STORAGE_DEFAULT_TAB_KEY,
} from 'react-devtools-shared/src/

;

export type StatusTypes = 'server-connected' | 'devtools-connected' | 'error';
export type StatusListener = (message: string, status: StatusTypes) => void;
export type OnDisconnectedCallback = () => void;

let node: HTMLElement = ((null: any): HTMLEleme

constants';
import {localStorageSetItem} from 'react-devtools-shared/src/storage';

import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
import type {ReactFunctionLocation, ReactCallSite} from 'shared/ReactTypes'


ct-core
 * @jest-environment node
 */

'use strict';

describe('ReactProfiler DevTools integration', () => {
  let React;
  let ReactFeatureFlags;
  let ReactTestRenderer;
  let Scheduler;
  let AdvanceTime;
  let hook;
  let waitForAll;
  let waitFor;
  let act;

  beforeEach(() => {
    global.__REACT_DEVTOOLS_GLOBAL_HOOK__ = hook = {
      inject: () => {},
      onCommitFiberRoot: jest.fn((rendererId, root) => {}),
      onCommitFiberUnmount: () => {},
      supportsFiber: true,
    };

    jest.resetMo

est-renderer');

    const InternalTestUtils = require('internal-test-utils');
    waitForAll = InternalTestUtils.waitForAll;
    waitFor = InternalTestUtils.waitFor;
    act = InternalTestUtils.act;

    AdvanceTime = class extends React.Component {

dules();

    ReactFeatureFlags = require('shared/ReactFeatureFlags');
    ReactFeatureFlags.enableProfilerTimer = true;
    Scheduler = require('scheduler');
    React = require('react');
    ReactTestRenderer = require('react-t


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

export const CHROME_WEBSTORE_EXTENSION_ID = 'fmkadmapgofadopljbjfkapdkoienihi';
export const INTERNAL_EXTENSION_ID = 'dnjnjgbfilfphmojnmhliehogmojhclc';
export const LOCAL_EXTENSION_ID = 'ikiahnapldjmdmpkmfhjdjilojjhgcbf';

// Flip this flag to true to enable verbose console debug logging.
export const __DEBUG__ = false;

// Flip this flag to true to enable performance.mark() and performance.measure() timin

ON = 4;
export const TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS = 5;
// Removed `TREE_OPERATION_REMOVE_ROOT`
export const TREE_OPERATION_SET_SUBTREE_MODE = 7;
export const SUSPENSE_TREE_OPERATION_ADD = 8;
export const SUSPENSE_TREE_OPERATION_REMOVE = 9;
expo

gs.
export const __PERFORMANCE_PROFILE__ = false;

export const TREE_OPERATION_ADD = 1;
export const TREE_OPERATION_REMOVE = 2;
export const TREE_OPERATION_REORDER_CHILDREN = 3;
export const TREE_OPERATION_UPDATE_TREE_BASE_DURATI


 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
 */

export default class EventEmitter<Events: Object> {
  listenersMap: Map<string, Array<Function>> = new Map();

  addListener<Event: $Keys<Events>>(
    event: Event,
    listener: (...Events[Event]) => any,
  ): void {
    const listeners = this.listenersMap.get(event);
    if (listeners === undefined) {
      this.listenersMap.set

id {
    const listeners = this.listenersMap.get(event);
    if (listeners !== undefined) {
      if (listeners.length === 1) {
        // No need to clone or try/catch
        const listener = listeners[0];
        listener.apply(null, args);
      } else

(event, [listener]);
    } else {
      const index = listeners.indexOf(listener);
      if (index < 0) {
        listeners.push(listener);
      }
    }
  }

  emit<Event: $Keys<Events>>(event: Event, ...args: Events[Event]): vo


import {__DEBUG__} from 'react-devtools-shared/src/constants';

import type {HooksTree} from 'react-debug-tools/src/ReactDebugHooks';
import type {
  Thenable,
  FulfilledThenable,
  RejectedThenable,
} from 'shared/ReactTypes';
import type {
  Element,
  HookNames,
} from 'react-devtools-shared/src/frontend/types';
import type {FetchFileWithCaching} from 'react-devtools-shared/src/devtools/views/Components/FetchFileWithCachingContext';

import * as React from 'react';

import {withCallbackPerfMeasurements}

-line react-hooks-published/rules-of-hooks
      return React.use(record);
    } catch (x) {
      if (record.status === 'rejected') {
        return null;
      }
      throw x;
    }
  }
  if (record.status === 'fulfilled') {
    return record.value;
  }

 from './PerformanceLoggingUtils';
import {logEvent} from './Logger';

const TIMEOUT = 30000;
function readRecord<T>(record: Thenable<T>): T | null {
  if (typeof React.use === 'function') {
    try {
      // eslint-disable-next


short'): symbol),
  readonly: (Symbol('readonly'): symbol),
  size: (Symbol('size'): symbol),
  type: (Symbol('type'): symbol),
  unserializable: (Symbol('unserializable'): symbol),
};

export type Dehydrated = {
  inspectable: boolean,
  name: string | null,
  preview_long: string | null,
  preview_short: string | null,
  readonly?: boolean,
  size?: number,
  type: string,
};

// Typed arrays, other complex iteratable objects (e.g. Map, Set, ImmutableJS) or Promises need special handling.
// These objects

e: string | null,
  preview_long: string | null,
  preview_short: string | null,
  readonly?: boolean,
  size?: number,
  type: string,
  unserializable: boolean,
  [string | number]: any,
};

// This threshold determines the depth at which the bridge "deh

 can't be serialized without losing type information,
// so a "Unserializable" type wrapper is used (with meta-data keys) to send nested values-
// while preserving the original type and name.
export type Unserializable = {
  nam


iates.
 *
 * 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
 */

import type {LoggerEvent} from 'react-devtools-shared/src/Logger';

import {registerEventLogger} from 'react-devtools-shared/src/Logger';
import {enableLogger} from 'react-devtools-feature-flags';

let currentLoggingIFrame = null;
let currentSessionId = null;
let missedEvents: Array<LoggerEvent> = [];

type LoggerContext = {
  page_url: ?string

enableLogger) {
      if (currentLoggingIFrame != null && currentSessionId != null) {
        const {metadata, ...eventWithoutMetadata} = event;
        const additionalContext: LoggerContext | {} =
          fetchAdditionalContext != null ? await fetchAdd

,
};

export function registerDevToolsEventLogger(
  surface: string,
  fetchAdditionalContext?:
    | (() => LoggerContext)
    | (() => Promise<LoggerContext>),
): void {
  async function logEvent(event: LoggerEvent) {
    if (


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import SourceMapConsumer from 'react-devtools-shared/src/hooks/SourceMapConsumer';

import type {ReactFunctionLocation} from 'shared/ReactTypes';
import type {FetchFileWithCaching} from 'react-devtools-shared/src/devtools/views/Components/FetchFileWithCachingContext';

const symbolicationCache: Map<
  string,
  Promise<SourceMappedLocation | null>,
> = new Map();

export type SourceMappedLocation = {
  loca

umber, // 1-based
  column: number, // 1-based
): Promise<SourceMappedLocation | null> {
  const key = `${sourceURL}:${line}:${column}`;
  const cachedPromise = symbolicationCache.get(key);
  if (cachedPromise != null) {
    return cachedPromise;
  }

  co

tion: ReactFunctionLocation,
  ignored: boolean, // Whether the file for this location was ignore listed
};

export function symbolicateSourceWithCache(
  fetchFileWithCaching: FetchFileWithCaching,
  sourceURL: string,
  line: n


unction,
  ElementTypeMemo,
  ElementTypeVirtual,
} from 'react-devtools-shared/src/frontend/types';
import {
  localStorageGetItem,
  localStorageSetItem,
  sessionStorageGetItem,
  sessionStorageRemoveItem,
  sessionStorageSetItem,
} from 'react-devtools-shared/src/storage';
import {meta} from './hydration';
import isArray from './isArray';

import type {
  ComponentFilter,
  ElementType,
  SerializedElement as SerializedElementFrontend,
  LRUCache,
} from 'react-devtools-shared/src/frontend/types';
impor

sOwnProperty = Object.prototype.hasOwnProperty;

const cachedDisplayNames: WeakMap<Function, string> = new WeakMap();

// On large trees, encoding takes significant time.
// Try to reuse the already encoded strings.
const encodedStringCache: LRUCache<strin

t type {
  ProfilingSettings,
  SerializedElement as SerializedElementBackend,
} from 'react-devtools-shared/src/backend/types';
import {isSynchronousXHRSupported} from './backend/utils';

// $FlowFixMe[method-unbinding]
const ha


require('webpack');
const {
  GITHUB_URL,
  getVersionString,
} = require('react-devtools-extensions/utils');
const {resolveFeatureFlags} = require('react-devtools-shared/buildUtils');

const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
  console.error('NODE_ENV not set');
  process.exit(1);
}

const builtModulesDir = resolve(
  __dirname,
  '..',
  '..',
  'build',
  'oss-experimental',
);

const __DEV__ = NODE_ENV === 'development';

const DEVTOOLS_VERSION = getVersionString();

const featureFlagTarg

ion',
  devtool: __DEV__ ? 'eval-cheap-module-source-map' : 'source-map',
  entry: {
    backend: './src/backend.js',
  },
  output: {
    path: __dirname + '/dist',
    filename: '[name].js',

    // This name is important; standalone references it in ord

et = process.env.FEATURE_FLAG_TARGET || 'core/backend-oss';

// This targets RN/Hermes.
process.env.BABEL_CONFIG_ADDITIONAL_TARGETS = JSON.stringify({
  ie: '11',
});

module.exports = {
  mode: __DEV__ ? 'development' : 'product


 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.
 *
 *
 */
const {
  useMemo,
  useState
} = require('react');

function Component(props) {
  const InnerComponent = useMemo(() => () => {
    const [state] = useState(0);
    return state;
  });
  props.callback(InnerComponent);
  return null;
}

module.exports = {
  Component
};
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjo


/constants';
import attachRenderer from './attachRenderer';
import formatConsoleArguments from 'react-devtools-shared/src/backend/utils/formatConsoleArguments';
import formatWithStyles from 'react-devtools-shared/src/backend/utils/formatWithStyles';

// React's custom built component stack strings match "\s{4}in"
// Chrome's prefix matches "\s{4}at"
const PREFIX_REGEX = /\s{4}(in|at)\s{1}/;
// Firefox and Safari have no prefix ("")
// but we can fallback to looking for location info (e.g. "foo.js:12:345")
c

rsions of React didn't do.
// To compare if it's equivalent we strip out the suffix to see if they're
// still equivalent. Similarly, we sometimes use [] and sometimes () so we
// strip them to for the comparison.
const frameDiffs = / \(\<anonymous\>\)$|\@

onst ROW_COLUMN_NUMBER_REGEX = /:\d+:\d+(\n|$)/;

function isStringComponentStack(text: string): boolean {
  return PREFIX_REGEX.test(text) || ROW_COLUMN_NUMBER_REGEX.test(text);
}

// We add a suffix to some frames that older ve


import LRU from 'lru-cache';
import {
  convertInspectedElementBackendToFrontend,
  hydrateHelper,
  inspectElement as inspectElementAPI,
  inspectScreen as inspectScreenAPI,
} from 'react-devtools-shared/src/backendAPI';
import {fillInPath} from 'react-devtools-shared/src/hydration';

import type {LRUCache} from 'react-devtools-shared/src/frontend/types';
import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
import type {
  InspectElementError,
  InspectElementFullData,
  InspectElementHydr

ment,
  InspectedElement as InspectedElementFrontend,
  InspectedElementResponseType,
  InspectedElementPath,
} from 'react-devtools-shared/src/frontend/types';

// Maps element ID to inspected data.
// We use an LRU for this rather than a WeakMap because

atedPath,
} from 'react-devtools-shared/src/backend/types';
import UserError from 'react-devtools-shared/src/errors/UserError';
import UnknownHookError from 'react-devtools-shared/src/errors/UnknownHookError';
import type {
  Ele


 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.
 *
 * @emails react-core
 */

'use strict';

describe('onlyChild', () => {
  let React;
  let WrapComponent;

  beforeEach(() => {
    React = require('react');
    WrapComponent = class extends React.Component {
      render() {
        return (
          <div>
            {React.Children.only(this.props.children, this.props.mapFn, this)}

>
      );
      React.Children.only(instance.props.children);
    }).toThrow();
  });

  it('should fail when passed nully values', () => {
    expect(function () {
      const instance = <WrapComponent>{null}</WrapComponent>;
      React.Children.only(in

        );
      }
    };
  });

  it('should fail when passed two children', () => {
    expect(function () {
      const instance = (
        <WrapComponent>

        </WrapComponent


React.Component().updater,
    );
  });

  it('should throw when `render` is not specified', () => {
    expect(function () {
      createReactClass({});
    }).toThrowError('Class specification must implement a `render` method.');
  });

  it('should copy prop types onto the Constructor', () => {
    const propValidator = jest.fn();
    const TestComponent = createReactClass({
      propTypes: {
        value: propValidator,
      },
      render: function () {
        return <div />;
      },
    });

propTypes: {
        prop: null,
      },
      render: function () {
        return <span>{this.props.prop}</span>;
      },
    });
    assertConsoleErrorDev([
      'Warning: Component: prop type `prop` is invalid; ' +
        'it must be a function, us

 expect(TestComponent.propTypes).toBeDefined();
    expect(TestComponent.propTypes.value).toBe(propValidator);
  });

  it('should warn on invalid prop types', () => {
    createReactClass({
      displayName: 'Component',


ource code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import ErrorStackParser from 'error-stack-parser';
import testErrorStack, {
  SOURCE_STACK_FRAME_LINE_NUMBER,
} from './ErrorTesterCompiled';

let sourceMapsAreAppliedToErrors: boolean | null = null;

// Source maps are automatically applied to Error stack frames.
export function areSourceMapsAppliedToErrors(): boolean {
  if (sourceMapsAreAppliedToErrors === null) {
    try

ToErrors = false;
    } catch (error) {
      const parsed = ErrorStackParser.parse(error);
      const topStackFrame = parsed[0];
      const lineNumber = topStackFrame.lineNumber;
      if (lineNumber === SOURCE_STACK_FRAME_LINE_NUMBER) {
        sourceM

{
      testErrorStack();
      sourceMapsAreApplied


ineProperty(exports, '__esModule', {
  value: true,
});
exports.default = testErrorStack;
exports.SOURCE_STACK_FRAME_LINE_NUMBER = void 0;

/**
 * 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
 */
function testErrorStack() {
  // If source maps are applied, this Error will have a stack frame with line 12.
  throw Error('Test Error stack');
}

const SOURCE_STACK_FR

AME_LINE_NUMBER = 12;
exports.SOURCE_STACK_FRAME_LINE_NUMBER = SOURCE_STACK_FRAME_LINE_NUMBER;
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInRlc3RFcm9yclN0YWNrLmpzIl0sIm5hbWVzIj


ght (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
 */

import type {EncodedHookMap} from './generateHookMap';

export type ReactSourceMetadata = [?EncodedHookMap];
export type ReactSourcesArray = $ReadOnlyArray<?ReactSourceMetadata>;

export type FBSourceMetadata = [?{...}, ?ReactSourceMetadata];
export type FBSourcesArray = $ReadOnlyArray<?FBSourceMetadata>;

ourcesArray,
  +x_react_sources?: ReactSourcesArray,
  +ignoreList?: Array<number>,
};

export type IndexSourceMapSection = {
  map: BasicSourceMap,
  offset: {
    line: number,
    column: number,
    ...
  },
  ...
};

export type IndexSourceMap = {
  +

export type BasicSourceMap = {
  +file?: string,
  +mappings: string,
  +names: Array<string>,
  +sourceRoot?: string,
  +sources: Array<string>,
  +sourcesContent?: Array<?string>,
  +version: number,
  +x_facebook_sources?: FBS


ION: 'CallExpression',
  MEMBER_EXPRESSION: 'MemberExpression',
  ARRAY_PATTERN: 'ArrayPattern',
  IDENTIFIER: 'Identifier',
  NUMERIC_LITERAL: 'NumericLiteral',
  VARIABLE_DECLARATOR: 'VariableDeclarator',
});

// Check if line number obtained from source map and the line number in hook node match
function checkNodeLocation(
  path: NodePath,
  line: number,
  column?: number | null = null,
): boolean {
  const {start, end} = path.node.loc;

  if (line !== start.line) {
    return false;
  }

  if (column

r,
    // because this code matches the 1-based Error stack location for the hook Identifier (e.g. useState)
    // with the larger 0-based VariableDeclarator (e.g. [foo, setFoo] = useState())
    // so the ranges should always overlap.
    //
    // For m

!== null) {
    // Column numbers are represented differently between tools/engines.
    // Error.prototype.stack columns are 1-based (like most IDEs) but ASTs are 0-based.
    //
    // In practice this will probably never matte


-local
 */

import type {
  HookMap,
  HookMapEntry,
  HookMapLine,
  HookMapMappings,
} from './generateHookMap';
import type {Position} from './astUtils';
import {NO_HOOK_NAME} from './astUtils';

/**
 * Finds the Hook name assigned to a given location in the source code,
 * and a HookMap extracted from an extended source map.
 * The given location must correspond to the location in the *original*
 * source code (i.e. *not* the generated one).
 *
 * Note that all locations in the source code are guarantee

 */
export function getHookNameForLocation(
  location: Position,
  hookMap: HookMap,
): string | null {
  const {names, mappings} = hookMap;

  // The HookMap mappings are grouped by lines, so first we look up
  // which line of mappings covers the targe

d to map
 * to a name, including a sentinel value that represents a missing
 * Hook name: '<no-hook>'.
 *
 * For more details on the format of the HookMap, see generateHookMap
 * and the tests for that function and this function.


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import {parse} from '@babel/parser';
import {generateEncodedHookMap, generateHookMap} from '../generateHookMap';

function expectHookMapToEqual(actual, expected) {
  expect(actual.names).toEqual(expected.names);

  const formattedMappings = [];
  actual.mappings.forEach(lines => {
    lines.forEach(segment => {
      const name = actual.names[segment[2]];
      if (name == null) {
        throw new Error(`E

p', () => {
  it('should parse names for built-in hooks', () => {
    const code = `
import {useState, useContext, useMemo, useReducer} from 'react';

export function Component() {
  const a = useMemo(() => A);
  const [b, setB] = useState(0);

  // pretti

xpected to find name at position ${segment[2]}`);
      }
      formattedMappings.push(`${name} from ${segment[0]}:${segment[1]}`);
    });
  });
  expect(formattedMappings).toEqual(expected.mappings);
}

describe('generateHookMa


sx = require('acorn-jsx');
const rollupResolve = require('@rollup/plugin-node-resolve').nodeResolve;
const {encode, decode} = require('@jridgewell/sourcemap-codec');
const {generateEncodedHookMap} = require('../generateHookMap');
const {parse} = require('@babel/parser');

const sourceDir = resolve(__dirname, '__source__');
const buildRoot = resolve(sourceDir, '__compiled__');
const externalDir = resolve(buildRoot, 'external');
const inlineDir = resolve(buildRoot, 'inline');
const bundleDir = resolve(buildRo

solve(inlineDir, 'fb-sources-extended');
const externalFbSourcesExtendedDir = resolve(
  externalDir,
  'fb-sources-extended',
);
const inlineFbSourcesIndexMapExtendedDir = resolve(
  inlineFbSourcesExtendedDir,
  'index-map',
);
const externalFbSourcesInd

ot, 'bundle');
const noColumnsDir = resolve(buildRoot, 'no-columns');
const inlineIndexMapDir = resolve(inlineDir, 'index-map');
const externalIndexMapDir = resolve(externalDir, 'index-map');
const inlineFbSourcesExtendedDir = re


ource code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import React, {useEffect, useState} from 'react';

export function Component() {
  const countState = useState(0);
  const count = countState[0];
  const setCount = countState[1];

  const darkMode = useIsDarkMode();
  const [isDarkMode] = darkMode;

  useEffect(() => {
    // ...
  }, []);

  const handleClick = () => setCount(count + 1);

  return (
    <>
      <div>Dark m

iv>
      <button onClick={handleClick}>Update count</button>
    </>
  );
}

function useIsDarkMode() {
  const darkModeState = useState(false);
  const [isDarkMode] = darkModeState;

  useEffect(function useEffectCreate() {
    // Here is where we may li


ource code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

export {Component as ComponentUsingHooksIndirectly} from './ComponentUsingHooksIndirectly';
export {Component as ComponentWithCustomHook} from './ComponentWithCustomHook';
export {Component as ComponentWithExternalCustomHooks} from './ComponentWithExternalCustomHooks';
export {Component as ComponentWithMultipleHooksPerLine} from './ComponentWithMultipleHooksPerLine';
export {

nentWithNestedHooks';
export {Component as ContainingStringSourceMappingURL} from './ContainingStringSourceMappingURL';
export {Component as Example} from './Example';
export {Component as InlineRequire} from './InlineRequire';
import * as ToDoList from '.

Component as ComponentWithNestedHooks} from './Compo


import * as React from 'react';

import {
  unstable_getCacheForType as getCacheForType,
  startTransition,
} from 'react';
import Store from 'react-devtools-shared/src/devtools/store';
import {inspectElement as inspectElementMutableSource} from 'react-devtools-shared/src/inspectedElementMutableSource';
import ElementPollingCancellationError from 'react-devtools-shared/src//errors/ElementPollingCancellationError';

import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
import type {
  Thenabl

d/src/frontend/types';

function readRecord<T>(record: Thenable<T>): T {
  if (typeof React.use === 'function') {
    // eslint-disable-next-line react-hooks-published/rules-of-hooks
    return React.use(record);
  }
  if (record.status === 'fulfilled') {

e,
  FulfilledThenable,
  RejectedThenable,
} from 'shared/ReactTypes';
import type {
  Element,
  InspectedElement as InspectedElementFrontend,
  InspectedElementResponseType,
  InspectedElementPath,
} from 'react-devtools-share


**
 * 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
 */

export function localStorageGetItem(key: string): any {
  try {
    return localStorage.getItem(key);
  } catch (error) {
    return null;
  }
}

export function localStorageRemoveItem(key: string): void {
  try {
    localStorage.removeItem(key);
  } catch (error) {}
}

export function localStorageSetItem(k

or) {
    return null;
  }
}

export function sessionStorageRemoveItem(key: string): void {
  try {
    sessionStorage.removeItem(key);
  } catch (error) {}
}

export function sessionStorageSetItem(key: string, value: any): void {
  try {
    return sessio

ey: string, value: any): void {
  try {
    return localStorage.setItem(key, value);
  } catch (error) {}
}

export function sessionStorageGetItem(key: string): any {
  try {
    return sessionStorage.getItem(key);
  } catch (err


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import {__DEBUG__} from 'react-devtools-shared/src/constants';

import type {
  Thenable,
  FulfilledThenable,
  RejectedThenable,
} from 'shared/ReactTypes';

import * as React from 'react';

const TIMEOUT = 30000;

type Module = any;
type ModuleLoaderFunction = () => Thenable<Module>;

// This is intentionally a module-level Map, rather than a React-managed one.
// Otherwise, refreshing the inspected elem

ct.use === 'function') {
    try {
      // eslint-disable-next-line react-hooks-published/rules-of-hooks
      return React.use(record);
    } catch (x) {
      if (x === null) {
        return null;
      }
      throw x;
    }
  }
  if (record.status ==

ent cache would also clear this cache.
// Modules are static anyway.
const moduleLoaderFunctionToModuleMap: Map<ModuleLoaderFunction, Module> =
  new Map();
function readRecord<T>(record: Thenable<T>): T | null {
  if (typeof Rea


-local
 */

import type {Position} from './astUtils';
import type {
  ReactSourceMetadata,
  IndexSourceMap,
  BasicSourceMap,
  MixedSourceMap,
} from './SourceMapTypes';
import type {HookMap} from './generateHookMap';
import * as util from 'source-map-js/lib/util';
import {decodeHookMap} from './generateHookMap';
import {getHookNameForLocation} from './getHookNameForLocation';

type MetadataMap = Map<string, ?ReactSourceMetadata>;

const HOOK_MAP_INDEX_IN_REACT_METADATA = 0;
const REACT_METADATA_INDEX_IN_

es are normalized using the same logic that the `source-map-js@0.6.2` package uses internally.
 * This is crucial for keeping the sources list in sync with a `SourceMapConsumer` instance.
 */
function normalizeSourcePath(
  sourceInput: string,
  map: {+so

FB_METADATA = 1;
const REACT_SOURCES_EXTENSION_KEY = 'x_react_sources';
const FB_SOURCES_EXTENSION_KEY = 'x_facebook_sources';

/**
 * Extracted from the logic in source-map-js@0.6.2's SourceMapConsumer.
 * By default, source nam


MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import {getHookNamesMappingFromAST} from './astUtils';
import {encode, decode} from '@jridgewell/sourcemap-codec';

// Missing types in @babel/types
type File = any;

export type HookMap = {
  names: $ReadOnlyArray<string>,
  mappings: HookMapMappings,
};

export type EncodedHookMap = {
  names: $ReadOnlyArray<string>,
  mappings: string,
};

// See generateHookMap below for more details on formatting
export

 TODO below)
];
export type HookMapLine = HookMapEntry[];
export type HookMapMappings = HookMapLine[];

/**
 * Given a parsed source code AST, returns a "Hook Map", which is a
 * mapping which maps locations in the source code to their to their
 * correspo

 type HookMapEntry = [
  number, // 1-indexed line number
  number, // 0-indexed column number
  number, // 0-indexed index into names array
  number, // TODO: filler number to support reusing encoding from `sourcemap-codec` (see


=> {
      console.trace('source-map-support');
    });

    fetchMock = initFetchMock();

    inspectHooks =
      require('react-debug-tools/src/ReactDebugHooks').inspectHooks;

    // Jest can't run the workerized version of this module.
    const {
      flattenHooksList,
      loadSourceAndMetadata,
    } = require('../parseHookNames/loadSourceAndMetadata');
    const parseSourceAndMetadata =
      require('../parseHookNames/parseSourceAndMetadata').parseSourceAndMetadata;
    parseHookNames = async ho

    // Runs in a Worker because it's CPU intensive:
      return parseSourceAndMetadata(
        hooksList,
        locationKeyToHookSourceAndMetadata,
      );
    };

    // Jest (jest-runner?) configures Errors to automatically account for source maps.

oksTree => {
      const hooksList = flattenHooksList(hooksTree);

      // Runs in the UI thread so it can share Network cache:
      const locationKeyToHookSourceAndMetadata =
        await loadSourceAndMetadata(hooksList);


ource code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import React, {useDebugValue, useEffect, useState} from 'react';

export function Component() {
  const [count, setCount] = useState(0);
  const isDarkMode = useIsDarkMode();
  const {foo} = useFoo();

  useEffect(() => {
    // ...
  }, []);

  const handleClick = () => setCount(count + 1);

  return (
    <>

Dark mode? {isDarkMode}

Count: {count}

lick={handleClick}>Update count</button>
    </>
  );
}

function useIsDarkMode() {
  const [isDarkMode] = useState(false);

  useEffect(function useEffectCreate() {
    // Here is where we may listen to a "theme" event...
  }, []);

  return isDarkMode;
}


iates.
 *
 * 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
 */

import {enableLogger} from 'react-devtools-feature-flags';

export type LoggerEvent =
  | {
      +event_name: 'loaded-dev-tools',
    }
  | {
      +event_name: 'error',
      +error_message: string | null,
      +error_stack: string | null,
      +error_component_stack: string | null,
    }
  | {
      +event_name: 'selected-components-tab',

     +duration_ms: number,
      +inspected_element_display_name: string | null,
      +inspected_element_number_of_hooks: number | null,
    }
  | {
      +event_name: 'select-element',
      +metadata: {
        +source: string,
      },
    }
  | {

    }
  | {
      +event_name: 'selected-profiler-tab',
    }
  | {
      +event_name: 'selected-suspense-tab',
    }
  | {
      +event_name: 'load-hook-names',
      +event_status: 'success' | 'error' | 'timeout' | 'unknown',


mport {withSyncPerfMeasurements} from 'react-devtools-shared/src/PerformanceLoggingUtils';
import {decode} from '@jridgewell/sourcemap-codec';

import type {
  IndexSourceMap,
  IndexSourceMapSection,
  BasicSourceMap,
  MixedSourceMap,
} from './SourceMapTypes';

type SearchPosition = {
  columnNumber: number,
  lineNumber: number,
};

type ResultPosition = {
  column: number,
  line: number,
  sourceContent: string | null,
  sourceURL: string | null,
  ignored: boolean,
};

export type SourceMapConsumerTy

sumerType {
  if (sourceMapJSON.sections != null) {
    return IndexedSourceMapConsumer(((sourceMapJSON: any): IndexSourceMap));
  } else {
    return BasicSourceMapConsumer(((sourceMapJSON: any): BasicSourceMap));
  }
}

function BasicSourceMapConsumer(so

pe = {
  originalPositionFor: SearchPosition => ResultPosition,
};

type Mappings = Array<Array<Array<number>>>;

export default function SourceMapConsumer(
  sourceMapJSON: MixedSourceMap | IndexSourceMapSection,
): SourceMapCon


directly.js";
function Component() {
  const countState = React.useState(0);
  const count = countState[0];
  const setCount = countState[1];
  const darkMode = useIsDarkMode();
  const [isDarkMode] = darkMode;
  React.useEffect(() => {// ...
  }, []);

  const handleClick = () => setCount(count + 1);

  return /*#__PURE__*/React__default.createElement(React__default.Fragment, null, /*#__PURE__*/React__default.createElement("div", {
    __source: {
      fileName: _jsxFileName,
      lineNumber: 28,
      c

_PURE__*/React__default.createElement("button", {
    onClick: handleClick,
    __source: {
      fileName: _jsxFileName,
      lineNumber: 30,
      columnNumber: 7
    }
  }, "Update count"));
}

function useIsDarkMode() {
  const darkModeState = React.u

olumnNumber: 7
    }
  }, "Dark mode? ", isDarkMode), /*#__PURE__*/React__default.createElement("div", {
    __source: {
      fileName: _jsxFileName,
      lineNumber: 29,
      columnNumber: 7
    }
  }, "Count: ", count), /*#_


ineProperty(exports, "__esModule", {
  value: true
});
exports.Component = Component;

var _react = _interopRequireDefault(require("react"));

var _useTheme = _interopRequireDefault(require("./useTheme"));

var _jsxFileName = "";

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function Component() {
  const theme = (0, _useTheme.default)();
  return /*#__PURE__*/_react.default.createElement("div", {
    __source: {
      fileName: _jsxFileName,
      lineNum

ber: 16,
      columnNumber: 10
    }
  }, "theme: ", theme);
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhFeHRlcm5hbEN1c3RvbUhvb2tzLmpzIl0sIm5hbWVzIjpbIkNvb


Module", {
  value: true
});
exports.Component = Component;

var _react = require("react");

/**
 * 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.
 *
 *
 */
const A = /*#__PURE__*/(0, _react.createContext)(1);
const B = /*#__PURE__*/(0, _react.createContext)(2);

function Component() {
  const a = (0, _react.useContext)(A);
  const b = (0, _react.useContext)(B); // prettier-i

gnore

  const c = (0, _react.useContext)(A),
        d = (0, _react.useContext)(B); // eslint-disable-line one-var

  return a + b + c + d;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3


mponent;

var _react = _interopRequireWildcard(require("react"));

var _jsxFileName = "";

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cac

var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, ne

he && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) {


trict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Component = Component;

/**
 * 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.
 *
 *
 */
function Component() {
  const [count] = require('react').useState(0);

  return count;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIklubGluZVJlcXVpcmUuan


interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDesc

on ListItem({
  item,
  removeItem,
  toggleItem
}) {
  const handleDelete = (0, React.useCallback)(() => {
    removeItem(item);
  }, [item, removeItem]);
  const handleToggle = (0, React.useCallback)(() => {
    toggleItem(item);
  }, [item, toggleItem])

riptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

functi


import {parse} from '@babel/parser';
import {generateHookMap} from '../generateHookMap';
import {getHookNameForLocation} from '../getHookNameForLocation';

function expectHookMapToEqual(actual, expected) {
  expect(actual.names).toEqual(expected.names);

  const formattedMappings = [];
  actual.mappings.forEach(lines => {
    lines.forEach(segment => {
      const name = actual.names[segment[2]];
      if (name == null) {
        throw new Error(`Expected to find name at position ${segment[2]}`);
      }

 => {
    const code = `
import {useState, useContext, useMemo, useReducer} from 'react';

export function Component() {
  const a = useMemo(() => A);
  const [b, setB] = useState(0);

  // prettier-ignore
  const c = useContext(A), d = useContext(B); // e

    formattedMappings.push(`${name} from ${segment[0]}:${segment[1]}`);
    });
  });
  expect(formattedMappings).toEqual(expected.mappings);
}

describe('generateHookMap', () => {
  it('should parse names for built-in hooks', ()


etRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.d

.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function Component() {
  const [count, setCount] = (0, _react.useState)(0);

efineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc


yright (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.
 *
 *
 */
const {
  useMemo,
  useState
} = require('react');

function Component(props) {
  const InnerComponent = useMemo(() => () => {
    const [state] = useState(0);
    return state;
  });
  props.callback(InnerComponent);
  return null;
}

module.exports = {
  Component
};
//# sourceMappingURL=data:application/json;charset=ut


 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.
 *
 *
 */
const {
  useMemo,
  useState
} = require('react');

function Component(props) {
  const InnerComponent = useMemo(() => () => {
    const [state] = useState(0);
    return state;
  });
  props.callback(InnerComponent);
  return null;
}

module.exports = {
  Component
};
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjo


Module", {
  value: true
});
exports.Component = Component;

var _react = _interopRequireWildcard(require("react"));

var _jsxFileName = "";

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }

(Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } n

; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if


 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
 */

import type {
  BasicSourceMap,
  MixedSourceMap,
  IndexSourceMap,
} from './SourceMapTypes';

export function sourceMapIncludesSource(
  sourcemap: MixedSourceMap,
  source: ?string,
): boolean {
  if (source == null) {
    return false;
  }
  if (sourcemap.mappings === undefined) {
    const index

dexSourceMap.sections.some(section => {
      return sourceMapIncludesSource(section.map, source);
    });
  }

  const basicMap: BasicSourceMap = sourcemap;
  return basicMap.sources.some(
    s => s === 'Inline Babel script' || source.endsWith(s),
  );
}

SourceMap: IndexSourceMap = sourcemap;
    return in


exports, "ComponentUsingHooksIndirectly", {
  enumerable: true,
  get: function () {
    return _ComponentUsingHooksIndirectly.Component;
  }
});
Object.defineProperty(exports, "ComponentWithCustomHook", {
  enumerable: true,
  get: function () {
    return _ComponentWithCustomHook.Component;
  }
});
Object.defineProperty(exports, "ComponentWithExternalCustomHooks", {
  enumerable: true,
  get: function () {
    return _ComponentWithExternalCustomHooks.Component;
  }
});
Object.defineProperty(exports, "Comp

unction () {
    return _ComponentWithNestedHooks.Component;
  }
});
Object.defineProperty(exports, "ContainingStringSourceMappingURL", {
  enumerable: true,
  get: function () {
    return _ContainingStringSourceMappingURL.Component;
  }
});
Object.define

onentWithMultipleHooksPerLine", {
  enumerable: true,
  get: function () {
    return _ComponentWithMultipleHooksPerLine.Component;
  }
});
Object.defineProperty(exports, "ComponentWithNestedHooks", {
  enumerable: true,
  get: f


iates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import * as React from 'react';
import {Fragment, useCallback, useState} from 'react';

export function ListItem({item, removeItem, toggleItem}) {
  const handleDelete = useCallback(() => {
    removeItem(item);
  }, [item, removeItem]);

  const handleToggle = useCallback(() => {
    toggleItem(item);
  }, [item, toggleItem]);

  return (
    <li>
      <b

>
  );
}

export function List(props) {
  const [newItemText, setNewItemText] = useState('');
  const [items, setItems] = useState([
    {id: 1, isComplete: true, text: 'First'},
    {id: 2, isComplete: true, text: 'Second'},
    {id: 3, isComplete: false,

utton onClick={handleDelete}>Delete</button>
      <label>
        <input
          checked={item.isComplete}
          onChange={handleToggle}
          type="checkbox"
        />{' '}
        {item.text}
      </label>
    </li


ineProperty(exports, "__esModule", {
  value: true
});
exports.default = useTheme;
exports.ThemeContext = void 0;

var _react = require("react");

/**
 * 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.
 *
 *
 */
const ThemeContext = /*#__PURE__*/(0, _react.createContext)('bright');
exports.ThemeContext = ThemeContext;

function useTheme() {
  const theme = (0, _react.useContex

t)(ThemeContext);
  (0, _react.useDebugValue)(theme);
  return theme;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInVzZVRoZW1lLmpzIl0sIm5hbWVzIjpbIlRoZW1lQ29udGV4dCIsInVzZVRoZ


ber: 16,
      columnNumber: 10
    }
  }, "theme: ", theme);
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozL


;

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Component = Component;

/**
 * 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.
 *
 *
 */
function Component() {
  const [count] = require('react').useState(0);

  return count;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAs


.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function Component() {
  const countState = (0, _react.useState)(0);
  cons


;

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Component = Component;

/**
 * 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.
 *
 *
 */
function Component() {
  const [count] = require('react').useState(0);

  return count;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIklubGluZVJlcXVpcmUuanMiXSwi


gnore

  const c = (0, _react.useContext)(A),
        d = (0, _react.useContext)(B); // eslint-disable-line one-var

  return a + b + c + d;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZW


t)(ThemeContext);
  (0, _react.useDebugValue)(theme);
  return theme;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJza


nentUsingHooksIndirectly.Component;
  }
});
Object.defineProperty(exports, "ComponentWithCustomHook", {
  enumerable: true,
  get: function () {
    return _ComponentWithCustomHook.Component;
  }
});
Object.defineProperty(exports, "ComponentWithExternalCustomHooks", {
  enumerable: true,
  get: function () {
    return _ComponentWithExternalCustomHooks.Component;
  }
});
Object.defineProperty(exports, "ComponentWithMultipleHooksPerLine", {
  enumerable: true,
  get: function () {
    return _ComponentWithMu

ontainingStringSourceMappingURL", {
  enumerable: true,
  get: function () {
    return _ContainingStringSourceMappingURL.Component;
  }
});
Object.defineProperty(exports, "Example", {
  enumerable: true,
  get: function () {
    return _Example.Component;

ltipleHooksPerLine.Component;
  }
});
Object.defineProperty(exports, "ComponentWithNestedHooks", {
  enumerable: true,
  get: function () {
    return _ComponentWithNestedHooks.Component;
  }
});
Object.defineProperty(exports, "C


ineProperty(exports, "__esModule", {
  value: true
});
exports.Component = Component;

var _react = _interopRequireDefault(require("react"));

var _useTheme = _interopRequireDefault(require("./useTheme"));

var _jsxFileName = "";

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function Component() {
  const theme = (0, _useTheme.default)();
  return /*#__PURE__*/_react.default.createElement("div", {
    __source: {
      fileName: _jsxFileName,
      lineNum


Module", {
  value: true
});
exports.Component = Component;

var _react = require("react");

/**
 * 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.
 *
 *
 */
const A = /*#__PURE__*/(0, _react.createContext)(1);
const B = /*#__PURE__*/(0, _react.createContext)(2);

function Component() {
  const a = (0, _react.useContext)(A);
  const b = (0, _react.useContext)(B); // prettier-i


mponent;

var _react = _interopRequireWildcard(require("react"));

var _jsxFileName = "";

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cac


iates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import {getVersionedRenderImplementation} from './utils';

describe('CompilerIntegration', () => {
  global.IS_REACT_ACT_ENVIRONMENT = true;
  let React;
  let act;
  let useMemoCache;

  beforeEach(() => {
    React = require('react');
    require('react-dom');
    require('react-dom/client');
    useMemoCache = require('react/compiler-runtime').c;

    co

play names should not have Forget prefix', () => {
    const hook = global.__REACT_DEVTOOLS_GLOBAL_HOOK__;
    const reactDOMFiberRendererInterface = hook.rendererInterfaces.get(1);
    expect(reactDOMFiberRendererInterface).not.toBeFalsy();

    const Foo

nst utils = require('./utils');
    act = utils.act;
  });

  afterEach(() => {
    jest.restoreAllMocks();
  });

  const {render} = getVersionedRenderImplementation();

  // @reactVersion >= 18.2
  it('By default, component dis


trict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Component = Component;

/**
 * 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.
 *
 *
 */
function Component() {
  const [count] = require('react').useState(0);

  return count;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIklubGluZVJlcXVpcmUuan


se strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Component = Component;

var _react = require("react");

/**
 * 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.
 *
 *
 */
const A = /*#__PURE__*/(0, _react.createContext)(1);
const B = /*#__PURE__*/(0, _react.createContext)(2);

function Component() {
  const a = (0, _react.useContext)(A);
  c

react.useContext)(B); // prettier-ignore

  const c = (0, _react.useContext)(A),
        d = (0, _react.useContext)(B); // eslint-disable-line one-var

  return a + b + c + d;
}
//# sourceMappingURL=ComponentWithMultipleHooksPerLine.js.map?foo=bar&param=so


ineProperty(exports, "__esModule", {
  value: true
});
exports.Component = Component;

var _react = _interopRequireWildcard(require("react"));

var _jsxFileName = "";

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function")

for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newOb

{ return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;


tItem;
exports.List = List;

var React = _interopRequireWildcard(require("react"));

var _jsxFileName = "";

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildca

call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) {

rdCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.


interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDesc


Module", {
  value: true
});
exports.Component = Component;

var _react = _interopRequireWildcard(require("react"));

var _jsxFileName = "";

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }


iates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import type {HookSourceAndMetadata} from './loadSourceAndMetadata';
import type {HooksNode, HooksTree} from 'react-debug-tools/src/ReactDebugHooks';
import type {HookNames} from 'react-devtools-shared/src/frontend/types';
import type {FetchFileWithCaching} from 'react-devtools-shared/src/devtools/views/Components/FetchFileWithCachingContext';

import 'react

 './parseSourceAndMetadata';
import {flattenHooksList, loadSourceAndMetadata} from './loadSourceAndMetadata';

const workerizedParseHookNames: ParseSourceAndMetadataModule =
  WorkerizedParseSourceAndMetadata();

export function parseSourceAndMetadata(
  h

';

import {withAsyncPerfMeasurements} from 'react-devtools-shared/src/PerformanceLoggingUtils';
import WorkerizedParseSourceAndMetadata from './parseSourceAndMetadata.worker';
import typeof * as ParseSourceAndMetadataModule from


ookName} from '../astUtils';
import {areSourceMapsAppliedToErrors} from '../ErrorTester';
import {__DEBUG__} from 'react-devtools-shared/src/constants';
import {getHookSourceLocationKey} from 'react-devtools-shared/src/hookSourceLocation';
import {SourceMapMetadataConsumer} from '../SourceMapMetadataConsumer';
import {
  withAsyncPerfMeasurements,
  withSyncPerfMeasurements,
} from 'react-devtools-shared/src/PerformanceLoggingUtils';
import SourceMapConsumer from '../SourceMapConsumer';

import type {Source

  HookNames,
  LRUCache,
} from 'react-devtools-shared/src/frontend/types';

type AST = mixed;

type HookParsedMetadata = {
  // API for consuming metadfata present in extended source map.
  metadataConsumer: SourceMapMetadataConsumer | null,

  // AST fo

MapConsumerType} from '../SourceMapConsumer';
import type {
  HooksList,
  LocationKeyToHookSourceAndMetadata,
} from './loadSourceAndMetadata';
import type {HookSource} from 'react-debug-tools/src/ReactDebugHooks';
import type {


);
    });

    afterEach(() => {
      // Verify all logged marks also get cleared.
      expect(currentlyNotClearedMarks).toHaveLength(0);

      setPerformanceMock(null);
    });

    describe('with legacy render', () => {
      const {render: legacyRender} = getLegacyRenderImplementation();

      // @reactVersion <= 18.2
      // @reactVersion >= 18.0
      it('should mark sync render without suspends or state updates', () => {
        utils.act(() => store.profilerStore.startProfiling());
        lega

          "--react-internal-module-stop-  at filtered (<anonymous>:1:1)",
            "--schedule-render-1",
            "--render-start-1",
            "--render-stop",
            "--commit-start-1",
            "--react-version-<filtered-version>",

cyRender(<div />);
        utils.act(() => store.profilerStore.stopProfiling());

        expect(registeredMarks).toMatchInlineSnapshot(`
          [
            "--react-internal-module-start-  at filtered (<anonymous>:0:0)",


 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
 */

describe('Bridge', () => {
  let Bridge;

  beforeEach(() => {
    Bridge = require('react-devtools-shared/src/bridge').default;
  });

  // @reactVersion >=16.0
  it('should shutdown properly', () => {
    const wall = {
      listen: jest.fn(() => () => {}),
      send: jest.fn(),
    };
    const bridge = new Bridge(wall);
    c

BeenCalledWith('reloadAppForProfiling', undefined);

    // Should flush pending messages and then shut down.
    wall.send.mockClear();
    bridge.send('update', '1');
    bridge.send('update', '2');
    bridge.shutdown();
    jest.runAllTimers();
    exp

onst shutdownCallback = jest.fn();
    bridge.addListener('shutdown', shutdownCallback);

    // Check that we're wired up correctly.
    bridge.send('reloadAppForProfiling');
    jest.runAllTimers();
    expect(wall.send).toHave


, 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
 */

const React = require('react');
const {useEffect, useState} = require('react');

function Component() {
  const countState = useState(0);
  const count = countState[0];
  const setCount = countState[1];

  const darkMode = useIsDarkMode();
  const [isDarkMode, setDarkMode] = darkMode;

  useEffect(() => {
    // ...
  }, []);

  const handle

function useIsDarkMode() {
  const darkModeState = useState(false);
  const [isDarkMode] = darkModeState;

  useEffect(function useEffectCreate() {
    // Here is where we may listen to a "theme" event...
  }, []);

  return [isDarkMode, () => {}];
}

mo

Click = () => setCount(count + 1);

  return null;
}


import {getVersionedRenderImplementation} from './utils';

describe('Fast Refresh', () => {
  let React;
  let ReactFreshRuntime;
  let act;
  let babel;
  let exportsObj;
  let freshPlugin;
  let store;
  let withErrorsOrWarningsIgnored;

  beforeEach(() => {
    global.IS_REACT_ACT_ENVIRONMENT = true;

    exportsObj = undefined;

    babel = require('@babel/core');
    freshPlugin = require('react-refresh/babel');

    store = global.store;

    React = require('react');

    ReactFreshRuntime = require(

: renderImplementation, getContainer} =
    getVersionedRenderImplementation();

  function execute(source) {
    const compiled = babel.transform(source, {
      babelrc: false,
      presets: ['@babel/react'],
      plugins: [
        [freshPlugin, {skip

'react-refresh/runtime');
    ReactFreshRuntime.injectIntoGlobalHook(global);

    const utils = require('./utils');
    act = utils.act;
    withErrorsOrWarningsIgnored = utils.withErrorsOrWarningsIgnored;
  });

  const {render


ng the file to begin with,
// and in some cases we can avoid serializing the source code at all
// (e.g. when we are in an environment that supports our custom metadata format).
//
// The overall flow of this file is such:
// 1. Find the Set of source files defining the hooks and load them all.
//    Then for each source file, do the following:
//
//    a. Search loaded source file to see if a source map is available.
//       If so, load that file and pass it to a Worker for parsing.
//       The source ma

ings in order to map the runtime code to the original source,
//       but at least the eventual source that we parse to an AST is small/fast.
//
//    b. If no source map, pass the full source to a Worker for parsing.
//       Use the source to infer hook

p is used to retrieve the original source,
//       which is then also parsed in the Worker to infer hook names.
//       This is less ideal because parsing a full source map is slower,
//       since we need to evaluate the mapp


left: number, width: number, height: number};

const assign = Object.assign;

// Note that the Overlay components are not affected by the active Theme,
// because they highlight elements in the main Chrome window (outside of devtools).
// The colors below were chosen to roughly match those used by Chrome devtools.

class OverlayRect {
  node: HTMLElement;
  border: HTMLElement;
  padding: HTMLElement;
  content: HTMLElement;

  constructor(doc: Document, container: HTMLElement) {
    this.node = doc.createE

e.borderColor = overlayStyles.padding;
    this.content.style.backgroundColor = overlayStyles.background;

    assign(this.node.style, {
      borderColor: overlayStyles.margin,
      pointerEvents: 'none',
      position: 'fixed',
    });

    this.node.s

lement('div');
    this.border = doc.createElement('div');
    this.padding = doc.createElement('div');
    this.content = doc.createElement('div');

    this.border.style.borderColor = overlayStyles.border;
    this.padding.styl


Stacks = true;
    }
    ReactDOMClient = require('react-dom/client');

    const utils = require('./utils');
    act = utils.act;
  });

  const {render} = getVersionedRenderImplementation();

  // @reactVersion >= 18.0
  it('should pass through logs when there is no current fiber', () => {
    expect(global.consoleLogMock).toHaveBeenCalledTimes(0);
    expect(global.consoleWarnMock).toHaveBeenCalledTimes(0);
    expect(global.consoleErrorMock).toHaveBeenCalledTimes(0);

    console.log('log');
    console

l([['error']]);
  });

  // @reactVersion >= 18.0
  it('should not append multiple stacks', () => {
    global.__REACT_DEVTOOLS_GLOBAL_HOOK__.settings.appendComponentStack = true;

    const Child = ({children}) => {
      console.warn('warn', '\n    in Ch

.warn('warn');
    console.error('error');

    expect(global.consoleLogMock.mock.calls).toEqual([['log']]);
    expect(global.consoleWarnMock.mock.calls).toEqual([['warn']]);
    expect(global.consoleErrorMock.mock.calls).toEqua


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

describe('events', () => {
  let dispatcher;

  beforeEach(() => {
    const EventEmitter = require('../events').default;

    dispatcher = new EventEmitter();
  });

  // @reactVersion >=16
  it('can dispatch an event with no listeners', () => {
    dispatcher.emit('event', 123);
  });

  // @reactVersion >=16
  it('handles a listener being attached multiple times', () => {
    const callback = jest.fn();

);

  // @reactVersion >=16
  it('notifies all attached listeners of events', () => {
    const callback1 = jest.fn();
    const callback2 = jest.fn();
    const callback3 = jest.fn();

    dispatcher.addListener('event', callback1);
    dispatcher.addList

    dispatcher.addListener('event', callback);
    dispatcher.addListener('event', callback);

    dispatcher.emit('event', 123);
    expect(callback).toHaveBeenCalledTimes(1);
    expect(callback).toHaveBeenCalledWith(123);
  }


dren;
      }
    };
  });

  afterEach(() => {
    jest.restoreAllMocks();
  });

  const {render: legacyRender} = getLegacyRenderImplementation();
  const {render: modernRender} = getModernRenderImplementation();
  const {render} = getVersionedRenderImplementation();

  const Contexts = ({
    children,
    defaultInspectedElementID = null,
    defaultInspectedElementIndex = null,
  }) => (
    <BridgeContext.Provider value={bridge}>
      <StoreContext.Provider value={store}>
        <SettingsContextCont

             {children}
            </InspectedElementContextController>
          </TreeContextController>
        </SettingsContextController>
      </StoreContext.Provider>
    </BridgeContext.Provider>
  );

  function useInspectedElement() {
    const

roller>
          <TreeContextController
            defaultInspectedElementID={defaultInspectedElementID}
            defaultInspectedElementIndex={defaultInspectedElementIndex}>
            <InspectedElementContextController>