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

/**
 * This is a renderer of React that doesn't have a render target output.
 * It is useful to demonstrate the internals of the reconciler in isolation
 * and for testing semantics of reconciliation separate from the host
 * environment.
 */

import type {Thenable} from 'shared/ReactTypes';
import type {FindSourceMapURLCallback} from 'react-client/flight';

import {readModule} from 'react-noop-renderer/fli

FlowFixMe[prop-missing]
  ReactFlightClient({
    createStringDecoder() {
      return new TextDecoder();
    },
    readPartialStringChunk(decoder: TextDecoder, buffer: Uint8Array): string {
      return decoder.decode(buffer, decoderOptions);
    },

ght-modules';

import ReactFlightClient from 'react-client/flight';

type Source = Array<Uint8Array>;

const decoderOptions = {stream: true};

const {createResponse, createStreamState, processBinaryChunk, getRoot, close} =
  // $


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

/**
 * This is a renderer of React that doesn't have a render target output.
 * It is useful to demonstrate the internals of the reconciler in isolation
 * and for testing semantics of reconciliation separate from the host
 * environment.
 */

import ReactFiberReconciler from 'react-reconciler';
import createReactNoop from './creat

dingChildrenAsJSX,
  getSuspenseyThingStatus,
  resolveSuspenseyThing,
  resetSuspenseyThingCache,
  createPortal,
  render,
  renderLegacySyncRoot,
  renderToRootWithID,
  unmountRootWithID,
  findInstance,
  flushNextYield,
  startTrackingHostCounters,

eReactNoop';

export const {
  _Scheduler,
  getChildren,
  dangerouslyGetChildren,
  getPendingChildren,
  dangerouslyGetPendingChildren,
  getOrCreateRootContainer,
  createRoot,
  createLegacyRoot,
  getChildrenAsJSX,
  getPen


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 {Fiber} from './ReactInternalTypes';

import {getStackByFiberInDevAndProd} from './ReactFiberComponentStack';

const CapturedStacks: WeakMap<any, CapturedValue<any>> = new WeakMap();

export type CapturedValue<+T> = {
  +value: T,
  source: Fiber | null,
  stack: string | null,
};

export function createCap

 null) {
    const existing = CapturedStacks.get(value);
    if (existing !== undefined) {
      return existing;
    }
    const captured: CapturedValue<T> = {
      value,
      source,
      stack: getStackByFiberInDevAndProd(source),
    };
    Capture

turedValueAtFiber<T>(
  value: T,
  source: Fiber,
): CapturedValue<T> {
  // If the value is an error, call this function immediately after it is thrown
  // so the stack is accurate.
  if (typeof value === 'object' && value !==


= debugInfo[i];
          const debugTask: ?ConsoleTask = componentInfo.debugTask;
          if (debugTask != null) {
            return debugTask;
          }
        }
      }
    }
  }
  return null;
}

let didWarnAboutMaps;
let didWarnAboutGenerators;
let ownerHasKeyUseWarning;
let ownerHasFunctionTypeWarning;
let ownerHasSymbolTypeWarning;
let warnForMissingKey = (
  returnFiber: Fiber,
  workInProgress: Fiber,
  child: mixed,
) => {};

