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 ReactDOMServer;

describe('escapeTextForBrowser', () => {
  beforeEach(() => {
    jest.resetModules();
    React = require('react');
    ReactDOMServer = require('react-dom/server');
  });

  it('ampersand is escaped when passed as text content', () => {
    const response = ReactDOMServer.renderToString(<span>{'&

e).toMatch('"');
  });

  it('single quote is escaped when passed as text content', () => {
    const response = ReactDOMServer.renderToString({"'"});
    expect(response).toMatch(''');
  });

  it('greater

'});
    expect(response).toMatch('&');
  });

  it('double quote is escaped when passed as text content', () => {
    const response = ReactDOMServer.renderToString({'"'});
    expect(respons


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

'use strict';

const ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegrationTestUtils');

let React;
let ReactDOMClient;
let ReactDOMServer;

function initModules() {
  // Reset warning cache.
  jest.resetModules();
  React = require('react');
  ReactDOMClient = require('react-dom/client');
  ReactDOMSe

actDOMServerIntegrationTextarea', () => {
  beforeEach(() => {
    resetModules();
  });

  // textareas
  // ---------
  itRenders('a textarea with a value and an onChange', async render => {
    const e = await render(<textarea value="foo" onChange={() =

rver = require('react-dom/server');

  // Make them available to the helpers.
  return {
    ReactDOMClient,
    ReactDOMServer,
  };
}

const {resetModules, itRenders} = ReactDOMServerIntegrationUtils(initModules);

describe('Re


 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 act;
let assertLog;
let Scheduler;

describe('ReactDOMSafariMicrotaskBug-test', () => {
  let container;
  let overrideQueueMicrotask;
  let flushFakeMicrotasks;

  beforeEach(() => {
    // In Safari, microtasks don't always run on clean stack.
    // This setup crudely approximates it.
    // In reality, the sync flush happens when an iframe

=> {
      if (overrideQueueMicrotask) {
        fakeMicrotaskQueue.push(cb);
      } else {
        originalQueueMicrotask(cb);
      }
    };
    flushFakeMicrotasks = () => {
      while (fakeMicrotaskQueue.length > 0) {
        const cb = fakeMicrotask

is added to the page.
    // https://github.com/facebook/react/issues/22459
    const originalQueueMicrotask = queueMicrotask;
    overrideQueueMicrotask = false;
    const fakeMicrotaskQueue = [];
    global.queueMicrotask = cb


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

'use strict';

const ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegrationTestUtils');

let React;
let ReactDOMClient;
let ReactFeatureFlags;
let ReactDOMServer;

function initModules() {
  // Reset warning cache.
  jest.resetModules();
  React = require('react');
  ReactDOMClient = require('react-dom

tDOMClient,
    ReactDOMServer,
  };
}

const {resetModules, itRenders} = ReactDOMServerIntegrationUtils(initModules);

function formatValue(val) {
  if (val === null) {
    return 'null';
  }
  if (val === undefined) {
    return 'undefined';
  }
  if (ty

/client');
  ReactDOMServer = require('react-dom/server');

  ReactFeatureFlags = require('shared/ReactFeatureFlags');
  ReactFeatureFlags.disableLegacyContext = true;

  // Make them available to the helpers.
  return {
    Reac


ct-core
 */

'use strict';

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

describe('ReactIdentity', () => {
  beforeEach(() => {
    jest.resetModules();
    React = require('react');
    ReactDOMClient = require('react-dom/client');
    act = require('internal-test-utils').act;
    assertConsoleErrorDev =
      require('internal-test-utils').assertConsoleErrorDev;
  });

  it('should allow key property to express identity', async () => {
    let node;
    const Component = props => (

t = ReactDOMClient.createRoot(container);
    await act(async () => {
      root.render(<Component />);
    });
    const origChildren = Array.from(node.childNodes);
    await act(async () => {
      root.render(<Component swap={true} />);
    });
    cons

 (node = c)}>

    );

    const container = document.createElement('div');
    const roo


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

// sanity tests to make sure act() works without a mocked scheduler

let React;
let ReactDOMClient;
let act;
let container;
let yields;
let prevActGlobal;

function clearLog() {
  try {
    return yields;
  } finally {
    yields = [];
  }
}

beforeEach(() => {
  prevActGlobal = global.IS_REACT_ACT_ENVIRONMENT;
  global.IS_REACT_ACT_ENVIRONMENT = true;
  jest.resetModules();
  jest.unmock('sche

global.IS_REACT_ACT_ENVIRONMENT = prevActGlobal;
  document.body.removeChild(container);
});

// @gate __DEV__
test('can use act to flush effects', async () => {
  function App() {
    React.useEffect(() => {
      yields.push(100);
    });
    return null

duler');
  yields = [];
  React = require('react');
  ReactDOMClient = require('react-dom/client');
  act = React.act;
  container = document.createElement('div');
  document.body.appendChild(container);
});

afterEach(() => {


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
 * @jest-environment ./scripts/jest/ReactDOMServerIntegrationEnvironment
 */

'use strict';

const ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegrationTestUtils');
// Set by `yarn test-fire`.
const {disableInputAttributeSyncing} = require('shared/ReactFeatureFlags');

let React;
let ReactDOMClient;
let ReactDOMServer;

functio

rs.
  return {
    ReactDOMClient,
    ReactDOMServer,
  };
}

const {resetModules, itRenders} = ReactDOMServerIntegrationUtils(initModules);

// TODO: Run this in React Fire mode after we figure out the SSR behavior.
const desc = disableInputAttributeSync

n initModules() {
  // Reset warning cache.
  jest.resetModules();
  React = require('react');
  ReactDOMClient = require('react-dom/client');
  ReactDOMServer = require('react-dom/server');

  // Make them available to the helpe


ViewTransition', () => {
  let container;

  beforeEach(() => {
    jest.resetModules();
    React = require('react');
    ReactDOMClient = require('react-dom/client');
    Scheduler = require('scheduler');
    act = require('internal-test-utils').act;
    assertLog = require('internal-test-utils').assertLog;
    Suspense = React.Suspense;
    ViewTransition = React.ViewTransition;
    startTransition = React.startTransition;
    if (gate(flags => flags.enableSuspenseList)) {
      SuspenseList = React.unst

resolveText(text) {
    const record = textCache.get(text);
    if (record === undefined) {
      const newRecord = {
        status: 'resolved',
        value: text,
      };
      textCache.set(text, newRecord);
    } else if (record.status === 'pending'

able_SuspenseList;
    }
    container = document.createElement('div');
    document.body.appendChild(container);

    textCache = new Map();
  });

  afterEach(() => {
    document.body.removeChild(container);
  });

  function


import type {Writable} from 'stream';
import type {Thenable} from 'shared/ReactTypes';

import type {Duplex} from 'stream';

import {Readable} from 'stream';

import {
  createRequest,
  startWork,
  startFlowing,
  startFlowingDebug,
  stopFlowing,
  abort,
  resolveDebugMessage,
  closeDebugChannel,
} from 'react-server/src/ReactFlightServer';

import {
  createResponse,
  reportGlobalError,
  close,
  resolveField,
  resolveFileInfo,
  resolveFileChunk,
  resolveFileComplete,
  getRoot,
} from 'react-ser

// Buffer-based string decoder helpers. The FB server environment does not
// have TextDecoder, so we use Buffer.toString('utf8') instead.
type BufferDecoder = {_pendingBytes: Array<Uint8Array>};

function createStringDecoder(): BufferDecoder {
  return

ver/src/ReactFlightReplyServer';

import {
  decodeAction,
  decodeFormState,
} from 'react-server/src/ReactFlightActionServer';

export {
  registerServerReference,
  registerClientReference,
} from '../ReactFlightFBReferences';


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

// ATTENTION
// When adding new symbols to this file,
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'

// The Symbol used to tag the ReactElement-like types.
export const REACT_LEGACY_ELEMENT_TYPE: symbol = Symbol.for('react.element');
export const REACT_ELEMENT_TYPE: symbol = Symbol.for(
  'react.transitional.element',
);

const REACT_PROFILER_TYPE: symbol = Symbol.for('react.profiler');
export const REACT_CONSUMER_TYPE: symbol = Symbol.for('react.consumer');
export const REACT_CONTEXT_TYPE: symbol = Symbol.for('react.context');
export const REACT_FORWARD_REF_TYPE: symbol =

export const REACT_PORTAL_TYPE: symbol = Symbol.for('react.portal');
export const REACT_FRAGMENT_TYPE: symbol = Symbol.for('react.fragment');
export const REACT_STRICT_MODE_TYPE: symbol = Symbol.for('react.strict_mode');
export


actPortal
  | ReactText
  | ReactFragment
  | ReactProvider<any>
  | ReactConsumer<any>;

export type ReactEmpty = null | void | boolean;

export type ReactFragment = ReactEmpty | Iterable<React$Node>;

export type ReactNodeList = ReactEmpty | React$Node;

export type ReactText = string | number;

export type ReactProvider<T> = {
  $$typeof: symbol | number,
  type: ReactContext<T>,
  key: ReactKey,
  ref: null,
  props: {
    value: T,
    children?: ReactNodeList,
  },
};

export type ReactConsumerType<T>

eactNodeList,
  },
};

export type ReactContext<T> = {
  $$typeof: symbol | number,
  Consumer: ReactConsumerType<T>,
  Provider: ReactContext<T>,
  _currentValue: T,
  _currentValue2: T,
  _threadCount: number,
  // DEV only
  _currentRenderer?: Object |

 = {
  $$typeof: symbol | number,
  _context: ReactContext<T>,
};

export type ReactConsumer<T> = {
  $$typeof: symbol | number,
  type: ReactConsumerType<T>,
  key: ReactKey,
  ref: null,
  props: {
    children: (value: T) => R


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

let didWarnAboutMessageChannel = false;
let enqueueTaskImpl = null;

export default function enqueueTask(task: () => void): void {
  if (enqueueTaskImpl === null) {
    try {
      // read require off the module object to get around the bundlers.
      // we don't want them to detect a require and bundle a Node polyfill.
      cons

rsion of setImmediate, bypassing fake timers if any.
      enqueueTaskImpl = nodeRequire.call(module, 'timers').setImmediate;
    } catch (_err) {
      // we're in a browser
      // we can't use regular timers because they may still be faked
      // so

t requireString = ('require' + Math.random()).slice(0, 7);
      // $FlowFixMe[invalid-computed-prop]
      const nodeRequire = module && module[requireString];
      // assuming we're in node, let's try to get node's
      // ve


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

// Do not require this module directly! Use normal `invariant` calls with
// template literal strings. The messages will be replaced with error codes
// during build.

function formatProdErrorMessage(code) {
  let url = 'https://react.dev/errors/' + code;
  if (arguments.length > 1) {
    url += '?args[]=' + encodeURIComponent(arguments[1]);
    for

= '&args[]=' + encodeURIComponent(arguments[i]);
    }
  }

  return (
    `Minified React error #${code}; visit ${url} for the full message or ` +
    'use the non-minified dev environment for full errors and additional ' +
    'helpful warnings.'
  );
}

(let i = 2; i < arguments.length; i++) {
      url +


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

import type {LazyComponent} from 'react/src/ReactLazy';
import type {ReactContext, ReactConsumerType} from 'shared/ReactTypes';

import {
  REACT_CONTEXT_TYPE,
  REACT_CONSUMER_TYPE,
  REACT_FORWARD_REF_TYPE,
  REACT_FRAGMENT_TYPE,
  REACT_PORTAL_TYPE,
  REACT_MEMO_TYPE,
  REACT_PROFILER_TYPE,
  REACT_STRICT_MODE_TYPE,
  REACT_SUSPENSE_TYPE,
  REACT_SUSPENSE_LIST_TYPE,
  REACT_LAZY_TYPE,
  REACT_TRACING_MAR

ponentNameFromFiber
function getWrappedName(
  outerType: mixed,
  innerType: any,
  wrapperName: string,
): string {
  const displayName = (outerType: any).displayName;
  if (displayName) {
    return displayName;
  }
  const functionName = innerType.disp

KER_TYPE,
  REACT_VIEW_TRANSITION_TYPE,
  REACT_ACTIVITY_TYPE,
} from 'shared/ReactSymbols';

import {
  enableTransitionTracing,
  enableViewTransition,
} from './ReactFeatureFlags';

// Keep in sync with react-reconciler/getCom


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

// Takes a format string (first argument to console) and returns a normalized
// string that has the exact number of arguments as the args. That way it's safe
// to prepend or append to it.
export default function normalizeConsoleFormat(
  formatString: string,
  args: $ReadOnlyArray<mixed>,
  firstArg: number,
): string {
  let j

= firstArg;
  let normalizedString = '';
  let last = 0;
  for (let i = 0; i < formatString.length - 1; i++) {
    if (formatString.charCodeAt(i) !== 37 /* "%" */) {
      continue;
    }
    switch (formatString.charCodeAt(++i))


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

const reportGlobalError: (error: mixed) => void =
  typeof reportError === 'function'
    ? // In modern browsers, reportError will dispatch an error event,
      // emulating an uncaught JavaScript error.
      reportError
    : error => {
        if (
          typeof window === 'object' &&
          typeof window.ErrorEvent ===

-next-line react-internal/safe-string-coercion
                String(error.message)
              : // eslint-disable-next-line react-internal/safe-string-coercion
                String(error);
          const event = new window.ErrorEvent('error', {

'function'
        ) {
          // Browser Polyfill
          const message =
            typeof error === 'object' &&
            error !== null &&
            typeof error.message === 'string'
              ? // eslint-disable


ight (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 is from './objectIs';
import hasOwnProperty from './hasOwnProperty';

/**
 * Performs equality by iterating through keys on an object and returning false
 * when any key has values which are not strictly equal between the arguments.
 * Returns true when the values of all keys are strictly equal.
 */
function sha

}

  const keysA = Object.keys(objA);
  const keysB = Object.keys(objB);

  if (keysA.length !== keysB.length) {
    return false;
  }

  // Test for A's keys different from B.
  for (let i = 0; i < keysA.length; i++) {
    const currentKey = keysA[i];

llowEqual(objA: mixed, objB: mixed): boolean {
  if (is(objA, objB)) {
    return true;
  }

  if (
    typeof objA !== 'object' ||
    objA === null ||
    typeof objB !== 'object' ||
    objB === null
  ) {
    return false;


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

'use strict';

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

    jest.unmock('scheduler');
  });

  // We're just testing importing, not using it.
  // It is important because even isomorphic components may import it.
  it('can import findDOMNode in No

al.window;
    try {
      // Simulate the Node environment:
      delete global.window;
      jest.resetModules();
      expect(() => {
        require('react-dom');
      }).not.toThrow();
    } finally {
      global.window = prevWindow;
    }
  });
});

de environment', () => {
    const prevWindow = glob


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 ReactDOMClient;
let act;

describe('ReactError', () => {
  let globalErrorMock;

  beforeEach(() => {
    if (!__DEV__) {
      // In production, our Jest environment overrides the global Error
      // class in order to decode error messages automatically. However
      // this is a single test where we actually *d

rror;
      expect(typeof global.Error).toBe('function');
    }
    jest.resetModules();
    React = require('react');
    ReactDOMClient = require('react-dom/client');
    act = require('internal-test-utils').act;
  });

  afterEach(() => {
    if (!__DEV

on't* want to decode
      // them. So we assert that the OriginalError exists, and temporarily
      // set the global Error object back to it.
      globalErrorMock = global.Error;
      global.Error = globalErrorMock.OriginalE


ight (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.
 *
 * @emails react-core
 */
'use strict';

let formatProdErrorMessage;

describe('ReactErrorProd', () => {
  beforeEach(() => {
    jest.resetModules();
    formatProdErrorMessage = require('shared/formatProdErrorMessage').default;
  });

  it('should throw with the correct number of `%s`s in the URL', () => {
    expect(formatProdErr

 for full errors and additional helpful warnings.',
    );

    expect(formatProdErrorMessage(20)).toEqual(
      'Minified React error #20; visit ' +
        'https://react.dev/errors/20' +
        ' for the full message or use the non-minified dev enviro

orMessage(124, 'foo', 'bar')).toEqual(
      'Minified React error #124; visit ' +
        'https://react.dev/errors/124?args[]=foo&args[]=bar' +
        ' for the full message or use the non-minified dev environment' +
        '


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

'use strict';

let normalizeConsoleFormat;

describe('normalizeConsoleFormat', () => {
  beforeEach(() => {
    normalizeConsoleFormat = require('shared/normalizeConsoleFormat').default;
  });

  it('normalize empty string', async () => {
    expect(normalizeConsoleFormat('', [1, {}, 'foo'], 0)).toMatchInl

than args', async () => {
    expect(
      normalizeConsoleFormat('%s %O %o %f', [1, {}, 'foo'], 0),
    ).toMatchInlineSnapshot(`"%s %O %o %%f"`);
  });

  it('normalize escape sequences', async () => {
    expect(
      normalizeConsoleFormat('hel%lo %s

ineSnapshot(
      `"%o %o %s"`,
    );
  });

  it('normalize extra args', async () => {
    expect(
      normalizeConsoleFormat('%f', [1, {}, 'foo'], 0),
    ).toMatchInlineSnapshot(`"%f %o %s"`);
  });

  it('normalize fewer


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

// This fork provides www-specific feature flag values for
// eslint-plugin-react-hooks without pulling in the full
// ReactFeatureFlags.www.js fork. The full fork imports dynamic flags
// via require('ReactFeatureFlags'), which is a www Haste module that
// doesn't exist in Node.js environments where the ESLint plugin runs.
//
// Only eprh_* fla

rh_enableUseKeyedStateCompilerLint: boolean = true;
export const eprh_enableVerboseNoSetStateInEffectCompilerLint: boolean = true;
export const eprh_enableExhaustiveEffectDependenciesCompilerLint:
  | 'off'
  | 'all'
  | 'extra-only'
  | 'missing-only' = '

gs are needed by the ESLint plugin.

export const ep


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

// In xplat, these flags are controlled by GKs. Because most GKs have some
// population running in either mode, we should run our tests that way, too,
//
// Use __VARIANT__ to simulate a GK. The tests will be run twice: once
// with the __VARIANT__ set to `true`, and once set to `false`.
//
// TODO: __VARIANT__

T__;
export const enableObjectFiber = __VARIANT__;
export const enableEagerAlternateStateNodeCleanup = __VARIANT__;
export const passChildrenWhenCloningPersistedNodes = __VARIANT__;
export const enableFragmentRefs = __VARIANT__;
export const enableFragment

 isn't supported for React Native flags yet. You can set the
// flag here but it won't be set to `true` in any of our test runs. Need to
// add a test configuration for React Native.

export const alwaysThrottleRetries = __VARIAN


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

import typeof * as FeatureFlagsType from 'shared/ReactFeatureFlags';
import typeof * as ExportsType from './ReactFeatureFlags.native-fb';
import typeof * as DynamicExportsType from './ReactFeatureFlags.native-fb-dynamic';

// Re-export dynamic flags from the internal module.
// Intentionally using * because this import is compiled to a `require` call.
import * as dynamicFlagsUntyped from 'ReactNativeInterna

  alwaysThrottleRetries,
  enableEffectEventMutationPhase,
  enableObjectFiber,
  enableEagerAlternateStateNodeCleanup,
  passChildrenWhenCloningPersistedNodes,
  enableFragmentRefs,
  enableFragmentRefsScrollIntoView,
  enableFragmentRefsInstanceHandles,

lFeatureFlags';
const dynamicFlags: DynamicExportsType = (dynamicFlagsUntyped: any);

// We destructure each value before re-exporting to avoid a dynamic look-up on
// the exports object every time a flag is read.
export const {


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

import typeof * as FeatureFlagsType from 'shared/ReactFeatureFlags';
import typeof * as ExportsType from './ReactFeatureFlags.native-oss';

// TODO: Align these flags with canary and delete this file once RN ships from Canary.

// -----------------------------------------------------------------------------
// All flags
// -----------------------------------------------------------------------------
export

disableLegacyContext: boolean = true;
export const disableLegacyContextForFunctionComponents: boolean = true;
export const disableLegacyMode: boolean = false;
export const disableSchedulerTimeoutInWorkLoop: boolean = false;
export const disableTextareaChil

const alwaysThrottleRetries: boolean = false;
export const disableClientCache: boolean = true;
export const disableCommentsAsDOMContainers: boolean = true;
export const disableInputAttributeSyncing: boolean = false;
export const


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

import typeof * as FeatureFlagsType from 'shared/ReactFeatureFlags';
import typeof * as ExportsType from './ReactFeatureFlags.test-renderer';

export const enableAsyncDebugInfo: boolean = true;
export const enableSchedulingProfiler: boolean = false;
export const enableProfilerTimer: boolean = __PROFILE__;
export const enableProfilerCommitHooks: boolean = __PROFILE__;
export const enableProfilerNestedUpdateP

acyCache: boolean = __EXPERIMENTAL__;
export const enableAsyncIterableChildren: boolean = false;
export const enableTaint: boolean = true;
export const disableCommentsAsDOMContainers: boolean = true;
export const disableInputAttributeSyncing: boolean = fal

hase: boolean = __PROFILE__;
export const enableComponentPerformanceTrack: boolean = true;
export const enablePerformanceIssueReporting: boolean = false;
export const enableUpdaterTracking: boolean = false;
export const enableLeg


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

import typeof * as FeatureFlagsType from 'shared/ReactFeatureFlags';
import typeof * as ExportsType from './ReactFeatureFlags.test-renderer';

export const alwaysThrottleRetries = false;
export const disableClientCache = true;
export const disableCommentsAsDOMContainers = true;
export const disableInputAttributeSyncing = false;
export const disableLegacyContext = false;
export const disableLegacyContextForF

eAsyncIterableChildren = false;
export const enableCPUSuspense = true;
export const enableCreateEventHandleAPI = false;
export const enableMoveBefore = false;
export const enableFizzExternalRuntime = true;
export const enableInfiniteRenderLoopDetection = f

unctionComponents = false;
export const disableLegacyMode = false;
export const disableSchedulerTimeoutInWorkLoop = false;
export const disableTextareaChildren = false;
export const enableAsyncDebugInfo = true;
export const enabl


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

import typeof * as FeatureFlagsType from 'shared/ReactFeatureFlags';
import typeof * as ExportsType from './ReactFeatureFlags.test-renderer.www';

export const enableAsyncDebugInfo: boolean = true;
export const enableSchedulingProfiler: boolean = false;
export const enableProfilerTimer: boolean = __PROFILE__;
export const enableProfilerCommitHooks: boolean = __PROFILE__;
export const enableProfilerNestedUpd

leLegacyCache: boolean = true;
export const enableAsyncIterableChildren: boolean = false;
export const enableTaint: boolean = true;
export const disableCommentsAsDOMContainers: boolean = true;
export const disableInputAttributeSyncing: boolean = false;
exp

atePhase: boolean = __PROFILE__;
export const enableComponentPerformanceTrack: boolean = false;
export const enablePerformanceIssueReporting: boolean = false;
export const enableUpdaterTracking: boolean = false;
export const enab


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

// In www, these flags are controlled by GKs. Because most GKs have some
// population running in either mode, we should run our tests that way, too,
//
// Use __VARIANT__ to simulate a GK. The tests will be run twice: once
// with the __VARIANT__ set to `true`, and once set to `false`.

export const alwaysThrottleRetries: boolean = __VARIANT__;
expo

jectFiber: boolean = __VARIANT__;
export const enableRetryLaneExpiration: boolean = __VARIANT__;
export const enableTransitionTracing: boolean = __VARIANT__;
export const retryLaneExpirationMs = 5000;
export const syncLaneExpirationMs = 250;
export const t

rt const disableLegacyContextForFunctionComponents: boolean = __VARIANT__;
export const disableSchedulerTimeoutInWorkLoop: boolean = __VARIANT__;
export const enableNoCloningMemoCache: boolean = __VARIANT__;
export const enableOb


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

import typeof * as FeatureFlagsType from 'shared/ReactFeatureFlags';
import typeof * as ExportsType from './ReactFeatureFlags.www';
import typeof * as DynamicFeatureFlags from './ReactFeatureFlags.www-dynamic';

// Re-export dynamic flags from the www version.
const dynamicFeatureFlags: DynamicFeatureFlags = require('ReactFeatureFlags');

export const {
  alwaysThrottleRetries,
  disableLegacyContextForFunc

etryLaneExpiration,
  enableTransitionTracing,
  retryLaneExpirationMs,
  syncLaneExpirationMs,
  transitionLaneExpirationMs,
  enableSuspenseyImages,
  enableViewTransition,
  enableScrollEndPolyfill,
  enableFragmentRefs,
  enableFragmentRefsScrollIntoVi

tionComponents,
  disableSchedulerTimeoutInWorkLoop,
  enableEffectEventMutationPhase,
  enableInfiniteRenderLoopDetection,
  enableInfiniteRenderLoopDetectionForceThrow,
  enableNoCloningMemoCache,
  enableObjectFiber,
  enableR


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

import {useSyncExternalStore} from 'use-sync-external-store/shim';

// Hook used for safely managing subscriptions in concurrent mode.
//
// In order to avoid removing and re-adding subscriptions each time this hook is called,
// the parameters passed to this hook should be memoized in some way–
// either by w

entValue,

  // This function is passed an event handler to attach to the subscription.
  // It should return an unsubscribe function that removes the handler.
  subscribe,
}: {
  getCurrentValue: () => Value,
  subscribe: (callback: Function) => () => voi

rapping the entire params object with useMemo()
// or by wrapping the individual callbacks with useCallback().
export function useSubscription<Value>({
  // (Synchronously) returns the current value of our subscription.
  getCurr


require('rxjs').BehaviorSubject;
    ReplaySubject = require('rxjs').ReplaySubject;

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

  function createBehaviorSubject(initialValue) {
    const behaviorSubject = new BehaviorSubject();
    if (initialValue) {
      behaviorSubject.next(initialValue);
    }

t('supports basic subscription pattern', async () => {
    function Child({value = 'default'}) {
      Scheduler.log(value);
      return null;
    }

    function Subscription({source}) {
      const value = useSubscription(
        React.useMemo(

  return behaviorSubject;
  }

  function createReplaySubject(initialValue) {
    const replaySubject = new ReplaySubject();
    if (initialValue) {
      replaySubject.next(initialValue);
    }
    return replaySubject;
  }

  i


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

import {REACT_ELEMENT_TYPE, REACT_FRAGMENT_TYPE} from 'shared/ReactSymbols';
const {assertConsoleLogsCleared} = require('internal-test-utils/consoleMock');

import isArray from 'shared/isArray';

function captureAssertion(fn) {
  // Trick to use a Jest matcher inside another Jest matcher. `fn` contains an
  // assertion; if it throws, we capture the error and return it, so the stack
  // trace presented to the user poi

root) {
  const Scheduler = root._Scheduler;
  const actualYields = Scheduler.unstable_clearLog();
  if (actualYields.length !== 0) {
    const error = Error(
      'Log of yielded values is not empty. ' +
        'Call expect(ReactTestRenderer).unstable_t

nts to the original assertion in the
  // test file.
  try {
    fn();
  } catch (error) {
    return {
      pass: false,
      message: () => error.message,
    };
  }
  return {pass: true};
}

function assertYieldsWereCleared(


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

import * as Scheduler from 'scheduler';

// Intentionally not named imports because Rollup would
// use dynamic dispatch for CommonJS interop named imports.
const {
  unstable_scheduleCallback: scheduleCallback,
  unstable_IdlePriority: IdlePriority,
} = Scheduler;

type Entry<T> = {
  value: T,
  onDelete: () => mixed,
  previous: Entry<T>,
  next: Entry<T>,
};

type LRU<T> = {
  add(value: Object, onDelet

Circular, doubly-linked list
  let first: Entry<T> | null = null;
  let size: number = 0;

  let cleanUpIsScheduled: boolean = false;

  function scheduleCleanUp() {
    if (cleanUpIsScheduled === false && size > LIMIT) {
      // The cache size exceeds th

e: () => mixed): Entry<Object>,
  update(entry: Entry<T>, newValue: T): void,
  access(entry: Entry<T>): T,
  setLimit(newLimit: number): void,
};

export function createLRU<T>(limit: number): LRU<T> {
  let LIMIT = limit;

  //


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

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

import * as React from 'react';

import {createLRU} from './LRU';

interface Suspender {
  then(resolve: () => mixed, reject: () => mixed): mixed;
}

type PendingResult = {
  status: 0,
  value: Suspender,
};

type ResolvedResult<V> = {
  status: 1,
  value: V,
};

type RejectedResult = {
  status: 2,
  value: mixed,
};

type Result<V> = Pendin

NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;

function readContext(Context: ReactContext<mixed>) {
  const dispatcher = SharedInternals.H;
  if (dispatcher === null) {
    // This wasn't being minified but we're going to retire this package anyway.
    // es

gResult | ResolvedResult<V> | RejectedResult;

type Resource<I, V> = {
  read(I): V,
  preload(I): void,
  ...
};

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

const SharedInternals =
  React.__CLIENT_INTERNALS_DO_


sertLog;
let waitForThrow;
let act;
let assertConsoleErrorDev;

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

    React = require('react');
    Suspense = React.Suspense;
    ReactCache = require('react-cache');
    createResource = ReactCache.unstable_createResource;
    ReactNoop = require('react-noop-renderer');
    Scheduler = require('scheduler');

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

act;

    TextResource = createResource(
      ([text, ms = 0]) => {
        let listeners = null;
        let status = 'pending';
        let value = null;
        return {
          then(resolve, reject) {
            switch (status) {
              case

 InternalTestUtils.assertLog;
    waitForThrow = InternalTestUtils.waitForThrow;
    waitForPaint = InternalTestUtils.waitForPaint;
    assertConsoleErrorDev = InternalTestUtils.assertConsoleErrorDev;
    act = InternalTestUtils.


 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 * from './ReactFiberConfigNoopHydration';
export * from './ReactFiberConfigNoopScopes';
export * from './ReactFiberConfigNoopTestSelectors';
export * from './ReactFiberConfigNoopResources';
export * from './ReactFiberConfigNoopSingletons';
// createReactNoop will overwrite these with the mutation or persis

r,
  hidden: boolean,
  context: HostContext,
};

export type Instance = {
  type: string,
  id: number,
  parent: number,
  children: Array<Instance | TextInstance>,
  text: string | null,
  prop: any,
  hidden: boolean,
  context: HostContext,
};

export

tence versions.
export * from './ReactFiberConfigNoopNoMutation';
export * from './ReactFiberConfigNoopNoPersistence';

export type HostContext = Object;

export type TextInstance = {
  text: string,
  id: number,
  parent: numbe


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

// Renderers that don't support hydration
// can re-export everything from this module.

function shim(...args: any): empty {
  throw new Error(
    'react-noop-renderer does not support hydration. ' +
      'This error is likely caused by a bug in React. ' +
      'Please file an issue.',
  );
}

// Hydration (when unsupported)
export type ActivityInstance

etails = shim;
export const registerSuspenseInstanceRetry = shim;
export const canHydrateFormStateMarker = shim;
export const isFormStateMarkerMatching = shim;
export const getNextHydratableSibling = shim;
export const getNextHydratableSiblingAfterSingleto

 = mixed;
export type SuspenseInstance = mixed;
export const supportsHydration = false;
export const isSuspenseInstancePending = shim;
export const isSuspenseInstanceFallback = shim;
export const getSuspenseInstanceFallbackErrorD


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

import type {ReactClientValue} from 'react-server/src/ReactFlightServer';

export type ServerReference<T: Function> = T & {
  $$typeof: symbol,
  $$id: string,
  $$bound: null | Array<ReactClientValue>,
  $$location?: Error,
};

// eslint-disable-next-line no-unused-vars
export type ClientReference<T> = {
  $$typeof: symbol,
  $$id: string,
  $$hblp: mixed,
};

const CLIENT_REFERENCE_TAG = Symbol.for('react

erverReference(reference: Object): boolean {
  return reference.$$typeof === SERVER_REFERENCE_TAG;
}

export function registerClientReference<T>(
  proxyImplementation: any,
  id: string,
  hblp: mixed,
): ClientReference<T> {
  return Object.definePropert

.client.reference');
const SERVER_REFERENCE_TAG = Symbol.for('react.server.reference');

export function isClientReference(reference: Object): boolean {
  return reference.$$typeof === CLIENT_REFERENCE_TAG;
}

export function isS


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

// Renderers that don't support mutation
// can re-export everything from this module.

function shim(...args: any): empty {
  throw new Error(
    'This entrypoint of react-noop-renderer does not support mutation. ' +
      'This error is likely caused by a bug in React. ' +
      'Please file an issue.',
  );
}

// Mutation (when unsupported)
export const

export const commitMount = shim;
export const commitUpdate = shim;
export const insertBefore = shim;
export const insertInContainerBefore = shim;
export const removeChild = shim;
export const removeChildFromContainer = shim;
export const resetTextContent

 supportsMutation = false;
export const cloneMutableInstance = shim;
export const cloneMutableTextInstance = shim;
export const appendChild = shim;
export const appendChildToContainer = shim;
export const commitTextUpdate = shim;


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

// Renderers that don't support persistence
// can re-export everything from this module.

function shim(...args: any): empty {
  throw new Error(
    'This entrypoint of react-noop-renderer does not support persistence. ' +
      'This error is likely caused by a bug in React. ' +
      'Please file an issue.',
  );
}

// Persistence (when

e;
export const cloneInstance = shim;
export const createContainerChildSet = shim;
export const appendChildToContainerChildSet = shim;
export const finalizeContainerChildren = shim;
export const replaceContainerChildren = shim;
export const cloneHiddenInst

unsupported)
export const supportsPersistence = fals


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

// Renderers that don't support hydration
// can re-export everything from this module.

function shim(...args: any): empty {
  throw new Error(
    'react-noop-renderer does not support Resources. ' +
      'This error is likely caused by a bug in React. ' +
      'Please file an issue.',
  );
}

export type Hoi

shim;
export const acquireResource = shim;
export const releaseResource = shim;
export const hydrateHoistable = shim;
export const mountHoistable = shim;
export const unmountHoistable = shim;
export const createHoistableInstance = shim;
export const prepar

stableRoot = mixed;
export type Resource = mixed;

// Resources (when unsupported)
export const supportsResources = false;
export const isHostHoistableType = shim;
export const getHoistableRoot = shim;
export const getResource =


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

import type {ModuleLoading} from 'react-client/src/ReactFlightClientConfig';

import {canUseDOM} from 'shared/ExecutionEnvironment';

export type ServerConsumerModuleMap = null;

export type ServerManifest = null;

export type ServerReferenceId = string;

import {prepareDestinationForModuleImpl} from 'react-client/src/ReactFlightClientConfig';

export opaque type

xport function prepareDestinationForModule(
  moduleLoading: ModuleLoading,
  nonce: ?string,
  metadata: ClientReferenceMetadata,
) {
  prepareDestinationForModuleImpl(moduleLoading, metadata.$$hblp, nonce);
}

export function resolveClientReference<T>(

 ClientReferenceMetadata = {
  $$typeof: symbol,
  $$id: string,
  $$hblp: mixed,
};

// eslint-disable-next-line no-unused-vars
export opaque type ClientReference<T> = {
  $$typeof: symbol,
  $$id: string,
  $$hblp: mixed,
};

e


import type {Thenable} from 'shared/ReactTypes.js';

import type {
  DebugChannel,
  DebugChannelCallback,
  FindSourceMapURLCallback,
  Response as FlightResponse,
} from 'react-client/src/ReactFlightClient';

import type {ReactServerValue} from 'react-client/src/ReactFlightReplyClient';

import {
  createResponse,
  createStreamState,
  getRoot,
  reportGlobalError,
  processBinaryChunk,
  processStringChunk,
  close,
  injectIntoDevTools,
} from 'react-client/src/ReactFlightClient';

import {processReply

ightTemporaryReferences';

export {createTemporaryReferenceSet} from 'react-client/src/ReactFlightTemporaryReferences';

export type {TemporaryReferenceSet};

type CallServerCallback = <A, T>(string, args: A) => Promise<T>;

export type Options = {
  callS

} from 'react-client/src/ReactFlightReplyClient';

export {
  createServerReference,
  registerServerReference,
} from 'react-client/src/ReactFlightReplyClient';

import type {TemporaryReferenceSet} from 'react-client/src/ReactFl


 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 type {ReactComponentInfo} from 'shared/ReactTypes';

import {describeBuiltInComponentFrame} from 'shared/ReactComponentStackFrame';

import {formatOwnerStack} from 'shared/ReactOwnerStackFrames';

export function getOwnerStackByComponentInfoInDev(
  componentInfo: ReactComponentInfo,
): string {
  if (!__DEV__) {
    return

le
    // on the regular stack that's currently executing. However, if there is no owner at all, then
    // there's no stack frame so we add the name of the root component to the stack to know which
    // component is currently executing.
    if (!compon

'';
  }
  try {
    let info = '';

    // The owner stack of the current component will be where it was created, i.e. inside its owner.
    // There's no actual name of the currently executing component. Instead, that is availab


iates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * Shared logic for Fragment Ref operations for DOM and Fabric configs
 *
 * @flow
 */

import type {Fiber} from 'react-reconciler/src/ReactInternalTypes';

import {getNextSiblingHostFiber} from 'react-reconciler/src/ReactFiberTreeReflection';

export function compareDocumentPositionForEmptyFragment<TPublicInstance>(
  fragmentFiber: Fiber,
  parentHostInstance: TPublicI

$FlowFixMe[incompatible-use] Fabric PublicInstance is opaque
  // $FlowFixMe[prop-missing]
  const parentResult = parentHostInstance.compareDocumentPosition(otherNode);
  result = parentResult;
  if (parentHostInstance === otherNode) {
    result = Node.DO

nstance,
  otherNode: TPublicInstance,
  getPublicInstance: (fiber: Fiber) => TPublicInstance,
): number {
  let result;
  // If the fragment has no children, we can use the parent and
  // siblings to determine a position.
  //


-------

// Need to remove didTimeout argument from Scheduler before landing
export const disableSchedulerTimeoutInWorkLoop: boolean = false;

// -----------------------------------------------------------------------------
// Slated for removal in the fut

erate effort)
//
// Flags that can be probably deleted or landed, but might require extra effort
// like migrating internal callers or performance testing.
// ----------------------------------------------------------------------


ight (c) Meta Platforms, Inc. and its 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 ReactSharedInternals from 'shared/ReactSharedInternals';

let lastResetTime = 0;

let getCurrentTime: () => number | DOMHighResTimeStamp;
const hasPerformanceNow =
  // $FlowFixMe[method-unbinding]
  typeof performance === 'object' && typeof performance.now === 'function';

if (hasPerformanceNow) {
  const l

ow = getCurrentTime();
    const timeSinceLastReset = now - lastResetTime;
    if (timeSinceLastReset > 1000) {
      ReactSharedInternals.recentlyCreatedOwnerStacks = 0;
      lastResetTime = now;
    }
  } else {
    // These errors should never make it

ocalPerformance = performance;
  getCurrentTime = () => localPerformance.now();
} else {
  const localDate = Date;
  getCurrentTime = () => localDate.now();
}

export function resetOwnerStackLimit() {
  if (__DEV__) {
    const n


import type {LazyComponent} from 'react/src/ReactLazy';

import isArray from 'shared/isArray';
import getPrototypeOf from 'shared/getPrototypeOf';

import {enableViewTransition} from 'shared/ReactFeatureFlags';

// Used for DEV messages to keep track of which parent rendered some props,
// in case they error.
export const jsxPropsParents: WeakMap<any, any> = new WeakMap();
export const jsxChildrenParents: WeakMap<any, any> = new WeakMap();

function isObjectPrototype(object: any): boolean {
  if (!object)

(getPrototypeOf(object)) {
    return false;
  }
  const names = Object.getOwnPropertyNames(object);
  for (let i = 0; i < names.length; i++) {
    if (!(names[i] in ObjectPrototype)) {
      return false;
    }
  }
  return true;
}

export function isGett

 {
    return false;
  }
  const ObjectPrototype = Object.prototype;
  if (object === ObjectPrototype) {
    return true;
  }
  // It might be an object from a different Realm which is
  // still just a plain simple object.
  if


ight (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 type {ReactNodeList} from 'shared/ReactTypes';

import {version, renderToStringImpl} from './ReactDOMLegacyServerImpl';

type ServerOptions = {
  identifierPrefix?: string,
};

function renderToString(
  children: ReactNodeList,
  options?: ServerOptions,
): string {
  return renderToStringImpl(
    children,

Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToPipeableStream" which supports Suspense on the server',
  );
}

function renderToStaticMarkup(
  children: ReactNodeList,
  options?: ServerOpt

  options,
    false,
    'The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the


iates.
 *
 * 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 defaultOnDefaultTransitionIndicator(): void | (() => void) {
  if (typeof navigation !== 'object') {
    // If the Navigation API is not available, then this is a noop.
    return;
  }

  let isCancelled = false;
  let pendingResolve: null | (() => void) = null;

  function handleNavigate(event: NavigateEvent) {
    if (event.canIntercept &&

   }
  }

  function handleNavigateComplete() {
    if (pendingResolve !== null) {
      // If this was not our navigation completing, we were probably cancelled.
      // We'll start a new one below.
      pendingResolve();
      pendingResolve = null;

 event.info === 'react-transition') {
      event.intercept({
        handler() {
          return new Promise(resolve => (pendingResolve = resolve));
        },
        focusReset: 'manual',
        scroll: 'manual',
      });


tInternalTypes';

import type {
  Container,
  PublicInstance,
} from 'react-dom-bindings/src/client/ReactFiberConfigDOM';

import {
  createRoot as createRootImpl,
  hydrateRoot as hydrateRootImpl,
} from './ReactDOMRoot';

import {
  disableLegacyMode,
  disableCommentsAsDOMContainers,
} from 'shared/ReactFeatureFlags';
import {clearContainer} from 'react-dom-bindings/src/client/ReactFiberConfigDOM';
import {
  getInstanceFromNode,
  isContainerMarkedAsRoot,
  markContainerAsRoot,
  unmarkContainerAsRoot,

ontainer';
import {
  DOCUMENT_NODE,
  ELEMENT_NODE,
  COMMENT_NODE,
} from 'react-dom-bindings/src/client/HTMLNodeType';

import {
  batchedUpdates,
  createContainer,
  createHydrationContainer,
  findHostInstanceWithNoPortals,
  updateContainer,
  updat

} from 'react-dom-bindings/src/client/ReactDOMComponentTree';
import {listenToAllSupportedEvents} from 'react-dom-bindings/src/events/DOMPluginEventSystem';
import {isValidContainer} from 'react-dom-bindings/src/client/ReactDOMC


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';

// TODO: can we express this test with only public API?
const getNodeForCharacterOffset =
  require('react-dom-bindings/src/client/getNodeForCharacterOffset').default;

// Create node from HTML string
function createNode(html) {
  const node = (getTestDocument() || document).createElement('div');
  node.innerHTML = html;
  return

doc.close();
  return doc;
}

// Check getNodeForCharacterOffset return value matches expected result.
function expectNodeOffset(result, textContent, nodeOffset) {
  expect(result.node.textContent).toBe(textContent);
  expect(result.offset).toBe(nodeOffset

 node;
}

function getTestDocument(markup) {
  const doc = document.implementation.createHTMLDocument('');
  doc.open();
  doc.write(
    markup ||
      '<!doctype html><html><meta charset=utf-8><title>test doc</title>',
  );


use strict';

async function insertNodesAndExecuteScripts(
  source: Document | Element,
  target: Node,
  CSPnonce: string | null,
) {
  const ownerDocument = target.ownerDocument || target;

  // We need to remove the script content for any scripts that would not run based on CSP
  // We restore the script content after moving the nodes into the target
  const badNonceScriptNodes: Map<Element, string> = new Map();
  if (CSPnonce) {
    const scripts = source.querySelectorAll('script');
    for (let i = 0;

);
        script.textContent = '';
      }
    }
  }
  let lastChild = null;
  while (source.firstChild) {
    const node = source.firstChild;
    if (lastChild === node) {
      throw new Error('Infinite loop.');
    }
    lastChild = node;

    if (node

 i < scripts.length; i++) {
      const script = scripts[i];
      if (
        !script.hasAttribute('src') &&
        script.getAttribute('nonce') !== CSPnonce
      ) {
        badNonceScriptNodes.set(script, script.textContent


;

function checkDCE() {
  /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
  if (
    typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' ||
    typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function'
  ) {
    return;
  }
  if (process.env.NODE_ENV !== 'production') {
    // This branch is unreachable because this function is only called
    // in production, but the condition is true only in development.
    // Therefore if the branch is still here, dead code elimination wasn't
    // properly applied

 Verify that the code above has been dead code eliminated (DCE'd).
    __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);
  } catch (err) {
    // DevTools shouldn't crash React, no matter what.
    // We should still report in case we break this code.

.
    // Don't change the message. React DevTools relies on it. Also make sure
    // this message doesn't occur elsewhere in this function, or it will cause
    // a false positive.
    throw new Error('^_^');
  }
  try {
    //


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

// Custom implementation of FlightServerConfigDOM.
// Resource hint dispatching is a no-op since we handle resource loading
// through our own runtime.

// We keep the same type definitions so the Flight server protocol is compatible.

// prettier-ignore
type TypeMap = {
  'D': string,
  'C': string | [string, st

tCode = $Keys<TypeMap>;
export type HintModel<T: HintCode> = TypeMap[T];

export type Hints = Set<string>;

export function createHints(): Hints {
  return new Set();
}

export opaque type FormatContext = number;

export function createRootFormatContext():

ring],
  'L': [string, string] | [string, string, any],
  'm': string | [string, any],
  'S': string | [string, string] | [string, string | 0, any],
  'X': string | [string, any],
  'M': string | [string, any],
}

export type Hin


ight (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 type {ReactClientValue} from 'react-server/src/ReactFlightServer';

import type {
  ClientReference,
  ServerReference,
} from '../ReactFlightFBReferences';

export type {ClientReference, ServerReference};

export type ClientManifest = null;

export type ServerReferenceId = string;

export type ClientReferenceMe

): ClientReferenceKey {
  return reference.$$id;
}

export function resolveClientReferenceMetadata<T>(
  config: ClientManifest,
  clientReference: ClientReference<T>,
): ClientReferenceMetadata {
  return clientReference;
}

export function getServerRefe

tadata = ClientReference<any>;

export type ClientReferenceKey = string;

export {isClientReference, isServerReference} from '../ReactFlightFBReferences';

export function getClientReferenceKey(
  reference: ClientReference<any>,


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

// Helpers to patch console.logs to avoid logging during side-effect free
// replaying on render function. This currently only patches the object
// lazily which won't cover if the log function was extracted eagerly.
// We could also eagerly patch the method.

let disabledDepth = 0;
let prevLog;
let prevInfo;
let prevWarn;
let prevError;
let prevGroup;
let

/no-production-logging */
      prevLog = console.log;
      prevInfo = console.info;
      prevWarn = console.warn;
      prevError = console.error;
      prevGroup = console.group;
      prevGroupCollapsed = console.groupCollapsed;
      prevGroupEnd = c

prevGroupCollapsed;
let prevGroupEnd;

function disabledLog() {}
disabledLog.__reactDisabledLog = true;

export function disableLogs(): void {
  if (__DEV__) {
    if (disabledDepth === 0) {
      /* eslint-disable react-internal


iates.
 *
 * 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 getIODescription(value: mixed): string {
  if (!__DEV__) {
    return '';
  }
  try {
    switch (typeof value) {
      case 'function':
        return value.name || '';
      case 'object':
        // Test the object for a bunch of common property names that are useful identifiers.
        // While we only have the return value here, it sho

ring-coercion
          return String(value.message);
        } else if (typeof value.url === 'string') {
          return value.url;
        } else if (typeof value.href === 'string') {
          return value.href;
        } else if (typeof value.src ===

uld ideally be a name that
        // describes the arguments requested.
        if (value === null) {
          return '';
        } else if (value instanceof Error) {
          // eslint-disable-next-line react-internal/safe-st


ols';
import getComponentNameFromType from './getComponentNameFromType';

const EMPTY_ARRAY = 0;
const COMPLEX_ARRAY = 1;
const PRIMITIVE_ARRAY = 2; // Primitive values only that are accepted by JSON.stringify
const ENTRIES_ARRAY = 3; // Tuple arrays of string and value (like Headers, Map, etc)

// Showing wider objects in the devtools is not useful.
const OBJECT_WIDTH_LIMIT = 100;

function getArrayKind(array: Object): 0 | 1 | 2 | 3 {
  let kind: 0 | 1 | 2 | 3 = EMPTY_ARRAY;
  for (let i = 0; i < array.len

  ) {
        // Key value tuple
        if (kind !== EMPTY_ARRAY && kind !== ENTRIES_ARRAY) {
          return COMPLEX_ARRAY;
        }
        kind = ENTRIES_ARRAY;
      } else {
        return COMPLEX_ARRAY;
      }
    } else if (typeof value === 'fun

gth && i < OBJECT_WIDTH_LIMIT; i++) {
    const value = array[i];
    if (typeof value === 'object' && value !== null) {
      if (
        isArray(value) &&
        value.length === 2 &&
        typeof value[0] === 'string'


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 {createRoot, hydrateRoot} from './ReactDOMRoot';

import {
  injectIntoDevTools,
  findHostInstance,
} from 'react-reconciler/src/ReactFiberReconciler';
import {canUseDOM} from 'shared/ExecutionEnvironment';
import ReactVersion from 'shared/ReactVersion';

import Internals from 'shared/ReactDOMSharedInternals';

import {ensureCorrectIsomorphicReactVe

ype
    Map.prototype == null ||
    typeof Map.prototype.forEach !== 'function' ||
    typeof Set !== 'function' ||
    // $FlowFixMe[prop-missing] Flow incorrectly thinks Set has no prototype
    Set.prototype == null ||
    typeof Set.prototype.clear !=

rsion} from '../shared/ensureCorrectIsomorphicReactVersion';
ensureCorrectIsomorphicReactVersion();

if (__DEV__) {
  if (
    typeof Map !== 'function' ||
    // $FlowFixMe[prop-missing] Flow incorrectly thinks Map has no protot


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

'use strict';

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

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

describe('dangerouslySetInnerHTML', () => {
  describe('when the node has innerHTML property', () => {
    it('sets innerHTML on it', async () => {
      const con

root = ReactDOMClient.createRoot(container);
      await act(() => {
        root.render(
          ,
        );
      });
      expect(container.firstChild.innerHTML).toBe('
Hello
');

tainer = document.createElement('div');
      const


// Fork of ReactServerStreamConfigNode for the FB Flight server.
// Avoids importing from 'util' and 'crypto'. Uses the global TextEncoder
// and stubs createFastHash.

import type {Writable} from 'stream';

import type {TextEncoder as TextEncoderType} from 'util';

interface MightBeFlushable {
  flush?: () => void;
}

export type Destination = Writable & MightBeFlushable;

export type PrecomputedChunk = Uint8Array;
export opaque type Chunk = string;
export type BinaryChunk = Uint8Array;

export function sc

 don't have any more data to send right now.
  // Flush whatever is in the buffer to the wire.
  if (typeof destination.flush === 'function') {
    // By convention the Zlib streams provide a flush function for this purpose.
    // For Express, compression

heduleWork(callback: () => void) {
  setImmediate(callback);
}

export function scheduleMicrotask(callback: () => void) {
  Promise.resolve().then(callback);
}

export function flushBuffered(destination: Destination) {
  // If we


/*
 * The `'' + value` pattern (used in perf-sensitive code) throws for Symbol
 * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
 *
 * The functions in this module will throw an easier-to-understand,
 * easier-to-debug exception with a clear errors message message explaining the
 * problem. (Instead of a confusing exception thrown inside the implementation
 * of the `value` object).
 */

// $FlowFixMe[incompatible-return] only called in DEV, so void return is not possible.
function

oStringTag && (value: any)[Symbol.toStringTag]) ||
      (value: any).constructor.name ||
      'Object';
    // $FlowFixMe[incompatible-return]
    return type;
  }
}

// $FlowFixMe[incompatible-return] only called in DEV, so void return is not possible.

typeName(value: mixed): string {
  if (__DEV__) {
    // toStringTag is needed for namespaced types like Temporal.Instant
    const hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
    const type =
      (hasT


;

import {formatOwnerStack} from './ReactOwnerStackFrames';

let prefix;
let suffix;
export function describeBuiltInComponentFrame(name: string): string {
  if (prefix === undefined) {
    // Extract the VM specific prefix used by each line.
    try {
      throw Error();
    } catch (x) {
      const match = x.stack.trim().match(/\n( *(at )?)/);
      prefix = (match && match[1]) || '';
      suffix =
        x.stack.indexOf('\n    at') > -1
          ? // V8
            ' (<anonymous>)'
          : // JS

efix + name + suffix;
}

export function describeDebugInfoFrame(
  name: string,
  env: ?string,
  location: ?Error,
): string {
  if (location != null) {
    // If we have a location, it's the child's owner stack. Treat the bottom most frame as
    // the

C/Spidermonkey
            x.stack.indexOf('@') > -1
            ? '@unknown:0:0'
            : // Other
              '';
    }
  }
  // We use the prefix to ensure our stacks line up with native stack frames.
  return '\n' + pr


rom 'react-dom-bindings/src/client/ReactDOMContainer';
import {queueExplicitHydrationTarget} from 'react-dom-bindings/src/events/ReactDOMEventReplaying';
import {REACT_ELEMENT_TYPE} from 'shared/ReactSymbols';
import {
  disableCommentsAsDOMContainers,
  enableDefaultTransitionIndicator,
} from 'shared/ReactFeatureFlags';

export type RootType = {
  render(children: ReactNodeList): void,
  unmount(): void,
  _internalRoot: FiberRoot | null,
};

export type CreateRootOptions = {
  unstable_strictMode?: boole

    errorInfo: {
      +componentStack?: ?string,
      +errorBoundary?: ?component(...props: any),
    },
  ) => void,
  onRecoverableError?: (
    error: mixed,
    errorInfo: {+componentStack?: ?string},
  ) => void,
  onDefaultTransitionIndicator?: ()

an,
  unstable_transitionCallbacks?: TransitionTracingCallbacks,
  identifierPrefix?: string,
  onUncaughtError?: (
    error: mixed,
    errorInfo: {+componentStack?: ?string},
  ) => void,
  onCaughtError?: (
    error: mixed,


ight (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 DefaultPrepareStackTrace from 'shared/DefaultPrepareStackTrace';

export function formatOwnerStack(error: Error): string {
  const prevPrepareStackTrace = Error.prepareStackTrace;
  Error.prepareStackTrace = DefaultPrepareStackTrace;
  let stack = error.stack;
  Error.prepareStackTrace = prevPrepareStackTrace;

x !== -1) {
    // Pop the JSX frame.
    stack = stack.slice(idx + 1);
  }
  idx = stack.indexOf('react_stack_bottom_frame');
  if (idx !== -1) {
    idx = stack.lastIndexOf('\n', idx);
  }
  if (idx !== -1) {
    // Cut off everything after the bottom fr

 if (stack.startsWith('Error: react-stack-top-frame\n')) {
    // V8's default formatting prefixes with the error message which we
    // don't want/need.
    stack = stack.slice(29);
  }
  let idx = stack.indexOf('\n');
  if (id


;
  let ttObject2;

  beforeEach(() => {
    jest.resetModules();
    container = document.createElement('div');
    const fakeTTObjects = new Set();
    window.trustedTypes = {
      isHTML: function (value) {
        if (this !== window.trustedTypes) {
          throw new Error(this);
        }
        return fakeTTObjects.has(value);
      },
      isScript: () => false,
      isScriptURL: () => false,
    };
    React = require('react');
    ReactDOMClient = require('react-dom/client');
    ({act, asser

ects.add(ttObject1);
    fakeTTObjects.add(ttObject2);
  });

  afterEach(() => {
    delete window.trustedTypes;
  });

  it('should not stringify trusted values for dangerouslySetInnerHTML', async () => {
    const innerHTMLDescriptor = Object.getOwnProp

tConsoleErrorDev} = require('internal-test-utils'));
    ttObject1 = {
      toString() {
        return 'Hi';
      },
    };
    ttObject2 = {
      toString() {
        return 'Bye';
      },
    };
    fakeTTObj


import type {ReactNodeList} from 'shared/ReactTypes';

import {disableLegacyMode} from 'shared/ReactFeatureFlags';
import {isValidContainer} from 'react-dom-bindings/src/client/ReactDOMContainer';
import {createEventHandle} from 'react-dom-bindings/src/client/ReactDOMEventHandle';
import {runWithPriority} from 'react-dom-bindings/src/client/ReactDOMUpdatePriority';
import {flushSync as flushSyncIsomorphic} from '../shared/ReactDOMFlushSync';

import {
  flushSyncFromReconciler as flushSyncWithoutWarningIfAl

DOM} from 'shared/ExecutionEnvironment';
import ReactVersion from 'shared/ReactVersion';

import {ensureCorrectIsomorphicReactVersion} from '../shared/ensureCorrectIsomorphicReactVersion';
ensureCorrectIsomorphicReactVersion();

import {
  getInstanceFromN

readyRendering,
  isAlreadyRendering,
  injectIntoDevTools,
  findHostInstance,
} from 'react-reconciler/src/ReactFiberReconciler';
import {createPortal as createPortalImpl} from 'react-reconciler/src/ReactPortal';
import {canUse


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

// Renderers that don't support mutation
// can re-export everything from this module.

function shim(...args: any): any {
  throw new Error(
    'react-noop-renderer does not support Singletons. ' +
      'This error is likely caused by a bug in React. ' +
      'Please file an issue.',
  );
}

// Resources

ted)
export const supportsSingletons = false;
export const resolveSingletonInstance = shim;
export const acquireSingletonInstance = shim;
export const releaseSingletonInstance = shim;
export const isHostSingletonType = shim;
export const isSingletonScope =


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

// Renderers that don't support persistence
// can re-export everything from this module.

function shim(...args: any): empty {
  throw new Error(
    'The current renderer does not support persistence. ' +
      'This error is likely caused by a bug in React. ' +
      'Please file an issue.',
  );
}

// Persistence (when unsupported)
expor

oneInstance = shim;
export const createContainerChildSet = shim;
export const appendChildToContainerChildSet = shim;
export const finalizeContainerChildren = shim;
export const replaceContainerChildren = shim;
export const cloneHiddenInstance = shim;
expor

t const supportsPersistence = false;
export const cl


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

// Renderers that don't support hydration
// can re-export everything from this module.

function shim(...args: any): empty {
  throw new Error(
    'The current renderer does not support Resources. ' +
      'This error is likely caused by a bug in React. ' +
      'Please file an issue.',
  );
}

export type Ho

 shim;
export const acquireResource = shim;
export const releaseResource = shim;
export const hydrateHoistable = shim;
export const mountHoistable = shim;
export const unmountHoistable = shim;
export const createHoistableInstance = shim;
export const prepa

istableRoot = mixed;
export type Resource = mixed;

// Resources (when unsupported)
export const supportsResources = false;
export const isHostHoistableType = shim;
export const getHoistableRoot = shim;
export const getResource =


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

// Renderers that don't support mutation
// can re-export everything from this module.

function shim(...args: any): any {
  throw new Error(
    'The current renderer does not support Singletons. ' +
      'This error is likely caused by a bug in React. ' +
      'Please file an issue.',
  );
}

// Resources

rted)
export const supportsSingletons = false;
export const resolveSingletonInstance = shim;
export const acquireSingletonInstance = shim;
export const releaseSingletonInstance = shim;
export const isHostSingletonType = shim;
export const isSingletonScope


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

// Renderers that don't support test selectors
// can re-export everything from this module.

function shim(...args: any): empty {
  throw new Error(
    'The current renderer does not support test selectors. ' +
      'This error is likely caused by a bug in React. ' +
      'Please file an issue.',
  );
}

// Test selectors (when unsupported)
export c

dFiberRoot = shim;
export const getBoundingRect = shim;
export const getTextContent = shim;
export const isHiddenSubtree = shim;
export const matchAccessibilityRole = shim;
export const setFocusIfFocusable = shim;
export const setupIntersectionObserver = s

onst supportsTestSelectors = false;
export const fin


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

// Renderers that don't support view transitions
// can re-export everything from this module.

function shim(...args: any): empty {
  throw new Error(
    'The current renderer does not support view transitions. ' +
      'This error is likely caused by a bug in React. ' +
      'Please file an issue.',
  );
}

// Vie

onst restoreRootViewTransitionName = shim;
export const cloneRootViewTransitionContainer = shim;
export const removeRootViewTransitionClone = shim;
export type InstanceMeasurement = any;
export const measureInstance = shim;
export const measureClonedInstan

w Transitions (when unsupported)
export const applyViewTransitionName = shim;
export const restoreViewTransitionName = shim;
export const cancelViewTransitionName = shim;
export const cancelRootViewTransitionName = shim;
export c


om './ReactEventPriorities';
// import type {DevToolsProfilingHooks} from 'react-devtools-shared/src/backend/types';
// TODO: This import doesn't work because the DevTools depend on the DOM version of React
// and to properly type check against DOM React we can't also type check again non-DOM
// React which this hook might be in.
type DevToolsProfilingHooks = any;

import {DidCapture} from './ReactFiberFlags';
import {
  enableProfilerTimer,
  enableSchedulingProfiler,
} from 'shared/ReactFeatureFlags';
imp

ckingSchedulerPriority,
  NormalPriority as NormalSchedulerPriority,
  IdlePriority as IdleSchedulerPriority,
  log,
  unstable_setDisableYieldValue,
} from './Scheduler';

declare const __REACT_DEVTOOLS_GLOBAL_HOOK__: Object | void;

let rendererID = null

ort {
  DiscreteEventPriority,
  ContinuousEventPriority,
  DefaultEventPriority,
  IdleEventPriority,
} from './ReactEventPriorities';
import {
  ImmediatePriority as ImmediateSchedulerPriority,
  UserBlockingPriority as UserBlo


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 {Fiber} from './ReactInternalTypes';
import type {ViewTransitionProps} from 'shared/ReactTypes';
import {runWithFiberInDEV} from './ReactCurrentFiber';

// Use in DEV to track mounted named ViewTransitions. This is used to warn for
// duplicate names. This should technically be tracked per Document because you could
// have two different documen

ap<string, Fiber> = __DEV__
  ? new Map()
  : (null: any);
const didWarnAboutName: {[string]: boolean} = __DEV__ ? {} : (null: any);

export function trackNamedViewTransition(fiber: Fiber): void {
  if (__DEV__) {
    const name = (fiber.memoizedProps: Vie

ts that can have separate namespaces, but to keep things
// simple we just use a global Map. Technically it should also include any manually
// assigned view-transition-name outside React too.
const mountedNamedViewTransitions: M


import type {Fiber, FiberRoot} from './ReactInternalTypes';
import type {CapturedValue} from './ReactCapturedValue';

import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber';

import {ClassComponent} from './ReactWorkTags';

import reportGlobalError from 'shared/reportGlobalError';

import ReactSharedInternals from 'shared/ReactSharedInternals';

import {bindToConsole} from './ReactFiberConfig';

// Side-channel since I'm not sure we want to make this part of the public API
le

se warnings e.g. for tests.
  // See https://github.com/facebook/react/pull/13384

  // For uncaught root errors we report them as uncaught to the browser's
  // onerror callback. This won't have component stacks and the error addendum.
  // So we add thos

t componentName: null | string = null;
let errorBoundaryName: null | string = null;

export function defaultOnUncaughtError(
  error: mixed,
  errorInfo: {+componentStack?: ?string},
): void {
  // Overriding this can silence the


import {
  enableCreateEventHandleAPI,
  enableEffectEventMutationPhase,
} from 'shared/ReactFeatureFlags';

export type Flags = number;

// Don't change these values. They're used by React Dev Tools.
export const NoFlags = /*                      */ 0b0000000000000000000000000000000;
export const PerformedWork = /*                */ 0b0000000000000000000000000000001;
export const Placement = /*                    */ 0b0000000000000000000000000000010;
export const DidCapture = /*                   */ 0b0000


sitionTypes} from 'react/src/ReactTransitionType';
import type {Lane} from './ReactFiberLane';

import {
  GestureLane,
  markRootEntangled,
  markRootFinished,
  NoLane,
  NoLanes,
} from './ReactFiberLane';
import {
  ensureRootIsScheduled,
  requestTransitionLane,
} from './ReactFiberRootScheduler';
import {getCurrentGestureOffset, stopViewTransition} from './ReactFiberConfig';
import {pingGestureRoot, restartGestureRoot} from './ReactFiberWorkLoop';

// This type keeps track of any scheduled or active g

ate starts.
  rangeEnd: number, // The percentage along the timeline where the "destination" state is reached.
  types: null | TransitionTypes, // Any addTransitionType call made during startGestureTransition.
  running: null | RunningViewTransition, // Us

estures.
export type ScheduledGesture = {
  provider: GestureTimeline,
  count: number, // The number of times this same provider has been started.
  rangeStart: number, // The percentage along the timeline where the "current" st


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 {Fiber} from './ReactInternalTypes';
import type {StackCursor} from './ReactFiberStack';
import type {Lanes} from './ReactFiberLane';

import {createCursor, push, pop} from './ReactFiberStack';

import {
  getEntangledRenderLanes,
  setEntangledRenderLanes,
} from './ReactFiberWorkLoop';
import {NoLanes, mergeLanes} from './ReactFiberLane';

//

nes` context from work loop in favor of this one.
  baseLanes: number,
  ...
};

// TODO: This isn't being used yet, but it's intended to replace the
// InvisibleParentContext that is currently managed by SuspenseContext.
export const currentTreeHiddenStac

TODO: Remove `renderLanes` context in favor of hidden context
type HiddenContext = {
  // Represents the lanes that must be included when processing updates in
  // order to reveal the hidden content.
  // TODO: Remove `subtreeLa


ate: () => (() => void) | void,
  deps: Array<mixed> | void | null,
  next: Effect,
};

type StoreInstance<T> = {
  value: T,
  getSnapshot: () => T,
};

type StoreConsistencyCheck<T> = {
  value: T,
  getSnapshot: () => T,
};

type EventFunctionPayload<Args, Return, F: (...Array<Args>) => Return> = {
  ref: {
    eventFn: F,
    impl: F,
  },
  nextImpl: F,
};

export type FunctionComponentUpdateQueue = {
  lastEffect: Effect | null,
  events: Array<EventFunctionPayload<any, any, any>> | null,
  stores: Ar

anes;
// The work-in-progress fiber. I've named it differently to distinguish it from
// the work-in-progress hook.
let currentlyRenderingFiber: Fiber = (null: any);

// Hooks are stored as a linked list on the fiber's memoizedState field. The
// current h

ray<StoreConsistencyCheck<any>> | null,
  memoCache: MemoCache | null,
};

type BasicStateAction<S> = (S => S) | S;

type Dispatch<A> = A => void;

// These are set right before calling the component.
let renderLanes: Lanes = NoL


import type {Fiber} from './ReactInternalTypes';
import type {StackCursor} from './ReactFiberStack';
import type {
  Container,
  HostContext,
  TransitionStatus,
} from './ReactFiberConfig';
import type {Hook} from './ReactFiberHooks';

import {
  getChildHostContext,
  getRootHostContext,
  HostTransitionContext,
  NotPendingTransition,
  isPrimaryRenderer,
} from './ReactFiberConfig';
import {createCursor, push, pop} from './ReactFiberStack';

const contextStackCursor: StackCursor<HostContext | null> = c

vider (in React DOM, a <form />)
// NOTE: Since forms cannot be nested, and this feature is only implemented by
// React DOM, we don't technically need this to be a stack. It could be a single
// module variable instead.
const hostTransitionProviderCursor:

reateCursor(null);
const contextFiberStackCursor: StackCursor<Fiber | null> = createCursor(null);
const rootInstanceStackCursor: StackCursor<Container | null> =
  createCursor(null);

// Represents the nearest host transition pro


 'shared/ReactTypes';

import {
  flushSyncWork,
  scheduleUpdateOnFiber,
  flushPendingEffects,
} from './ReactFiberWorkLoop';
import {enqueueConcurrentRenderForLane} from './ReactFiberConcurrentUpdates';
import {updateContainerSync} from './ReactFiberReconciler';
import {emptyContextObject} from './ReactFiberLegacyContext';
import {SyncLane} from './ReactFiberLane';
import {
  ClassComponent,
  FunctionComponent,
  ForwardRef,
  MemoComponent,
  SimpleMemoComponent,
} from './ReactWorkTags';
import {
  RE

// Resolves type to a family.
type RefreshHandler = any => Family | void;

// Used by React Refresh runtime through DevTools Global Hook.
export type SetRefreshHandler = (handler: RefreshHandler | null) => void;
export type ScheduleRefresh = (root: FiberR

ACT_FORWARD_REF_TYPE,
  REACT_MEMO_TYPE,
  REACT_LAZY_TYPE,
} from 'shared/ReactSymbols';

export type Family = {
  current: any,
};

export type RefreshUpdate = {
  staleFamilies: Set<Family>,
  updatedFamilies: Set<Family>,
};


onent,
} from './ReactWorkTags';

import {createCapturedValueAtFiber} from './ReactCapturedValue';

import {createFiberFromDehydratedFragment} from './ReactFiber';
import {
  shouldSetTextContent,
  supportsHydration,
  supportsSingletons,
  getNextHydratableSibling,
  getNextHydratableSiblingAfterSingleton,
  getFirstHydratableChild,
  getFirstHydratableChildWithinContainer,
  getFirstHydratableChildWithinActivityInstance,
  getFirstHydratableChildWithinSuspenseInstance,
  getFirstHydratableChildWithinSing

atableInstanceAfterActivityInstance,
  getNextHydratableInstanceAfterSuspenseInstance,
  shouldDeleteUnhydratedTailInstances,
  resolveSingletonInstance,
  canHydrateInstance,
  canHydrateTextInstance,
  canHydrateActivityInstance,
  canHydrateSuspenseInst

leton,
  hydrateInstance,
  diffHydratedPropsForDevWarnings,
  describeHydratableInstanceForDevWarnings,
  hydrateTextInstance,
  diffHydratedTextForDevWarnings,
  hydrateActivityInstance,
  hydrateSuspenseInstance,
  getNextHydr


Fiber,
  children: Array<HydrationDiffNode>,
  serverProps: void | null | $ReadOnly<{[propName: string]: mixed}> | string, // null means no matching server node
  serverTail: Array<
    | $ReadOnly<{type: string, props: $ReadOnly<{[propName: string]: mixed}>}>
    | string,
  >,
  distanceFromLeaf: number,
};

const maxRowLength = 120;
const idealDepth = 15;

function findNotableNode(
  node: HydrationDiffNode,
  indent: number,
): HydrationDiffNode {
  if (
    node.serverProps === undefined &&
    node.se

   const child = node.children[0];
    return findNotableNode(child, indent);
  }
  return node;
}

function indentation(indent: number): string {
  return '  ' + '  '.repeat(indent);
}

function added(indent: number): string {
  return '+ ' + '  '.repeat(

rverTail.length === 0 &&
    node.children.length === 1 &&
    node.distanceFromLeaf > 3 &&
    node.distanceFromLeaf > idealDepth - indent
  ) {
    // This is not an interesting node for contextual purposes so we can skip it.


dateLanes: Lane =
  SyncLane | InputContinuousLane | DefaultLane;

export const GestureLane: Lane = /*                     */ 0b0000000000000000000000001000000;

const TransitionHydrationLane: Lane = /*                */ 0b000000


./ReactWorkTags';
import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber';

import {createCursor, push, pop} from './ReactFiberStack';

let warnedAboutMissingGetChildContext;

if (__DEV__) {
  warnedAboutMissingGetChildContext = ({}: {[string]: boolean});
}

export const emptyContextObject: {} = {};
if (__DEV__) {
  Object.freeze(emptyContextObject);
}

// A cursor to the current merged context object on the stack.
const contextStackCursor: StackCursor<Object> =
  createCursor

stack.
// We use this to get access to the parent context after we have already
// pushed the next context provider, and now need to merge their contexts.
let previousContext: Object = emptyContextObject;

function getUnmaskedContext(
  workInProgress: Fib

(emptyContextObject);
// A cursor to a boolean indicating whether the context has changed.
const didPerformWorkStackCursor: StackCursor<boolean> = createCursor(false);
// Keep track of the previous context object that was on the


 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 {
  enableDefaultTransitionIndicator,
  enableViewTransition,
} from 'shared/ReactFeatureFlags';

export let rootMutationContext: boolean = false;
export let viewTransitionMutationContext: boolean = false;

export function pushRootMutationContext(): void {
  if (enableDefaultTransitionIndicator) {
    rootMutationContext = f

Context;
  viewTransitionMutationContext = false;
  return prev;
}

export function popMutationContext(prev: boolean): void {
  if (enableViewTransition) {
    if (viewTransitionMutationContext) {
      rootMutationContext = true;
    }
    viewTransitionM

alse;
  }
  if (enableViewTransition) {
    viewTransitionMutationContext = false;
  }
}

export function pushMutationContext(): boolean {
  if (!enableViewTransition) {
    return false;
  }
  const prev = viewTransitionMutation


geLanes} from './ReactFiberLane';
import {
  NoFlags,
  DidPropagateContext,
  NeedsPropagation,
} from './ReactFiberFlags';

import is from 'shared/objectIs';
import {getHostTransitionProvider} from './ReactFiberHostContext';

const valueCursor: StackCursor<mixed> = createCursor(null);

let rendererCursorDEV: StackCursor<Object | null>;
if (__DEV__) {
  rendererCursorDEV = createCursor(null);
}
let renderer2CursorDEV: StackCursor<Object | null>;
if (__DEV__) {
  renderer2CursorDEV = createCursor(null);
}

null = null;

let isDisallowedContextReadInDEV: boolean = false;

export function resetContextDependencies(): void {
  // This is called right before React yields execution, to ensure `readContext`
  // cannot be called outside the render phase.
  currentl

let rendererSigil;
if (__DEV__) {
  // Use this to detect multiple renderers using the same context
  rendererSigil = {};
}

let currentlyRenderingFiber: Fiber | null = null;
let lastContextDependency: ContextDependency<mixed> |


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 {ReactNodeList, Wakeable} from 'shared/ReactTypes';
import type {Lanes} from './ReactFiberLane';
import type {SpawnedCachePool} from './ReactFiberCacheComponent';
import type {Transition} from 'react/src/ReactStartTransition';
import type {TracingMarkerInstance} from './ReactFiberTracingMarkerComponent';
import type {RetryQueue} from './ReactFib

ps = {
  // TODO: Pick an API before exposing the Offscreen type. I've chosen an enum
  // for now, since we might have multiple variants. For example, hiding the
  // content without changing the layout.
  //
  // Default mode is visible. Kind of a weird

erSuspenseComponent';

type OffscreenMode = 'hidden' | 'unstable-defer-without-hiding' | 'visible';

export type LegacyHiddenProps = {
  mode?: OffscreenMode | null | void,
  children?: ReactNodeList,
};

export type OffscreenPro


rtsUserTiming) {
    // Ensure we create all tracks in priority order. Currently performance.mark() are in
    // first insertion order but performance.measure() are in the reverse order. We can
    // always add the 0 time slot even if it's in the past. That's still considered for
    // ordering.
    console.timeStamp(
      'Blocking Track',
      0.003,
      0.003,
      'Blocking',
      LANES_TRACK_GROUP,
      'primary-light',
    );
    if (enableGestureTransition) {
      console.timeStamp(

      LANES_TRACK_GROUP,
      'primary-light',
    );
    console.timeStamp(
      'Suspense Track',
      0.003,
      0.003,
      'Suspense',
      LANES_TRACK_GROUP,
      'primary-light',
    );
    console.timeStamp(
      'Idle Track',
      0.003

  'Gesture Track',
        0.003,
        0.003,
        'Gesture',
        LANES_TRACK_GROUP,
        'primary-light',
      );
    }
    console.timeStamp(
      'Transition Track',
      0.003,
      0.003,
      'Transition',


tFiberWithNoPortals,
} from './ReactFiberTreeReflection';
import {get as getInstance} from 'shared/ReactInstanceMap';
import {
  HostComponent,
  HostSingleton,
  ClassComponent,
  HostRoot,
  SuspenseComponent,
  ActivityComponent,
} from './ReactWorkTags';
import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber';
import isArray from 'shared/isArray';
import {
  enableSchedulingProfiler,
  disableLegacyMode,
} from 'shared/ReactFeatureFlags';
import ReactSharedInternals from '

tObject,
  isContextProvider as isLegacyContextProvider,
} from './ReactFiberLegacyContext';
import {createFiberRoot} from './ReactFiberRoot';
import {isRootDehydrated} from './ReactFiberShellHydration';
import {
  injectInternals,
  markRenderScheduled,

shared/ReactSharedInternals';
import {
  getPublicInstance,
  rendererVersion,
  rendererPackageName,
  extraDevToolsConfig,
} from './ReactFiberConfig';
import {
  findCurrentUnmaskedContext,
  processChildContext,
  emptyContex


import type {ReactNodeList, ReactFormState} from 'shared/ReactTypes';
import type {
  FiberRoot,
  SuspenseHydrationCallbacks,
  TransitionTracingCallbacks,
} from './ReactInternalTypes';
import type {RootTag} from './ReactRootTags';
import type {Cache} from './ReactFiberCacheComponent';
import type {Container} from './ReactFiberConfig';

import {noTimeout} from './ReactFiberConfig';
import {createHostRootFiber} from './ReactFiber';
import {
  NoLane,
  NoLanes,
  NoTimestamp,
  TotalLanes,
  createLaneMap,

ansition,
  enableDefaultTransitionIndicator,
} from 'shared/ReactFeatureFlags';
import {initializeUpdateQueue} from './ReactFiberClassUpdateQueue';
import {LegacyRoot, ConcurrentRoot} from './ReactRootTags';
import {createCache, retainCache} from './React

} from './ReactFiberLane';
import {
  enableSuspenseCallback,
  enableProfilerCommitHooks,
  enableProfilerTimer,
  enableUpdaterTracking,
  enableTransitionTracing,
  disableLegacyMode,
  enableViewTransition,
  enableGestureTr


tNextLanes,
  includesSyncLane,
  markStarvedLanesAsExpired,
  claimNextTransitionUpdateLane,
  getNextLanesToFlushSync,
  checkIfRootIsPrerendering,
  isGestureRender,
} from './ReactFiberLane';
import {
  CommitContext,
  NoContext,
  RenderContext,
  flushPendingEffects,
  flushPendingEffectsDelayed,
  getExecutionContext,
  getWorkInProgressRoot,
  getWorkInProgressRootRenderLanes,
  getRootWithPendingPassiveEffects,
  getPendingPassiveEffectsLanes,
  hasPendingCommitEffects,
  isWorkLoopSuspendedOnData

ty as NormalSchedulerPriority,
  IdlePriority as IdleSchedulerPriority,
  cancelCallback as Scheduler_cancelCallback,
  scheduleCallback as Scheduler_scheduleCallback,
  now,
} from './Scheduler';
import {
  DiscreteEventPriority,
  ContinuousEventPriority

,
  performWorkOnRoot,
} from './ReactFiberWorkLoop';
import {LegacyRoot} from './ReactRootTags';
import {
  ImmediatePriority as ImmediateSchedulerPriority,
  UserBlockingPriority as UserBlockingSchedulerPriority,
  NormalPriori


import type {Fiber} from './ReactInternalTypes';
import type {
  ReactScopeInstance,
  ReactContext,
  ReactScopeQuery,
} from 'shared/ReactTypes';

import {
  getPublicInstance,
  getInstanceFromNode,
  getInstanceFromScope,
} from './ReactFiberConfig';
import {isFiberSuspenseAndTimedOut} from './ReactFiberTreeReflection';

import {HostComponent, ScopeComponent, ContextProvider} from './ReactWorkTags';
import {enableScopeAPI} from 'shared/ReactFeatureFlags';

function getSuspenseFallbackChild(fiber: Fiber)

ScopeAPI) {
    if (node.tag === HostComponent) {
      const {type, memoizedProps, stateNode} = node;
      const instance = getPublicInstance(stateNode);
      if (
        instance !== null &&
        fn(type, memoizedProps || emptyObject, instance) ===

: Fiber | null {
  return ((((fiber.child: any): Fiber).sibling: any): Fiber).child;
}

const emptyObject = {};

function collectScopedNodes(
  node: Fiber,
  fn: ReactScopeQuery,
  scopedNodes: Array<any>,
): void {
  if (enable


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

import type {Fiber} from './ReactInternalTypes';

export type StackCursor<T> = {current: T};

const valueStack: Array<any> = [];

let fiberStack: Array<Fiber | null>;

if (__DEV__) {
  fiberStack = [];
}

let index = -1;

function createCursor<T>(defaultValue: T): StackCursor<T> {
  return {
    current: defaultV

) {
      console.error('Unexpected Fiber popped.');
    }
  }

  cursor.current = valueStack[index];

  valueStack[index] = null;

  if (__DEV__) {
    fiberStack[index] = null;
  }

  index--;
}

function push<T>(cursor: StackCursor<T>, value: T, fiber:

alue,
  };
}

function pop<T>(cursor: StackCursor<T>, fiber: Fiber): void {
  if (index < 0) {
    if (__DEV__) {
      console.error('Unexpected pop.');
    }
    return;
  }

  if (__DEV__) {
    if (fiber !== fiberStack[index]


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

import type {Wakeable, SuspenseListTailMode} from 'shared/ReactTypes';
import type {Fiber} from './ReactInternalTypes';
import type {SuspenseInstance} from './ReactFiberConfig';
import type {Lane} from './ReactFiberLane';
import type {TreeContext} from './ReactFiberTreeContext';
import type {CapturedValue} from './ReactCapturedValue';

import {SuspenseComponent, SuspenseListComponent} from './ReactWorkTags'

.
// A non-null SuspenseState means that it is blocked for one reason or another.
// - A non-null dehydrated field means it's blocked pending hydration.
//   - A non-null dehydrated field can use isSuspenseInstancePending or
//     isSuspenseInstanceFallba

;
import {NoFlags, DidCapture} from './ReactFiberFlags';
import {
  isSuspenseInstancePending,
  isSuspenseInstanceFallback,
} from './ReactFiberConfig';

// A null SuspenseState represents an unsuspended normal Suspense boundary


import type {SuspenseProps} from 'shared/ReactTypes';
import type {Fiber} from './ReactInternalTypes';
import type {StackCursor} from './ReactFiberStack';
import type {SuspenseState} from './ReactFiberSuspenseComponent';

import {enableSuspenseAvoidThisFallback} from 'shared/ReactFeatureFlags';
import {createCursor, push, pop} from './ReactFiberStack';
import {isCurrentTreeHidden} from './ReactFiberHiddenContext';
import {OffscreenComponent} from './ReactWorkTags';

// The Suspense handler is the boundary t

visible in the current tree.
// Everything above this is the "shell". When this is null, it means we're
// rendering in the shell of the app. If it's non-null, it means we're rendering
// deeper than the shell, inside a new tree that wasn't already visible

hat should capture if something
// suspends, i.e. it's the nearest `catch` block on the stack.
const suspenseHandlerStackCursor: StackCursor<Fiber | null> =
  createCursor(null);

// Represents the outermost boundary that is not


;

import {callLazyInitInDEV} from './ReactFiberCallUserSpace';

import {getWorkInProgressRoot} from './ReactFiberWorkLoop';

import ReactSharedInternals from 'shared/ReactSharedInternals';

import {enableAsyncDebugInfo} from 'shared/ReactFeatureFlags';

import noop from 'shared/noop';

opaque type ThenableStateDev = {
  didWarnAboutUncachedPromise: boolean,
  thenables: Array<Thenable<any>>,
};

opaque type ThenableStateProd = Array<Thenable<any>>;

export opaque type ThenableState = ThenableStateDev | The

state: any);
    return prodState;
  }
}

// An error that is thrown (e.g. by `use`) to trigger Suspense. If we
// detect this is caught by userspace, we'll log a warning in development.
export const SuspenseException: mixed = new Error(
  "Suspense Except

nableStateProd;

function getThenablesFromState(state: ThenableState): Array<Thenable<any>> {
  if (__DEV__) {
    const devState: ThenableStateDev = (state: any);
    return devState.thenables;
  } else {
    const prodState = (


  FunctionComponent,
  ForwardRef,
  SimpleMemoComponent,
  ActivityComponent,
  SuspenseComponent,
  OffscreenComponent,
  SuspenseListComponent,
} from './ReactWorkTags';
import {
  DidCapture,
  Incomplete,
  NoFlags,
  ShouldCapture,
  LifecycleEffectMask,
  ForceUpdateForLegacySuspense,
  ForceClientRender,
  ScheduleRetry,
} from './ReactFiberFlags';
import {NoMode, ConcurrentMode} from './ReactTypeOfMode';
import {
  enableUpdaterTracking,
  disableLegacyMode,
} from 'shared/ReactFeatureFlags';
impo

yForHotReloading} from './ReactFiberHotReloading';
import {
  getShellBoundary,
  getSuspenseHandler,
} from './ReactFiberSuspenseContext';
import {
  renderDidError,
  queueConcurrentError,
  renderDidSuspendDelayIfPossible,
  markLegacyErrorBoundaryAsFai

rt {createCapturedValueAtFiber} from './ReactCapturedValue';
import {
  enqueueCapturedUpdate,
  createUpdate,
  CaptureUpdate,
  ForceUpdate,
  enqueueUpdate,
} from './ReactFiberClassUpdateQueue';
import {markFailedErrorBoundar


tFiberOffscreenComponent';
import type {StackCursor} from './ReactFiberStack';

import {enableTransitionTracing} from 'shared/ReactFeatureFlags';
import {createCursor, push, pop} from './ReactFiberStack';
import {getWorkInProgressTransitions} from './ReactFiberWorkLoop';

export type SuspenseInfo = {name: string | null};

export type PendingTransitionCallbacks = {
  transitionStart: Array<Transition> | null,
  transitionProgress: Map<Transition, PendingBoundaries> | null,
  transitionComplete: Array<Transit

sition>},
  > | null,
  markerComplete: Map<string, Set<Transition>> | null,
};

// TODO: Is there a way to not include the tag or name here?
export type TracingMarkerInstance = {
  tag?: TracingMarkerTag,
  transitions: Set<Transition> | null,
  pendingBo

ion> | null,
  markerProgress: Map<
    string,
    {pendingBoundaries: PendingBoundaries, transitions: Set<Transition>},
  > | null,
  markerIncomplete: Map<
    string,
    {aborts: Array<TransitionAbort>, transitions: Set<Tran


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

// Renderers that don't support test selectors
// can re-export everything from this module.

function shim(...args: any): empty {
  throw new Error(
    'react-noop-renderer does not support test selectors. ' +
      'This error is likely caused by a bug in React. ' +
      'Please file an issue.',
  );
}

// Test selectors (when unsupported)
export co

FiberRoot = shim;
export const getBoundingRect = shim;
export const getTextContent = shim;
export const isHiddenSubtree = shim;
export const matchAccessibilityRole = shim;
export const setFocusIfFocusable = shim;
export const setupIntersectionObserver = sh

nst supportsTestSelectors = false;
export const find