From b19c9fedc22f992bc98cf31d4845951f9f2902ae Mon Sep 17 00:00:00 2001 From: gaearon Date: Fri, 16 Feb 2024 00:40:11 +0000 Subject: [PATCH] Remove non-JSX propTypes checks (#28326) Removes all `propTypes` validation called from outside the JSX factories. Haven't touched JSX. Tests that verify related behavior are stripped down to the non-`propTypes` logic. DiffTrain build for [fea900e45447214ddd6ef69076ab7e38433b5ffd](https://github.com/facebook/react/commit/fea900e45447214ddd6ef69076ab7e38433b5ffd) --- compiled/facebook-www/REVISION | 2 +- compiled/facebook-www/React-dev.classic.js | 6 +- compiled/facebook-www/React-dev.modern.js | 6 +- compiled/facebook-www/React-prod.classic.js | 2 +- compiled/facebook-www/React-prod.modern.js | 2 +- .../facebook-www/React-profiling.modern.js | 2 +- compiled/facebook-www/ReactART-dev.classic.js | 412 +- compiled/facebook-www/ReactART-dev.modern.js | 412 +- .../facebook-www/ReactART-prod.classic.js | 50 +- compiled/facebook-www/ReactART-prod.modern.js | 50 +- compiled/facebook-www/ReactDOM-dev.classic.js | 330 +- compiled/facebook-www/ReactDOM-dev.modern.js | 330 +- .../facebook-www/ReactDOM-profiling.modern.js | 6 +- .../ReactDOMServer-dev.classic.js | 4124 ++++++++--------- .../facebook-www/ReactDOMServer-dev.modern.js | 3854 +++++++-------- .../ReactDOMServer-prod.classic.js | 294 +- .../ReactDOMServer-prod.modern.js | 294 +- .../ReactDOMServerStreaming-dev.modern.js | 3852 +++++++-------- .../ReactDOMServerStreaming-prod.modern.js | 292 +- .../ReactDOMTesting-dev.classic.js | 330 +- .../ReactDOMTesting-dev.modern.js | 330 +- .../facebook-www/ReactServer-dev.modern.js | 6 +- .../ReactTestRenderer-dev.classic.js | 412 +- .../ReactTestRenderer-dev.modern.js | 412 +- .../__test_utils__/ReactAllWarnings.js | 2 +- 25 files changed, 6562 insertions(+), 9250 deletions(-) diff --git a/compiled/facebook-www/REVISION b/compiled/facebook-www/REVISION index e09cbb097687c..809f6756daf75 100644 --- a/compiled/facebook-www/REVISION +++ b/compiled/facebook-www/REVISION @@ -1 +1 @@ -2e470a788e359e34feeadb422daaff046baf66cc +fea900e45447214ddd6ef69076ab7e38433b5ffd diff --git a/compiled/facebook-www/React-dev.classic.js b/compiled/facebook-www/React-dev.classic.js index 90f6877e94de3..e9acdabb31e1b 100644 --- a/compiled/facebook-www/React-dev.classic.js +++ b/compiled/facebook-www/React-dev.classic.js @@ -24,7 +24,7 @@ if (__DEV__) { ) { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); } - var ReactVersion = "18.3.0-www-classic-77190284"; + var ReactVersion = "18.3.0-www-classic-77843590"; // ATTENTION // When adding new symbols to this file, @@ -2741,9 +2741,9 @@ if (__DEV__) { } if (render != null) { - if (render.defaultProps != null || render.propTypes != null) { + if (render.defaultProps != null) { error( - "forwardRef render functions do not support propTypes or defaultProps. " + + "forwardRef render functions do not support defaultProps. " + "Did you accidentally pass a React component?" ); } diff --git a/compiled/facebook-www/React-dev.modern.js b/compiled/facebook-www/React-dev.modern.js index 96251fe23d900..bd1deb63debda 100644 --- a/compiled/facebook-www/React-dev.modern.js +++ b/compiled/facebook-www/React-dev.modern.js @@ -24,7 +24,7 @@ if (__DEV__) { ) { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); } - var ReactVersion = "18.3.0-www-modern-5d2c8ee0"; + var ReactVersion = "18.3.0-www-modern-0bb55f38"; // ATTENTION // When adding new symbols to this file, @@ -2706,9 +2706,9 @@ if (__DEV__) { } if (render != null) { - if (render.defaultProps != null || render.propTypes != null) { + if (render.defaultProps != null) { error( - "forwardRef render functions do not support propTypes or defaultProps. " + + "forwardRef render functions do not support defaultProps. " + "Did you accidentally pass a React component?" ); } diff --git a/compiled/facebook-www/React-prod.classic.js b/compiled/facebook-www/React-prod.classic.js index 81b1bdfc6a079..67dea9aebb24d 100644 --- a/compiled/facebook-www/React-prod.classic.js +++ b/compiled/facebook-www/React-prod.classic.js @@ -618,4 +618,4 @@ exports.useSyncExternalStore = function ( exports.useTransition = function () { return ReactCurrentDispatcher.current.useTransition(); }; -exports.version = "18.3.0-www-classic-e7aae6cc"; +exports.version = "18.3.0-www-classic-22e81a9f"; diff --git a/compiled/facebook-www/React-prod.modern.js b/compiled/facebook-www/React-prod.modern.js index 7fdad59084482..f0c20a0e84960 100644 --- a/compiled/facebook-www/React-prod.modern.js +++ b/compiled/facebook-www/React-prod.modern.js @@ -610,4 +610,4 @@ exports.useSyncExternalStore = function ( exports.useTransition = function () { return ReactCurrentDispatcher.current.useTransition(); }; -exports.version = "18.3.0-www-modern-cbc861b3"; +exports.version = "18.3.0-www-modern-f4321f8c"; diff --git a/compiled/facebook-www/React-profiling.modern.js b/compiled/facebook-www/React-profiling.modern.js index cac8fcbf50022..1bdd95f9c76cc 100644 --- a/compiled/facebook-www/React-profiling.modern.js +++ b/compiled/facebook-www/React-profiling.modern.js @@ -614,7 +614,7 @@ exports.useSyncExternalStore = function ( exports.useTransition = function () { return ReactCurrentDispatcher.current.useTransition(); }; -exports.version = "18.3.0-www-modern-0840aeae"; +exports.version = "18.3.0-www-modern-e254c3a6"; "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && diff --git a/compiled/facebook-www/ReactART-dev.classic.js b/compiled/facebook-www/ReactART-dev.classic.js index 1c55b4ab7d090..bc6c4c573cac5 100644 --- a/compiled/facebook-www/ReactART-dev.classic.js +++ b/compiled/facebook-www/ReactART-dev.classic.js @@ -66,7 +66,7 @@ if (__DEV__) { return self; } - var ReactVersion = "18.3.0-www-classic-67fbc8af"; + var ReactVersion = "18.3.0-www-classic-ed34a3bc"; var LegacyRoot = 0; var ConcurrentRoot = 1; @@ -5137,6 +5137,50 @@ if (__DEV__) { } } + // $FlowFixMe[method-unbinding] + var hasOwnProperty = Object.prototype.hasOwnProperty; + + /** + * Performs equality by iterating through keys on an object and returning false + * when any key has values which are not strictly equal between the arguments. + * Returns true when the values of all keys are strictly equal. + */ + + function shallowEqual(objA, objB) { + if (objectIs(objA, objB)) { + return true; + } + + if ( + typeof objA !== "object" || + objA === null || + typeof objB !== "object" || + objB === null + ) { + return false; + } + + var keysA = Object.keys(objA); + var keysB = Object.keys(objB); + + if (keysA.length !== keysB.length) { + return false; + } // Test for A's keys different from B. + + for (var i = 0; i < keysA.length; i++) { + var currentKey = keysA[i]; + + if ( + !hasOwnProperty.call(objB, currentKey) || // $FlowFixMe[incompatible-use] lost refinement of `objB` + !objectIs(objA[currentKey], objB[currentKey]) + ) { + return false; + } + } + + return true; + } + var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher; var prefix; function describeBuiltInComponentFrame(name, ownerFn) { @@ -5420,211 +5464,6 @@ if (__DEV__) { } } - function shouldConstruct$1(Component) { - var prototype = Component.prototype; - return !!(prototype && prototype.isReactComponent); - } - - function describeUnknownElementTypeFrameInDEV(type, ownerFn) { - if (type == null) { - return ""; - } - - if (typeof type === "function") { - { - return describeNativeComponentFrame(type, shouldConstruct$1(type)); - } - } - - if (typeof type === "string") { - return describeBuiltInComponentFrame(type); - } - - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame("Suspense"); - - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame("SuspenseList"); - } - - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render); - - case REACT_MEMO_TYPE: - // Memo may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV(type.type, ownerFn); - - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - // Lazy may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV( - init(payload), - ownerFn - ); - } catch (x) {} - } - } - } - - return ""; - } - - // $FlowFixMe[method-unbinding] - var hasOwnProperty = Object.prototype.hasOwnProperty; - - var loggedTypeFailures = {}; - var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; - - function setCurrentlyValidatingElement(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV( - element.type, - owner ? owner.type : null - ); - ReactDebugCurrentFrame$1.setExtraStackFrame(stack); - } else { - ReactDebugCurrentFrame$1.setExtraStackFrame(null); - } - } - } - - function checkPropTypes( - typeSpecs, - values, - location, - componentName, - element - ) { - { - // $FlowFixMe[incompatible-use] This is okay but Flow doesn't know it. - var has = Function.call.bind(hasOwnProperty); - - for (var typeSpecName in typeSpecs) { - if (has(typeSpecs, typeSpecName)) { - var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to - // fail the render phase where it didn't fail before. So we log it. - // After these have been cleaned up, we'll let them throw. - - try { - // This is intentionally an invariant that gets caught. It's the same - // behavior as without this statement except with a better message. - if (typeof typeSpecs[typeSpecName] !== "function") { - // eslint-disable-next-line react-internal/prod-error-codes - var err = Error( - (componentName || "React class") + - ": " + - location + - " type `" + - typeSpecName + - "` is invalid; " + - "it must be a function, usually from the `prop-types` package, but received `" + - typeof typeSpecs[typeSpecName] + - "`." + - "This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`." - ); - err.name = "Invariant Violation"; - throw err; - } - - error$1 = typeSpecs[typeSpecName]( - values, - typeSpecName, - componentName, - location, - null, - "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED" - ); - } catch (ex) { - error$1 = ex; - } - - if (error$1 && !(error$1 instanceof Error)) { - setCurrentlyValidatingElement(element); - - error( - "%s: type specification of %s" + - " `%s` is invalid; the type checker " + - "function must return `null` or an `Error` but returned a %s. " + - "You may have forgotten to pass an argument to the type checker " + - "creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and " + - "shape all require an argument).", - componentName || "React class", - location, - typeSpecName, - typeof error$1 - ); - - setCurrentlyValidatingElement(null); - } - - if ( - error$1 instanceof Error && - !(error$1.message in loggedTypeFailures) - ) { - // Only monitor this failure once because there tends to be a lot of the - // same error. - loggedTypeFailures[error$1.message] = true; - setCurrentlyValidatingElement(element); - - error("Failed %s type: %s", location, error$1.message); - - setCurrentlyValidatingElement(null); - } - } - } - } - } - - /** - * Performs equality by iterating through keys on an object and returning false - * when any key has values which are not strictly equal between the arguments. - * Returns true when the values of all keys are strictly equal. - */ - - function shallowEqual(objA, objB) { - if (objectIs(objA, objB)) { - return true; - } - - if ( - typeof objA !== "object" || - objA === null || - typeof objB !== "object" || - objB === null - ) { - return false; - } - - var keysA = Object.keys(objA); - var keysB = Object.keys(objB); - - if (keysA.length !== keysB.length) { - return false; - } // Test for A's keys different from B. - - for (var i = 0; i < keysA.length; i++) { - var currentKey = keysA[i]; - - if ( - !hasOwnProperty.call(objB, currentKey) || // $FlowFixMe[incompatible-use] lost refinement of `objB` - !objectIs(objA[currentKey], objB[currentKey]) - ) { - return false; - } - } - - return true; - } - function describeFiber(fiber) { switch (fiber.tag) { case HostHoistable: @@ -14734,23 +14573,6 @@ if (__DEV__) { // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens after the first render suspends. // We'll need to figure out if this is fine or can cause issues. - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } - } - var render = Component.render; var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent @@ -14833,19 +14655,6 @@ if (__DEV__) { } { - var innerPropTypes = type.propTypes; - - if (innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(type) - ); - } - if (Component.defaultProps !== undefined) { var componentName = getComponentNameFromType(type) || "Unknown"; @@ -14875,22 +14684,6 @@ if (__DEV__) { return child; } - { - var _type = Component.type; - var _innerPropTypes = _type.propTypes; - - if (_innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes( - _innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(_type) - ); - } - } - var currentChild = current.child; // This is always exactly one child var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext( @@ -14936,40 +14729,6 @@ if (__DEV__) { // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens when the inner render suspends. // We'll need to figure out if this is fine or can cause issues. - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var outerMemoType = workInProgress.elementType; - - if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { - // We warn when you define propTypes on lazy() - // so let's just skip over it to find memo() outer wrapper. - // Inner props for memo are validated later. - var lazyComponent = outerMemoType; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - outerMemoType = init(payload); - } catch (x) { - outerMemoType = null; - } // Inner propTypes will be validated in the function component path. - - var outerPropTypes = outerMemoType && outerMemoType.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - nextProps, // Resolved (SimpleMemoComponent has no defaultProps) - "prop", - getComponentNameFromType(outerMemoType) - ); - } - } - } - } - if (current !== null) { var prevProps = current.memoizedProps; @@ -15420,23 +15179,6 @@ if (__DEV__) { nextProps, renderLanes ) { - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } - } - var context; { @@ -15573,21 +15315,6 @@ if (__DEV__) { break; } } - - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } } // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. @@ -15977,21 +15704,6 @@ if (__DEV__) { } case MemoComponent: { - { - if (workInProgress.type !== workInProgress.elementType) { - var outerPropTypes = Component.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - resolvedProps, // Resolved for outer only - "prop", - getComponentNameFromType(Component) - ); - } - } - } - child = updateMemoComponent( null, workInProgress, @@ -17562,17 +17274,6 @@ if (__DEV__) { ); } } - - var providerPropTypes = workInProgress.type.propTypes; - - if (providerPropTypes) { - checkPropTypes( - providerPropTypes, - newProps, - "prop", - "Context.Provider" - ); - } } pushProvider(workInProgress, context, newValue); @@ -18252,31 +17953,16 @@ if (__DEV__) { return updateContextConsumer(current, workInProgress, renderLanes); case MemoComponent: { - var _type2 = workInProgress.type; + var _type = workInProgress.type; var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props. - var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3); - - { - if (workInProgress.type !== workInProgress.elementType) { - var outerPropTypes = _type2.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - _resolvedProps3, // Resolved for outer only - "prop", - getComponentNameFromType(_type2) - ); - } - } - } + var _resolvedProps3 = resolveDefaultProps(_type, _unresolvedProps3); - _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3); + _resolvedProps3 = resolveDefaultProps(_type.type, _resolvedProps3); return updateMemoComponent( current, workInProgress, - _type2, + _type, _resolvedProps3, renderLanes ); diff --git a/compiled/facebook-www/ReactART-dev.modern.js b/compiled/facebook-www/ReactART-dev.modern.js index 6ec51008dcde9..63fb0f08ca55d 100644 --- a/compiled/facebook-www/ReactART-dev.modern.js +++ b/compiled/facebook-www/ReactART-dev.modern.js @@ -66,7 +66,7 @@ if (__DEV__) { return self; } - var ReactVersion = "18.3.0-www-modern-f7b80cf4"; + var ReactVersion = "18.3.0-www-modern-d27591d2"; var LegacyRoot = 0; var ConcurrentRoot = 1; @@ -4902,6 +4902,50 @@ if (__DEV__) { } } + // $FlowFixMe[method-unbinding] + var hasOwnProperty = Object.prototype.hasOwnProperty; + + /** + * Performs equality by iterating through keys on an object and returning false + * when any key has values which are not strictly equal between the arguments. + * Returns true when the values of all keys are strictly equal. + */ + + function shallowEqual(objA, objB) { + if (objectIs(objA, objB)) { + return true; + } + + if ( + typeof objA !== "object" || + objA === null || + typeof objB !== "object" || + objB === null + ) { + return false; + } + + var keysA = Object.keys(objA); + var keysB = Object.keys(objB); + + if (keysA.length !== keysB.length) { + return false; + } // Test for A's keys different from B. + + for (var i = 0; i < keysA.length; i++) { + var currentKey = keysA[i]; + + if ( + !hasOwnProperty.call(objB, currentKey) || // $FlowFixMe[incompatible-use] lost refinement of `objB` + !objectIs(objA[currentKey], objB[currentKey]) + ) { + return false; + } + } + + return true; + } + var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher; var prefix; function describeBuiltInComponentFrame(name, ownerFn) { @@ -5185,211 +5229,6 @@ if (__DEV__) { } } - function shouldConstruct$1(Component) { - var prototype = Component.prototype; - return !!(prototype && prototype.isReactComponent); - } - - function describeUnknownElementTypeFrameInDEV(type, ownerFn) { - if (type == null) { - return ""; - } - - if (typeof type === "function") { - { - return describeNativeComponentFrame(type, shouldConstruct$1(type)); - } - } - - if (typeof type === "string") { - return describeBuiltInComponentFrame(type); - } - - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame("Suspense"); - - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame("SuspenseList"); - } - - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render); - - case REACT_MEMO_TYPE: - // Memo may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV(type.type, ownerFn); - - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - // Lazy may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV( - init(payload), - ownerFn - ); - } catch (x) {} - } - } - } - - return ""; - } - - // $FlowFixMe[method-unbinding] - var hasOwnProperty = Object.prototype.hasOwnProperty; - - var loggedTypeFailures = {}; - var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; - - function setCurrentlyValidatingElement(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV( - element.type, - owner ? owner.type : null - ); - ReactDebugCurrentFrame$1.setExtraStackFrame(stack); - } else { - ReactDebugCurrentFrame$1.setExtraStackFrame(null); - } - } - } - - function checkPropTypes( - typeSpecs, - values, - location, - componentName, - element - ) { - { - // $FlowFixMe[incompatible-use] This is okay but Flow doesn't know it. - var has = Function.call.bind(hasOwnProperty); - - for (var typeSpecName in typeSpecs) { - if (has(typeSpecs, typeSpecName)) { - var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to - // fail the render phase where it didn't fail before. So we log it. - // After these have been cleaned up, we'll let them throw. - - try { - // This is intentionally an invariant that gets caught. It's the same - // behavior as without this statement except with a better message. - if (typeof typeSpecs[typeSpecName] !== "function") { - // eslint-disable-next-line react-internal/prod-error-codes - var err = Error( - (componentName || "React class") + - ": " + - location + - " type `" + - typeSpecName + - "` is invalid; " + - "it must be a function, usually from the `prop-types` package, but received `" + - typeof typeSpecs[typeSpecName] + - "`." + - "This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`." - ); - err.name = "Invariant Violation"; - throw err; - } - - error$1 = typeSpecs[typeSpecName]( - values, - typeSpecName, - componentName, - location, - null, - "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED" - ); - } catch (ex) { - error$1 = ex; - } - - if (error$1 && !(error$1 instanceof Error)) { - setCurrentlyValidatingElement(element); - - error( - "%s: type specification of %s" + - " `%s` is invalid; the type checker " + - "function must return `null` or an `Error` but returned a %s. " + - "You may have forgotten to pass an argument to the type checker " + - "creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and " + - "shape all require an argument).", - componentName || "React class", - location, - typeSpecName, - typeof error$1 - ); - - setCurrentlyValidatingElement(null); - } - - if ( - error$1 instanceof Error && - !(error$1.message in loggedTypeFailures) - ) { - // Only monitor this failure once because there tends to be a lot of the - // same error. - loggedTypeFailures[error$1.message] = true; - setCurrentlyValidatingElement(element); - - error("Failed %s type: %s", location, error$1.message); - - setCurrentlyValidatingElement(null); - } - } - } - } - } - - /** - * Performs equality by iterating through keys on an object and returning false - * when any key has values which are not strictly equal between the arguments. - * Returns true when the values of all keys are strictly equal. - */ - - function shallowEqual(objA, objB) { - if (objectIs(objA, objB)) { - return true; - } - - if ( - typeof objA !== "object" || - objA === null || - typeof objB !== "object" || - objB === null - ) { - return false; - } - - var keysA = Object.keys(objA); - var keysB = Object.keys(objB); - - if (keysA.length !== keysB.length) { - return false; - } // Test for A's keys different from B. - - for (var i = 0; i < keysA.length; i++) { - var currentKey = keysA[i]; - - if ( - !hasOwnProperty.call(objB, currentKey) || // $FlowFixMe[incompatible-use] lost refinement of `objB` - !objectIs(objA[currentKey], objB[currentKey]) - ) { - return false; - } - } - - return true; - } - function describeFiber(fiber) { switch (fiber.tag) { case HostHoistable: @@ -14458,23 +14297,6 @@ if (__DEV__) { // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens after the first render suspends. // We'll need to figure out if this is fine or can cause issues. - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } - } - var render = Component.render; var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent @@ -14557,19 +14379,6 @@ if (__DEV__) { } { - var innerPropTypes = type.propTypes; - - if (innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(type) - ); - } - if (Component.defaultProps !== undefined) { var componentName = getComponentNameFromType(type) || "Unknown"; @@ -14599,22 +14408,6 @@ if (__DEV__) { return child; } - { - var _type = Component.type; - var _innerPropTypes = _type.propTypes; - - if (_innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes( - _innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(_type) - ); - } - } - var currentChild = current.child; // This is always exactly one child var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext( @@ -14660,40 +14453,6 @@ if (__DEV__) { // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens when the inner render suspends. // We'll need to figure out if this is fine or can cause issues. - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var outerMemoType = workInProgress.elementType; - - if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { - // We warn when you define propTypes on lazy() - // so let's just skip over it to find memo() outer wrapper. - // Inner props for memo are validated later. - var lazyComponent = outerMemoType; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - outerMemoType = init(payload); - } catch (x) { - outerMemoType = null; - } // Inner propTypes will be validated in the function component path. - - var outerPropTypes = outerMemoType && outerMemoType.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - nextProps, // Resolved (SimpleMemoComponent has no defaultProps) - "prop", - getComponentNameFromType(outerMemoType) - ); - } - } - } - } - if (current !== null) { var prevProps = current.memoizedProps; @@ -15144,23 +14903,6 @@ if (__DEV__) { nextProps, renderLanes ) { - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } - } - var context; var nextChildren; @@ -15288,21 +15030,6 @@ if (__DEV__) { break; } } - - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } } // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. @@ -15671,21 +15398,6 @@ if (__DEV__) { } case MemoComponent: { - { - if (workInProgress.type !== workInProgress.elementType) { - var outerPropTypes = Component.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - resolvedProps, // Resolved for outer only - "prop", - getComponentNameFromType(Component) - ); - } - } - } - child = updateMemoComponent( null, workInProgress, @@ -17256,17 +16968,6 @@ if (__DEV__) { ); } } - - var providerPropTypes = workInProgress.type.propTypes; - - if (providerPropTypes) { - checkPropTypes( - providerPropTypes, - newProps, - "prop", - "Context.Provider" - ); - } } pushProvider(workInProgress, context, newValue); @@ -17940,31 +17641,16 @@ if (__DEV__) { return updateContextConsumer(current, workInProgress, renderLanes); case MemoComponent: { - var _type2 = workInProgress.type; + var _type = workInProgress.type; var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props. - var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3); - - { - if (workInProgress.type !== workInProgress.elementType) { - var outerPropTypes = _type2.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - _resolvedProps3, // Resolved for outer only - "prop", - getComponentNameFromType(_type2) - ); - } - } - } + var _resolvedProps3 = resolveDefaultProps(_type, _unresolvedProps3); - _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3); + _resolvedProps3 = resolveDefaultProps(_type.type, _resolvedProps3); return updateMemoComponent( current, workInProgress, - _type2, + _type, _resolvedProps3, renderLanes ); diff --git a/compiled/facebook-www/ReactART-prod.classic.js b/compiled/facebook-www/ReactART-prod.classic.js index ed52c2941eaef..ed81057f1481a 100644 --- a/compiled/facebook-www/ReactART-prod.classic.js +++ b/compiled/facebook-www/ReactART-prod.classic.js @@ -1556,6 +1556,29 @@ function commitCallbacks(updateQueue, context) { ) callCallback(callbacks[updateQueue], context); } +var hasOwnProperty = Object.prototype.hasOwnProperty; +function shallowEqual(objA, objB) { + if (objectIs(objA, objB)) return !0; + if ( + "object" !== typeof objA || + null === objA || + "object" !== typeof objB || + null === objB + ) + return !1; + var keysA = Object.keys(objA), + keysB = Object.keys(objB); + if (keysA.length !== keysB.length) return !1; + for (keysB = 0; keysB < keysA.length; keysB++) { + var currentKey = keysA[keysB]; + if ( + !hasOwnProperty.call(objB, currentKey) || + !objectIs(objA[currentKey], objB[currentKey]) + ) + return !1; + } + return !0; +} var prefix; function describeBuiltInComponentFrame(name) { if (void 0 === prefix) @@ -1699,29 +1722,6 @@ function describeNativeComponentFrame(fn, construct) { ? describeBuiltInComponentFrame(previousPrepareStackTrace) : ""; } -var hasOwnProperty = Object.prototype.hasOwnProperty; -function shallowEqual(objA, objB) { - if (objectIs(objA, objB)) return !0; - if ( - "object" !== typeof objA || - null === objA || - "object" !== typeof objB || - null === objB - ) - return !1; - var keysA = Object.keys(objA), - keysB = Object.keys(objB); - if (keysA.length !== keysB.length) return !1; - for (keysB = 0; keysB < keysA.length; keysB++) { - var currentKey = keysA[keysB]; - if ( - !hasOwnProperty.call(objB, currentKey) || - !objectIs(objA[currentKey], objB[currentKey]) - ) - return !1; - } - return !0; -} function describeFiber(fiber) { switch (fiber.tag) { case 26: @@ -10587,7 +10587,7 @@ var slice = Array.prototype.slice, return null; }, bundleType: 0, - version: "18.3.0-www-classic-82c2613b", + version: "18.3.0-www-classic-84c34a04", rendererPackageName: "react-art" }; var internals$jscomp$inline_1323 = { @@ -10618,7 +10618,7 @@ var internals$jscomp$inline_1323 = { scheduleRoot: null, setRefreshHandler: null, getCurrentFiber: null, - reconcilerVersion: "18.3.0-www-classic-82c2613b" + reconcilerVersion: "18.3.0-www-classic-84c34a04" }; if ("undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__) { var hook$jscomp$inline_1324 = __REACT_DEVTOOLS_GLOBAL_HOOK__; diff --git a/compiled/facebook-www/ReactART-prod.modern.js b/compiled/facebook-www/ReactART-prod.modern.js index 49ebcbfe23f6b..ba1d0b249ae95 100644 --- a/compiled/facebook-www/ReactART-prod.modern.js +++ b/compiled/facebook-www/ReactART-prod.modern.js @@ -1352,6 +1352,29 @@ function commitCallbacks(updateQueue, context) { ) callCallback(callbacks[updateQueue], context); } +var hasOwnProperty = Object.prototype.hasOwnProperty; +function shallowEqual(objA, objB) { + if (objectIs(objA, objB)) return !0; + if ( + "object" !== typeof objA || + null === objA || + "object" !== typeof objB || + null === objB + ) + return !1; + var keysA = Object.keys(objA), + keysB = Object.keys(objB); + if (keysA.length !== keysB.length) return !1; + for (keysB = 0; keysB < keysA.length; keysB++) { + var currentKey = keysA[keysB]; + if ( + !hasOwnProperty.call(objB, currentKey) || + !objectIs(objA[currentKey], objB[currentKey]) + ) + return !1; + } + return !0; +} var prefix; function describeBuiltInComponentFrame(name) { if (void 0 === prefix) @@ -1495,29 +1518,6 @@ function describeNativeComponentFrame(fn, construct) { ? describeBuiltInComponentFrame(previousPrepareStackTrace) : ""; } -var hasOwnProperty = Object.prototype.hasOwnProperty; -function shallowEqual(objA, objB) { - if (objectIs(objA, objB)) return !0; - if ( - "object" !== typeof objA || - null === objA || - "object" !== typeof objB || - null === objB - ) - return !1; - var keysA = Object.keys(objA), - keysB = Object.keys(objB); - if (keysA.length !== keysB.length) return !1; - for (keysB = 0; keysB < keysA.length; keysB++) { - var currentKey = keysA[keysB]; - if ( - !hasOwnProperty.call(objB, currentKey) || - !objectIs(objA[currentKey], objB[currentKey]) - ) - return !1; - } - return !0; -} function describeFiber(fiber) { switch (fiber.tag) { case 26: @@ -10242,7 +10242,7 @@ var slice = Array.prototype.slice, return null; }, bundleType: 0, - version: "18.3.0-www-modern-95350842", + version: "18.3.0-www-modern-df10e75d", rendererPackageName: "react-art" }; var internals$jscomp$inline_1303 = { @@ -10273,7 +10273,7 @@ var internals$jscomp$inline_1303 = { scheduleRoot: null, setRefreshHandler: null, getCurrentFiber: null, - reconcilerVersion: "18.3.0-www-modern-95350842" + reconcilerVersion: "18.3.0-www-modern-df10e75d" }; if ("undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__) { var hook$jscomp$inline_1304 = __REACT_DEVTOOLS_GLOBAL_HOOK__; diff --git a/compiled/facebook-www/ReactDOM-dev.classic.js b/compiled/facebook-www/ReactDOM-dev.classic.js index 02e44b9944973..d7af38cb149dc 100644 --- a/compiled/facebook-www/ReactDOM-dev.classic.js +++ b/compiled/facebook-www/ReactDOM-dev.classic.js @@ -3697,62 +3697,6 @@ if (__DEV__) { } } - function shouldConstruct$1(Component) { - var prototype = Component.prototype; - return !!(prototype && prototype.isReactComponent); - } - - function describeUnknownElementTypeFrameInDEV(type, ownerFn) { - if (type == null) { - return ""; - } - - if (typeof type === "function") { - { - return describeNativeComponentFrame(type, shouldConstruct$1(type)); - } - } - - if (typeof type === "string") { - return describeBuiltInComponentFrame(type); - } - - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame("Suspense"); - - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame("SuspenseList"); - } - - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render); - - case REACT_MEMO_TYPE: - // Memo may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV(type.type, ownerFn); - - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - // Lazy may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV( - init(payload), - ownerFn - ); - } catch (x) {} - } - } - } - - return ""; - } - function describeFiber(fiber) { switch (fiber.tag) { case HostHoistable: @@ -3802,7 +3746,7 @@ if (__DEV__) { } } - var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var current = null; var isRendering = false; function getCurrentFiberOwnerNameInDevOrNull() { @@ -3834,14 +3778,14 @@ if (__DEV__) { function resetCurrentFiber() { { - ReactDebugCurrentFrame$1.getCurrentStack = null; + ReactDebugCurrentFrame.getCurrentStack = null; current = null; isRendering = false; } } function setCurrentFiber(fiber) { { - ReactDebugCurrentFrame$1.getCurrentStack = + ReactDebugCurrentFrame.getCurrentStack = fiber === null ? null : getCurrentFiberStackInDev; current = fiber; isRendering = false; @@ -10298,111 +10242,6 @@ if (__DEV__) { } } - var loggedTypeFailures = {}; - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - - function setCurrentlyValidatingElement(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV( - element.type, - owner ? owner.type : null - ); - ReactDebugCurrentFrame.setExtraStackFrame(stack); - } else { - ReactDebugCurrentFrame.setExtraStackFrame(null); - } - } - } - - function checkPropTypes( - typeSpecs, - values, - location, - componentName, - element - ) { - { - // $FlowFixMe[incompatible-use] This is okay but Flow doesn't know it. - var has = Function.call.bind(hasOwnProperty); - - for (var typeSpecName in typeSpecs) { - if (has(typeSpecs, typeSpecName)) { - var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to - // fail the render phase where it didn't fail before. So we log it. - // After these have been cleaned up, we'll let them throw. - - try { - // This is intentionally an invariant that gets caught. It's the same - // behavior as without this statement except with a better message. - if (typeof typeSpecs[typeSpecName] !== "function") { - // eslint-disable-next-line react-internal/prod-error-codes - var err = Error( - (componentName || "React class") + - ": " + - location + - " type `" + - typeSpecName + - "` is invalid; " + - "it must be a function, usually from the `prop-types` package, but received `" + - typeof typeSpecs[typeSpecName] + - "`." + - "This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`." - ); - err.name = "Invariant Violation"; - throw err; - } - - error$1 = typeSpecs[typeSpecName]( - values, - typeSpecName, - componentName, - location, - null, - "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED" - ); - } catch (ex) { - error$1 = ex; - } - - if (error$1 && !(error$1 instanceof Error)) { - setCurrentlyValidatingElement(element); - - error( - "%s: type specification of %s" + - " `%s` is invalid; the type checker " + - "function must return `null` or an `Error` but returned a %s. " + - "You may have forgotten to pass an argument to the type checker " + - "creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and " + - "shape all require an argument).", - componentName || "React class", - location, - typeSpecName, - typeof error$1 - ); - - setCurrentlyValidatingElement(null); - } - - if ( - error$1 instanceof Error && - !(error$1.message in loggedTypeFailures) - ) { - // Only monitor this failure once because there tends to be a lot of the - // same error. - loggedTypeFailures[error$1.message] = true; - setCurrentlyValidatingElement(element); - - error("Failed %s type: %s", location, error$1.message); - - setCurrentlyValidatingElement(null); - } - } - } - } - } - /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. @@ -19606,23 +19445,6 @@ if (__DEV__) { // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens after the first render suspends. // We'll need to figure out if this is fine or can cause issues. - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } - } - var render = Component.render; var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent @@ -19711,19 +19533,6 @@ if (__DEV__) { } { - var innerPropTypes = type.propTypes; - - if (innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(type) - ); - } - if (Component.defaultProps !== undefined) { var componentName = getComponentNameFromType(type) || "Unknown"; @@ -19753,22 +19562,6 @@ if (__DEV__) { return child; } - { - var _type = Component.type; - var _innerPropTypes = _type.propTypes; - - if (_innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes( - _innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(_type) - ); - } - } - var currentChild = current.child; // This is always exactly one child var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext( @@ -19814,40 +19607,6 @@ if (__DEV__) { // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens when the inner render suspends. // We'll need to figure out if this is fine or can cause issues. - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var outerMemoType = workInProgress.elementType; - - if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { - // We warn when you define propTypes on lazy() - // so let's just skip over it to find memo() outer wrapper. - // Inner props for memo are validated later. - var lazyComponent = outerMemoType; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - outerMemoType = init(payload); - } catch (x) { - outerMemoType = null; - } // Inner propTypes will be validated in the function component path. - - var outerPropTypes = outerMemoType && outerMemoType.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - nextProps, // Resolved (SimpleMemoComponent has no defaultProps) - "prop", - getComponentNameFromType(outerMemoType) - ); - } - } - } - } - if (current !== null) { var prevProps = current.memoizedProps; @@ -20298,23 +20057,6 @@ if (__DEV__) { nextProps, renderLanes ) { - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } - } - var context; { @@ -20462,21 +20204,6 @@ if (__DEV__) { break; } } - - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } } // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. @@ -21021,21 +20748,6 @@ if (__DEV__) { } case MemoComponent: { - { - if (workInProgress.type !== workInProgress.elementType) { - var outerPropTypes = Component.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - resolvedProps, // Resolved for outer only - "prop", - getComponentNameFromType(Component) - ); - } - } - } - child = updateMemoComponent( null, workInProgress, @@ -22695,17 +22407,6 @@ if (__DEV__) { ); } } - - var providerPropTypes = workInProgress.type.propTypes; - - if (providerPropTypes) { - checkPropTypes( - providerPropTypes, - newProps, - "prop", - "Context.Provider" - ); - } } pushProvider(workInProgress, context, newValue); @@ -23406,31 +23107,16 @@ if (__DEV__) { return updateContextConsumer(current, workInProgress, renderLanes); case MemoComponent: { - var _type2 = workInProgress.type; + var _type = workInProgress.type; var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props. - var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3); - - { - if (workInProgress.type !== workInProgress.elementType) { - var outerPropTypes = _type2.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - _resolvedProps3, // Resolved for outer only - "prop", - getComponentNameFromType(_type2) - ); - } - } - } + var _resolvedProps3 = resolveDefaultProps(_type, _unresolvedProps3); - _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3); + _resolvedProps3 = resolveDefaultProps(_type.type, _resolvedProps3); return updateMemoComponent( current, workInProgress, - _type2, + _type, _resolvedProps3, renderLanes ); @@ -36017,7 +35703,7 @@ if (__DEV__) { return root; } - var ReactVersion = "18.3.0-www-classic-fb240cfb"; + var ReactVersion = "18.3.0-www-classic-f91bf9b5"; function createPortal$1( children, diff --git a/compiled/facebook-www/ReactDOM-dev.modern.js b/compiled/facebook-www/ReactDOM-dev.modern.js index 292df53f571ba..4d136b97f0746 100644 --- a/compiled/facebook-www/ReactDOM-dev.modern.js +++ b/compiled/facebook-www/ReactDOM-dev.modern.js @@ -3287,62 +3287,6 @@ if (__DEV__) { } } - function shouldConstruct$1(Component) { - var prototype = Component.prototype; - return !!(prototype && prototype.isReactComponent); - } - - function describeUnknownElementTypeFrameInDEV(type, ownerFn) { - if (type == null) { - return ""; - } - - if (typeof type === "function") { - { - return describeNativeComponentFrame(type, shouldConstruct$1(type)); - } - } - - if (typeof type === "string") { - return describeBuiltInComponentFrame(type); - } - - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame("Suspense"); - - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame("SuspenseList"); - } - - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render); - - case REACT_MEMO_TYPE: - // Memo may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV(type.type, ownerFn); - - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - // Lazy may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV( - init(payload), - ownerFn - ); - } catch (x) {} - } - } - } - - return ""; - } - function describeFiber(fiber) { switch (fiber.tag) { case HostHoistable: @@ -3645,7 +3589,7 @@ if (__DEV__) { return null; } - var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var current = null; var isRendering = false; function getCurrentFiberOwnerNameInDevOrNull() { @@ -3677,14 +3621,14 @@ if (__DEV__) { function resetCurrentFiber() { { - ReactDebugCurrentFrame$1.getCurrentStack = null; + ReactDebugCurrentFrame.getCurrentStack = null; current = null; isRendering = false; } } function setCurrentFiber(fiber) { { - ReactDebugCurrentFrame$1.getCurrentStack = + ReactDebugCurrentFrame.getCurrentStack = fiber === null ? null : getCurrentFiberStackInDev; current = fiber; isRendering = false; @@ -10249,111 +10193,6 @@ if (__DEV__) { } } - var loggedTypeFailures = {}; - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - - function setCurrentlyValidatingElement(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV( - element.type, - owner ? owner.type : null - ); - ReactDebugCurrentFrame.setExtraStackFrame(stack); - } else { - ReactDebugCurrentFrame.setExtraStackFrame(null); - } - } - } - - function checkPropTypes( - typeSpecs, - values, - location, - componentName, - element - ) { - { - // $FlowFixMe[incompatible-use] This is okay but Flow doesn't know it. - var has = Function.call.bind(hasOwnProperty); - - for (var typeSpecName in typeSpecs) { - if (has(typeSpecs, typeSpecName)) { - var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to - // fail the render phase where it didn't fail before. So we log it. - // After these have been cleaned up, we'll let them throw. - - try { - // This is intentionally an invariant that gets caught. It's the same - // behavior as without this statement except with a better message. - if (typeof typeSpecs[typeSpecName] !== "function") { - // eslint-disable-next-line react-internal/prod-error-codes - var err = Error( - (componentName || "React class") + - ": " + - location + - " type `" + - typeSpecName + - "` is invalid; " + - "it must be a function, usually from the `prop-types` package, but received `" + - typeof typeSpecs[typeSpecName] + - "`." + - "This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`." - ); - err.name = "Invariant Violation"; - throw err; - } - - error$1 = typeSpecs[typeSpecName]( - values, - typeSpecName, - componentName, - location, - null, - "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED" - ); - } catch (ex) { - error$1 = ex; - } - - if (error$1 && !(error$1 instanceof Error)) { - setCurrentlyValidatingElement(element); - - error( - "%s: type specification of %s" + - " `%s` is invalid; the type checker " + - "function must return `null` or an `Error` but returned a %s. " + - "You may have forgotten to pass an argument to the type checker " + - "creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and " + - "shape all require an argument).", - componentName || "React class", - location, - typeSpecName, - typeof error$1 - ); - - setCurrentlyValidatingElement(null); - } - - if ( - error$1 instanceof Error && - !(error$1.message in loggedTypeFailures) - ) { - // Only monitor this failure once because there tends to be a lot of the - // same error. - loggedTypeFailures[error$1.message] = true; - setCurrentlyValidatingElement(element); - - error("Failed %s type: %s", location, error$1.message); - - setCurrentlyValidatingElement(null); - } - } - } - } - } - /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. @@ -19516,23 +19355,6 @@ if (__DEV__) { // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens after the first render suspends. // We'll need to figure out if this is fine or can cause issues. - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } - } - var render = Component.render; var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent @@ -19621,19 +19443,6 @@ if (__DEV__) { } { - var innerPropTypes = type.propTypes; - - if (innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(type) - ); - } - if (Component.defaultProps !== undefined) { var componentName = getComponentNameFromType(type) || "Unknown"; @@ -19663,22 +19472,6 @@ if (__DEV__) { return child; } - { - var _type = Component.type; - var _innerPropTypes = _type.propTypes; - - if (_innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes( - _innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(_type) - ); - } - } - var currentChild = current.child; // This is always exactly one child var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext( @@ -19724,40 +19517,6 @@ if (__DEV__) { // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens when the inner render suspends. // We'll need to figure out if this is fine or can cause issues. - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var outerMemoType = workInProgress.elementType; - - if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { - // We warn when you define propTypes on lazy() - // so let's just skip over it to find memo() outer wrapper. - // Inner props for memo are validated later. - var lazyComponent = outerMemoType; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - outerMemoType = init(payload); - } catch (x) { - outerMemoType = null; - } // Inner propTypes will be validated in the function component path. - - var outerPropTypes = outerMemoType && outerMemoType.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - nextProps, // Resolved (SimpleMemoComponent has no defaultProps) - "prop", - getComponentNameFromType(outerMemoType) - ); - } - } - } - } - if (current !== null) { var prevProps = current.memoizedProps; @@ -20208,23 +19967,6 @@ if (__DEV__) { nextProps, renderLanes ) { - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } - } - var context; var nextChildren; @@ -20363,21 +20105,6 @@ if (__DEV__) { break; } } - - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } } // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. @@ -20901,21 +20628,6 @@ if (__DEV__) { } case MemoComponent: { - { - if (workInProgress.type !== workInProgress.elementType) { - var outerPropTypes = Component.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - resolvedProps, // Resolved for outer only - "prop", - getComponentNameFromType(Component) - ); - } - } - } - child = updateMemoComponent( null, workInProgress, @@ -22575,17 +22287,6 @@ if (__DEV__) { ); } } - - var providerPropTypes = workInProgress.type.propTypes; - - if (providerPropTypes) { - checkPropTypes( - providerPropTypes, - newProps, - "prop", - "Context.Provider" - ); - } } pushProvider(workInProgress, context, newValue); @@ -23280,31 +22981,16 @@ if (__DEV__) { return updateContextConsumer(current, workInProgress, renderLanes); case MemoComponent: { - var _type2 = workInProgress.type; + var _type = workInProgress.type; var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props. - var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3); - - { - if (workInProgress.type !== workInProgress.elementType) { - var outerPropTypes = _type2.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - _resolvedProps3, // Resolved for outer only - "prop", - getComponentNameFromType(_type2) - ); - } - } - } + var _resolvedProps3 = resolveDefaultProps(_type, _unresolvedProps3); - _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3); + _resolvedProps3 = resolveDefaultProps(_type.type, _resolvedProps3); return updateMemoComponent( current, workInProgress, - _type2, + _type, _resolvedProps3, renderLanes ); @@ -35853,7 +35539,7 @@ if (__DEV__) { return root; } - var ReactVersion = "18.3.0-www-modern-b0d7b4a2"; + var ReactVersion = "18.3.0-www-modern-37b33a94"; function createPortal$1( children, diff --git a/compiled/facebook-www/ReactDOM-profiling.modern.js b/compiled/facebook-www/ReactDOM-profiling.modern.js index e17e1a5bfbe88..017ebfb14aaa8 100644 --- a/compiled/facebook-www/ReactDOM-profiling.modern.js +++ b/compiled/facebook-www/ReactDOM-profiling.modern.js @@ -17453,7 +17453,7 @@ Internals.Events = [ var devToolsConfig$jscomp$inline_1869 = { findFiberByHostInstance: getClosestInstanceFromNode, bundleType: 0, - version: "18.3.0-www-modern-f7b80cf4", + version: "18.3.0-www-modern-d27591d2", rendererPackageName: "react-dom" }; (function (internals) { @@ -17498,7 +17498,7 @@ var devToolsConfig$jscomp$inline_1869 = { scheduleRoot: null, setRefreshHandler: null, getCurrentFiber: null, - reconcilerVersion: "18.3.0-www-modern-f7b80cf4" + reconcilerVersion: "18.3.0-www-modern-d27591d2" }); exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = Internals; exports.createPortal = function (children, container) { @@ -17756,7 +17756,7 @@ exports.useFormState = function (action, initialState, permalink) { exports.useFormStatus = function () { return ReactCurrentDispatcher$2.current.useHostTransitionStatus(); }; -exports.version = "18.3.0-www-modern-f7b80cf4"; +exports.version = "18.3.0-www-modern-d27591d2"; "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && diff --git a/compiled/facebook-www/ReactDOMServer-dev.classic.js b/compiled/facebook-www/ReactDOMServer-dev.classic.js index a8bb0a0bf3d7a..76ed394fc35e2 100644 --- a/compiled/facebook-www/ReactDOMServer-dev.classic.js +++ b/compiled/facebook-www/ReactDOMServer-dev.classic.js @@ -19,7 +19,7 @@ if (__DEV__) { var React = require("react"); var ReactDOM = require("react-dom"); - var ReactVersion = "18.3.0-www-classic-dec32670"; + var ReactVersion = "18.3.0-www-classic-1211dccf"; // This refers to a WWW module. var warningWWW = require("warning"); @@ -8592,2621 +8592,2445 @@ if (__DEV__) { return null; } - // Helpers to patch console.logs to avoid logging during side-effect free - // replaying on render function. This currently only patches the object - // lazily which won't cover if the log function was extracted eagerly. - // We could also eagerly patch the method. - var disabledDepth = 0; - var prevLog; - var prevInfo; - var prevWarn; - var prevError; - var prevGroup; - var prevGroupCollapsed; - var prevGroupEnd; + var warnedAboutMissingGetChildContext; - function disabledLog() {} + { + warnedAboutMissingGetChildContext = {}; + } - disabledLog.__reactDisabledLog = true; - function disableLogs() { + var emptyContextObject = {}; + + { + Object.freeze(emptyContextObject); + } + + function getMaskedContext(type, unmaskedContext) { { - if (disabledDepth === 0) { - /* eslint-disable react-internal/no-production-logging */ - prevLog = console.log; - prevInfo = console.info; - prevWarn = console.warn; - prevError = console.error; - prevGroup = console.group; - prevGroupCollapsed = console.groupCollapsed; - prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 + var contextTypes = type.contextTypes; - var props = { - configurable: true, - enumerable: true, - value: disabledLog, - writable: true - }; // $FlowFixMe[cannot-write] Flow thinks console is immutable. + if (!contextTypes) { + return emptyContextObject; + } - Object.defineProperties(console, { - info: props, - log: props, - warn: props, - error: props, - group: props, - groupCollapsed: props, - groupEnd: props - }); - /* eslint-enable react-internal/no-production-logging */ + var context = {}; + + for (var key in contextTypes) { + context[key] = unmaskedContext[key]; } - disabledDepth++; + return context; } } - function reenableLogs() { + function processChildContext( + instance, + type, + parentContext, + childContextTypes + ) { { - disabledDepth--; + // TODO (bvaughn) Replace this behavior with an invariant() in the future. + // It has only been added in Fiber to match the (unintentional) behavior in Stack. + if (typeof instance.getChildContext !== "function") { + { + var componentName = getComponentNameFromType(type) || "Unknown"; - if (disabledDepth === 0) { - /* eslint-disable react-internal/no-production-logging */ - var props = { - configurable: true, - enumerable: true, - writable: true - }; // $FlowFixMe[cannot-write] Flow thinks console is immutable. + if (!warnedAboutMissingGetChildContext[componentName]) { + warnedAboutMissingGetChildContext[componentName] = true; - Object.defineProperties(console, { - log: assign({}, props, { - value: prevLog - }), - info: assign({}, props, { - value: prevInfo - }), - warn: assign({}, props, { - value: prevWarn - }), - error: assign({}, props, { - value: prevError - }), - group: assign({}, props, { - value: prevGroup - }), - groupCollapsed: assign({}, props, { - value: prevGroupCollapsed - }), - groupEnd: assign({}, props, { - value: prevGroupEnd - }) - }); - /* eslint-enable react-internal/no-production-logging */ - } + error( + "%s.childContextTypes is specified but there is no getChildContext() method " + + "on the instance. You can either define getChildContext() on %s or remove " + + "childContextTypes from it.", + componentName, + componentName + ); + } + } - if (disabledDepth < 0) { - error( - "disabledDepth fell below zero. " + - "This is a bug in React. Please file an issue." - ); + return parentContext; } - } - } - var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; - var prefix; - function describeBuiltInComponentFrame(name, ownerFn) { - { - if (prefix === undefined) { - // Extract the VM specific prefix used by each line. - try { - throw Error(); - } catch (x) { - var match = x.stack.trim().match(/\n( *(at )?)/); - prefix = (match && match[1]) || ""; + var childContext = instance.getChildContext(); + + for (var contextKey in childContext) { + if (!(contextKey in childContextTypes)) { + throw new Error( + (getComponentNameFromType(type) || "Unknown") + + '.getChildContext(): key "' + + contextKey + + '" is not defined in childContextTypes.' + ); } - } // We use the prefix to ensure our stacks line up with native stack frames. + } - return "\n" + prefix + name; + return assign({}, parentContext, childContext); } } - var reentry = false; - var componentFrameCache; + + var rendererSigil; { - var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; - componentFrameCache = new PossiblyWeakMap(); - } - /** - * Leverages native browser/VM stack frames to get proper details (e.g. - * filename, line + col number) for a single component in a component stack. We - * do this by: - * (1) throwing and catching an error in the function - this will be our - * control error. - * (2) calling the component which will eventually throw an error that we'll - * catch - this will be our sample error. - * (3) diffing the control and sample error stacks to find the stack frame - * which represents our component. - */ + // Use this to detect multiple renderers using the same context + rendererSigil = {}; + } // Used to store the parent path of all context overrides in a shared linked list. + // Forming a reverse tree. + // The structure of a context snapshot is an implementation of this file. + // Currently, it's implemented as tracking the current active node. - function describeNativeComponentFrame(fn, construct) { - // If something asked for a stack inside a fake render, it should get ignored. - if (!fn || reentry) { - return ""; - } + var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances. + // This global (actually thread local) state represents what state all those "current", + // fields are currently in. + + var currentActiveSnapshot = null; + function popNode(prev) { { - var frame = componentFrameCache.get(fn); + prev.context._currentValue2 = prev.parentValue; + } + } - if (frame !== undefined) { - return frame; - } + function pushNode(next) { + { + next.context._currentValue2 = next.value; } + } - reentry = true; - var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe[incompatible-type] It does accept undefined. + function popToNearestCommonAncestor(prev, next) { + if (prev === next); + else { + popNode(prev); + var parentPrev = prev.parent; + var parentNext = next.parent; - Error.prepareStackTrace = undefined; - var previousDispatcher; + if (parentPrev === null) { + if (parentNext !== null) { + throw new Error( + "The stacks must reach the root at the same time. This is a bug in React." + ); + } + } else { + if (parentNext === null) { + throw new Error( + "The stacks must reach the root at the same time. This is a bug in React." + ); + } - { - previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function - // for warnings. + popToNearestCommonAncestor(parentPrev, parentNext); + } // On the way back, we push the new ones that weren't common. - ReactCurrentDispatcher$1.current = null; - disableLogs(); + pushNode(next); } - /** - * Finding a common stack frame between sample and control errors can be - * tricky given the different types and levels of stack trace truncation from - * different JS VMs. So instead we'll attempt to control what that common - * frame should be through this object method: - * Having both the sample and control errors be in the function under the - * `DescribeNativeComponentFrameRoot` property, + setting the `name` and - * `displayName` properties of the function ensures that a stack - * frame exists that has the method name `DescribeNativeComponentFrameRoot` in - * it for both control and sample stacks. - */ + } - var RunInRootFrame = { - DetermineComponentFrameRoot: function () { - var control; + function popAllPrevious(prev) { + popNode(prev); + var parentPrev = prev.parent; - try { - // This should throw. - if (construct) { - // Something should be setting the props in the constructor. - var Fake = function () { - throw Error(); - }; // $FlowFixMe[prop-missing] + if (parentPrev !== null) { + popAllPrevious(parentPrev); + } + } - Object.defineProperty(Fake.prototype, "props", { - set: function () { - // We use a throwing setter instead of frozen or non-writable props - // because that won't throw in a non-strict mode function. - throw Error(); - } - }); - - if (typeof Reflect === "object" && Reflect.construct) { - // We construct a different control for this case to include any extra - // frames added by the construct call. - try { - Reflect.construct(Fake, []); - } catch (x) { - control = x; - } - - Reflect.construct(fn, [], Fake); - } else { - try { - Fake.call(); - } catch (x) { - control = x; - } // $FlowFixMe[prop-missing] found when upgrading Flow - - fn.call(Fake.prototype); - } - } else { - try { - throw Error(); - } catch (x) { - control = x; - } // TODO(luna): This will currently only throw if the function component - // tries to access React/ReactDOM/props. We should probably make this throw - // in simple components too - - var maybePromise = fn(); // If the function component returns a promise, it's likely an async - // component, which we don't yet support. Attach a noop catch handler to - // silence the error. - // TODO: Implement component stacks for async client components? + function pushAllNext(next) { + var parentNext = next.parent; - if (maybePromise && typeof maybePromise.catch === "function") { - maybePromise.catch(function () {}); - } - } - } catch (sample) { - // This is inlined manually because closure doesn't do it for us. - if (sample && control && typeof sample.stack === "string") { - return [sample.stack, control.stack]; - } - } + if (parentNext !== null) { + pushAllNext(parentNext); + } - return [null, null]; - } - }; // $FlowFixMe[prop-missing] + pushNode(next); + } - RunInRootFrame.DetermineComponentFrameRoot.displayName = - "DetermineComponentFrameRoot"; - var namePropDescriptor = Object.getOwnPropertyDescriptor( - RunInRootFrame.DetermineComponentFrameRoot, - "name" - ); // Before ES6, the `name` property was not configurable. + function popPreviousToCommonLevel(prev, next) { + popNode(prev); + var parentPrev = prev.parent; - if (namePropDescriptor && namePropDescriptor.configurable) { - // V8 utilizes a function's `name` property when generating a stack trace. - Object.defineProperty( - RunInRootFrame.DetermineComponentFrameRoot, // Configurable properties can be updated even if its writable descriptor - // is set to `false`. - // $FlowFixMe[cannot-write] - "name", - { - value: "DetermineComponentFrameRoot" - } + if (parentPrev === null) { + throw new Error( + "The depth must equal at least at zero before reaching the root. This is a bug in React." ); } - try { - var _RunInRootFrame$Deter = - RunInRootFrame.DetermineComponentFrameRoot(), - sampleStack = _RunInRootFrame$Deter[0], - controlStack = _RunInRootFrame$Deter[1]; - - if (sampleStack && controlStack) { - // This extracts the first frame from the sample that isn't also in the control. - // Skipping one frame that we assume is the frame that calls the two. - var sampleLines = sampleStack.split("\n"); - var controlLines = controlStack.split("\n"); - var s = 0; - var c = 0; - - while ( - s < sampleLines.length && - !sampleLines[s].includes("DetermineComponentFrameRoot") - ) { - s++; - } - - while ( - c < controlLines.length && - !controlLines[c].includes("DetermineComponentFrameRoot") - ) { - c++; - } // We couldn't find our intentionally injected common root frame, attempt - // to find another common root frame by search from the bottom of the - // control stack... - - if (s === sampleLines.length || c === controlLines.length) { - s = sampleLines.length - 1; - c = controlLines.length - 1; - - while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { - // We expect at least one stack frame to be shared. - // Typically this will be the root most one. However, stack frames may be - // cut off due to maximum stack limits. In this case, one maybe cut off - // earlier than the other. We assume that the sample is longer or the same - // and there for cut off earlier. So we should find the root most frame in - // the sample somewhere in the control. - c--; - } - } + if (parentPrev.depth === next.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(parentPrev, next); + } else { + // We must still be deeper. + popPreviousToCommonLevel(parentPrev, next); + } + } - for (; s >= 1 && c >= 0; s--, c--) { - // Next we find the first one that isn't the same which should be the - // frame that called our sample function and the control. - if (sampleLines[s] !== controlLines[c]) { - // In V8, the first line is describing the message but other VMs don't. - // If we're about to return the first line, and the control is also on the same - // line, that's a pretty good indicator that our sample threw at same line as - // the control. I.e. before we entered the sample frame. So we ignore this result. - // This can happen if you passed a class to function component, or non-function. - if (s !== 1 || c !== 1) { - do { - s--; - c--; // We may still have similar intermediate frames from the construct call. - // The next one that isn't the same should be our match though. + function popNextToCommonLevel(prev, next) { + var parentNext = next.parent; - if (c < 0 || sampleLines[s] !== controlLines[c]) { - // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. - var _frame = - "\n" + sampleLines[s].replace(" at new ", " at "); // If our component frame is labeled "" - // but we have a user-provided "displayName" - // splice it in to make the stack more readable. + if (parentNext === null) { + throw new Error( + "The depth must equal at least at zero before reaching the root. This is a bug in React." + ); + } - if (fn.displayName && _frame.includes("")) { - _frame = _frame.replace("", fn.displayName); - } + if (prev.depth === parentNext.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(prev, parentNext); + } else { + // We must still be deeper. + popNextToCommonLevel(prev, parentNext); + } - if (true) { - if (typeof fn === "function") { - componentFrameCache.set(fn, _frame); - } - } // Return the line we found. + pushNode(next); + } // Perform context switching to the new snapshot. + // To make it cheap to read many contexts, while not suspending, we make the switch eagerly by + // updating all the context's current values. That way reads, always just read the current value. + // At the cost of updating contexts even if they're never read by this subtree. - return _frame; - } - } while (s >= 1 && c >= 0); - } + function switchContext(newSnapshot) { + // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack. + // We also need to update any new contexts that are now on the stack with the deepest value. + // The easiest way to update new contexts is to just reapply them in reverse order from the + // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack + // for that. Therefore this algorithm is recursive. + // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go. + // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go. + // 3) Then we reapply new contexts on the way back up the stack. + var prev = currentActiveSnapshot; + var next = newSnapshot; - break; - } - } + if (prev !== next) { + if (prev === null) { + // $FlowFixMe[incompatible-call]: This has to be non-null since it's not equal to prev. + pushAllNext(next); + } else if (next === null) { + popAllPrevious(prev); + } else if (prev.depth === next.depth) { + popToNearestCommonAncestor(prev, next); + } else if (prev.depth > next.depth) { + popPreviousToCommonLevel(prev, next); + } else { + popNextToCommonLevel(prev, next); } - } finally { - reentry = false; - { - ReactCurrentDispatcher$1.current = previousDispatcher; - reenableLogs(); - } + currentActiveSnapshot = next; + } + } + function pushProvider(context, nextValue) { + var prevValue; - Error.prepareStackTrace = previousPrepareStackTrace; - } // Fallback to just using the name if we couldn't make it throw. + { + prevValue = context._currentValue2; + context._currentValue2 = nextValue; - var name = fn ? fn.displayName || fn.name : ""; - var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; + { + if ( + context._currentRenderer2 !== undefined && + context._currentRenderer2 !== null && + context._currentRenderer2 !== rendererSigil + ) { + error( + "Detected multiple renderers concurrently rendering the " + + "same context provider. This is currently unsupported." + ); + } - { - if (typeof fn === "function") { - componentFrameCache.set(fn, syntheticFrame); + context._currentRenderer2 = rendererSigil; } } - return syntheticFrame; + var prevNode = currentActiveSnapshot; + var newNode = { + parent: prevNode, + depth: prevNode === null ? 0 : prevNode.depth + 1, + context: context, + parentValue: prevValue, + value: nextValue + }; + currentActiveSnapshot = newNode; + return newNode; } + function popProvider(context) { + var prevSnapshot = currentActiveSnapshot; - function describeClassComponentFrame(ctor, ownerFn) { - { - return describeNativeComponentFrame(ctor, true); + if (prevSnapshot === null) { + throw new Error( + "Tried to pop a Context at the root of the app. This is a bug in React." + ); } - } - function describeFunctionComponentFrame(fn, ownerFn) { + { - return describeNativeComponentFrame(fn, false); + if (prevSnapshot.context !== context) { + error( + "The parent context is not the expected context. This is probably a bug in React." + ); + } } - } - - function shouldConstruct$1(Component) { - var prototype = Component.prototype; - return !!(prototype && prototype.isReactComponent); - } - function describeUnknownElementTypeFrameInDEV(type, ownerFn) { - if (type == null) { - return ""; - } + { + var _value = prevSnapshot.parentValue; + prevSnapshot.context._currentValue2 = _value; - if (typeof type === "function") { { - return describeNativeComponentFrame(type, shouldConstruct$1(type)); - } - } + if ( + context._currentRenderer2 !== undefined && + context._currentRenderer2 !== null && + context._currentRenderer2 !== rendererSigil + ) { + error( + "Detected multiple renderers concurrently rendering the " + + "same context provider. This is currently unsupported." + ); + } - if (typeof type === "string") { - return describeBuiltInComponentFrame(type); + context._currentRenderer2 = rendererSigil; + } } - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame("Suspense"); - - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame("SuspenseList"); - } + return (currentActiveSnapshot = prevSnapshot.parent); + } + function getActiveContext() { + return currentActiveSnapshot; + } + function readContext$1(context) { + var value = context._currentValue2; + return value; + } - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render); + /** + * `ReactInstanceMap` maintains a mapping from a public facing stateful + * instance (key) and the internal representation (value). This allows public + * methods to accept the user facing instance as an argument and map them back + * to internal methods. + * + * Note that this module is currently shared and assumed to be stateless. + * If this becomes an actual Map, that will break. + */ + function get(key) { + return key._reactInternals; + } + function set(key, value) { + key._reactInternals = value; + } - case REACT_MEMO_TYPE: - // Memo may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV(type.type, ownerFn); + var didWarnAboutNoopUpdateForComponent = {}; + var didWarnAboutDeprecatedWillMount = {}; + var didWarnAboutUninitializedState; + var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; + var didWarnAboutLegacyLifecyclesAndDerivedState; + var didWarnAboutUndefinedDerivedState; + var didWarnAboutDirectlyAssigningPropsToState; + var didWarnAboutContextTypeAndContextTypes; + var didWarnAboutInvalidateContextType; + var didWarnOnInvalidCallback; - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; + { + didWarnAboutUninitializedState = new Set(); + didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set(); + didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); + didWarnAboutDirectlyAssigningPropsToState = new Set(); + didWarnAboutUndefinedDerivedState = new Set(); + didWarnAboutContextTypeAndContextTypes = new Set(); + didWarnAboutInvalidateContextType = new Set(); + didWarnOnInvalidCallback = new Set(); + } - try { - // Lazy may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV( - init(payload), - ownerFn - ); - } catch (x) {} - } + function warnOnInvalidCallback(callback, callerName) { + { + if (callback === null || typeof callback === "function") { + return; } - } - return ""; - } + var key = callerName + "_" + callback; - var loggedTypeFailures = {}; - var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + if (!didWarnOnInvalidCallback.has(key)) { + didWarnOnInvalidCallback.add(key); - function setCurrentlyValidatingElement(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV( - element.type, - owner ? owner.type : null + error( + "%s(...): Expected the last optional `callback` argument to be a " + + "function. Instead received: %s.", + callerName, + callback ); - ReactDebugCurrentFrame$1.setExtraStackFrame(stack); - } else { - ReactDebugCurrentFrame$1.setExtraStackFrame(null); } } } - function checkPropTypes( - typeSpecs, - values, - location, - componentName, - element - ) { + function warnOnUndefinedDerivedState(type, partialState) { { - // $FlowFixMe[incompatible-use] This is okay but Flow doesn't know it. - var has = Function.call.bind(hasOwnProperty); - - for (var typeSpecName in typeSpecs) { - if (has(typeSpecs, typeSpecName)) { - var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to - // fail the render phase where it didn't fail before. So we log it. - // After these have been cleaned up, we'll let them throw. - - try { - // This is intentionally an invariant that gets caught. It's the same - // behavior as without this statement except with a better message. - if (typeof typeSpecs[typeSpecName] !== "function") { - // eslint-disable-next-line react-internal/prod-error-codes - var err = Error( - (componentName || "React class") + - ": " + - location + - " type `" + - typeSpecName + - "` is invalid; " + - "it must be a function, usually from the `prop-types` package, but received `" + - typeof typeSpecs[typeSpecName] + - "`." + - "This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`." - ); - err.name = "Invariant Violation"; - throw err; - } - - error$1 = typeSpecs[typeSpecName]( - values, - typeSpecName, - componentName, - location, - null, - "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED" - ); - } catch (ex) { - error$1 = ex; - } - - if (error$1 && !(error$1 instanceof Error)) { - setCurrentlyValidatingElement(element); - - error( - "%s: type specification of %s" + - " `%s` is invalid; the type checker " + - "function must return `null` or an `Error` but returned a %s. " + - "You may have forgotten to pass an argument to the type checker " + - "creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and " + - "shape all require an argument).", - componentName || "React class", - location, - typeSpecName, - typeof error$1 - ); - - setCurrentlyValidatingElement(null); - } - - if ( - error$1 instanceof Error && - !(error$1.message in loggedTypeFailures) - ) { - // Only monitor this failure once because there tends to be a lot of the - // same error. - loggedTypeFailures[error$1.message] = true; - setCurrentlyValidatingElement(element); + if (partialState === undefined) { + var componentName = getComponentNameFromType(type) || "Component"; - error("Failed %s type: %s", location, error$1.message); + if (!didWarnAboutUndefinedDerivedState.has(componentName)) { + didWarnAboutUndefinedDerivedState.add(componentName); - setCurrentlyValidatingElement(null); - } + error( + "%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. " + + "You have returned undefined.", + componentName + ); } } } } - var warnedAboutMissingGetChildContext; + function warnNoop(publicInstance, callerName) { + { + var _constructor = publicInstance.constructor; + var componentName = + (_constructor && getComponentNameFromType(_constructor)) || + "ReactClass"; + var warningKey = componentName + "." + callerName; - { - warnedAboutMissingGetChildContext = {}; - } + if (didWarnAboutNoopUpdateForComponent[warningKey]) { + return; + } - var emptyContextObject = {}; + error( + "%s(...): Can only update a mounting component. " + + "This usually means you called %s() outside componentWillMount() on the server. " + + "This is a no-op.\n\nPlease check the code for the %s component.", + callerName, + callerName, + componentName + ); - { - Object.freeze(emptyContextObject); + didWarnAboutNoopUpdateForComponent[warningKey] = true; + } } - function getMaskedContext(type, unmaskedContext) { - { - var contextTypes = type.contextTypes; - - if (!contextTypes) { - return emptyContextObject; - } + var classComponentUpdater = { + isMounted: function (inst) { + return false; + }, + // $FlowFixMe[missing-local-annot] + enqueueSetState: function (inst, payload, callback) { + var internals = get(inst); - var context = {}; + if (internals.queue === null) { + warnNoop(inst, "setState"); + } else { + internals.queue.push(payload); - for (var key in contextTypes) { - context[key] = unmaskedContext[key]; + { + if (callback !== undefined && callback !== null) { + warnOnInvalidCallback(callback, "setState"); + } + } } + }, + enqueueReplaceState: function (inst, payload, callback) { + var internals = get(inst); + internals.replace = true; + internals.queue = [payload]; { - var name = getComponentNameFromType(type) || "Unknown"; - checkPropTypes(contextTypes, context, "context", name); + if (callback !== undefined && callback !== null) { + warnOnInvalidCallback(callback, "setState"); + } } + }, + // $FlowFixMe[missing-local-annot] + enqueueForceUpdate: function (inst, callback) { + var internals = get(inst); - return context; + if (internals.queue === null) { + warnNoop(inst, "forceUpdate"); + } else { + { + if (callback !== undefined && callback !== null) { + warnOnInvalidCallback(callback, "setState"); + } + } + } } - } - function processChildContext( + }; + + function applyDerivedStateFromProps( instance, - type, - parentContext, - childContextTypes + ctor, + getDerivedStateFromProps, + prevState, + nextProps ) { + var partialState = getDerivedStateFromProps(nextProps, prevState); + { - // TODO (bvaughn) Replace this behavior with an invariant() in the future. - // It has only been added in Fiber to match the (unintentional) behavior in Stack. - if (typeof instance.getChildContext !== "function") { - { - var componentName = getComponentNameFromType(type) || "Unknown"; + warnOnUndefinedDerivedState(ctor, partialState); + } // Merge the partial state and the previous state. - if (!warnedAboutMissingGetChildContext[componentName]) { - warnedAboutMissingGetChildContext[componentName] = true; + var newState = + partialState === null || partialState === undefined + ? prevState + : assign({}, prevState, partialState); + return newState; + } - error( - "%s.childContextTypes is specified but there is no getChildContext() method " + - "on the instance. You can either define getChildContext() on %s or remove " + - "childContextTypes from it.", - componentName, - componentName - ); - } - } + function constructClassInstance(ctor, props, maskedLegacyContext) { + var context = emptyContextObject; + var contextType = ctor.contextType; - return parentContext; - } + { + if ("contextType" in ctor) { + var isValid = // Allow null for conditional declaration + contextType === null || + (contextType !== undefined && + contextType.$$typeof === REACT_CONTEXT_TYPE); - var childContext = instance.getChildContext(); + if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { + didWarnAboutInvalidateContextType.add(ctor); + var addendum = ""; - for (var contextKey in childContext) { - if (!(contextKey in childContextTypes)) { - throw new Error( - (getComponentNameFromType(type) || "Unknown") + - '.getChildContext(): key "' + - contextKey + - '" is not defined in childContextTypes.' + if (contextType === undefined) { + addendum = + " However, it is set to undefined. " + + "This can be caused by a typo or by mixing up named and default imports. " + + "This can also happen due to a circular dependency, so " + + "try moving the createContext() call to a separate file."; + } else if (typeof contextType !== "object") { + addendum = " However, it is set to a " + typeof contextType + "."; + } else if (contextType.$$typeof === REACT_CONSUMER_TYPE) { + addendum = + " Did you accidentally pass the Context.Consumer instead?"; + } else { + addendum = + " However, it is set to an object with keys {" + + Object.keys(contextType).join(", ") + + "}."; + } + + error( + "%s defines an invalid contextType. " + + "contextType should point to the Context object returned by React.createContext().%s", + getComponentNameFromType(ctor) || "Component", + addendum ); } } - - { - var name = getComponentNameFromType(type) || "Unknown"; - checkPropTypes( - childContextTypes, - childContext, - "child context", - name - ); - } - - return assign({}, parentContext, childContext); } - } - - var rendererSigil; - - { - // Use this to detect multiple renderers using the same context - rendererSigil = {}; - } // Used to store the parent path of all context overrides in a shared linked list. - // Forming a reverse tree. - // The structure of a context snapshot is an implementation of this file. - // Currently, it's implemented as tracking the current active node. - - var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances. - // This global (actually thread local) state represents what state all those "current", - // fields are currently in. - - var currentActiveSnapshot = null; - function popNode(prev) { - { - prev.context._currentValue2 = prev.parentValue; + if (typeof contextType === "object" && contextType !== null) { + context = readContext$1(contextType); + } else { + context = maskedLegacyContext; } - } - function pushNode(next) { + var instance = new ctor(props, context); + { - next.context._currentValue2 = next.value; - } - } + if ( + typeof ctor.getDerivedStateFromProps === "function" && + (instance.state === null || instance.state === undefined) + ) { + var componentName = getComponentNameFromType(ctor) || "Component"; - function popToNearestCommonAncestor(prev, next) { - if (prev === next); - else { - popNode(prev); - var parentPrev = prev.parent; - var parentNext = next.parent; + if (!didWarnAboutUninitializedState.has(componentName)) { + didWarnAboutUninitializedState.add(componentName); - if (parentPrev === null) { - if (parentNext !== null) { - throw new Error( - "The stacks must reach the root at the same time. This is a bug in React." - ); - } - } else { - if (parentNext === null) { - throw new Error( - "The stacks must reach the root at the same time. This is a bug in React." + error( + "`%s` uses `getDerivedStateFromProps` but its initial state is " + + "%s. This is not recommended. Instead, define the initial state by " + + "assigning an object to `this.state` in the constructor of `%s`. " + + "This ensures that `getDerivedStateFromProps` arguments have a consistent shape.", + componentName, + instance.state === null ? "null" : "undefined", + componentName ); } + } // If new component APIs are defined, "unsafe" lifecycles won't be called. + // Warn about these lifecycles if they are present. + // Don't warn about react-lifecycles-compat polyfilled methods though. - popToNearestCommonAncestor(parentPrev, parentNext); - } // On the way back, we push the new ones that weren't common. - - pushNode(next); - } - } + if ( + typeof ctor.getDerivedStateFromProps === "function" || + typeof instance.getSnapshotBeforeUpdate === "function" + ) { + var foundWillMountName = null; + var foundWillReceivePropsName = null; + var foundWillUpdateName = null; - function popAllPrevious(prev) { - popNode(prev); - var parentPrev = prev.parent; + if ( + typeof instance.componentWillMount === "function" && + instance.componentWillMount.__suppressDeprecationWarning !== true + ) { + foundWillMountName = "componentWillMount"; + } else if (typeof instance.UNSAFE_componentWillMount === "function") { + foundWillMountName = "UNSAFE_componentWillMount"; + } - if (parentPrev !== null) { - popAllPrevious(parentPrev); - } - } + if ( + typeof instance.componentWillReceiveProps === "function" && + instance.componentWillReceiveProps.__suppressDeprecationWarning !== + true + ) { + foundWillReceivePropsName = "componentWillReceiveProps"; + } else if ( + typeof instance.UNSAFE_componentWillReceiveProps === "function" + ) { + foundWillReceivePropsName = "UNSAFE_componentWillReceiveProps"; + } - function pushAllNext(next) { - var parentNext = next.parent; + if ( + typeof instance.componentWillUpdate === "function" && + instance.componentWillUpdate.__suppressDeprecationWarning !== true + ) { + foundWillUpdateName = "componentWillUpdate"; + } else if ( + typeof instance.UNSAFE_componentWillUpdate === "function" + ) { + foundWillUpdateName = "UNSAFE_componentWillUpdate"; + } - if (parentNext !== null) { - pushAllNext(parentNext); - } + if ( + foundWillMountName !== null || + foundWillReceivePropsName !== null || + foundWillUpdateName !== null + ) { + var _componentName = getComponentNameFromType(ctor) || "Component"; - pushNode(next); - } + var newApiName = + typeof ctor.getDerivedStateFromProps === "function" + ? "getDerivedStateFromProps()" + : "getSnapshotBeforeUpdate()"; - function popPreviousToCommonLevel(prev, next) { - popNode(prev); - var parentPrev = prev.parent; + if ( + !didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName) + ) { + didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName); - if (parentPrev === null) { - throw new Error( - "The depth must equal at least at zero before reaching the root. This is a bug in React." - ); + error( + "Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n" + + "%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n" + + "The above lifecycles should be removed. Learn more about this warning here:\n" + + "https://reactjs.org/link/unsafe-component-lifecycles", + _componentName, + newApiName, + foundWillMountName !== null ? "\n " + foundWillMountName : "", + foundWillReceivePropsName !== null + ? "\n " + foundWillReceivePropsName + : "", + foundWillUpdateName !== null ? "\n " + foundWillUpdateName : "" + ); + } + } + } } - if (parentPrev.depth === next.depth) { - // We found the same level. Now we just need to find a shared ancestor. - popToNearestCommonAncestor(parentPrev, next); - } else { - // We must still be deeper. - popPreviousToCommonLevel(parentPrev, next); - } + return instance; } - function popNextToCommonLevel(prev, next) { - var parentNext = next.parent; + function checkClassInstance(instance, ctor, newProps) { + { + var name = getComponentNameFromType(ctor) || "Component"; + var renderPresent = instance.render; - if (parentNext === null) { - throw new Error( - "The depth must equal at least at zero before reaching the root. This is a bug in React." - ); - } + if (!renderPresent) { + if (ctor.prototype && typeof ctor.prototype.render === "function") { + error( + "%s(...): No `render` method found on the returned component " + + "instance: did you accidentally return an object from the constructor?", + name + ); + } else { + error( + "%s(...): No `render` method found on the returned component " + + "instance: you may have forgotten to define `render`.", + name + ); + } + } - if (prev.depth === parentNext.depth) { - // We found the same level. Now we just need to find a shared ancestor. - popToNearestCommonAncestor(prev, parentNext); - } else { - // We must still be deeper. - popNextToCommonLevel(prev, parentNext); - } - - pushNode(next); - } // Perform context switching to the new snapshot. - // To make it cheap to read many contexts, while not suspending, we make the switch eagerly by - // updating all the context's current values. That way reads, always just read the current value. - // At the cost of updating contexts even if they're never read by this subtree. - - function switchContext(newSnapshot) { - // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack. - // We also need to update any new contexts that are now on the stack with the deepest value. - // The easiest way to update new contexts is to just reapply them in reverse order from the - // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack - // for that. Therefore this algorithm is recursive. - // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go. - // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go. - // 3) Then we reapply new contexts on the way back up the stack. - var prev = currentActiveSnapshot; - var next = newSnapshot; - - if (prev !== next) { - if (prev === null) { - // $FlowFixMe[incompatible-call]: This has to be non-null since it's not equal to prev. - pushAllNext(next); - } else if (next === null) { - popAllPrevious(prev); - } else if (prev.depth === next.depth) { - popToNearestCommonAncestor(prev, next); - } else if (prev.depth > next.depth) { - popPreviousToCommonLevel(prev, next); - } else { - popNextToCommonLevel(prev, next); + if ( + instance.getInitialState && + !instance.getInitialState.isReactClassApproved && + !instance.state + ) { + error( + "getInitialState was defined on %s, a plain JavaScript class. " + + "This is only supported for classes created using React.createClass. " + + "Did you mean to define a state property instead?", + name + ); } - currentActiveSnapshot = next; - } - } - function pushProvider(context, nextValue) { - var prevValue; - - { - prevValue = context._currentValue2; - context._currentValue2 = nextValue; - - { - if ( - context._currentRenderer2 !== undefined && - context._currentRenderer2 !== null && - context._currentRenderer2 !== rendererSigil - ) { - error( - "Detected multiple renderers concurrently rendering the " + - "same context provider. This is currently unsupported." - ); - } - - context._currentRenderer2 = rendererSigil; + if ( + instance.getDefaultProps && + !instance.getDefaultProps.isReactClassApproved + ) { + error( + "getDefaultProps was defined on %s, a plain JavaScript class. " + + "This is only supported for classes created using React.createClass. " + + "Use a static property to define defaultProps instead.", + name + ); } - } - - var prevNode = currentActiveSnapshot; - var newNode = { - parent: prevNode, - depth: prevNode === null ? 0 : prevNode.depth + 1, - context: context, - parentValue: prevValue, - value: nextValue - }; - currentActiveSnapshot = newNode; - return newNode; - } - function popProvider(context) { - var prevSnapshot = currentActiveSnapshot; - - if (prevSnapshot === null) { - throw new Error( - "Tried to pop a Context at the root of the app. This is a bug in React." - ); - } - { - if (prevSnapshot.context !== context) { + if (instance.propTypes) { error( - "The parent context is not the expected context. This is probably a bug in React." + "propTypes was defined as an instance property on %s. Use a static " + + "property to define propTypes instead.", + name ); } - } - { - var _value = prevSnapshot.parentValue; - prevSnapshot.context._currentValue2 = _value; + if (instance.contextType) { + error( + "contextType was defined as an instance property on %s. Use a static " + + "property to define contextType instead.", + name + ); + } { + if (instance.contextTypes) { + error( + "contextTypes was defined as an instance property on %s. Use a static " + + "property to define contextTypes instead.", + name + ); + } + if ( - context._currentRenderer2 !== undefined && - context._currentRenderer2 !== null && - context._currentRenderer2 !== rendererSigil + ctor.contextType && + ctor.contextTypes && + !didWarnAboutContextTypeAndContextTypes.has(ctor) ) { + didWarnAboutContextTypeAndContextTypes.add(ctor); + error( - "Detected multiple renderers concurrently rendering the " + - "same context provider. This is currently unsupported." + "%s declares both contextTypes and contextType static properties. " + + "The legacy contextTypes property will be ignored.", + name ); } - - context._currentRenderer2 = rendererSigil; } - } - return (currentActiveSnapshot = prevSnapshot.parent); - } - function getActiveContext() { - return currentActiveSnapshot; - } - function readContext$1(context) { - var value = context._currentValue2; - return value; - } + if (typeof instance.componentShouldUpdate === "function") { + error( + "%s has a method called " + + "componentShouldUpdate(). Did you mean shouldComponentUpdate()? " + + "The name is phrased as a question because the function is " + + "expected to return a value.", + name + ); + } - /** - * `ReactInstanceMap` maintains a mapping from a public facing stateful - * instance (key) and the internal representation (value). This allows public - * methods to accept the user facing instance as an argument and map them back - * to internal methods. - * - * Note that this module is currently shared and assumed to be stateless. - * If this becomes an actual Map, that will break. - */ - function get(key) { - return key._reactInternals; - } - function set(key, value) { - key._reactInternals = value; - } + if ( + ctor.prototype && + ctor.prototype.isPureReactComponent && + typeof instance.shouldComponentUpdate !== "undefined" + ) { + error( + "%s has a method called shouldComponentUpdate(). " + + "shouldComponentUpdate should not be used when extending React.PureComponent. " + + "Please extend React.Component if shouldComponentUpdate is used.", + getComponentNameFromType(ctor) || "A pure component" + ); + } - var didWarnAboutNoopUpdateForComponent = {}; - var didWarnAboutDeprecatedWillMount = {}; - var didWarnAboutUninitializedState; - var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; - var didWarnAboutLegacyLifecyclesAndDerivedState; - var didWarnAboutUndefinedDerivedState; - var didWarnAboutDirectlyAssigningPropsToState; - var didWarnAboutContextTypeAndContextTypes; - var didWarnAboutInvalidateContextType; - var didWarnOnInvalidCallback; + if (typeof instance.componentDidUnmount === "function") { + error( + "%s has a method called " + + "componentDidUnmount(). But there is no such lifecycle method. " + + "Did you mean componentWillUnmount()?", + name + ); + } - { - didWarnAboutUninitializedState = new Set(); - didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set(); - didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); - didWarnAboutDirectlyAssigningPropsToState = new Set(); - didWarnAboutUndefinedDerivedState = new Set(); - didWarnAboutContextTypeAndContextTypes = new Set(); - didWarnAboutInvalidateContextType = new Set(); - didWarnOnInvalidCallback = new Set(); - } + if (typeof instance.componentDidReceiveProps === "function") { + error( + "%s has a method called " + + "componentDidReceiveProps(). But there is no such lifecycle method. " + + "If you meant to update the state in response to changing props, " + + "use componentWillReceiveProps(). If you meant to fetch data or " + + "run side-effects or mutations after React has updated the UI, use componentDidUpdate().", + name + ); + } - function warnOnInvalidCallback(callback, callerName) { - { - if (callback === null || typeof callback === "function") { - return; + if (typeof instance.componentWillRecieveProps === "function") { + error( + "%s has a method called " + + "componentWillRecieveProps(). Did you mean componentWillReceiveProps()?", + name + ); } - var key = callerName + "_" + callback; + if (typeof instance.UNSAFE_componentWillRecieveProps === "function") { + error( + "%s has a method called " + + "UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?", + name + ); + } - if (!didWarnOnInvalidCallback.has(key)) { - didWarnOnInvalidCallback.add(key); + var hasMutatedProps = instance.props !== newProps; + if (instance.props !== undefined && hasMutatedProps) { error( - "%s(...): Expected the last optional `callback` argument to be a " + - "function. Instead received: %s.", - callerName, - callback + "%s(...): When calling super() in `%s`, make sure to pass " + + "up the same props that your component's constructor was passed.", + name, + name ); } - } - } - function warnOnUndefinedDerivedState(type, partialState) { - { - if (partialState === undefined) { - var componentName = getComponentNameFromType(type) || "Component"; + if (instance.defaultProps) { + error( + "Setting defaultProps as an instance property on %s is not supported and will be ignored." + + " Instead, define defaultProps as a static property on %s.", + name, + name + ); + } - if (!didWarnAboutUndefinedDerivedState.has(componentName)) { - didWarnAboutUndefinedDerivedState.add(componentName); + if ( + typeof instance.getSnapshotBeforeUpdate === "function" && + typeof instance.componentDidUpdate !== "function" && + !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor) + ) { + didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor); - error( - "%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. " + - "You have returned undefined.", - componentName - ); - } + error( + "%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). " + + "This component defines getSnapshotBeforeUpdate() only.", + getComponentNameFromType(ctor) + ); } - } - } - function warnNoop(publicInstance, callerName) { - { - var _constructor = publicInstance.constructor; - var componentName = - (_constructor && getComponentNameFromType(_constructor)) || - "ReactClass"; - var warningKey = componentName + "." + callerName; + if (typeof instance.getDerivedStateFromProps === "function") { + error( + "%s: getDerivedStateFromProps() is defined as an instance method " + + "and will be ignored. Instead, declare it as a static method.", + name + ); + } - if (didWarnAboutNoopUpdateForComponent[warningKey]) { - return; + if (typeof instance.getDerivedStateFromError === "function") { + error( + "%s: getDerivedStateFromError() is defined as an instance method " + + "and will be ignored. Instead, declare it as a static method.", + name + ); } - error( - "%s(...): Can only update a mounting component. " + - "This usually means you called %s() outside componentWillMount() on the server. " + - "This is a no-op.\n\nPlease check the code for the %s component.", - callerName, - callerName, - componentName - ); + if (typeof ctor.getSnapshotBeforeUpdate === "function") { + error( + "%s: getSnapshotBeforeUpdate() is defined as a static method " + + "and will be ignored. Instead, declare it as an instance method.", + name + ); + } - didWarnAboutNoopUpdateForComponent[warningKey] = true; + var state = instance.state; + + if (state && (typeof state !== "object" || isArray(state))) { + error("%s.state: must be set to an object or null", name); + } + + if ( + typeof instance.getChildContext === "function" && + typeof ctor.childContextTypes !== "object" + ) { + error( + "%s.getChildContext(): childContextTypes must be defined in order to " + + "use getChildContext().", + name + ); + } } } - var classComponentUpdater = { - isMounted: function (inst) { - return false; - }, - // $FlowFixMe[missing-local-annot] - enqueueSetState: function (inst, payload, callback) { - var internals = get(inst); + function callComponentWillMount(type, instance) { + var oldState = instance.state; - if (internals.queue === null) { - warnNoop(inst, "setState"); - } else { - internals.queue.push(payload); + if (typeof instance.componentWillMount === "function") { + { + if ( + instance.componentWillMount.__suppressDeprecationWarning !== true + ) { + var componentName = getComponentNameFromType(type) || "Unknown"; - { - if (callback !== undefined && callback !== null) { - warnOnInvalidCallback(callback, "setState"); + if (!didWarnAboutDeprecatedWillMount[componentName]) { + warn( + // keep this warning in sync with ReactStrictModeWarning.js + "componentWillMount has been renamed, and is not recommended for use. " + + "See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n" + + "* Move code from componentWillMount to componentDidMount (preferred in most cases) " + + "or the constructor.\n" + + "\nPlease update the following components: %s", + componentName + ); + + didWarnAboutDeprecatedWillMount[componentName] = true; } } } - }, - enqueueReplaceState: function (inst, payload, callback) { - var internals = get(inst); - internals.replace = true; - internals.queue = [payload]; + instance.componentWillMount(); + } + + if (typeof instance.UNSAFE_componentWillMount === "function") { + instance.UNSAFE_componentWillMount(); + } + + if (oldState !== instance.state) { { - if (callback !== undefined && callback !== null) { - warnOnInvalidCallback(callback, "setState"); - } + error( + "%s.componentWillMount(): Assigning directly to this.state is " + + "deprecated (except inside a component's " + + "constructor). Use setState instead.", + getComponentNameFromType(type) || "Component" + ); } - }, - // $FlowFixMe[missing-local-annot] - enqueueForceUpdate: function (inst, callback) { - var internals = get(inst); - if (internals.queue === null) { - warnNoop(inst, "forceUpdate"); + classComponentUpdater.enqueueReplaceState( + instance, + instance.state, + null + ); + } + } + + function processUpdateQueue( + internalInstance, + inst, + props, + maskedLegacyContext + ) { + if ( + internalInstance.queue !== null && + internalInstance.queue.length > 0 + ) { + var oldQueue = internalInstance.queue; + var oldReplace = internalInstance.replace; + internalInstance.queue = null; + internalInstance.replace = false; + + if (oldReplace && oldQueue.length === 1) { + inst.state = oldQueue[0]; } else { - { - if (callback !== undefined && callback !== null) { - warnOnInvalidCallback(callback, "setState"); + var nextState = oldReplace ? oldQueue[0] : inst.state; + var dontMutate = true; + + for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) { + var partial = oldQueue[i]; + var partialState = + typeof partial === "function" + ? partial.call(inst, nextState, props, maskedLegacyContext) + : partial; + + if (partialState != null) { + if (dontMutate) { + dontMutate = false; + nextState = assign({}, nextState, partialState); + } else { + assign(nextState, partialState); + } } } + + inst.state = nextState; } + } else { + internalInstance.queue = null; } - }; - - function applyDerivedStateFromProps( - instance, - ctor, - getDerivedStateFromProps, - prevState, - nextProps - ) { - var partialState = getDerivedStateFromProps(nextProps, prevState); + } // Invokes the mount life-cycles on a previously never rendered instance. + function mountClassInstance(instance, ctor, newProps, maskedLegacyContext) { { - warnOnUndefinedDerivedState(ctor, partialState); - } // Merge the partial state and the previous state. + checkClassInstance(instance, ctor, newProps); + } - var newState = - partialState === null || partialState === undefined - ? prevState - : assign({}, prevState, partialState); - return newState; - } + var initialState = instance.state !== undefined ? instance.state : null; + instance.updater = classComponentUpdater; + instance.props = newProps; + instance.state = initialState; // We don't bother initializing the refs object on the server, since we're not going to resolve them anyway. + // The internal instance will be used to manage updates that happen during this mount. - function constructClassInstance(ctor, props, maskedLegacyContext) { - var context = emptyContextObject; + var internalInstance = { + queue: [], + replace: false + }; + set(instance, internalInstance); var contextType = ctor.contextType; + if (typeof contextType === "object" && contextType !== null) { + instance.context = readContext$1(contextType); + } else { + instance.context = maskedLegacyContext; + } + { - if ("contextType" in ctor) { - var isValid = // Allow null for conditional declaration - contextType === null || - (contextType !== undefined && - contextType.$$typeof === REACT_CONTEXT_TYPE); + if (instance.state === newProps) { + var componentName = getComponentNameFromType(ctor) || "Component"; - if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { - didWarnAboutInvalidateContextType.add(ctor); - var addendum = ""; - - if (contextType === undefined) { - addendum = - " However, it is set to undefined. " + - "This can be caused by a typo or by mixing up named and default imports. " + - "This can also happen due to a circular dependency, so " + - "try moving the createContext() call to a separate file."; - } else if (typeof contextType !== "object") { - addendum = " However, it is set to a " + typeof contextType + "."; - } else if (contextType.$$typeof === REACT_CONSUMER_TYPE) { - addendum = - " Did you accidentally pass the Context.Consumer instead?"; - } else { - addendum = - " However, it is set to an object with keys {" + - Object.keys(contextType).join(", ") + - "}."; - } + if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { + didWarnAboutDirectlyAssigningPropsToState.add(componentName); error( - "%s defines an invalid contextType. " + - "contextType should point to the Context object returned by React.createContext().%s", - getComponentNameFromType(ctor) || "Component", - addendum + "%s: It is not recommended to assign props directly to state " + + "because updates to props won't be reflected in state. " + + "In most cases, it is better to use props directly.", + componentName ); } } } - if (typeof contextType === "object" && contextType !== null) { - context = readContext$1(contextType); - } else { - context = maskedLegacyContext; - } - - var instance = new ctor(props, context); - - { - if ( - typeof ctor.getDerivedStateFromProps === "function" && - (instance.state === null || instance.state === undefined) - ) { - var componentName = getComponentNameFromType(ctor) || "Component"; - - if (!didWarnAboutUninitializedState.has(componentName)) { - didWarnAboutUninitializedState.add(componentName); - - error( - "`%s` uses `getDerivedStateFromProps` but its initial state is " + - "%s. This is not recommended. Instead, define the initial state by " + - "assigning an object to `this.state` in the constructor of `%s`. " + - "This ensures that `getDerivedStateFromProps` arguments have a consistent shape.", - componentName, - instance.state === null ? "null" : "undefined", - componentName - ); - } - } // If new component APIs are defined, "unsafe" lifecycles won't be called. - // Warn about these lifecycles if they are present. - // Don't warn about react-lifecycles-compat polyfilled methods though. - - if ( - typeof ctor.getDerivedStateFromProps === "function" || - typeof instance.getSnapshotBeforeUpdate === "function" - ) { - var foundWillMountName = null; - var foundWillReceivePropsName = null; - var foundWillUpdateName = null; - - if ( - typeof instance.componentWillMount === "function" && - instance.componentWillMount.__suppressDeprecationWarning !== true - ) { - foundWillMountName = "componentWillMount"; - } else if (typeof instance.UNSAFE_componentWillMount === "function") { - foundWillMountName = "UNSAFE_componentWillMount"; - } - - if ( - typeof instance.componentWillReceiveProps === "function" && - instance.componentWillReceiveProps.__suppressDeprecationWarning !== - true - ) { - foundWillReceivePropsName = "componentWillReceiveProps"; - } else if ( - typeof instance.UNSAFE_componentWillReceiveProps === "function" - ) { - foundWillReceivePropsName = "UNSAFE_componentWillReceiveProps"; - } - - if ( - typeof instance.componentWillUpdate === "function" && - instance.componentWillUpdate.__suppressDeprecationWarning !== true - ) { - foundWillUpdateName = "componentWillUpdate"; - } else if ( - typeof instance.UNSAFE_componentWillUpdate === "function" - ) { - foundWillUpdateName = "UNSAFE_componentWillUpdate"; - } - - if ( - foundWillMountName !== null || - foundWillReceivePropsName !== null || - foundWillUpdateName !== null - ) { - var _componentName = getComponentNameFromType(ctor) || "Component"; + var getDerivedStateFromProps = ctor.getDerivedStateFromProps; - var newApiName = - typeof ctor.getDerivedStateFromProps === "function" - ? "getDerivedStateFromProps()" - : "getSnapshotBeforeUpdate()"; + if (typeof getDerivedStateFromProps === "function") { + instance.state = applyDerivedStateFromProps( + instance, + ctor, + getDerivedStateFromProps, + initialState, + newProps + ); + } // In order to support react-lifecycles-compat polyfilled components, + // Unsafe lifecycles should not be invoked for components using the new APIs. - if ( - !didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName) - ) { - didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName); + if ( + typeof ctor.getDerivedStateFromProps !== "function" && + typeof instance.getSnapshotBeforeUpdate !== "function" && + (typeof instance.UNSAFE_componentWillMount === "function" || + typeof instance.componentWillMount === "function") + ) { + callComponentWillMount(ctor, instance); // If we had additional state updates during this life-cycle, let's + // process them now. - error( - "Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n" + - "%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n" + - "The above lifecycles should be removed. Learn more about this warning here:\n" + - "https://reactjs.org/link/unsafe-component-lifecycles", - _componentName, - newApiName, - foundWillMountName !== null ? "\n " + foundWillMountName : "", - foundWillReceivePropsName !== null - ? "\n " + foundWillReceivePropsName - : "", - foundWillUpdateName !== null ? "\n " + foundWillUpdateName : "" - ); - } - } - } + processUpdateQueue( + internalInstance, + instance, + newProps, + maskedLegacyContext + ); } - - return instance; } - function checkClassInstance(instance, ctor, newProps) { - { - var name = getComponentNameFromType(ctor) || "Component"; - var renderPresent = instance.render; - - if (!renderPresent) { - if (ctor.prototype && typeof ctor.prototype.render === "function") { - error( - "%s(...): No `render` method found on the returned component " + - "instance: did you accidentally return an object from the constructor?", - name - ); - } else { - error( - "%s(...): No `render` method found on the returned component " + - "instance: you may have forgotten to define `render`.", - name - ); - } - } - - if ( - instance.getInitialState && - !instance.getInitialState.isReactClassApproved && - !instance.state - ) { - error( - "getInitialState was defined on %s, a plain JavaScript class. " + - "This is only supported for classes created using React.createClass. " + - "Did you mean to define a state property instead?", - name - ); - } + // Ids are base 32 strings whose binary representation corresponds to the + // position of a node in a tree. + // Every time the tree forks into multiple children, we add additional bits to + // the left of the 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. Otherwise, + // 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 the + // sequence. It's treated as a transparent indirection. For example, these two + // trees produce the same ids: + // + // <> <> + // + // + // + // + // + // + // However, we cannot skip any node that materializes an id. Otherwise, a parent + // id that does not fork would be indistinguishable from its child id. For + // example, this tree does not fork, but the parent and child must have + // different ids. + // + // + // + // + // + // To handle this scenario, every time we materialize an id, we allocate a + // new level with a single slot. You can think of this as a fork with only one + // prong, or an array of children with length 1. + // + // It's possible for the size of the sequence to exceed 32 bits, the max + // size for bitwise operations. When this happens, we make more room by + // converting the right part of the id to a string and storing it in an overflow + // variable. We use a base 32 string representation, because 32 is the largest + // power of 2 that is supported by toString(). We want the base to be large so + // that the resulting ids are compact, and we want the base to be a power of 2 + // because every log2(base) bits corresponds to a single character, i.e. every + // log2(32) = 5 bits. That means we can lop bits off the end 5 at a time without + // affecting the final result. + var emptyTreeContext = { + id: 1, + overflow: "" + }; + function getTreeId(context) { + var overflow = context.overflow; + var idWithLeadingBit = context.id; + var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit); + return id.toString(32) + overflow; + } + function pushTreeContext(baseContext, totalChildren, index) { + var baseIdWithLeadingBit = baseContext.id; + var baseOverflow = baseContext.overflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part + // of the id; we use it to account for leading 0s. - if ( - instance.getDefaultProps && - !instance.getDefaultProps.isReactClassApproved - ) { - error( - "getDefaultProps was defined on %s, a plain JavaScript class. " + - "This is only supported for classes created using React.createClass. " + - "Use a static property to define defaultProps instead.", - name - ); - } + var baseLength = getBitLength(baseIdWithLeadingBit) - 1; + var baseId = baseIdWithLeadingBit & ~(1 << baseLength); + var slot = index + 1; + var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into + // consideration the leading 1 we use to mark the end of the sequence. - if (instance.propTypes) { - error( - "propTypes was defined as an instance property on %s. Use a static " + - "property to define propTypes instead.", - name - ); - } + if (length > 30) { + // We overflowed the bitwise-safe range. Fall back to slower algorithm. + // This branch assumes the length of the base id is greater than 5; it won't + // work for smaller ids, because you need 5 bits per character. + // + // We encode the id in multiple steps: first the base id, then the + // remaining digits. + // + // Each 5 bit sequence corresponds to a single base 32 character. So for + // example, if the current id is 23 bits long, we can convert 20 of those + // bits into a string of 4 characters, with 3 bits left over. + // + // First calculate how many bits in the base id represent a complete + // sequence of characters. + var numberOfOverflowBits = baseLength - (baseLength % 5); // Then create a bitmask that selects only those bits. - if (instance.contextType) { - error( - "contextType was defined as an instance property on %s. Use a static " + - "property to define contextType instead.", - name - ); - } + var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string. - { - if (instance.contextTypes) { - error( - "contextTypes was defined as an instance property on %s. Use a static " + - "property to define contextTypes instead.", - name - ); - } + var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id. - if ( - ctor.contextType && - ctor.contextTypes && - !didWarnAboutContextTypeAndContextTypes.has(ctor) - ) { - didWarnAboutContextTypeAndContextTypes.add(ctor); + var restOfBaseId = baseId >> numberOfOverflowBits; + var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because + // we made more room, this time it won't overflow. - error( - "%s declares both contextTypes and contextType static properties. " + - "The legacy contextTypes property will be ignored.", - name - ); - } - } + var restOfLength = getBitLength(totalChildren) + restOfBaseLength; + var restOfNewBits = slot << restOfBaseLength; + var id = restOfNewBits | restOfBaseId; + var overflow = newOverflow + baseOverflow; + return { + id: (1 << restOfLength) | id, + overflow: overflow + }; + } else { + // Normal path + var newBits = slot << baseLength; - if (typeof instance.componentShouldUpdate === "function") { - error( - "%s has a method called " + - "componentShouldUpdate(). Did you mean shouldComponentUpdate()? " + - "The name is phrased as a question because the function is " + - "expected to return a value.", - name - ); - } + var _id = newBits | baseId; - if ( - ctor.prototype && - ctor.prototype.isPureReactComponent && - typeof instance.shouldComponentUpdate !== "undefined" - ) { - error( - "%s has a method called shouldComponentUpdate(). " + - "shouldComponentUpdate should not be used when extending React.PureComponent. " + - "Please extend React.Component if shouldComponentUpdate is used.", - getComponentNameFromType(ctor) || "A pure component" - ); - } + var _overflow = baseOverflow; + return { + id: (1 << length) | _id, + overflow: _overflow + }; + } + } - if (typeof instance.componentDidUnmount === "function") { - error( - "%s has a method called " + - "componentDidUnmount(). But there is no such lifecycle method. " + - "Did you mean componentWillUnmount()?", - name - ); - } + function getBitLength(number) { + return 32 - clz32(number); + } - if (typeof instance.componentDidReceiveProps === "function") { - error( - "%s has a method called " + - "componentDidReceiveProps(). But there is no such lifecycle method. " + - "If you meant to update the state in response to changing props, " + - "use componentWillReceiveProps(). If you meant to fetch data or " + - "run side-effects or mutations after React has updated the UI, use componentDidUpdate().", - name - ); - } + function getLeadingBit(id) { + return 1 << (getBitLength(id) - 1); + } // TODO: Math.clz32 is supported in Node 12+. Maybe we can drop the fallback. - if (typeof instance.componentWillRecieveProps === "function") { - error( - "%s has a method called " + - "componentWillRecieveProps(). Did you mean componentWillReceiveProps()?", - name - ); - } + var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros. + // Based on: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32 - if (typeof instance.UNSAFE_componentWillRecieveProps === "function") { - error( - "%s has a method called " + - "UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?", - name - ); - } + var log = Math.log; + var LN2 = Math.LN2; - var hasMutatedProps = instance.props !== newProps; + function clz32Fallback(x) { + var asUint = x >>> 0; - if (instance.props !== undefined && hasMutatedProps) { - error( - "%s(...): When calling super() in `%s`, make sure to pass " + - "up the same props that your component's constructor was passed.", - name, - name - ); - } + if (asUint === 0) { + return 32; + } - if (instance.defaultProps) { - error( - "Setting defaultProps as an instance property on %s is not supported and will be ignored." + - " Instead, define defaultProps as a static property on %s.", - name, - name - ); - } + return (31 - ((log(asUint) / LN2) | 0)) | 0; + } - if ( - typeof instance.getSnapshotBeforeUpdate === "function" && - typeof instance.componentDidUpdate !== "function" && - !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor) - ) { - didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor); + // Corresponds to ReactFiberWakeable and ReactFlightWakeable modules. Generally, + // changes to one module should be reflected in the others. + // TODO: Rename this module and the corresponding Fiber one to "Thenable" + // instead of "Wakeable". Or some other more appropriate name. + // An error that is thrown (e.g. by `use`) to trigger Suspense. If we + // detect this is caught by userspace, we'll log a warning in development. + var SuspenseException = new Error( + "Suspense Exception: This is not a real error! It's an implementation " + + "detail of `use` to interrupt the current render. You must either " + + "rethrow it immediately, or move the `use` call outside of the " + + "`try/catch` block. Capturing without rethrowing will lead to " + + "unexpected behavior.\n\n" + + "To handle async errors, wrap your component in an error boundary, or " + + "call the promise's `.catch` method and pass the result to `use`" + ); + function createThenableState() { + // The ThenableState is created the first time a component suspends. If it + // suspends again, we'll reuse the same state. + return []; + } - error( - "%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). " + - "This component defines getSnapshotBeforeUpdate() only.", - getComponentNameFromType(ctor) - ); - } + function noop$2() {} - if (typeof instance.getDerivedStateFromProps === "function") { - error( - "%s: getDerivedStateFromProps() is defined as an instance method " + - "and will be ignored. Instead, declare it as a static method.", - name - ); + function trackUsedThenable(thenableState, thenable, index) { + var previous = thenableState[index]; + + if (previous === undefined) { + thenableState.push(thenable); + } else { + if (previous !== thenable) { + // Reuse the previous thenable, and drop the new one. We can assume + // they represent the same value, because components are idempotent. + // Avoid an unhandled rejection errors for the Promises that we'll + // intentionally ignore. + thenable.then(noop$2, noop$2); + thenable = previous; } + } // We use an expando to track the status and result of a thenable so that we + // can synchronously unwrap the value. Think of this as an extension of the + // Promise API, or a custom interface that is a superset of Thenable. + // + // If the thenable doesn't have a status, set it to "pending" and attach + // a listener that will update its status and result when it resolves. - if (typeof instance.getDerivedStateFromError === "function") { - error( - "%s: getDerivedStateFromError() is defined as an instance method " + - "and will be ignored. Instead, declare it as a static method.", - name - ); + switch (thenable.status) { + case "fulfilled": { + var fulfilledValue = thenable.value; + return fulfilledValue; } - if (typeof ctor.getSnapshotBeforeUpdate === "function") { - error( - "%s: getSnapshotBeforeUpdate() is defined as a static method " + - "and will be ignored. Instead, declare it as an instance method.", - name - ); + case "rejected": { + var rejectedError = thenable.reason; + throw rejectedError; } - var state = instance.state; + default: { + if (typeof thenable.status === "string"); + else { + var pendingThenable = thenable; + pendingThenable.status = "pending"; + pendingThenable.then( + function (fulfilledValue) { + if (thenable.status === "pending") { + var fulfilledThenable = thenable; + fulfilledThenable.status = "fulfilled"; + fulfilledThenable.value = fulfilledValue; + } + }, + function (error) { + if (thenable.status === "pending") { + var rejectedThenable = thenable; + rejectedThenable.status = "rejected"; + rejectedThenable.reason = error; + } + } + ); // Check one more time in case the thenable resolved synchronously - if (state && (typeof state !== "object" || isArray(state))) { - error("%s.state: must be set to an object or null", name); - } + switch (thenable.status) { + case "fulfilled": { + var fulfilledThenable = thenable; + return fulfilledThenable.value; + } - if ( - typeof instance.getChildContext === "function" && - typeof ctor.childContextTypes !== "object" - ) { - error( - "%s.getChildContext(): childContextTypes must be defined in order to " + - "use getChildContext().", - name - ); + case "rejected": { + var rejectedThenable = thenable; + throw rejectedThenable.reason; + } + } + } // Suspend. + // + // Throwing here is an implementation detail that allows us to unwind the + // call stack. But we shouldn't allow it to leak into userspace. Throw an + // opaque placeholder value instead of the actual thenable. If it doesn't + // get captured by the work loop, log a warning, because that means + // something in userspace must have caught it. + + suspendedThenable = thenable; + throw SuspenseException; } } + } // This is used to track the actual thenable that suspended so it can be + // passed to the rest of the Suspense implementation — which, for historical + // reasons, expects to receive a thenable. + + var suspendedThenable = null; + function getSuspendedThenable() { + // This is called right after `use` suspends by throwing an exception. `use` + // throws an opaque value instead of the thenable itself so that it can't be + // caught in userspace. Then the work loop accesses the actual thenable using + // this function. + if (suspendedThenable === null) { + throw new Error( + "Expected a suspended thenable. This is a bug in React. Please file " + + "an issue." + ); + } + + var thenable = suspendedThenable; + suspendedThenable = null; + return thenable; } - function callComponentWillMount(type, instance) { - var oldState = instance.state; + /** + * inlined Object.is polyfill to avoid requiring consumers ship their own + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + */ + function is(x, y) { + return ( + (x === y && (x !== 0 || 1 / x === 1 / y)) || (x !== x && y !== y) // eslint-disable-line no-self-compare + ); + } - if (typeof instance.componentWillMount === "function") { - { - if ( - instance.componentWillMount.__suppressDeprecationWarning !== true - ) { - var componentName = getComponentNameFromType(type) || "Unknown"; + var objectIs = typeof Object.is === "function" ? Object.is : is; // $FlowFixMe[method-unbinding] - if (!didWarnAboutDeprecatedWillMount[componentName]) { - warn( - // keep this warning in sync with ReactStrictModeWarning.js - "componentWillMount has been renamed, and is not recommended for use. " + - "See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n" + - "* Move code from componentWillMount to componentDidMount (preferred in most cases) " + - "or the constructor.\n" + - "\nPlease update the following components: %s", - componentName - ); + var currentlyRenderingComponent = null; + var currentlyRenderingTask = null; + var currentlyRenderingRequest = null; + var currentlyRenderingKeyPath = null; + var firstWorkInProgressHook = null; + var workInProgressHook = null; // Whether the work-in-progress hook is a re-rendered hook - didWarnAboutDeprecatedWillMount[componentName] = true; - } - } - } + var isReRender = false; // Whether an update was scheduled during the currently executing render pass. - instance.componentWillMount(); - } + var didScheduleRenderPhaseUpdate = false; // Counts the number of useId hooks in this component - if (typeof instance.UNSAFE_componentWillMount === "function") { - instance.UNSAFE_componentWillMount(); - } + var localIdCounter = 0; // Chunks that should be pushed to the stream once the component + // finishes rendering. + // Counts the number of useFormState calls in this component - if (oldState !== instance.state) { - { - error( - "%s.componentWillMount(): Assigning directly to this.state is " + - "deprecated (except inside a component's " + - "constructor). Use setState instead.", - getComponentNameFromType(type) || "Component" - ); - } + var formStateCounter = 0; // The index of the useFormState hook that matches the one passed in at the + // root during an MPA navigation, if any. - classComponentUpdater.enqueueReplaceState( - instance, - instance.state, - null - ); - } - } + var formStateMatchingIndex = -1; // Counts the number of use(thenable) calls in this component - function processUpdateQueue( - internalInstance, - inst, - props, - maskedLegacyContext - ) { - if ( - internalInstance.queue !== null && - internalInstance.queue.length > 0 - ) { - var oldQueue = internalInstance.queue; - var oldReplace = internalInstance.replace; - internalInstance.queue = null; - internalInstance.replace = false; + var thenableIndexCounter = 0; + var thenableState = null; // Lazily created map of render-phase updates - if (oldReplace && oldQueue.length === 1) { - inst.state = oldQueue[0]; - } else { - var nextState = oldReplace ? oldQueue[0] : inst.state; - var dontMutate = true; + var renderPhaseUpdates = null; // Counter to prevent infinite loops. - for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) { - var partial = oldQueue[i]; - var partialState = - typeof partial === "function" - ? partial.call(inst, nextState, props, maskedLegacyContext) - : partial; + var numberOfReRenders = 0; + var RE_RENDER_LIMIT = 25; + var isInHookUserCodeInDev = false; // In DEV, this is the name of the currently executing primitive hook - if (partialState != null) { - if (dontMutate) { - dontMutate = false; - nextState = assign({}, nextState, partialState); - } else { - assign(nextState, partialState); - } - } - } + var currentHookNameInDev; - inst.state = nextState; + function resolveCurrentlyRenderingComponent() { + if (currentlyRenderingComponent === null) { + throw new Error( + "Invalid hook call. Hooks can only be called inside of the body of a function 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 of Hooks\n" + + "3. You might have more than one copy of React in the same app\n" + + "See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem." + ); + } + + { + if (isInHookUserCodeInDev) { + error( + "Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. " + + "You can only call Hooks at the top level of your React function. " + + "For more information, see " + + "https://reactjs.org/link/rules-of-hooks" + ); } - } else { - internalInstance.queue = null; - } - } // Invokes the mount life-cycles on a previously never rendered instance. - - function mountClassInstance(instance, ctor, newProps, maskedLegacyContext) { - { - checkClassInstance(instance, ctor, newProps); } - var initialState = instance.state !== undefined ? instance.state : null; - instance.updater = classComponentUpdater; - instance.props = newProps; - instance.state = initialState; // We don't bother initializing the refs object on the server, since we're not going to resolve them anyway. - // The internal instance will be used to manage updates that happen during this mount. + return currentlyRenderingComponent; + } - var internalInstance = { - queue: [], - replace: false - }; - set(instance, internalInstance); - var contextType = ctor.contextType; + function areHookInputsEqual(nextDeps, prevDeps) { + if (prevDeps === null) { + { + error( + "%s received a final argument during this render, but not during " + + "the previous render. Even though the final argument is optional, " + + "its type cannot change between renders.", + currentHookNameInDev + ); + } - if (typeof contextType === "object" && contextType !== null) { - instance.context = readContext$1(contextType); - } else { - instance.context = maskedLegacyContext; + return false; } { - if (instance.state === newProps) { - var componentName = getComponentNameFromType(ctor) || "Component"; - - if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { - didWarnAboutDirectlyAssigningPropsToState.add(componentName); - - error( - "%s: It is not recommended to assign props directly to state " + - "because updates to props won't be reflected in state. " + - "In most cases, it is better to use props directly.", - componentName - ); - } + // Don't bother comparing lengths in prod because these arrays should be + // passed inline. + if (nextDeps.length !== prevDeps.length) { + error( + "The final argument passed to %s changed size between renders. The " + + "order and size of this array must remain constant.\n\n" + + "Previous: %s\n" + + "Incoming: %s", + currentHookNameInDev, + "[" + nextDeps.join(", ") + "]", + "[" + prevDeps.join(", ") + "]" + ); } - } + } // $FlowFixMe[incompatible-use] found when upgrading Flow - var getDerivedStateFromProps = ctor.getDerivedStateFromProps; + for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) { + // $FlowFixMe[incompatible-use] found when upgrading Flow + if (objectIs(nextDeps[i], prevDeps[i])) { + continue; + } - if (typeof getDerivedStateFromProps === "function") { - instance.state = applyDerivedStateFromProps( - instance, - ctor, - getDerivedStateFromProps, - initialState, - newProps - ); - } // In order to support react-lifecycles-compat polyfilled components, - // Unsafe lifecycles should not be invoked for components using the new APIs. + return false; + } - if ( - typeof ctor.getDerivedStateFromProps !== "function" && - typeof instance.getSnapshotBeforeUpdate !== "function" && - (typeof instance.UNSAFE_componentWillMount === "function" || - typeof instance.componentWillMount === "function") - ) { - callComponentWillMount(ctor, instance); // If we had additional state updates during this life-cycle, let's - // process them now. + return true; + } - processUpdateQueue( - internalInstance, - instance, - newProps, - maskedLegacyContext - ); + function createHook() { + if (numberOfReRenders > 0) { + throw new Error("Rendered more hooks than during the previous render"); } - } - // Ids are base 32 strings whose binary representation corresponds to the - // position of a node in a tree. - // Every time the tree forks into multiple children, we add additional bits to - // the left of the 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. Otherwise, - // 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 the - // sequence. It's treated as a transparent indirection. For example, these two - // trees produce the same ids: - // - // <> <> - // - // - // - // - // - // - // However, we cannot skip any node that materializes an id. Otherwise, a parent - // id that does not fork would be indistinguishable from its child id. For - // example, this tree does not fork, but the parent and child must have - // different ids. - // - // - // - // - // - // To handle this scenario, every time we materialize an id, we allocate a - // new level with a single slot. You can think of this as a fork with only one - // prong, or an array of children with length 1. - // - // It's possible for the size of the sequence to exceed 32 bits, the max - // size for bitwise operations. When this happens, we make more room by - // converting the right part of the id to a string and storing it in an overflow - // variable. We use a base 32 string representation, because 32 is the largest - // power of 2 that is supported by toString(). We want the base to be large so - // that the resulting ids are compact, and we want the base to be a power of 2 - // because every log2(base) bits corresponds to a single character, i.e. every - // log2(32) = 5 bits. That means we can lop bits off the end 5 at a time without - // affecting the final result. - var emptyTreeContext = { - id: 1, - overflow: "" - }; - function getTreeId(context) { - var overflow = context.overflow; - var idWithLeadingBit = context.id; - var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit); - return id.toString(32) + overflow; + return { + memoizedState: null, + queue: null, + next: null + }; } - function pushTreeContext(baseContext, totalChildren, index) { - var baseIdWithLeadingBit = baseContext.id; - var baseOverflow = baseContext.overflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part - // of the id; we use it to account for leading 0s. - - var baseLength = getBitLength(baseIdWithLeadingBit) - 1; - var baseId = baseIdWithLeadingBit & ~(1 << baseLength); - var slot = index + 1; - var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into - // consideration the leading 1 we use to mark the end of the sequence. - if (length > 30) { - // We overflowed the bitwise-safe range. Fall back to slower algorithm. - // This branch assumes the length of the base id is greater than 5; it won't - // work for smaller ids, because you need 5 bits per character. - // - // We encode the id in multiple steps: first the base id, then the - // remaining digits. - // - // Each 5 bit sequence corresponds to a single base 32 character. So for - // example, if the current id is 23 bits long, we can convert 20 of those - // bits into a string of 4 characters, with 3 bits left over. - // - // First calculate how many bits in the base id represent a complete - // sequence of characters. - var numberOfOverflowBits = baseLength - (baseLength % 5); // Then create a bitmask that selects only those bits. + function createWorkInProgressHook() { + if (workInProgressHook === null) { + // This is the first hook in the list + if (firstWorkInProgressHook === null) { + isReRender = false; + firstWorkInProgressHook = workInProgressHook = createHook(); + } else { + // There's already a work-in-progress. Reuse it. + isReRender = true; + workInProgressHook = firstWorkInProgressHook; + } + } else { + if (workInProgressHook.next === null) { + isReRender = false; // Append to the end of the list - var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string. + workInProgressHook = workInProgressHook.next = createHook(); + } else { + // There's already a work-in-progress. Reuse it. + isReRender = true; + workInProgressHook = workInProgressHook.next; + } + } - var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id. + return workInProgressHook; + } - var restOfBaseId = baseId >> numberOfOverflowBits; - var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because - // we made more room, this time it won't overflow. + function prepareToUseHooks( + request, + task, + keyPath, + componentIdentity, + prevThenableState + ) { + currentlyRenderingComponent = componentIdentity; + currentlyRenderingTask = task; + currentlyRenderingRequest = request; + currentlyRenderingKeyPath = keyPath; - var restOfLength = getBitLength(totalChildren) + restOfBaseLength; - var restOfNewBits = slot << restOfBaseLength; - var id = restOfNewBits | restOfBaseId; - var overflow = newOverflow + baseOverflow; - return { - id: (1 << restOfLength) | id, - overflow: overflow - }; - } else { - // Normal path - var newBits = slot << baseLength; + { + isInHookUserCodeInDev = false; + } // The following should have already been reset + // didScheduleRenderPhaseUpdate = false; + // firstWorkInProgressHook = null; + // numberOfReRenders = 0; + // renderPhaseUpdates = null; + // workInProgressHook = null; - var _id = newBits | baseId; + localIdCounter = 0; + formStateCounter = 0; + formStateMatchingIndex = -1; + thenableIndexCounter = 0; + thenableState = prevThenableState; + } + function finishHooks(Component, props, children, refOrContext) { + // This must be called after every function component to prevent hooks from + // being used in classes. + while (didScheduleRenderPhaseUpdate) { + // Updates were scheduled during the render phase. They are stored in + // the `renderPhaseUpdates` map. Call the component again, reusing the + // work-in-progress hooks and applying the additional updates on top. Keep + // restarting until no more updates are scheduled. + didScheduleRenderPhaseUpdate = false; + localIdCounter = 0; + formStateCounter = 0; + formStateMatchingIndex = -1; + thenableIndexCounter = 0; + numberOfReRenders += 1; // Start over from the beginning of the list - var _overflow = baseOverflow; - return { - id: (1 << length) | _id, - overflow: _overflow - }; + workInProgressHook = null; + children = Component(props, refOrContext); } - } - function getBitLength(number) { - return 32 - clz32(number); + resetHooksState(); + return children; + } + function getThenableStateAfterSuspending() { + var state = thenableState; + thenableState = null; + return state; + } + function checkDidRenderIdHook() { + // This should be called immediately after every finishHooks call. + // Conceptually, it's part of the return value of finishHooks; it's only a + // separate function to avoid using an array tuple. + var didRenderIdHook = localIdCounter !== 0; + return didRenderIdHook; + } + function getFormStateCount() { + // This should be called immediately after every finishHooks call. + // Conceptually, it's part of the return value of finishHooks; it's only a + // separate function to avoid using an array tuple. + return formStateCounter; } + function getFormStateMatchingIndex() { + // This should be called immediately after every finishHooks call. + // Conceptually, it's part of the return value of finishHooks; it's only a + // separate function to avoid using an array tuple. + return formStateMatchingIndex; + } // Reset the internal hooks state if an error occurs while rendering a component - function getLeadingBit(id) { - return 1 << (getBitLength(id) - 1); - } // TODO: Math.clz32 is supported in Node 12+. Maybe we can drop the fallback. + function resetHooksState() { + { + isInHookUserCodeInDev = false; + } - var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros. - // Based on: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32 + currentlyRenderingComponent = null; + currentlyRenderingTask = null; + currentlyRenderingRequest = null; + currentlyRenderingKeyPath = null; + didScheduleRenderPhaseUpdate = false; + firstWorkInProgressHook = null; + numberOfReRenders = 0; + renderPhaseUpdates = null; + workInProgressHook = null; + } - var log = Math.log; - var LN2 = Math.LN2; + function readContext(context) { + { + if (isInHookUserCodeInDev) { + error( + "Context can only be read while React is rendering. " + + "In classes, you can read it in the render method or getDerivedStateFromProps. " + + "In function components, you can read it directly in the function body, but not " + + "inside Hooks like useReducer() or useMemo()." + ); + } + } - function clz32Fallback(x) { - var asUint = x >>> 0; + return readContext$1(context); + } - if (asUint === 0) { - return 32; + function useContext(context) { + { + currentHookNameInDev = "useContext"; } - return (31 - ((log(asUint) / LN2) | 0)) | 0; + resolveCurrentlyRenderingComponent(); + return readContext$1(context); } - // Corresponds to ReactFiberWakeable and ReactFlightWakeable modules. Generally, - // changes to one module should be reflected in the others. - // TODO: Rename this module and the corresponding Fiber one to "Thenable" - // instead of "Wakeable". Or some other more appropriate name. - // An error that is thrown (e.g. by `use`) to trigger Suspense. If we - // detect this is caught by userspace, we'll log a warning in development. - var SuspenseException = new Error( - "Suspense Exception: This is not a real error! It's an implementation " + - "detail of `use` to interrupt the current render. You must either " + - "rethrow it immediately, or move the `use` call outside of the " + - "`try/catch` block. Capturing without rethrowing will lead to " + - "unexpected behavior.\n\n" + - "To handle async errors, wrap your component in an error boundary, or " + - "call the promise's `.catch` method and pass the result to `use`" - ); - function createThenableState() { - // The ThenableState is created the first time a component suspends. If it - // suspends again, we'll reuse the same state. - return []; + function basicStateReducer(state, action) { + // $FlowFixMe[incompatible-use]: Flow doesn't like mixed types + return typeof action === "function" ? action(state) : action; } - function noop$2() {} - - function trackUsedThenable(thenableState, thenable, index) { - var previous = thenableState[index]; - - if (previous === undefined) { - thenableState.push(thenable); - } else { - if (previous !== thenable) { - // Reuse the previous thenable, and drop the new one. We can assume - // they represent the same value, because components are idempotent. - // Avoid an unhandled rejection errors for the Promises that we'll - // intentionally ignore. - thenable.then(noop$2, noop$2); - thenable = previous; - } - } // We use an expando to track the status and result of a thenable so that we - // can synchronously unwrap the value. Think of this as an extension of the - // Promise API, or a custom interface that is a superset of Thenable. - // - // If the thenable doesn't have a status, set it to "pending" and attach - // a listener that will update its status and result when it resolves. - - switch (thenable.status) { - case "fulfilled": { - var fulfilledValue = thenable.value; - return fulfilledValue; - } + function useState(initialState) { + { + currentHookNameInDev = "useState"; + } - case "rejected": { - var rejectedError = thenable.reason; - throw rejectedError; + return useReducer( + basicStateReducer, // useReducer has a special case to support lazy useState initializers + initialState + ); + } + function useReducer(reducer, initialArg, init) { + { + if (reducer !== basicStateReducer) { + currentHookNameInDev = "useReducer"; } + } - default: { - if (typeof thenable.status === "string"); - else { - var pendingThenable = thenable; - pendingThenable.status = "pending"; - pendingThenable.then( - function (fulfilledValue) { - if (thenable.status === "pending") { - var fulfilledThenable = thenable; - fulfilledThenable.status = "fulfilled"; - fulfilledThenable.value = fulfilledValue; - } - }, - function (error) { - if (thenable.status === "pending") { - var rejectedThenable = thenable; - rejectedThenable.status = "rejected"; - rejectedThenable.reason = error; - } - } - ); // Check one more time in case the thenable resolved synchronously + currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); + workInProgressHook = createWorkInProgressHook(); - switch (thenable.status) { - case "fulfilled": { - var fulfilledThenable = thenable; - return fulfilledThenable.value; - } + if (isReRender) { + // This is a re-render. Apply the new render phase updates to the previous + // current hook. + var queue = workInProgressHook.queue; + var dispatch = queue.dispatch; - case "rejected": { - var rejectedThenable = thenable; - throw rejectedThenable.reason; - } - } - } // Suspend. - // - // Throwing here is an implementation detail that allows us to unwind the - // call stack. But we shouldn't allow it to leak into userspace. Throw an - // opaque placeholder value instead of the actual thenable. If it doesn't - // get captured by the work loop, log a warning, because that means - // something in userspace must have caught it. + if (renderPhaseUpdates !== null) { + // Render phase updates are stored in a map of queue -> linked list + var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); - suspendedThenable = thenable; - throw SuspenseException; - } - } - } // This is used to track the actual thenable that suspended so it can be - // passed to the rest of the Suspense implementation — which, for historical - // reasons, expects to receive a thenable. + if (firstRenderPhaseUpdate !== undefined) { + // $FlowFixMe[incompatible-use] found when upgrading Flow + renderPhaseUpdates.delete(queue); // $FlowFixMe[incompatible-use] found when upgrading Flow - var suspendedThenable = null; - function getSuspendedThenable() { - // This is called right after `use` suspends by throwing an exception. `use` - // throws an opaque value instead of the thenable itself so that it can't be - // caught in userspace. Then the work loop accesses the actual thenable using - // this function. - if (suspendedThenable === null) { - throw new Error( - "Expected a suspended thenable. This is a bug in React. Please file " + - "an issue." - ); - } + var newState = workInProgressHook.memoizedState; + var update = firstRenderPhaseUpdate; - var thenable = suspendedThenable; - suspendedThenable = null; - return thenable; - } + do { + // Process this render phase update. We don't have to check the + // priority because it will always be the same as the current + // render's. + var action = update.action; - /** - * inlined Object.is polyfill to avoid requiring consumers ship their own - * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is - */ - function is(x, y) { - return ( - (x === y && (x !== 0 || 1 / x === 1 / y)) || (x !== x && y !== y) // eslint-disable-line no-self-compare - ); - } + { + isInHookUserCodeInDev = true; + } - var objectIs = typeof Object.is === "function" ? Object.is : is; // $FlowFixMe[method-unbinding] + newState = reducer(newState, action); - var currentlyRenderingComponent = null; - var currentlyRenderingTask = null; - var currentlyRenderingRequest = null; - var currentlyRenderingKeyPath = null; - var firstWorkInProgressHook = null; - var workInProgressHook = null; // Whether the work-in-progress hook is a re-rendered hook + { + isInHookUserCodeInDev = false; + } // $FlowFixMe[incompatible-type] we bail out when we get a null - var isReRender = false; // Whether an update was scheduled during the currently executing render pass. + update = update.next; + } while (update !== null); // $FlowFixMe[incompatible-use] found when upgrading Flow - var didScheduleRenderPhaseUpdate = false; // Counts the number of useId hooks in this component + workInProgressHook.memoizedState = newState; + return [newState, dispatch]; + } + } // $FlowFixMe[incompatible-use] found when upgrading Flow - var localIdCounter = 0; // Chunks that should be pushed to the stream once the component - // finishes rendering. - // Counts the number of useFormState calls in this component + return [workInProgressHook.memoizedState, dispatch]; + } else { + { + isInHookUserCodeInDev = true; + } - var formStateCounter = 0; // The index of the useFormState hook that matches the one passed in at the - // root during an MPA navigation, if any. + var initialState; - var formStateMatchingIndex = -1; // Counts the number of use(thenable) calls in this component + if (reducer === basicStateReducer) { + // Special case for `useState`. + initialState = + typeof initialArg === "function" ? initialArg() : initialArg; + } else { + initialState = init !== undefined ? init(initialArg) : initialArg; + } - var thenableIndexCounter = 0; - var thenableState = null; // Lazily created map of render-phase updates + { + isInHookUserCodeInDev = false; + } // $FlowFixMe[incompatible-use] found when upgrading Flow - var renderPhaseUpdates = null; // Counter to prevent infinite loops. + workInProgressHook.memoizedState = initialState; // $FlowFixMe[incompatible-use] found when upgrading Flow - var numberOfReRenders = 0; - var RE_RENDER_LIMIT = 25; - var isInHookUserCodeInDev = false; // In DEV, this is the name of the currently executing primitive hook + var _queue = (workInProgressHook.queue = { + last: null, + dispatch: null + }); - var currentHookNameInDev; + var _dispatch = (_queue.dispatch = dispatchAction.bind( + null, + currentlyRenderingComponent, + _queue + )); // $FlowFixMe[incompatible-use] found when upgrading Flow - function resolveCurrentlyRenderingComponent() { - if (currentlyRenderingComponent === null) { - throw new Error( - "Invalid hook call. Hooks can only be called inside of the body of a function 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 of Hooks\n" + - "3. You might have more than one copy of React in the same app\n" + - "See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem." - ); + return [workInProgressHook.memoizedState, _dispatch]; } + } - { - if (isInHookUserCodeInDev) { - error( - "Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. " + - "You can only call Hooks at the top level of your React function. " + - "For more information, see " + - "https://reactjs.org/link/rules-of-hooks" - ); - } - } + function useMemo(nextCreate, deps) { + currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); + workInProgressHook = createWorkInProgressHook(); + var nextDeps = deps === undefined ? null : deps; - return currentlyRenderingComponent; - } + if (workInProgressHook !== null) { + var prevState = workInProgressHook.memoizedState; - function areHookInputsEqual(nextDeps, prevDeps) { - if (prevDeps === null) { - { - error( - "%s received a final argument during this render, but not during " + - "the previous render. Even though the final argument is optional, " + - "its type cannot change between renders.", - currentHookNameInDev - ); - } + if (prevState !== null) { + if (nextDeps !== null) { + var prevDeps = prevState[1]; - return false; + if (areHookInputsEqual(nextDeps, prevDeps)) { + return prevState[0]; + } + } + } } { - // Don't bother comparing lengths in prod because these arrays should be - // passed inline. - if (nextDeps.length !== prevDeps.length) { - error( - "The final argument passed to %s changed size between renders. The " + - "order and size of this array must remain constant.\n\n" + - "Previous: %s\n" + - "Incoming: %s", - currentHookNameInDev, - "[" + nextDeps.join(", ") + "]", - "[" + prevDeps.join(", ") + "]" - ); - } - } // $FlowFixMe[incompatible-use] found when upgrading Flow + isInHookUserCodeInDev = true; + } - for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) { - // $FlowFixMe[incompatible-use] found when upgrading Flow - if (objectIs(nextDeps[i], prevDeps[i])) { - continue; - } + var nextValue = nextCreate(); - return false; - } + { + isInHookUserCodeInDev = false; + } // $FlowFixMe[incompatible-use] found when upgrading Flow - return true; + workInProgressHook.memoizedState = [nextValue, nextDeps]; + return nextValue; } - function createHook() { - if (numberOfReRenders > 0) { - throw new Error("Rendered more hooks than during the previous render"); - } + function useRef(initialValue) { + currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); + workInProgressHook = createWorkInProgressHook(); + var previousRef = workInProgressHook.memoizedState; - return { - memoizedState: null, - queue: null, - next: null - }; - } + if (previousRef === null) { + var ref = { + current: initialValue + }; - function createWorkInProgressHook() { - if (workInProgressHook === null) { - // This is the first hook in the list - if (firstWorkInProgressHook === null) { - isReRender = false; - firstWorkInProgressHook = workInProgressHook = createHook(); - } else { - // There's already a work-in-progress. Reuse it. - isReRender = true; - workInProgressHook = firstWorkInProgressHook; - } + { + Object.seal(ref); + } // $FlowFixMe[incompatible-use] found when upgrading Flow + + workInProgressHook.memoizedState = ref; + return ref; } else { - if (workInProgressHook.next === null) { - isReRender = false; // Append to the end of the list + return previousRef; + } + } - workInProgressHook = workInProgressHook.next = createHook(); - } else { - // There's already a work-in-progress. Reuse it. - isReRender = true; - workInProgressHook = workInProgressHook.next; - } + function dispatchAction(componentIdentity, queue, action) { + if (numberOfReRenders >= RE_RENDER_LIMIT) { + throw new Error( + "Too many re-renders. React limits the number of renders to prevent " + + "an infinite loop." + ); } - return workInProgressHook; - } + if (componentIdentity === currentlyRenderingComponent) { + // This is a render phase update. Stash it in a lazily-created map of + // queue -> linked list of updates. After this render pass, we'll restart + // and apply the stashed updates on top of the work-in-progress hook. + didScheduleRenderPhaseUpdate = true; + var update = { + action: action, + next: null + }; - function prepareToUseHooks( - request, - task, - keyPath, - componentIdentity, - prevThenableState - ) { - currentlyRenderingComponent = componentIdentity; - currentlyRenderingTask = task; - currentlyRenderingRequest = request; - currentlyRenderingKeyPath = keyPath; + if (renderPhaseUpdates === null) { + renderPhaseUpdates = new Map(); + } - { - isInHookUserCodeInDev = false; - } // The following should have already been reset - // didScheduleRenderPhaseUpdate = false; - // firstWorkInProgressHook = null; - // numberOfReRenders = 0; - // renderPhaseUpdates = null; - // workInProgressHook = null; + var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); - localIdCounter = 0; - formStateCounter = 0; - formStateMatchingIndex = -1; - thenableIndexCounter = 0; - thenableState = prevThenableState; - } - function finishHooks(Component, props, children, refOrContext) { - // This must be called after every function component to prevent hooks from - // being used in classes. - while (didScheduleRenderPhaseUpdate) { - // Updates were scheduled during the render phase. They are stored in - // the `renderPhaseUpdates` map. Call the component again, reusing the - // work-in-progress hooks and applying the additional updates on top. Keep - // restarting until no more updates are scheduled. - didScheduleRenderPhaseUpdate = false; - localIdCounter = 0; - formStateCounter = 0; - formStateMatchingIndex = -1; - thenableIndexCounter = 0; - numberOfReRenders += 1; // Start over from the beginning of the list + if (firstRenderPhaseUpdate === undefined) { + // $FlowFixMe[incompatible-use] found when upgrading Flow + renderPhaseUpdates.set(queue, update); + } else { + // Append the update to the end of the list. + var lastRenderPhaseUpdate = firstRenderPhaseUpdate; - workInProgressHook = null; - children = Component(props, refOrContext); + while (lastRenderPhaseUpdate.next !== null) { + lastRenderPhaseUpdate = lastRenderPhaseUpdate.next; + } + + lastRenderPhaseUpdate.next = update; + } } - - resetHooksState(); - return children; } - function getThenableStateAfterSuspending() { - var state = thenableState; - thenableState = null; - return state; + + function useCallback(callback, deps) { + return useMemo(function () { + return callback; + }, deps); } - function checkDidRenderIdHook() { - // This should be called immediately after every finishHooks call. - // Conceptually, it's part of the return value of finishHooks; it's only a - // separate function to avoid using an array tuple. - var didRenderIdHook = localIdCounter !== 0; - return didRenderIdHook; + + function throwOnUseEffectEventCall() { + throw new Error( + "A function wrapped in useEffectEvent can't be called during rendering." + ); } - function getFormStateCount() { - // This should be called immediately after every finishHooks call. - // Conceptually, it's part of the return value of finishHooks; it's only a - // separate function to avoid using an array tuple. - return formStateCounter; + + function useEffectEvent(callback) { + // $FlowIgnore[incompatible-return] + return throwOnUseEffectEventCall; } - function getFormStateMatchingIndex() { - // This should be called immediately after every finishHooks call. - // Conceptually, it's part of the return value of finishHooks; it's only a - // separate function to avoid using an array tuple. - return formStateMatchingIndex; - } // Reset the internal hooks state if an error occurs while rendering a component - function resetHooksState() { - { - isInHookUserCodeInDev = false; + function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { + if (getServerSnapshot === undefined) { + throw new Error( + "Missing getServerSnapshot, which is required for " + + "server-rendered content. Will revert to client rendering." + ); } - currentlyRenderingComponent = null; - currentlyRenderingTask = null; - currentlyRenderingRequest = null; - currentlyRenderingKeyPath = null; - didScheduleRenderPhaseUpdate = false; - firstWorkInProgressHook = null; - numberOfReRenders = 0; - renderPhaseUpdates = null; - workInProgressHook = null; + return getServerSnapshot(); } - function readContext(context) { - { - if (isInHookUserCodeInDev) { - error( - "Context can only be read while React is rendering. " + - "In classes, you can read it in the render method or getDerivedStateFromProps. " + - "In function components, you can read it directly in the function body, but not " + - "inside Hooks like useReducer() or useMemo()." - ); - } - } + function useDeferredValue(value, initialValue) { + resolveCurrentlyRenderingComponent(); - return readContext$1(context); + if (enableUseDeferredValueInitialArg) { + return initialValue !== undefined ? initialValue : value; + } else { + return value; + } } - function useContext(context) { - { - currentHookNameInDev = "useContext"; - } + function unsupportedStartTransition() { + throw new Error( + "startTransition cannot be called during server rendering." + ); + } + function useTransition() { resolveCurrentlyRenderingComponent(); - return readContext$1(context); + return [false, unsupportedStartTransition]; } - function basicStateReducer(state, action) { - // $FlowFixMe[incompatible-use]: Flow doesn't like mixed types - return typeof action === "function" ? action(state) : action; + function useHostTransitionStatus() { + resolveCurrentlyRenderingComponent(); + return NotPendingTransition; } - function useState(initialState) { - { - currentHookNameInDev = "useState"; - } + function unsupportedSetOptimisticState() { + throw new Error("Cannot update optimistic state while rendering."); + } - return useReducer( - basicStateReducer, // useReducer has a special case to support lazy useState initializers - initialState - ); + function useOptimistic(passthrough, reducer) { + resolveCurrentlyRenderingComponent(); + return [passthrough, unsupportedSetOptimisticState]; } - function useReducer(reducer, initialArg, init) { - { - if (reducer !== basicStateReducer) { - currentHookNameInDev = "useReducer"; - } - } - currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); - workInProgressHook = createWorkInProgressHook(); + function createPostbackFormStateKey( + permalink, + componentKeyPath, + hookIndex + ) { + if (permalink !== undefined) { + // Don't bother to hash a permalink-based key since it's already short. + return "p" + permalink; + } else { + // Append a node to the key path that represents the form state hook. + var keyPath = [componentKeyPath, null, hookIndex]; // Key paths are hashed to reduce the size. It does not need to be secure, + // and it's more important that it's fast than that it's completely + // collision-free. - if (isReRender) { - // This is a re-render. Apply the new render phase updates to the previous - // current hook. - var queue = workInProgressHook.queue; - var dispatch = queue.dispatch; + var keyPathHash = createFastHashJS(JSON.stringify(keyPath)); + return "k" + keyPathHash; + } + } - if (renderPhaseUpdates !== null) { - // Render phase updates are stored in a map of queue -> linked list - var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); + function useFormState(action, initialState, permalink) { + resolveCurrentlyRenderingComponent(); // Count the number of useFormState hooks per component. We also use this to + // track the position of this useFormState hook relative to the other ones in + // this component, so we can generate a unique key for each one. - if (firstRenderPhaseUpdate !== undefined) { - // $FlowFixMe[incompatible-use] found when upgrading Flow - renderPhaseUpdates.delete(queue); // $FlowFixMe[incompatible-use] found when upgrading Flow + var formStateHookIndex = formStateCounter++; + var request = currentlyRenderingRequest; // $FlowIgnore[prop-missing] - var newState = workInProgressHook.memoizedState; - var update = firstRenderPhaseUpdate; + var formAction = action.$$FORM_ACTION; - do { - // Process this render phase update. We don't have to check the - // priority because it will always be the same as the current - // render's. - var action = update.action; + if (typeof formAction === "function") { + // This is a server action. These have additional features to enable + // MPA-style form submissions with progressive enhancement. + // TODO: If the same permalink is passed to multiple useFormStates, and + // they all have the same action signature, Fizz will pass the postback + // state to all of them. We should probably only pass it to the first one, + // and/or warn. + // The key is lazily generated and deduped so the that the keypath doesn't + // get JSON.stringify-ed unnecessarily, and at most once. + var nextPostbackStateKey = null; // Determine the current form state. If we received state during an MPA form + // submission, then we will reuse that, if the action identity matches. + // Otherwise we'll use the initial state argument. We will emit a comment + // marker into the stream that indicates whether the state was reused. - { - isInHookUserCodeInDev = true; - } + var state = initialState; + var componentKeyPath = currentlyRenderingKeyPath; + var postbackFormState = getFormState(request); // $FlowIgnore[prop-missing] - newState = reducer(newState, action); + var isSignatureEqual = action.$$IS_SIGNATURE_EQUAL; - { - isInHookUserCodeInDev = false; - } // $FlowFixMe[incompatible-type] we bail out when we get a null + if ( + postbackFormState !== null && + typeof isSignatureEqual === "function" + ) { + var postbackKey = postbackFormState[1]; + var postbackReferenceId = postbackFormState[2]; + var postbackBoundArity = postbackFormState[3]; - update = update.next; - } while (update !== null); // $FlowFixMe[incompatible-use] found when upgrading Flow + if ( + isSignatureEqual.call( + action, + postbackReferenceId, + postbackBoundArity + ) + ) { + nextPostbackStateKey = createPostbackFormStateKey( + permalink, + componentKeyPath, + formStateHookIndex + ); - workInProgressHook.memoizedState = newState; - return [newState, dispatch]; + if (postbackKey === nextPostbackStateKey) { + // This was a match + formStateMatchingIndex = formStateHookIndex; // Reuse the state that was submitted by the form. + + state = postbackFormState[0]; + } } - } // $FlowFixMe[incompatible-use] found when upgrading Flow + } // Bind the state to the first argument of the action. - return [workInProgressHook.memoizedState, dispatch]; - } else { - { - isInHookUserCodeInDev = true; - } + var boundAction = action.bind(null, state); // Wrap the action so the return value is void. - var initialState; + var dispatch = function (payload) { + boundAction(payload); + }; // $FlowIgnore[prop-missing] - if (reducer === basicStateReducer) { - // Special case for `useState`. - initialState = - typeof initialArg === "function" ? initialArg() : initialArg; - } else { - initialState = init !== undefined ? init(initialArg) : initialArg; - } + if (typeof boundAction.$$FORM_ACTION === "function") { + // $FlowIgnore[prop-missing] + dispatch.$$FORM_ACTION = function (prefix) { + var metadata = boundAction.$$FORM_ACTION(prefix); // Override the action URL - { - isInHookUserCodeInDev = false; - } // $FlowFixMe[incompatible-use] found when upgrading Flow + if (permalink !== undefined) { + { + checkAttributeStringCoercion(permalink, "target"); + } + + permalink += ""; + metadata.action = permalink; + } + + var formData = metadata.data; + + if (formData) { + if (nextPostbackStateKey === null) { + nextPostbackStateKey = createPostbackFormStateKey( + permalink, + componentKeyPath, + formStateHookIndex + ); + } - workInProgressHook.memoizedState = initialState; // $FlowFixMe[incompatible-use] found when upgrading Flow + formData.append("$ACTION_KEY", nextPostbackStateKey); + } - var _queue = (workInProgressHook.queue = { - last: null, - dispatch: null - }); + return metadata; + }; + } - var _dispatch = (_queue.dispatch = dispatchAction.bind( - null, - currentlyRenderingComponent, - _queue - )); // $FlowFixMe[incompatible-use] found when upgrading Flow + return [state, dispatch]; + } else { + // This is not a server action, so the implementation is much simpler. + // Bind the state to the first argument of the action. + var _boundAction = action.bind(null, initialState); // Wrap the action so the return value is void. - return [workInProgressHook.memoizedState, _dispatch]; + var _dispatch2 = function (payload) { + _boundAction(payload); + }; + + return [initialState, _dispatch2]; } } - function useMemo(nextCreate, deps) { - currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); - workInProgressHook = createWorkInProgressHook(); - var nextDeps = deps === undefined ? null : deps; + function useId() { + var task = currentlyRenderingTask; + var treeId = getTreeId(task.treeContext); + var resumableState = currentResumableState; - if (workInProgressHook !== null) { - var prevState = workInProgressHook.memoizedState; + if (resumableState === null) { + throw new Error( + "Invalid hook call. Hooks can only be called inside of the body of a function component." + ); + } - if (prevState !== null) { - if (nextDeps !== null) { - var prevDeps = prevState[1]; + var localId = localIdCounter++; + return makeId(resumableState, treeId, localId); + } - if (areHookInputsEqual(nextDeps, prevDeps)) { - return prevState[0]; - } - } + function use(usable) { + if (usable !== null && typeof usable === "object") { + // $FlowFixMe[method-unbinding] + if (typeof usable.then === "function") { + // This is a thenable. + var thenable = usable; + return unwrapThenable(thenable); + } else if (usable.$$typeof === REACT_CONTEXT_TYPE) { + var context = usable; + return readContext(context); } - } + } // eslint-disable-next-line react-internal/safe-string-coercion - { - isInHookUserCodeInDev = true; - } + throw new Error( + "An unsupported type was passed to use(): " + String(usable) + ); + } - var nextValue = nextCreate(); + function unwrapThenable(thenable) { + var index = thenableIndexCounter; + thenableIndexCounter += 1; - { - isInHookUserCodeInDev = false; - } // $FlowFixMe[incompatible-use] found when upgrading Flow + if (thenableState === null) { + thenableState = createThenableState(); + } - workInProgressHook.memoizedState = [nextValue, nextDeps]; - return nextValue; + return trackUsedThenable(thenableState, thenable, index); } - function useRef(initialValue) { - currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); - workInProgressHook = createWorkInProgressHook(); - var previousRef = workInProgressHook.memoizedState; + function unsupportedRefresh() { + throw new Error("Cache cannot be refreshed during server rendering."); + } - if (previousRef === null) { - var ref = { - current: initialValue - }; + function useCacheRefresh() { + return unsupportedRefresh; + } - { - Object.seal(ref); - } // $FlowFixMe[incompatible-use] found when upgrading Flow + function useMemoCache(size) { + var data = new Array(size); - workInProgressHook.memoizedState = ref; - return ref; - } else { - return previousRef; + for (var i = 0; i < size; i++) { + data[i] = REACT_MEMO_CACHE_SENTINEL; } + + return data; } - function dispatchAction(componentIdentity, queue, action) { - if (numberOfReRenders >= RE_RENDER_LIMIT) { - throw new Error( - "Too many re-renders. React limits the number of renders to prevent " + - "an infinite loop." - ); - } + function noop$1() {} - if (componentIdentity === currentlyRenderingComponent) { - // This is a render phase update. Stash it in a lazily-created map of - // queue -> linked list of updates. After this render pass, we'll restart - // and apply the stashed updates on top of the work-in-progress hook. - didScheduleRenderPhaseUpdate = true; - var update = { - action: action, - next: null - }; + var HooksDispatcher = { + readContext: readContext, + use: use, + useContext: useContext, + useMemo: useMemo, + useReducer: useReducer, + useRef: useRef, + useState: useState, + useInsertionEffect: noop$1, + useLayoutEffect: noop$1, + useCallback: useCallback, + // useImperativeHandle is not run in the server environment + useImperativeHandle: noop$1, + // Effects are not run in the server environment. + useEffect: noop$1, + // Debugging effect + useDebugValue: noop$1, + useDeferredValue: useDeferredValue, + useTransition: useTransition, + useId: useId, + // Subscriptions are not setup in a server environment. + useSyncExternalStore: useSyncExternalStore + }; - if (renderPhaseUpdates === null) { - renderPhaseUpdates = new Map(); - } + { + HooksDispatcher.useCacheRefresh = useCacheRefresh; + } - var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); + { + HooksDispatcher.useEffectEvent = useEffectEvent; + } - if (firstRenderPhaseUpdate === undefined) { - // $FlowFixMe[incompatible-use] found when upgrading Flow - renderPhaseUpdates.set(queue, update); - } else { - // Append the update to the end of the list. - var lastRenderPhaseUpdate = firstRenderPhaseUpdate; + { + HooksDispatcher.useMemoCache = useMemoCache; + } - while (lastRenderPhaseUpdate.next !== null) { - lastRenderPhaseUpdate = lastRenderPhaseUpdate.next; - } + { + HooksDispatcher.useHostTransitionStatus = useHostTransitionStatus; + } - lastRenderPhaseUpdate.next = update; - } - } + { + HooksDispatcher.useOptimistic = useOptimistic; + HooksDispatcher.useFormState = useFormState; } - function useCallback(callback, deps) { - return useMemo(function () { - return callback; - }, deps); + var currentResumableState = null; + function setCurrentResumableState(resumableState) { + currentResumableState = resumableState; } - function throwOnUseEffectEventCall() { - throw new Error( - "A function wrapped in useEffectEvent can't be called during rendering." - ); + function getCacheSignal() { + throw new Error("Not implemented."); } - function useEffectEvent(callback) { - // $FlowIgnore[incompatible-return] - return throwOnUseEffectEventCall; + function getCacheForType(resourceType) { + throw new Error("Not implemented."); } - function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { - if (getServerSnapshot === undefined) { - throw new Error( - "Missing getServerSnapshot, which is required for " + - "server-rendered content. Will revert to client rendering." - ); - } + var DefaultCacheDispatcher = { + getCacheSignal: getCacheSignal, + getCacheForType: getCacheForType + }; - return getServerSnapshot(); - } + // Helpers to patch console.logs to avoid logging during side-effect free + // replaying on render function. This currently only patches the object + // lazily which won't cover if the log function was extracted eagerly. + // We could also eagerly patch the method. + var disabledDepth = 0; + var prevLog; + var prevInfo; + var prevWarn; + var prevError; + var prevGroup; + var prevGroupCollapsed; + var prevGroupEnd; - function useDeferredValue(value, initialValue) { - resolveCurrentlyRenderingComponent(); + function disabledLog() {} + + disabledLog.__reactDisabledLog = true; + function disableLogs() { + { + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 + + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; // $FlowFixMe[cannot-write] Flow thinks console is immutable. + + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + /* eslint-enable react-internal/no-production-logging */ + } - if (enableUseDeferredValueInitialArg) { - return initialValue !== undefined ? initialValue : value; - } else { - return value; + disabledDepth++; } } + function reenableLogs() { + { + disabledDepth--; - function unsupportedStartTransition() { - throw new Error( - "startTransition cannot be called during server rendering." - ); - } - - function useTransition() { - resolveCurrentlyRenderingComponent(); - return [false, unsupportedStartTransition]; - } - - function useHostTransitionStatus() { - resolveCurrentlyRenderingComponent(); - return NotPendingTransition; - } + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + var props = { + configurable: true, + enumerable: true, + writable: true + }; // $FlowFixMe[cannot-write] Flow thinks console is immutable. - function unsupportedSetOptimisticState() { - throw new Error("Cannot update optimistic state while rendering."); - } + Object.defineProperties(console, { + log: assign({}, props, { + value: prevLog + }), + info: assign({}, props, { + value: prevInfo + }), + warn: assign({}, props, { + value: prevWarn + }), + error: assign({}, props, { + value: prevError + }), + group: assign({}, props, { + value: prevGroup + }), + groupCollapsed: assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: assign({}, props, { + value: prevGroupEnd + }) + }); + /* eslint-enable react-internal/no-production-logging */ + } - function useOptimistic(passthrough, reducer) { - resolveCurrentlyRenderingComponent(); - return [passthrough, unsupportedSetOptimisticState]; + if (disabledDepth < 0) { + error( + "disabledDepth fell below zero. " + + "This is a bug in React. Please file an issue." + ); + } + } } - function createPostbackFormStateKey( - permalink, - componentKeyPath, - hookIndex - ) { - if (permalink !== undefined) { - // Don't bother to hash a permalink-based key since it's already short. - return "p" + permalink; - } else { - // Append a node to the key path that represents the form state hook. - var keyPath = [componentKeyPath, null, hookIndex]; // Key paths are hashed to reduce the size. It does not need to be secure, - // and it's more important that it's fast than that it's completely - // collision-free. + var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; + var prefix; + function describeBuiltInComponentFrame(name, ownerFn) { + { + if (prefix === undefined) { + // Extract the VM specific prefix used by each line. + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = (match && match[1]) || ""; + } + } // We use the prefix to ensure our stacks line up with native stack frames. - var keyPathHash = createFastHashJS(JSON.stringify(keyPath)); - return "k" + keyPathHash; + return "\n" + prefix + name; } } + var reentry = false; + var componentFrameCache; - function useFormState(action, initialState, permalink) { - resolveCurrentlyRenderingComponent(); // Count the number of useFormState hooks per component. We also use this to - // track the position of this useFormState hook relative to the other ones in - // this component, so we can generate a unique key for each one. + { + var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); + } + /** + * Leverages native browser/VM stack frames to get proper details (e.g. + * filename, line + col number) for a single component in a component stack. We + * do this by: + * (1) throwing and catching an error in the function - this will be our + * control error. + * (2) calling the component which will eventually throw an error that we'll + * catch - this will be our sample error. + * (3) diffing the control and sample error stacks to find the stack frame + * which represents our component. + */ - var formStateHookIndex = formStateCounter++; - var request = currentlyRenderingRequest; // $FlowIgnore[prop-missing] + function describeNativeComponentFrame(fn, construct) { + // If something asked for a stack inside a fake render, it should get ignored. + if (!fn || reentry) { + return ""; + } - var formAction = action.$$FORM_ACTION; + { + var frame = componentFrameCache.get(fn); - if (typeof formAction === "function") { - // This is a server action. These have additional features to enable - // MPA-style form submissions with progressive enhancement. - // TODO: If the same permalink is passed to multiple useFormStates, and - // they all have the same action signature, Fizz will pass the postback - // state to all of them. We should probably only pass it to the first one, - // and/or warn. - // The key is lazily generated and deduped so the that the keypath doesn't - // get JSON.stringify-ed unnecessarily, and at most once. - var nextPostbackStateKey = null; // Determine the current form state. If we received state during an MPA form - // submission, then we will reuse that, if the action identity matches. - // Otherwise we'll use the initial state argument. We will emit a comment - // marker into the stream that indicates whether the state was reused. + if (frame !== undefined) { + return frame; + } + } - var state = initialState; - var componentKeyPath = currentlyRenderingKeyPath; - var postbackFormState = getFormState(request); // $FlowIgnore[prop-missing] + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe[incompatible-type] It does accept undefined. - var isSignatureEqual = action.$$IS_SIGNATURE_EQUAL; + Error.prepareStackTrace = undefined; + var previousDispatcher; - if ( - postbackFormState !== null && - typeof isSignatureEqual === "function" - ) { - var postbackKey = postbackFormState[1]; - var postbackReferenceId = postbackFormState[2]; - var postbackBoundArity = postbackFormState[3]; + { + previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function + // for warnings. - if ( - isSignatureEqual.call( - action, - postbackReferenceId, - postbackBoundArity - ) - ) { - nextPostbackStateKey = createPostbackFormStateKey( - permalink, - componentKeyPath, - formStateHookIndex - ); + ReactCurrentDispatcher$1.current = null; + disableLogs(); + } + /** + * Finding a common stack frame between sample and control errors can be + * tricky given the different types and levels of stack trace truncation from + * different JS VMs. So instead we'll attempt to control what that common + * frame should be through this object method: + * Having both the sample and control errors be in the function under the + * `DescribeNativeComponentFrameRoot` property, + setting the `name` and + * `displayName` properties of the function ensures that a stack + * frame exists that has the method name `DescribeNativeComponentFrameRoot` in + * it for both control and sample stacks. + */ - if (postbackKey === nextPostbackStateKey) { - // This was a match - formStateMatchingIndex = formStateHookIndex; // Reuse the state that was submitted by the form. + var RunInRootFrame = { + DetermineComponentFrameRoot: function () { + var control; - state = postbackFormState[0]; - } - } - } // Bind the state to the first argument of the action. + try { + // This should throw. + if (construct) { + // Something should be setting the props in the constructor. + var Fake = function () { + throw Error(); + }; // $FlowFixMe[prop-missing] - var boundAction = action.bind(null, state); // Wrap the action so the return value is void. + Object.defineProperty(Fake.prototype, "props", { + set: function () { + // We use a throwing setter instead of frozen or non-writable props + // because that won't throw in a non-strict mode function. + throw Error(); + } + }); - var dispatch = function (payload) { - boundAction(payload); - }; // $FlowIgnore[prop-missing] + if (typeof Reflect === "object" && Reflect.construct) { + // We construct a different control for this case to include any extra + // frames added by the construct call. + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } - if (typeof boundAction.$$FORM_ACTION === "function") { - // $FlowIgnore[prop-missing] - dispatch.$$FORM_ACTION = function (prefix) { - var metadata = boundAction.$$FORM_ACTION(prefix); // Override the action URL + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } // $FlowFixMe[prop-missing] found when upgrading Flow - if (permalink !== undefined) { - { - checkAttributeStringCoercion(permalink, "target"); + fn.call(Fake.prototype); } + } else { + try { + throw Error(); + } catch (x) { + control = x; + } // TODO(luna): This will currently only throw if the function component + // tries to access React/ReactDOM/props. We should probably make this throw + // in simple components too - permalink += ""; - metadata.action = permalink; - } - - var formData = metadata.data; + var maybePromise = fn(); // If the function component returns a promise, it's likely an async + // component, which we don't yet support. Attach a noop catch handler to + // silence the error. + // TODO: Implement component stacks for async client components? - if (formData) { - if (nextPostbackStateKey === null) { - nextPostbackStateKey = createPostbackFormStateKey( - permalink, - componentKeyPath, - formStateHookIndex - ); + if (maybePromise && typeof maybePromise.catch === "function") { + maybePromise.catch(function () {}); } - - formData.append("$ACTION_KEY", nextPostbackStateKey); } + } catch (sample) { + // This is inlined manually because closure doesn't do it for us. + if (sample && control && typeof sample.stack === "string") { + return [sample.stack, control.stack]; + } + } - return metadata; - }; + return [null, null]; } + }; // $FlowFixMe[prop-missing] - return [state, dispatch]; - } else { - // This is not a server action, so the implementation is much simpler. - // Bind the state to the first argument of the action. - var _boundAction = action.bind(null, initialState); // Wrap the action so the return value is void. - - var _dispatch2 = function (payload) { - _boundAction(payload); - }; - - return [initialState, _dispatch2]; - } - } - - function useId() { - var task = currentlyRenderingTask; - var treeId = getTreeId(task.treeContext); - var resumableState = currentResumableState; + RunInRootFrame.DetermineComponentFrameRoot.displayName = + "DetermineComponentFrameRoot"; + var namePropDescriptor = Object.getOwnPropertyDescriptor( + RunInRootFrame.DetermineComponentFrameRoot, + "name" + ); // Before ES6, the `name` property was not configurable. - if (resumableState === null) { - throw new Error( - "Invalid hook call. Hooks can only be called inside of the body of a function component." + if (namePropDescriptor && namePropDescriptor.configurable) { + // V8 utilizes a function's `name` property when generating a stack trace. + Object.defineProperty( + RunInRootFrame.DetermineComponentFrameRoot, // Configurable properties can be updated even if its writable descriptor + // is set to `false`. + // $FlowFixMe[cannot-write] + "name", + { + value: "DetermineComponentFrameRoot" + } ); } - var localId = localIdCounter++; - return makeId(resumableState, treeId, localId); - } - - function use(usable) { - if (usable !== null && typeof usable === "object") { - // $FlowFixMe[method-unbinding] - if (typeof usable.then === "function") { - // This is a thenable. - var thenable = usable; - return unwrapThenable(thenable); - } else if (usable.$$typeof === REACT_CONTEXT_TYPE) { - var context = usable; - return readContext(context); - } - } // eslint-disable-next-line react-internal/safe-string-coercion - - throw new Error( - "An unsupported type was passed to use(): " + String(usable) - ); - } + try { + var _RunInRootFrame$Deter = + RunInRootFrame.DetermineComponentFrameRoot(), + sampleStack = _RunInRootFrame$Deter[0], + controlStack = _RunInRootFrame$Deter[1]; - function unwrapThenable(thenable) { - var index = thenableIndexCounter; - thenableIndexCounter += 1; + if (sampleStack && controlStack) { + // This extracts the first frame from the sample that isn't also in the control. + // Skipping one frame that we assume is the frame that calls the two. + var sampleLines = sampleStack.split("\n"); + var controlLines = controlStack.split("\n"); + var s = 0; + var c = 0; - if (thenableState === null) { - thenableState = createThenableState(); - } + while ( + s < sampleLines.length && + !sampleLines[s].includes("DetermineComponentFrameRoot") + ) { + s++; + } - return trackUsedThenable(thenableState, thenable, index); - } + while ( + c < controlLines.length && + !controlLines[c].includes("DetermineComponentFrameRoot") + ) { + c++; + } // We couldn't find our intentionally injected common root frame, attempt + // to find another common root frame by search from the bottom of the + // control stack... - function unsupportedRefresh() { - throw new Error("Cache cannot be refreshed during server rendering."); - } + if (s === sampleLines.length || c === controlLines.length) { + s = sampleLines.length - 1; + c = controlLines.length - 1; - function useCacheRefresh() { - return unsupportedRefresh; - } + while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { + // We expect at least one stack frame to be shared. + // Typically this will be the root most one. However, stack frames may be + // cut off due to maximum stack limits. In this case, one maybe cut off + // earlier than the other. We assume that the sample is longer or the same + // and there for cut off earlier. So we should find the root most frame in + // the sample somewhere in the control. + c--; + } + } - function useMemoCache(size) { - var data = new Array(size); + for (; s >= 1 && c >= 0; s--, c--) { + // Next we find the first one that isn't the same which should be the + // frame that called our sample function and the control. + if (sampleLines[s] !== controlLines[c]) { + // In V8, the first line is describing the message but other VMs don't. + // If we're about to return the first line, and the control is also on the same + // line, that's a pretty good indicator that our sample threw at same line as + // the control. I.e. before we entered the sample frame. So we ignore this result. + // This can happen if you passed a class to function component, or non-function. + if (s !== 1 || c !== 1) { + do { + s--; + c--; // We may still have similar intermediate frames from the construct call. + // The next one that isn't the same should be our match though. - for (var i = 0; i < size; i++) { - data[i] = REACT_MEMO_CACHE_SENTINEL; - } + if (c < 0 || sampleLines[s] !== controlLines[c]) { + // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. + var _frame = + "\n" + sampleLines[s].replace(" at new ", " at "); // If our component frame is labeled "" + // but we have a user-provided "displayName" + // splice it in to make the stack more readable. - return data; - } + if (fn.displayName && _frame.includes("")) { + _frame = _frame.replace("", fn.displayName); + } - function noop$1() {} + if (true) { + if (typeof fn === "function") { + componentFrameCache.set(fn, _frame); + } + } // Return the line we found. - var HooksDispatcher = { - readContext: readContext, - use: use, - useContext: useContext, - useMemo: useMemo, - useReducer: useReducer, - useRef: useRef, - useState: useState, - useInsertionEffect: noop$1, - useLayoutEffect: noop$1, - useCallback: useCallback, - // useImperativeHandle is not run in the server environment - useImperativeHandle: noop$1, - // Effects are not run in the server environment. - useEffect: noop$1, - // Debugging effect - useDebugValue: noop$1, - useDeferredValue: useDeferredValue, - useTransition: useTransition, - useId: useId, - // Subscriptions are not setup in a server environment. - useSyncExternalStore: useSyncExternalStore - }; + return _frame; + } + } while (s >= 1 && c >= 0); + } - { - HooksDispatcher.useCacheRefresh = useCacheRefresh; - } + break; + } + } + } + } finally { + reentry = false; - { - HooksDispatcher.useEffectEvent = useEffectEvent; - } + { + ReactCurrentDispatcher$1.current = previousDispatcher; + reenableLogs(); + } - { - HooksDispatcher.useMemoCache = useMemoCache; - } + Error.prepareStackTrace = previousPrepareStackTrace; + } // Fallback to just using the name if we couldn't make it throw. - { - HooksDispatcher.useHostTransitionStatus = useHostTransitionStatus; - } + var name = fn ? fn.displayName || fn.name : ""; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; - { - HooksDispatcher.useOptimistic = useOptimistic; - HooksDispatcher.useFormState = useFormState; - } + { + if (typeof fn === "function") { + componentFrameCache.set(fn, syntheticFrame); + } + } - var currentResumableState = null; - function setCurrentResumableState(resumableState) { - currentResumableState = resumableState; + return syntheticFrame; } - function getCacheSignal() { - throw new Error("Not implemented."); + function describeClassComponentFrame(ctor, ownerFn) { + { + return describeNativeComponentFrame(ctor, true); + } } - - function getCacheForType(resourceType) { - throw new Error("Not implemented."); + function describeFunctionComponentFrame(fn, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } } - var DefaultCacheDispatcher = { - getCacheSignal: getCacheSignal, - getCacheForType: getCacheForType - }; - function getStackByComponentStackNode(componentStack) { try { var info = ""; diff --git a/compiled/facebook-www/ReactDOMServer-dev.modern.js b/compiled/facebook-www/ReactDOMServer-dev.modern.js index a750cadb4e8ef..0fef6195f9158 100644 --- a/compiled/facebook-www/ReactDOMServer-dev.modern.js +++ b/compiled/facebook-www/ReactDOMServer-dev.modern.js @@ -19,7 +19,7 @@ if (__DEV__) { var React = require("react"); var ReactDOM = require("react-dom"); - var ReactVersion = "18.3.0-www-modern-40548e7e"; + var ReactVersion = "18.3.0-www-modern-ba9c385a"; // This refers to a WWW module. var warningWWW = require("warning"); @@ -8592,2366 +8592,2366 @@ if (__DEV__) { return null; } - // Helpers to patch console.logs to avoid logging during side-effect free - // replaying on render function. This currently only patches the object - // lazily which won't cover if the log function was extracted eagerly. - // We could also eagerly patch the method. - var disabledDepth = 0; - var prevLog; - var prevInfo; - var prevWarn; - var prevError; - var prevGroup; - var prevGroupCollapsed; - var prevGroupEnd; + var emptyContextObject = {}; - function disabledLog() {} + { + Object.freeze(emptyContextObject); + } - disabledLog.__reactDisabledLog = true; - function disableLogs() { - { - if (disabledDepth === 0) { - /* eslint-disable react-internal/no-production-logging */ - prevLog = console.log; - prevInfo = console.info; - prevWarn = console.warn; - prevError = console.error; - prevGroup = console.group; - prevGroupCollapsed = console.groupCollapsed; - prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 + var rendererSigil; - var props = { - configurable: true, - enumerable: true, - value: disabledLog, - writable: true - }; // $FlowFixMe[cannot-write] Flow thinks console is immutable. + { + // Use this to detect multiple renderers using the same context + rendererSigil = {}; + } // Used to store the parent path of all context overrides in a shared linked list. + // Forming a reverse tree. + // The structure of a context snapshot is an implementation of this file. + // Currently, it's implemented as tracking the current active node. - Object.defineProperties(console, { - info: props, - log: props, - warn: props, - error: props, - group: props, - groupCollapsed: props, - groupEnd: props - }); - /* eslint-enable react-internal/no-production-logging */ - } + var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances. + // This global (actually thread local) state represents what state all those "current", + // fields are currently in. - disabledDepth++; + var currentActiveSnapshot = null; + + function popNode(prev) { + { + prev.context._currentValue2 = prev.parentValue; } } - function reenableLogs() { + + function pushNode(next) { { - disabledDepth--; + next.context._currentValue2 = next.value; + } + } - if (disabledDepth === 0) { - /* eslint-disable react-internal/no-production-logging */ - var props = { - configurable: true, - enumerable: true, - writable: true - }; // $FlowFixMe[cannot-write] Flow thinks console is immutable. + function popToNearestCommonAncestor(prev, next) { + if (prev === next); + else { + popNode(prev); + var parentPrev = prev.parent; + var parentNext = next.parent; - Object.defineProperties(console, { - log: assign({}, props, { - value: prevLog - }), - info: assign({}, props, { - value: prevInfo - }), - warn: assign({}, props, { - value: prevWarn - }), - error: assign({}, props, { - value: prevError - }), - group: assign({}, props, { - value: prevGroup - }), - groupCollapsed: assign({}, props, { - value: prevGroupCollapsed - }), - groupEnd: assign({}, props, { - value: prevGroupEnd - }) - }); - /* eslint-enable react-internal/no-production-logging */ - } + if (parentPrev === null) { + if (parentNext !== null) { + throw new Error( + "The stacks must reach the root at the same time. This is a bug in React." + ); + } + } else { + if (parentNext === null) { + throw new Error( + "The stacks must reach the root at the same time. This is a bug in React." + ); + } - if (disabledDepth < 0) { - error( - "disabledDepth fell below zero. " + - "This is a bug in React. Please file an issue." - ); - } + popToNearestCommonAncestor(parentPrev, parentNext); + } // On the way back, we push the new ones that weren't common. + + pushNode(next); } } - var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; - var prefix; - function describeBuiltInComponentFrame(name, ownerFn) { - { - if (prefix === undefined) { - // Extract the VM specific prefix used by each line. - try { - throw Error(); - } catch (x) { - var match = x.stack.trim().match(/\n( *(at )?)/); - prefix = (match && match[1]) || ""; - } - } // We use the prefix to ensure our stacks line up with native stack frames. + function popAllPrevious(prev) { + popNode(prev); + var parentPrev = prev.parent; - return "\n" + prefix + name; + if (parentPrev !== null) { + popAllPrevious(parentPrev); } } - var reentry = false; - var componentFrameCache; - { - var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; - componentFrameCache = new PossiblyWeakMap(); - } - /** - * Leverages native browser/VM stack frames to get proper details (e.g. - * filename, line + col number) for a single component in a component stack. We - * do this by: - * (1) throwing and catching an error in the function - this will be our - * control error. - * (2) calling the component which will eventually throw an error that we'll - * catch - this will be our sample error. - * (3) diffing the control and sample error stacks to find the stack frame - * which represents our component. - */ + function pushAllNext(next) { + var parentNext = next.parent; - function describeNativeComponentFrame(fn, construct) { - // If something asked for a stack inside a fake render, it should get ignored. - if (!fn || reentry) { - return ""; + if (parentNext !== null) { + pushAllNext(parentNext); } - { - var frame = componentFrameCache.get(fn); + pushNode(next); + } - if (frame !== undefined) { - return frame; - } + function popPreviousToCommonLevel(prev, next) { + popNode(prev); + var parentPrev = prev.parent; + + if (parentPrev === null) { + throw new Error( + "The depth must equal at least at zero before reaching the root. This is a bug in React." + ); } - reentry = true; - var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe[incompatible-type] It does accept undefined. + if (parentPrev.depth === next.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(parentPrev, next); + } else { + // We must still be deeper. + popPreviousToCommonLevel(parentPrev, next); + } + } - Error.prepareStackTrace = undefined; - var previousDispatcher; + function popNextToCommonLevel(prev, next) { + var parentNext = next.parent; - { - previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function - // for warnings. + if (parentNext === null) { + throw new Error( + "The depth must equal at least at zero before reaching the root. This is a bug in React." + ); + } - ReactCurrentDispatcher$1.current = null; - disableLogs(); + if (prev.depth === parentNext.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(prev, parentNext); + } else { + // We must still be deeper. + popNextToCommonLevel(prev, parentNext); } - /** - * Finding a common stack frame between sample and control errors can be - * tricky given the different types and levels of stack trace truncation from - * different JS VMs. So instead we'll attempt to control what that common - * frame should be through this object method: - * Having both the sample and control errors be in the function under the - * `DescribeNativeComponentFrameRoot` property, + setting the `name` and - * `displayName` properties of the function ensures that a stack - * frame exists that has the method name `DescribeNativeComponentFrameRoot` in - * it for both control and sample stacks. - */ - var RunInRootFrame = { - DetermineComponentFrameRoot: function () { - var control; + pushNode(next); + } // Perform context switching to the new snapshot. + // To make it cheap to read many contexts, while not suspending, we make the switch eagerly by + // updating all the context's current values. That way reads, always just read the current value. + // At the cost of updating contexts even if they're never read by this subtree. - try { - // This should throw. - if (construct) { - // Something should be setting the props in the constructor. - var Fake = function () { - throw Error(); - }; // $FlowFixMe[prop-missing] + function switchContext(newSnapshot) { + // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack. + // We also need to update any new contexts that are now on the stack with the deepest value. + // The easiest way to update new contexts is to just reapply them in reverse order from the + // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack + // for that. Therefore this algorithm is recursive. + // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go. + // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go. + // 3) Then we reapply new contexts on the way back up the stack. + var prev = currentActiveSnapshot; + var next = newSnapshot; - Object.defineProperty(Fake.prototype, "props", { - set: function () { - // We use a throwing setter instead of frozen or non-writable props - // because that won't throw in a non-strict mode function. - throw Error(); - } - }); - - if (typeof Reflect === "object" && Reflect.construct) { - // We construct a different control for this case to include any extra - // frames added by the construct call. - try { - Reflect.construct(Fake, []); - } catch (x) { - control = x; - } - - Reflect.construct(fn, [], Fake); - } else { - try { - Fake.call(); - } catch (x) { - control = x; - } // $FlowFixMe[prop-missing] found when upgrading Flow + if (prev !== next) { + if (prev === null) { + // $FlowFixMe[incompatible-call]: This has to be non-null since it's not equal to prev. + pushAllNext(next); + } else if (next === null) { + popAllPrevious(prev); + } else if (prev.depth === next.depth) { + popToNearestCommonAncestor(prev, next); + } else if (prev.depth > next.depth) { + popPreviousToCommonLevel(prev, next); + } else { + popNextToCommonLevel(prev, next); + } - fn.call(Fake.prototype); - } - } else { - try { - throw Error(); - } catch (x) { - control = x; - } // TODO(luna): This will currently only throw if the function component - // tries to access React/ReactDOM/props. We should probably make this throw - // in simple components too + currentActiveSnapshot = next; + } + } + function pushProvider(context, nextValue) { + var prevValue; - var maybePromise = fn(); // If the function component returns a promise, it's likely an async - // component, which we don't yet support. Attach a noop catch handler to - // silence the error. - // TODO: Implement component stacks for async client components? + { + prevValue = context._currentValue2; + context._currentValue2 = nextValue; - if (maybePromise && typeof maybePromise.catch === "function") { - maybePromise.catch(function () {}); - } - } - } catch (sample) { - // This is inlined manually because closure doesn't do it for us. - if (sample && control && typeof sample.stack === "string") { - return [sample.stack, control.stack]; - } + { + if ( + context._currentRenderer2 !== undefined && + context._currentRenderer2 !== null && + context._currentRenderer2 !== rendererSigil + ) { + error( + "Detected multiple renderers concurrently rendering the " + + "same context provider. This is currently unsupported." + ); } - return [null, null]; + context._currentRenderer2 = rendererSigil; } - }; // $FlowFixMe[prop-missing] + } - RunInRootFrame.DetermineComponentFrameRoot.displayName = - "DetermineComponentFrameRoot"; - var namePropDescriptor = Object.getOwnPropertyDescriptor( - RunInRootFrame.DetermineComponentFrameRoot, - "name" - ); // Before ES6, the `name` property was not configurable. + var prevNode = currentActiveSnapshot; + var newNode = { + parent: prevNode, + depth: prevNode === null ? 0 : prevNode.depth + 1, + context: context, + parentValue: prevValue, + value: nextValue + }; + currentActiveSnapshot = newNode; + return newNode; + } + function popProvider(context) { + var prevSnapshot = currentActiveSnapshot; - if (namePropDescriptor && namePropDescriptor.configurable) { - // V8 utilizes a function's `name` property when generating a stack trace. - Object.defineProperty( - RunInRootFrame.DetermineComponentFrameRoot, // Configurable properties can be updated even if its writable descriptor - // is set to `false`. - // $FlowFixMe[cannot-write] - "name", - { - value: "DetermineComponentFrameRoot" - } + if (prevSnapshot === null) { + throw new Error( + "Tried to pop a Context at the root of the app. This is a bug in React." ); } - try { - var _RunInRootFrame$Deter = - RunInRootFrame.DetermineComponentFrameRoot(), - sampleStack = _RunInRootFrame$Deter[0], - controlStack = _RunInRootFrame$Deter[1]; + { + if (prevSnapshot.context !== context) { + error( + "The parent context is not the expected context. This is probably a bug in React." + ); + } + } - if (sampleStack && controlStack) { - // This extracts the first frame from the sample that isn't also in the control. - // Skipping one frame that we assume is the frame that calls the two. - var sampleLines = sampleStack.split("\n"); - var controlLines = controlStack.split("\n"); - var s = 0; - var c = 0; + { + var _value = prevSnapshot.parentValue; + prevSnapshot.context._currentValue2 = _value; - while ( - s < sampleLines.length && - !sampleLines[s].includes("DetermineComponentFrameRoot") + { + if ( + context._currentRenderer2 !== undefined && + context._currentRenderer2 !== null && + context._currentRenderer2 !== rendererSigil ) { - s++; + error( + "Detected multiple renderers concurrently rendering the " + + "same context provider. This is currently unsupported." + ); } - while ( - c < controlLines.length && - !controlLines[c].includes("DetermineComponentFrameRoot") - ) { - c++; - } // We couldn't find our intentionally injected common root frame, attempt - // to find another common root frame by search from the bottom of the - // control stack... + context._currentRenderer2 = rendererSigil; + } + } - if (s === sampleLines.length || c === controlLines.length) { - s = sampleLines.length - 1; - c = controlLines.length - 1; + return (currentActiveSnapshot = prevSnapshot.parent); + } + function getActiveContext() { + return currentActiveSnapshot; + } + function readContext$1(context) { + var value = context._currentValue2; + return value; + } - while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { - // We expect at least one stack frame to be shared. - // Typically this will be the root most one. However, stack frames may be - // cut off due to maximum stack limits. In this case, one maybe cut off - // earlier than the other. We assume that the sample is longer or the same - // and there for cut off earlier. So we should find the root most frame in - // the sample somewhere in the control. - c--; - } - } + /** + * `ReactInstanceMap` maintains a mapping from a public facing stateful + * instance (key) and the internal representation (value). This allows public + * methods to accept the user facing instance as an argument and map them back + * to internal methods. + * + * Note that this module is currently shared and assumed to be stateless. + * If this becomes an actual Map, that will break. + */ + function get(key) { + return key._reactInternals; + } + function set(key, value) { + key._reactInternals = value; + } - for (; s >= 1 && c >= 0; s--, c--) { - // Next we find the first one that isn't the same which should be the - // frame that called our sample function and the control. - if (sampleLines[s] !== controlLines[c]) { - // In V8, the first line is describing the message but other VMs don't. - // If we're about to return the first line, and the control is also on the same - // line, that's a pretty good indicator that our sample threw at same line as - // the control. I.e. before we entered the sample frame. So we ignore this result. - // This can happen if you passed a class to function component, or non-function. - if (s !== 1 || c !== 1) { - do { - s--; - c--; // We may still have similar intermediate frames from the construct call. - // The next one that isn't the same should be our match though. + var didWarnAboutNoopUpdateForComponent = {}; + var didWarnAboutDeprecatedWillMount = {}; + var didWarnAboutUninitializedState; + var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; + var didWarnAboutLegacyLifecyclesAndDerivedState; + var didWarnAboutUndefinedDerivedState; + var didWarnAboutDirectlyAssigningPropsToState; + var didWarnAboutInvalidateContextType; + var didWarnOnInvalidCallback; - if (c < 0 || sampleLines[s] !== controlLines[c]) { - // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. - var _frame = - "\n" + sampleLines[s].replace(" at new ", " at "); // If our component frame is labeled "" - // but we have a user-provided "displayName" - // splice it in to make the stack more readable. + { + didWarnAboutUninitializedState = new Set(); + didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set(); + didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); + didWarnAboutDirectlyAssigningPropsToState = new Set(); + didWarnAboutUndefinedDerivedState = new Set(); + didWarnAboutInvalidateContextType = new Set(); + didWarnOnInvalidCallback = new Set(); + } - if (fn.displayName && _frame.includes("")) { - _frame = _frame.replace("", fn.displayName); - } + function warnOnInvalidCallback(callback, callerName) { + { + if (callback === null || typeof callback === "function") { + return; + } - if (true) { - if (typeof fn === "function") { - componentFrameCache.set(fn, _frame); - } - } // Return the line we found. + var key = callerName + "_" + callback; - return _frame; - } - } while (s >= 1 && c >= 0); - } + if (!didWarnOnInvalidCallback.has(key)) { + didWarnOnInvalidCallback.add(key); - break; - } - } - } - } finally { - reentry = false; - - { - ReactCurrentDispatcher$1.current = previousDispatcher; - reenableLogs(); - } - - Error.prepareStackTrace = previousPrepareStackTrace; - } // Fallback to just using the name if we couldn't make it throw. - - var name = fn ? fn.displayName || fn.name : ""; - var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; - - { - if (typeof fn === "function") { - componentFrameCache.set(fn, syntheticFrame); + error( + "%s(...): Expected the last optional `callback` argument to be a " + + "function. Instead received: %s.", + callerName, + callback + ); } } - - return syntheticFrame; } - function describeClassComponentFrame(ctor, ownerFn) { - { - return describeNativeComponentFrame(ctor, true); - } - } - function describeFunctionComponentFrame(fn, ownerFn) { + function warnOnUndefinedDerivedState(type, partialState) { { - return describeNativeComponentFrame(fn, false); - } - } + if (partialState === undefined) { + var componentName = getComponentNameFromType(type) || "Component"; - var emptyContextObject = {}; + if (!didWarnAboutUndefinedDerivedState.has(componentName)) { + didWarnAboutUndefinedDerivedState.add(componentName); - { - Object.freeze(emptyContextObject); + error( + "%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. " + + "You have returned undefined.", + componentName + ); + } + } + } } - var rendererSigil; - - { - // Use this to detect multiple renderers using the same context - rendererSigil = {}; - } // Used to store the parent path of all context overrides in a shared linked list. - // Forming a reverse tree. - // The structure of a context snapshot is an implementation of this file. - // Currently, it's implemented as tracking the current active node. - - var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances. - // This global (actually thread local) state represents what state all those "current", - // fields are currently in. + function warnNoop(publicInstance, callerName) { + { + var _constructor = publicInstance.constructor; + var componentName = + (_constructor && getComponentNameFromType(_constructor)) || + "ReactClass"; + var warningKey = componentName + "." + callerName; - var currentActiveSnapshot = null; + if (didWarnAboutNoopUpdateForComponent[warningKey]) { + return; + } - function popNode(prev) { - { - prev.context._currentValue2 = prev.parentValue; - } - } + error( + "%s(...): Can only update a mounting component. " + + "This usually means you called %s() outside componentWillMount() on the server. " + + "This is a no-op.\n\nPlease check the code for the %s component.", + callerName, + callerName, + componentName + ); - function pushNode(next) { - { - next.context._currentValue2 = next.value; + didWarnAboutNoopUpdateForComponent[warningKey] = true; } } - function popToNearestCommonAncestor(prev, next) { - if (prev === next); - else { - popNode(prev); - var parentPrev = prev.parent; - var parentNext = next.parent; + var classComponentUpdater = { + isMounted: function (inst) { + return false; + }, + // $FlowFixMe[missing-local-annot] + enqueueSetState: function (inst, payload, callback) { + var internals = get(inst); - if (parentPrev === null) { - if (parentNext !== null) { - throw new Error( - "The stacks must reach the root at the same time. This is a bug in React." - ); - } + if (internals.queue === null) { + warnNoop(inst, "setState"); } else { - if (parentNext === null) { - throw new Error( - "The stacks must reach the root at the same time. This is a bug in React." - ); + internals.queue.push(payload); + + { + if (callback !== undefined && callback !== null) { + warnOnInvalidCallback(callback, "setState"); + } } + } + }, + enqueueReplaceState: function (inst, payload, callback) { + var internals = get(inst); + internals.replace = true; + internals.queue = [payload]; - popToNearestCommonAncestor(parentPrev, parentNext); - } // On the way back, we push the new ones that weren't common. + { + if (callback !== undefined && callback !== null) { + warnOnInvalidCallback(callback, "setState"); + } + } + }, + // $FlowFixMe[missing-local-annot] + enqueueForceUpdate: function (inst, callback) { + var internals = get(inst); - pushNode(next); + if (internals.queue === null) { + warnNoop(inst, "forceUpdate"); + } else { + { + if (callback !== undefined && callback !== null) { + warnOnInvalidCallback(callback, "setState"); + } + } + } } - } + }; - function popAllPrevious(prev) { - popNode(prev); - var parentPrev = prev.parent; + function applyDerivedStateFromProps( + instance, + ctor, + getDerivedStateFromProps, + prevState, + nextProps + ) { + var partialState = getDerivedStateFromProps(nextProps, prevState); - if (parentPrev !== null) { - popAllPrevious(parentPrev); - } + { + warnOnUndefinedDerivedState(ctor, partialState); + } // Merge the partial state and the previous state. + + var newState = + partialState === null || partialState === undefined + ? prevState + : assign({}, prevState, partialState); + return newState; } - function pushAllNext(next) { - var parentNext = next.parent; + function constructClassInstance(ctor, props, maskedLegacyContext) { + var context = emptyContextObject; + var contextType = ctor.contextType; - if (parentNext !== null) { - pushAllNext(parentNext); - } + { + if ("contextType" in ctor) { + var isValid = // Allow null for conditional declaration + contextType === null || + (contextType !== undefined && + contextType.$$typeof === REACT_CONTEXT_TYPE); - pushNode(next); - } + if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { + didWarnAboutInvalidateContextType.add(ctor); + var addendum = ""; - function popPreviousToCommonLevel(prev, next) { - popNode(prev); - var parentPrev = prev.parent; + if (contextType === undefined) { + addendum = + " However, it is set to undefined. " + + "This can be caused by a typo or by mixing up named and default imports. " + + "This can also happen due to a circular dependency, so " + + "try moving the createContext() call to a separate file."; + } else if (typeof contextType !== "object") { + addendum = " However, it is set to a " + typeof contextType + "."; + } else if (contextType.$$typeof === REACT_CONSUMER_TYPE) { + addendum = + " Did you accidentally pass the Context.Consumer instead?"; + } else { + addendum = + " However, it is set to an object with keys {" + + Object.keys(contextType).join(", ") + + "}."; + } - if (parentPrev === null) { - throw new Error( - "The depth must equal at least at zero before reaching the root. This is a bug in React." - ); + error( + "%s defines an invalid contextType. " + + "contextType should point to the Context object returned by React.createContext().%s", + getComponentNameFromType(ctor) || "Component", + addendum + ); + } + } } - if (parentPrev.depth === next.depth) { - // We found the same level. Now we just need to find a shared ancestor. - popToNearestCommonAncestor(parentPrev, next); - } else { - // We must still be deeper. - popPreviousToCommonLevel(parentPrev, next); + if (typeof contextType === "object" && contextType !== null) { + context = readContext$1(contextType); } - } - function popNextToCommonLevel(prev, next) { - var parentNext = next.parent; + var instance = new ctor(props, context); - if (parentNext === null) { - throw new Error( - "The depth must equal at least at zero before reaching the root. This is a bug in React." - ); - } + { + if ( + typeof ctor.getDerivedStateFromProps === "function" && + (instance.state === null || instance.state === undefined) + ) { + var componentName = getComponentNameFromType(ctor) || "Component"; - if (prev.depth === parentNext.depth) { - // We found the same level. Now we just need to find a shared ancestor. - popToNearestCommonAncestor(prev, parentNext); - } else { - // We must still be deeper. - popNextToCommonLevel(prev, parentNext); - } + if (!didWarnAboutUninitializedState.has(componentName)) { + didWarnAboutUninitializedState.add(componentName); - pushNode(next); - } // Perform context switching to the new snapshot. - // To make it cheap to read many contexts, while not suspending, we make the switch eagerly by - // updating all the context's current values. That way reads, always just read the current value. - // At the cost of updating contexts even if they're never read by this subtree. + error( + "`%s` uses `getDerivedStateFromProps` but its initial state is " + + "%s. This is not recommended. Instead, define the initial state by " + + "assigning an object to `this.state` in the constructor of `%s`. " + + "This ensures that `getDerivedStateFromProps` arguments have a consistent shape.", + componentName, + instance.state === null ? "null" : "undefined", + componentName + ); + } + } // If new component APIs are defined, "unsafe" lifecycles won't be called. + // Warn about these lifecycles if they are present. + // Don't warn about react-lifecycles-compat polyfilled methods though. - function switchContext(newSnapshot) { - // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack. - // We also need to update any new contexts that are now on the stack with the deepest value. - // The easiest way to update new contexts is to just reapply them in reverse order from the - // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack - // for that. Therefore this algorithm is recursive. - // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go. - // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go. - // 3) Then we reapply new contexts on the way back up the stack. - var prev = currentActiveSnapshot; - var next = newSnapshot; + if ( + typeof ctor.getDerivedStateFromProps === "function" || + typeof instance.getSnapshotBeforeUpdate === "function" + ) { + var foundWillMountName = null; + var foundWillReceivePropsName = null; + var foundWillUpdateName = null; - if (prev !== next) { - if (prev === null) { - // $FlowFixMe[incompatible-call]: This has to be non-null since it's not equal to prev. - pushAllNext(next); - } else if (next === null) { - popAllPrevious(prev); - } else if (prev.depth === next.depth) { - popToNearestCommonAncestor(prev, next); - } else if (prev.depth > next.depth) { - popPreviousToCommonLevel(prev, next); - } else { - popNextToCommonLevel(prev, next); - } + if ( + typeof instance.componentWillMount === "function" && + instance.componentWillMount.__suppressDeprecationWarning !== true + ) { + foundWillMountName = "componentWillMount"; + } else if (typeof instance.UNSAFE_componentWillMount === "function") { + foundWillMountName = "UNSAFE_componentWillMount"; + } - currentActiveSnapshot = next; + if ( + typeof instance.componentWillReceiveProps === "function" && + instance.componentWillReceiveProps.__suppressDeprecationWarning !== + true + ) { + foundWillReceivePropsName = "componentWillReceiveProps"; + } else if ( + typeof instance.UNSAFE_componentWillReceiveProps === "function" + ) { + foundWillReceivePropsName = "UNSAFE_componentWillReceiveProps"; + } + + if ( + typeof instance.componentWillUpdate === "function" && + instance.componentWillUpdate.__suppressDeprecationWarning !== true + ) { + foundWillUpdateName = "componentWillUpdate"; + } else if ( + typeof instance.UNSAFE_componentWillUpdate === "function" + ) { + foundWillUpdateName = "UNSAFE_componentWillUpdate"; + } + + if ( + foundWillMountName !== null || + foundWillReceivePropsName !== null || + foundWillUpdateName !== null + ) { + var _componentName = getComponentNameFromType(ctor) || "Component"; + + var newApiName = + typeof ctor.getDerivedStateFromProps === "function" + ? "getDerivedStateFromProps()" + : "getSnapshotBeforeUpdate()"; + + if ( + !didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName) + ) { + didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName); + + error( + "Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n" + + "%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n" + + "The above lifecycles should be removed. Learn more about this warning here:\n" + + "https://reactjs.org/link/unsafe-component-lifecycles", + _componentName, + newApiName, + foundWillMountName !== null ? "\n " + foundWillMountName : "", + foundWillReceivePropsName !== null + ? "\n " + foundWillReceivePropsName + : "", + foundWillUpdateName !== null ? "\n " + foundWillUpdateName : "" + ); + } + } + } } + + return instance; } - function pushProvider(context, nextValue) { - var prevValue; + function checkClassInstance(instance, ctor, newProps) { { - prevValue = context._currentValue2; - context._currentValue2 = nextValue; + var name = getComponentNameFromType(ctor) || "Component"; + var renderPresent = instance.render; - { - if ( - context._currentRenderer2 !== undefined && - context._currentRenderer2 !== null && - context._currentRenderer2 !== rendererSigil - ) { + if (!renderPresent) { + if (ctor.prototype && typeof ctor.prototype.render === "function") { error( - "Detected multiple renderers concurrently rendering the " + - "same context provider. This is currently unsupported." + "%s(...): No `render` method found on the returned component " + + "instance: did you accidentally return an object from the constructor?", + name + ); + } else { + error( + "%s(...): No `render` method found on the returned component " + + "instance: you may have forgotten to define `render`.", + name ); } - - context._currentRenderer2 = rendererSigil; } - } - var prevNode = currentActiveSnapshot; - var newNode = { - parent: prevNode, - depth: prevNode === null ? 0 : prevNode.depth + 1, - context: context, - parentValue: prevValue, - value: nextValue - }; - currentActiveSnapshot = newNode; - return newNode; - } - function popProvider(context) { - var prevSnapshot = currentActiveSnapshot; + if ( + instance.getInitialState && + !instance.getInitialState.isReactClassApproved && + !instance.state + ) { + error( + "getInitialState was defined on %s, a plain JavaScript class. " + + "This is only supported for classes created using React.createClass. " + + "Did you mean to define a state property instead?", + name + ); + } - if (prevSnapshot === null) { - throw new Error( - "Tried to pop a Context at the root of the app. This is a bug in React." - ); - } + if ( + instance.getDefaultProps && + !instance.getDefaultProps.isReactClassApproved + ) { + error( + "getDefaultProps was defined on %s, a plain JavaScript class. " + + "This is only supported for classes created using React.createClass. " + + "Use a static property to define defaultProps instead.", + name + ); + } - { - if (prevSnapshot.context !== context) { + if (instance.propTypes) { error( - "The parent context is not the expected context. This is probably a bug in React." + "propTypes was defined as an instance property on %s. Use a static " + + "property to define propTypes instead.", + name ); } - } - { - var _value = prevSnapshot.parentValue; - prevSnapshot.context._currentValue2 = _value; + if (instance.contextType) { + error( + "contextType was defined as an instance property on %s. Use a static " + + "property to define contextType instead.", + name + ); + } { - if ( - context._currentRenderer2 !== undefined && - context._currentRenderer2 !== null && - context._currentRenderer2 !== rendererSigil - ) { + if (ctor.childContextTypes) { error( - "Detected multiple renderers concurrently rendering the " + - "same context provider. This is currently unsupported." + "%s uses the legacy childContextTypes API which is no longer supported. " + + "Use React.createContext() instead.", + name ); } - context._currentRenderer2 = rendererSigil; + if (ctor.contextTypes) { + error( + "%s uses the legacy contextTypes API which is no longer supported. " + + "Use React.createContext() with static contextType instead.", + name + ); + } } - } - return (currentActiveSnapshot = prevSnapshot.parent); - } - function getActiveContext() { - return currentActiveSnapshot; - } - function readContext$1(context) { - var value = context._currentValue2; - return value; - } + if (typeof instance.componentShouldUpdate === "function") { + error( + "%s has a method called " + + "componentShouldUpdate(). Did you mean shouldComponentUpdate()? " + + "The name is phrased as a question because the function is " + + "expected to return a value.", + name + ); + } - /** - * `ReactInstanceMap` maintains a mapping from a public facing stateful - * instance (key) and the internal representation (value). This allows public - * methods to accept the user facing instance as an argument and map them back - * to internal methods. - * - * Note that this module is currently shared and assumed to be stateless. - * If this becomes an actual Map, that will break. - */ - function get(key) { - return key._reactInternals; - } - function set(key, value) { - key._reactInternals = value; - } + if ( + ctor.prototype && + ctor.prototype.isPureReactComponent && + typeof instance.shouldComponentUpdate !== "undefined" + ) { + error( + "%s has a method called shouldComponentUpdate(). " + + "shouldComponentUpdate should not be used when extending React.PureComponent. " + + "Please extend React.Component if shouldComponentUpdate is used.", + getComponentNameFromType(ctor) || "A pure component" + ); + } - var didWarnAboutNoopUpdateForComponent = {}; - var didWarnAboutDeprecatedWillMount = {}; - var didWarnAboutUninitializedState; - var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; - var didWarnAboutLegacyLifecyclesAndDerivedState; - var didWarnAboutUndefinedDerivedState; - var didWarnAboutDirectlyAssigningPropsToState; - var didWarnAboutInvalidateContextType; - var didWarnOnInvalidCallback; + if (typeof instance.componentDidUnmount === "function") { + error( + "%s has a method called " + + "componentDidUnmount(). But there is no such lifecycle method. " + + "Did you mean componentWillUnmount()?", + name + ); + } - { - didWarnAboutUninitializedState = new Set(); - didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set(); - didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); - didWarnAboutDirectlyAssigningPropsToState = new Set(); - didWarnAboutUndefinedDerivedState = new Set(); - didWarnAboutInvalidateContextType = new Set(); - didWarnOnInvalidCallback = new Set(); - } + if (typeof instance.componentDidReceiveProps === "function") { + error( + "%s has a method called " + + "componentDidReceiveProps(). But there is no such lifecycle method. " + + "If you meant to update the state in response to changing props, " + + "use componentWillReceiveProps(). If you meant to fetch data or " + + "run side-effects or mutations after React has updated the UI, use componentDidUpdate().", + name + ); + } - function warnOnInvalidCallback(callback, callerName) { - { - if (callback === null || typeof callback === "function") { - return; + if (typeof instance.componentWillRecieveProps === "function") { + error( + "%s has a method called " + + "componentWillRecieveProps(). Did you mean componentWillReceiveProps()?", + name + ); } - var key = callerName + "_" + callback; + if (typeof instance.UNSAFE_componentWillRecieveProps === "function") { + error( + "%s has a method called " + + "UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?", + name + ); + } - if (!didWarnOnInvalidCallback.has(key)) { - didWarnOnInvalidCallback.add(key); + var hasMutatedProps = instance.props !== newProps; + if (instance.props !== undefined && hasMutatedProps) { error( - "%s(...): Expected the last optional `callback` argument to be a " + - "function. Instead received: %s.", - callerName, - callback + "%s(...): When calling super() in `%s`, make sure to pass " + + "up the same props that your component's constructor was passed.", + name, + name ); } - } - } - function warnOnUndefinedDerivedState(type, partialState) { - { - if (partialState === undefined) { - var componentName = getComponentNameFromType(type) || "Component"; + if (instance.defaultProps) { + error( + "Setting defaultProps as an instance property on %s is not supported and will be ignored." + + " Instead, define defaultProps as a static property on %s.", + name, + name + ); + } - if (!didWarnAboutUndefinedDerivedState.has(componentName)) { - didWarnAboutUndefinedDerivedState.add(componentName); + if ( + typeof instance.getSnapshotBeforeUpdate === "function" && + typeof instance.componentDidUpdate !== "function" && + !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor) + ) { + didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor); - error( - "%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. " + - "You have returned undefined.", - componentName - ); - } + error( + "%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). " + + "This component defines getSnapshotBeforeUpdate() only.", + getComponentNameFromType(ctor) + ); } - } - } - function warnNoop(publicInstance, callerName) { - { - var _constructor = publicInstance.constructor; - var componentName = - (_constructor && getComponentNameFromType(_constructor)) || - "ReactClass"; - var warningKey = componentName + "." + callerName; + if (typeof instance.getDerivedStateFromProps === "function") { + error( + "%s: getDerivedStateFromProps() is defined as an instance method " + + "and will be ignored. Instead, declare it as a static method.", + name + ); + } - if (didWarnAboutNoopUpdateForComponent[warningKey]) { - return; + if (typeof instance.getDerivedStateFromError === "function") { + error( + "%s: getDerivedStateFromError() is defined as an instance method " + + "and will be ignored. Instead, declare it as a static method.", + name + ); } - error( - "%s(...): Can only update a mounting component. " + - "This usually means you called %s() outside componentWillMount() on the server. " + - "This is a no-op.\n\nPlease check the code for the %s component.", - callerName, - callerName, - componentName - ); + if (typeof ctor.getSnapshotBeforeUpdate === "function") { + error( + "%s: getSnapshotBeforeUpdate() is defined as a static method " + + "and will be ignored. Instead, declare it as an instance method.", + name + ); + } - didWarnAboutNoopUpdateForComponent[warningKey] = true; + var state = instance.state; + + if (state && (typeof state !== "object" || isArray(state))) { + error("%s.state: must be set to an object or null", name); + } + + if ( + typeof instance.getChildContext === "function" && + typeof ctor.childContextTypes !== "object" + ) { + error( + "%s.getChildContext(): childContextTypes must be defined in order to " + + "use getChildContext().", + name + ); + } } } - var classComponentUpdater = { - isMounted: function (inst) { - return false; - }, - // $FlowFixMe[missing-local-annot] - enqueueSetState: function (inst, payload, callback) { - var internals = get(inst); + function callComponentWillMount(type, instance) { + var oldState = instance.state; - if (internals.queue === null) { - warnNoop(inst, "setState"); - } else { - internals.queue.push(payload); + if (typeof instance.componentWillMount === "function") { + { + if ( + instance.componentWillMount.__suppressDeprecationWarning !== true + ) { + var componentName = getComponentNameFromType(type) || "Unknown"; - { - if (callback !== undefined && callback !== null) { - warnOnInvalidCallback(callback, "setState"); + if (!didWarnAboutDeprecatedWillMount[componentName]) { + warn( + // keep this warning in sync with ReactStrictModeWarning.js + "componentWillMount has been renamed, and is not recommended for use. " + + "See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n" + + "* Move code from componentWillMount to componentDidMount (preferred in most cases) " + + "or the constructor.\n" + + "\nPlease update the following components: %s", + componentName + ); + + didWarnAboutDeprecatedWillMount[componentName] = true; } } } - }, - enqueueReplaceState: function (inst, payload, callback) { - var internals = get(inst); - internals.replace = true; - internals.queue = [payload]; + instance.componentWillMount(); + } + + if (typeof instance.UNSAFE_componentWillMount === "function") { + instance.UNSAFE_componentWillMount(); + } + + if (oldState !== instance.state) { { - if (callback !== undefined && callback !== null) { - warnOnInvalidCallback(callback, "setState"); - } + error( + "%s.componentWillMount(): Assigning directly to this.state is " + + "deprecated (except inside a component's " + + "constructor). Use setState instead.", + getComponentNameFromType(type) || "Component" + ); } - }, - // $FlowFixMe[missing-local-annot] - enqueueForceUpdate: function (inst, callback) { - var internals = get(inst); - if (internals.queue === null) { - warnNoop(inst, "forceUpdate"); - } else { - { - if (callback !== undefined && callback !== null) { - warnOnInvalidCallback(callback, "setState"); - } - } - } + classComponentUpdater.enqueueReplaceState( + instance, + instance.state, + null + ); } - }; + } - function applyDerivedStateFromProps( - instance, - ctor, - getDerivedStateFromProps, - prevState, - nextProps - ) { - var partialState = getDerivedStateFromProps(nextProps, prevState); - - { - warnOnUndefinedDerivedState(ctor, partialState); - } // Merge the partial state and the previous state. - - var newState = - partialState === null || partialState === undefined - ? prevState - : assign({}, prevState, partialState); - return newState; - } - - function constructClassInstance(ctor, props, maskedLegacyContext) { - var context = emptyContextObject; - var contextType = ctor.contextType; + function processUpdateQueue( + internalInstance, + inst, + props, + maskedLegacyContext + ) { + if ( + internalInstance.queue !== null && + internalInstance.queue.length > 0 + ) { + var oldQueue = internalInstance.queue; + var oldReplace = internalInstance.replace; + internalInstance.queue = null; + internalInstance.replace = false; - { - if ("contextType" in ctor) { - var isValid = // Allow null for conditional declaration - contextType === null || - (contextType !== undefined && - contextType.$$typeof === REACT_CONTEXT_TYPE); + if (oldReplace && oldQueue.length === 1) { + inst.state = oldQueue[0]; + } else { + var nextState = oldReplace ? oldQueue[0] : inst.state; + var dontMutate = true; - if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { - didWarnAboutInvalidateContextType.add(ctor); - var addendum = ""; + for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) { + var partial = oldQueue[i]; + var partialState = + typeof partial === "function" + ? partial.call(inst, nextState, props, maskedLegacyContext) + : partial; - if (contextType === undefined) { - addendum = - " However, it is set to undefined. " + - "This can be caused by a typo or by mixing up named and default imports. " + - "This can also happen due to a circular dependency, so " + - "try moving the createContext() call to a separate file."; - } else if (typeof contextType !== "object") { - addendum = " However, it is set to a " + typeof contextType + "."; - } else if (contextType.$$typeof === REACT_CONSUMER_TYPE) { - addendum = - " Did you accidentally pass the Context.Consumer instead?"; - } else { - addendum = - " However, it is set to an object with keys {" + - Object.keys(contextType).join(", ") + - "}."; + if (partialState != null) { + if (dontMutate) { + dontMutate = false; + nextState = assign({}, nextState, partialState); + } else { + assign(nextState, partialState); + } } - - error( - "%s defines an invalid contextType. " + - "contextType should point to the Context object returned by React.createContext().%s", - getComponentNameFromType(ctor) || "Component", - addendum - ); } + + inst.state = nextState; } + } else { + internalInstance.queue = null; } + } // Invokes the mount life-cycles on a previously never rendered instance. - if (typeof contextType === "object" && contextType !== null) { - context = readContext$1(contextType); + function mountClassInstance(instance, ctor, newProps, maskedLegacyContext) { + { + checkClassInstance(instance, ctor, newProps); } - var instance = new ctor(props, context); + var initialState = instance.state !== undefined ? instance.state : null; + instance.updater = classComponentUpdater; + instance.props = newProps; + instance.state = initialState; // We don't bother initializing the refs object on the server, since we're not going to resolve them anyway. + // The internal instance will be used to manage updates that happen during this mount. + + var internalInstance = { + queue: [], + replace: false + }; + set(instance, internalInstance); + var contextType = ctor.contextType; + + if (typeof contextType === "object" && contextType !== null) { + instance.context = readContext$1(contextType); + } else { + instance.context = emptyContextObject; + } { - if ( - typeof ctor.getDerivedStateFromProps === "function" && - (instance.state === null || instance.state === undefined) - ) { + if (instance.state === newProps) { var componentName = getComponentNameFromType(ctor) || "Component"; - if (!didWarnAboutUninitializedState.has(componentName)) { - didWarnAboutUninitializedState.add(componentName); + if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { + didWarnAboutDirectlyAssigningPropsToState.add(componentName); error( - "`%s` uses `getDerivedStateFromProps` but its initial state is " + - "%s. This is not recommended. Instead, define the initial state by " + - "assigning an object to `this.state` in the constructor of `%s`. " + - "This ensures that `getDerivedStateFromProps` arguments have a consistent shape.", - componentName, - instance.state === null ? "null" : "undefined", + "%s: It is not recommended to assign props directly to state " + + "because updates to props won't be reflected in state. " + + "In most cases, it is better to use props directly.", componentName ); } - } // If new component APIs are defined, "unsafe" lifecycles won't be called. - // Warn about these lifecycles if they are present. - // Don't warn about react-lifecycles-compat polyfilled methods though. - - if ( - typeof ctor.getDerivedStateFromProps === "function" || - typeof instance.getSnapshotBeforeUpdate === "function" - ) { - var foundWillMountName = null; - var foundWillReceivePropsName = null; - var foundWillUpdateName = null; - - if ( - typeof instance.componentWillMount === "function" && - instance.componentWillMount.__suppressDeprecationWarning !== true - ) { - foundWillMountName = "componentWillMount"; - } else if (typeof instance.UNSAFE_componentWillMount === "function") { - foundWillMountName = "UNSAFE_componentWillMount"; - } - - if ( - typeof instance.componentWillReceiveProps === "function" && - instance.componentWillReceiveProps.__suppressDeprecationWarning !== - true - ) { - foundWillReceivePropsName = "componentWillReceiveProps"; - } else if ( - typeof instance.UNSAFE_componentWillReceiveProps === "function" - ) { - foundWillReceivePropsName = "UNSAFE_componentWillReceiveProps"; - } - - if ( - typeof instance.componentWillUpdate === "function" && - instance.componentWillUpdate.__suppressDeprecationWarning !== true - ) { - foundWillUpdateName = "componentWillUpdate"; - } else if ( - typeof instance.UNSAFE_componentWillUpdate === "function" - ) { - foundWillUpdateName = "UNSAFE_componentWillUpdate"; - } + } + } - if ( - foundWillMountName !== null || - foundWillReceivePropsName !== null || - foundWillUpdateName !== null - ) { - var _componentName = getComponentNameFromType(ctor) || "Component"; + var getDerivedStateFromProps = ctor.getDerivedStateFromProps; - var newApiName = - typeof ctor.getDerivedStateFromProps === "function" - ? "getDerivedStateFromProps()" - : "getSnapshotBeforeUpdate()"; + if (typeof getDerivedStateFromProps === "function") { + instance.state = applyDerivedStateFromProps( + instance, + ctor, + getDerivedStateFromProps, + initialState, + newProps + ); + } // In order to support react-lifecycles-compat polyfilled components, + // Unsafe lifecycles should not be invoked for components using the new APIs. - if ( - !didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName) - ) { - didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName); + if ( + typeof ctor.getDerivedStateFromProps !== "function" && + typeof instance.getSnapshotBeforeUpdate !== "function" && + (typeof instance.UNSAFE_componentWillMount === "function" || + typeof instance.componentWillMount === "function") + ) { + callComponentWillMount(ctor, instance); // If we had additional state updates during this life-cycle, let's + // process them now. - error( - "Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n" + - "%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n" + - "The above lifecycles should be removed. Learn more about this warning here:\n" + - "https://reactjs.org/link/unsafe-component-lifecycles", - _componentName, - newApiName, - foundWillMountName !== null ? "\n " + foundWillMountName : "", - foundWillReceivePropsName !== null - ? "\n " + foundWillReceivePropsName - : "", - foundWillUpdateName !== null ? "\n " + foundWillUpdateName : "" - ); - } - } - } + processUpdateQueue( + internalInstance, + instance, + newProps, + maskedLegacyContext + ); } - - return instance; } - function checkClassInstance(instance, ctor, newProps) { - { - var name = getComponentNameFromType(ctor) || "Component"; - var renderPresent = instance.render; - - if (!renderPresent) { - if (ctor.prototype && typeof ctor.prototype.render === "function") { - error( - "%s(...): No `render` method found on the returned component " + - "instance: did you accidentally return an object from the constructor?", - name - ); - } else { - error( - "%s(...): No `render` method found on the returned component " + - "instance: you may have forgotten to define `render`.", - name - ); - } - } - - if ( - instance.getInitialState && - !instance.getInitialState.isReactClassApproved && - !instance.state - ) { - error( - "getInitialState was defined on %s, a plain JavaScript class. " + - "This is only supported for classes created using React.createClass. " + - "Did you mean to define a state property instead?", - name - ); - } + // Ids are base 32 strings whose binary representation corresponds to the + // position of a node in a tree. + // Every time the tree forks into multiple children, we add additional bits to + // the left of the 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. Otherwise, + // 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 the + // sequence. It's treated as a transparent indirection. For example, these two + // trees produce the same ids: + // + // <> <> + // + // + // + // + // + // + // However, we cannot skip any node that materializes an id. Otherwise, a parent + // id that does not fork would be indistinguishable from its child id. For + // example, this tree does not fork, but the parent and child must have + // different ids. + // + // + // + // + // + // To handle this scenario, every time we materialize an id, we allocate a + // new level with a single slot. You can think of this as a fork with only one + // prong, or an array of children with length 1. + // + // It's possible for the size of the sequence to exceed 32 bits, the max + // size for bitwise operations. When this happens, we make more room by + // converting the right part of the id to a string and storing it in an overflow + // variable. We use a base 32 string representation, because 32 is the largest + // power of 2 that is supported by toString(). We want the base to be large so + // that the resulting ids are compact, and we want the base to be a power of 2 + // because every log2(base) bits corresponds to a single character, i.e. every + // log2(32) = 5 bits. That means we can lop bits off the end 5 at a time without + // affecting the final result. + var emptyTreeContext = { + id: 1, + overflow: "" + }; + function getTreeId(context) { + var overflow = context.overflow; + var idWithLeadingBit = context.id; + var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit); + return id.toString(32) + overflow; + } + function pushTreeContext(baseContext, totalChildren, index) { + var baseIdWithLeadingBit = baseContext.id; + var baseOverflow = baseContext.overflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part + // of the id; we use it to account for leading 0s. - if ( - instance.getDefaultProps && - !instance.getDefaultProps.isReactClassApproved - ) { - error( - "getDefaultProps was defined on %s, a plain JavaScript class. " + - "This is only supported for classes created using React.createClass. " + - "Use a static property to define defaultProps instead.", - name - ); - } + var baseLength = getBitLength(baseIdWithLeadingBit) - 1; + var baseId = baseIdWithLeadingBit & ~(1 << baseLength); + var slot = index + 1; + var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into + // consideration the leading 1 we use to mark the end of the sequence. - if (instance.propTypes) { - error( - "propTypes was defined as an instance property on %s. Use a static " + - "property to define propTypes instead.", - name - ); - } + if (length > 30) { + // We overflowed the bitwise-safe range. Fall back to slower algorithm. + // This branch assumes the length of the base id is greater than 5; it won't + // work for smaller ids, because you need 5 bits per character. + // + // We encode the id in multiple steps: first the base id, then the + // remaining digits. + // + // Each 5 bit sequence corresponds to a single base 32 character. So for + // example, if the current id is 23 bits long, we can convert 20 of those + // bits into a string of 4 characters, with 3 bits left over. + // + // First calculate how many bits in the base id represent a complete + // sequence of characters. + var numberOfOverflowBits = baseLength - (baseLength % 5); // Then create a bitmask that selects only those bits. - if (instance.contextType) { - error( - "contextType was defined as an instance property on %s. Use a static " + - "property to define contextType instead.", - name - ); - } + var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string. - { - if (ctor.childContextTypes) { - error( - "%s uses the legacy childContextTypes API which is no longer supported. " + - "Use React.createContext() instead.", - name - ); - } + var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id. - if (ctor.contextTypes) { - error( - "%s uses the legacy contextTypes API which is no longer supported. " + - "Use React.createContext() with static contextType instead.", - name - ); - } - } + var restOfBaseId = baseId >> numberOfOverflowBits; + var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because + // we made more room, this time it won't overflow. - if (typeof instance.componentShouldUpdate === "function") { - error( - "%s has a method called " + - "componentShouldUpdate(). Did you mean shouldComponentUpdate()? " + - "The name is phrased as a question because the function is " + - "expected to return a value.", - name - ); - } + var restOfLength = getBitLength(totalChildren) + restOfBaseLength; + var restOfNewBits = slot << restOfBaseLength; + var id = restOfNewBits | restOfBaseId; + var overflow = newOverflow + baseOverflow; + return { + id: (1 << restOfLength) | id, + overflow: overflow + }; + } else { + // Normal path + var newBits = slot << baseLength; - if ( - ctor.prototype && - ctor.prototype.isPureReactComponent && - typeof instance.shouldComponentUpdate !== "undefined" - ) { - error( - "%s has a method called shouldComponentUpdate(). " + - "shouldComponentUpdate should not be used when extending React.PureComponent. " + - "Please extend React.Component if shouldComponentUpdate is used.", - getComponentNameFromType(ctor) || "A pure component" - ); - } + var _id = newBits | baseId; - if (typeof instance.componentDidUnmount === "function") { - error( - "%s has a method called " + - "componentDidUnmount(). But there is no such lifecycle method. " + - "Did you mean componentWillUnmount()?", - name - ); - } + var _overflow = baseOverflow; + return { + id: (1 << length) | _id, + overflow: _overflow + }; + } + } - if (typeof instance.componentDidReceiveProps === "function") { - error( - "%s has a method called " + - "componentDidReceiveProps(). But there is no such lifecycle method. " + - "If you meant to update the state in response to changing props, " + - "use componentWillReceiveProps(). If you meant to fetch data or " + - "run side-effects or mutations after React has updated the UI, use componentDidUpdate().", - name - ); - } + function getBitLength(number) { + return 32 - clz32(number); + } - if (typeof instance.componentWillRecieveProps === "function") { - error( - "%s has a method called " + - "componentWillRecieveProps(). Did you mean componentWillReceiveProps()?", - name - ); - } + function getLeadingBit(id) { + return 1 << (getBitLength(id) - 1); + } // TODO: Math.clz32 is supported in Node 12+. Maybe we can drop the fallback. - if (typeof instance.UNSAFE_componentWillRecieveProps === "function") { - error( - "%s has a method called " + - "UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?", - name - ); - } + var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros. + // Based on: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32 - var hasMutatedProps = instance.props !== newProps; + var log = Math.log; + var LN2 = Math.LN2; - if (instance.props !== undefined && hasMutatedProps) { - error( - "%s(...): When calling super() in `%s`, make sure to pass " + - "up the same props that your component's constructor was passed.", - name, - name - ); - } + function clz32Fallback(x) { + var asUint = x >>> 0; - if (instance.defaultProps) { - error( - "Setting defaultProps as an instance property on %s is not supported and will be ignored." + - " Instead, define defaultProps as a static property on %s.", - name, - name - ); - } + if (asUint === 0) { + return 32; + } - if ( - typeof instance.getSnapshotBeforeUpdate === "function" && - typeof instance.componentDidUpdate !== "function" && - !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor) - ) { - didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor); + return (31 - ((log(asUint) / LN2) | 0)) | 0; + } + + // Corresponds to ReactFiberWakeable and ReactFlightWakeable modules. Generally, + // changes to one module should be reflected in the others. + // TODO: Rename this module and the corresponding Fiber one to "Thenable" + // instead of "Wakeable". Or some other more appropriate name. + // An error that is thrown (e.g. by `use`) to trigger Suspense. If we + // detect this is caught by userspace, we'll log a warning in development. + var SuspenseException = new Error( + "Suspense Exception: This is not a real error! It's an implementation " + + "detail of `use` to interrupt the current render. You must either " + + "rethrow it immediately, or move the `use` call outside of the " + + "`try/catch` block. Capturing without rethrowing will lead to " + + "unexpected behavior.\n\n" + + "To handle async errors, wrap your component in an error boundary, or " + + "call the promise's `.catch` method and pass the result to `use`" + ); + function createThenableState() { + // The ThenableState is created the first time a component suspends. If it + // suspends again, we'll reuse the same state. + return []; + } - error( - "%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). " + - "This component defines getSnapshotBeforeUpdate() only.", - getComponentNameFromType(ctor) - ); - } + function noop$2() {} - if (typeof instance.getDerivedStateFromProps === "function") { - error( - "%s: getDerivedStateFromProps() is defined as an instance method " + - "and will be ignored. Instead, declare it as a static method.", - name - ); + function trackUsedThenable(thenableState, thenable, index) { + var previous = thenableState[index]; + + if (previous === undefined) { + thenableState.push(thenable); + } else { + if (previous !== thenable) { + // Reuse the previous thenable, and drop the new one. We can assume + // they represent the same value, because components are idempotent. + // Avoid an unhandled rejection errors for the Promises that we'll + // intentionally ignore. + thenable.then(noop$2, noop$2); + thenable = previous; } + } // We use an expando to track the status and result of a thenable so that we + // can synchronously unwrap the value. Think of this as an extension of the + // Promise API, or a custom interface that is a superset of Thenable. + // + // If the thenable doesn't have a status, set it to "pending" and attach + // a listener that will update its status and result when it resolves. - if (typeof instance.getDerivedStateFromError === "function") { - error( - "%s: getDerivedStateFromError() is defined as an instance method " + - "and will be ignored. Instead, declare it as a static method.", - name - ); + switch (thenable.status) { + case "fulfilled": { + var fulfilledValue = thenable.value; + return fulfilledValue; } - if (typeof ctor.getSnapshotBeforeUpdate === "function") { - error( - "%s: getSnapshotBeforeUpdate() is defined as a static method " + - "and will be ignored. Instead, declare it as an instance method.", - name - ); + case "rejected": { + var rejectedError = thenable.reason; + throw rejectedError; } - var state = instance.state; + default: { + if (typeof thenable.status === "string"); + else { + var pendingThenable = thenable; + pendingThenable.status = "pending"; + pendingThenable.then( + function (fulfilledValue) { + if (thenable.status === "pending") { + var fulfilledThenable = thenable; + fulfilledThenable.status = "fulfilled"; + fulfilledThenable.value = fulfilledValue; + } + }, + function (error) { + if (thenable.status === "pending") { + var rejectedThenable = thenable; + rejectedThenable.status = "rejected"; + rejectedThenable.reason = error; + } + } + ); // Check one more time in case the thenable resolved synchronously - if (state && (typeof state !== "object" || isArray(state))) { - error("%s.state: must be set to an object or null", name); - } + switch (thenable.status) { + case "fulfilled": { + var fulfilledThenable = thenable; + return fulfilledThenable.value; + } - if ( - typeof instance.getChildContext === "function" && - typeof ctor.childContextTypes !== "object" - ) { - error( - "%s.getChildContext(): childContextTypes must be defined in order to " + - "use getChildContext().", - name - ); + case "rejected": { + var rejectedThenable = thenable; + throw rejectedThenable.reason; + } + } + } // Suspend. + // + // Throwing here is an implementation detail that allows us to unwind the + // call stack. But we shouldn't allow it to leak into userspace. Throw an + // opaque placeholder value instead of the actual thenable. If it doesn't + // get captured by the work loop, log a warning, because that means + // something in userspace must have caught it. + + suspendedThenable = thenable; + throw SuspenseException; } } + } // This is used to track the actual thenable that suspended so it can be + // passed to the rest of the Suspense implementation — which, for historical + // reasons, expects to receive a thenable. + + var suspendedThenable = null; + function getSuspendedThenable() { + // This is called right after `use` suspends by throwing an exception. `use` + // throws an opaque value instead of the thenable itself so that it can't be + // caught in userspace. Then the work loop accesses the actual thenable using + // this function. + if (suspendedThenable === null) { + throw new Error( + "Expected a suspended thenable. This is a bug in React. Please file " + + "an issue." + ); + } + + var thenable = suspendedThenable; + suspendedThenable = null; + return thenable; } - function callComponentWillMount(type, instance) { - var oldState = instance.state; + /** + * inlined Object.is polyfill to avoid requiring consumers ship their own + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + */ + function is(x, y) { + return ( + (x === y && (x !== 0 || 1 / x === 1 / y)) || (x !== x && y !== y) // eslint-disable-line no-self-compare + ); + } - if (typeof instance.componentWillMount === "function") { - { - if ( - instance.componentWillMount.__suppressDeprecationWarning !== true - ) { - var componentName = getComponentNameFromType(type) || "Unknown"; + var objectIs = typeof Object.is === "function" ? Object.is : is; // $FlowFixMe[method-unbinding] - if (!didWarnAboutDeprecatedWillMount[componentName]) { - warn( - // keep this warning in sync with ReactStrictModeWarning.js - "componentWillMount has been renamed, and is not recommended for use. " + - "See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n" + - "* Move code from componentWillMount to componentDidMount (preferred in most cases) " + - "or the constructor.\n" + - "\nPlease update the following components: %s", - componentName - ); + var currentlyRenderingComponent = null; + var currentlyRenderingTask = null; + var currentlyRenderingRequest = null; + var currentlyRenderingKeyPath = null; + var firstWorkInProgressHook = null; + var workInProgressHook = null; // Whether the work-in-progress hook is a re-rendered hook - didWarnAboutDeprecatedWillMount[componentName] = true; - } - } - } + var isReRender = false; // Whether an update was scheduled during the currently executing render pass. - instance.componentWillMount(); - } + var didScheduleRenderPhaseUpdate = false; // Counts the number of useId hooks in this component - if (typeof instance.UNSAFE_componentWillMount === "function") { - instance.UNSAFE_componentWillMount(); - } + var localIdCounter = 0; // Chunks that should be pushed to the stream once the component + // finishes rendering. + // Counts the number of useFormState calls in this component - if (oldState !== instance.state) { - { - error( - "%s.componentWillMount(): Assigning directly to this.state is " + - "deprecated (except inside a component's " + - "constructor). Use setState instead.", - getComponentNameFromType(type) || "Component" - ); - } + var formStateCounter = 0; // The index of the useFormState hook that matches the one passed in at the + // root during an MPA navigation, if any. - classComponentUpdater.enqueueReplaceState( - instance, - instance.state, - null - ); - } - } + var formStateMatchingIndex = -1; // Counts the number of use(thenable) calls in this component - function processUpdateQueue( - internalInstance, - inst, - props, - maskedLegacyContext - ) { - if ( - internalInstance.queue !== null && - internalInstance.queue.length > 0 - ) { - var oldQueue = internalInstance.queue; - var oldReplace = internalInstance.replace; - internalInstance.queue = null; - internalInstance.replace = false; + var thenableIndexCounter = 0; + var thenableState = null; // Lazily created map of render-phase updates - if (oldReplace && oldQueue.length === 1) { - inst.state = oldQueue[0]; - } else { - var nextState = oldReplace ? oldQueue[0] : inst.state; - var dontMutate = true; + var renderPhaseUpdates = null; // Counter to prevent infinite loops. - for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) { - var partial = oldQueue[i]; - var partialState = - typeof partial === "function" - ? partial.call(inst, nextState, props, maskedLegacyContext) - : partial; + var numberOfReRenders = 0; + var RE_RENDER_LIMIT = 25; + var isInHookUserCodeInDev = false; // In DEV, this is the name of the currently executing primitive hook - if (partialState != null) { - if (dontMutate) { - dontMutate = false; - nextState = assign({}, nextState, partialState); - } else { - assign(nextState, partialState); - } - } - } + var currentHookNameInDev; - inst.state = nextState; + function resolveCurrentlyRenderingComponent() { + if (currentlyRenderingComponent === null) { + throw new Error( + "Invalid hook call. Hooks can only be called inside of the body of a function 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 of Hooks\n" + + "3. You might have more than one copy of React in the same app\n" + + "See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem." + ); + } + + { + if (isInHookUserCodeInDev) { + error( + "Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. " + + "You can only call Hooks at the top level of your React function. " + + "For more information, see " + + "https://reactjs.org/link/rules-of-hooks" + ); } - } else { - internalInstance.queue = null; - } - } // Invokes the mount life-cycles on a previously never rendered instance. - - function mountClassInstance(instance, ctor, newProps, maskedLegacyContext) { - { - checkClassInstance(instance, ctor, newProps); } - var initialState = instance.state !== undefined ? instance.state : null; - instance.updater = classComponentUpdater; - instance.props = newProps; - instance.state = initialState; // We don't bother initializing the refs object on the server, since we're not going to resolve them anyway. - // The internal instance will be used to manage updates that happen during this mount. + return currentlyRenderingComponent; + } - var internalInstance = { - queue: [], - replace: false - }; - set(instance, internalInstance); - var contextType = ctor.contextType; + function areHookInputsEqual(nextDeps, prevDeps) { + if (prevDeps === null) { + { + error( + "%s received a final argument during this render, but not during " + + "the previous render. Even though the final argument is optional, " + + "its type cannot change between renders.", + currentHookNameInDev + ); + } - if (typeof contextType === "object" && contextType !== null) { - instance.context = readContext$1(contextType); - } else { - instance.context = emptyContextObject; + return false; } { - if (instance.state === newProps) { - var componentName = getComponentNameFromType(ctor) || "Component"; - - if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { - didWarnAboutDirectlyAssigningPropsToState.add(componentName); - - error( - "%s: It is not recommended to assign props directly to state " + - "because updates to props won't be reflected in state. " + - "In most cases, it is better to use props directly.", - componentName - ); - } + // Don't bother comparing lengths in prod because these arrays should be + // passed inline. + if (nextDeps.length !== prevDeps.length) { + error( + "The final argument passed to %s changed size between renders. The " + + "order and size of this array must remain constant.\n\n" + + "Previous: %s\n" + + "Incoming: %s", + currentHookNameInDev, + "[" + nextDeps.join(", ") + "]", + "[" + prevDeps.join(", ") + "]" + ); } - } + } // $FlowFixMe[incompatible-use] found when upgrading Flow - var getDerivedStateFromProps = ctor.getDerivedStateFromProps; + for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) { + // $FlowFixMe[incompatible-use] found when upgrading Flow + if (objectIs(nextDeps[i], prevDeps[i])) { + continue; + } - if (typeof getDerivedStateFromProps === "function") { - instance.state = applyDerivedStateFromProps( - instance, - ctor, - getDerivedStateFromProps, - initialState, - newProps - ); - } // In order to support react-lifecycles-compat polyfilled components, - // Unsafe lifecycles should not be invoked for components using the new APIs. + return false; + } - if ( - typeof ctor.getDerivedStateFromProps !== "function" && - typeof instance.getSnapshotBeforeUpdate !== "function" && - (typeof instance.UNSAFE_componentWillMount === "function" || - typeof instance.componentWillMount === "function") - ) { - callComponentWillMount(ctor, instance); // If we had additional state updates during this life-cycle, let's - // process them now. + return true; + } - processUpdateQueue( - internalInstance, - instance, - newProps, - maskedLegacyContext - ); + function createHook() { + if (numberOfReRenders > 0) { + throw new Error("Rendered more hooks than during the previous render"); } - } - // Ids are base 32 strings whose binary representation corresponds to the - // position of a node in a tree. - // Every time the tree forks into multiple children, we add additional bits to - // the left of the 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. Otherwise, - // 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 the - // sequence. It's treated as a transparent indirection. For example, these two - // trees produce the same ids: - // - // <> <> - // - // - // - // - // - // - // However, we cannot skip any node that materializes an id. Otherwise, a parent - // id that does not fork would be indistinguishable from its child id. For - // example, this tree does not fork, but the parent and child must have - // different ids. - // - // - // - // - // - // To handle this scenario, every time we materialize an id, we allocate a - // new level with a single slot. You can think of this as a fork with only one - // prong, or an array of children with length 1. - // - // It's possible for the size of the sequence to exceed 32 bits, the max - // size for bitwise operations. When this happens, we make more room by - // converting the right part of the id to a string and storing it in an overflow - // variable. We use a base 32 string representation, because 32 is the largest - // power of 2 that is supported by toString(). We want the base to be large so - // that the resulting ids are compact, and we want the base to be a power of 2 - // because every log2(base) bits corresponds to a single character, i.e. every - // log2(32) = 5 bits. That means we can lop bits off the end 5 at a time without - // affecting the final result. - var emptyTreeContext = { - id: 1, - overflow: "" - }; - function getTreeId(context) { - var overflow = context.overflow; - var idWithLeadingBit = context.id; - var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit); - return id.toString(32) + overflow; + return { + memoizedState: null, + queue: null, + next: null + }; } - function pushTreeContext(baseContext, totalChildren, index) { - var baseIdWithLeadingBit = baseContext.id; - var baseOverflow = baseContext.overflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part - // of the id; we use it to account for leading 0s. - - var baseLength = getBitLength(baseIdWithLeadingBit) - 1; - var baseId = baseIdWithLeadingBit & ~(1 << baseLength); - var slot = index + 1; - var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into - // consideration the leading 1 we use to mark the end of the sequence. - if (length > 30) { - // We overflowed the bitwise-safe range. Fall back to slower algorithm. - // This branch assumes the length of the base id is greater than 5; it won't - // work for smaller ids, because you need 5 bits per character. - // - // We encode the id in multiple steps: first the base id, then the - // remaining digits. - // - // Each 5 bit sequence corresponds to a single base 32 character. So for - // example, if the current id is 23 bits long, we can convert 20 of those - // bits into a string of 4 characters, with 3 bits left over. - // - // First calculate how many bits in the base id represent a complete - // sequence of characters. - var numberOfOverflowBits = baseLength - (baseLength % 5); // Then create a bitmask that selects only those bits. + function createWorkInProgressHook() { + if (workInProgressHook === null) { + // This is the first hook in the list + if (firstWorkInProgressHook === null) { + isReRender = false; + firstWorkInProgressHook = workInProgressHook = createHook(); + } else { + // There's already a work-in-progress. Reuse it. + isReRender = true; + workInProgressHook = firstWorkInProgressHook; + } + } else { + if (workInProgressHook.next === null) { + isReRender = false; // Append to the end of the list - var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string. + workInProgressHook = workInProgressHook.next = createHook(); + } else { + // There's already a work-in-progress. Reuse it. + isReRender = true; + workInProgressHook = workInProgressHook.next; + } + } - var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id. + return workInProgressHook; + } - var restOfBaseId = baseId >> numberOfOverflowBits; - var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because - // we made more room, this time it won't overflow. + function prepareToUseHooks( + request, + task, + keyPath, + componentIdentity, + prevThenableState + ) { + currentlyRenderingComponent = componentIdentity; + currentlyRenderingTask = task; + currentlyRenderingRequest = request; + currentlyRenderingKeyPath = keyPath; - var restOfLength = getBitLength(totalChildren) + restOfBaseLength; - var restOfNewBits = slot << restOfBaseLength; - var id = restOfNewBits | restOfBaseId; - var overflow = newOverflow + baseOverflow; - return { - id: (1 << restOfLength) | id, - overflow: overflow - }; - } else { - // Normal path - var newBits = slot << baseLength; + { + isInHookUserCodeInDev = false; + } // The following should have already been reset + // didScheduleRenderPhaseUpdate = false; + // firstWorkInProgressHook = null; + // numberOfReRenders = 0; + // renderPhaseUpdates = null; + // workInProgressHook = null; - var _id = newBits | baseId; + localIdCounter = 0; + formStateCounter = 0; + formStateMatchingIndex = -1; + thenableIndexCounter = 0; + thenableState = prevThenableState; + } + function finishHooks(Component, props, children, refOrContext) { + // This must be called after every function component to prevent hooks from + // being used in classes. + while (didScheduleRenderPhaseUpdate) { + // Updates were scheduled during the render phase. They are stored in + // the `renderPhaseUpdates` map. Call the component again, reusing the + // work-in-progress hooks and applying the additional updates on top. Keep + // restarting until no more updates are scheduled. + didScheduleRenderPhaseUpdate = false; + localIdCounter = 0; + formStateCounter = 0; + formStateMatchingIndex = -1; + thenableIndexCounter = 0; + numberOfReRenders += 1; // Start over from the beginning of the list - var _overflow = baseOverflow; - return { - id: (1 << length) | _id, - overflow: _overflow - }; + workInProgressHook = null; + children = Component(props, refOrContext); } - } - function getBitLength(number) { - return 32 - clz32(number); + resetHooksState(); + return children; + } + function getThenableStateAfterSuspending() { + var state = thenableState; + thenableState = null; + return state; + } + function checkDidRenderIdHook() { + // This should be called immediately after every finishHooks call. + // Conceptually, it's part of the return value of finishHooks; it's only a + // separate function to avoid using an array tuple. + var didRenderIdHook = localIdCounter !== 0; + return didRenderIdHook; + } + function getFormStateCount() { + // This should be called immediately after every finishHooks call. + // Conceptually, it's part of the return value of finishHooks; it's only a + // separate function to avoid using an array tuple. + return formStateCounter; } + function getFormStateMatchingIndex() { + // This should be called immediately after every finishHooks call. + // Conceptually, it's part of the return value of finishHooks; it's only a + // separate function to avoid using an array tuple. + return formStateMatchingIndex; + } // Reset the internal hooks state if an error occurs while rendering a component - function getLeadingBit(id) { - return 1 << (getBitLength(id) - 1); - } // TODO: Math.clz32 is supported in Node 12+. Maybe we can drop the fallback. + function resetHooksState() { + { + isInHookUserCodeInDev = false; + } - var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros. - // Based on: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32 + currentlyRenderingComponent = null; + currentlyRenderingTask = null; + currentlyRenderingRequest = null; + currentlyRenderingKeyPath = null; + didScheduleRenderPhaseUpdate = false; + firstWorkInProgressHook = null; + numberOfReRenders = 0; + renderPhaseUpdates = null; + workInProgressHook = null; + } - var log = Math.log; - var LN2 = Math.LN2; + function readContext(context) { + { + if (isInHookUserCodeInDev) { + error( + "Context can only be read while React is rendering. " + + "In classes, you can read it in the render method or getDerivedStateFromProps. " + + "In function components, you can read it directly in the function body, but not " + + "inside Hooks like useReducer() or useMemo()." + ); + } + } - function clz32Fallback(x) { - var asUint = x >>> 0; + return readContext$1(context); + } - if (asUint === 0) { - return 32; + function useContext(context) { + { + currentHookNameInDev = "useContext"; } - return (31 - ((log(asUint) / LN2) | 0)) | 0; + resolveCurrentlyRenderingComponent(); + return readContext$1(context); } - // Corresponds to ReactFiberWakeable and ReactFlightWakeable modules. Generally, - // changes to one module should be reflected in the others. - // TODO: Rename this module and the corresponding Fiber one to "Thenable" - // instead of "Wakeable". Or some other more appropriate name. - // An error that is thrown (e.g. by `use`) to trigger Suspense. If we - // detect this is caught by userspace, we'll log a warning in development. - var SuspenseException = new Error( - "Suspense Exception: This is not a real error! It's an implementation " + - "detail of `use` to interrupt the current render. You must either " + - "rethrow it immediately, or move the `use` call outside of the " + - "`try/catch` block. Capturing without rethrowing will lead to " + - "unexpected behavior.\n\n" + - "To handle async errors, wrap your component in an error boundary, or " + - "call the promise's `.catch` method and pass the result to `use`" - ); - function createThenableState() { - // The ThenableState is created the first time a component suspends. If it - // suspends again, we'll reuse the same state. - return []; + function basicStateReducer(state, action) { + // $FlowFixMe[incompatible-use]: Flow doesn't like mixed types + return typeof action === "function" ? action(state) : action; } - function noop$2() {} - - function trackUsedThenable(thenableState, thenable, index) { - var previous = thenableState[index]; - - if (previous === undefined) { - thenableState.push(thenable); - } else { - if (previous !== thenable) { - // Reuse the previous thenable, and drop the new one. We can assume - // they represent the same value, because components are idempotent. - // Avoid an unhandled rejection errors for the Promises that we'll - // intentionally ignore. - thenable.then(noop$2, noop$2); - thenable = previous; - } - } // We use an expando to track the status and result of a thenable so that we - // can synchronously unwrap the value. Think of this as an extension of the - // Promise API, or a custom interface that is a superset of Thenable. - // - // If the thenable doesn't have a status, set it to "pending" and attach - // a listener that will update its status and result when it resolves. - - switch (thenable.status) { - case "fulfilled": { - var fulfilledValue = thenable.value; - return fulfilledValue; - } + function useState(initialState) { + { + currentHookNameInDev = "useState"; + } - case "rejected": { - var rejectedError = thenable.reason; - throw rejectedError; + return useReducer( + basicStateReducer, // useReducer has a special case to support lazy useState initializers + initialState + ); + } + function useReducer(reducer, initialArg, init) { + { + if (reducer !== basicStateReducer) { + currentHookNameInDev = "useReducer"; } + } - default: { - if (typeof thenable.status === "string"); - else { - var pendingThenable = thenable; - pendingThenable.status = "pending"; - pendingThenable.then( - function (fulfilledValue) { - if (thenable.status === "pending") { - var fulfilledThenable = thenable; - fulfilledThenable.status = "fulfilled"; - fulfilledThenable.value = fulfilledValue; - } - }, - function (error) { - if (thenable.status === "pending") { - var rejectedThenable = thenable; - rejectedThenable.status = "rejected"; - rejectedThenable.reason = error; - } - } - ); // Check one more time in case the thenable resolved synchronously + currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); + workInProgressHook = createWorkInProgressHook(); - switch (thenable.status) { - case "fulfilled": { - var fulfilledThenable = thenable; - return fulfilledThenable.value; - } + if (isReRender) { + // This is a re-render. Apply the new render phase updates to the previous + // current hook. + var queue = workInProgressHook.queue; + var dispatch = queue.dispatch; - case "rejected": { - var rejectedThenable = thenable; - throw rejectedThenable.reason; - } - } - } // Suspend. - // - // Throwing here is an implementation detail that allows us to unwind the - // call stack. But we shouldn't allow it to leak into userspace. Throw an - // opaque placeholder value instead of the actual thenable. If it doesn't - // get captured by the work loop, log a warning, because that means - // something in userspace must have caught it. + if (renderPhaseUpdates !== null) { + // Render phase updates are stored in a map of queue -> linked list + var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); - suspendedThenable = thenable; - throw SuspenseException; - } - } - } // This is used to track the actual thenable that suspended so it can be - // passed to the rest of the Suspense implementation — which, for historical - // reasons, expects to receive a thenable. + if (firstRenderPhaseUpdate !== undefined) { + // $FlowFixMe[incompatible-use] found when upgrading Flow + renderPhaseUpdates.delete(queue); // $FlowFixMe[incompatible-use] found when upgrading Flow - var suspendedThenable = null; - function getSuspendedThenable() { - // This is called right after `use` suspends by throwing an exception. `use` - // throws an opaque value instead of the thenable itself so that it can't be - // caught in userspace. Then the work loop accesses the actual thenable using - // this function. - if (suspendedThenable === null) { - throw new Error( - "Expected a suspended thenable. This is a bug in React. Please file " + - "an issue." - ); - } + var newState = workInProgressHook.memoizedState; + var update = firstRenderPhaseUpdate; - var thenable = suspendedThenable; - suspendedThenable = null; - return thenable; - } + do { + // Process this render phase update. We don't have to check the + // priority because it will always be the same as the current + // render's. + var action = update.action; - /** - * inlined Object.is polyfill to avoid requiring consumers ship their own - * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is - */ - function is(x, y) { - return ( - (x === y && (x !== 0 || 1 / x === 1 / y)) || (x !== x && y !== y) // eslint-disable-line no-self-compare - ); - } + { + isInHookUserCodeInDev = true; + } - var objectIs = typeof Object.is === "function" ? Object.is : is; // $FlowFixMe[method-unbinding] + newState = reducer(newState, action); - var currentlyRenderingComponent = null; - var currentlyRenderingTask = null; - var currentlyRenderingRequest = null; - var currentlyRenderingKeyPath = null; - var firstWorkInProgressHook = null; - var workInProgressHook = null; // Whether the work-in-progress hook is a re-rendered hook + { + isInHookUserCodeInDev = false; + } // $FlowFixMe[incompatible-type] we bail out when we get a null - var isReRender = false; // Whether an update was scheduled during the currently executing render pass. + update = update.next; + } while (update !== null); // $FlowFixMe[incompatible-use] found when upgrading Flow - var didScheduleRenderPhaseUpdate = false; // Counts the number of useId hooks in this component + workInProgressHook.memoizedState = newState; + return [newState, dispatch]; + } + } // $FlowFixMe[incompatible-use] found when upgrading Flow - var localIdCounter = 0; // Chunks that should be pushed to the stream once the component - // finishes rendering. - // Counts the number of useFormState calls in this component + return [workInProgressHook.memoizedState, dispatch]; + } else { + { + isInHookUserCodeInDev = true; + } - var formStateCounter = 0; // The index of the useFormState hook that matches the one passed in at the - // root during an MPA navigation, if any. + var initialState; - var formStateMatchingIndex = -1; // Counts the number of use(thenable) calls in this component + if (reducer === basicStateReducer) { + // Special case for `useState`. + initialState = + typeof initialArg === "function" ? initialArg() : initialArg; + } else { + initialState = init !== undefined ? init(initialArg) : initialArg; + } - var thenableIndexCounter = 0; - var thenableState = null; // Lazily created map of render-phase updates + { + isInHookUserCodeInDev = false; + } // $FlowFixMe[incompatible-use] found when upgrading Flow - var renderPhaseUpdates = null; // Counter to prevent infinite loops. + workInProgressHook.memoizedState = initialState; // $FlowFixMe[incompatible-use] found when upgrading Flow - var numberOfReRenders = 0; - var RE_RENDER_LIMIT = 25; - var isInHookUserCodeInDev = false; // In DEV, this is the name of the currently executing primitive hook + var _queue = (workInProgressHook.queue = { + last: null, + dispatch: null + }); - var currentHookNameInDev; + var _dispatch = (_queue.dispatch = dispatchAction.bind( + null, + currentlyRenderingComponent, + _queue + )); // $FlowFixMe[incompatible-use] found when upgrading Flow - function resolveCurrentlyRenderingComponent() { - if (currentlyRenderingComponent === null) { - throw new Error( - "Invalid hook call. Hooks can only be called inside of the body of a function 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 of Hooks\n" + - "3. You might have more than one copy of React in the same app\n" + - "See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem." - ); + return [workInProgressHook.memoizedState, _dispatch]; } + } - { - if (isInHookUserCodeInDev) { - error( - "Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. " + - "You can only call Hooks at the top level of your React function. " + - "For more information, see " + - "https://reactjs.org/link/rules-of-hooks" - ); - } - } + function useMemo(nextCreate, deps) { + currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); + workInProgressHook = createWorkInProgressHook(); + var nextDeps = deps === undefined ? null : deps; - return currentlyRenderingComponent; - } + if (workInProgressHook !== null) { + var prevState = workInProgressHook.memoizedState; - function areHookInputsEqual(nextDeps, prevDeps) { - if (prevDeps === null) { - { - error( - "%s received a final argument during this render, but not during " + - "the previous render. Even though the final argument is optional, " + - "its type cannot change between renders.", - currentHookNameInDev - ); - } + if (prevState !== null) { + if (nextDeps !== null) { + var prevDeps = prevState[1]; - return false; + if (areHookInputsEqual(nextDeps, prevDeps)) { + return prevState[0]; + } + } + } } { - // Don't bother comparing lengths in prod because these arrays should be - // passed inline. - if (nextDeps.length !== prevDeps.length) { - error( - "The final argument passed to %s changed size between renders. The " + - "order and size of this array must remain constant.\n\n" + - "Previous: %s\n" + - "Incoming: %s", - currentHookNameInDev, - "[" + nextDeps.join(", ") + "]", - "[" + prevDeps.join(", ") + "]" - ); - } - } // $FlowFixMe[incompatible-use] found when upgrading Flow + isInHookUserCodeInDev = true; + } - for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) { - // $FlowFixMe[incompatible-use] found when upgrading Flow - if (objectIs(nextDeps[i], prevDeps[i])) { - continue; - } + var nextValue = nextCreate(); - return false; - } + { + isInHookUserCodeInDev = false; + } // $FlowFixMe[incompatible-use] found when upgrading Flow - return true; + workInProgressHook.memoizedState = [nextValue, nextDeps]; + return nextValue; } - function createHook() { - if (numberOfReRenders > 0) { - throw new Error("Rendered more hooks than during the previous render"); - } + function useRef(initialValue) { + currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); + workInProgressHook = createWorkInProgressHook(); + var previousRef = workInProgressHook.memoizedState; - return { - memoizedState: null, - queue: null, - next: null - }; - } + if (previousRef === null) { + var ref = { + current: initialValue + }; - function createWorkInProgressHook() { - if (workInProgressHook === null) { - // This is the first hook in the list - if (firstWorkInProgressHook === null) { - isReRender = false; - firstWorkInProgressHook = workInProgressHook = createHook(); - } else { - // There's already a work-in-progress. Reuse it. - isReRender = true; - workInProgressHook = firstWorkInProgressHook; - } + { + Object.seal(ref); + } // $FlowFixMe[incompatible-use] found when upgrading Flow + + workInProgressHook.memoizedState = ref; + return ref; } else { - if (workInProgressHook.next === null) { - isReRender = false; // Append to the end of the list + return previousRef; + } + } - workInProgressHook = workInProgressHook.next = createHook(); - } else { - // There's already a work-in-progress. Reuse it. - isReRender = true; - workInProgressHook = workInProgressHook.next; - } + function dispatchAction(componentIdentity, queue, action) { + if (numberOfReRenders >= RE_RENDER_LIMIT) { + throw new Error( + "Too many re-renders. React limits the number of renders to prevent " + + "an infinite loop." + ); } - return workInProgressHook; - } + if (componentIdentity === currentlyRenderingComponent) { + // This is a render phase update. Stash it in a lazily-created map of + // queue -> linked list of updates. After this render pass, we'll restart + // and apply the stashed updates on top of the work-in-progress hook. + didScheduleRenderPhaseUpdate = true; + var update = { + action: action, + next: null + }; - function prepareToUseHooks( - request, - task, - keyPath, - componentIdentity, - prevThenableState - ) { - currentlyRenderingComponent = componentIdentity; - currentlyRenderingTask = task; - currentlyRenderingRequest = request; - currentlyRenderingKeyPath = keyPath; + if (renderPhaseUpdates === null) { + renderPhaseUpdates = new Map(); + } - { - isInHookUserCodeInDev = false; - } // The following should have already been reset - // didScheduleRenderPhaseUpdate = false; - // firstWorkInProgressHook = null; - // numberOfReRenders = 0; - // renderPhaseUpdates = null; - // workInProgressHook = null; + var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); - localIdCounter = 0; - formStateCounter = 0; - formStateMatchingIndex = -1; - thenableIndexCounter = 0; - thenableState = prevThenableState; - } - function finishHooks(Component, props, children, refOrContext) { - // This must be called after every function component to prevent hooks from - // being used in classes. - while (didScheduleRenderPhaseUpdate) { - // Updates were scheduled during the render phase. They are stored in - // the `renderPhaseUpdates` map. Call the component again, reusing the - // work-in-progress hooks and applying the additional updates on top. Keep - // restarting until no more updates are scheduled. - didScheduleRenderPhaseUpdate = false; - localIdCounter = 0; - formStateCounter = 0; - formStateMatchingIndex = -1; - thenableIndexCounter = 0; - numberOfReRenders += 1; // Start over from the beginning of the list + if (firstRenderPhaseUpdate === undefined) { + // $FlowFixMe[incompatible-use] found when upgrading Flow + renderPhaseUpdates.set(queue, update); + } else { + // Append the update to the end of the list. + var lastRenderPhaseUpdate = firstRenderPhaseUpdate; - workInProgressHook = null; - children = Component(props, refOrContext); + while (lastRenderPhaseUpdate.next !== null) { + lastRenderPhaseUpdate = lastRenderPhaseUpdate.next; + } + + lastRenderPhaseUpdate.next = update; + } } - - resetHooksState(); - return children; } - function getThenableStateAfterSuspending() { - var state = thenableState; - thenableState = null; - return state; + + function useCallback(callback, deps) { + return useMemo(function () { + return callback; + }, deps); } - function checkDidRenderIdHook() { - // This should be called immediately after every finishHooks call. - // Conceptually, it's part of the return value of finishHooks; it's only a - // separate function to avoid using an array tuple. - var didRenderIdHook = localIdCounter !== 0; - return didRenderIdHook; + + function throwOnUseEffectEventCall() { + throw new Error( + "A function wrapped in useEffectEvent can't be called during rendering." + ); } - function getFormStateCount() { - // This should be called immediately after every finishHooks call. - // Conceptually, it's part of the return value of finishHooks; it's only a - // separate function to avoid using an array tuple. - return formStateCounter; + + function useEffectEvent(callback) { + // $FlowIgnore[incompatible-return] + return throwOnUseEffectEventCall; } - function getFormStateMatchingIndex() { - // This should be called immediately after every finishHooks call. - // Conceptually, it's part of the return value of finishHooks; it's only a - // separate function to avoid using an array tuple. - return formStateMatchingIndex; - } // Reset the internal hooks state if an error occurs while rendering a component - function resetHooksState() { - { - isInHookUserCodeInDev = false; + function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { + if (getServerSnapshot === undefined) { + throw new Error( + "Missing getServerSnapshot, which is required for " + + "server-rendered content. Will revert to client rendering." + ); } - currentlyRenderingComponent = null; - currentlyRenderingTask = null; - currentlyRenderingRequest = null; - currentlyRenderingKeyPath = null; - didScheduleRenderPhaseUpdate = false; - firstWorkInProgressHook = null; - numberOfReRenders = 0; - renderPhaseUpdates = null; - workInProgressHook = null; + return getServerSnapshot(); } - function readContext(context) { - { - if (isInHookUserCodeInDev) { - error( - "Context can only be read while React is rendering. " + - "In classes, you can read it in the render method or getDerivedStateFromProps. " + - "In function components, you can read it directly in the function body, but not " + - "inside Hooks like useReducer() or useMemo()." - ); - } - } + function useDeferredValue(value, initialValue) { + resolveCurrentlyRenderingComponent(); - return readContext$1(context); + if (enableUseDeferredValueInitialArg) { + return initialValue !== undefined ? initialValue : value; + } else { + return value; + } } - function useContext(context) { - { - currentHookNameInDev = "useContext"; - } + function unsupportedStartTransition() { + throw new Error( + "startTransition cannot be called during server rendering." + ); + } + function useTransition() { resolveCurrentlyRenderingComponent(); - return readContext$1(context); + return [false, unsupportedStartTransition]; } - function basicStateReducer(state, action) { - // $FlowFixMe[incompatible-use]: Flow doesn't like mixed types - return typeof action === "function" ? action(state) : action; + function useHostTransitionStatus() { + resolveCurrentlyRenderingComponent(); + return NotPendingTransition; } - function useState(initialState) { - { - currentHookNameInDev = "useState"; - } + function unsupportedSetOptimisticState() { + throw new Error("Cannot update optimistic state while rendering."); + } - return useReducer( - basicStateReducer, // useReducer has a special case to support lazy useState initializers - initialState - ); + function useOptimistic(passthrough, reducer) { + resolveCurrentlyRenderingComponent(); + return [passthrough, unsupportedSetOptimisticState]; } - function useReducer(reducer, initialArg, init) { - { - if (reducer !== basicStateReducer) { - currentHookNameInDev = "useReducer"; - } - } - currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); - workInProgressHook = createWorkInProgressHook(); + function createPostbackFormStateKey( + permalink, + componentKeyPath, + hookIndex + ) { + if (permalink !== undefined) { + // Don't bother to hash a permalink-based key since it's already short. + return "p" + permalink; + } else { + // Append a node to the key path that represents the form state hook. + var keyPath = [componentKeyPath, null, hookIndex]; // Key paths are hashed to reduce the size. It does not need to be secure, + // and it's more important that it's fast than that it's completely + // collision-free. - if (isReRender) { - // This is a re-render. Apply the new render phase updates to the previous - // current hook. - var queue = workInProgressHook.queue; - var dispatch = queue.dispatch; + var keyPathHash = createFastHashJS(JSON.stringify(keyPath)); + return "k" + keyPathHash; + } + } - if (renderPhaseUpdates !== null) { - // Render phase updates are stored in a map of queue -> linked list - var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); + function useFormState(action, initialState, permalink) { + resolveCurrentlyRenderingComponent(); // Count the number of useFormState hooks per component. We also use this to + // track the position of this useFormState hook relative to the other ones in + // this component, so we can generate a unique key for each one. - if (firstRenderPhaseUpdate !== undefined) { - // $FlowFixMe[incompatible-use] found when upgrading Flow - renderPhaseUpdates.delete(queue); // $FlowFixMe[incompatible-use] found when upgrading Flow + var formStateHookIndex = formStateCounter++; + var request = currentlyRenderingRequest; // $FlowIgnore[prop-missing] - var newState = workInProgressHook.memoizedState; - var update = firstRenderPhaseUpdate; + var formAction = action.$$FORM_ACTION; - do { - // Process this render phase update. We don't have to check the - // priority because it will always be the same as the current - // render's. - var action = update.action; + if (typeof formAction === "function") { + // This is a server action. These have additional features to enable + // MPA-style form submissions with progressive enhancement. + // TODO: If the same permalink is passed to multiple useFormStates, and + // they all have the same action signature, Fizz will pass the postback + // state to all of them. We should probably only pass it to the first one, + // and/or warn. + // The key is lazily generated and deduped so the that the keypath doesn't + // get JSON.stringify-ed unnecessarily, and at most once. + var nextPostbackStateKey = null; // Determine the current form state. If we received state during an MPA form + // submission, then we will reuse that, if the action identity matches. + // Otherwise we'll use the initial state argument. We will emit a comment + // marker into the stream that indicates whether the state was reused. - { - isInHookUserCodeInDev = true; - } + var state = initialState; + var componentKeyPath = currentlyRenderingKeyPath; + var postbackFormState = getFormState(request); // $FlowIgnore[prop-missing] - newState = reducer(newState, action); + var isSignatureEqual = action.$$IS_SIGNATURE_EQUAL; - { - isInHookUserCodeInDev = false; - } // $FlowFixMe[incompatible-type] we bail out when we get a null + if ( + postbackFormState !== null && + typeof isSignatureEqual === "function" + ) { + var postbackKey = postbackFormState[1]; + var postbackReferenceId = postbackFormState[2]; + var postbackBoundArity = postbackFormState[3]; - update = update.next; - } while (update !== null); // $FlowFixMe[incompatible-use] found when upgrading Flow + if ( + isSignatureEqual.call( + action, + postbackReferenceId, + postbackBoundArity + ) + ) { + nextPostbackStateKey = createPostbackFormStateKey( + permalink, + componentKeyPath, + formStateHookIndex + ); - workInProgressHook.memoizedState = newState; - return [newState, dispatch]; + if (postbackKey === nextPostbackStateKey) { + // This was a match + formStateMatchingIndex = formStateHookIndex; // Reuse the state that was submitted by the form. + + state = postbackFormState[0]; + } } - } // $FlowFixMe[incompatible-use] found when upgrading Flow + } // Bind the state to the first argument of the action. - return [workInProgressHook.memoizedState, dispatch]; - } else { - { - isInHookUserCodeInDev = true; - } + var boundAction = action.bind(null, state); // Wrap the action so the return value is void. - var initialState; + var dispatch = function (payload) { + boundAction(payload); + }; // $FlowIgnore[prop-missing] - if (reducer === basicStateReducer) { - // Special case for `useState`. - initialState = - typeof initialArg === "function" ? initialArg() : initialArg; - } else { - initialState = init !== undefined ? init(initialArg) : initialArg; - } + if (typeof boundAction.$$FORM_ACTION === "function") { + // $FlowIgnore[prop-missing] + dispatch.$$FORM_ACTION = function (prefix) { + var metadata = boundAction.$$FORM_ACTION(prefix); // Override the action URL - { - isInHookUserCodeInDev = false; - } // $FlowFixMe[incompatible-use] found when upgrading Flow + if (permalink !== undefined) { + { + checkAttributeStringCoercion(permalink, "target"); + } + + permalink += ""; + metadata.action = permalink; + } + + var formData = metadata.data; + + if (formData) { + if (nextPostbackStateKey === null) { + nextPostbackStateKey = createPostbackFormStateKey( + permalink, + componentKeyPath, + formStateHookIndex + ); + } - workInProgressHook.memoizedState = initialState; // $FlowFixMe[incompatible-use] found when upgrading Flow + formData.append("$ACTION_KEY", nextPostbackStateKey); + } - var _queue = (workInProgressHook.queue = { - last: null, - dispatch: null - }); + return metadata; + }; + } - var _dispatch = (_queue.dispatch = dispatchAction.bind( - null, - currentlyRenderingComponent, - _queue - )); // $FlowFixMe[incompatible-use] found when upgrading Flow + return [state, dispatch]; + } else { + // This is not a server action, so the implementation is much simpler. + // Bind the state to the first argument of the action. + var _boundAction = action.bind(null, initialState); // Wrap the action so the return value is void. - return [workInProgressHook.memoizedState, _dispatch]; + var _dispatch2 = function (payload) { + _boundAction(payload); + }; + + return [initialState, _dispatch2]; } } - function useMemo(nextCreate, deps) { - currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); - workInProgressHook = createWorkInProgressHook(); - var nextDeps = deps === undefined ? null : deps; + function useId() { + var task = currentlyRenderingTask; + var treeId = getTreeId(task.treeContext); + var resumableState = currentResumableState; - if (workInProgressHook !== null) { - var prevState = workInProgressHook.memoizedState; + if (resumableState === null) { + throw new Error( + "Invalid hook call. Hooks can only be called inside of the body of a function component." + ); + } - if (prevState !== null) { - if (nextDeps !== null) { - var prevDeps = prevState[1]; + var localId = localIdCounter++; + return makeId(resumableState, treeId, localId); + } - if (areHookInputsEqual(nextDeps, prevDeps)) { - return prevState[0]; - } - } + function use(usable) { + if (usable !== null && typeof usable === "object") { + // $FlowFixMe[method-unbinding] + if (typeof usable.then === "function") { + // This is a thenable. + var thenable = usable; + return unwrapThenable(thenable); + } else if (usable.$$typeof === REACT_CONTEXT_TYPE) { + var context = usable; + return readContext(context); } - } + } // eslint-disable-next-line react-internal/safe-string-coercion - { - isInHookUserCodeInDev = true; - } + throw new Error( + "An unsupported type was passed to use(): " + String(usable) + ); + } - var nextValue = nextCreate(); + function unwrapThenable(thenable) { + var index = thenableIndexCounter; + thenableIndexCounter += 1; - { - isInHookUserCodeInDev = false; - } // $FlowFixMe[incompatible-use] found when upgrading Flow + if (thenableState === null) { + thenableState = createThenableState(); + } - workInProgressHook.memoizedState = [nextValue, nextDeps]; - return nextValue; + return trackUsedThenable(thenableState, thenable, index); } - function useRef(initialValue) { - currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); - workInProgressHook = createWorkInProgressHook(); - var previousRef = workInProgressHook.memoizedState; + function unsupportedRefresh() { + throw new Error("Cache cannot be refreshed during server rendering."); + } - if (previousRef === null) { - var ref = { - current: initialValue - }; + function useCacheRefresh() { + return unsupportedRefresh; + } - { - Object.seal(ref); - } // $FlowFixMe[incompatible-use] found when upgrading Flow + function useMemoCache(size) { + var data = new Array(size); - workInProgressHook.memoizedState = ref; - return ref; - } else { - return previousRef; + for (var i = 0; i < size; i++) { + data[i] = REACT_MEMO_CACHE_SENTINEL; } + + return data; } - function dispatchAction(componentIdentity, queue, action) { - if (numberOfReRenders >= RE_RENDER_LIMIT) { - throw new Error( - "Too many re-renders. React limits the number of renders to prevent " + - "an infinite loop." - ); - } + function noop$1() {} - if (componentIdentity === currentlyRenderingComponent) { - // This is a render phase update. Stash it in a lazily-created map of - // queue -> linked list of updates. After this render pass, we'll restart - // and apply the stashed updates on top of the work-in-progress hook. - didScheduleRenderPhaseUpdate = true; - var update = { - action: action, - next: null - }; + var HooksDispatcher = { + readContext: readContext, + use: use, + useContext: useContext, + useMemo: useMemo, + useReducer: useReducer, + useRef: useRef, + useState: useState, + useInsertionEffect: noop$1, + useLayoutEffect: noop$1, + useCallback: useCallback, + // useImperativeHandle is not run in the server environment + useImperativeHandle: noop$1, + // Effects are not run in the server environment. + useEffect: noop$1, + // Debugging effect + useDebugValue: noop$1, + useDeferredValue: useDeferredValue, + useTransition: useTransition, + useId: useId, + // Subscriptions are not setup in a server environment. + useSyncExternalStore: useSyncExternalStore + }; - if (renderPhaseUpdates === null) { - renderPhaseUpdates = new Map(); - } + { + HooksDispatcher.useCacheRefresh = useCacheRefresh; + } - var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); + { + HooksDispatcher.useEffectEvent = useEffectEvent; + } - if (firstRenderPhaseUpdate === undefined) { - // $FlowFixMe[incompatible-use] found when upgrading Flow - renderPhaseUpdates.set(queue, update); - } else { - // Append the update to the end of the list. - var lastRenderPhaseUpdate = firstRenderPhaseUpdate; + { + HooksDispatcher.useMemoCache = useMemoCache; + } - while (lastRenderPhaseUpdate.next !== null) { - lastRenderPhaseUpdate = lastRenderPhaseUpdate.next; - } + { + HooksDispatcher.useHostTransitionStatus = useHostTransitionStatus; + } - lastRenderPhaseUpdate.next = update; - } - } + { + HooksDispatcher.useOptimistic = useOptimistic; + HooksDispatcher.useFormState = useFormState; } - function useCallback(callback, deps) { - return useMemo(function () { - return callback; - }, deps); + var currentResumableState = null; + function setCurrentResumableState(resumableState) { + currentResumableState = resumableState; } - function throwOnUseEffectEventCall() { - throw new Error( - "A function wrapped in useEffectEvent can't be called during rendering." - ); + function getCacheSignal() { + throw new Error("Not implemented."); } - function useEffectEvent(callback) { - // $FlowIgnore[incompatible-return] - return throwOnUseEffectEventCall; + function getCacheForType(resourceType) { + throw new Error("Not implemented."); } - function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { - if (getServerSnapshot === undefined) { - throw new Error( - "Missing getServerSnapshot, which is required for " + - "server-rendered content. Will revert to client rendering." - ); - } + var DefaultCacheDispatcher = { + getCacheSignal: getCacheSignal, + getCacheForType: getCacheForType + }; - return getServerSnapshot(); - } + // Helpers to patch console.logs to avoid logging during side-effect free + // replaying on render function. This currently only patches the object + // lazily which won't cover if the log function was extracted eagerly. + // We could also eagerly patch the method. + var disabledDepth = 0; + var prevLog; + var prevInfo; + var prevWarn; + var prevError; + var prevGroup; + var prevGroupCollapsed; + var prevGroupEnd; - function useDeferredValue(value, initialValue) { - resolveCurrentlyRenderingComponent(); + function disabledLog() {} + + disabledLog.__reactDisabledLog = true; + function disableLogs() { + { + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 + + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; // $FlowFixMe[cannot-write] Flow thinks console is immutable. + + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + /* eslint-enable react-internal/no-production-logging */ + } - if (enableUseDeferredValueInitialArg) { - return initialValue !== undefined ? initialValue : value; - } else { - return value; + disabledDepth++; } } + function reenableLogs() { + { + disabledDepth--; - function unsupportedStartTransition() { - throw new Error( - "startTransition cannot be called during server rendering." - ); - } - - function useTransition() { - resolveCurrentlyRenderingComponent(); - return [false, unsupportedStartTransition]; - } - - function useHostTransitionStatus() { - resolveCurrentlyRenderingComponent(); - return NotPendingTransition; - } + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + var props = { + configurable: true, + enumerable: true, + writable: true + }; // $FlowFixMe[cannot-write] Flow thinks console is immutable. - function unsupportedSetOptimisticState() { - throw new Error("Cannot update optimistic state while rendering."); - } + Object.defineProperties(console, { + log: assign({}, props, { + value: prevLog + }), + info: assign({}, props, { + value: prevInfo + }), + warn: assign({}, props, { + value: prevWarn + }), + error: assign({}, props, { + value: prevError + }), + group: assign({}, props, { + value: prevGroup + }), + groupCollapsed: assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: assign({}, props, { + value: prevGroupEnd + }) + }); + /* eslint-enable react-internal/no-production-logging */ + } - function useOptimistic(passthrough, reducer) { - resolveCurrentlyRenderingComponent(); - return [passthrough, unsupportedSetOptimisticState]; + if (disabledDepth < 0) { + error( + "disabledDepth fell below zero. " + + "This is a bug in React. Please file an issue." + ); + } + } } - function createPostbackFormStateKey( - permalink, - componentKeyPath, - hookIndex - ) { - if (permalink !== undefined) { - // Don't bother to hash a permalink-based key since it's already short. - return "p" + permalink; - } else { - // Append a node to the key path that represents the form state hook. - var keyPath = [componentKeyPath, null, hookIndex]; // Key paths are hashed to reduce the size. It does not need to be secure, - // and it's more important that it's fast than that it's completely - // collision-free. + var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; + var prefix; + function describeBuiltInComponentFrame(name, ownerFn) { + { + if (prefix === undefined) { + // Extract the VM specific prefix used by each line. + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = (match && match[1]) || ""; + } + } // We use the prefix to ensure our stacks line up with native stack frames. - var keyPathHash = createFastHashJS(JSON.stringify(keyPath)); - return "k" + keyPathHash; + return "\n" + prefix + name; } } + var reentry = false; + var componentFrameCache; - function useFormState(action, initialState, permalink) { - resolveCurrentlyRenderingComponent(); // Count the number of useFormState hooks per component. We also use this to - // track the position of this useFormState hook relative to the other ones in - // this component, so we can generate a unique key for each one. + { + var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); + } + /** + * Leverages native browser/VM stack frames to get proper details (e.g. + * filename, line + col number) for a single component in a component stack. We + * do this by: + * (1) throwing and catching an error in the function - this will be our + * control error. + * (2) calling the component which will eventually throw an error that we'll + * catch - this will be our sample error. + * (3) diffing the control and sample error stacks to find the stack frame + * which represents our component. + */ - var formStateHookIndex = formStateCounter++; - var request = currentlyRenderingRequest; // $FlowIgnore[prop-missing] + function describeNativeComponentFrame(fn, construct) { + // If something asked for a stack inside a fake render, it should get ignored. + if (!fn || reentry) { + return ""; + } - var formAction = action.$$FORM_ACTION; + { + var frame = componentFrameCache.get(fn); - if (typeof formAction === "function") { - // This is a server action. These have additional features to enable - // MPA-style form submissions with progressive enhancement. - // TODO: If the same permalink is passed to multiple useFormStates, and - // they all have the same action signature, Fizz will pass the postback - // state to all of them. We should probably only pass it to the first one, - // and/or warn. - // The key is lazily generated and deduped so the that the keypath doesn't - // get JSON.stringify-ed unnecessarily, and at most once. - var nextPostbackStateKey = null; // Determine the current form state. If we received state during an MPA form - // submission, then we will reuse that, if the action identity matches. - // Otherwise we'll use the initial state argument. We will emit a comment - // marker into the stream that indicates whether the state was reused. + if (frame !== undefined) { + return frame; + } + } - var state = initialState; - var componentKeyPath = currentlyRenderingKeyPath; - var postbackFormState = getFormState(request); // $FlowIgnore[prop-missing] + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe[incompatible-type] It does accept undefined. - var isSignatureEqual = action.$$IS_SIGNATURE_EQUAL; + Error.prepareStackTrace = undefined; + var previousDispatcher; - if ( - postbackFormState !== null && - typeof isSignatureEqual === "function" - ) { - var postbackKey = postbackFormState[1]; - var postbackReferenceId = postbackFormState[2]; - var postbackBoundArity = postbackFormState[3]; + { + previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function + // for warnings. - if ( - isSignatureEqual.call( - action, - postbackReferenceId, - postbackBoundArity - ) - ) { - nextPostbackStateKey = createPostbackFormStateKey( - permalink, - componentKeyPath, - formStateHookIndex - ); + ReactCurrentDispatcher$1.current = null; + disableLogs(); + } + /** + * Finding a common stack frame between sample and control errors can be + * tricky given the different types and levels of stack trace truncation from + * different JS VMs. So instead we'll attempt to control what that common + * frame should be through this object method: + * Having both the sample and control errors be in the function under the + * `DescribeNativeComponentFrameRoot` property, + setting the `name` and + * `displayName` properties of the function ensures that a stack + * frame exists that has the method name `DescribeNativeComponentFrameRoot` in + * it for both control and sample stacks. + */ - if (postbackKey === nextPostbackStateKey) { - // This was a match - formStateMatchingIndex = formStateHookIndex; // Reuse the state that was submitted by the form. + var RunInRootFrame = { + DetermineComponentFrameRoot: function () { + var control; - state = postbackFormState[0]; - } - } - } // Bind the state to the first argument of the action. + try { + // This should throw. + if (construct) { + // Something should be setting the props in the constructor. + var Fake = function () { + throw Error(); + }; // $FlowFixMe[prop-missing] - var boundAction = action.bind(null, state); // Wrap the action so the return value is void. + Object.defineProperty(Fake.prototype, "props", { + set: function () { + // We use a throwing setter instead of frozen or non-writable props + // because that won't throw in a non-strict mode function. + throw Error(); + } + }); - var dispatch = function (payload) { - boundAction(payload); - }; // $FlowIgnore[prop-missing] + if (typeof Reflect === "object" && Reflect.construct) { + // We construct a different control for this case to include any extra + // frames added by the construct call. + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } - if (typeof boundAction.$$FORM_ACTION === "function") { - // $FlowIgnore[prop-missing] - dispatch.$$FORM_ACTION = function (prefix) { - var metadata = boundAction.$$FORM_ACTION(prefix); // Override the action URL + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } // $FlowFixMe[prop-missing] found when upgrading Flow - if (permalink !== undefined) { - { - checkAttributeStringCoercion(permalink, "target"); + fn.call(Fake.prototype); } + } else { + try { + throw Error(); + } catch (x) { + control = x; + } // TODO(luna): This will currently only throw if the function component + // tries to access React/ReactDOM/props. We should probably make this throw + // in simple components too - permalink += ""; - metadata.action = permalink; - } - - var formData = metadata.data; + var maybePromise = fn(); // If the function component returns a promise, it's likely an async + // component, which we don't yet support. Attach a noop catch handler to + // silence the error. + // TODO: Implement component stacks for async client components? - if (formData) { - if (nextPostbackStateKey === null) { - nextPostbackStateKey = createPostbackFormStateKey( - permalink, - componentKeyPath, - formStateHookIndex - ); + if (maybePromise && typeof maybePromise.catch === "function") { + maybePromise.catch(function () {}); } - - formData.append("$ACTION_KEY", nextPostbackStateKey); } + } catch (sample) { + // This is inlined manually because closure doesn't do it for us. + if (sample && control && typeof sample.stack === "string") { + return [sample.stack, control.stack]; + } + } - return metadata; - }; + return [null, null]; } + }; // $FlowFixMe[prop-missing] - return [state, dispatch]; - } else { - // This is not a server action, so the implementation is much simpler. - // Bind the state to the first argument of the action. - var _boundAction = action.bind(null, initialState); // Wrap the action so the return value is void. - - var _dispatch2 = function (payload) { - _boundAction(payload); - }; - - return [initialState, _dispatch2]; - } - } - - function useId() { - var task = currentlyRenderingTask; - var treeId = getTreeId(task.treeContext); - var resumableState = currentResumableState; + RunInRootFrame.DetermineComponentFrameRoot.displayName = + "DetermineComponentFrameRoot"; + var namePropDescriptor = Object.getOwnPropertyDescriptor( + RunInRootFrame.DetermineComponentFrameRoot, + "name" + ); // Before ES6, the `name` property was not configurable. - if (resumableState === null) { - throw new Error( - "Invalid hook call. Hooks can only be called inside of the body of a function component." + if (namePropDescriptor && namePropDescriptor.configurable) { + // V8 utilizes a function's `name` property when generating a stack trace. + Object.defineProperty( + RunInRootFrame.DetermineComponentFrameRoot, // Configurable properties can be updated even if its writable descriptor + // is set to `false`. + // $FlowFixMe[cannot-write] + "name", + { + value: "DetermineComponentFrameRoot" + } ); } - var localId = localIdCounter++; - return makeId(resumableState, treeId, localId); - } - - function use(usable) { - if (usable !== null && typeof usable === "object") { - // $FlowFixMe[method-unbinding] - if (typeof usable.then === "function") { - // This is a thenable. - var thenable = usable; - return unwrapThenable(thenable); - } else if (usable.$$typeof === REACT_CONTEXT_TYPE) { - var context = usable; - return readContext(context); - } - } // eslint-disable-next-line react-internal/safe-string-coercion - - throw new Error( - "An unsupported type was passed to use(): " + String(usable) - ); - } + try { + var _RunInRootFrame$Deter = + RunInRootFrame.DetermineComponentFrameRoot(), + sampleStack = _RunInRootFrame$Deter[0], + controlStack = _RunInRootFrame$Deter[1]; - function unwrapThenable(thenable) { - var index = thenableIndexCounter; - thenableIndexCounter += 1; + if (sampleStack && controlStack) { + // This extracts the first frame from the sample that isn't also in the control. + // Skipping one frame that we assume is the frame that calls the two. + var sampleLines = sampleStack.split("\n"); + var controlLines = controlStack.split("\n"); + var s = 0; + var c = 0; - if (thenableState === null) { - thenableState = createThenableState(); - } + while ( + s < sampleLines.length && + !sampleLines[s].includes("DetermineComponentFrameRoot") + ) { + s++; + } - return trackUsedThenable(thenableState, thenable, index); - } + while ( + c < controlLines.length && + !controlLines[c].includes("DetermineComponentFrameRoot") + ) { + c++; + } // We couldn't find our intentionally injected common root frame, attempt + // to find another common root frame by search from the bottom of the + // control stack... - function unsupportedRefresh() { - throw new Error("Cache cannot be refreshed during server rendering."); - } + if (s === sampleLines.length || c === controlLines.length) { + s = sampleLines.length - 1; + c = controlLines.length - 1; - function useCacheRefresh() { - return unsupportedRefresh; - } + while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { + // We expect at least one stack frame to be shared. + // Typically this will be the root most one. However, stack frames may be + // cut off due to maximum stack limits. In this case, one maybe cut off + // earlier than the other. We assume that the sample is longer or the same + // and there for cut off earlier. So we should find the root most frame in + // the sample somewhere in the control. + c--; + } + } - function useMemoCache(size) { - var data = new Array(size); + for (; s >= 1 && c >= 0; s--, c--) { + // Next we find the first one that isn't the same which should be the + // frame that called our sample function and the control. + if (sampleLines[s] !== controlLines[c]) { + // In V8, the first line is describing the message but other VMs don't. + // If we're about to return the first line, and the control is also on the same + // line, that's a pretty good indicator that our sample threw at same line as + // the control. I.e. before we entered the sample frame. So we ignore this result. + // This can happen if you passed a class to function component, or non-function. + if (s !== 1 || c !== 1) { + do { + s--; + c--; // We may still have similar intermediate frames from the construct call. + // The next one that isn't the same should be our match though. - for (var i = 0; i < size; i++) { - data[i] = REACT_MEMO_CACHE_SENTINEL; - } + if (c < 0 || sampleLines[s] !== controlLines[c]) { + // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. + var _frame = + "\n" + sampleLines[s].replace(" at new ", " at "); // If our component frame is labeled "" + // but we have a user-provided "displayName" + // splice it in to make the stack more readable. - return data; - } + if (fn.displayName && _frame.includes("")) { + _frame = _frame.replace("", fn.displayName); + } - function noop$1() {} + if (true) { + if (typeof fn === "function") { + componentFrameCache.set(fn, _frame); + } + } // Return the line we found. - var HooksDispatcher = { - readContext: readContext, - use: use, - useContext: useContext, - useMemo: useMemo, - useReducer: useReducer, - useRef: useRef, - useState: useState, - useInsertionEffect: noop$1, - useLayoutEffect: noop$1, - useCallback: useCallback, - // useImperativeHandle is not run in the server environment - useImperativeHandle: noop$1, - // Effects are not run in the server environment. - useEffect: noop$1, - // Debugging effect - useDebugValue: noop$1, - useDeferredValue: useDeferredValue, - useTransition: useTransition, - useId: useId, - // Subscriptions are not setup in a server environment. - useSyncExternalStore: useSyncExternalStore - }; + return _frame; + } + } while (s >= 1 && c >= 0); + } - { - HooksDispatcher.useCacheRefresh = useCacheRefresh; - } + break; + } + } + } + } finally { + reentry = false; - { - HooksDispatcher.useEffectEvent = useEffectEvent; - } + { + ReactCurrentDispatcher$1.current = previousDispatcher; + reenableLogs(); + } - { - HooksDispatcher.useMemoCache = useMemoCache; - } + Error.prepareStackTrace = previousPrepareStackTrace; + } // Fallback to just using the name if we couldn't make it throw. - { - HooksDispatcher.useHostTransitionStatus = useHostTransitionStatus; - } + var name = fn ? fn.displayName || fn.name : ""; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; - { - HooksDispatcher.useOptimistic = useOptimistic; - HooksDispatcher.useFormState = useFormState; - } + { + if (typeof fn === "function") { + componentFrameCache.set(fn, syntheticFrame); + } + } - var currentResumableState = null; - function setCurrentResumableState(resumableState) { - currentResumableState = resumableState; + return syntheticFrame; } - function getCacheSignal() { - throw new Error("Not implemented."); + function describeClassComponentFrame(ctor, ownerFn) { + { + return describeNativeComponentFrame(ctor, true); + } } - - function getCacheForType(resourceType) { - throw new Error("Not implemented."); + function describeFunctionComponentFrame(fn, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } } - var DefaultCacheDispatcher = { - getCacheSignal: getCacheSignal, - getCacheForType: getCacheForType - }; - function getStackByComponentStackNode(componentStack) { try { var info = ""; diff --git a/compiled/facebook-www/ReactDOMServer-prod.classic.js b/compiled/facebook-www/ReactDOMServer-prod.classic.js index 24616aeea19d1..ae246f3b50aad 100644 --- a/compiled/facebook-www/ReactDOMServer-prod.classic.js +++ b/compiled/facebook-www/ReactDOMServer-prod.classic.js @@ -2794,149 +2794,6 @@ function getComponentNameFromType(type) { } return null; } -var prefix; -function describeBuiltInComponentFrame(name) { - if (void 0 === prefix) - try { - throw Error(); - } catch (x) { - var match = x.stack.trim().match(/\n( *(at )?)/); - prefix = (match && match[1]) || ""; - } - return "\n" + prefix + name; -} -var reentry = !1; -function describeNativeComponentFrame(fn, construct) { - if (!fn || reentry) return ""; - reentry = !0; - var previousPrepareStackTrace = Error.prepareStackTrace; - Error.prepareStackTrace = void 0; - var RunInRootFrame = { - DetermineComponentFrameRoot: function () { - try { - if (construct) { - var Fake = function () { - throw Error(); - }; - Object.defineProperty(Fake.prototype, "props", { - set: function () { - throw Error(); - } - }); - if ("object" === typeof Reflect && Reflect.construct) { - try { - Reflect.construct(Fake, []); - } catch (x) { - var control = x; - } - Reflect.construct(fn, [], Fake); - } else { - try { - Fake.call(); - } catch (x$19) { - control = x$19; - } - fn.call(Fake.prototype); - } - } else { - try { - throw Error(); - } catch (x$20) { - control = x$20; - } - (Fake = fn()) && - "function" === typeof Fake.catch && - Fake.catch(function () {}); - } - } catch (sample) { - if (sample && control && "string" === typeof sample.stack) - return [sample.stack, control.stack]; - } - return [null, null]; - } - }; - RunInRootFrame.DetermineComponentFrameRoot.displayName = - "DetermineComponentFrameRoot"; - var namePropDescriptor = Object.getOwnPropertyDescriptor( - RunInRootFrame.DetermineComponentFrameRoot, - "name" - ); - namePropDescriptor && - namePropDescriptor.configurable && - Object.defineProperty(RunInRootFrame.DetermineComponentFrameRoot, "name", { - value: "DetermineComponentFrameRoot" - }); - try { - var _RunInRootFrame$Deter = RunInRootFrame.DetermineComponentFrameRoot(), - sampleStack = _RunInRootFrame$Deter[0], - controlStack = _RunInRootFrame$Deter[1]; - if (sampleStack && controlStack) { - var sampleLines = sampleStack.split("\n"), - controlLines = controlStack.split("\n"); - for ( - namePropDescriptor = RunInRootFrame = 0; - RunInRootFrame < sampleLines.length && - !sampleLines[RunInRootFrame].includes("DetermineComponentFrameRoot"); - - ) - RunInRootFrame++; - for ( - ; - namePropDescriptor < controlLines.length && - !controlLines[namePropDescriptor].includes( - "DetermineComponentFrameRoot" - ); - - ) - namePropDescriptor++; - if ( - RunInRootFrame === sampleLines.length || - namePropDescriptor === controlLines.length - ) - for ( - RunInRootFrame = sampleLines.length - 1, - namePropDescriptor = controlLines.length - 1; - 1 <= RunInRootFrame && - 0 <= namePropDescriptor && - sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]; - - ) - namePropDescriptor--; - for ( - ; - 1 <= RunInRootFrame && 0 <= namePropDescriptor; - RunInRootFrame--, namePropDescriptor-- - ) - if (sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]) { - if (1 !== RunInRootFrame || 1 !== namePropDescriptor) { - do - if ( - (RunInRootFrame--, - namePropDescriptor--, - 0 > namePropDescriptor || - sampleLines[RunInRootFrame] !== - controlLines[namePropDescriptor]) - ) { - var frame = - "\n" + - sampleLines[RunInRootFrame].replace(" at new ", " at "); - fn.displayName && - frame.includes("") && - (frame = frame.replace("", fn.displayName)); - return frame; - } - while (1 <= RunInRootFrame && 0 <= namePropDescriptor); - } - break; - } - } - } finally { - (reentry = !1), (Error.prepareStackTrace = previousPrepareStackTrace); - } - return (previousPrepareStackTrace = fn ? fn.displayName || fn.name : "") - ? describeBuiltInComponentFrame(previousPrepareStackTrace) - : ""; -} var emptyContextObject = {}; function getMaskedContext(type, unmaskedContext) { type = type.contextTypes; @@ -3407,11 +3264,11 @@ var HooksDispatcher = { }); return [initialState, action]; } - var boundAction$25 = action.bind(null, initialState); + var boundAction$23 = action.bind(null, initialState); return [ initialState, function (payload) { - boundAction$25(payload); + boundAction$23(payload); } ]; } @@ -3425,7 +3282,150 @@ var HooksDispatcher = { throw Error(formatProdErrorMessage(248)); } }, - ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher, + prefix; +function describeBuiltInComponentFrame(name) { + if (void 0 === prefix) + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = (match && match[1]) || ""; + } + return "\n" + prefix + name; +} +var reentry = !1; +function describeNativeComponentFrame(fn, construct) { + if (!fn || reentry) return ""; + reentry = !0; + var previousPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = void 0; + var RunInRootFrame = { + DetermineComponentFrameRoot: function () { + try { + if (construct) { + var Fake = function () { + throw Error(); + }; + Object.defineProperty(Fake.prototype, "props", { + set: function () { + throw Error(); + } + }); + if ("object" === typeof Reflect && Reflect.construct) { + try { + Reflect.construct(Fake, []); + } catch (x) { + var control = x; + } + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x$25) { + control = x$25; + } + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x$26) { + control = x$26; + } + (Fake = fn()) && + "function" === typeof Fake.catch && + Fake.catch(function () {}); + } + } catch (sample) { + if (sample && control && "string" === typeof sample.stack) + return [sample.stack, control.stack]; + } + return [null, null]; + } + }; + RunInRootFrame.DetermineComponentFrameRoot.displayName = + "DetermineComponentFrameRoot"; + var namePropDescriptor = Object.getOwnPropertyDescriptor( + RunInRootFrame.DetermineComponentFrameRoot, + "name" + ); + namePropDescriptor && + namePropDescriptor.configurable && + Object.defineProperty(RunInRootFrame.DetermineComponentFrameRoot, "name", { + value: "DetermineComponentFrameRoot" + }); + try { + var _RunInRootFrame$Deter = RunInRootFrame.DetermineComponentFrameRoot(), + sampleStack = _RunInRootFrame$Deter[0], + controlStack = _RunInRootFrame$Deter[1]; + if (sampleStack && controlStack) { + var sampleLines = sampleStack.split("\n"), + controlLines = controlStack.split("\n"); + for ( + namePropDescriptor = RunInRootFrame = 0; + RunInRootFrame < sampleLines.length && + !sampleLines[RunInRootFrame].includes("DetermineComponentFrameRoot"); + + ) + RunInRootFrame++; + for ( + ; + namePropDescriptor < controlLines.length && + !controlLines[namePropDescriptor].includes( + "DetermineComponentFrameRoot" + ); + + ) + namePropDescriptor++; + if ( + RunInRootFrame === sampleLines.length || + namePropDescriptor === controlLines.length + ) + for ( + RunInRootFrame = sampleLines.length - 1, + namePropDescriptor = controlLines.length - 1; + 1 <= RunInRootFrame && + 0 <= namePropDescriptor && + sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]; + + ) + namePropDescriptor--; + for ( + ; + 1 <= RunInRootFrame && 0 <= namePropDescriptor; + RunInRootFrame--, namePropDescriptor-- + ) + if (sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]) { + if (1 !== RunInRootFrame || 1 !== namePropDescriptor) { + do + if ( + (RunInRootFrame--, + namePropDescriptor--, + 0 > namePropDescriptor || + sampleLines[RunInRootFrame] !== + controlLines[namePropDescriptor]) + ) { + var frame = + "\n" + + sampleLines[RunInRootFrame].replace(" at new ", " at "); + fn.displayName && + frame.includes("") && + (frame = frame.replace("", fn.displayName)); + return frame; + } + while (1 <= RunInRootFrame && 0 <= namePropDescriptor); + } + break; + } + } + } finally { + (reentry = !1), (Error.prepareStackTrace = previousPrepareStackTrace); + } + return (previousPrepareStackTrace = fn ? fn.displayName || fn.name : "") + ? describeBuiltInComponentFrame(previousPrepareStackTrace) + : ""; +} +var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher, ReactCurrentCache = ReactSharedInternals.ReactCurrentCache; function defaultErrorHandler(error) { console.error(error); @@ -5675,4 +5675,4 @@ exports.renderToString = function (children, options) { 'The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server' ); }; -exports.version = "18.3.0-www-classic-14b4f2b8"; +exports.version = "18.3.0-www-classic-abb496f0"; diff --git a/compiled/facebook-www/ReactDOMServer-prod.modern.js b/compiled/facebook-www/ReactDOMServer-prod.modern.js index e4aada38fcc17..b9486ac967309 100644 --- a/compiled/facebook-www/ReactDOMServer-prod.modern.js +++ b/compiled/facebook-www/ReactDOMServer-prod.modern.js @@ -2794,149 +2794,6 @@ function getComponentNameFromType(type) { } return null; } -var prefix; -function describeBuiltInComponentFrame(name) { - if (void 0 === prefix) - try { - throw Error(); - } catch (x) { - var match = x.stack.trim().match(/\n( *(at )?)/); - prefix = (match && match[1]) || ""; - } - return "\n" + prefix + name; -} -var reentry = !1; -function describeNativeComponentFrame(fn, construct) { - if (!fn || reentry) return ""; - reentry = !0; - var previousPrepareStackTrace = Error.prepareStackTrace; - Error.prepareStackTrace = void 0; - var RunInRootFrame = { - DetermineComponentFrameRoot: function () { - try { - if (construct) { - var Fake = function () { - throw Error(); - }; - Object.defineProperty(Fake.prototype, "props", { - set: function () { - throw Error(); - } - }); - if ("object" === typeof Reflect && Reflect.construct) { - try { - Reflect.construct(Fake, []); - } catch (x) { - var control = x; - } - Reflect.construct(fn, [], Fake); - } else { - try { - Fake.call(); - } catch (x$19) { - control = x$19; - } - fn.call(Fake.prototype); - } - } else { - try { - throw Error(); - } catch (x$20) { - control = x$20; - } - (Fake = fn()) && - "function" === typeof Fake.catch && - Fake.catch(function () {}); - } - } catch (sample) { - if (sample && control && "string" === typeof sample.stack) - return [sample.stack, control.stack]; - } - return [null, null]; - } - }; - RunInRootFrame.DetermineComponentFrameRoot.displayName = - "DetermineComponentFrameRoot"; - var namePropDescriptor = Object.getOwnPropertyDescriptor( - RunInRootFrame.DetermineComponentFrameRoot, - "name" - ); - namePropDescriptor && - namePropDescriptor.configurable && - Object.defineProperty(RunInRootFrame.DetermineComponentFrameRoot, "name", { - value: "DetermineComponentFrameRoot" - }); - try { - var _RunInRootFrame$Deter = RunInRootFrame.DetermineComponentFrameRoot(), - sampleStack = _RunInRootFrame$Deter[0], - controlStack = _RunInRootFrame$Deter[1]; - if (sampleStack && controlStack) { - var sampleLines = sampleStack.split("\n"), - controlLines = controlStack.split("\n"); - for ( - namePropDescriptor = RunInRootFrame = 0; - RunInRootFrame < sampleLines.length && - !sampleLines[RunInRootFrame].includes("DetermineComponentFrameRoot"); - - ) - RunInRootFrame++; - for ( - ; - namePropDescriptor < controlLines.length && - !controlLines[namePropDescriptor].includes( - "DetermineComponentFrameRoot" - ); - - ) - namePropDescriptor++; - if ( - RunInRootFrame === sampleLines.length || - namePropDescriptor === controlLines.length - ) - for ( - RunInRootFrame = sampleLines.length - 1, - namePropDescriptor = controlLines.length - 1; - 1 <= RunInRootFrame && - 0 <= namePropDescriptor && - sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]; - - ) - namePropDescriptor--; - for ( - ; - 1 <= RunInRootFrame && 0 <= namePropDescriptor; - RunInRootFrame--, namePropDescriptor-- - ) - if (sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]) { - if (1 !== RunInRootFrame || 1 !== namePropDescriptor) { - do - if ( - (RunInRootFrame--, - namePropDescriptor--, - 0 > namePropDescriptor || - sampleLines[RunInRootFrame] !== - controlLines[namePropDescriptor]) - ) { - var frame = - "\n" + - sampleLines[RunInRootFrame].replace(" at new ", " at "); - fn.displayName && - frame.includes("") && - (frame = frame.replace("", fn.displayName)); - return frame; - } - while (1 <= RunInRootFrame && 0 <= namePropDescriptor); - } - break; - } - } - } finally { - (reentry = !1), (Error.prepareStackTrace = previousPrepareStackTrace); - } - return (previousPrepareStackTrace = fn ? fn.displayName || fn.name : "") - ? describeBuiltInComponentFrame(previousPrepareStackTrace) - : ""; -} var emptyContextObject = {}, currentActiveSnapshot = null; function popToNearestCommonAncestor(prev, next) { @@ -3399,11 +3256,11 @@ var HooksDispatcher = { }); return [initialState, action]; } - var boundAction$25 = action.bind(null, initialState); + var boundAction$23 = action.bind(null, initialState); return [ initialState, function (payload) { - boundAction$25(payload); + boundAction$23(payload); } ]; } @@ -3417,7 +3274,150 @@ var HooksDispatcher = { throw Error(formatProdErrorMessage(248)); } }, - ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher, + prefix; +function describeBuiltInComponentFrame(name) { + if (void 0 === prefix) + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = (match && match[1]) || ""; + } + return "\n" + prefix + name; +} +var reentry = !1; +function describeNativeComponentFrame(fn, construct) { + if (!fn || reentry) return ""; + reentry = !0; + var previousPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = void 0; + var RunInRootFrame = { + DetermineComponentFrameRoot: function () { + try { + if (construct) { + var Fake = function () { + throw Error(); + }; + Object.defineProperty(Fake.prototype, "props", { + set: function () { + throw Error(); + } + }); + if ("object" === typeof Reflect && Reflect.construct) { + try { + Reflect.construct(Fake, []); + } catch (x) { + var control = x; + } + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x$25) { + control = x$25; + } + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x$26) { + control = x$26; + } + (Fake = fn()) && + "function" === typeof Fake.catch && + Fake.catch(function () {}); + } + } catch (sample) { + if (sample && control && "string" === typeof sample.stack) + return [sample.stack, control.stack]; + } + return [null, null]; + } + }; + RunInRootFrame.DetermineComponentFrameRoot.displayName = + "DetermineComponentFrameRoot"; + var namePropDescriptor = Object.getOwnPropertyDescriptor( + RunInRootFrame.DetermineComponentFrameRoot, + "name" + ); + namePropDescriptor && + namePropDescriptor.configurable && + Object.defineProperty(RunInRootFrame.DetermineComponentFrameRoot, "name", { + value: "DetermineComponentFrameRoot" + }); + try { + var _RunInRootFrame$Deter = RunInRootFrame.DetermineComponentFrameRoot(), + sampleStack = _RunInRootFrame$Deter[0], + controlStack = _RunInRootFrame$Deter[1]; + if (sampleStack && controlStack) { + var sampleLines = sampleStack.split("\n"), + controlLines = controlStack.split("\n"); + for ( + namePropDescriptor = RunInRootFrame = 0; + RunInRootFrame < sampleLines.length && + !sampleLines[RunInRootFrame].includes("DetermineComponentFrameRoot"); + + ) + RunInRootFrame++; + for ( + ; + namePropDescriptor < controlLines.length && + !controlLines[namePropDescriptor].includes( + "DetermineComponentFrameRoot" + ); + + ) + namePropDescriptor++; + if ( + RunInRootFrame === sampleLines.length || + namePropDescriptor === controlLines.length + ) + for ( + RunInRootFrame = sampleLines.length - 1, + namePropDescriptor = controlLines.length - 1; + 1 <= RunInRootFrame && + 0 <= namePropDescriptor && + sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]; + + ) + namePropDescriptor--; + for ( + ; + 1 <= RunInRootFrame && 0 <= namePropDescriptor; + RunInRootFrame--, namePropDescriptor-- + ) + if (sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]) { + if (1 !== RunInRootFrame || 1 !== namePropDescriptor) { + do + if ( + (RunInRootFrame--, + namePropDescriptor--, + 0 > namePropDescriptor || + sampleLines[RunInRootFrame] !== + controlLines[namePropDescriptor]) + ) { + var frame = + "\n" + + sampleLines[RunInRootFrame].replace(" at new ", " at "); + fn.displayName && + frame.includes("") && + (frame = frame.replace("", fn.displayName)); + return frame; + } + while (1 <= RunInRootFrame && 0 <= namePropDescriptor); + } + break; + } + } + } finally { + (reentry = !1), (Error.prepareStackTrace = previousPrepareStackTrace); + } + return (previousPrepareStackTrace = fn ? fn.displayName || fn.name : "") + ? describeBuiltInComponentFrame(previousPrepareStackTrace) + : ""; +} +var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher, ReactCurrentCache = ReactSharedInternals.ReactCurrentCache; function defaultErrorHandler(error) { console.error(error); @@ -5634,4 +5634,4 @@ exports.renderToString = function (children, options) { 'The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server' ); }; -exports.version = "18.3.0-www-modern-aad78460"; +exports.version = "18.3.0-www-modern-96bf6a25"; diff --git a/compiled/facebook-www/ReactDOMServerStreaming-dev.modern.js b/compiled/facebook-www/ReactDOMServerStreaming-dev.modern.js index 53089177a9bfd..e10b4fbee4edd 100644 --- a/compiled/facebook-www/ReactDOMServerStreaming-dev.modern.js +++ b/compiled/facebook-www/ReactDOMServerStreaming-dev.modern.js @@ -8476,2366 +8476,2366 @@ if (__DEV__) { return null; } - // Helpers to patch console.logs to avoid logging during side-effect free - // replaying on render function. This currently only patches the object - // lazily which won't cover if the log function was extracted eagerly. - // We could also eagerly patch the method. - var disabledDepth = 0; - var prevLog; - var prevInfo; - var prevWarn; - var prevError; - var prevGroup; - var prevGroupCollapsed; - var prevGroupEnd; + var emptyContextObject = {}; - function disabledLog() {} + { + Object.freeze(emptyContextObject); + } - disabledLog.__reactDisabledLog = true; - function disableLogs() { - { - if (disabledDepth === 0) { - /* eslint-disable react-internal/no-production-logging */ - prevLog = console.log; - prevInfo = console.info; - prevWarn = console.warn; - prevError = console.error; - prevGroup = console.group; - prevGroupCollapsed = console.groupCollapsed; - prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 + var rendererSigil; - var props = { - configurable: true, - enumerable: true, - value: disabledLog, - writable: true - }; // $FlowFixMe[cannot-write] Flow thinks console is immutable. + { + // Use this to detect multiple renderers using the same context + rendererSigil = {}; + } // Used to store the parent path of all context overrides in a shared linked list. + // Forming a reverse tree. + // The structure of a context snapshot is an implementation of this file. + // Currently, it's implemented as tracking the current active node. - Object.defineProperties(console, { - info: props, - log: props, - warn: props, - error: props, - group: props, - groupCollapsed: props, - groupEnd: props - }); - /* eslint-enable react-internal/no-production-logging */ - } + var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances. + // This global (actually thread local) state represents what state all those "current", + // fields are currently in. - disabledDepth++; + var currentActiveSnapshot = null; + + function popNode(prev) { + { + prev.context._currentValue = prev.parentValue; } } - function reenableLogs() { + + function pushNode(next) { { - disabledDepth--; + next.context._currentValue = next.value; + } + } - if (disabledDepth === 0) { - /* eslint-disable react-internal/no-production-logging */ - var props = { - configurable: true, - enumerable: true, - writable: true - }; // $FlowFixMe[cannot-write] Flow thinks console is immutable. + function popToNearestCommonAncestor(prev, next) { + if (prev === next); + else { + popNode(prev); + var parentPrev = prev.parent; + var parentNext = next.parent; - Object.defineProperties(console, { - log: assign({}, props, { - value: prevLog - }), - info: assign({}, props, { - value: prevInfo - }), - warn: assign({}, props, { - value: prevWarn - }), - error: assign({}, props, { - value: prevError - }), - group: assign({}, props, { - value: prevGroup - }), - groupCollapsed: assign({}, props, { - value: prevGroupCollapsed - }), - groupEnd: assign({}, props, { - value: prevGroupEnd - }) - }); - /* eslint-enable react-internal/no-production-logging */ - } + if (parentPrev === null) { + if (parentNext !== null) { + throw new Error( + "The stacks must reach the root at the same time. This is a bug in React." + ); + } + } else { + if (parentNext === null) { + throw new Error( + "The stacks must reach the root at the same time. This is a bug in React." + ); + } - if (disabledDepth < 0) { - error( - "disabledDepth fell below zero. " + - "This is a bug in React. Please file an issue." - ); - } + popToNearestCommonAncestor(parentPrev, parentNext); + } // On the way back, we push the new ones that weren't common. + + pushNode(next); } } - var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; - var prefix; - function describeBuiltInComponentFrame(name, ownerFn) { - { - if (prefix === undefined) { - // Extract the VM specific prefix used by each line. - try { - throw Error(); - } catch (x) { - var match = x.stack.trim().match(/\n( *(at )?)/); - prefix = (match && match[1]) || ""; - } - } // We use the prefix to ensure our stacks line up with native stack frames. + function popAllPrevious(prev) { + popNode(prev); + var parentPrev = prev.parent; - return "\n" + prefix + name; + if (parentPrev !== null) { + popAllPrevious(parentPrev); } } - var reentry = false; - var componentFrameCache; - { - var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; - componentFrameCache = new PossiblyWeakMap(); - } - /** - * Leverages native browser/VM stack frames to get proper details (e.g. - * filename, line + col number) for a single component in a component stack. We - * do this by: - * (1) throwing and catching an error in the function - this will be our - * control error. - * (2) calling the component which will eventually throw an error that we'll - * catch - this will be our sample error. - * (3) diffing the control and sample error stacks to find the stack frame - * which represents our component. - */ + function pushAllNext(next) { + var parentNext = next.parent; - function describeNativeComponentFrame(fn, construct) { - // If something asked for a stack inside a fake render, it should get ignored. - if (!fn || reentry) { - return ""; + if (parentNext !== null) { + pushAllNext(parentNext); } - { - var frame = componentFrameCache.get(fn); + pushNode(next); + } - if (frame !== undefined) { - return frame; - } + function popPreviousToCommonLevel(prev, next) { + popNode(prev); + var parentPrev = prev.parent; + + if (parentPrev === null) { + throw new Error( + "The depth must equal at least at zero before reaching the root. This is a bug in React." + ); } - reentry = true; - var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe[incompatible-type] It does accept undefined. + if (parentPrev.depth === next.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(parentPrev, next); + } else { + // We must still be deeper. + popPreviousToCommonLevel(parentPrev, next); + } + } - Error.prepareStackTrace = undefined; - var previousDispatcher; + function popNextToCommonLevel(prev, next) { + var parentNext = next.parent; - { - previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function - // for warnings. + if (parentNext === null) { + throw new Error( + "The depth must equal at least at zero before reaching the root. This is a bug in React." + ); + } - ReactCurrentDispatcher$1.current = null; - disableLogs(); + if (prev.depth === parentNext.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(prev, parentNext); + } else { + // We must still be deeper. + popNextToCommonLevel(prev, parentNext); } - /** - * Finding a common stack frame between sample and control errors can be - * tricky given the different types and levels of stack trace truncation from - * different JS VMs. So instead we'll attempt to control what that common - * frame should be through this object method: - * Having both the sample and control errors be in the function under the - * `DescribeNativeComponentFrameRoot` property, + setting the `name` and - * `displayName` properties of the function ensures that a stack - * frame exists that has the method name `DescribeNativeComponentFrameRoot` in - * it for both control and sample stacks. - */ - var RunInRootFrame = { - DetermineComponentFrameRoot: function () { - var control; + pushNode(next); + } // Perform context switching to the new snapshot. + // To make it cheap to read many contexts, while not suspending, we make the switch eagerly by + // updating all the context's current values. That way reads, always just read the current value. + // At the cost of updating contexts even if they're never read by this subtree. - try { - // This should throw. - if (construct) { - // Something should be setting the props in the constructor. - var Fake = function () { - throw Error(); - }; // $FlowFixMe[prop-missing] + function switchContext(newSnapshot) { + // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack. + // We also need to update any new contexts that are now on the stack with the deepest value. + // The easiest way to update new contexts is to just reapply them in reverse order from the + // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack + // for that. Therefore this algorithm is recursive. + // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go. + // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go. + // 3) Then we reapply new contexts on the way back up the stack. + var prev = currentActiveSnapshot; + var next = newSnapshot; - Object.defineProperty(Fake.prototype, "props", { - set: function () { - // We use a throwing setter instead of frozen or non-writable props - // because that won't throw in a non-strict mode function. - throw Error(); - } - }); - - if (typeof Reflect === "object" && Reflect.construct) { - // We construct a different control for this case to include any extra - // frames added by the construct call. - try { - Reflect.construct(Fake, []); - } catch (x) { - control = x; - } - - Reflect.construct(fn, [], Fake); - } else { - try { - Fake.call(); - } catch (x) { - control = x; - } // $FlowFixMe[prop-missing] found when upgrading Flow + if (prev !== next) { + if (prev === null) { + // $FlowFixMe[incompatible-call]: This has to be non-null since it's not equal to prev. + pushAllNext(next); + } else if (next === null) { + popAllPrevious(prev); + } else if (prev.depth === next.depth) { + popToNearestCommonAncestor(prev, next); + } else if (prev.depth > next.depth) { + popPreviousToCommonLevel(prev, next); + } else { + popNextToCommonLevel(prev, next); + } - fn.call(Fake.prototype); - } - } else { - try { - throw Error(); - } catch (x) { - control = x; - } // TODO(luna): This will currently only throw if the function component - // tries to access React/ReactDOM/props. We should probably make this throw - // in simple components too + currentActiveSnapshot = next; + } + } + function pushProvider(context, nextValue) { + var prevValue; - var maybePromise = fn(); // If the function component returns a promise, it's likely an async - // component, which we don't yet support. Attach a noop catch handler to - // silence the error. - // TODO: Implement component stacks for async client components? + { + prevValue = context._currentValue; + context._currentValue = nextValue; - if (maybePromise && typeof maybePromise.catch === "function") { - maybePromise.catch(function () {}); - } - } - } catch (sample) { - // This is inlined manually because closure doesn't do it for us. - if (sample && control && typeof sample.stack === "string") { - return [sample.stack, control.stack]; - } + { + if ( + context._currentRenderer !== undefined && + context._currentRenderer !== null && + context._currentRenderer !== rendererSigil + ) { + error( + "Detected multiple renderers concurrently rendering the " + + "same context provider. This is currently unsupported." + ); } - return [null, null]; + context._currentRenderer = rendererSigil; } - }; // $FlowFixMe[prop-missing] + } - RunInRootFrame.DetermineComponentFrameRoot.displayName = - "DetermineComponentFrameRoot"; - var namePropDescriptor = Object.getOwnPropertyDescriptor( - RunInRootFrame.DetermineComponentFrameRoot, - "name" - ); // Before ES6, the `name` property was not configurable. + var prevNode = currentActiveSnapshot; + var newNode = { + parent: prevNode, + depth: prevNode === null ? 0 : prevNode.depth + 1, + context: context, + parentValue: prevValue, + value: nextValue + }; + currentActiveSnapshot = newNode; + return newNode; + } + function popProvider(context) { + var prevSnapshot = currentActiveSnapshot; - if (namePropDescriptor && namePropDescriptor.configurable) { - // V8 utilizes a function's `name` property when generating a stack trace. - Object.defineProperty( - RunInRootFrame.DetermineComponentFrameRoot, // Configurable properties can be updated even if its writable descriptor - // is set to `false`. - // $FlowFixMe[cannot-write] - "name", - { - value: "DetermineComponentFrameRoot" - } + if (prevSnapshot === null) { + throw new Error( + "Tried to pop a Context at the root of the app. This is a bug in React." ); } - try { - var _RunInRootFrame$Deter = - RunInRootFrame.DetermineComponentFrameRoot(), - sampleStack = _RunInRootFrame$Deter[0], - controlStack = _RunInRootFrame$Deter[1]; + { + if (prevSnapshot.context !== context) { + error( + "The parent context is not the expected context. This is probably a bug in React." + ); + } + } - if (sampleStack && controlStack) { - // This extracts the first frame from the sample that isn't also in the control. - // Skipping one frame that we assume is the frame that calls the two. - var sampleLines = sampleStack.split("\n"); - var controlLines = controlStack.split("\n"); - var s = 0; - var c = 0; + { + var value = prevSnapshot.parentValue; + prevSnapshot.context._currentValue = value; - while ( - s < sampleLines.length && - !sampleLines[s].includes("DetermineComponentFrameRoot") + { + if ( + context._currentRenderer !== undefined && + context._currentRenderer !== null && + context._currentRenderer !== rendererSigil ) { - s++; + error( + "Detected multiple renderers concurrently rendering the " + + "same context provider. This is currently unsupported." + ); } - while ( - c < controlLines.length && - !controlLines[c].includes("DetermineComponentFrameRoot") - ) { - c++; - } // We couldn't find our intentionally injected common root frame, attempt - // to find another common root frame by search from the bottom of the - // control stack... + context._currentRenderer = rendererSigil; + } + } - if (s === sampleLines.length || c === controlLines.length) { - s = sampleLines.length - 1; - c = controlLines.length - 1; + return (currentActiveSnapshot = prevSnapshot.parent); + } + function getActiveContext() { + return currentActiveSnapshot; + } + function readContext$1(context) { + var value = context._currentValue; + return value; + } - while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { - // We expect at least one stack frame to be shared. - // Typically this will be the root most one. However, stack frames may be - // cut off due to maximum stack limits. In this case, one maybe cut off - // earlier than the other. We assume that the sample is longer or the same - // and there for cut off earlier. So we should find the root most frame in - // the sample somewhere in the control. - c--; - } - } + /** + * `ReactInstanceMap` maintains a mapping from a public facing stateful + * instance (key) and the internal representation (value). This allows public + * methods to accept the user facing instance as an argument and map them back + * to internal methods. + * + * Note that this module is currently shared and assumed to be stateless. + * If this becomes an actual Map, that will break. + */ + function get(key) { + return key._reactInternals; + } + function set(key, value) { + key._reactInternals = value; + } - for (; s >= 1 && c >= 0; s--, c--) { - // Next we find the first one that isn't the same which should be the - // frame that called our sample function and the control. - if (sampleLines[s] !== controlLines[c]) { - // In V8, the first line is describing the message but other VMs don't. - // If we're about to return the first line, and the control is also on the same - // line, that's a pretty good indicator that our sample threw at same line as - // the control. I.e. before we entered the sample frame. So we ignore this result. - // This can happen if you passed a class to function component, or non-function. - if (s !== 1 || c !== 1) { - do { - s--; - c--; // We may still have similar intermediate frames from the construct call. - // The next one that isn't the same should be our match though. + var didWarnAboutNoopUpdateForComponent = {}; + var didWarnAboutDeprecatedWillMount = {}; + var didWarnAboutUninitializedState; + var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; + var didWarnAboutLegacyLifecyclesAndDerivedState; + var didWarnAboutUndefinedDerivedState; + var didWarnAboutDirectlyAssigningPropsToState; + var didWarnAboutInvalidateContextType; + var didWarnOnInvalidCallback; - if (c < 0 || sampleLines[s] !== controlLines[c]) { - // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. - var _frame = - "\n" + sampleLines[s].replace(" at new ", " at "); // If our component frame is labeled "" - // but we have a user-provided "displayName" - // splice it in to make the stack more readable. + { + didWarnAboutUninitializedState = new Set(); + didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set(); + didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); + didWarnAboutDirectlyAssigningPropsToState = new Set(); + didWarnAboutUndefinedDerivedState = new Set(); + didWarnAboutInvalidateContextType = new Set(); + didWarnOnInvalidCallback = new Set(); + } - if (fn.displayName && _frame.includes("")) { - _frame = _frame.replace("", fn.displayName); - } + function warnOnInvalidCallback(callback, callerName) { + { + if (callback === null || typeof callback === "function") { + return; + } - if (true) { - if (typeof fn === "function") { - componentFrameCache.set(fn, _frame); - } - } // Return the line we found. + var key = callerName + "_" + callback; - return _frame; - } - } while (s >= 1 && c >= 0); - } + if (!didWarnOnInvalidCallback.has(key)) { + didWarnOnInvalidCallback.add(key); - break; - } - } - } - } finally { - reentry = false; - - { - ReactCurrentDispatcher$1.current = previousDispatcher; - reenableLogs(); - } - - Error.prepareStackTrace = previousPrepareStackTrace; - } // Fallback to just using the name if we couldn't make it throw. - - var name = fn ? fn.displayName || fn.name : ""; - var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; - - { - if (typeof fn === "function") { - componentFrameCache.set(fn, syntheticFrame); + error( + "%s(...): Expected the last optional `callback` argument to be a " + + "function. Instead received: %s.", + callerName, + callback + ); } } - - return syntheticFrame; } - function describeClassComponentFrame(ctor, ownerFn) { - { - return describeNativeComponentFrame(ctor, true); - } - } - function describeFunctionComponentFrame(fn, ownerFn) { + function warnOnUndefinedDerivedState(type, partialState) { { - return describeNativeComponentFrame(fn, false); - } - } + if (partialState === undefined) { + var componentName = getComponentNameFromType(type) || "Component"; - var emptyContextObject = {}; + if (!didWarnAboutUndefinedDerivedState.has(componentName)) { + didWarnAboutUndefinedDerivedState.add(componentName); - { - Object.freeze(emptyContextObject); + error( + "%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. " + + "You have returned undefined.", + componentName + ); + } + } + } } - var rendererSigil; - - { - // Use this to detect multiple renderers using the same context - rendererSigil = {}; - } // Used to store the parent path of all context overrides in a shared linked list. - // Forming a reverse tree. - // The structure of a context snapshot is an implementation of this file. - // Currently, it's implemented as tracking the current active node. - - var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances. - // This global (actually thread local) state represents what state all those "current", - // fields are currently in. + function warnNoop(publicInstance, callerName) { + { + var _constructor = publicInstance.constructor; + var componentName = + (_constructor && getComponentNameFromType(_constructor)) || + "ReactClass"; + var warningKey = componentName + "." + callerName; - var currentActiveSnapshot = null; + if (didWarnAboutNoopUpdateForComponent[warningKey]) { + return; + } - function popNode(prev) { - { - prev.context._currentValue = prev.parentValue; - } - } + error( + "%s(...): Can only update a mounting component. " + + "This usually means you called %s() outside componentWillMount() on the server. " + + "This is a no-op.\n\nPlease check the code for the %s component.", + callerName, + callerName, + componentName + ); - function pushNode(next) { - { - next.context._currentValue = next.value; + didWarnAboutNoopUpdateForComponent[warningKey] = true; } } - function popToNearestCommonAncestor(prev, next) { - if (prev === next); - else { - popNode(prev); - var parentPrev = prev.parent; - var parentNext = next.parent; + var classComponentUpdater = { + isMounted: function (inst) { + return false; + }, + // $FlowFixMe[missing-local-annot] + enqueueSetState: function (inst, payload, callback) { + var internals = get(inst); - if (parentPrev === null) { - if (parentNext !== null) { - throw new Error( - "The stacks must reach the root at the same time. This is a bug in React." - ); - } + if (internals.queue === null) { + warnNoop(inst, "setState"); } else { - if (parentNext === null) { - throw new Error( - "The stacks must reach the root at the same time. This is a bug in React." - ); + internals.queue.push(payload); + + { + if (callback !== undefined && callback !== null) { + warnOnInvalidCallback(callback, "setState"); + } } + } + }, + enqueueReplaceState: function (inst, payload, callback) { + var internals = get(inst); + internals.replace = true; + internals.queue = [payload]; - popToNearestCommonAncestor(parentPrev, parentNext); - } // On the way back, we push the new ones that weren't common. + { + if (callback !== undefined && callback !== null) { + warnOnInvalidCallback(callback, "setState"); + } + } + }, + // $FlowFixMe[missing-local-annot] + enqueueForceUpdate: function (inst, callback) { + var internals = get(inst); - pushNode(next); + if (internals.queue === null) { + warnNoop(inst, "forceUpdate"); + } else { + { + if (callback !== undefined && callback !== null) { + warnOnInvalidCallback(callback, "setState"); + } + } + } } - } + }; - function popAllPrevious(prev) { - popNode(prev); - var parentPrev = prev.parent; + function applyDerivedStateFromProps( + instance, + ctor, + getDerivedStateFromProps, + prevState, + nextProps + ) { + var partialState = getDerivedStateFromProps(nextProps, prevState); - if (parentPrev !== null) { - popAllPrevious(parentPrev); - } + { + warnOnUndefinedDerivedState(ctor, partialState); + } // Merge the partial state and the previous state. + + var newState = + partialState === null || partialState === undefined + ? prevState + : assign({}, prevState, partialState); + return newState; } - function pushAllNext(next) { - var parentNext = next.parent; + function constructClassInstance(ctor, props, maskedLegacyContext) { + var context = emptyContextObject; + var contextType = ctor.contextType; - if (parentNext !== null) { - pushAllNext(parentNext); - } + { + if ("contextType" in ctor) { + var isValid = // Allow null for conditional declaration + contextType === null || + (contextType !== undefined && + contextType.$$typeof === REACT_CONTEXT_TYPE); - pushNode(next); - } + if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { + didWarnAboutInvalidateContextType.add(ctor); + var addendum = ""; - function popPreviousToCommonLevel(prev, next) { - popNode(prev); - var parentPrev = prev.parent; + if (contextType === undefined) { + addendum = + " However, it is set to undefined. " + + "This can be caused by a typo or by mixing up named and default imports. " + + "This can also happen due to a circular dependency, so " + + "try moving the createContext() call to a separate file."; + } else if (typeof contextType !== "object") { + addendum = " However, it is set to a " + typeof contextType + "."; + } else if (contextType.$$typeof === REACT_CONSUMER_TYPE) { + addendum = + " Did you accidentally pass the Context.Consumer instead?"; + } else { + addendum = + " However, it is set to an object with keys {" + + Object.keys(contextType).join(", ") + + "}."; + } - if (parentPrev === null) { - throw new Error( - "The depth must equal at least at zero before reaching the root. This is a bug in React." - ); + error( + "%s defines an invalid contextType. " + + "contextType should point to the Context object returned by React.createContext().%s", + getComponentNameFromType(ctor) || "Component", + addendum + ); + } + } } - if (parentPrev.depth === next.depth) { - // We found the same level. Now we just need to find a shared ancestor. - popToNearestCommonAncestor(parentPrev, next); - } else { - // We must still be deeper. - popPreviousToCommonLevel(parentPrev, next); + if (typeof contextType === "object" && contextType !== null) { + context = readContext$1(contextType); } - } - function popNextToCommonLevel(prev, next) { - var parentNext = next.parent; + var instance = new ctor(props, context); - if (parentNext === null) { - throw new Error( - "The depth must equal at least at zero before reaching the root. This is a bug in React." - ); - } + { + if ( + typeof ctor.getDerivedStateFromProps === "function" && + (instance.state === null || instance.state === undefined) + ) { + var componentName = getComponentNameFromType(ctor) || "Component"; - if (prev.depth === parentNext.depth) { - // We found the same level. Now we just need to find a shared ancestor. - popToNearestCommonAncestor(prev, parentNext); - } else { - // We must still be deeper. - popNextToCommonLevel(prev, parentNext); - } + if (!didWarnAboutUninitializedState.has(componentName)) { + didWarnAboutUninitializedState.add(componentName); - pushNode(next); - } // Perform context switching to the new snapshot. - // To make it cheap to read many contexts, while not suspending, we make the switch eagerly by - // updating all the context's current values. That way reads, always just read the current value. - // At the cost of updating contexts even if they're never read by this subtree. + error( + "`%s` uses `getDerivedStateFromProps` but its initial state is " + + "%s. This is not recommended. Instead, define the initial state by " + + "assigning an object to `this.state` in the constructor of `%s`. " + + "This ensures that `getDerivedStateFromProps` arguments have a consistent shape.", + componentName, + instance.state === null ? "null" : "undefined", + componentName + ); + } + } // If new component APIs are defined, "unsafe" lifecycles won't be called. + // Warn about these lifecycles if they are present. + // Don't warn about react-lifecycles-compat polyfilled methods though. - function switchContext(newSnapshot) { - // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack. - // We also need to update any new contexts that are now on the stack with the deepest value. - // The easiest way to update new contexts is to just reapply them in reverse order from the - // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack - // for that. Therefore this algorithm is recursive. - // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go. - // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go. - // 3) Then we reapply new contexts on the way back up the stack. - var prev = currentActiveSnapshot; - var next = newSnapshot; + if ( + typeof ctor.getDerivedStateFromProps === "function" || + typeof instance.getSnapshotBeforeUpdate === "function" + ) { + var foundWillMountName = null; + var foundWillReceivePropsName = null; + var foundWillUpdateName = null; - if (prev !== next) { - if (prev === null) { - // $FlowFixMe[incompatible-call]: This has to be non-null since it's not equal to prev. - pushAllNext(next); - } else if (next === null) { - popAllPrevious(prev); - } else if (prev.depth === next.depth) { - popToNearestCommonAncestor(prev, next); - } else if (prev.depth > next.depth) { - popPreviousToCommonLevel(prev, next); - } else { - popNextToCommonLevel(prev, next); - } + if ( + typeof instance.componentWillMount === "function" && + instance.componentWillMount.__suppressDeprecationWarning !== true + ) { + foundWillMountName = "componentWillMount"; + } else if (typeof instance.UNSAFE_componentWillMount === "function") { + foundWillMountName = "UNSAFE_componentWillMount"; + } - currentActiveSnapshot = next; + if ( + typeof instance.componentWillReceiveProps === "function" && + instance.componentWillReceiveProps.__suppressDeprecationWarning !== + true + ) { + foundWillReceivePropsName = "componentWillReceiveProps"; + } else if ( + typeof instance.UNSAFE_componentWillReceiveProps === "function" + ) { + foundWillReceivePropsName = "UNSAFE_componentWillReceiveProps"; + } + + if ( + typeof instance.componentWillUpdate === "function" && + instance.componentWillUpdate.__suppressDeprecationWarning !== true + ) { + foundWillUpdateName = "componentWillUpdate"; + } else if ( + typeof instance.UNSAFE_componentWillUpdate === "function" + ) { + foundWillUpdateName = "UNSAFE_componentWillUpdate"; + } + + if ( + foundWillMountName !== null || + foundWillReceivePropsName !== null || + foundWillUpdateName !== null + ) { + var _componentName = getComponentNameFromType(ctor) || "Component"; + + var newApiName = + typeof ctor.getDerivedStateFromProps === "function" + ? "getDerivedStateFromProps()" + : "getSnapshotBeforeUpdate()"; + + if ( + !didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName) + ) { + didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName); + + error( + "Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n" + + "%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n" + + "The above lifecycles should be removed. Learn more about this warning here:\n" + + "https://reactjs.org/link/unsafe-component-lifecycles", + _componentName, + newApiName, + foundWillMountName !== null ? "\n " + foundWillMountName : "", + foundWillReceivePropsName !== null + ? "\n " + foundWillReceivePropsName + : "", + foundWillUpdateName !== null ? "\n " + foundWillUpdateName : "" + ); + } + } + } } + + return instance; } - function pushProvider(context, nextValue) { - var prevValue; + function checkClassInstance(instance, ctor, newProps) { { - prevValue = context._currentValue; - context._currentValue = nextValue; + var name = getComponentNameFromType(ctor) || "Component"; + var renderPresent = instance.render; - { - if ( - context._currentRenderer !== undefined && - context._currentRenderer !== null && - context._currentRenderer !== rendererSigil - ) { + if (!renderPresent) { + if (ctor.prototype && typeof ctor.prototype.render === "function") { error( - "Detected multiple renderers concurrently rendering the " + - "same context provider. This is currently unsupported." + "%s(...): No `render` method found on the returned component " + + "instance: did you accidentally return an object from the constructor?", + name + ); + } else { + error( + "%s(...): No `render` method found on the returned component " + + "instance: you may have forgotten to define `render`.", + name ); } - - context._currentRenderer = rendererSigil; } - } - var prevNode = currentActiveSnapshot; - var newNode = { - parent: prevNode, - depth: prevNode === null ? 0 : prevNode.depth + 1, - context: context, - parentValue: prevValue, - value: nextValue - }; - currentActiveSnapshot = newNode; - return newNode; - } - function popProvider(context) { - var prevSnapshot = currentActiveSnapshot; + if ( + instance.getInitialState && + !instance.getInitialState.isReactClassApproved && + !instance.state + ) { + error( + "getInitialState was defined on %s, a plain JavaScript class. " + + "This is only supported for classes created using React.createClass. " + + "Did you mean to define a state property instead?", + name + ); + } - if (prevSnapshot === null) { - throw new Error( - "Tried to pop a Context at the root of the app. This is a bug in React." - ); - } + if ( + instance.getDefaultProps && + !instance.getDefaultProps.isReactClassApproved + ) { + error( + "getDefaultProps was defined on %s, a plain JavaScript class. " + + "This is only supported for classes created using React.createClass. " + + "Use a static property to define defaultProps instead.", + name + ); + } - { - if (prevSnapshot.context !== context) { + if (instance.propTypes) { error( - "The parent context is not the expected context. This is probably a bug in React." + "propTypes was defined as an instance property on %s. Use a static " + + "property to define propTypes instead.", + name ); } - } - { - var value = prevSnapshot.parentValue; - prevSnapshot.context._currentValue = value; + if (instance.contextType) { + error( + "contextType was defined as an instance property on %s. Use a static " + + "property to define contextType instead.", + name + ); + } { - if ( - context._currentRenderer !== undefined && - context._currentRenderer !== null && - context._currentRenderer !== rendererSigil - ) { + if (ctor.childContextTypes) { error( - "Detected multiple renderers concurrently rendering the " + - "same context provider. This is currently unsupported." + "%s uses the legacy childContextTypes API which is no longer supported. " + + "Use React.createContext() instead.", + name ); } - context._currentRenderer = rendererSigil; + if (ctor.contextTypes) { + error( + "%s uses the legacy contextTypes API which is no longer supported. " + + "Use React.createContext() with static contextType instead.", + name + ); + } } - } - return (currentActiveSnapshot = prevSnapshot.parent); - } - function getActiveContext() { - return currentActiveSnapshot; - } - function readContext$1(context) { - var value = context._currentValue; - return value; - } + if (typeof instance.componentShouldUpdate === "function") { + error( + "%s has a method called " + + "componentShouldUpdate(). Did you mean shouldComponentUpdate()? " + + "The name is phrased as a question because the function is " + + "expected to return a value.", + name + ); + } - /** - * `ReactInstanceMap` maintains a mapping from a public facing stateful - * instance (key) and the internal representation (value). This allows public - * methods to accept the user facing instance as an argument and map them back - * to internal methods. - * - * Note that this module is currently shared and assumed to be stateless. - * If this becomes an actual Map, that will break. - */ - function get(key) { - return key._reactInternals; - } - function set(key, value) { - key._reactInternals = value; - } + if ( + ctor.prototype && + ctor.prototype.isPureReactComponent && + typeof instance.shouldComponentUpdate !== "undefined" + ) { + error( + "%s has a method called shouldComponentUpdate(). " + + "shouldComponentUpdate should not be used when extending React.PureComponent. " + + "Please extend React.Component if shouldComponentUpdate is used.", + getComponentNameFromType(ctor) || "A pure component" + ); + } - var didWarnAboutNoopUpdateForComponent = {}; - var didWarnAboutDeprecatedWillMount = {}; - var didWarnAboutUninitializedState; - var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; - var didWarnAboutLegacyLifecyclesAndDerivedState; - var didWarnAboutUndefinedDerivedState; - var didWarnAboutDirectlyAssigningPropsToState; - var didWarnAboutInvalidateContextType; - var didWarnOnInvalidCallback; + if (typeof instance.componentDidUnmount === "function") { + error( + "%s has a method called " + + "componentDidUnmount(). But there is no such lifecycle method. " + + "Did you mean componentWillUnmount()?", + name + ); + } - { - didWarnAboutUninitializedState = new Set(); - didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set(); - didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); - didWarnAboutDirectlyAssigningPropsToState = new Set(); - didWarnAboutUndefinedDerivedState = new Set(); - didWarnAboutInvalidateContextType = new Set(); - didWarnOnInvalidCallback = new Set(); - } + if (typeof instance.componentDidReceiveProps === "function") { + error( + "%s has a method called " + + "componentDidReceiveProps(). But there is no such lifecycle method. " + + "If you meant to update the state in response to changing props, " + + "use componentWillReceiveProps(). If you meant to fetch data or " + + "run side-effects or mutations after React has updated the UI, use componentDidUpdate().", + name + ); + } - function warnOnInvalidCallback(callback, callerName) { - { - if (callback === null || typeof callback === "function") { - return; + if (typeof instance.componentWillRecieveProps === "function") { + error( + "%s has a method called " + + "componentWillRecieveProps(). Did you mean componentWillReceiveProps()?", + name + ); } - var key = callerName + "_" + callback; + if (typeof instance.UNSAFE_componentWillRecieveProps === "function") { + error( + "%s has a method called " + + "UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?", + name + ); + } - if (!didWarnOnInvalidCallback.has(key)) { - didWarnOnInvalidCallback.add(key); + var hasMutatedProps = instance.props !== newProps; + if (instance.props !== undefined && hasMutatedProps) { error( - "%s(...): Expected the last optional `callback` argument to be a " + - "function. Instead received: %s.", - callerName, - callback + "%s(...): When calling super() in `%s`, make sure to pass " + + "up the same props that your component's constructor was passed.", + name, + name ); } - } - } - function warnOnUndefinedDerivedState(type, partialState) { - { - if (partialState === undefined) { - var componentName = getComponentNameFromType(type) || "Component"; + if (instance.defaultProps) { + error( + "Setting defaultProps as an instance property on %s is not supported and will be ignored." + + " Instead, define defaultProps as a static property on %s.", + name, + name + ); + } - if (!didWarnAboutUndefinedDerivedState.has(componentName)) { - didWarnAboutUndefinedDerivedState.add(componentName); + if ( + typeof instance.getSnapshotBeforeUpdate === "function" && + typeof instance.componentDidUpdate !== "function" && + !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor) + ) { + didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor); - error( - "%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. " + - "You have returned undefined.", - componentName - ); - } + error( + "%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). " + + "This component defines getSnapshotBeforeUpdate() only.", + getComponentNameFromType(ctor) + ); } - } - } - function warnNoop(publicInstance, callerName) { - { - var _constructor = publicInstance.constructor; - var componentName = - (_constructor && getComponentNameFromType(_constructor)) || - "ReactClass"; - var warningKey = componentName + "." + callerName; + if (typeof instance.getDerivedStateFromProps === "function") { + error( + "%s: getDerivedStateFromProps() is defined as an instance method " + + "and will be ignored. Instead, declare it as a static method.", + name + ); + } - if (didWarnAboutNoopUpdateForComponent[warningKey]) { - return; + if (typeof instance.getDerivedStateFromError === "function") { + error( + "%s: getDerivedStateFromError() is defined as an instance method " + + "and will be ignored. Instead, declare it as a static method.", + name + ); } - error( - "%s(...): Can only update a mounting component. " + - "This usually means you called %s() outside componentWillMount() on the server. " + - "This is a no-op.\n\nPlease check the code for the %s component.", - callerName, - callerName, - componentName - ); + if (typeof ctor.getSnapshotBeforeUpdate === "function") { + error( + "%s: getSnapshotBeforeUpdate() is defined as a static method " + + "and will be ignored. Instead, declare it as an instance method.", + name + ); + } - didWarnAboutNoopUpdateForComponent[warningKey] = true; + var state = instance.state; + + if (state && (typeof state !== "object" || isArray(state))) { + error("%s.state: must be set to an object or null", name); + } + + if ( + typeof instance.getChildContext === "function" && + typeof ctor.childContextTypes !== "object" + ) { + error( + "%s.getChildContext(): childContextTypes must be defined in order to " + + "use getChildContext().", + name + ); + } } } - var classComponentUpdater = { - isMounted: function (inst) { - return false; - }, - // $FlowFixMe[missing-local-annot] - enqueueSetState: function (inst, payload, callback) { - var internals = get(inst); + function callComponentWillMount(type, instance) { + var oldState = instance.state; - if (internals.queue === null) { - warnNoop(inst, "setState"); - } else { - internals.queue.push(payload); + if (typeof instance.componentWillMount === "function") { + { + if ( + instance.componentWillMount.__suppressDeprecationWarning !== true + ) { + var componentName = getComponentNameFromType(type) || "Unknown"; - { - if (callback !== undefined && callback !== null) { - warnOnInvalidCallback(callback, "setState"); + if (!didWarnAboutDeprecatedWillMount[componentName]) { + warn( + // keep this warning in sync with ReactStrictModeWarning.js + "componentWillMount has been renamed, and is not recommended for use. " + + "See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n" + + "* Move code from componentWillMount to componentDidMount (preferred in most cases) " + + "or the constructor.\n" + + "\nPlease update the following components: %s", + componentName + ); + + didWarnAboutDeprecatedWillMount[componentName] = true; } } } - }, - enqueueReplaceState: function (inst, payload, callback) { - var internals = get(inst); - internals.replace = true; - internals.queue = [payload]; + instance.componentWillMount(); + } + + if (typeof instance.UNSAFE_componentWillMount === "function") { + instance.UNSAFE_componentWillMount(); + } + + if (oldState !== instance.state) { { - if (callback !== undefined && callback !== null) { - warnOnInvalidCallback(callback, "setState"); - } + error( + "%s.componentWillMount(): Assigning directly to this.state is " + + "deprecated (except inside a component's " + + "constructor). Use setState instead.", + getComponentNameFromType(type) || "Component" + ); } - }, - // $FlowFixMe[missing-local-annot] - enqueueForceUpdate: function (inst, callback) { - var internals = get(inst); - if (internals.queue === null) { - warnNoop(inst, "forceUpdate"); - } else { - { - if (callback !== undefined && callback !== null) { - warnOnInvalidCallback(callback, "setState"); - } - } - } + classComponentUpdater.enqueueReplaceState( + instance, + instance.state, + null + ); } - }; + } - function applyDerivedStateFromProps( - instance, - ctor, - getDerivedStateFromProps, - prevState, - nextProps - ) { - var partialState = getDerivedStateFromProps(nextProps, prevState); - - { - warnOnUndefinedDerivedState(ctor, partialState); - } // Merge the partial state and the previous state. - - var newState = - partialState === null || partialState === undefined - ? prevState - : assign({}, prevState, partialState); - return newState; - } - - function constructClassInstance(ctor, props, maskedLegacyContext) { - var context = emptyContextObject; - var contextType = ctor.contextType; + function processUpdateQueue( + internalInstance, + inst, + props, + maskedLegacyContext + ) { + if ( + internalInstance.queue !== null && + internalInstance.queue.length > 0 + ) { + var oldQueue = internalInstance.queue; + var oldReplace = internalInstance.replace; + internalInstance.queue = null; + internalInstance.replace = false; - { - if ("contextType" in ctor) { - var isValid = // Allow null for conditional declaration - contextType === null || - (contextType !== undefined && - contextType.$$typeof === REACT_CONTEXT_TYPE); + if (oldReplace && oldQueue.length === 1) { + inst.state = oldQueue[0]; + } else { + var nextState = oldReplace ? oldQueue[0] : inst.state; + var dontMutate = true; - if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { - didWarnAboutInvalidateContextType.add(ctor); - var addendum = ""; + for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) { + var partial = oldQueue[i]; + var partialState = + typeof partial === "function" + ? partial.call(inst, nextState, props, maskedLegacyContext) + : partial; - if (contextType === undefined) { - addendum = - " However, it is set to undefined. " + - "This can be caused by a typo or by mixing up named and default imports. " + - "This can also happen due to a circular dependency, so " + - "try moving the createContext() call to a separate file."; - } else if (typeof contextType !== "object") { - addendum = " However, it is set to a " + typeof contextType + "."; - } else if (contextType.$$typeof === REACT_CONSUMER_TYPE) { - addendum = - " Did you accidentally pass the Context.Consumer instead?"; - } else { - addendum = - " However, it is set to an object with keys {" + - Object.keys(contextType).join(", ") + - "}."; + if (partialState != null) { + if (dontMutate) { + dontMutate = false; + nextState = assign({}, nextState, partialState); + } else { + assign(nextState, partialState); + } } - - error( - "%s defines an invalid contextType. " + - "contextType should point to the Context object returned by React.createContext().%s", - getComponentNameFromType(ctor) || "Component", - addendum - ); } + + inst.state = nextState; } + } else { + internalInstance.queue = null; } + } // Invokes the mount life-cycles on a previously never rendered instance. - if (typeof contextType === "object" && contextType !== null) { - context = readContext$1(contextType); + function mountClassInstance(instance, ctor, newProps, maskedLegacyContext) { + { + checkClassInstance(instance, ctor, newProps); } - var instance = new ctor(props, context); + var initialState = instance.state !== undefined ? instance.state : null; + instance.updater = classComponentUpdater; + instance.props = newProps; + instance.state = initialState; // We don't bother initializing the refs object on the server, since we're not going to resolve them anyway. + // The internal instance will be used to manage updates that happen during this mount. + + var internalInstance = { + queue: [], + replace: false + }; + set(instance, internalInstance); + var contextType = ctor.contextType; + + if (typeof contextType === "object" && contextType !== null) { + instance.context = readContext$1(contextType); + } else { + instance.context = emptyContextObject; + } { - if ( - typeof ctor.getDerivedStateFromProps === "function" && - (instance.state === null || instance.state === undefined) - ) { + if (instance.state === newProps) { var componentName = getComponentNameFromType(ctor) || "Component"; - if (!didWarnAboutUninitializedState.has(componentName)) { - didWarnAboutUninitializedState.add(componentName); + if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { + didWarnAboutDirectlyAssigningPropsToState.add(componentName); error( - "`%s` uses `getDerivedStateFromProps` but its initial state is " + - "%s. This is not recommended. Instead, define the initial state by " + - "assigning an object to `this.state` in the constructor of `%s`. " + - "This ensures that `getDerivedStateFromProps` arguments have a consistent shape.", - componentName, - instance.state === null ? "null" : "undefined", + "%s: It is not recommended to assign props directly to state " + + "because updates to props won't be reflected in state. " + + "In most cases, it is better to use props directly.", componentName ); } - } // If new component APIs are defined, "unsafe" lifecycles won't be called. - // Warn about these lifecycles if they are present. - // Don't warn about react-lifecycles-compat polyfilled methods though. - - if ( - typeof ctor.getDerivedStateFromProps === "function" || - typeof instance.getSnapshotBeforeUpdate === "function" - ) { - var foundWillMountName = null; - var foundWillReceivePropsName = null; - var foundWillUpdateName = null; - - if ( - typeof instance.componentWillMount === "function" && - instance.componentWillMount.__suppressDeprecationWarning !== true - ) { - foundWillMountName = "componentWillMount"; - } else if (typeof instance.UNSAFE_componentWillMount === "function") { - foundWillMountName = "UNSAFE_componentWillMount"; - } - - if ( - typeof instance.componentWillReceiveProps === "function" && - instance.componentWillReceiveProps.__suppressDeprecationWarning !== - true - ) { - foundWillReceivePropsName = "componentWillReceiveProps"; - } else if ( - typeof instance.UNSAFE_componentWillReceiveProps === "function" - ) { - foundWillReceivePropsName = "UNSAFE_componentWillReceiveProps"; - } - - if ( - typeof instance.componentWillUpdate === "function" && - instance.componentWillUpdate.__suppressDeprecationWarning !== true - ) { - foundWillUpdateName = "componentWillUpdate"; - } else if ( - typeof instance.UNSAFE_componentWillUpdate === "function" - ) { - foundWillUpdateName = "UNSAFE_componentWillUpdate"; - } + } + } - if ( - foundWillMountName !== null || - foundWillReceivePropsName !== null || - foundWillUpdateName !== null - ) { - var _componentName = getComponentNameFromType(ctor) || "Component"; + var getDerivedStateFromProps = ctor.getDerivedStateFromProps; - var newApiName = - typeof ctor.getDerivedStateFromProps === "function" - ? "getDerivedStateFromProps()" - : "getSnapshotBeforeUpdate()"; + if (typeof getDerivedStateFromProps === "function") { + instance.state = applyDerivedStateFromProps( + instance, + ctor, + getDerivedStateFromProps, + initialState, + newProps + ); + } // In order to support react-lifecycles-compat polyfilled components, + // Unsafe lifecycles should not be invoked for components using the new APIs. - if ( - !didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName) - ) { - didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName); + if ( + typeof ctor.getDerivedStateFromProps !== "function" && + typeof instance.getSnapshotBeforeUpdate !== "function" && + (typeof instance.UNSAFE_componentWillMount === "function" || + typeof instance.componentWillMount === "function") + ) { + callComponentWillMount(ctor, instance); // If we had additional state updates during this life-cycle, let's + // process them now. - error( - "Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n" + - "%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n" + - "The above lifecycles should be removed. Learn more about this warning here:\n" + - "https://reactjs.org/link/unsafe-component-lifecycles", - _componentName, - newApiName, - foundWillMountName !== null ? "\n " + foundWillMountName : "", - foundWillReceivePropsName !== null - ? "\n " + foundWillReceivePropsName - : "", - foundWillUpdateName !== null ? "\n " + foundWillUpdateName : "" - ); - } - } - } + processUpdateQueue( + internalInstance, + instance, + newProps, + maskedLegacyContext + ); } - - return instance; } - function checkClassInstance(instance, ctor, newProps) { - { - var name = getComponentNameFromType(ctor) || "Component"; - var renderPresent = instance.render; - - if (!renderPresent) { - if (ctor.prototype && typeof ctor.prototype.render === "function") { - error( - "%s(...): No `render` method found on the returned component " + - "instance: did you accidentally return an object from the constructor?", - name - ); - } else { - error( - "%s(...): No `render` method found on the returned component " + - "instance: you may have forgotten to define `render`.", - name - ); - } - } - - if ( - instance.getInitialState && - !instance.getInitialState.isReactClassApproved && - !instance.state - ) { - error( - "getInitialState was defined on %s, a plain JavaScript class. " + - "This is only supported for classes created using React.createClass. " + - "Did you mean to define a state property instead?", - name - ); - } + // Ids are base 32 strings whose binary representation corresponds to the + // position of a node in a tree. + // Every time the tree forks into multiple children, we add additional bits to + // the left of the 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. Otherwise, + // 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 the + // sequence. It's treated as a transparent indirection. For example, these two + // trees produce the same ids: + // + // <> <> + // + // + // + // + // + // + // However, we cannot skip any node that materializes an id. Otherwise, a parent + // id that does not fork would be indistinguishable from its child id. For + // example, this tree does not fork, but the parent and child must have + // different ids. + // + // + // + // + // + // To handle this scenario, every time we materialize an id, we allocate a + // new level with a single slot. You can think of this as a fork with only one + // prong, or an array of children with length 1. + // + // It's possible for the size of the sequence to exceed 32 bits, the max + // size for bitwise operations. When this happens, we make more room by + // converting the right part of the id to a string and storing it in an overflow + // variable. We use a base 32 string representation, because 32 is the largest + // power of 2 that is supported by toString(). We want the base to be large so + // that the resulting ids are compact, and we want the base to be a power of 2 + // because every log2(base) bits corresponds to a single character, i.e. every + // log2(32) = 5 bits. That means we can lop bits off the end 5 at a time without + // affecting the final result. + var emptyTreeContext = { + id: 1, + overflow: "" + }; + function getTreeId(context) { + var overflow = context.overflow; + var idWithLeadingBit = context.id; + var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit); + return id.toString(32) + overflow; + } + function pushTreeContext(baseContext, totalChildren, index) { + var baseIdWithLeadingBit = baseContext.id; + var baseOverflow = baseContext.overflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part + // of the id; we use it to account for leading 0s. - if ( - instance.getDefaultProps && - !instance.getDefaultProps.isReactClassApproved - ) { - error( - "getDefaultProps was defined on %s, a plain JavaScript class. " + - "This is only supported for classes created using React.createClass. " + - "Use a static property to define defaultProps instead.", - name - ); - } + var baseLength = getBitLength(baseIdWithLeadingBit) - 1; + var baseId = baseIdWithLeadingBit & ~(1 << baseLength); + var slot = index + 1; + var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into + // consideration the leading 1 we use to mark the end of the sequence. - if (instance.propTypes) { - error( - "propTypes was defined as an instance property on %s. Use a static " + - "property to define propTypes instead.", - name - ); - } + if (length > 30) { + // We overflowed the bitwise-safe range. Fall back to slower algorithm. + // This branch assumes the length of the base id is greater than 5; it won't + // work for smaller ids, because you need 5 bits per character. + // + // We encode the id in multiple steps: first the base id, then the + // remaining digits. + // + // Each 5 bit sequence corresponds to a single base 32 character. So for + // example, if the current id is 23 bits long, we can convert 20 of those + // bits into a string of 4 characters, with 3 bits left over. + // + // First calculate how many bits in the base id represent a complete + // sequence of characters. + var numberOfOverflowBits = baseLength - (baseLength % 5); // Then create a bitmask that selects only those bits. - if (instance.contextType) { - error( - "contextType was defined as an instance property on %s. Use a static " + - "property to define contextType instead.", - name - ); - } + var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string. - { - if (ctor.childContextTypes) { - error( - "%s uses the legacy childContextTypes API which is no longer supported. " + - "Use React.createContext() instead.", - name - ); - } + var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id. - if (ctor.contextTypes) { - error( - "%s uses the legacy contextTypes API which is no longer supported. " + - "Use React.createContext() with static contextType instead.", - name - ); - } - } + var restOfBaseId = baseId >> numberOfOverflowBits; + var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because + // we made more room, this time it won't overflow. - if (typeof instance.componentShouldUpdate === "function") { - error( - "%s has a method called " + - "componentShouldUpdate(). Did you mean shouldComponentUpdate()? " + - "The name is phrased as a question because the function is " + - "expected to return a value.", - name - ); - } + var restOfLength = getBitLength(totalChildren) + restOfBaseLength; + var restOfNewBits = slot << restOfBaseLength; + var id = restOfNewBits | restOfBaseId; + var overflow = newOverflow + baseOverflow; + return { + id: (1 << restOfLength) | id, + overflow: overflow + }; + } else { + // Normal path + var newBits = slot << baseLength; - if ( - ctor.prototype && - ctor.prototype.isPureReactComponent && - typeof instance.shouldComponentUpdate !== "undefined" - ) { - error( - "%s has a method called shouldComponentUpdate(). " + - "shouldComponentUpdate should not be used when extending React.PureComponent. " + - "Please extend React.Component if shouldComponentUpdate is used.", - getComponentNameFromType(ctor) || "A pure component" - ); - } + var _id = newBits | baseId; - if (typeof instance.componentDidUnmount === "function") { - error( - "%s has a method called " + - "componentDidUnmount(). But there is no such lifecycle method. " + - "Did you mean componentWillUnmount()?", - name - ); - } + var _overflow = baseOverflow; + return { + id: (1 << length) | _id, + overflow: _overflow + }; + } + } - if (typeof instance.componentDidReceiveProps === "function") { - error( - "%s has a method called " + - "componentDidReceiveProps(). But there is no such lifecycle method. " + - "If you meant to update the state in response to changing props, " + - "use componentWillReceiveProps(). If you meant to fetch data or " + - "run side-effects or mutations after React has updated the UI, use componentDidUpdate().", - name - ); - } + function getBitLength(number) { + return 32 - clz32(number); + } - if (typeof instance.componentWillRecieveProps === "function") { - error( - "%s has a method called " + - "componentWillRecieveProps(). Did you mean componentWillReceiveProps()?", - name - ); - } + function getLeadingBit(id) { + return 1 << (getBitLength(id) - 1); + } // TODO: Math.clz32 is supported in Node 12+. Maybe we can drop the fallback. - if (typeof instance.UNSAFE_componentWillRecieveProps === "function") { - error( - "%s has a method called " + - "UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?", - name - ); - } + var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros. + // Based on: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32 - var hasMutatedProps = instance.props !== newProps; + var log = Math.log; + var LN2 = Math.LN2; - if (instance.props !== undefined && hasMutatedProps) { - error( - "%s(...): When calling super() in `%s`, make sure to pass " + - "up the same props that your component's constructor was passed.", - name, - name - ); - } + function clz32Fallback(x) { + var asUint = x >>> 0; - if (instance.defaultProps) { - error( - "Setting defaultProps as an instance property on %s is not supported and will be ignored." + - " Instead, define defaultProps as a static property on %s.", - name, - name - ); - } + if (asUint === 0) { + return 32; + } - if ( - typeof instance.getSnapshotBeforeUpdate === "function" && - typeof instance.componentDidUpdate !== "function" && - !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor) - ) { - didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor); + return (31 - ((log(asUint) / LN2) | 0)) | 0; + } + + // Corresponds to ReactFiberWakeable and ReactFlightWakeable modules. Generally, + // changes to one module should be reflected in the others. + // TODO: Rename this module and the corresponding Fiber one to "Thenable" + // instead of "Wakeable". Or some other more appropriate name. + // An error that is thrown (e.g. by `use`) to trigger Suspense. If we + // detect this is caught by userspace, we'll log a warning in development. + var SuspenseException = new Error( + "Suspense Exception: This is not a real error! It's an implementation " + + "detail of `use` to interrupt the current render. You must either " + + "rethrow it immediately, or move the `use` call outside of the " + + "`try/catch` block. Capturing without rethrowing will lead to " + + "unexpected behavior.\n\n" + + "To handle async errors, wrap your component in an error boundary, or " + + "call the promise's `.catch` method and pass the result to `use`" + ); + function createThenableState() { + // The ThenableState is created the first time a component suspends. If it + // suspends again, we'll reuse the same state. + return []; + } - error( - "%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). " + - "This component defines getSnapshotBeforeUpdate() only.", - getComponentNameFromType(ctor) - ); - } + function noop$2() {} - if (typeof instance.getDerivedStateFromProps === "function") { - error( - "%s: getDerivedStateFromProps() is defined as an instance method " + - "and will be ignored. Instead, declare it as a static method.", - name - ); + function trackUsedThenable(thenableState, thenable, index) { + var previous = thenableState[index]; + + if (previous === undefined) { + thenableState.push(thenable); + } else { + if (previous !== thenable) { + // Reuse the previous thenable, and drop the new one. We can assume + // they represent the same value, because components are idempotent. + // Avoid an unhandled rejection errors for the Promises that we'll + // intentionally ignore. + thenable.then(noop$2, noop$2); + thenable = previous; } + } // We use an expando to track the status and result of a thenable so that we + // can synchronously unwrap the value. Think of this as an extension of the + // Promise API, or a custom interface that is a superset of Thenable. + // + // If the thenable doesn't have a status, set it to "pending" and attach + // a listener that will update its status and result when it resolves. - if (typeof instance.getDerivedStateFromError === "function") { - error( - "%s: getDerivedStateFromError() is defined as an instance method " + - "and will be ignored. Instead, declare it as a static method.", - name - ); + switch (thenable.status) { + case "fulfilled": { + var fulfilledValue = thenable.value; + return fulfilledValue; } - if (typeof ctor.getSnapshotBeforeUpdate === "function") { - error( - "%s: getSnapshotBeforeUpdate() is defined as a static method " + - "and will be ignored. Instead, declare it as an instance method.", - name - ); + case "rejected": { + var rejectedError = thenable.reason; + throw rejectedError; } - var state = instance.state; + default: { + if (typeof thenable.status === "string"); + else { + var pendingThenable = thenable; + pendingThenable.status = "pending"; + pendingThenable.then( + function (fulfilledValue) { + if (thenable.status === "pending") { + var fulfilledThenable = thenable; + fulfilledThenable.status = "fulfilled"; + fulfilledThenable.value = fulfilledValue; + } + }, + function (error) { + if (thenable.status === "pending") { + var rejectedThenable = thenable; + rejectedThenable.status = "rejected"; + rejectedThenable.reason = error; + } + } + ); // Check one more time in case the thenable resolved synchronously - if (state && (typeof state !== "object" || isArray(state))) { - error("%s.state: must be set to an object or null", name); - } + switch (thenable.status) { + case "fulfilled": { + var fulfilledThenable = thenable; + return fulfilledThenable.value; + } - if ( - typeof instance.getChildContext === "function" && - typeof ctor.childContextTypes !== "object" - ) { - error( - "%s.getChildContext(): childContextTypes must be defined in order to " + - "use getChildContext().", - name - ); + case "rejected": { + var rejectedThenable = thenable; + throw rejectedThenable.reason; + } + } + } // Suspend. + // + // Throwing here is an implementation detail that allows us to unwind the + // call stack. But we shouldn't allow it to leak into userspace. Throw an + // opaque placeholder value instead of the actual thenable. If it doesn't + // get captured by the work loop, log a warning, because that means + // something in userspace must have caught it. + + suspendedThenable = thenable; + throw SuspenseException; } } + } // This is used to track the actual thenable that suspended so it can be + // passed to the rest of the Suspense implementation — which, for historical + // reasons, expects to receive a thenable. + + var suspendedThenable = null; + function getSuspendedThenable() { + // This is called right after `use` suspends by throwing an exception. `use` + // throws an opaque value instead of the thenable itself so that it can't be + // caught in userspace. Then the work loop accesses the actual thenable using + // this function. + if (suspendedThenable === null) { + throw new Error( + "Expected a suspended thenable. This is a bug in React. Please file " + + "an issue." + ); + } + + var thenable = suspendedThenable; + suspendedThenable = null; + return thenable; } - function callComponentWillMount(type, instance) { - var oldState = instance.state; + /** + * inlined Object.is polyfill to avoid requiring consumers ship their own + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + */ + function is(x, y) { + return ( + (x === y && (x !== 0 || 1 / x === 1 / y)) || (x !== x && y !== y) // eslint-disable-line no-self-compare + ); + } - if (typeof instance.componentWillMount === "function") { - { - if ( - instance.componentWillMount.__suppressDeprecationWarning !== true - ) { - var componentName = getComponentNameFromType(type) || "Unknown"; + var objectIs = typeof Object.is === "function" ? Object.is : is; // $FlowFixMe[method-unbinding] - if (!didWarnAboutDeprecatedWillMount[componentName]) { - warn( - // keep this warning in sync with ReactStrictModeWarning.js - "componentWillMount has been renamed, and is not recommended for use. " + - "See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n" + - "* Move code from componentWillMount to componentDidMount (preferred in most cases) " + - "or the constructor.\n" + - "\nPlease update the following components: %s", - componentName - ); + var currentlyRenderingComponent = null; + var currentlyRenderingTask = null; + var currentlyRenderingRequest = null; + var currentlyRenderingKeyPath = null; + var firstWorkInProgressHook = null; + var workInProgressHook = null; // Whether the work-in-progress hook is a re-rendered hook - didWarnAboutDeprecatedWillMount[componentName] = true; - } - } - } + var isReRender = false; // Whether an update was scheduled during the currently executing render pass. - instance.componentWillMount(); - } + var didScheduleRenderPhaseUpdate = false; // Counts the number of useId hooks in this component - if (typeof instance.UNSAFE_componentWillMount === "function") { - instance.UNSAFE_componentWillMount(); - } + var localIdCounter = 0; // Chunks that should be pushed to the stream once the component + // finishes rendering. + // Counts the number of useFormState calls in this component - if (oldState !== instance.state) { - { - error( - "%s.componentWillMount(): Assigning directly to this.state is " + - "deprecated (except inside a component's " + - "constructor). Use setState instead.", - getComponentNameFromType(type) || "Component" - ); - } + var formStateCounter = 0; // The index of the useFormState hook that matches the one passed in at the + // root during an MPA navigation, if any. - classComponentUpdater.enqueueReplaceState( - instance, - instance.state, - null - ); - } - } + var formStateMatchingIndex = -1; // Counts the number of use(thenable) calls in this component - function processUpdateQueue( - internalInstance, - inst, - props, - maskedLegacyContext - ) { - if ( - internalInstance.queue !== null && - internalInstance.queue.length > 0 - ) { - var oldQueue = internalInstance.queue; - var oldReplace = internalInstance.replace; - internalInstance.queue = null; - internalInstance.replace = false; + var thenableIndexCounter = 0; + var thenableState = null; // Lazily created map of render-phase updates - if (oldReplace && oldQueue.length === 1) { - inst.state = oldQueue[0]; - } else { - var nextState = oldReplace ? oldQueue[0] : inst.state; - var dontMutate = true; + var renderPhaseUpdates = null; // Counter to prevent infinite loops. - for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) { - var partial = oldQueue[i]; - var partialState = - typeof partial === "function" - ? partial.call(inst, nextState, props, maskedLegacyContext) - : partial; + var numberOfReRenders = 0; + var RE_RENDER_LIMIT = 25; + var isInHookUserCodeInDev = false; // In DEV, this is the name of the currently executing primitive hook - if (partialState != null) { - if (dontMutate) { - dontMutate = false; - nextState = assign({}, nextState, partialState); - } else { - assign(nextState, partialState); - } - } - } + var currentHookNameInDev; - inst.state = nextState; + function resolveCurrentlyRenderingComponent() { + if (currentlyRenderingComponent === null) { + throw new Error( + "Invalid hook call. Hooks can only be called inside of the body of a function 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 of Hooks\n" + + "3. You might have more than one copy of React in the same app\n" + + "See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem." + ); + } + + { + if (isInHookUserCodeInDev) { + error( + "Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. " + + "You can only call Hooks at the top level of your React function. " + + "For more information, see " + + "https://reactjs.org/link/rules-of-hooks" + ); } - } else { - internalInstance.queue = null; - } - } // Invokes the mount life-cycles on a previously never rendered instance. - - function mountClassInstance(instance, ctor, newProps, maskedLegacyContext) { - { - checkClassInstance(instance, ctor, newProps); } - var initialState = instance.state !== undefined ? instance.state : null; - instance.updater = classComponentUpdater; - instance.props = newProps; - instance.state = initialState; // We don't bother initializing the refs object on the server, since we're not going to resolve them anyway. - // The internal instance will be used to manage updates that happen during this mount. + return currentlyRenderingComponent; + } - var internalInstance = { - queue: [], - replace: false - }; - set(instance, internalInstance); - var contextType = ctor.contextType; + function areHookInputsEqual(nextDeps, prevDeps) { + if (prevDeps === null) { + { + error( + "%s received a final argument during this render, but not during " + + "the previous render. Even though the final argument is optional, " + + "its type cannot change between renders.", + currentHookNameInDev + ); + } - if (typeof contextType === "object" && contextType !== null) { - instance.context = readContext$1(contextType); - } else { - instance.context = emptyContextObject; + return false; } { - if (instance.state === newProps) { - var componentName = getComponentNameFromType(ctor) || "Component"; - - if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { - didWarnAboutDirectlyAssigningPropsToState.add(componentName); - - error( - "%s: It is not recommended to assign props directly to state " + - "because updates to props won't be reflected in state. " + - "In most cases, it is better to use props directly.", - componentName - ); - } + // Don't bother comparing lengths in prod because these arrays should be + // passed inline. + if (nextDeps.length !== prevDeps.length) { + error( + "The final argument passed to %s changed size between renders. The " + + "order and size of this array must remain constant.\n\n" + + "Previous: %s\n" + + "Incoming: %s", + currentHookNameInDev, + "[" + nextDeps.join(", ") + "]", + "[" + prevDeps.join(", ") + "]" + ); } - } + } // $FlowFixMe[incompatible-use] found when upgrading Flow - var getDerivedStateFromProps = ctor.getDerivedStateFromProps; + for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) { + // $FlowFixMe[incompatible-use] found when upgrading Flow + if (objectIs(nextDeps[i], prevDeps[i])) { + continue; + } - if (typeof getDerivedStateFromProps === "function") { - instance.state = applyDerivedStateFromProps( - instance, - ctor, - getDerivedStateFromProps, - initialState, - newProps - ); - } // In order to support react-lifecycles-compat polyfilled components, - // Unsafe lifecycles should not be invoked for components using the new APIs. + return false; + } - if ( - typeof ctor.getDerivedStateFromProps !== "function" && - typeof instance.getSnapshotBeforeUpdate !== "function" && - (typeof instance.UNSAFE_componentWillMount === "function" || - typeof instance.componentWillMount === "function") - ) { - callComponentWillMount(ctor, instance); // If we had additional state updates during this life-cycle, let's - // process them now. + return true; + } - processUpdateQueue( - internalInstance, - instance, - newProps, - maskedLegacyContext - ); + function createHook() { + if (numberOfReRenders > 0) { + throw new Error("Rendered more hooks than during the previous render"); } - } - // Ids are base 32 strings whose binary representation corresponds to the - // position of a node in a tree. - // Every time the tree forks into multiple children, we add additional bits to - // the left of the 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. Otherwise, - // 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 the - // sequence. It's treated as a transparent indirection. For example, these two - // trees produce the same ids: - // - // <> <> - // - // - // - // - // - // - // However, we cannot skip any node that materializes an id. Otherwise, a parent - // id that does not fork would be indistinguishable from its child id. For - // example, this tree does not fork, but the parent and child must have - // different ids. - // - // - // - // - // - // To handle this scenario, every time we materialize an id, we allocate a - // new level with a single slot. You can think of this as a fork with only one - // prong, or an array of children with length 1. - // - // It's possible for the size of the sequence to exceed 32 bits, the max - // size for bitwise operations. When this happens, we make more room by - // converting the right part of the id to a string and storing it in an overflow - // variable. We use a base 32 string representation, because 32 is the largest - // power of 2 that is supported by toString(). We want the base to be large so - // that the resulting ids are compact, and we want the base to be a power of 2 - // because every log2(base) bits corresponds to a single character, i.e. every - // log2(32) = 5 bits. That means we can lop bits off the end 5 at a time without - // affecting the final result. - var emptyTreeContext = { - id: 1, - overflow: "" - }; - function getTreeId(context) { - var overflow = context.overflow; - var idWithLeadingBit = context.id; - var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit); - return id.toString(32) + overflow; + return { + memoizedState: null, + queue: null, + next: null + }; } - function pushTreeContext(baseContext, totalChildren, index) { - var baseIdWithLeadingBit = baseContext.id; - var baseOverflow = baseContext.overflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part - // of the id; we use it to account for leading 0s. - - var baseLength = getBitLength(baseIdWithLeadingBit) - 1; - var baseId = baseIdWithLeadingBit & ~(1 << baseLength); - var slot = index + 1; - var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into - // consideration the leading 1 we use to mark the end of the sequence. - if (length > 30) { - // We overflowed the bitwise-safe range. Fall back to slower algorithm. - // This branch assumes the length of the base id is greater than 5; it won't - // work for smaller ids, because you need 5 bits per character. - // - // We encode the id in multiple steps: first the base id, then the - // remaining digits. - // - // Each 5 bit sequence corresponds to a single base 32 character. So for - // example, if the current id is 23 bits long, we can convert 20 of those - // bits into a string of 4 characters, with 3 bits left over. - // - // First calculate how many bits in the base id represent a complete - // sequence of characters. - var numberOfOverflowBits = baseLength - (baseLength % 5); // Then create a bitmask that selects only those bits. + function createWorkInProgressHook() { + if (workInProgressHook === null) { + // This is the first hook in the list + if (firstWorkInProgressHook === null) { + isReRender = false; + firstWorkInProgressHook = workInProgressHook = createHook(); + } else { + // There's already a work-in-progress. Reuse it. + isReRender = true; + workInProgressHook = firstWorkInProgressHook; + } + } else { + if (workInProgressHook.next === null) { + isReRender = false; // Append to the end of the list - var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string. + workInProgressHook = workInProgressHook.next = createHook(); + } else { + // There's already a work-in-progress. Reuse it. + isReRender = true; + workInProgressHook = workInProgressHook.next; + } + } - var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id. + return workInProgressHook; + } - var restOfBaseId = baseId >> numberOfOverflowBits; - var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because - // we made more room, this time it won't overflow. + function prepareToUseHooks( + request, + task, + keyPath, + componentIdentity, + prevThenableState + ) { + currentlyRenderingComponent = componentIdentity; + currentlyRenderingTask = task; + currentlyRenderingRequest = request; + currentlyRenderingKeyPath = keyPath; - var restOfLength = getBitLength(totalChildren) + restOfBaseLength; - var restOfNewBits = slot << restOfBaseLength; - var id = restOfNewBits | restOfBaseId; - var overflow = newOverflow + baseOverflow; - return { - id: (1 << restOfLength) | id, - overflow: overflow - }; - } else { - // Normal path - var newBits = slot << baseLength; + { + isInHookUserCodeInDev = false; + } // The following should have already been reset + // didScheduleRenderPhaseUpdate = false; + // firstWorkInProgressHook = null; + // numberOfReRenders = 0; + // renderPhaseUpdates = null; + // workInProgressHook = null; - var _id = newBits | baseId; + localIdCounter = 0; + formStateCounter = 0; + formStateMatchingIndex = -1; + thenableIndexCounter = 0; + thenableState = prevThenableState; + } + function finishHooks(Component, props, children, refOrContext) { + // This must be called after every function component to prevent hooks from + // being used in classes. + while (didScheduleRenderPhaseUpdate) { + // Updates were scheduled during the render phase. They are stored in + // the `renderPhaseUpdates` map. Call the component again, reusing the + // work-in-progress hooks and applying the additional updates on top. Keep + // restarting until no more updates are scheduled. + didScheduleRenderPhaseUpdate = false; + localIdCounter = 0; + formStateCounter = 0; + formStateMatchingIndex = -1; + thenableIndexCounter = 0; + numberOfReRenders += 1; // Start over from the beginning of the list - var _overflow = baseOverflow; - return { - id: (1 << length) | _id, - overflow: _overflow - }; + workInProgressHook = null; + children = Component(props, refOrContext); } - } - function getBitLength(number) { - return 32 - clz32(number); + resetHooksState(); + return children; + } + function getThenableStateAfterSuspending() { + var state = thenableState; + thenableState = null; + return state; + } + function checkDidRenderIdHook() { + // This should be called immediately after every finishHooks call. + // Conceptually, it's part of the return value of finishHooks; it's only a + // separate function to avoid using an array tuple. + var didRenderIdHook = localIdCounter !== 0; + return didRenderIdHook; + } + function getFormStateCount() { + // This should be called immediately after every finishHooks call. + // Conceptually, it's part of the return value of finishHooks; it's only a + // separate function to avoid using an array tuple. + return formStateCounter; } + function getFormStateMatchingIndex() { + // This should be called immediately after every finishHooks call. + // Conceptually, it's part of the return value of finishHooks; it's only a + // separate function to avoid using an array tuple. + return formStateMatchingIndex; + } // Reset the internal hooks state if an error occurs while rendering a component - function getLeadingBit(id) { - return 1 << (getBitLength(id) - 1); - } // TODO: Math.clz32 is supported in Node 12+. Maybe we can drop the fallback. + function resetHooksState() { + { + isInHookUserCodeInDev = false; + } - var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros. - // Based on: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32 + currentlyRenderingComponent = null; + currentlyRenderingTask = null; + currentlyRenderingRequest = null; + currentlyRenderingKeyPath = null; + didScheduleRenderPhaseUpdate = false; + firstWorkInProgressHook = null; + numberOfReRenders = 0; + renderPhaseUpdates = null; + workInProgressHook = null; + } - var log = Math.log; - var LN2 = Math.LN2; + function readContext(context) { + { + if (isInHookUserCodeInDev) { + error( + "Context can only be read while React is rendering. " + + "In classes, you can read it in the render method or getDerivedStateFromProps. " + + "In function components, you can read it directly in the function body, but not " + + "inside Hooks like useReducer() or useMemo()." + ); + } + } - function clz32Fallback(x) { - var asUint = x >>> 0; + return readContext$1(context); + } - if (asUint === 0) { - return 32; + function useContext(context) { + { + currentHookNameInDev = "useContext"; } - return (31 - ((log(asUint) / LN2) | 0)) | 0; + resolveCurrentlyRenderingComponent(); + return readContext$1(context); } - // Corresponds to ReactFiberWakeable and ReactFlightWakeable modules. Generally, - // changes to one module should be reflected in the others. - // TODO: Rename this module and the corresponding Fiber one to "Thenable" - // instead of "Wakeable". Or some other more appropriate name. - // An error that is thrown (e.g. by `use`) to trigger Suspense. If we - // detect this is caught by userspace, we'll log a warning in development. - var SuspenseException = new Error( - "Suspense Exception: This is not a real error! It's an implementation " + - "detail of `use` to interrupt the current render. You must either " + - "rethrow it immediately, or move the `use` call outside of the " + - "`try/catch` block. Capturing without rethrowing will lead to " + - "unexpected behavior.\n\n" + - "To handle async errors, wrap your component in an error boundary, or " + - "call the promise's `.catch` method and pass the result to `use`" - ); - function createThenableState() { - // The ThenableState is created the first time a component suspends. If it - // suspends again, we'll reuse the same state. - return []; + function basicStateReducer(state, action) { + // $FlowFixMe[incompatible-use]: Flow doesn't like mixed types + return typeof action === "function" ? action(state) : action; } - function noop$2() {} - - function trackUsedThenable(thenableState, thenable, index) { - var previous = thenableState[index]; - - if (previous === undefined) { - thenableState.push(thenable); - } else { - if (previous !== thenable) { - // Reuse the previous thenable, and drop the new one. We can assume - // they represent the same value, because components are idempotent. - // Avoid an unhandled rejection errors for the Promises that we'll - // intentionally ignore. - thenable.then(noop$2, noop$2); - thenable = previous; - } - } // We use an expando to track the status and result of a thenable so that we - // can synchronously unwrap the value. Think of this as an extension of the - // Promise API, or a custom interface that is a superset of Thenable. - // - // If the thenable doesn't have a status, set it to "pending" and attach - // a listener that will update its status and result when it resolves. - - switch (thenable.status) { - case "fulfilled": { - var fulfilledValue = thenable.value; - return fulfilledValue; - } + function useState(initialState) { + { + currentHookNameInDev = "useState"; + } - case "rejected": { - var rejectedError = thenable.reason; - throw rejectedError; + return useReducer( + basicStateReducer, // useReducer has a special case to support lazy useState initializers + initialState + ); + } + function useReducer(reducer, initialArg, init) { + { + if (reducer !== basicStateReducer) { + currentHookNameInDev = "useReducer"; } + } - default: { - if (typeof thenable.status === "string"); - else { - var pendingThenable = thenable; - pendingThenable.status = "pending"; - pendingThenable.then( - function (fulfilledValue) { - if (thenable.status === "pending") { - var fulfilledThenable = thenable; - fulfilledThenable.status = "fulfilled"; - fulfilledThenable.value = fulfilledValue; - } - }, - function (error) { - if (thenable.status === "pending") { - var rejectedThenable = thenable; - rejectedThenable.status = "rejected"; - rejectedThenable.reason = error; - } - } - ); // Check one more time in case the thenable resolved synchronously + currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); + workInProgressHook = createWorkInProgressHook(); - switch (thenable.status) { - case "fulfilled": { - var fulfilledThenable = thenable; - return fulfilledThenable.value; - } + if (isReRender) { + // This is a re-render. Apply the new render phase updates to the previous + // current hook. + var queue = workInProgressHook.queue; + var dispatch = queue.dispatch; - case "rejected": { - var rejectedThenable = thenable; - throw rejectedThenable.reason; - } - } - } // Suspend. - // - // Throwing here is an implementation detail that allows us to unwind the - // call stack. But we shouldn't allow it to leak into userspace. Throw an - // opaque placeholder value instead of the actual thenable. If it doesn't - // get captured by the work loop, log a warning, because that means - // something in userspace must have caught it. + if (renderPhaseUpdates !== null) { + // Render phase updates are stored in a map of queue -> linked list + var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); - suspendedThenable = thenable; - throw SuspenseException; - } - } - } // This is used to track the actual thenable that suspended so it can be - // passed to the rest of the Suspense implementation — which, for historical - // reasons, expects to receive a thenable. + if (firstRenderPhaseUpdate !== undefined) { + // $FlowFixMe[incompatible-use] found when upgrading Flow + renderPhaseUpdates.delete(queue); // $FlowFixMe[incompatible-use] found when upgrading Flow - var suspendedThenable = null; - function getSuspendedThenable() { - // This is called right after `use` suspends by throwing an exception. `use` - // throws an opaque value instead of the thenable itself so that it can't be - // caught in userspace. Then the work loop accesses the actual thenable using - // this function. - if (suspendedThenable === null) { - throw new Error( - "Expected a suspended thenable. This is a bug in React. Please file " + - "an issue." - ); - } + var newState = workInProgressHook.memoizedState; + var update = firstRenderPhaseUpdate; - var thenable = suspendedThenable; - suspendedThenable = null; - return thenable; - } + do { + // Process this render phase update. We don't have to check the + // priority because it will always be the same as the current + // render's. + var action = update.action; - /** - * inlined Object.is polyfill to avoid requiring consumers ship their own - * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is - */ - function is(x, y) { - return ( - (x === y && (x !== 0 || 1 / x === 1 / y)) || (x !== x && y !== y) // eslint-disable-line no-self-compare - ); - } + { + isInHookUserCodeInDev = true; + } - var objectIs = typeof Object.is === "function" ? Object.is : is; // $FlowFixMe[method-unbinding] + newState = reducer(newState, action); - var currentlyRenderingComponent = null; - var currentlyRenderingTask = null; - var currentlyRenderingRequest = null; - var currentlyRenderingKeyPath = null; - var firstWorkInProgressHook = null; - var workInProgressHook = null; // Whether the work-in-progress hook is a re-rendered hook + { + isInHookUserCodeInDev = false; + } // $FlowFixMe[incompatible-type] we bail out when we get a null - var isReRender = false; // Whether an update was scheduled during the currently executing render pass. + update = update.next; + } while (update !== null); // $FlowFixMe[incompatible-use] found when upgrading Flow - var didScheduleRenderPhaseUpdate = false; // Counts the number of useId hooks in this component + workInProgressHook.memoizedState = newState; + return [newState, dispatch]; + } + } // $FlowFixMe[incompatible-use] found when upgrading Flow - var localIdCounter = 0; // Chunks that should be pushed to the stream once the component - // finishes rendering. - // Counts the number of useFormState calls in this component + return [workInProgressHook.memoizedState, dispatch]; + } else { + { + isInHookUserCodeInDev = true; + } - var formStateCounter = 0; // The index of the useFormState hook that matches the one passed in at the - // root during an MPA navigation, if any. + var initialState; - var formStateMatchingIndex = -1; // Counts the number of use(thenable) calls in this component + if (reducer === basicStateReducer) { + // Special case for `useState`. + initialState = + typeof initialArg === "function" ? initialArg() : initialArg; + } else { + initialState = init !== undefined ? init(initialArg) : initialArg; + } - var thenableIndexCounter = 0; - var thenableState = null; // Lazily created map of render-phase updates + { + isInHookUserCodeInDev = false; + } // $FlowFixMe[incompatible-use] found when upgrading Flow - var renderPhaseUpdates = null; // Counter to prevent infinite loops. + workInProgressHook.memoizedState = initialState; // $FlowFixMe[incompatible-use] found when upgrading Flow - var numberOfReRenders = 0; - var RE_RENDER_LIMIT = 25; - var isInHookUserCodeInDev = false; // In DEV, this is the name of the currently executing primitive hook + var _queue = (workInProgressHook.queue = { + last: null, + dispatch: null + }); - var currentHookNameInDev; + var _dispatch = (_queue.dispatch = dispatchAction.bind( + null, + currentlyRenderingComponent, + _queue + )); // $FlowFixMe[incompatible-use] found when upgrading Flow - function resolveCurrentlyRenderingComponent() { - if (currentlyRenderingComponent === null) { - throw new Error( - "Invalid hook call. Hooks can only be called inside of the body of a function 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 of Hooks\n" + - "3. You might have more than one copy of React in the same app\n" + - "See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem." - ); + return [workInProgressHook.memoizedState, _dispatch]; } + } - { - if (isInHookUserCodeInDev) { - error( - "Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. " + - "You can only call Hooks at the top level of your React function. " + - "For more information, see " + - "https://reactjs.org/link/rules-of-hooks" - ); - } - } + function useMemo(nextCreate, deps) { + currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); + workInProgressHook = createWorkInProgressHook(); + var nextDeps = deps === undefined ? null : deps; - return currentlyRenderingComponent; - } + if (workInProgressHook !== null) { + var prevState = workInProgressHook.memoizedState; - function areHookInputsEqual(nextDeps, prevDeps) { - if (prevDeps === null) { - { - error( - "%s received a final argument during this render, but not during " + - "the previous render. Even though the final argument is optional, " + - "its type cannot change between renders.", - currentHookNameInDev - ); - } + if (prevState !== null) { + if (nextDeps !== null) { + var prevDeps = prevState[1]; - return false; + if (areHookInputsEqual(nextDeps, prevDeps)) { + return prevState[0]; + } + } + } } { - // Don't bother comparing lengths in prod because these arrays should be - // passed inline. - if (nextDeps.length !== prevDeps.length) { - error( - "The final argument passed to %s changed size between renders. The " + - "order and size of this array must remain constant.\n\n" + - "Previous: %s\n" + - "Incoming: %s", - currentHookNameInDev, - "[" + nextDeps.join(", ") + "]", - "[" + prevDeps.join(", ") + "]" - ); - } - } // $FlowFixMe[incompatible-use] found when upgrading Flow + isInHookUserCodeInDev = true; + } - for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) { - // $FlowFixMe[incompatible-use] found when upgrading Flow - if (objectIs(nextDeps[i], prevDeps[i])) { - continue; - } + var nextValue = nextCreate(); - return false; - } + { + isInHookUserCodeInDev = false; + } // $FlowFixMe[incompatible-use] found when upgrading Flow - return true; + workInProgressHook.memoizedState = [nextValue, nextDeps]; + return nextValue; } - function createHook() { - if (numberOfReRenders > 0) { - throw new Error("Rendered more hooks than during the previous render"); - } + function useRef(initialValue) { + currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); + workInProgressHook = createWorkInProgressHook(); + var previousRef = workInProgressHook.memoizedState; - return { - memoizedState: null, - queue: null, - next: null - }; - } + if (previousRef === null) { + var ref = { + current: initialValue + }; - function createWorkInProgressHook() { - if (workInProgressHook === null) { - // This is the first hook in the list - if (firstWorkInProgressHook === null) { - isReRender = false; - firstWorkInProgressHook = workInProgressHook = createHook(); - } else { - // There's already a work-in-progress. Reuse it. - isReRender = true; - workInProgressHook = firstWorkInProgressHook; - } + { + Object.seal(ref); + } // $FlowFixMe[incompatible-use] found when upgrading Flow + + workInProgressHook.memoizedState = ref; + return ref; } else { - if (workInProgressHook.next === null) { - isReRender = false; // Append to the end of the list + return previousRef; + } + } - workInProgressHook = workInProgressHook.next = createHook(); - } else { - // There's already a work-in-progress. Reuse it. - isReRender = true; - workInProgressHook = workInProgressHook.next; - } + function dispatchAction(componentIdentity, queue, action) { + if (numberOfReRenders >= RE_RENDER_LIMIT) { + throw new Error( + "Too many re-renders. React limits the number of renders to prevent " + + "an infinite loop." + ); } - return workInProgressHook; - } + if (componentIdentity === currentlyRenderingComponent) { + // This is a render phase update. Stash it in a lazily-created map of + // queue -> linked list of updates. After this render pass, we'll restart + // and apply the stashed updates on top of the work-in-progress hook. + didScheduleRenderPhaseUpdate = true; + var update = { + action: action, + next: null + }; - function prepareToUseHooks( - request, - task, - keyPath, - componentIdentity, - prevThenableState - ) { - currentlyRenderingComponent = componentIdentity; - currentlyRenderingTask = task; - currentlyRenderingRequest = request; - currentlyRenderingKeyPath = keyPath; + if (renderPhaseUpdates === null) { + renderPhaseUpdates = new Map(); + } - { - isInHookUserCodeInDev = false; - } // The following should have already been reset - // didScheduleRenderPhaseUpdate = false; - // firstWorkInProgressHook = null; - // numberOfReRenders = 0; - // renderPhaseUpdates = null; - // workInProgressHook = null; + var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); - localIdCounter = 0; - formStateCounter = 0; - formStateMatchingIndex = -1; - thenableIndexCounter = 0; - thenableState = prevThenableState; - } - function finishHooks(Component, props, children, refOrContext) { - // This must be called after every function component to prevent hooks from - // being used in classes. - while (didScheduleRenderPhaseUpdate) { - // Updates were scheduled during the render phase. They are stored in - // the `renderPhaseUpdates` map. Call the component again, reusing the - // work-in-progress hooks and applying the additional updates on top. Keep - // restarting until no more updates are scheduled. - didScheduleRenderPhaseUpdate = false; - localIdCounter = 0; - formStateCounter = 0; - formStateMatchingIndex = -1; - thenableIndexCounter = 0; - numberOfReRenders += 1; // Start over from the beginning of the list + if (firstRenderPhaseUpdate === undefined) { + // $FlowFixMe[incompatible-use] found when upgrading Flow + renderPhaseUpdates.set(queue, update); + } else { + // Append the update to the end of the list. + var lastRenderPhaseUpdate = firstRenderPhaseUpdate; - workInProgressHook = null; - children = Component(props, refOrContext); + while (lastRenderPhaseUpdate.next !== null) { + lastRenderPhaseUpdate = lastRenderPhaseUpdate.next; + } + + lastRenderPhaseUpdate.next = update; + } } - - resetHooksState(); - return children; } - function getThenableStateAfterSuspending() { - var state = thenableState; - thenableState = null; - return state; + + function useCallback(callback, deps) { + return useMemo(function () { + return callback; + }, deps); } - function checkDidRenderIdHook() { - // This should be called immediately after every finishHooks call. - // Conceptually, it's part of the return value of finishHooks; it's only a - // separate function to avoid using an array tuple. - var didRenderIdHook = localIdCounter !== 0; - return didRenderIdHook; + + function throwOnUseEffectEventCall() { + throw new Error( + "A function wrapped in useEffectEvent can't be called during rendering." + ); } - function getFormStateCount() { - // This should be called immediately after every finishHooks call. - // Conceptually, it's part of the return value of finishHooks; it's only a - // separate function to avoid using an array tuple. - return formStateCounter; + + function useEffectEvent(callback) { + // $FlowIgnore[incompatible-return] + return throwOnUseEffectEventCall; } - function getFormStateMatchingIndex() { - // This should be called immediately after every finishHooks call. - // Conceptually, it's part of the return value of finishHooks; it's only a - // separate function to avoid using an array tuple. - return formStateMatchingIndex; - } // Reset the internal hooks state if an error occurs while rendering a component - function resetHooksState() { - { - isInHookUserCodeInDev = false; + function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { + if (getServerSnapshot === undefined) { + throw new Error( + "Missing getServerSnapshot, which is required for " + + "server-rendered content. Will revert to client rendering." + ); } - currentlyRenderingComponent = null; - currentlyRenderingTask = null; - currentlyRenderingRequest = null; - currentlyRenderingKeyPath = null; - didScheduleRenderPhaseUpdate = false; - firstWorkInProgressHook = null; - numberOfReRenders = 0; - renderPhaseUpdates = null; - workInProgressHook = null; + return getServerSnapshot(); } - function readContext(context) { - { - if (isInHookUserCodeInDev) { - error( - "Context can only be read while React is rendering. " + - "In classes, you can read it in the render method or getDerivedStateFromProps. " + - "In function components, you can read it directly in the function body, but not " + - "inside Hooks like useReducer() or useMemo()." - ); - } - } + function useDeferredValue(value, initialValue) { + resolveCurrentlyRenderingComponent(); - return readContext$1(context); + if (enableUseDeferredValueInitialArg) { + return initialValue !== undefined ? initialValue : value; + } else { + return value; + } } - function useContext(context) { - { - currentHookNameInDev = "useContext"; - } + function unsupportedStartTransition() { + throw new Error( + "startTransition cannot be called during server rendering." + ); + } + function useTransition() { resolveCurrentlyRenderingComponent(); - return readContext$1(context); + return [false, unsupportedStartTransition]; } - function basicStateReducer(state, action) { - // $FlowFixMe[incompatible-use]: Flow doesn't like mixed types - return typeof action === "function" ? action(state) : action; + function useHostTransitionStatus() { + resolveCurrentlyRenderingComponent(); + return NotPendingTransition; } - function useState(initialState) { - { - currentHookNameInDev = "useState"; - } + function unsupportedSetOptimisticState() { + throw new Error("Cannot update optimistic state while rendering."); + } - return useReducer( - basicStateReducer, // useReducer has a special case to support lazy useState initializers - initialState - ); + function useOptimistic(passthrough, reducer) { + resolveCurrentlyRenderingComponent(); + return [passthrough, unsupportedSetOptimisticState]; } - function useReducer(reducer, initialArg, init) { - { - if (reducer !== basicStateReducer) { - currentHookNameInDev = "useReducer"; - } - } - currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); - workInProgressHook = createWorkInProgressHook(); + function createPostbackFormStateKey( + permalink, + componentKeyPath, + hookIndex + ) { + if (permalink !== undefined) { + // Don't bother to hash a permalink-based key since it's already short. + return "p" + permalink; + } else { + // Append a node to the key path that represents the form state hook. + var keyPath = [componentKeyPath, null, hookIndex]; // Key paths are hashed to reduce the size. It does not need to be secure, + // and it's more important that it's fast than that it's completely + // collision-free. - if (isReRender) { - // This is a re-render. Apply the new render phase updates to the previous - // current hook. - var queue = workInProgressHook.queue; - var dispatch = queue.dispatch; + var keyPathHash = createFastHashJS(JSON.stringify(keyPath)); + return "k" + keyPathHash; + } + } - if (renderPhaseUpdates !== null) { - // Render phase updates are stored in a map of queue -> linked list - var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); + function useFormState(action, initialState, permalink) { + resolveCurrentlyRenderingComponent(); // Count the number of useFormState hooks per component. We also use this to + // track the position of this useFormState hook relative to the other ones in + // this component, so we can generate a unique key for each one. - if (firstRenderPhaseUpdate !== undefined) { - // $FlowFixMe[incompatible-use] found when upgrading Flow - renderPhaseUpdates.delete(queue); // $FlowFixMe[incompatible-use] found when upgrading Flow + var formStateHookIndex = formStateCounter++; + var request = currentlyRenderingRequest; // $FlowIgnore[prop-missing] - var newState = workInProgressHook.memoizedState; - var update = firstRenderPhaseUpdate; + var formAction = action.$$FORM_ACTION; - do { - // Process this render phase update. We don't have to check the - // priority because it will always be the same as the current - // render's. - var action = update.action; + if (typeof formAction === "function") { + // This is a server action. These have additional features to enable + // MPA-style form submissions with progressive enhancement. + // TODO: If the same permalink is passed to multiple useFormStates, and + // they all have the same action signature, Fizz will pass the postback + // state to all of them. We should probably only pass it to the first one, + // and/or warn. + // The key is lazily generated and deduped so the that the keypath doesn't + // get JSON.stringify-ed unnecessarily, and at most once. + var nextPostbackStateKey = null; // Determine the current form state. If we received state during an MPA form + // submission, then we will reuse that, if the action identity matches. + // Otherwise we'll use the initial state argument. We will emit a comment + // marker into the stream that indicates whether the state was reused. - { - isInHookUserCodeInDev = true; - } + var state = initialState; + var componentKeyPath = currentlyRenderingKeyPath; + var postbackFormState = getFormState(request); // $FlowIgnore[prop-missing] - newState = reducer(newState, action); + var isSignatureEqual = action.$$IS_SIGNATURE_EQUAL; - { - isInHookUserCodeInDev = false; - } // $FlowFixMe[incompatible-type] we bail out when we get a null + if ( + postbackFormState !== null && + typeof isSignatureEqual === "function" + ) { + var postbackKey = postbackFormState[1]; + var postbackReferenceId = postbackFormState[2]; + var postbackBoundArity = postbackFormState[3]; - update = update.next; - } while (update !== null); // $FlowFixMe[incompatible-use] found when upgrading Flow + if ( + isSignatureEqual.call( + action, + postbackReferenceId, + postbackBoundArity + ) + ) { + nextPostbackStateKey = createPostbackFormStateKey( + permalink, + componentKeyPath, + formStateHookIndex + ); - workInProgressHook.memoizedState = newState; - return [newState, dispatch]; + if (postbackKey === nextPostbackStateKey) { + // This was a match + formStateMatchingIndex = formStateHookIndex; // Reuse the state that was submitted by the form. + + state = postbackFormState[0]; + } } - } // $FlowFixMe[incompatible-use] found when upgrading Flow + } // Bind the state to the first argument of the action. - return [workInProgressHook.memoizedState, dispatch]; - } else { - { - isInHookUserCodeInDev = true; - } + var boundAction = action.bind(null, state); // Wrap the action so the return value is void. - var initialState; + var dispatch = function (payload) { + boundAction(payload); + }; // $FlowIgnore[prop-missing] - if (reducer === basicStateReducer) { - // Special case for `useState`. - initialState = - typeof initialArg === "function" ? initialArg() : initialArg; - } else { - initialState = init !== undefined ? init(initialArg) : initialArg; - } + if (typeof boundAction.$$FORM_ACTION === "function") { + // $FlowIgnore[prop-missing] + dispatch.$$FORM_ACTION = function (prefix) { + var metadata = boundAction.$$FORM_ACTION(prefix); // Override the action URL - { - isInHookUserCodeInDev = false; - } // $FlowFixMe[incompatible-use] found when upgrading Flow + if (permalink !== undefined) { + { + checkAttributeStringCoercion(permalink, "target"); + } + + permalink += ""; + metadata.action = permalink; + } + + var formData = metadata.data; + + if (formData) { + if (nextPostbackStateKey === null) { + nextPostbackStateKey = createPostbackFormStateKey( + permalink, + componentKeyPath, + formStateHookIndex + ); + } - workInProgressHook.memoizedState = initialState; // $FlowFixMe[incompatible-use] found when upgrading Flow + formData.append("$ACTION_KEY", nextPostbackStateKey); + } - var _queue = (workInProgressHook.queue = { - last: null, - dispatch: null - }); + return metadata; + }; + } - var _dispatch = (_queue.dispatch = dispatchAction.bind( - null, - currentlyRenderingComponent, - _queue - )); // $FlowFixMe[incompatible-use] found when upgrading Flow + return [state, dispatch]; + } else { + // This is not a server action, so the implementation is much simpler. + // Bind the state to the first argument of the action. + var _boundAction = action.bind(null, initialState); // Wrap the action so the return value is void. - return [workInProgressHook.memoizedState, _dispatch]; + var _dispatch2 = function (payload) { + _boundAction(payload); + }; + + return [initialState, _dispatch2]; } } - function useMemo(nextCreate, deps) { - currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); - workInProgressHook = createWorkInProgressHook(); - var nextDeps = deps === undefined ? null : deps; + function useId() { + var task = currentlyRenderingTask; + var treeId = getTreeId(task.treeContext); + var resumableState = currentResumableState; - if (workInProgressHook !== null) { - var prevState = workInProgressHook.memoizedState; + if (resumableState === null) { + throw new Error( + "Invalid hook call. Hooks can only be called inside of the body of a function component." + ); + } - if (prevState !== null) { - if (nextDeps !== null) { - var prevDeps = prevState[1]; + var localId = localIdCounter++; + return makeId(resumableState, treeId, localId); + } - if (areHookInputsEqual(nextDeps, prevDeps)) { - return prevState[0]; - } - } + function use(usable) { + if (usable !== null && typeof usable === "object") { + // $FlowFixMe[method-unbinding] + if (typeof usable.then === "function") { + // This is a thenable. + var thenable = usable; + return unwrapThenable(thenable); + } else if (usable.$$typeof === REACT_CONTEXT_TYPE) { + var context = usable; + return readContext(context); } - } + } // eslint-disable-next-line react-internal/safe-string-coercion - { - isInHookUserCodeInDev = true; - } + throw new Error( + "An unsupported type was passed to use(): " + String(usable) + ); + } - var nextValue = nextCreate(); + function unwrapThenable(thenable) { + var index = thenableIndexCounter; + thenableIndexCounter += 1; - { - isInHookUserCodeInDev = false; - } // $FlowFixMe[incompatible-use] found when upgrading Flow + if (thenableState === null) { + thenableState = createThenableState(); + } - workInProgressHook.memoizedState = [nextValue, nextDeps]; - return nextValue; + return trackUsedThenable(thenableState, thenable, index); } - function useRef(initialValue) { - currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); - workInProgressHook = createWorkInProgressHook(); - var previousRef = workInProgressHook.memoizedState; + function unsupportedRefresh() { + throw new Error("Cache cannot be refreshed during server rendering."); + } - if (previousRef === null) { - var ref = { - current: initialValue - }; + function useCacheRefresh() { + return unsupportedRefresh; + } - { - Object.seal(ref); - } // $FlowFixMe[incompatible-use] found when upgrading Flow + function useMemoCache(size) { + var data = new Array(size); - workInProgressHook.memoizedState = ref; - return ref; - } else { - return previousRef; + for (var i = 0; i < size; i++) { + data[i] = REACT_MEMO_CACHE_SENTINEL; } + + return data; } - function dispatchAction(componentIdentity, queue, action) { - if (numberOfReRenders >= RE_RENDER_LIMIT) { - throw new Error( - "Too many re-renders. React limits the number of renders to prevent " + - "an infinite loop." - ); - } + function noop$1() {} - if (componentIdentity === currentlyRenderingComponent) { - // This is a render phase update. Stash it in a lazily-created map of - // queue -> linked list of updates. After this render pass, we'll restart - // and apply the stashed updates on top of the work-in-progress hook. - didScheduleRenderPhaseUpdate = true; - var update = { - action: action, - next: null - }; + var HooksDispatcher = { + readContext: readContext, + use: use, + useContext: useContext, + useMemo: useMemo, + useReducer: useReducer, + useRef: useRef, + useState: useState, + useInsertionEffect: noop$1, + useLayoutEffect: noop$1, + useCallback: useCallback, + // useImperativeHandle is not run in the server environment + useImperativeHandle: noop$1, + // Effects are not run in the server environment. + useEffect: noop$1, + // Debugging effect + useDebugValue: noop$1, + useDeferredValue: useDeferredValue, + useTransition: useTransition, + useId: useId, + // Subscriptions are not setup in a server environment. + useSyncExternalStore: useSyncExternalStore + }; - if (renderPhaseUpdates === null) { - renderPhaseUpdates = new Map(); - } + { + HooksDispatcher.useCacheRefresh = useCacheRefresh; + } - var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); + { + HooksDispatcher.useEffectEvent = useEffectEvent; + } - if (firstRenderPhaseUpdate === undefined) { - // $FlowFixMe[incompatible-use] found when upgrading Flow - renderPhaseUpdates.set(queue, update); - } else { - // Append the update to the end of the list. - var lastRenderPhaseUpdate = firstRenderPhaseUpdate; + { + HooksDispatcher.useMemoCache = useMemoCache; + } - while (lastRenderPhaseUpdate.next !== null) { - lastRenderPhaseUpdate = lastRenderPhaseUpdate.next; - } + { + HooksDispatcher.useHostTransitionStatus = useHostTransitionStatus; + } - lastRenderPhaseUpdate.next = update; - } - } + { + HooksDispatcher.useOptimistic = useOptimistic; + HooksDispatcher.useFormState = useFormState; } - function useCallback(callback, deps) { - return useMemo(function () { - return callback; - }, deps); + var currentResumableState = null; + function setCurrentResumableState(resumableState) { + currentResumableState = resumableState; } - function throwOnUseEffectEventCall() { - throw new Error( - "A function wrapped in useEffectEvent can't be called during rendering." - ); + function getCacheSignal() { + throw new Error("Not implemented."); } - function useEffectEvent(callback) { - // $FlowIgnore[incompatible-return] - return throwOnUseEffectEventCall; + function getCacheForType(resourceType) { + throw new Error("Not implemented."); } - function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { - if (getServerSnapshot === undefined) { - throw new Error( - "Missing getServerSnapshot, which is required for " + - "server-rendered content. Will revert to client rendering." - ); - } + var DefaultCacheDispatcher = { + getCacheSignal: getCacheSignal, + getCacheForType: getCacheForType + }; - return getServerSnapshot(); - } + // Helpers to patch console.logs to avoid logging during side-effect free + // replaying on render function. This currently only patches the object + // lazily which won't cover if the log function was extracted eagerly. + // We could also eagerly patch the method. + var disabledDepth = 0; + var prevLog; + var prevInfo; + var prevWarn; + var prevError; + var prevGroup; + var prevGroupCollapsed; + var prevGroupEnd; - function useDeferredValue(value, initialValue) { - resolveCurrentlyRenderingComponent(); + function disabledLog() {} + + disabledLog.__reactDisabledLog = true; + function disableLogs() { + { + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 + + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; // $FlowFixMe[cannot-write] Flow thinks console is immutable. + + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + /* eslint-enable react-internal/no-production-logging */ + } - if (enableUseDeferredValueInitialArg) { - return initialValue !== undefined ? initialValue : value; - } else { - return value; + disabledDepth++; } } + function reenableLogs() { + { + disabledDepth--; - function unsupportedStartTransition() { - throw new Error( - "startTransition cannot be called during server rendering." - ); - } - - function useTransition() { - resolveCurrentlyRenderingComponent(); - return [false, unsupportedStartTransition]; - } - - function useHostTransitionStatus() { - resolveCurrentlyRenderingComponent(); - return NotPendingTransition; - } + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + var props = { + configurable: true, + enumerable: true, + writable: true + }; // $FlowFixMe[cannot-write] Flow thinks console is immutable. - function unsupportedSetOptimisticState() { - throw new Error("Cannot update optimistic state while rendering."); - } + Object.defineProperties(console, { + log: assign({}, props, { + value: prevLog + }), + info: assign({}, props, { + value: prevInfo + }), + warn: assign({}, props, { + value: prevWarn + }), + error: assign({}, props, { + value: prevError + }), + group: assign({}, props, { + value: prevGroup + }), + groupCollapsed: assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: assign({}, props, { + value: prevGroupEnd + }) + }); + /* eslint-enable react-internal/no-production-logging */ + } - function useOptimistic(passthrough, reducer) { - resolveCurrentlyRenderingComponent(); - return [passthrough, unsupportedSetOptimisticState]; + if (disabledDepth < 0) { + error( + "disabledDepth fell below zero. " + + "This is a bug in React. Please file an issue." + ); + } + } } - function createPostbackFormStateKey( - permalink, - componentKeyPath, - hookIndex - ) { - if (permalink !== undefined) { - // Don't bother to hash a permalink-based key since it's already short. - return "p" + permalink; - } else { - // Append a node to the key path that represents the form state hook. - var keyPath = [componentKeyPath, null, hookIndex]; // Key paths are hashed to reduce the size. It does not need to be secure, - // and it's more important that it's fast than that it's completely - // collision-free. + var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; + var prefix; + function describeBuiltInComponentFrame(name, ownerFn) { + { + if (prefix === undefined) { + // Extract the VM specific prefix used by each line. + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = (match && match[1]) || ""; + } + } // We use the prefix to ensure our stacks line up with native stack frames. - var keyPathHash = createFastHashJS(JSON.stringify(keyPath)); - return "k" + keyPathHash; + return "\n" + prefix + name; } } + var reentry = false; + var componentFrameCache; - function useFormState(action, initialState, permalink) { - resolveCurrentlyRenderingComponent(); // Count the number of useFormState hooks per component. We also use this to - // track the position of this useFormState hook relative to the other ones in - // this component, so we can generate a unique key for each one. + { + var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); + } + /** + * Leverages native browser/VM stack frames to get proper details (e.g. + * filename, line + col number) for a single component in a component stack. We + * do this by: + * (1) throwing and catching an error in the function - this will be our + * control error. + * (2) calling the component which will eventually throw an error that we'll + * catch - this will be our sample error. + * (3) diffing the control and sample error stacks to find the stack frame + * which represents our component. + */ - var formStateHookIndex = formStateCounter++; - var request = currentlyRenderingRequest; // $FlowIgnore[prop-missing] + function describeNativeComponentFrame(fn, construct) { + // If something asked for a stack inside a fake render, it should get ignored. + if (!fn || reentry) { + return ""; + } - var formAction = action.$$FORM_ACTION; + { + var frame = componentFrameCache.get(fn); - if (typeof formAction === "function") { - // This is a server action. These have additional features to enable - // MPA-style form submissions with progressive enhancement. - // TODO: If the same permalink is passed to multiple useFormStates, and - // they all have the same action signature, Fizz will pass the postback - // state to all of them. We should probably only pass it to the first one, - // and/or warn. - // The key is lazily generated and deduped so the that the keypath doesn't - // get JSON.stringify-ed unnecessarily, and at most once. - var nextPostbackStateKey = null; // Determine the current form state. If we received state during an MPA form - // submission, then we will reuse that, if the action identity matches. - // Otherwise we'll use the initial state argument. We will emit a comment - // marker into the stream that indicates whether the state was reused. + if (frame !== undefined) { + return frame; + } + } - var state = initialState; - var componentKeyPath = currentlyRenderingKeyPath; - var postbackFormState = getFormState(request); // $FlowIgnore[prop-missing] + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe[incompatible-type] It does accept undefined. - var isSignatureEqual = action.$$IS_SIGNATURE_EQUAL; + Error.prepareStackTrace = undefined; + var previousDispatcher; - if ( - postbackFormState !== null && - typeof isSignatureEqual === "function" - ) { - var postbackKey = postbackFormState[1]; - var postbackReferenceId = postbackFormState[2]; - var postbackBoundArity = postbackFormState[3]; + { + previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function + // for warnings. - if ( - isSignatureEqual.call( - action, - postbackReferenceId, - postbackBoundArity - ) - ) { - nextPostbackStateKey = createPostbackFormStateKey( - permalink, - componentKeyPath, - formStateHookIndex - ); + ReactCurrentDispatcher$1.current = null; + disableLogs(); + } + /** + * Finding a common stack frame between sample and control errors can be + * tricky given the different types and levels of stack trace truncation from + * different JS VMs. So instead we'll attempt to control what that common + * frame should be through this object method: + * Having both the sample and control errors be in the function under the + * `DescribeNativeComponentFrameRoot` property, + setting the `name` and + * `displayName` properties of the function ensures that a stack + * frame exists that has the method name `DescribeNativeComponentFrameRoot` in + * it for both control and sample stacks. + */ - if (postbackKey === nextPostbackStateKey) { - // This was a match - formStateMatchingIndex = formStateHookIndex; // Reuse the state that was submitted by the form. + var RunInRootFrame = { + DetermineComponentFrameRoot: function () { + var control; - state = postbackFormState[0]; - } - } - } // Bind the state to the first argument of the action. + try { + // This should throw. + if (construct) { + // Something should be setting the props in the constructor. + var Fake = function () { + throw Error(); + }; // $FlowFixMe[prop-missing] - var boundAction = action.bind(null, state); // Wrap the action so the return value is void. + Object.defineProperty(Fake.prototype, "props", { + set: function () { + // We use a throwing setter instead of frozen or non-writable props + // because that won't throw in a non-strict mode function. + throw Error(); + } + }); - var dispatch = function (payload) { - boundAction(payload); - }; // $FlowIgnore[prop-missing] + if (typeof Reflect === "object" && Reflect.construct) { + // We construct a different control for this case to include any extra + // frames added by the construct call. + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } - if (typeof boundAction.$$FORM_ACTION === "function") { - // $FlowIgnore[prop-missing] - dispatch.$$FORM_ACTION = function (prefix) { - var metadata = boundAction.$$FORM_ACTION(prefix); // Override the action URL + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } // $FlowFixMe[prop-missing] found when upgrading Flow - if (permalink !== undefined) { - { - checkAttributeStringCoercion(permalink, "target"); + fn.call(Fake.prototype); } + } else { + try { + throw Error(); + } catch (x) { + control = x; + } // TODO(luna): This will currently only throw if the function component + // tries to access React/ReactDOM/props. We should probably make this throw + // in simple components too - permalink += ""; - metadata.action = permalink; - } - - var formData = metadata.data; + var maybePromise = fn(); // If the function component returns a promise, it's likely an async + // component, which we don't yet support. Attach a noop catch handler to + // silence the error. + // TODO: Implement component stacks for async client components? - if (formData) { - if (nextPostbackStateKey === null) { - nextPostbackStateKey = createPostbackFormStateKey( - permalink, - componentKeyPath, - formStateHookIndex - ); + if (maybePromise && typeof maybePromise.catch === "function") { + maybePromise.catch(function () {}); } - - formData.append("$ACTION_KEY", nextPostbackStateKey); } + } catch (sample) { + // This is inlined manually because closure doesn't do it for us. + if (sample && control && typeof sample.stack === "string") { + return [sample.stack, control.stack]; + } + } - return metadata; - }; + return [null, null]; } + }; // $FlowFixMe[prop-missing] - return [state, dispatch]; - } else { - // This is not a server action, so the implementation is much simpler. - // Bind the state to the first argument of the action. - var _boundAction = action.bind(null, initialState); // Wrap the action so the return value is void. - - var _dispatch2 = function (payload) { - _boundAction(payload); - }; - - return [initialState, _dispatch2]; - } - } - - function useId() { - var task = currentlyRenderingTask; - var treeId = getTreeId(task.treeContext); - var resumableState = currentResumableState; + RunInRootFrame.DetermineComponentFrameRoot.displayName = + "DetermineComponentFrameRoot"; + var namePropDescriptor = Object.getOwnPropertyDescriptor( + RunInRootFrame.DetermineComponentFrameRoot, + "name" + ); // Before ES6, the `name` property was not configurable. - if (resumableState === null) { - throw new Error( - "Invalid hook call. Hooks can only be called inside of the body of a function component." + if (namePropDescriptor && namePropDescriptor.configurable) { + // V8 utilizes a function's `name` property when generating a stack trace. + Object.defineProperty( + RunInRootFrame.DetermineComponentFrameRoot, // Configurable properties can be updated even if its writable descriptor + // is set to `false`. + // $FlowFixMe[cannot-write] + "name", + { + value: "DetermineComponentFrameRoot" + } ); } - var localId = localIdCounter++; - return makeId(resumableState, treeId, localId); - } - - function use(usable) { - if (usable !== null && typeof usable === "object") { - // $FlowFixMe[method-unbinding] - if (typeof usable.then === "function") { - // This is a thenable. - var thenable = usable; - return unwrapThenable(thenable); - } else if (usable.$$typeof === REACT_CONTEXT_TYPE) { - var context = usable; - return readContext(context); - } - } // eslint-disable-next-line react-internal/safe-string-coercion - - throw new Error( - "An unsupported type was passed to use(): " + String(usable) - ); - } + try { + var _RunInRootFrame$Deter = + RunInRootFrame.DetermineComponentFrameRoot(), + sampleStack = _RunInRootFrame$Deter[0], + controlStack = _RunInRootFrame$Deter[1]; - function unwrapThenable(thenable) { - var index = thenableIndexCounter; - thenableIndexCounter += 1; + if (sampleStack && controlStack) { + // This extracts the first frame from the sample that isn't also in the control. + // Skipping one frame that we assume is the frame that calls the two. + var sampleLines = sampleStack.split("\n"); + var controlLines = controlStack.split("\n"); + var s = 0; + var c = 0; - if (thenableState === null) { - thenableState = createThenableState(); - } + while ( + s < sampleLines.length && + !sampleLines[s].includes("DetermineComponentFrameRoot") + ) { + s++; + } - return trackUsedThenable(thenableState, thenable, index); - } + while ( + c < controlLines.length && + !controlLines[c].includes("DetermineComponentFrameRoot") + ) { + c++; + } // We couldn't find our intentionally injected common root frame, attempt + // to find another common root frame by search from the bottom of the + // control stack... - function unsupportedRefresh() { - throw new Error("Cache cannot be refreshed during server rendering."); - } + if (s === sampleLines.length || c === controlLines.length) { + s = sampleLines.length - 1; + c = controlLines.length - 1; - function useCacheRefresh() { - return unsupportedRefresh; - } + while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { + // We expect at least one stack frame to be shared. + // Typically this will be the root most one. However, stack frames may be + // cut off due to maximum stack limits. In this case, one maybe cut off + // earlier than the other. We assume that the sample is longer or the same + // and there for cut off earlier. So we should find the root most frame in + // the sample somewhere in the control. + c--; + } + } - function useMemoCache(size) { - var data = new Array(size); + for (; s >= 1 && c >= 0; s--, c--) { + // Next we find the first one that isn't the same which should be the + // frame that called our sample function and the control. + if (sampleLines[s] !== controlLines[c]) { + // In V8, the first line is describing the message but other VMs don't. + // If we're about to return the first line, and the control is also on the same + // line, that's a pretty good indicator that our sample threw at same line as + // the control. I.e. before we entered the sample frame. So we ignore this result. + // This can happen if you passed a class to function component, or non-function. + if (s !== 1 || c !== 1) { + do { + s--; + c--; // We may still have similar intermediate frames from the construct call. + // The next one that isn't the same should be our match though. - for (var i = 0; i < size; i++) { - data[i] = REACT_MEMO_CACHE_SENTINEL; - } + if (c < 0 || sampleLines[s] !== controlLines[c]) { + // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. + var _frame = + "\n" + sampleLines[s].replace(" at new ", " at "); // If our component frame is labeled "" + // but we have a user-provided "displayName" + // splice it in to make the stack more readable. - return data; - } + if (fn.displayName && _frame.includes("")) { + _frame = _frame.replace("", fn.displayName); + } - function noop$1() {} + if (true) { + if (typeof fn === "function") { + componentFrameCache.set(fn, _frame); + } + } // Return the line we found. - var HooksDispatcher = { - readContext: readContext, - use: use, - useContext: useContext, - useMemo: useMemo, - useReducer: useReducer, - useRef: useRef, - useState: useState, - useInsertionEffect: noop$1, - useLayoutEffect: noop$1, - useCallback: useCallback, - // useImperativeHandle is not run in the server environment - useImperativeHandle: noop$1, - // Effects are not run in the server environment. - useEffect: noop$1, - // Debugging effect - useDebugValue: noop$1, - useDeferredValue: useDeferredValue, - useTransition: useTransition, - useId: useId, - // Subscriptions are not setup in a server environment. - useSyncExternalStore: useSyncExternalStore - }; + return _frame; + } + } while (s >= 1 && c >= 0); + } - { - HooksDispatcher.useCacheRefresh = useCacheRefresh; - } + break; + } + } + } + } finally { + reentry = false; - { - HooksDispatcher.useEffectEvent = useEffectEvent; - } + { + ReactCurrentDispatcher$1.current = previousDispatcher; + reenableLogs(); + } - { - HooksDispatcher.useMemoCache = useMemoCache; - } + Error.prepareStackTrace = previousPrepareStackTrace; + } // Fallback to just using the name if we couldn't make it throw. - { - HooksDispatcher.useHostTransitionStatus = useHostTransitionStatus; - } + var name = fn ? fn.displayName || fn.name : ""; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; - { - HooksDispatcher.useOptimistic = useOptimistic; - HooksDispatcher.useFormState = useFormState; - } + { + if (typeof fn === "function") { + componentFrameCache.set(fn, syntheticFrame); + } + } - var currentResumableState = null; - function setCurrentResumableState(resumableState) { - currentResumableState = resumableState; + return syntheticFrame; } - function getCacheSignal() { - throw new Error("Not implemented."); + function describeClassComponentFrame(ctor, ownerFn) { + { + return describeNativeComponentFrame(ctor, true); + } } - - function getCacheForType(resourceType) { - throw new Error("Not implemented."); + function describeFunctionComponentFrame(fn, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } } - var DefaultCacheDispatcher = { - getCacheSignal: getCacheSignal, - getCacheForType: getCacheForType - }; - function getStackByComponentStackNode(componentStack) { try { var info = ""; diff --git a/compiled/facebook-www/ReactDOMServerStreaming-prod.modern.js b/compiled/facebook-www/ReactDOMServerStreaming-prod.modern.js index 58d910df2ed64..349bd118e9f4e 100644 --- a/compiled/facebook-www/ReactDOMServerStreaming-prod.modern.js +++ b/compiled/facebook-www/ReactDOMServerStreaming-prod.modern.js @@ -2654,149 +2654,6 @@ function getComponentNameFromType(type) { } return null; } -var prefix; -function describeBuiltInComponentFrame(name) { - if (void 0 === prefix) - try { - throw Error(); - } catch (x) { - var match = x.stack.trim().match(/\n( *(at )?)/); - prefix = (match && match[1]) || ""; - } - return "\n" + prefix + name; -} -var reentry = !1; -function describeNativeComponentFrame(fn, construct) { - if (!fn || reentry) return ""; - reentry = !0; - var previousPrepareStackTrace = Error.prepareStackTrace; - Error.prepareStackTrace = void 0; - var RunInRootFrame = { - DetermineComponentFrameRoot: function () { - try { - if (construct) { - var Fake = function () { - throw Error(); - }; - Object.defineProperty(Fake.prototype, "props", { - set: function () { - throw Error(); - } - }); - if ("object" === typeof Reflect && Reflect.construct) { - try { - Reflect.construct(Fake, []); - } catch (x) { - var control = x; - } - Reflect.construct(fn, [], Fake); - } else { - try { - Fake.call(); - } catch (x$19) { - control = x$19; - } - fn.call(Fake.prototype); - } - } else { - try { - throw Error(); - } catch (x$20) { - control = x$20; - } - (Fake = fn()) && - "function" === typeof Fake.catch && - Fake.catch(function () {}); - } - } catch (sample) { - if (sample && control && "string" === typeof sample.stack) - return [sample.stack, control.stack]; - } - return [null, null]; - } - }; - RunInRootFrame.DetermineComponentFrameRoot.displayName = - "DetermineComponentFrameRoot"; - var namePropDescriptor = Object.getOwnPropertyDescriptor( - RunInRootFrame.DetermineComponentFrameRoot, - "name" - ); - namePropDescriptor && - namePropDescriptor.configurable && - Object.defineProperty(RunInRootFrame.DetermineComponentFrameRoot, "name", { - value: "DetermineComponentFrameRoot" - }); - try { - var _RunInRootFrame$Deter = RunInRootFrame.DetermineComponentFrameRoot(), - sampleStack = _RunInRootFrame$Deter[0], - controlStack = _RunInRootFrame$Deter[1]; - if (sampleStack && controlStack) { - var sampleLines = sampleStack.split("\n"), - controlLines = controlStack.split("\n"); - for ( - namePropDescriptor = RunInRootFrame = 0; - RunInRootFrame < sampleLines.length && - !sampleLines[RunInRootFrame].includes("DetermineComponentFrameRoot"); - - ) - RunInRootFrame++; - for ( - ; - namePropDescriptor < controlLines.length && - !controlLines[namePropDescriptor].includes( - "DetermineComponentFrameRoot" - ); - - ) - namePropDescriptor++; - if ( - RunInRootFrame === sampleLines.length || - namePropDescriptor === controlLines.length - ) - for ( - RunInRootFrame = sampleLines.length - 1, - namePropDescriptor = controlLines.length - 1; - 1 <= RunInRootFrame && - 0 <= namePropDescriptor && - sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]; - - ) - namePropDescriptor--; - for ( - ; - 1 <= RunInRootFrame && 0 <= namePropDescriptor; - RunInRootFrame--, namePropDescriptor-- - ) - if (sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]) { - if (1 !== RunInRootFrame || 1 !== namePropDescriptor) { - do - if ( - (RunInRootFrame--, - namePropDescriptor--, - 0 > namePropDescriptor || - sampleLines[RunInRootFrame] !== - controlLines[namePropDescriptor]) - ) { - var frame = - "\n" + - sampleLines[RunInRootFrame].replace(" at new ", " at "); - fn.displayName && - frame.includes("") && - (frame = frame.replace("", fn.displayName)); - return frame; - } - while (1 <= RunInRootFrame && 0 <= namePropDescriptor); - } - break; - } - } - } finally { - (reentry = !1), (Error.prepareStackTrace = previousPrepareStackTrace); - } - return (previousPrepareStackTrace = fn ? fn.displayName || fn.name : "") - ? describeBuiltInComponentFrame(previousPrepareStackTrace) - : ""; -} var emptyContextObject = {}, currentActiveSnapshot = null; function popToNearestCommonAncestor(prev, next) { @@ -3288,11 +3145,11 @@ var HooksDispatcher = { }); return [initialState, action]; } - var boundAction$25 = action.bind(null, initialState); + var boundAction$23 = action.bind(null, initialState); return [ initialState, function (payload) { - boundAction$25(payload); + boundAction$23(payload); } ]; } @@ -3306,7 +3163,150 @@ var HooksDispatcher = { throw Error("Not implemented."); } }, - ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher, + prefix; +function describeBuiltInComponentFrame(name) { + if (void 0 === prefix) + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = (match && match[1]) || ""; + } + return "\n" + prefix + name; +} +var reentry = !1; +function describeNativeComponentFrame(fn, construct) { + if (!fn || reentry) return ""; + reentry = !0; + var previousPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = void 0; + var RunInRootFrame = { + DetermineComponentFrameRoot: function () { + try { + if (construct) { + var Fake = function () { + throw Error(); + }; + Object.defineProperty(Fake.prototype, "props", { + set: function () { + throw Error(); + } + }); + if ("object" === typeof Reflect && Reflect.construct) { + try { + Reflect.construct(Fake, []); + } catch (x) { + var control = x; + } + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x$25) { + control = x$25; + } + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x$26) { + control = x$26; + } + (Fake = fn()) && + "function" === typeof Fake.catch && + Fake.catch(function () {}); + } + } catch (sample) { + if (sample && control && "string" === typeof sample.stack) + return [sample.stack, control.stack]; + } + return [null, null]; + } + }; + RunInRootFrame.DetermineComponentFrameRoot.displayName = + "DetermineComponentFrameRoot"; + var namePropDescriptor = Object.getOwnPropertyDescriptor( + RunInRootFrame.DetermineComponentFrameRoot, + "name" + ); + namePropDescriptor && + namePropDescriptor.configurable && + Object.defineProperty(RunInRootFrame.DetermineComponentFrameRoot, "name", { + value: "DetermineComponentFrameRoot" + }); + try { + var _RunInRootFrame$Deter = RunInRootFrame.DetermineComponentFrameRoot(), + sampleStack = _RunInRootFrame$Deter[0], + controlStack = _RunInRootFrame$Deter[1]; + if (sampleStack && controlStack) { + var sampleLines = sampleStack.split("\n"), + controlLines = controlStack.split("\n"); + for ( + namePropDescriptor = RunInRootFrame = 0; + RunInRootFrame < sampleLines.length && + !sampleLines[RunInRootFrame].includes("DetermineComponentFrameRoot"); + + ) + RunInRootFrame++; + for ( + ; + namePropDescriptor < controlLines.length && + !controlLines[namePropDescriptor].includes( + "DetermineComponentFrameRoot" + ); + + ) + namePropDescriptor++; + if ( + RunInRootFrame === sampleLines.length || + namePropDescriptor === controlLines.length + ) + for ( + RunInRootFrame = sampleLines.length - 1, + namePropDescriptor = controlLines.length - 1; + 1 <= RunInRootFrame && + 0 <= namePropDescriptor && + sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]; + + ) + namePropDescriptor--; + for ( + ; + 1 <= RunInRootFrame && 0 <= namePropDescriptor; + RunInRootFrame--, namePropDescriptor-- + ) + if (sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]) { + if (1 !== RunInRootFrame || 1 !== namePropDescriptor) { + do + if ( + (RunInRootFrame--, + namePropDescriptor--, + 0 > namePropDescriptor || + sampleLines[RunInRootFrame] !== + controlLines[namePropDescriptor]) + ) { + var frame = + "\n" + + sampleLines[RunInRootFrame].replace(" at new ", " at "); + fn.displayName && + frame.includes("") && + (frame = frame.replace("", fn.displayName)); + return frame; + } + while (1 <= RunInRootFrame && 0 <= namePropDescriptor); + } + break; + } + } + } finally { + (reentry = !1), (Error.prepareStackTrace = previousPrepareStackTrace); + } + return (previousPrepareStackTrace = fn ? fn.displayName || fn.name : "") + ? describeBuiltInComponentFrame(previousPrepareStackTrace) + : ""; +} +var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher, ReactCurrentCache = ReactSharedInternals.ReactCurrentCache; function defaultErrorHandler(error) { console.error(error); diff --git a/compiled/facebook-www/ReactDOMTesting-dev.classic.js b/compiled/facebook-www/ReactDOMTesting-dev.classic.js index 658537cf8d7c6..b73a1afddff41 100644 --- a/compiled/facebook-www/ReactDOMTesting-dev.classic.js +++ b/compiled/facebook-www/ReactDOMTesting-dev.classic.js @@ -3834,62 +3834,6 @@ if (__DEV__) { } } - function shouldConstruct$1(Component) { - var prototype = Component.prototype; - return !!(prototype && prototype.isReactComponent); - } - - function describeUnknownElementTypeFrameInDEV(type, ownerFn) { - if (type == null) { - return ""; - } - - if (typeof type === "function") { - { - return describeNativeComponentFrame(type, shouldConstruct$1(type)); - } - } - - if (typeof type === "string") { - return describeBuiltInComponentFrame(type); - } - - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame("Suspense"); - - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame("SuspenseList"); - } - - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render); - - case REACT_MEMO_TYPE: - // Memo may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV(type.type, ownerFn); - - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - // Lazy may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV( - init(payload), - ownerFn - ); - } catch (x) {} - } - } - } - - return ""; - } - function describeFiber(fiber) { switch (fiber.tag) { case HostHoistable: @@ -3939,7 +3883,7 @@ if (__DEV__) { } } - var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var current = null; var isRendering = false; function getCurrentFiberOwnerNameInDevOrNull() { @@ -3971,14 +3915,14 @@ if (__DEV__) { function resetCurrentFiber() { { - ReactDebugCurrentFrame$1.getCurrentStack = null; + ReactDebugCurrentFrame.getCurrentStack = null; current = null; isRendering = false; } } function setCurrentFiber(fiber) { { - ReactDebugCurrentFrame$1.getCurrentStack = + ReactDebugCurrentFrame.getCurrentStack = fiber === null ? null : getCurrentFiberStackInDev; current = fiber; isRendering = false; @@ -10435,111 +10379,6 @@ if (__DEV__) { } } - var loggedTypeFailures = {}; - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - - function setCurrentlyValidatingElement(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV( - element.type, - owner ? owner.type : null - ); - ReactDebugCurrentFrame.setExtraStackFrame(stack); - } else { - ReactDebugCurrentFrame.setExtraStackFrame(null); - } - } - } - - function checkPropTypes( - typeSpecs, - values, - location, - componentName, - element - ) { - { - // $FlowFixMe[incompatible-use] This is okay but Flow doesn't know it. - var has = Function.call.bind(hasOwnProperty); - - for (var typeSpecName in typeSpecs) { - if (has(typeSpecs, typeSpecName)) { - var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to - // fail the render phase where it didn't fail before. So we log it. - // After these have been cleaned up, we'll let them throw. - - try { - // This is intentionally an invariant that gets caught. It's the same - // behavior as without this statement except with a better message. - if (typeof typeSpecs[typeSpecName] !== "function") { - // eslint-disable-next-line react-internal/prod-error-codes - var err = Error( - (componentName || "React class") + - ": " + - location + - " type `" + - typeSpecName + - "` is invalid; " + - "it must be a function, usually from the `prop-types` package, but received `" + - typeof typeSpecs[typeSpecName] + - "`." + - "This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`." - ); - err.name = "Invariant Violation"; - throw err; - } - - error$1 = typeSpecs[typeSpecName]( - values, - typeSpecName, - componentName, - location, - null, - "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED" - ); - } catch (ex) { - error$1 = ex; - } - - if (error$1 && !(error$1 instanceof Error)) { - setCurrentlyValidatingElement(element); - - error( - "%s: type specification of %s" + - " `%s` is invalid; the type checker " + - "function must return `null` or an `Error` but returned a %s. " + - "You may have forgotten to pass an argument to the type checker " + - "creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and " + - "shape all require an argument).", - componentName || "React class", - location, - typeSpecName, - typeof error$1 - ); - - setCurrentlyValidatingElement(null); - } - - if ( - error$1 instanceof Error && - !(error$1.message in loggedTypeFailures) - ) { - // Only monitor this failure once because there tends to be a lot of the - // same error. - loggedTypeFailures[error$1.message] = true; - setCurrentlyValidatingElement(element); - - error("Failed %s type: %s", location, error$1.message); - - setCurrentlyValidatingElement(null); - } - } - } - } - } - /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. @@ -19743,23 +19582,6 @@ if (__DEV__) { // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens after the first render suspends. // We'll need to figure out if this is fine or can cause issues. - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } - } - var render = Component.render; var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent @@ -19848,19 +19670,6 @@ if (__DEV__) { } { - var innerPropTypes = type.propTypes; - - if (innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(type) - ); - } - if (Component.defaultProps !== undefined) { var componentName = getComponentNameFromType(type) || "Unknown"; @@ -19890,22 +19699,6 @@ if (__DEV__) { return child; } - { - var _type = Component.type; - var _innerPropTypes = _type.propTypes; - - if (_innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes( - _innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(_type) - ); - } - } - var currentChild = current.child; // This is always exactly one child var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext( @@ -19951,40 +19744,6 @@ if (__DEV__) { // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens when the inner render suspends. // We'll need to figure out if this is fine or can cause issues. - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var outerMemoType = workInProgress.elementType; - - if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { - // We warn when you define propTypes on lazy() - // so let's just skip over it to find memo() outer wrapper. - // Inner props for memo are validated later. - var lazyComponent = outerMemoType; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - outerMemoType = init(payload); - } catch (x) { - outerMemoType = null; - } // Inner propTypes will be validated in the function component path. - - var outerPropTypes = outerMemoType && outerMemoType.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - nextProps, // Resolved (SimpleMemoComponent has no defaultProps) - "prop", - getComponentNameFromType(outerMemoType) - ); - } - } - } - } - if (current !== null) { var prevProps = current.memoizedProps; @@ -20435,23 +20194,6 @@ if (__DEV__) { nextProps, renderLanes ) { - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } - } - var context; { @@ -20599,21 +20341,6 @@ if (__DEV__) { break; } } - - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } } // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. @@ -21158,21 +20885,6 @@ if (__DEV__) { } case MemoComponent: { - { - if (workInProgress.type !== workInProgress.elementType) { - var outerPropTypes = Component.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - resolvedProps, // Resolved for outer only - "prop", - getComponentNameFromType(Component) - ); - } - } - } - child = updateMemoComponent( null, workInProgress, @@ -22832,17 +22544,6 @@ if (__DEV__) { ); } } - - var providerPropTypes = workInProgress.type.propTypes; - - if (providerPropTypes) { - checkPropTypes( - providerPropTypes, - newProps, - "prop", - "Context.Provider" - ); - } } pushProvider(workInProgress, context, newValue); @@ -23543,31 +23244,16 @@ if (__DEV__) { return updateContextConsumer(current, workInProgress, renderLanes); case MemoComponent: { - var _type2 = workInProgress.type; + var _type = workInProgress.type; var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props. - var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3); - - { - if (workInProgress.type !== workInProgress.elementType) { - var outerPropTypes = _type2.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - _resolvedProps3, // Resolved for outer only - "prop", - getComponentNameFromType(_type2) - ); - } - } - } + var _resolvedProps3 = resolveDefaultProps(_type, _unresolvedProps3); - _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3); + _resolvedProps3 = resolveDefaultProps(_type.type, _resolvedProps3); return updateMemoComponent( current, workInProgress, - _type2, + _type, _resolvedProps3, renderLanes ); @@ -36641,7 +36327,7 @@ if (__DEV__) { return root; } - var ReactVersion = "18.3.0-www-classic-e7aae6cc"; + var ReactVersion = "18.3.0-www-classic-22e81a9f"; function createPortal$1( children, diff --git a/compiled/facebook-www/ReactDOMTesting-dev.modern.js b/compiled/facebook-www/ReactDOMTesting-dev.modern.js index 4d96097dd630a..5adbafd543c1d 100644 --- a/compiled/facebook-www/ReactDOMTesting-dev.modern.js +++ b/compiled/facebook-www/ReactDOMTesting-dev.modern.js @@ -3424,62 +3424,6 @@ if (__DEV__) { } } - function shouldConstruct$1(Component) { - var prototype = Component.prototype; - return !!(prototype && prototype.isReactComponent); - } - - function describeUnknownElementTypeFrameInDEV(type, ownerFn) { - if (type == null) { - return ""; - } - - if (typeof type === "function") { - { - return describeNativeComponentFrame(type, shouldConstruct$1(type)); - } - } - - if (typeof type === "string") { - return describeBuiltInComponentFrame(type); - } - - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame("Suspense"); - - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame("SuspenseList"); - } - - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render); - - case REACT_MEMO_TYPE: - // Memo may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV(type.type, ownerFn); - - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - // Lazy may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV( - init(payload), - ownerFn - ); - } catch (x) {} - } - } - } - - return ""; - } - function describeFiber(fiber) { switch (fiber.tag) { case HostHoistable: @@ -3782,7 +3726,7 @@ if (__DEV__) { return null; } - var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var current = null; var isRendering = false; function getCurrentFiberOwnerNameInDevOrNull() { @@ -3814,14 +3758,14 @@ if (__DEV__) { function resetCurrentFiber() { { - ReactDebugCurrentFrame$1.getCurrentStack = null; + ReactDebugCurrentFrame.getCurrentStack = null; current = null; isRendering = false; } } function setCurrentFiber(fiber) { { - ReactDebugCurrentFrame$1.getCurrentStack = + ReactDebugCurrentFrame.getCurrentStack = fiber === null ? null : getCurrentFiberStackInDev; current = fiber; isRendering = false; @@ -10386,111 +10330,6 @@ if (__DEV__) { } } - var loggedTypeFailures = {}; - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - - function setCurrentlyValidatingElement(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV( - element.type, - owner ? owner.type : null - ); - ReactDebugCurrentFrame.setExtraStackFrame(stack); - } else { - ReactDebugCurrentFrame.setExtraStackFrame(null); - } - } - } - - function checkPropTypes( - typeSpecs, - values, - location, - componentName, - element - ) { - { - // $FlowFixMe[incompatible-use] This is okay but Flow doesn't know it. - var has = Function.call.bind(hasOwnProperty); - - for (var typeSpecName in typeSpecs) { - if (has(typeSpecs, typeSpecName)) { - var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to - // fail the render phase where it didn't fail before. So we log it. - // After these have been cleaned up, we'll let them throw. - - try { - // This is intentionally an invariant that gets caught. It's the same - // behavior as without this statement except with a better message. - if (typeof typeSpecs[typeSpecName] !== "function") { - // eslint-disable-next-line react-internal/prod-error-codes - var err = Error( - (componentName || "React class") + - ": " + - location + - " type `" + - typeSpecName + - "` is invalid; " + - "it must be a function, usually from the `prop-types` package, but received `" + - typeof typeSpecs[typeSpecName] + - "`." + - "This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`." - ); - err.name = "Invariant Violation"; - throw err; - } - - error$1 = typeSpecs[typeSpecName]( - values, - typeSpecName, - componentName, - location, - null, - "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED" - ); - } catch (ex) { - error$1 = ex; - } - - if (error$1 && !(error$1 instanceof Error)) { - setCurrentlyValidatingElement(element); - - error( - "%s: type specification of %s" + - " `%s` is invalid; the type checker " + - "function must return `null` or an `Error` but returned a %s. " + - "You may have forgotten to pass an argument to the type checker " + - "creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and " + - "shape all require an argument).", - componentName || "React class", - location, - typeSpecName, - typeof error$1 - ); - - setCurrentlyValidatingElement(null); - } - - if ( - error$1 instanceof Error && - !(error$1.message in loggedTypeFailures) - ) { - // Only monitor this failure once because there tends to be a lot of the - // same error. - loggedTypeFailures[error$1.message] = true; - setCurrentlyValidatingElement(element); - - error("Failed %s type: %s", location, error$1.message); - - setCurrentlyValidatingElement(null); - } - } - } - } - } - /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. @@ -19653,23 +19492,6 @@ if (__DEV__) { // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens after the first render suspends. // We'll need to figure out if this is fine or can cause issues. - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } - } - var render = Component.render; var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent @@ -19758,19 +19580,6 @@ if (__DEV__) { } { - var innerPropTypes = type.propTypes; - - if (innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(type) - ); - } - if (Component.defaultProps !== undefined) { var componentName = getComponentNameFromType(type) || "Unknown"; @@ -19800,22 +19609,6 @@ if (__DEV__) { return child; } - { - var _type = Component.type; - var _innerPropTypes = _type.propTypes; - - if (_innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes( - _innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(_type) - ); - } - } - var currentChild = current.child; // This is always exactly one child var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext( @@ -19861,40 +19654,6 @@ if (__DEV__) { // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens when the inner render suspends. // We'll need to figure out if this is fine or can cause issues. - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var outerMemoType = workInProgress.elementType; - - if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { - // We warn when you define propTypes on lazy() - // so let's just skip over it to find memo() outer wrapper. - // Inner props for memo are validated later. - var lazyComponent = outerMemoType; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - outerMemoType = init(payload); - } catch (x) { - outerMemoType = null; - } // Inner propTypes will be validated in the function component path. - - var outerPropTypes = outerMemoType && outerMemoType.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - nextProps, // Resolved (SimpleMemoComponent has no defaultProps) - "prop", - getComponentNameFromType(outerMemoType) - ); - } - } - } - } - if (current !== null) { var prevProps = current.memoizedProps; @@ -20345,23 +20104,6 @@ if (__DEV__) { nextProps, renderLanes ) { - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } - } - var context; var nextChildren; @@ -20500,21 +20242,6 @@ if (__DEV__) { break; } } - - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } } // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. @@ -21038,21 +20765,6 @@ if (__DEV__) { } case MemoComponent: { - { - if (workInProgress.type !== workInProgress.elementType) { - var outerPropTypes = Component.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - resolvedProps, // Resolved for outer only - "prop", - getComponentNameFromType(Component) - ); - } - } - } - child = updateMemoComponent( null, workInProgress, @@ -22712,17 +22424,6 @@ if (__DEV__) { ); } } - - var providerPropTypes = workInProgress.type.propTypes; - - if (providerPropTypes) { - checkPropTypes( - providerPropTypes, - newProps, - "prop", - "Context.Provider" - ); - } } pushProvider(workInProgress, context, newValue); @@ -23417,31 +23118,16 @@ if (__DEV__) { return updateContextConsumer(current, workInProgress, renderLanes); case MemoComponent: { - var _type2 = workInProgress.type; + var _type = workInProgress.type; var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props. - var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3); - - { - if (workInProgress.type !== workInProgress.elementType) { - var outerPropTypes = _type2.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - _resolvedProps3, // Resolved for outer only - "prop", - getComponentNameFromType(_type2) - ); - } - } - } + var _resolvedProps3 = resolveDefaultProps(_type, _unresolvedProps3); - _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3); + _resolvedProps3 = resolveDefaultProps(_type.type, _resolvedProps3); return updateMemoComponent( current, workInProgress, - _type2, + _type, _resolvedProps3, renderLanes ); @@ -36477,7 +36163,7 @@ if (__DEV__) { return root; } - var ReactVersion = "18.3.0-www-modern-6eadd94f"; + var ReactVersion = "18.3.0-www-modern-f98671a5"; function createPortal$1( children, diff --git a/compiled/facebook-www/ReactServer-dev.modern.js b/compiled/facebook-www/ReactServer-dev.modern.js index f4c0c9fea4ff6..0d086b6981892 100644 --- a/compiled/facebook-www/ReactServer-dev.modern.js +++ b/compiled/facebook-www/ReactServer-dev.modern.js @@ -2231,9 +2231,9 @@ if (__DEV__) { } if (render != null) { - if (render.defaultProps != null || render.propTypes != null) { + if (render.defaultProps != null) { error( - "forwardRef render functions do not support propTypes or defaultProps. " + + "forwardRef render functions do not support defaultProps. " + "Did you accidentally pass a React component?" ); } @@ -2662,7 +2662,7 @@ if (__DEV__) { console["error"](error); }; - var ReactVersion = "18.3.0-www-modern-5d89467b"; + var ReactVersion = "18.3.0-www-modern-508518a5"; // Patch fetch var Children = { diff --git a/compiled/facebook-www/ReactTestRenderer-dev.classic.js b/compiled/facebook-www/ReactTestRenderer-dev.classic.js index 101e3da384959..4467995c2de3d 100644 --- a/compiled/facebook-www/ReactTestRenderer-dev.classic.js +++ b/compiled/facebook-www/ReactTestRenderer-dev.classic.js @@ -4069,6 +4069,50 @@ if (__DEV__) { } } + // $FlowFixMe[method-unbinding] + var hasOwnProperty = Object.prototype.hasOwnProperty; + + /** + * Performs equality by iterating through keys on an object and returning false + * when any key has values which are not strictly equal between the arguments. + * Returns true when the values of all keys are strictly equal. + */ + + function shallowEqual(objA, objB) { + if (objectIs(objA, objB)) { + return true; + } + + if ( + typeof objA !== "object" || + objA === null || + typeof objB !== "object" || + objB === null + ) { + return false; + } + + var keysA = Object.keys(objA); + var keysB = Object.keys(objB); + + if (keysA.length !== keysB.length) { + return false; + } // Test for A's keys different from B. + + for (var i = 0; i < keysA.length; i++) { + var currentKey = keysA[i]; + + if ( + !hasOwnProperty.call(objB, currentKey) || // $FlowFixMe[incompatible-use] lost refinement of `objB` + !objectIs(objA[currentKey], objB[currentKey]) + ) { + return false; + } + } + + return true; + } + var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher; var prefix; function describeBuiltInComponentFrame(name, ownerFn) { @@ -4352,211 +4396,6 @@ if (__DEV__) { } } - function shouldConstruct$1(Component) { - var prototype = Component.prototype; - return !!(prototype && prototype.isReactComponent); - } - - function describeUnknownElementTypeFrameInDEV(type, ownerFn) { - if (type == null) { - return ""; - } - - if (typeof type === "function") { - { - return describeNativeComponentFrame(type, shouldConstruct$1(type)); - } - } - - if (typeof type === "string") { - return describeBuiltInComponentFrame(type); - } - - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame("Suspense"); - - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame("SuspenseList"); - } - - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render); - - case REACT_MEMO_TYPE: - // Memo may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV(type.type, ownerFn); - - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - // Lazy may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV( - init(payload), - ownerFn - ); - } catch (x) {} - } - } - } - - return ""; - } - - // $FlowFixMe[method-unbinding] - var hasOwnProperty = Object.prototype.hasOwnProperty; - - var loggedTypeFailures = {}; - var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; - - function setCurrentlyValidatingElement(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV( - element.type, - owner ? owner.type : null - ); - ReactDebugCurrentFrame$1.setExtraStackFrame(stack); - } else { - ReactDebugCurrentFrame$1.setExtraStackFrame(null); - } - } - } - - function checkPropTypes( - typeSpecs, - values, - location, - componentName, - element - ) { - { - // $FlowFixMe[incompatible-use] This is okay but Flow doesn't know it. - var has = Function.call.bind(hasOwnProperty); - - for (var typeSpecName in typeSpecs) { - if (has(typeSpecs, typeSpecName)) { - var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to - // fail the render phase where it didn't fail before. So we log it. - // After these have been cleaned up, we'll let them throw. - - try { - // This is intentionally an invariant that gets caught. It's the same - // behavior as without this statement except with a better message. - if (typeof typeSpecs[typeSpecName] !== "function") { - // eslint-disable-next-line react-internal/prod-error-codes - var err = Error( - (componentName || "React class") + - ": " + - location + - " type `" + - typeSpecName + - "` is invalid; " + - "it must be a function, usually from the `prop-types` package, but received `" + - typeof typeSpecs[typeSpecName] + - "`." + - "This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`." - ); - err.name = "Invariant Violation"; - throw err; - } - - error$1 = typeSpecs[typeSpecName]( - values, - typeSpecName, - componentName, - location, - null, - "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED" - ); - } catch (ex) { - error$1 = ex; - } - - if (error$1 && !(error$1 instanceof Error)) { - setCurrentlyValidatingElement(element); - - error( - "%s: type specification of %s" + - " `%s` is invalid; the type checker " + - "function must return `null` or an `Error` but returned a %s. " + - "You may have forgotten to pass an argument to the type checker " + - "creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and " + - "shape all require an argument).", - componentName || "React class", - location, - typeSpecName, - typeof error$1 - ); - - setCurrentlyValidatingElement(null); - } - - if ( - error$1 instanceof Error && - !(error$1.message in loggedTypeFailures) - ) { - // Only monitor this failure once because there tends to be a lot of the - // same error. - loggedTypeFailures[error$1.message] = true; - setCurrentlyValidatingElement(element); - - error("Failed %s type: %s", location, error$1.message); - - setCurrentlyValidatingElement(null); - } - } - } - } - } - - /** - * Performs equality by iterating through keys on an object and returning false - * when any key has values which are not strictly equal between the arguments. - * Returns true when the values of all keys are strictly equal. - */ - - function shallowEqual(objA, objB) { - if (objectIs(objA, objB)) { - return true; - } - - if ( - typeof objA !== "object" || - objA === null || - typeof objB !== "object" || - objB === null - ) { - return false; - } - - var keysA = Object.keys(objA); - var keysB = Object.keys(objB); - - if (keysA.length !== keysB.length) { - return false; - } // Test for A's keys different from B. - - for (var i = 0; i < keysA.length; i++) { - var currentKey = keysA[i]; - - if ( - !hasOwnProperty.call(objB, currentKey) || // $FlowFixMe[incompatible-use] lost refinement of `objB` - !objectIs(objA[currentKey], objB[currentKey]) - ) { - return false; - } - } - - return true; - } - function describeFiber(fiber) { switch (fiber.tag) { case HostHoistable: @@ -13066,23 +12905,6 @@ if (__DEV__) { // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens after the first render suspends. // We'll need to figure out if this is fine or can cause issues. - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } - } - var render = Component.render; var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent @@ -13157,19 +12979,6 @@ if (__DEV__) { } { - var innerPropTypes = type.propTypes; - - if (innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(type) - ); - } - if (Component.defaultProps !== undefined) { var componentName = getComponentNameFromType(type) || "Unknown"; @@ -13199,22 +13008,6 @@ if (__DEV__) { return child; } - { - var _type = Component.type; - var _innerPropTypes = _type.propTypes; - - if (_innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes( - _innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(_type) - ); - } - } - var currentChild = current.child; // This is always exactly one child var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext( @@ -13260,40 +13053,6 @@ if (__DEV__) { // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens when the inner render suspends. // We'll need to figure out if this is fine or can cause issues. - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var outerMemoType = workInProgress.elementType; - - if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { - // We warn when you define propTypes on lazy() - // so let's just skip over it to find memo() outer wrapper. - // Inner props for memo are validated later. - var lazyComponent = outerMemoType; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - outerMemoType = init(payload); - } catch (x) { - outerMemoType = null; - } // Inner propTypes will be validated in the function component path. - - var outerPropTypes = outerMemoType && outerMemoType.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - nextProps, // Resolved (SimpleMemoComponent has no defaultProps) - "prop", - getComponentNameFromType(outerMemoType) - ); - } - } - } - } - if (current !== null) { var prevProps = current.memoizedProps; @@ -13660,23 +13419,6 @@ if (__DEV__) { nextProps, renderLanes ) { - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } - } - var context; { @@ -13797,21 +13539,6 @@ if (__DEV__) { break; } } - - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } } // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. @@ -14168,21 +13895,6 @@ if (__DEV__) { } case MemoComponent: { - { - if (workInProgress.type !== workInProgress.elementType) { - var outerPropTypes = Component.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - resolvedProps, // Resolved for outer only - "prop", - getComponentNameFromType(Component) - ); - } - } - } - child = updateMemoComponent( null, workInProgress, @@ -15639,17 +15351,6 @@ if (__DEV__) { ); } } - - var providerPropTypes = workInProgress.type.propTypes; - - if (providerPropTypes) { - checkPropTypes( - providerPropTypes, - newProps, - "prop", - "Context.Provider" - ); - } } pushProvider(workInProgress, context, newValue); @@ -16257,31 +15958,16 @@ if (__DEV__) { return updateContextConsumer(current, workInProgress, renderLanes); case MemoComponent: { - var _type2 = workInProgress.type; + var _type = workInProgress.type; var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props. - var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3); - - { - if (workInProgress.type !== workInProgress.elementType) { - var outerPropTypes = _type2.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - _resolvedProps3, // Resolved for outer only - "prop", - getComponentNameFromType(_type2) - ); - } - } - } + var _resolvedProps3 = resolveDefaultProps(_type, _unresolvedProps3); - _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3); + _resolvedProps3 = resolveDefaultProps(_type.type, _resolvedProps3); return updateMemoComponent( current, workInProgress, - _type2, + _type, _resolvedProps3, renderLanes ); @@ -26297,7 +25983,7 @@ if (__DEV__) { return root; } - var ReactVersion = "18.3.0-www-classic-2ab113e0"; + var ReactVersion = "18.3.0-www-classic-4db3a9db"; // Might add PROFILE later. diff --git a/compiled/facebook-www/ReactTestRenderer-dev.modern.js b/compiled/facebook-www/ReactTestRenderer-dev.modern.js index 4d3439670cf39..416e3a9540c5e 100644 --- a/compiled/facebook-www/ReactTestRenderer-dev.modern.js +++ b/compiled/facebook-www/ReactTestRenderer-dev.modern.js @@ -4069,6 +4069,50 @@ if (__DEV__) { } } + // $FlowFixMe[method-unbinding] + var hasOwnProperty = Object.prototype.hasOwnProperty; + + /** + * Performs equality by iterating through keys on an object and returning false + * when any key has values which are not strictly equal between the arguments. + * Returns true when the values of all keys are strictly equal. + */ + + function shallowEqual(objA, objB) { + if (objectIs(objA, objB)) { + return true; + } + + if ( + typeof objA !== "object" || + objA === null || + typeof objB !== "object" || + objB === null + ) { + return false; + } + + var keysA = Object.keys(objA); + var keysB = Object.keys(objB); + + if (keysA.length !== keysB.length) { + return false; + } // Test for A's keys different from B. + + for (var i = 0; i < keysA.length; i++) { + var currentKey = keysA[i]; + + if ( + !hasOwnProperty.call(objB, currentKey) || // $FlowFixMe[incompatible-use] lost refinement of `objB` + !objectIs(objA[currentKey], objB[currentKey]) + ) { + return false; + } + } + + return true; + } + var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher; var prefix; function describeBuiltInComponentFrame(name, ownerFn) { @@ -4352,211 +4396,6 @@ if (__DEV__) { } } - function shouldConstruct$1(Component) { - var prototype = Component.prototype; - return !!(prototype && prototype.isReactComponent); - } - - function describeUnknownElementTypeFrameInDEV(type, ownerFn) { - if (type == null) { - return ""; - } - - if (typeof type === "function") { - { - return describeNativeComponentFrame(type, shouldConstruct$1(type)); - } - } - - if (typeof type === "string") { - return describeBuiltInComponentFrame(type); - } - - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame("Suspense"); - - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame("SuspenseList"); - } - - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render); - - case REACT_MEMO_TYPE: - // Memo may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV(type.type, ownerFn); - - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - // Lazy may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV( - init(payload), - ownerFn - ); - } catch (x) {} - } - } - } - - return ""; - } - - // $FlowFixMe[method-unbinding] - var hasOwnProperty = Object.prototype.hasOwnProperty; - - var loggedTypeFailures = {}; - var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; - - function setCurrentlyValidatingElement(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV( - element.type, - owner ? owner.type : null - ); - ReactDebugCurrentFrame$1.setExtraStackFrame(stack); - } else { - ReactDebugCurrentFrame$1.setExtraStackFrame(null); - } - } - } - - function checkPropTypes( - typeSpecs, - values, - location, - componentName, - element - ) { - { - // $FlowFixMe[incompatible-use] This is okay but Flow doesn't know it. - var has = Function.call.bind(hasOwnProperty); - - for (var typeSpecName in typeSpecs) { - if (has(typeSpecs, typeSpecName)) { - var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to - // fail the render phase where it didn't fail before. So we log it. - // After these have been cleaned up, we'll let them throw. - - try { - // This is intentionally an invariant that gets caught. It's the same - // behavior as without this statement except with a better message. - if (typeof typeSpecs[typeSpecName] !== "function") { - // eslint-disable-next-line react-internal/prod-error-codes - var err = Error( - (componentName || "React class") + - ": " + - location + - " type `" + - typeSpecName + - "` is invalid; " + - "it must be a function, usually from the `prop-types` package, but received `" + - typeof typeSpecs[typeSpecName] + - "`." + - "This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`." - ); - err.name = "Invariant Violation"; - throw err; - } - - error$1 = typeSpecs[typeSpecName]( - values, - typeSpecName, - componentName, - location, - null, - "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED" - ); - } catch (ex) { - error$1 = ex; - } - - if (error$1 && !(error$1 instanceof Error)) { - setCurrentlyValidatingElement(element); - - error( - "%s: type specification of %s" + - " `%s` is invalid; the type checker " + - "function must return `null` or an `Error` but returned a %s. " + - "You may have forgotten to pass an argument to the type checker " + - "creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and " + - "shape all require an argument).", - componentName || "React class", - location, - typeSpecName, - typeof error$1 - ); - - setCurrentlyValidatingElement(null); - } - - if ( - error$1 instanceof Error && - !(error$1.message in loggedTypeFailures) - ) { - // Only monitor this failure once because there tends to be a lot of the - // same error. - loggedTypeFailures[error$1.message] = true; - setCurrentlyValidatingElement(element); - - error("Failed %s type: %s", location, error$1.message); - - setCurrentlyValidatingElement(null); - } - } - } - } - } - - /** - * Performs equality by iterating through keys on an object and returning false - * when any key has values which are not strictly equal between the arguments. - * Returns true when the values of all keys are strictly equal. - */ - - function shallowEqual(objA, objB) { - if (objectIs(objA, objB)) { - return true; - } - - if ( - typeof objA !== "object" || - objA === null || - typeof objB !== "object" || - objB === null - ) { - return false; - } - - var keysA = Object.keys(objA); - var keysB = Object.keys(objB); - - if (keysA.length !== keysB.length) { - return false; - } // Test for A's keys different from B. - - for (var i = 0; i < keysA.length; i++) { - var currentKey = keysA[i]; - - if ( - !hasOwnProperty.call(objB, currentKey) || // $FlowFixMe[incompatible-use] lost refinement of `objB` - !objectIs(objA[currentKey], objB[currentKey]) - ) { - return false; - } - } - - return true; - } - function describeFiber(fiber) { switch (fiber.tag) { case HostHoistable: @@ -13066,23 +12905,6 @@ if (__DEV__) { // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens after the first render suspends. // We'll need to figure out if this is fine or can cause issues. - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } - } - var render = Component.render; var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent @@ -13157,19 +12979,6 @@ if (__DEV__) { } { - var innerPropTypes = type.propTypes; - - if (innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(type) - ); - } - if (Component.defaultProps !== undefined) { var componentName = getComponentNameFromType(type) || "Unknown"; @@ -13199,22 +13008,6 @@ if (__DEV__) { return child; } - { - var _type = Component.type; - var _innerPropTypes = _type.propTypes; - - if (_innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes( - _innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(_type) - ); - } - } - var currentChild = current.child; // This is always exactly one child var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext( @@ -13260,40 +13053,6 @@ if (__DEV__) { // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens when the inner render suspends. // We'll need to figure out if this is fine or can cause issues. - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var outerMemoType = workInProgress.elementType; - - if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { - // We warn when you define propTypes on lazy() - // so let's just skip over it to find memo() outer wrapper. - // Inner props for memo are validated later. - var lazyComponent = outerMemoType; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - outerMemoType = init(payload); - } catch (x) { - outerMemoType = null; - } // Inner propTypes will be validated in the function component path. - - var outerPropTypes = outerMemoType && outerMemoType.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - nextProps, // Resolved (SimpleMemoComponent has no defaultProps) - "prop", - getComponentNameFromType(outerMemoType) - ); - } - } - } - } - if (current !== null) { var prevProps = current.memoizedProps; @@ -13660,23 +13419,6 @@ if (__DEV__) { nextProps, renderLanes ) { - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } - } - var context; { @@ -13797,21 +13539,6 @@ if (__DEV__) { break; } } - - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } } // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. @@ -14168,21 +13895,6 @@ if (__DEV__) { } case MemoComponent: { - { - if (workInProgress.type !== workInProgress.elementType) { - var outerPropTypes = Component.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - resolvedProps, // Resolved for outer only - "prop", - getComponentNameFromType(Component) - ); - } - } - } - child = updateMemoComponent( null, workInProgress, @@ -15639,17 +15351,6 @@ if (__DEV__) { ); } } - - var providerPropTypes = workInProgress.type.propTypes; - - if (providerPropTypes) { - checkPropTypes( - providerPropTypes, - newProps, - "prop", - "Context.Provider" - ); - } } pushProvider(workInProgress, context, newValue); @@ -16257,31 +15958,16 @@ if (__DEV__) { return updateContextConsumer(current, workInProgress, renderLanes); case MemoComponent: { - var _type2 = workInProgress.type; + var _type = workInProgress.type; var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props. - var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3); - - { - if (workInProgress.type !== workInProgress.elementType) { - var outerPropTypes = _type2.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - _resolvedProps3, // Resolved for outer only - "prop", - getComponentNameFromType(_type2) - ); - } - } - } + var _resolvedProps3 = resolveDefaultProps(_type, _unresolvedProps3); - _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3); + _resolvedProps3 = resolveDefaultProps(_type.type, _resolvedProps3); return updateMemoComponent( current, workInProgress, - _type2, + _type, _resolvedProps3, renderLanes ); @@ -26297,7 +25983,7 @@ if (__DEV__) { return root; } - var ReactVersion = "18.3.0-www-modern-0a08dcb6"; + var ReactVersion = "18.3.0-www-modern-b7080615"; // Might add PROFILE later. diff --git a/compiled/facebook-www/__test_utils__/ReactAllWarnings.js b/compiled/facebook-www/__test_utils__/ReactAllWarnings.js index ef8c4eaa7c6f2..c1efca153efc6 100644 --- a/compiled/facebook-www/__test_utils__/ReactAllWarnings.js +++ b/compiled/facebook-www/__test_utils__/ReactAllWarnings.js @@ -371,7 +371,7 @@ export default [ "dispatchCommand was called with a ref that isn't a native component. Use React.forwardRef to get access to the underlying native component", "flushSync was called from inside a lifecycle method. React cannot flush when React is already rendering. Consider moving this call to a scheduler task or micro task.", "forwardRef render functions accept exactly two parameters: props and ref. %s", - "forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?", + "forwardRef render functions do not support defaultProps. Did you accidentally pass a React component?", "forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...)).", "forwardRef requires a render function but was given %s.", "getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.",