if (__DEV__) {
  didWarnAboutMaps = false;
  didWarnAboutGenerator

tring]: boolean});
  ownerHasFunctionTypeWarning = ({}: {[string]: boolean});
  ownerHasSymbolTypeWarning = ({}: {[string]: boolean});

  warnForMissingKey = (
    returnFiber: Fiber,
    workInProgress: Fiber,
    child: mixed,
  ) => {
    if (child ===

s = false;

  /**
   * Warn if there's no key explicitly set on dynamic arrays of children or
   * object keys are not valid. This allows us to keep track of children between
   * updates.
   */
  ownerHasKeyUseWarning = ({}: {[s


pe {ViewTransitionState} from './ReactFiberViewTransitionComponent';
import type {TracingMarkerInstance} from './ReactFiberTracingMarkerComponent';

import {
  supportsResources,
  supportsSingletons,
  isHostHoistableType,
  isHostSingletonType,
} from './ReactFiberConfig';
import {
  enableProfilerTimer,
  enableScopeAPI,
  enableLegacyHidden,
  enableTransitionTracing,
  disableLegacyMode,
  enableObjectFiber,
  enableViewTransition,
  enableSuspenseyImages,
  enableOptimisticKey,
} from 'shared/ReactFea

stSingleton,
  ForwardRef,
  Fragment,
  Mode,
  ContextProvider,
  ContextConsumer,
  Profiler,
  SuspenseComponent,
  SuspenseListComponent,
  DehydratedFragment,
  FunctionComponent,
  MemoComponent,
  SimpleMemoComponent,
  LazyComponent,
  ScopeCompon

tureFlags';
import {NoFlags, Placement, StaticMask} from './ReactFiberFlags';
import {ConcurrentRoot} from './ReactRootTags';
import {
  ClassComponent,
  HostRoot,
  HostComponent,
  HostText,
  HostPortal,
  HostHoistable,
  Ho


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

import type {ActivityInstance} from './ReactFiberConfig';
import type {CapturedValue} from './ReactCapturedValue';
import type {Lane} from './ReactFiberLane';
import type {TreeContext} from './ReactFiberTreeContext';

// A non-null ActivityState represents a dehydrated Activity boundary.
export type ActivityState = {
  dehydrated: ActivityInstance,
  treeContext: null | TreeC

o hydrate a dehydrated boundary at.
  // OffscreenLane is the default for dehydrated boundaries.
  // NoLane is the default for normal boundaries, which turns into "normal" pri.
  retryLane: Lane,
  // Stashed Errors that happened while attempting to hydra

ontext,
  // Represents the lane we should attempt t


./ReactWorkTags';
import {
  restoreEnterOrExitViewTransitions,
  restoreNestedViewTransitions,
  restoreUpdateViewTransitionForGesture,
  appearingViewTransitions,
  commitEnterViewTransitions,
  measureNestedViewTransitions,
  measureUpdateViewTransition,
  viewTransitionCancelableChildren,
  pushViewTransitionCancelableScope,
  popViewTransitionCancelableScope,
} from './ReactFiberCommitViewTransitions';
import {
  commitHookEffectListMount,
  commitHookEffectListUnmount,
} from './ReactFiberCommitEffect

kAnimatingTask} from './ReactProfilerTimer';
import {scheduleGestureTransitionEvent} from './ReactFiberWorkLoop';

// Used during the apply phase to track whether a parent ViewTransition component
// might have been affected by any mutations / relayouts be

s';
import {
  getViewTransitionName,
  getViewTransitionClassName,
} from './ReactFiberViewTransitionComponent';

import {
  enableProfilerTimer,
  enableComponentPerformanceTrack,
} from 'shared/ReactFeatureFlags';
import {trac


ntext';
import {
  constructClassInstance,
  mountClassInstance,
  resumeMountClassInstance,
  updateClassInstance,
  resolveClassComponentProps,
} from './ReactFiberClassComponent';
import {
  createFiberFromTypeAndProps,
  createFiberFromFragment,
  createFiberFromOffscreen,
  createWorkInProgress,
  isSimpleFunctionComponent,
  isFunctionClassComponent,
} from './ReactFiber';
import {
  scheduleUpdateOnFiber,
  renderDidSuspendDelayIfPossible,
  markSkippedUpdateLanes,
  markRenderDerivedCause,
  getWork

  createCapturedValueFromError,
  createCapturedValueAtFiber,
} from './ReactCapturedValue';
import {OffscreenVisible} from './ReactFiberOffscreenComponent';
import {
  createClassErrorUpdate,
  initializeClassErrorUpdate,
} from './ReactFiberThrow';
impo

InProgressRoot,
  peekDeferredLane,
} from './ReactFiberWorkLoop';
import {enqueueConcurrentRenderForLane} from './ReactFiberConcurrentUpdates';
import {pushCacheProvider, CacheContext} from './ReactFiberCacheComponent';
import {


import type {Fiber} from './ReactInternalTypes';
import type {LazyComponent} from 'react/src/ReactLazy';
import type {Effect} from './ReactFiberHooks';
import type {CapturedValue} from './ReactCapturedValue';

import {isRendering, setIsRendering} from './ReactCurrentFiber';
import {captureCommitPhaseError} from './ReactFiberWorkLoop';

// These indirections exists so we can exclude its stack frame in DEV (and anything below it).
// TODO: Consider marking the whole bundle instead of these boundaries.

const

try {
      const result = Component(props, secondArg);
      return result;
    } finally {
      setIsRendering(wasRendering);
    }
  },
};

export const callComponentInDEV: <Props, Arg, R>(
  Component: (p: Props, arg: Arg) => R,
  props: Props,
  seco

callComponent = {
  react_stack_bottom_frame: function <Props, Arg, R>(
    Component: (p: Props, arg: Arg) => R,
    props: Props,
    secondArg: Arg,
  ): R {
    const wasRendering = isRendering;
    setIsRendering(true);


yContext';
import {readContext, checkIfContextChanged} from './ReactFiberNewContext';
import {requestUpdateLane, scheduleUpdateOnFiber} from './ReactFiberWorkLoop';
import {
  markForceUpdateScheduled,
  markStateUpdateScheduled,
  setIsStrictModeForDevtools,
} from './ReactFiberDevToolsHook';
import {startUpdateTimerByLane} from './ReactProfilerTimer';

const fakeInternalInstance = {};

let didWarnAboutStateAssignmentForComponent;
let didWarnAboutUninitializedState;
let didWarnAboutGetSnapshotBeforeUpdateW

 didWarnAboutChildContextTypes;
let didWarnAboutInvalidateContextType;
let didWarnOnInvalidCallback;

if (__DEV__) {
  didWarnAboutStateAssignmentForComponent = new Set<string>();
  didWarnAboutUninitializedState = new Set<string>();
  didWarnAboutGetSnaps

ithoutDidUpdate;
let didWarnAboutLegacyLifecyclesAndDerivedState;
let didWarnAboutUndefinedDerivedState;
let didWarnAboutDirectlyAssigningPropsToState;
let didWarnAboutContextTypeAndContextTypes;
let didWarnAboutContextTypes;
let


ainer,
  insertBefore,
  insertInContainerBefore,
  replaceContainerChildren,
  hideDehydratedBoundary,
  hideInstance,
  hideTextInstance,
  unhideDehydratedBoundary,
  unhideInstance,
  unhideTextInstance,
  commitHydratedInstance,
  commitHydratedContainer,
  commitHydratedActivityInstance,
  commitHydratedSuspenseInstance,
  removeChildFromContainer,
  removeChild,
  acquireSingletonInstance,
  releaseSingletonInstance,
  isSingletonScope,
  commitNewChildToFragmentInstance,
  deleteChildFromFragmentIns

enableFragmentRefs,
  enableFragmentRefsTextNodes,
} from 'shared/ReactFeatureFlags';

export function commitHostMount(finishedWork: Fiber) {
  const type = finishedWork.type;
  const props = finishedWork.memoizedProps;
  const instance: Instance = finishe

tance,
} from './ReactFiberConfig';
import {captureCommitPhaseError} from './ReactFiberWorkLoop';
import {trackHostMutation} from './ReactFiberMutationTracking';

import {runWithFiberInDEV} from './ReactCurrentFiber';
import {


seBoundary,
  commitShowHideHostInstance,
  commitShowHideHostTextInstance,
  commitHostPlacement,
  commitHostRootContainerChildren,
  commitHostPortalContainerChildren,
  commitHostHydratedContainer,
  commitHostHydratedActivity,
  commitHostHydratedSuspense,
  commitHostRemoveChildFromContainer,
  commitHostRemoveChild,
  commitHostSingletonAcquisition,
  commitHostSingletonRelease,
  commitFragmentInstanceDeletionEffects,
  commitFragmentInstanceInsertionEffects,
} from './ReactFiberCommitHostEffects';

n,
  restoreNestedViewTransitions,
  measureUpdateViewTransition,
  measureNestedViewTransitions,
  resetAppearingViewTransitions,
  trackAppearingViewTransition,
  viewTransitionCancelableChildren,
  pushViewTransitionCancelableScope,
  popViewTransitionC

import {
  trackEnterViewTransitions,
  commitEnterViewTransitions,
  commitExitViewTransitions,
  commitBeforeUpdateViewTransition,
  commitNestedViewTransitions,
  restoreEnterOrExitViewTransitions,
  restoreUpdateViewTransitio


import {enableViewTransition} from 'shared/ReactFeatureFlags';
import type {Fiber} from './ReactInternalTypes';
import type {ReactComponentInfo} from 'shared/ReactTypes';

import {
  HostComponent,
  HostHoistable,
  HostSingleton,
  LazyComponent,
  SuspenseComponent,
  SuspenseListComponent,
  FunctionComponent,
  ForwardRef,
  SimpleMemoComponent,
  ClassComponent,
  HostText,
  ViewTransitionComponent,
  ActivityComponent,
} from './ReactWorkTags';
import {
  describeBuiltInComponentFrame,
  describeFun

er: null | Fiber): string {
  switch (fiber.tag) {
    case HostHoistable:
    case HostSingleton:
    case HostComponent:
      return describeBuiltInComponentFrame(fiber.type);
    case LazyComponent:
      // TODO: When we support Thenables as component

ctionComponentFrame,
  describeClassComponentFrame,
  describeDebugInfoFrame,
} from 'shared/ReactComponentStackFrame';
import {formatOwnerStack} from 'shared/ReactOwnerStackFrames';

function describeFiber(fiber: Fiber, childFib


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(
    'The current renderer does not support hydration. ' +
      'This error is likely caused by a bug in React. ' +
      'Please file an issue.',
  );
}

// Hydration (when unsupported)
export type ActivityInstanc

Details = shim;
export const registerSuspenseInstanceRetry = shim;
export const canHydrateFormStateMarker = shim;
export const isFormStateMarkerMatching = shim;
export const getNextHydratableSibling = shim;
export const getNextHydratableSiblingAfterSinglet

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


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

/**
 * This is a renderer of React that doesn't have a render target output.
 * It is useful to demonstrate the internals of the reconciler in isolation
 * and for testing semantics of reconciliation separate from the host
 * environment.
 */

import ReactFiberReconciler from 'react-reconciler';
import createReactNoop

JSX,
  getPendingChildrenAsJSX,
  getSuspenseyThingStatus,
  resolveSuspenseyThing,
  resetSuspenseyThingCache,
  createPortal,
  render,
  renderLegacySyncRoot,
  renderToRootWithID,
  unmountRootWithID,
  findInstance,
  flushNextYield,
  startTrackingHo

from './createReactNoop';

export const {
  _Scheduler,
  getChildren,
  dangerouslyGetChildren,
  getPendingChildren,
  dangerouslyGetPendingChildren,
  getOrCreateRootContainer,
  createRoot,
  createLegacyRoot,
  getChildrenAs


ate from the host
 * environment.
 */

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

import ReactFizzServer from 'react-server';

type Instance = {
  type: string,
  children: Array<Instance | TextInstance | SuspenseInstance>,
  prop: any,
  hidden: boolean,
};

type TextInstance = {
  text: string,
  hidden: boolean,
};

type ActivityInstance = {
  children: Array<Instance | TextInstance | SuspenseInstance>,
};

type SuspenseInstance = {
  state: 'pending' | 'complete' | 'client-render',
  childre

};

type Destination = {
  root: null | Instance | TextInstance | SuspenseInstance,
  placeholders: Map<number, Placeholder>,
  segments: Map<number, Segment>,
  stack: Array<Segment | Instance | SuspenseInstance>,
};

type ResumableState = null;
type Rend

n: Array<Instance | TextInstance | SuspenseInstance>,
};

type Placeholder = {
  parent: Instance | Segment | SuspenseInstance,
  index: number,
};

type Segment = {
  children: Array<Instance | TextInstance | SuspenseInstance>,


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 ReactSharedInternals from 'shared/ReactSharedInternals';
import {getOwnerStackByFiberInDev} from './ReactFiberComponentStack';
import {getComponentNameFromOwner} from 'react-reconciler/src/getComponentNameFromFiber';

export let current: Fiber | null = null;
export let isRendering: boolean = false;

e

NameFromOwner(owner);
    }
  }
  return null;
}

function getCurrentFiberStackInDev(): string {
  if (__DEV__) {
    if (current === null) {
      return '';
    }
    // Safe because if current fiber exists, we are reconciling,
    // and it is guarantee

xport function getCurrentFiberOwnerNameInDevOrNull(): string | null {
  if (__DEV__) {
    if (current === null) {
      return null;
    }
    const owner = current._debugOwner;
    if (owner != null) {
      return getComponent


 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 {Lane, Lanes} from './ReactFiberLane';

import {
  NoLane,
  SyncLane,
  InputContinuousLane,
  DefaultLane,
  IdleLane,
  getHighestPriorityLane,
  includesNonIdleWork,
} from './ReactFiberLane';

export opaque type EventPriority = Lane;

export const NoEventPriority: EventPriority = NoLane;
export const DiscreteEventP

e;

export function higherEventPriority(
  a: EventPriority,
  b: EventPriority,
): EventPriority {
  return a !== 0 && a < b ? a : b;
}

export function lowerEventPriority(
  a: EventPriority,
  b: EventPriority,
): EventPriority {
  return a === 0 || a >

riority: EventPriority = SyncLane;
export const ContinuousEventPriority: EventPriority = InputContinuousLane;
export const DefaultEventPriority: EventPriority = DefaultLane;
export const IdleEventPriority: EventPriority = IdleLan


 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 {AsyncDispatcher, Fiber} from './ReactInternalTypes';
import type {Cache} from './ReactFiberCacheComponent';

import {readContext} from './ReactFiberNewContext';
import {CacheContext} from './ReactFiberCacheComponent';

import {current as currentOwner} from './ReactCurrentFiber';

function getCacheFor

cache.data.set(resourceType, cacheForType);
  }
  return cacheForType;
}

function cacheSignal(): null | AbortSignal {
  const cache: Cache = readContext(CacheContext);
  return cache.controller.signal;
}

export const DefaultAsyncDispatcher: AsyncDispatch

Type<T>(resourceType: () => T): T {
  const cache: Cache = readContext(CacheContext);
  let cacheForType: T | void = (cache.data.get(resourceType): any);
  if (cacheForType === undefined) {
    cacheForType = resourceType();


 update in the persistent list that hasn't been processed.
// The work-in-progress pointer always has a position equal to or greater than
// the current queue, since we always work on that one. The current queue's
// pointer is only updated during the commit phase, when we swap in the
// work-in-progress.
//
// For example:
//
//   Current pointer:           A - B - C - D - E - F
//   Work-in-progress pointer:              D - E - F
//                                          ^
//

rocessing them. For example, if we only add updates to
// the work-in-progress queue, some updates could be lost whenever a work-in
// -progress render restarts by cloning from current. Similarly, if we only add
// updates to the current queue, the updates

               The work-in-progress queue has
//                                          processed more updates than current.
//
// The reason we append to both queues is because otherwise we might drop
// updates without ever p


nableProfilerNestedUpdatePhase,
  enableSchedulingProfiler,
  enableViewTransition,
  enableFragmentRefs,
} from 'shared/ReactFeatureFlags';
import {
  ClassComponent,
  Fragment,
  HostComponent,
  HostHoistable,
  HostSingleton,
  ViewTransitionComponent,
} from './ReactWorkTags';
import {NoFlags} from './ReactFiberFlags';
import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber';
import {resolveClassComponentProps} from './ReactFiberClassComponent';
import {
  recordEffectDur

import {
  getPublicInstance,
  createViewTransitionInstance,
  createFragmentInstance,
} from './ReactFiberConfig';
import {
  captureCommitPhaseError,
  setIsRunningInsertionEffect,
} from './ReactFiberWorkLoop';
import {
  NoFlags as NoHookEffect,
  La

ation,
  startEffectTimer,
  isCurrentUpdateNested,
} from './ReactProfilerTimer';
import {NoMode, ProfileMode} from './ReactTypeOfMode';
import {
  commitCallbacks,
  commitHiddenCallbacks,
} from './ReactFiberClassUpdateQueue';


 as ClassUpdate,
} from './ReactFiberClassUpdateQueue';
import type {Lane, Lanes} from './ReactFiberLane';
import type {OffscreenInstance} from './ReactFiberOffscreenComponent';

import {
  warnAboutUpdateOnNotYetMountedFiberInDEV,
  throwIfInfiniteUpdateLoopDetected,
  getWorkInProgressRoot,
} from './ReactFiberWorkLoop';
import {NoLane, NoLanes, mergeLanes, markHiddenUpdate} from './ReactFiberLane';
import {NoFlags, Placement, Hydrating} from './ReactFiberFlags';
import {HostRoot, OffscreenComponent} from

/ If a render is in progress, and we receive an update from a concurrent event,
// we wait until the current render is over (either finished or interrupted)
// before adding it to the fiber/hook queue. Push to this array so we can
// access the queue, fibe

 './ReactWorkTags';
import {OffscreenVisible} from './ReactFiberOffscreenComponent';

export type ConcurrentUpdate = {
  next: ConcurrentUpdate,
  lane: Lane,
};

type ConcurrentQueue = {
  pending: ConcurrentUpdate | null,
};

/


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

/**
 * This is a renderer of React that doesn't have a render target output.
 * It is useful to demonstrate the internals of the reconciler in isolation
 * and for testing semantics of reconciliation separate from the host
 * environment.
 */

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

import {saveModule} from 'react-noop-renderer/flight-modules';

import ReactFlightServer fr

void) {
    callback();
  },
  scheduleWork(callback: () => void) {
    callback();
  },
  beginWriting(destination: Destination): void {},
  writeChunk(destination: Destination, chunk: string): void {
    destination.push(chunk);
  },
  writeChunkAndRetur

om 'react-server/flight';

type Destination = Array<Uint8Array | string>;

const textEncoder = new TextEncoder();

// $FlowFixMe[prop-missing]
const ReactNoopFlightServer = ReactFlightServer({
  scheduleMicrotask(callback: () =>


 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 './ReactFiber';

import ReactSharedInternals from 'shared/ReactSharedInternals';

import {warnsIfNotActing} from './ReactFiberConfig';

export function isLegacyActEnvironment(fiber: Fiber): boolean {
  if (__DEV__) {
    // Legacy mode. We preserve the behavior of React 17's act. It assumes an
    // act en

-name] Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global
      typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined'
        ? // $FlowFixMe[cannot-resolve-name]
          IS_REACT_ACT_ENVIRONMENT
        : undefined;

    // $FlowFixMe[cannot-resolve-name

vironment whenever `jest` is defined, but you can still turn off
    // spurious warnings by setting IS_REACT_ACT_ENVIRONMENT explicitly
    // to false.

    const isReactActEnvironmentGlobal =
      // $FlowFixMe[cannot-resolve


import type {
  Thenable,
  FulfilledThenable,
  RejectedThenable,
} from 'shared/ReactTypes';
import type {Lane} from './ReactFiberLane';
import type {Transition} from 'react/src/ReactStartTransition';

import {
  requestTransitionLane,
  ensureScheduleIsScheduled,
} from './ReactFiberRootScheduler';
import {NoLane} from './ReactFiberLane';
import {
  hasScheduledTransitionWork,
  clearAsyncTransitionTimer,
} from './ReactProfilerTimer';
import {
  enableComponentPerformanceTrack,
  enableProfilerTimer,

balError';

// If there are multiple, concurrent async actions, they are entangled. All
// transition updates that occur while the async action is still in progress
// are treated as part of the action.
//
// The ideal behavior would be to treat each async

enableDefaultTransitionIndicator,
} from 'shared/ReactFeatureFlags';
import {clearEntangledAsyncTransitionTypes} from './ReactFiberTransitionTypes';

import noop from 'shared/noop';
import reportGlobalError from 'shared/reportGlo


erHiddenContext';
import {findFirstSuspended} from './ReactFiberSuspenseComponent';
import {
  isContextProvider as isLegacyContextProvider,
  popContext as popLegacyContext,
  popTopLevelContextObject as popTopLevelLegacyContextObject,
} from './ReactFiberLegacyContext';
import {popProvider} from './ReactFiberNewContext';
import {
  prepareToHydrateHostInstance,
  prepareToHydrateHostTextInstance,
  prepareToHydrateHostActivityInstance,
  prepareToHydrateHostSuspenseInstance,
  popHydrationState,
  resetHy

ons,
  shouldRemainOnPreviousScreen,
  markSpawnedRetryLane,
} from './ReactFiberWorkLoop';
import {
  OffscreenLane,
  SomeRetryLane,
  NoLanes,
  includesSomeLane,
  mergeLanes,
  claimNextRetryLane,
  includesOnlySuspenseyCommitEligibleLanes,
} from './

drationState,
  getIsHydrating,
  upgradeHydrationErrorsToRecoverable,
  emitPendingHydrationWarnings,
} from './ReactFiberHydrationContext';
import {
  renderHasNotSuspendedYet,
  getRenderTargetTime,
  getWorkInProgressTransiti


ared/ReactSymbols';
import isArray from 'shared/isArray';
import {checkPropStringCoercion} from 'shared/CheckStringCoercion';
import {
  NoEventPriority,
  DiscreteEventPriority,
  DefaultEventPriority,
  IdleEventPriority,
  ConcurrentRoot,
  LegacyRoot,
} from 'react-reconciler/constants';
import * as DefaultConfig from './ReactFiberConfigNoop';

import {disableLegacyMode} from 'shared/ReactFeatureFlags';

import ReactSharedInternals from 'shared/ReactSharedInternals';
import ReactVersion from 'shared/Rea

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

ctVersion';

type Props = {
  prop: any,
  hidden: boolean,
  children?: mixed,
  bottom?: null | number,
  left?: null | number,
  right?: null | number,
  top?: null | number,
  src?: string,
  ...
};
type CreateRootOptions = {


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

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

import {REACT_CONTEXT_TYPE} from 'shared/ReactSymbols';

import {pushProvider, popProvider} from './ReactFiberNewContext';
import * as Scheduler from 'scheduler';

// In environments without AbortController (e.g. tests)
// replace it with a lightweight shim that only has the features we

rShim() {
        const listeners = [];
        const signal = (this.signal = {
          aborted: false as boolean,
          addEventListener: (type, listener) => {
            listeners.push(listener);
          },
        });

        this.abort = () =

use.
const AbortControllerLocal: typeof AbortController =
  typeof AbortController !== 'undefined'
    ? AbortController
    : // $FlowFixMe[incompatible-type]
      // $FlowFixMe[missing-this-annot]
      function AbortControlle


irs in the beforeMutation phase.
export let appearingViewTransitions: Map<string, ViewTransitionState> | null =
  null;

export function resetAppearingViewTransitions(): void {
  appearingViewTransitions = null;
}

export function trackAppearingViewTransition(
  name: string,
  state: ViewTransitionState,
): void {
  if (appearingViewTransitions === null) {
    appearingViewTransitions = new Map();
  }
  appearingViewTransitions.set(name, state);
}

export function trackEnterViewTransitions(placement: Fiber

n immediate child, then that will trigger as an "Enter" in future passes.
    // We don't do anything else for that case in the "before mutation" phase but we
    // still have to mark it as needing to call startViewTransition if nothing else
    // update

): void {
  if (
    placement.tag === ViewTransitionComponent ||
    (placement.subtreeFlags & ViewTransitionStatic) !== NoFlags
  ) {
    // If an inserted or appearing Fiber is a ViewTransition component or has one as
    // a


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 mutation
// can re-export everything from this module.

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

// Mutation (when unsu

mitTextUpdate = shim;
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 co

pported)
export const supportsMutation = false;
export const cloneMutableInstance = shim;
export const cloneMutableTextInstance = shim;
export const appendChild = shim;
export const appendChildToContainer = shim;
export const com


 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 type WorkTag =
  | 0
  | 1
  | 2
  | 3
  | 4
  | 5
  | 6
  | 7
  | 8
  | 9
  | 10
  | 11
  | 12
  | 13
  | 14
  | 15
  | 16
  | 17
  | 18
  | 19
  | 20
  | 21
  | 22
  | 23
  | 24
  | 25
  | 26
  | 27
  | 28
  | 29
  | 30
  | 31;

export const FunctionComponent = 0;
export const ClassComponent = 1;
export const HostRoot = 3;

gment = 7;
export const Mode = 8;
export const ContextConsumer = 9;
export const ContextProvider = 10;
export const ForwardRef = 11;
export const Profiler = 12;
export const SuspenseComponent = 13;
export const MemoComponent = 14;
export const SimpleMemoCo

 // Root of a host tree. Could be nested inside another node.
export const HostPortal = 4; // A subtree. Could be an entry point to a different renderer.
export const HostComponent = 5;
export const HostText = 6;
export const Fra


acheForType;

    caches = [];
    seededCache = null;
  });

  function createTextCache() {
    if (seededCache !== null) {
      // Trick to seed a cache before it exists.
      // TODO: Need a built-in API to seed data before the initial render (i.e.
      // not a refresh because nothing has mounted yet).
      const cache = seededCache;
      seededCache = null;
      return cache;
    }

    const data = new Map();
    const version = caches.length + 1;
    const cache = {
      version,
      data,

d);
        } else if (record.status === 'pending') {
          const thenable = record.value;
          record.status = 'resolved';
          record.value = text;
          thenable.pings.forEach(t => t());
        }
      },
      reject(text, error) {

     resolve(text) {
        const record = data.get(text);
        if (record === undefined) {
          const newRecord = {
            status: 'resolved',
            value: text,
          };
          data.set(text, newRecor


 waitForPaint;

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

    React = require('react');
    ReactNoop = require('react-noop-renderer');
    Scheduler = require('scheduler');
    const InternalTestUtils = require('internal-test-utils');
    act = InternalTestUtils.act;
    assertLog = InternalTestUtils.assertLog;
    waitForPaint = InternalTestUtils.waitForPaint;
    use = React.use;
    useOptimistic = React.useOptimistic;
    useState = React.useStat

 let resolve;
    const promise = new Promise(r => (resolve = r));
    function App() {
      return use(promise);
    }

    const root = ReactNoop.createRoot({
      onDefaultTransitionIndicator() {
        Scheduler.log('start');
        return () => {

e;
    useTransition = React.useTransition;
    useDeferredValue = React.useDeferredValue;
  });

  // @gate enableDefaultTransitionIndicator
  it('triggers the default indicator while a transition is on-going', async () => {


      Scheduler.log(`Suspend! [${text}]`);
          throw record.value;
        case 'rejected':
          throw record.value;
        case 'resolved':
          return record.value;
      }
    } else {
      Scheduler.log(`Suspend! [${text}]`);
      const thenable = {
        pings: [],
        then(resolve) {
          if (newRecord.status === 'pending') {
            thenable.pings.push(resolve);
          } else {
            Promise.resolve().then(() => resolve(newRecord.value));
          }

eturn text;
  }

  function AsyncText({text}) {
    readText(text);
    Scheduler.log(text);
    return text;
  }

  it('does not cause an infinite defer loop if the original value isn\t memoized', async () => {
    function App({value}) {
      // The obj

 },
      };

      const newRecord = {
        status: 'pending',
        value: thenable,
      };
      textCache.set(text, newRecord);

      throw thenable;
    }
  }

  function Text({text}) {
    Scheduler.log(text);
    r


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

'use strict';

let React;
let ReactNoop;
let Scheduler;
let act;
let useEffect;
let useLayoutEffect;
let assertLog;

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

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

InternalTestUtils.assertLog;
  });

  it('layout unmounts on deletion are fired in parent -> child order', async () => {
    const root = ReactNoop.createRoot();

    function Parent() {
      useLayoutEffect(() => {
        return () => Scheduler.log('Unm

r = require('scheduler');
    act = require('internal-test-utils').act;
    useEffect = React.useEffect;
    useLayoutEffect = React.useLayoutEffect;

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


  let rootCaughtErrors = [];
  let SomethingThatErrors;
  let CatchingBoundary;
  let onCaughtError;

  beforeEach(function () {
    jest.resetModules();

    React = require('react');
    Suspense = React.Suspense;
    Activity = React.Activity;
    ViewTransition = React.ViewTransition;
    ReactNoop = require('react-noop-renderer');
    const InternalTestUtils = require('internal-test-utils');
    waitForAll = InternalTestUtils.waitForAll;

    didCatchErrors = [];
    rootCaughtErrors = [];

    onCaugh

rStack())
          : null,
      );
    };

    SomethingThatErrors = () => {
      throw new Error('uh oh');
    };

    // eslint-disable-next-line no-shadow
    CatchingBoundary = class CatchingBoundary extends React.Component {
      constructor() {

tError = function (error, errorInfo) {
      rootCaughtErrors.push(
        error.message,
        normalizeCodeLocInfo(errorInfo.componentStack),
        React.captureOwnerStack
          ? normalizeCodeLocInfo(React.captureOwne


tils = require('internal-test-utils');
    assertLog = InternalTestUtils.assertLog;
    waitFor = InternalTestUtils.waitFor;
    waitForAll = InternalTestUtils.waitForAll;
    unstable_waitForExpired = InternalTestUtils.unstable_waitForExpired;

    const textCache = new Map();

    readText = text => {
      const record = textCache.get(text);
      if (record !== undefined) {
        switch (record.status) {
          case 'pending':
            throw record.promise;
          case 'rejected':

          status: 'pending',
          ping: ping,
          promise,
        };
        textCache.set(text, newRecord);
        throw promise;
      }
    };

    resolveText = text => {
      const record = textCache.get(text);
      if (record !== unde

 throw Error('Failed to load: ' + text);
          case 'resolved':
            return text;
        }
      } else {
        let ping;
        const promise = new Promise(resolve => (ping = resolve));
        const newRecord = {


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

'use strict';

let React;
let act;
let ReactFiberReconciler;
let ConcurrentRoot;
let DefaultEventPriority;
let NoEventPriority;

describe('ReactFiberHostContext', () => {
  beforeEach(() => {
    jest.resetModules();
    React = require('react');
    act = React.act;
    ReactFiberReconciler = require('react-reconciler');
    ConcurrentRoot =
      require('react-recon

).NoEventPriority;
  });

  global.IS_REACT_ACT_ENVIRONMENT = true;

  // @gate __DEV__
  it('should send the context to prepareForCommit and resetAfterCommit', () => {
    const rootContext = {};
    const childContext = {};
    let updatePriority: typeof

ciler/src/ReactRootTags').ConcurrentRoot;
    DefaultEventPriority =
      require('react-reconciler/src/ReactEventPriorities').DefaultEventPriority;
    NoEventPriority =
      require('react-reconciler/src/ReactEventPriorities'


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

'use strict';

let React;
let Scheduler;
let ReactNoop;
let act;
let assertLog;

describe('ReactFiberRefs', () => {
  beforeEach(() => {
    jest.resetModules();
    React = require('react');
    Scheduler = require('scheduler');
    ReactNoop = require('react-noop-renderer');
    act = require('internal-test-utils').act;
    assertLog = require('internal-test-utils').assertLog;
  });

  it('re

ops or state
        return false;
      }
      render() {
        Scheduler.log('Render');
        component = this;
        return 'Hi';
      }
    }

    const ref1 = React.createRef();
    const ref2 = React.createRef();
    const root = ReactNoop.cr

f is attached even if there are no other updates (class)', async () => {
    let component;
    class Component extends React.Component {
      shouldComponentUpdate() {
        // This component's output doesn't depend on any pr


require('react-dom/client');
    Scheduler = require('scheduler');
    act = require('internal-test-utils').act;
    useState = React.useState;
    useEffect = React.useEffect;
    startTransition = React.startTransition;

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

  function Text({text}) {
    Scheduler.log(text);

gName !== 'SCRIPT' && node.tagName !== 'script') ||
            node.hasAttribute('data-meaningful')) &&
          node.tagName !== 'TEMPLATE' &&
          node.tagName !== 'template' &&
          !node.hasAttribute('hidden') &&
          !node.hasAttribut

return text;
  }

  function getVisibleChildren(element: Element): React$Node {
    const children = [];
    let node: any = element.firstChild;
    while (node) {
      if (node.nodeType === 1) {
        if (
          ((node.ta


Microtask;
let flushFakeMicrotasks;

// TODO: Migrate tests to React DOM instead of React Noop

describe('ReactFlushSync (AggregateError not available)', () => {
  beforeEach(() => {
    jest.resetModules();

    global.AggregateError = undefined;

    // When AggregateError is not available, the errors are rethrown in a
    // microtask. This is an implementation detail but we want to test it here
    // so override the global one.
    const originalQueueMicrotask = queueMicrotask;
    overrideQueueMicrota

shFakeMicrotasks = () => {
      while (fakeMicrotaskQueue.length > 0) {
        const cb = fakeMicrotaskQueue.shift();
        cb();
      }
    };

    React = require('react');
    ReactDOM = require('react-dom');
    ReactDOMClient = require('react-dom

sk = false;
    const fakeMicrotaskQueue = [];
    global.queueMicrotask = cb => {
      if (overrideQueueMicrotask) {
        fakeMicrotaskQueue.push(cb);
      } else {
        originalQueueMicrotask(cb);
      }
    };
    flu


ReactNoop.render(element);
    await waitForAll([]);

    expect(ReactNoop).toMatchRenderedOutput(foo);
  });

  it('should render zero children via noop renderer', async () => {
    const element = <React.Fragment />;

    ReactNoop.render(element);
    await waitForAll([]);

    expect(ReactNoop).toMatchRenderedOutput(null);
  });

  it('should render multiple children via noop renderer', async () => {
    const element = (
      <>
        hello world
      </>
    );

> {
    const element = (
      <>{new Set([hi, bye])}</>
    );

    ReactNoop.render(element);
    await waitForAll([]);

    expect(ReactNoop).toMatchRenderedOutput(
      <>
        hi
        <spa

ReactNoop.render(element);
    await waitForAll([]);

    expect(ReactNoop).toMatchRenderedOutput(
      <>
        hello world
      </>,
    );
  });

  it('should render an iterable via noop renderer', async () =


or one of the following reasons:\n' +
          '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
          '2. You might be breaking the Rules of Hooks\n' +
          '3. You might have more than one copy of React in the same app\n' +
          'See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem.',
      );
    });
  }

  it('bails out in the render phase if all of the state is the same', async () => {
    const {useState,

State(0);
      setCounter1 = _setCounter1;
      const [counter2, _setCounter2] = useState(0);
      setCounter2 = _setCounter2;

      const text = `${counter1}, ${counter2}`;
      Scheduler.log(`Parent: ${text}`);
      useLayoutEffect(() => {

useLayoutEffect} = React;

    function Child({text}) {
      Scheduler.log('Child: ' + text);
      return text;
    }

    let setCounter1;
    let setCounter2;
    function Parent() {
      const [counter1, _setCounter1] = use


k works properly.
    function GoodCounter(props, ref) {
      const [count] = useState(props.initialCount);
      return <Text text={count} />;
    }
    ReactNoop.render(<GoodCounter initialCount={10} />);
    await waitForAll([10]);
  });

  it('throws when called outside the render phase', async () => {
    expect(() => useState(0)).toThrow(
      "Cannot read property 'useState' of null",
    );
    assertConsoleErrorDev([
      'Invalid hook call. Hooks can only be called inside of the body of a funct

f Hooks\n' +
        '3. You might have more than one copy of React in the same app\n' +
        'See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem.',
    ]);
  });

  describe('useState', () => {
    it('simple

ion component. This could happen for' +
        ' one of the following reasons:\n' +
        '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
        '2. You might be breaking the Rules o


der and Content.
    await waitForAll([
      'Foo',
      'Content',
      'firstRenderCallbackCalled',
      'secondRenderCallbackCalled',
    ]);
  });

  it('can cancel partially rendered work and restart', async () => {
    function Bar(props) {
      Scheduler.log('Bar');
      return
{props.children}
;
    }

    function Foo(props) {
      Scheduler.log('Foo');
      return (

          <Bar>{props.text}</Bar>
          <Bar>{props.text}</Bar>

      );
    }

or(['Foo', 'Bar']);

    // This will abort the previous work and restart
    ReactNoop.flushSync(() => ReactNoop.render(null));

    React.startTransition(() => {
      ReactNoop.render(<Foo text="baz" />);
    });

    // Flush part of the new work
    a

  // Init
    ReactNoop.render(<Foo text="foo" />);
    await waitForAll(['Foo', 'Bar', 'Bar']);

    React.startTransition(() => {
      ReactNoop.render(<Foo text="bar" />);
    });
    // Flush part of the work
    await waitF


t-hiding' : mode}>
          {children}
        </React.unstable_LegacyHidden>
      </div>
    );
  }

  it('recovers from errors asynchronously', async () => {
    class ErrorBoundary extends React.Component {
      state = {error: null};
      static getDerivedStateFromError(error) {
        Scheduler.log('getDerivedStateFromError');
        return {error};
      }
      render() {
        if (this.state.error) {
          Scheduler.log('ErrorBoundary (catch)');
          return <ErrorMessage error={this

ht an error: ${error.message}`} />;
    }

    function Indirection({children}) {
      Scheduler.log('Indirection');
      return children || null;
    }

    function BadRender({unused}) {
      Scheduler.log('throw');
      throw new Error('oops!');

.state.error} />;
        }
        Scheduler.log('ErrorBoundary (try)');
        return this.props.children;
      }
    }

    function ErrorMessage({error}) {
      Scheduler.log('ErrorMessage');
      return <span prop={`Caug


re because we want to observe how errors are reported for real.
  await cb();
  Scheduler.unstable_flushAll();
}

describe('ReactIncrementalErrorLogging', () => {
  beforeEach(() => {
    jest.resetModules();
    React = require('react');
    ReactNoop = require('react-noop-renderer');
    Scheduler = require('scheduler');

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

  // Note: in this test file we won't be using assertConsoleDev() matc

arn = jest.fn();
    console.error = jest.fn();
    uncaughtExceptionMock = jest.fn();
    process.on('uncaughtException', uncaughtExceptionMock);
  });

  afterEach(() => {
    console.warn = oldConsoleWarn;
    console.error = oldConsoleError;
    proces

hers
  // because they filter out precisely the messages we want to test for.
  let oldConsoleWarn;
  let oldConsoleError;
  beforeEach(() => {
    oldConsoleWarn = console.warn;
    oldConsoleError = console.error;
    console.w


port type {StackCursor} from './ReactFiberStack';
import type {Cache, SpawnedCachePool} from './ReactFiberCacheComponent';
import type {Transition} from 'react/src/ReactStartTransition';
import type {ScheduledGesture} from './ReactFiberGestureScheduler';

import {
  enableTransitionTracing,
  enableViewTransition,
  enableGestureTransition,
} from 'shared/ReactFeatureFlags';
import {isPrimaryRenderer} from './ReactFiberConfig';
import {createCursor, push, pop} from './ReactFiberStack';
import {
  getWorkInP

ntangleAsyncTransitionTypes,
  entangledTransitionTypes,
} from './ReactFiberTransitionTypes';

import ReactSharedInternals from 'shared/ReactSharedInternals';
import {
  entangleAsyncAction,
  peekEntangledActionLane,
} from './ReactFiberAsyncAction';
imp

rogressRoot,
  getWorkInProgressTransitions,
  markTransitionStarted,
} from './ReactFiberWorkLoop';
import {
  createCache,
  retainCache,
  CacheContext,
} from './ReactFiberCacheComponent';
import {
  queueTransitionTypes,
  e


 sequence that represent the position of the child within the
// current level of children.
//
//      00101       00010001011010101
//      ╰─┬─╯       ╰───────┬───────╯
//   Fork 5 of 20       Parent id
//
// The leading 0s are important. In the above example, you only need 3 bits to
// represent slot 5. However, you need 5 bits to represent all the forks at
// the current level, so we must account for the empty bits at the end.
//
// For this same reason, slots are 1-indexed instead of 0-indexed. Otherwi

he
// sequence. It's treated as a transparent indirection. For example, these two
// trees produce the same ids:
//
// <>                          <>
//   <Indirection>               <A />
//     <A />                     <B />
//   </Indirection>

se,
// the zeroth id at a level would be indistinguishable from its parent.
//
// If a node has only one child, and does not materialize an id (i.e. does not
// contain a useId hook), then we don't need to allocate any space in t


ctivityComponent';
import type {
  SuspenseState,
  SuspenseListRenderState,
} from './ReactFiberSuspenseComponent';
import type {Cache} from './ReactFiberCacheComponent';
import type {TracingMarkerInstance} from './ReactFiberTracingMarkerComponent';

import {
  ClassComponent,
  HostRoot,
  HostComponent,
  HostHoistable,
  HostSingleton,
  HostPortal,
  ContextProvider,
  ActivityComponent,
  SuspenseComponent,
  SuspenseListComponent,
  OffscreenComponent,
  LegacyHiddenComponent,
  CacheComponent,
  Tra

nTracing,
} from 'shared/ReactFeatureFlags';

import {popHostContainer, popHostContext} from './ReactFiberHostContext';
import {
  popSuspenseListContext,
  popSuspenseHandler,
} from './ReactFiberSuspenseContext';
import {popHiddenContext} from './ReactFi

cingMarkerComponent,
} from './ReactWorkTags';
import {DidCapture, NoFlags, ShouldCapture, Update} from './ReactFiberFlags';
import {NoMode, ProfileMode} from './ReactTypeOfMode';
import {
  enableProfilerTimer,
  enableTransitio


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 {ViewTransitionClass, ViewTransitionProps} from 'shared/ReactTypes';
import type {FiberRoot} from './ReactInternalTypes';
import type {ViewTransitionInstance, Instance} from './ReactFiberConfig';

import {
  getCommittingRoot,
  getPendingTransitionTypes,
} from './ReactFiberWorkLoop';

export type ViewTransitionState = {
  autoName: null | stri

nstance>, // a temporary state during the apply gesture phase if we cloned this boundary
  ref: null | ViewTransitionInstance, // the current ref instance. This can change through the lifetime of the instance.
};

let globalClientIdCounter: number = 0;

ex

ng, // the view-transition-name to use when an explicit one is not specified
  paired: null | ViewTransitionState, // a temporary state during the commit phase if we have paired this with another instance
  clones: null | Array<I


 * 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 {REACT_PORTAL_TYPE, REACT_OPTIMISTIC_KEY} from 'shared/ReactSymbols';
import {checkKeyStringCoercion} from 'shared/CheckStringCoercion';

import type {
  ReactNodeList,
  ReactPortal,
  ReactOptimisticKey,
} from 'shared/ReactTypes';

export function createPortal(
  children: ReactNodeList,
  containerI

se if (key === REACT_OPTIMISTIC_KEY) {
    resolvedKey = REACT_OPTIMISTIC_KEY;
  } else {
    if (__DEV__) {
      checkKeyStringCoercion(key);
    }
    resolvedKey = '' + key;
  }
  return {
    // This tag allow us to uniquely identify this as a React P

nfo: any,
  // TODO: figure out the API for cross-renderer implementation.
  implementation: any,
  key: ?string | ReactOptimisticKey = null,
): ReactPortal {
  let resolvedKey;
  if (key == null) {
    resolvedKey = null;
  } el


ctLegacyMode} from './ReactTypeOfMode';

type FiberArray = Array<Fiber>;
type FiberToFiberComponentsMap = Map<Fiber, FiberArray>;

const ReactStrictModeWarnings = {
  recordUnsafeLifecycleWarnings: (fiber: Fiber, instance: any): void => {},
  flushPendingUnsafeLifecycleWarnings: (): void => {},
  recordLegacyContextWarning: (fiber: Fiber, instance: any): void => {},
  flushLegacyContextWarning: (): void => {},
  discardPendingWarnings: (): void => {},
};

if (__DEV__) {
  const findStrictRoot = (fiber: Fibe

  }

    return maybeStrictRoot;
  };

  const setToSortedString = (set: Set<string>) => {
    const array = [];
    set.forEach(value => {
      array.push(value);
    });
    return array.sort().join(', ');
  };

  let pendingComponentWillMountWarnings:

r): Fiber | null => {
    let maybeStrictRoot = null;

    let node: null | Fiber = fiber;
    while (node !== null) {
      if (node.mode & StrictLegacyMode) {
        maybeStrictRoot = node;
      }
      node = node.return;


reconciler/src/ReactWorkTags';
import getComponentNameFromType from 'shared/getComponentNameFromType';
import {
  findFiberRoot,
  getBoundingRect,
  getInstanceFromNode,
  getTextContent,
  isHiddenSubtree,
  matchAccessibilityRole,
  setFocusIfFocusable,
  setupIntersectionObserver,
  supportsTestSelectors,
} from './ReactFiberConfig';

let COMPONENT_TYPE: symbol | number = 0b000;
let HAS_PSEUDO_CLASS_TYPE: symbol | number = 0b001;
let ROLE_TYPE: symbol | number = 0b010;
let TEST_NAME_TYPE: symbol | numbe

or.has_pseudo_class');
  ROLE_TYPE = symbolFor('selector.role');
  TEST_NAME_TYPE = symbolFor('selector.test_id');
  TEXT_TYPE = symbolFor('selector.text');
}

type Type = symbol | number;

type ComponentSelector = {
  $$typeof: Type,
  value: component(),

r = 0b011;
let TEXT_TYPE: symbol | number = 0b100;

if (typeof Symbol === 'function' && Symbol.for) {
  const symbolFor = Symbol.for;
  COMPONENT_TYPE = symbolFor('selector.component');
  HAS_PSEUDO_CLASS_TYPE = symbolFor('select


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

import {
  disableLegacyMode,
  enableLegacyHidden,
  enableViewTransition,
} from 'shared/ReactFeatureFlags';

import {
  FunctionComponent,
  ClassComponent,
  HostRoot,
  HostPortal,
  HostComponent,
  HostHoistable,
  HostSingleton,
  HostText,
  Fragment,
  Mode,
  ContextConsumer,
  ContextProvider,
  ForwardRef,
  Profiler,
  SuspenseComponent,
  MemoComponent,
  SimpleMemoCompone

onent,
  Throw,
  ViewTransitionComponent,
  ActivityComponent,
} from 'react-reconciler/src/ReactWorkTags';
import getComponentNameFromType from 'shared/getComponentNameFromType';
import {REACT_STRICT_MODE_TYPE} from 'shared/ReactSymbols';
import type {Re

nt,
  LazyComponent,
  IncompleteClassComponent,
  IncompleteFunctionComponent,
  DehydratedFragment,
  SuspenseListComponent,
  ScopeComponent,
  OffscreenComponent,
  LegacyHiddenComponent,
  CacheComponent,
  TracingMarkerComp


et Activity;
let useState;
let assertLog;

describe('Activity error handling', () => {
  beforeEach(() => {
    jest.resetModules();

    React = require('react');
    ReactNoop = require('react-noop-renderer');
    Scheduler = require('scheduler');
    act = require('internal-test-utils').act;
    Activity = React.Activity;
    useState = React.useState;

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

  function Text({text}) {
    Scheduler

ull};
        static getDerivedStateFromError(error) {
          return {error};
        }
        render() {
          if (this.state.error) {
            return (
              <Text text={`Caught an error: ${this.state.error.message}`} />
            );

.log(text);
    return text;
  }

  it(
    'errors inside a hidden Activity do not escape in the visible part ' +
      'of the UI',
    async () => {
      class ErrorBoundary extends React.Component {
        state = {error: n


 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
 * @jest-environment node
 */

'use strict';

let act;
let Activity;
let React;
let ReactServer;
let ReactNoop;
let ReactNoopFlightClient;
let ReactNoopFlightServer;

describe('ActivityReactServer', () => {
  beforeEach(() => {
    jest.resetModules();
    jest.mock('react', () => require('react/react.react-server'));
    R

oopFlightClient = require('react-noop-renderer/flight-client');
    ReactNoop = require('react-noop-renderer');
    const InternalTestUtils = require('internal-test-utils');
    act = InternalTestUtils.act;
  });

  afterEach(() => {
    jest.restoreAllMoc

eactServer = require('react');
    Activity = ReactServer.Activity;
    ReactNoopFlightServer = require('react-noop-renderer/flight-server');

    jest.resetModules();
    __unmockReact();
    React = require('react');
    ReactN


duler');
    act = require('internal-test-utils').act;
    LegacyHidden = React.unstable_LegacyHidden;
    Activity = React.Activity;
    Suspense = React.Suspense;
    useState = React.useState;
    useEffect = React.useEffect;
    startTransition = React.startTransition;
    use = React.use;

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

    textCache =

, newRecord);
    } else if (record.status === 'pending') {
      const resolve = record.resolve;
      record.status = 'resolved';
      record.value = text;
      resolve();
    }
  }

  function readText(text) {
    const record = textCache.get(text);

new Map();
  });

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


;

// These tests are mostly concerned with concurrent roots. The legacy root
// behavior is covered by other older test suites and is unchanged from
// React 17.
describe('act warnings', () => {
  beforeEach(() => {
    jest.resetModules();
    React = require('react');
    Scheduler = require('scheduler');
    ReactNoop = require('react-noop-renderer');
    act = React.act;
    useState = React.useState;
    Suspense = React.Suspense;
    startTransition = React.startTransition;
    getCacheForType = Reac

nternalTestUtils.assertConsoleErrorDev;
  });

  function createTextCache() {
    const data = new Map();
    const version = caches.length + 1;
    const cache = {
      version,
      data,
      resolve(text) {
        const record = data.get(text);

t.unstable_getCacheForType;
    caches = [];

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


let TextResource;
let act;

describe('ReactBlockingMode', () => {
  beforeEach(() => {
    jest.resetModules();
    React = require('react');
    ReactNoop = require('react-noop-renderer');
    Scheduler = require('scheduler');
    ReactCache = require('react-cache');
    Suspense = React.Suspense;

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

    TextResource = Reac

  }, ms),
        );
      },
      ([text, ms]) => text,
    );
  });

  function Text(props) {
    Scheduler.log(props.text);
    return props.text;
  }

  function AsyncText(props) {
    const text = props.text;
    try {
      TextResource.read([props.

tCache.unstable_createResource(
      ([text, ms = 0]) => {
        return new Promise((resolve, reject) =>
          setTimeout(() => {
            Scheduler.log(`Promise resolved [${text}]`);
            resolve(text);


;
let waitForPaint;

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

    React = require('react');
    ReactNoop = require('react-noop-renderer');
    Scheduler = require('scheduler');
    act = require('internal-test-utils').act;
    Suspense = React.Suspense;
    useState = React.useState;

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

    textCa

ejected':
            throw Error('Failed to load: ' + text);
          case 'resolved':
            return text;
        }
      } else {
        let ping;
        const promise = new Promise(resolve => (ping = resolve));
        const newRecord = {

che = new Map();

    readText = text => {
      const record = textCache.get(text);
      if (record !== undefined) {
        switch (record.status) {
          case 'pending':
            throw record.promise;
          case 'r


act;
let ReactNoop;
let Scheduler;
let act;
let assertLog;

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

    React = require('react');
    ReactNoop = require('react-noop-renderer');
    Scheduler = require('scheduler');
    act = require('internal-test-utils').act;

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

  function Text({text}) {
    Scheduler.log(text);
    return text;
  }

  it('re

ext text={this.state.step} />;
      }
    }

    const root = ReactNoop.createRoot();
    await act(() => {
      root.render(<App />);
    });
    assertLog([0]);

    await act(() => {
      React.startTransition(() => {
        app.setState({step: 1},

gression: setState callback (2nd arg) should only fire once, even after a rebase', async () => {
    let app;
    class App extends React.Component {
      state = {step: 0};
      render() {
        app = this;
        return <T


ct-core
 */

'use strict';

let React;
let ReactDOMClient;
let Scheduler;
let container;
let act;

async function fakeAct(cb) {
  // We don't use act/waitForThrow here because we want to observe how errors are reported for real.
  await cb();
  Scheduler.unstable_flushAll();
}

describe('ReactConfigurableErrorLogging', () => {
  beforeEach(() => {
    jest.resetModules();
    React = require('react');
    ReactDOMClient = require('react-dom/client');
    Scheduler = require('scheduler');
    container = doc

ctor(props) {
        super(props);
        throw new Error('constructor error');
      }
      render() {
        return <div />;
      }
    }
    const uncaughtErrors = [];
    const caughtErrors = [];
    const root = ReactDOMClient.createRoot(containe

ument.createElement('div');
    if (__DEV__) {
      act = React.act;
    }
  });

  it('should log errors that occur during the begin phase', async () => {
    class ErrorThrowingComponent extends React.Component {
      constru


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 {FiberRoot} from './ReactInternalTypes';
import type {TransitionTypes} from 'react/src/ReactTransitionType';

import {enableViewTransition} from 'shared/ReactFeatureFlags';
import {includesTransitionLane} from './ReactFiberLane';

export function queueTransitionTypes(
  root: FiberRoot,
  transitionTypes: TransitionTypes,
): void {
  if (enableV

nLane(root.pendingLanes)) {
      let queued = root.transitionTypes;
      if (queued === null) {
        queued = root.transitionTypes = [];
      }
      for (let i = 0; i < transitionTypes.length; i++) {
        const transitionType = transitionTypes[i]

iewTransition) {
    // TODO: We should really store transitionTypes per lane in a LaneMap on
    // the root. Then merge it when we commit. We currently assume that all
    // Transitions are entangled.
    if (includesTransitio


t type {TransitionTypes} from 'react/src/ReactTransitionType';
import type {WorkTag} from './ReactWorkTags';
import type {TypeOfMode} from './ReactTypeOfMode';
import type {Flags} from './ReactFiberFlags';
import type {Lane, Lanes, LaneMap} from './ReactFiberLane';
import type {RootTag} from './ReactRootTags';
import type {
  Container,
  Instance,
  TimeoutHandle,
  NoTimeout,
  ActivityInstance,
  SuspenseInstance,
  TransitionStatus,
} from './ReactFiberConfig';
import type {Cache} from './ReactFiberCach

rt type {ComponentStackNode} from 'react-server/src/ReactFizzComponentStack';
import type {ThenableState} from './ReactFiberThenable';
import type {ScheduledGesture} from './ReactFiberGestureScheduler';

// Unwind Circular: moved from ReactFiberHooks.old
e

eComponent';
import type {Transition} from 'react/src/ReactStartTransition';
import type {TracingMarkerInstance} from './ReactFiberTracingMarkerComponent';
import type {ConcurrentUpdate} from './ReactFiberConcurrentUpdates';
impo


, 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 type TypeOfMode = number;

export const NoMode = /*                         */ 0b0000000;
// TODO: Remove ConcurrentMode by reading from the root tag instead
export const ConcurrentMode = /*                 */ 0b0000001;
export const ProfileMode = /*                    */ 0b0000010;
//export const DebugTracingMode = /*             */

= /*               */ 0b0001000;
export const StrictEffectsMode = /*              */ 0b0010000;
// Keep track of if we're in a SuspenseyImages eligible subtree.
// TODO: Remove this when enableSuspenseyImages ship where it's always on.
export const Suspens

0b0000100; // Removed
export const StrictLegacyMode


onst root = ReactNoop.createRoot();
    await act(async () => {
      root.render(<App mode="unstable-defer-without-hiding" />);
      await waitForPaint(['Normal']);
      expect(root).toMatchRenderedOutput();
    });
    assertLog(['Deferred']);
    expect(root).toMatchRenderedOutput(
      <>

      </>,
    );

    // Now try after an update
    await act(() => {
      root.render(<App mode="visible" />);
    });
    as

e-defer-without-hiding" />);
      await waitForPaint(['Normal']);
      expect(root).toMatchRenderedOutput(
        <>

        </>,
      );
    });
    assertLog(['Deferred']);
    expec

sertLog(['Normal', 'Deferred']);
    expect(root).toMatchRenderedOutput(
      <>

      </>,
    );

    await act(async () => {
      root.render(<App mode="unstabl


 React.Activity;
    ReactNoop = require('react-noop-renderer');
    act = require('internal-test-utils').act;
  });

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

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

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

    return <span>label</s

<Component label="A" />
          </Activity>
        </React.StrictMode>,
      );
    });

    expect(log).toEqual([
      'A: render',
      'A: render',
      'A: useLayoutEffect mount',
      'A: useEffect mount',
      'A: useLayoutEffect unmount',

pan>;
  }

  // @gate __DEV__
  it('should trigger strict effects when offscreen is visible', async () => {
    await act(() => {
      ReactNoop.render(
        <React.StrictMode>
          <Activity mode="visible">


henable = {
        pings: [],
        then(resolve) {
          if (newRecord.status === 'pending') {
            thenable.pings.push(resolve);
          } else {
            Promise.resolve().then(() => resolve(newRecord.value));
          }
        },
      };

      const newRecord = {
        status: 'pending',
        value: thenable,
      };
      textCache.set(text, newRecord);

      throw thenable;
    }
  }

  function getText(text) {
    const record = textCache.get(text);
    if (record === un

resolve(newRecord.value));
          }
        },
      };
      const newRecord = {
        status: 'pending',
        value: thenable,
      };
      textCache.set(text, newRecord);
      return thenable;
    } else {
      switch (record.status) {

defined) {
      const thenable = {
        pings: [],
        then(resolve) {
          if (newRecord.status === 'pending') {
            thenable.pings.push(resolve);
          } else {
            Promise.resolve().then(() =>


ct-core
 * @jest-environment node
 */

'use strict';

let React;
let ReactNoopFlightServer;
let ReactNoopFlightClient;
let cache;
let cacheSignal;

describe('ReactCache', () => {
  beforeEach(() => {
    jest.resetModules();
    jest.mock('react', () => require('react/react.react-server'));
    React = require('react');

    ReactNoopFlightServer = require('react-noop-renderer/flight-server');
    ReactNoopFlightClient = require('react-noop-renderer/flight-client');

    cache = React.cache;
    cacheSignal

on Print({a, b}) {
      return types(a, b).a + ' ' + types(a, b).b + ' ';
    }
    function Same({a, b}) {
      const x = types(a, b);
      const y = types(a, b);
      return (x === y).toString() + ' ';
    }
    function FlippedOrder({a, b}) {

 = React.cacheSignal;

    jest.resetModules();
    __unmockReact();
  });

  it('cache objects and primitive arguments and a mix of them', async () => {
    const types = cache((a, b) => ({a: typeof a, b: typeof b}));
    functi


    Suspense = React.Suspense;
    startTransition = React.startTransition;

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

    getCacheForType = React.unstable_getCacheForType;

    caches = [];
    seededCache = null;
  });

  function createTextCache() {
    if (seededCache !== null) {
      // Trick to seed a cache before it exists.
      // TODO: Need a built-in API to seed data before the initial render (i.e.
      // not a refresh because

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

nothing has mounted yet).
      const cache = seededCache;
      seededCache = null;
      return cache;
    }

    const data = new Map();
    const version = caches.length + 1;
    const cache = {
      version,
      data,


';

import getComponentNameFromFiber from './getComponentNameFromFiber';
import {isAlreadyRendering} from './ReactFiberWorkLoop';

// Intentionally not named imports because Rollup would use dynamic dispatch for
// CommonJS interop named imports.
import * as Scheduler from 'scheduler';

const {unstable_now: now} = Scheduler;

const createTask =
  // eslint-disable-next-line react-internal/no-production-logging
  __DEV__ && console.createTask
    ? // eslint-disable-next-line react-internal/no-production-log

| 1 | 2;

export let renderStartTime: number = -0;
export let commitStartTime: number = -0;
export let commitEndTime: number = -0;
export let commitErrors: null | Array<CapturedValue<mixed>> = null;
export let profilerStartTime: number = -1.1;
export let p

ging
      console.createTask
    : (name: string) => null;

export const REGULAR_UPDATE: UpdateType = 0;
export const SPAWNED_UPDATE: UpdateType = 1;
export const PINGED_UPDATE: UpdateType = 2;
export opaque type UpdateType = 0


 Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

// This module only exists as an ESM wrapper around the external CommonJS
// Scheduler dependency. Notice that we're intentionally not using named imports
// because Rollup would use dynamic dispatch for CommonJS interop named imports.
// When we switch to ESM, we can delete this module.
import * as Scheduler from 'scheduler';

exp

nstable_requestPaint;
export const now = Scheduler.unstable_now;
export const getCurrentPriorityLevel =
  Scheduler.unstable_getCurrentPriorityLevel;
export const ImmediatePriority = Scheduler.unstable_ImmediatePriority;
export const UserBlockingPriority =

ort const scheduleCallback = Scheduler.unstable_scheduleCallback;
export const cancelCallback = Scheduler.unstable_cancelCallback;
export const shouldYield = Scheduler.unstable_shouldYield;
export const requestPaint = Scheduler.u


et BrokenRender;
  let DidCatchErrorBoundary;
  let GetDerivedErrorBoundary;
  let React;
  let ReactTestRenderer;
  let span;
  let act;

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

    ReactTestRenderer = require('react-test-renderer');
    React = require('react');
    act = require('internal-test-utils').act;
    DidCatchErrorBoundary = class extends React.Component {
      state = {error: null};
      componentDidCatch(error) {
        this.setState({error});
      }
      render() {
        return

.Component {
      state = {error: null};
      static getDerivedStateFromError(error) {
        return {error};
      }
      render() {
        return this.state.error
          ? React.createElement(this.props.fallbackTagName, {
              prop: 'Err

this.state.error
          ? React.createElement(this.props.fallbackTagName, {
              prop: 'ErrorBoundary',
            })
          : this.props.children;
      }
    };

    GetDerivedErrorBoundary = class extends React


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

'use strict';

let React;
let ReactNoop;
let Scheduler;
let act;
let assertLog;

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

    React = require('react');
    ReactNoop = require('react-noop-renderer');
    Scheduler = require('scheduler');
    act = require('internal-test-utils').act;
    assertLog = require('internal-test-utils').assert

PropKeys(props) {
      return Object.keys(props).join(', ');
    }

    class Component extends React.Component {
      constructor(props) {
        super(props);
        Scheduler.log('constructor: ' + getPropKeys(props));
      }
      shouldComponentUp

Log;
  });

  function Text({text}) {
    Scheduler.log(text);
    return text;
  }

  it('resolves ref and default props before calling lifecycle methods', async () => {
    const root = ReactNoop.createRoot();

    function get


rLayoutEffects,
  disconnectPassiveEffect,
  invokeLayoutEffectMountInDEV,
  invokePassiveEffectMountInDEV,
  invokeLayoutEffectUnmountInDEV,
  invokePassiveEffectUnmountInDEV,
  accumulateSuspenseyCommit,
} from './ReactFiberCommitWork';
import {resetShouldStartViewTransition} from './ReactFiberCommitViewTransitions';
import {shouldStartViewTransition} from './ReactFiberCommitViewTransitions';
import {
  insertDestinationClones,
  applyDepartureTransitions,
  startGestureAnimations,
} from './ReactFiberApp

actFiberHooks';
import {DefaultAsyncDispatcher} from './ReactFiberAsyncDispatcher';
import {
  createCapturedValueAtFiber,
  type CapturedValue,
} from './ReactCapturedValue';
import {
  enqueueConcurrentRenderForLane,
  finishQueueingConcurrentUpdates,

lyGesture';
import {enqueueUpdate} from './ReactFiberClassUpdateQueue';
import {resetContextDependencies} from './ReactFiberNewContext';
import {
  resetHooksAfterThrow,
  resetHooksOnUnwind,
  ContextOnlyDispatcher,
} from './Re


    act = require('internal-test-utils').act;
    LegacyHidden = React.unstable_LegacyHidden;
    Activity = React.Activity;
    Suspense = React.Suspense;
    useState = React.useState;
    useEffect = React.useEffect;
    startTransition = React.startTransition;

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

    textCache = new Map();
  });

  function r

ecord.status === 'pending') {
      const thenable = record.value;
      record.status = 'resolved';
      record.value = text;
      thenable.pings.forEach(t => t());
    }
  }

  function readText(text) {
    const record = textCache.get(text);
    if (r

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


xport function getNearestMountedFiber(fiber: Fiber): null | Fiber {
  let node = fiber;
  let nearestMounted: null | Fiber = fiber;
  // If there is no alternate, this might be a new tree that isn't inserted
  // yet. If it is, then it will have a pending insertion effect on it.
  let nextNode: Fiber = node;
  while (nextNode && !nextNode.alternate) {
    node = nextNode;
    if ((node.flags & (Placement | Hydrating)) !== NoFlags) {
      // This is an insertion or in-progress hydration. The nearest possibl

 nextNode = node.return;
  }
  // After we've reached an alternate, go the rest of the way to see if the
  // tree is still mounted. If it's not, its return pointer will be disconnected.
  while (node.return) {
    node = node.return;
  }
  if (node.tag ==

e
      // mounted fiber is the parent but we need to continue to figure out
      // if that one is still mounted.
      nearestMounted = node.return;
    }
    // $FlowFixMe[incompatible-type] we bail out when we get a null


 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
 * @jest-environment node
 */

'use strict';

let React;
let ReactNoop;
let assertConsoleErrorDev;
let waitForAll;
let waitForThrow;

describe('ReactIncrementalErrorReplay', () => {
  beforeEach(() => {
    jest.resetModules();
    React = require('react');
    ReactNoop = require('react-noop-renderer');

    const Internal

d fail gracefully on error in the host environment', async () => {
    ReactNoop.render(<errorInBeginPhase />);
    await waitForThrow('Error in host config.');
  });

  it("should ignore error if it doesn't throw on retry", async () => {
    let didInit =

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

  it('shoul


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

'use strict';

let React;
let ReactNoopPersistent;
let act;

describe('ReactPersistentUpdatesMinimalism', () => {
  beforeEach(() => {
    jest.resetModules();
    React = require('react');
    ReactNoopPersistent = require('react-noop-renderer/persistent');
    act = require('internal-test-utils').act;
  });

  it('should render a simple component', async () => {

);
    expect(ReactNoopPersistent.stopTrackingHostCounters()).toEqual({
      hostCloneCounter: 0,
    });

    ReactNoopPersistent.startTrackingHostCounters();
    await act(() => ReactNoopPersistent.render(<Parent />));
    expect(ReactNoopPersistent.sto

function Child() {
      return
Hello World
;
    }

    function Parent() {
      return <Child />;
    }

    ReactNoopPersistent.startTrackingHostCounters();
    await act(() => ReactNoopPersistent.render(<Parent />)


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

    React = require('react');
    ReactNoop = require('react-noop-renderer');
    Scheduler = require('scheduler');
    act = require('internal-test-utils').act;

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

  it('schedules and flushes deferred wor

rk on other roots once the current root completes', async () => {
    ReactNoop.renderToRootWithID(, 'a');
    ReactNoop.renderToRootWithID(, 'b');
    ReactNoop.renderToRootWithID(, 'c');

    await

k', async () => {
    ReactNoop.render();
    expect(ReactNoop).toMatchRenderedOutput(null);

    await waitForAll([]);
    expect(ReactNoop).toMatchRenderedOutput();
  });

  it('searches for wo


s');
    waitForAll = InternalTestUtils.waitForAll;
    waitFor = InternalTestUtils.waitFor;
    assertLog = InternalTestUtils.assertLog;
    assertConsoleErrorDev = InternalTestUtils.assertConsoleErrorDev;
  });

  function Text({text}) {
    Scheduler.log(text);
    return text;
  }

  it('applies updates in order of priority', async () => {
    let state;
    class Foo extends React.Component {
      state = {};
      componentDidMount() {
        Scheduler.log('commit');
        React.startTransition(()

te;
        return <div />;
      }
    }

    ReactNoop.render(<Foo />);
    await waitFor(['commit']);

    expect(state).toEqual({a: 'a'});
    await waitForAll([]);
    expect(state).toEqual({a: 'a', b: 'b', c: 'c'});
  });

  it('applies updates with

 => {
          // Has low priority
          this.setState({b: 'b'});
          this.setState({c: 'c'});
        });
        // Has Task priority
        this.setState({a: 'a'});
      }
      render() {
        state = this.sta


t assertLog;
let waitFor;
let waitForPaint;

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

    React = require('react');
    ReactNoop = require('react-noop-renderer');
    Scheduler = require('scheduler');
    act = require('internal-test-utils').act;
    startTransition = React.startTransition;
    useState = React.useState;
    useEffect = React.useEffect;

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

sed during the current render', async () => {
    const updaters = [];

    function Child() {
      const [state, setState] = useState(0);
      useEffect(() => {
        updaters.push(setState);
      }, []);
      return <Text text={state} />;
    }

g;
    waitFor = InternalTestUtils.waitFor;
    waitForPaint = InternalTestUtils.waitForPaint;
  });

  function Text({text}) {
    Scheduler.log(text);
    return text;
  }

  it('update during an interleaved event is not proces


escribe('isomorphic act()', () => {
  beforeEach(() => {
    React = require('react');
    Scheduler = require('scheduler');

    ReactNoop = require('react-noop-renderer');
    DiscreteEventPriority =
      require('react-reconciler/constants').DiscreteEventPriority;
    act = React.act;
    use = React.use;
    Suspense = React.Suspense;
    startTransition = React.startTransition;

    waitForMicrotasks = require('internal-test-utils').waitForMicrotasks;
    assertLog = require('internal-test-utils').ass

 in production', () => {
    if (!__DEV__) {
      if (gate('fb')) {
        expect(() => act(() => {})).toThrow(
          'act(...) is not supported in production builds of React',
        );
      } else {
        expect(React).not.toHaveProperty('act')

ertLog;
  });

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

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

  function Text({text}) {
    Scheduler.log(text);
    return text;
  }

  it('behavior


  </div>
    );
  }

  // We have several ways of reading from context. sharedContextTests runs
  // a suite of tests for a given context consumer implementation.
  sharedContextTests('Context.Consumer', Context => Context.Consumer);
  sharedContextTests(
    'useContext inside function component',
    Context =>
      function Consumer(props) {
        const contextValue = useContext(Context);
        const render = props.children;
        return render(contextValue);
      },
  );
  sharedContextTests('us

,
  );
  sharedContextTests('useContext inside memoized function component', Context =>
    React.memo(function Consumer(props) {
      const contextValue = useContext(Context);
      const render = props.children;
      return render(contextValue);
    })

eContext inside forwardRef component', Context =>
    React.forwardRef(function Consumer(props, ref) {
      const contextValue = useContext(Context);
      const render = props.children;
      return render(contextValue);
    })


actOwnerStacks', () => {
  beforeEach(function () {
    let time = 10;
    advanceTimersByTime = timeMS => {
      jest.advanceTimersByTime(timeMS);
      time += timeMS;
    };

    const now = jest.fn().mockImplementation(() => {
      return time++;
    });
    Object.defineProperty(performance, 'timeOrigin', {
      value: time,
      configurable: true,
    });
    Object.defineProperty(performance, 'now', {
      value: now,
      configurable: true,
    });

    jest.resetModules();
    React = requi

('internal-test-utils').assertLog;
    serverAct = require('internal-test-utils').serverAct;
    waitFor = require('internal-test-utils').waitFor;
  });

  function normalizeCodeLocInfo(str) {
    return (
      str &&
      str.replace(/\n +(?:at|in) ([\S

re('react');
    ReactNoop = require('react-noop-renderer');
    ReactNoopServer = require('react-noop-renderer/server');
    Scheduler = require('scheduler');
    act = require('internal-test-utils').act;
    assertLog = require


ed': {
              throw newRecord.value;
            }
          }
        },
      };
      fakeModuleCache.set(Component, newRecord);
      return newRecord;
    }
    return record;
  }

  function resolveFakeImport(moduleName) {
    const record = fakeModuleCache.get(moduleName);
    if (record === undefined) {
      throw new Error('Module not found');
    }
    if (record.status !== 'pending') {
      throw new Error('Module already resolved');
    }
    record.status = 'resolved';
    record.pings

="Loading..." />}>
        <LazyText text="Hi" />
      </Suspense>,
      {
        unstable_isConcurrent: true,
      },
    );

    await waitForAll(['Loading...']);
    expect(root).not.toMatchRenderedOutput('Hi');

    await act(() => resolveFakeImpor

.forEach(ping => ping(record.value));
  }

  it('suspends until module has loaded', async () => {
    const LazyText = lazy(() => fakeImport(Text));

    const root = ReactTestRenderer.create(
      <Suspense fallback={<Text text


    function Counter({incrementBy}) {
      const [count, updateCount] = useState(0);
      const onClick = useEffectEvent(() => updateCount(c => c + incrementBy));

      return (
        <>
          <IncrementButton onClick={() => onClick()} ref={button} />
          <Text text={'Count: ' + count} />
        </>
      );
    }

    const button = React.createRef(null);
    ReactNoop.render(<Counter incrementBy={1} />);
    await waitForAll(['Increment', 'Count: 0']);
    expect(ReactNoop).toMatchRendered

edOutput(
      <>

      </>,
    );

    await act(() => button.current.increment());
    assertLog([
      'Increment',
      // Event should use the updated callback function closed over

Output(
      <>

      </>,
    );

    await act(() => button.current.increment());
    assertLog(['Increment', 'Count: 1']);
    expect(ReactNoop).toMatchRender


assertLog;
    useMemo = React.useMemo;
    useMemoCache = require('react/compiler-runtime').c;
    useState = React.useState;
    MemoCacheSentinel = Symbol.for('react.memo_cache_sentinel');

    class _ErrorBoundary extends React.Component {
      constructor(props) {
        super(props);
        this.state = {hasError: false};
      }

      static getDerivedStateFromError(error) {
        // Update state so the next render will show the fallback UI.
        return {hasError: true};
      }

      compo

ren;
      }
    }
    ErrorBoundary = _ErrorBoundary;
  });

  it('render component using cache', async () => {
    function Component(props) {
      const cache = useMemoCache(1);
      expect(Array.isArray(cache)).toBe(true);
      expect(cache.length).

nentDidCatch(error, errorInfo) {}

      render() {
        if (this.state.hasError) {
          // You can render any custom fallback UI
          return
Something went wrong.
;
        }

        return this.props.child


ct-core
 * @jest-environment node
 */

'use strict';

describe('useRef', () => {
  let React;
  let ReactNoop;
  let Scheduler;
  let act;
  let useCallback;
  let useEffect;
  let useLayoutEffect;
  let useRef;
  let useState;
  let waitForAll;
  let assertLog;

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

    act = require('internal-test-utils').act;
    useCallback = React.useCallback;
    useEffect = React.useEf

Log = InternalTestUtils.assertLog;
  });

  function Text(props) {
    Scheduler.log(props.text);
    return <span prop={props.text} />;
  }

  it('creates a ref object initialized with the provided value', async () => {
    jest.useFakeTimers();

    func

fect;
    useLayoutEffect = React.useLayoutEffect;
    useRef = React.useRef;
    useState = React.useState;

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


startTransition;
let waitFor;
let waitForAll;
let assertLog;
let Suspense;
let useMemo;
let textCache;

// This tests the native useSyncExternalStore implementation, not the shim.
// Tests that apply to both the native implementation and the shim should go
// into useSyncExternalStoreShared-test.js. The reason they are separate is
// because at some point we may start running the shared tests against vendored
// React DOM versions (16, 17, etc) instead of React Noop.
describe('useSyncExternalStore', () => {

dle = React.useImperativeHandle;
    forwardRef = React.forwardRef;
    useRef = React.useRef;
    useState = React.useState;
    use = React.use;
    useSyncExternalStore = React.useSyncExternalStore;
    startTransition = React.startTransition;
    Suspe

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

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


he `react-reconciler` we treat host config as a module.
// This file is a shim between two worlds.
//
// It works because the `react-reconciler` bundle is wrapped in something like:
//
// module.exports = function ($$$config) {
//   /* reconciler code */
// }
//
// So `$$$config` looks like a global variable, but it's
// really an argument to a top-level wrapping function.

declare const $$$config: any;
export opaque type Type = mixed;
export opaque type Props = mixed;
export opaque type Container = mixed;

type PublicInstance = mixed;
export opaque type HostContext = mixed;
export opaque type UpdatePayload = mixed;
export opaque type ChildSet = mixed;
export opaque type TimeoutHandle = mixed;
export opaque type NoTimeout = mixed;
export opaque type RendererI

export opaque type Instance = mixed;
export opaque type TextInstance = mixed;
export opaque type ActivityInstance = mixed;
export opaque type SuspenseInstance = mixed;
export opaque type HydratableInstance = mixed;
export opaque


module.
// This file is a shim between two worlds.
//
// It works because the `react-reconciler` bundle is wrapped in something like:
//
// module.exports = function ($$$config) {
//   /* reconciler code */
// }
//
// So `$$$config` looks like a global variable, but it's
// really an argument to a top-level wrapping function.

export * from 'react-noop-renderer/src/ReactFiberConfigNoop';

declare const $$$config: $FlowFixMe;
export opaque type Type = mixed;
export opaque type Props = mixed;
export opaque ty

dle = mixed;
export opaque type NoTimeout = mixed;
export opaque type RendererInspectionConfig = mixed;
export opaque type FormInstance = mixed;
export opaque type SuspendedState = mixed;
export type RunningViewTransition = mixed;
export type ViewTransitio

pe ActivityInstance = mixed;
export opaque type SuspenseInstance = mixed;
export opaque type HydratableInstance = mixed;
export opaque type UpdatePayload = mixed;
export opaque type ChildSet = mixed;
export opaque type TimeoutHan


/simulateBrowserEventDispatch';
import {
  clearLogs,
  clearWarnings,
  clearErrors,
  createLogAssertion,
} from './consoleMock';
export {getDebugInfo} from './debugInfo';
export {act, serverAct} from './internalAct';
const {assertConsoleLogsCleared} = require('internal-test-utils/consoleMock');

import {thrownErrors, actingUpdatesScopeDepth} from './internalAct';

function assertYieldsWereCleared(caller) {
  const actualYields = SchedulerMock.unstable_clearLog();
  if (actualYields.length !== 0) {
    co

 {
  return new Promise(resolve => {
    enqueueTask(() => resolve());
  });
}

export async function waitFor(expectedLog, options) {
  assertYieldsWereCleared(waitFor);

  // Create the error object before doing any async work, to get a better
  // stack

nst error = Error(
      'The event log is not empty. Call assertLog(...) first.',
    );
    Error.captureStackTrace(error, caller);
    throw error;
  }
  assertConsoleLogsCleared();
}

export async function waitForMicrotasks()


export function setupDocumentReadyState(
  document: Document,
  Event: typeof Event,
) {
  let readyState: 0 | 1 | 2 = 0;
  Object.defineProperty(document, 'readyState', {
    get() {
      switch (readyState) {
        case 0:
          return 'loading';
        case 1:
          return 'interactive';
        case 2:
          return 'complete';
      }
    },
    set(value) {
      if (value === 'interactive' && readyState < 1) {
        readyState = 1;
        document.dispatchEvent(new Event('readystat

else if (value === 'loading') {
        // We allow resetting the readyState to loading mostly for pragamtism.
        // tests that use this environment don't reset the document between tests.
        readyState = 0;
      }
    },
    configurable: true,

echange'));
      } else if (value === 'complete' && readyState < 2) {
        readyState = 2;
        document.dispatchEvent(new Event('readystatechange'));
        document.dispatchEvent(new Event('DOMContentLoaded'));
      }


]);
const loggedLogs = (global.__loggedLogs = global.__loggedLogs || []);

const patchConsoleMethod = (methodName, logged) => {
  const newMethod = function (format, ...args) {
    // Ignore uncaught errors reported by jsdom
    // and React addendums because they're too noisy.
    if (shouldIgnoreConsoleError(format, args)) {
      return;
    }

    // Ignore certain React warnings causing test failures
    if (methodName === 'warn' && shouldIgnoreConsoleWarn(format)) {
      return;
    }

    // Append

lly we could remove this check, but we have some tests like
      // useSyncExternalStoreShared-test that tests against React 17,
      // which doesn't have the captureOwnerStack method.
      if (React.captureOwnerStack) {
        const stack = React.cap

Component Stacks. Simulates a framework or DevTools appending them.
    if (
      typeof format === 'string' &&
      (methodName === 'error' || methodName === 'warn')
    ) {
      const React = require('react');

      // Idea


eFixedTime?: boolean,
  useV8Stack?: boolean,
};

function formatV8Stack(stack) {
  let v8StyleStack = '';
  if (stack) {
    for (let i = 0; i < stack.length; i++) {
      const [name] = stack[i];
      if (v8StyleStack !== '') {
        v8StyleStack += '\n';
      }
      v8StyleStack += '    in ' + name + ' (at **)';
    }
  }
  return v8StyleStack;
}

function normalizeStack(stack) {
  if (!stack) {
    return stack;
  }
  const copy = [];
  for (let i = 0; i < stack.length; i++) {
    const [name, file

ction normalizeIOInfo(config: DebugInfoConfig, ioInfo) {
  const {debugTask, debugStack, debugLocation, ...copy} = ioInfo;
  if (ioInfo.stack) {
    copy.stack = config.useV8Stack
      ? formatV8Stack(ioInfo.stack)
      : normalizeStack(ioInfo.stack);

, line, col, enclosingLine, enclosingCol] = stack[i];
    copy.push([
      name,
      file.replace(__REACT_ROOT_PATH_TEST__, ''),
      line,
      col,
      enclosingLine,
      enclosingCol,
    ]);
  }
  return copy;
}

fun


avior from the public
// version, too, since our constraints in our test suite are not the same as
// those of developers using React — we're testing React itself, as opposed to
// building an app with React.

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

import * as Scheduler from 'scheduler/unstable_mock';

import enqueueTask from './enqueueTask';
import {assertConsoleLogsCleared} from './consoleMock';
import {diff} from 'jest-diff';

export let actingUpdatesScopeDepth: number = 0;

export const throw

eof AggregateError === 'function') {
    return new AggregateError(errors);
  }
  return errors[0];
}

export async function act<T>(scope: () => Thenable<T>): Thenable<T> {
  if (Scheduler.unstable_flushUntilNextPaint === undefined) {
    throw Error(

nErrors: Array<mixed> = [];

async function waitForMicrotasks() {
  return new Promise(resolve => {
    enqueueTask(() => resolve());
  });
}

function aggregateErrors(errors: Array<mixed>): mixed {
  if (errors.length > 1 && typ


orts = function shouldIgnoreConsoleError(format, args) {
  if (__DEV__) {
    if (typeof format === 'string') {
      if (format.startsWith('%c%s')) {
        // Looks like a badged error message
        args.splice(0, 3);
      }
      if (
        args[0] != null &&
        ((typeof args[0] === 'object' &&
          typeof args[0].message === 'string' &&
          // This specific log has the same signature as error logging.
          // The trick is to get rid of this whole file.
          !format.includ

 error with addendum from ReactFiberErrorLogger.
        // They are noisy too so we'll try to ignore them.
        return true;
      }
      if (
        format.indexOf('ReactDOM.render was removed in React 19') !== -1 ||
        format.indexOf('ReactDOM

es('Failed to serialize an action') &&
          typeof args[0].stack === 'string') ||
          (typeof args[0] === 'string' &&
            args[0].indexOf('An error occurred in ') === 0))
      ) {
        // This looks like an


rotasks} = require('./ReactInternalTestUtils');

const EVENT_PHASE = {
  NONE: 0,
  CAPTURING_PHASE: 1,
  AT_TARGET: 2,
  BUBBLING_PHASE: 3,
};

// Hack to get Symbol(wrapper) for target nodes.
let wrapperSymbol;
function wrapperForImpl(impl) {
  if (impl == null) {
    return null;
  }

  return impl[wrapperSymbol];
}

// This is a forked implementation of the jsdom dispatchEvent. The goal of
// this fork is to match the actual browser behavior of user events more closely.
// Real browser events yield to m

r of real user interactions, so we simulate it.
//
// It's async because we need to wait for microtasks between event handlers.
//
// Taken from:
// https://github.com/jsdom/jsdom/blob/2f8a7302a43fff92f244d5f3426367a8eb2b8896/lib/jsdom/living/events/EventT

icrotasks in-between event handlers, which is
// different from programmatically calling dispatchEvent (which does not yield).
// JSDOM correctly implements programmatic dispatchEvent, but sometimes we need
// to test the behavio