repo_name
stringlengths
4
68
text
stringlengths
21
269k
avg_line_length
float64
9.4
9.51k
max_line_length
int64
20
28.5k
alphnanum_fraction
float64
0.3
0.92
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {ReactContext} from 'shared/ReactTypes'; import {REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED} from 'shared/ReactSymbols'; import {isPrimaryRenderer} from './ReactFizzConfig'; let rendererSigil; if (__DEV__) { // 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. type ContextNode<T> = { parent: null | ContextNode<any>, depth: number, // Short hand to compute the depth of the tree at this node. context: ReactContext<T>, parentValue: T, value: T, }; // The structure of a context snapshot is an implementation of this file. // Currently, it's implemented as tracking the current active node. export opaque type ContextSnapshot = null | ContextNode<any>; export const rootContextSnapshot: ContextSnapshot = 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. let currentActiveSnapshot: ContextSnapshot = null; function popNode(prev: ContextNode<any>): void { if (isPrimaryRenderer) { prev.context._currentValue = prev.parentValue; } else { prev.context._currentValue2 = prev.parentValue; } } function pushNode(next: ContextNode<any>): void { if (isPrimaryRenderer) { next.context._currentValue = next.value; } else { next.context._currentValue2 = next.value; } } function popToNearestCommonAncestor( prev: ContextNode<any>, next: ContextNode<any>, ): void { if (prev === next) { // We've found a shared ancestor. We don't need to pop nor reapply this one or anything above. } else { popNode(prev); const parentPrev = prev.parent; const parentNext = next.parent; 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.', ); } popToNearestCommonAncestor(parentPrev, parentNext); } // On the way back, we push the new ones that weren't common. pushNode(next); } } function popAllPrevious(prev: ContextNode<any>): void { popNode(prev); const parentPrev = prev.parent; if (parentPrev !== null) { popAllPrevious(parentPrev); } } function pushAllNext(next: ContextNode<any>): void { const parentNext = next.parent; if (parentNext !== null) { pushAllNext(parentNext); } pushNode(next); } function popPreviousToCommonLevel( prev: ContextNode<any>, next: ContextNode<any>, ): void { popNode(prev); const 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.', ); } 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); } } function popNextToCommonLevel( prev: ContextNode<any>, next: ContextNode<any>, ): void { const parentNext = next.parent; 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 (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. export function switchContext(newSnapshot: ContextSnapshot): void { // 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. const prev = currentActiveSnapshot; const 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); } currentActiveSnapshot = next; } } export function pushProvider<T>( context: ReactContext<T>, nextValue: T, ): ContextSnapshot { let prevValue; if (isPrimaryRenderer) { prevValue = context._currentValue; context._currentValue = nextValue; if (__DEV__) { if ( context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil ) { console.error( 'Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.', ); } context._currentRenderer = rendererSigil; } } else { prevValue = context._currentValue2; context._currentValue2 = nextValue; if (__DEV__) { if ( context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil ) { console.error( 'Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.', ); } context._currentRenderer2 = rendererSigil; } } const prevNode = currentActiveSnapshot; const newNode: ContextNode<T> = { parent: prevNode, depth: prevNode === null ? 0 : prevNode.depth + 1, context: context, parentValue: prevValue, value: nextValue, }; currentActiveSnapshot = newNode; return newNode; } export function popProvider<T>(context: ReactContext<T>): ContextSnapshot { const 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 (__DEV__) { if (prevSnapshot.context !== context) { console.error( 'The parent context is not the expected context. This is probably a bug in React.', ); } } if (isPrimaryRenderer) { const value = prevSnapshot.parentValue; if (value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) { prevSnapshot.context._currentValue = prevSnapshot.context._defaultValue; } else { prevSnapshot.context._currentValue = value; } if (__DEV__) { if ( context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil ) { console.error( 'Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.', ); } context._currentRenderer = rendererSigil; } } else { const value = prevSnapshot.parentValue; if (value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) { prevSnapshot.context._currentValue2 = prevSnapshot.context._defaultValue; } else { prevSnapshot.context._currentValue2 = value; } if (__DEV__) { if ( context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil ) { console.error( 'Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.', ); } context._currentRenderer2 = rendererSigil; } } return (currentActiveSnapshot = prevSnapshot.parent); } export function getActiveContext(): ContextSnapshot { return currentActiveSnapshot; } export function readContext<T>(context: ReactContext<T>): T { const value = isPrimaryRenderer ? context._currentValue : context._currentValue2; return value; }
30.076412
99
0.6677
Python-Penetration-Testing-for-Developers
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core * @jest-environment node */ 'use strict'; let React; let ReactNoop; let act; describe('ReactIncrementalUpdatesMinimalism', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); act = require('internal-test-utils').act; }); it('should render a simple component', async () => { function Child() { return <div>Hello World</div>; } function Parent() { return <Child />; } ReactNoop.startTrackingHostCounters(); await act(() => ReactNoop.render(<Parent />)); expect(ReactNoop.stopTrackingHostCounters()).toEqual({ hostUpdateCounter: 0, }); ReactNoop.startTrackingHostCounters(); await act(() => ReactNoop.render(<Parent />)); expect(ReactNoop.stopTrackingHostCounters()).toEqual({ hostUpdateCounter: 1, }); }); it('should not diff referentially equal host elements', async () => { function Leaf(props) { return ( <span> hello <b /> {props.name} </span> ); } const constEl = ( <div> <Leaf name="world" /> </div> ); function Child() { return constEl; } function Parent() { return <Child />; } ReactNoop.startTrackingHostCounters(); await act(() => ReactNoop.render(<Parent />)); expect(ReactNoop.stopTrackingHostCounters()).toEqual({ hostUpdateCounter: 0, }); ReactNoop.startTrackingHostCounters(); await act(() => ReactNoop.render(<Parent />)); expect(ReactNoop.stopTrackingHostCounters()).toEqual({ hostUpdateCounter: 0, }); }); it('should not diff parents of setState targets', async () => { let childInst; function Leaf(props) { return ( <span> hello <b /> {props.name} </span> ); } class Child extends React.Component { state = {name: 'Batman'}; render() { childInst = this; return ( <div> <Leaf name={this.state.name} /> </div> ); } } function Parent() { return ( <section> <div> <Leaf name="world" /> <Child /> <hr /> <Leaf name="world" /> </div> </section> ); } ReactNoop.startTrackingHostCounters(); await act(() => ReactNoop.render(<Parent />)); expect(ReactNoop.stopTrackingHostCounters()).toEqual({ hostUpdateCounter: 0, }); ReactNoop.startTrackingHostCounters(); await act(() => childInst.setState({name: 'Robin'})); expect(ReactNoop.stopTrackingHostCounters()).toEqual({ // Child > div // Child > Leaf > span // Child > Leaf > span > b // Child > Leaf > span > #text hostUpdateCounter: 4, }); ReactNoop.startTrackingHostCounters(); await act(() => ReactNoop.render(<Parent />)); expect(ReactNoop.stopTrackingHostCounters()).toEqual({ // Parent > section // Parent > section > div // Parent > section > div > Leaf > span // Parent > section > div > Leaf > span > b // Parent > section > div > Child > div // Parent > section > div > Child > div > Leaf > span // Parent > section > div > Child > div > Leaf > span > b // Parent > section > div > hr // Parent > section > div > Leaf > span // Parent > section > div > Leaf > span > b hostUpdateCounter: 10, }); }); });
22.878981
71
0.554696
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core * @jest-environment node */ 'use strict'; let React; let ReactDOMFizzStatic; let Suspense; describe('ReactDOMFizzStaticNode', () => { beforeEach(() => { jest.resetModules(); React = require('react'); if (__EXPERIMENTAL__) { ReactDOMFizzStatic = require('react-dom/static'); } Suspense = React.Suspense; }); const theError = new Error('This is an error'); function Throw() { throw theError; } const theInfinitePromise = new Promise(() => {}); function InfiniteSuspend() { throw theInfinitePromise; } function readContent(readable) { return new Promise((resolve, reject) => { let content = ''; readable.on('data', chunk => { content += Buffer.from(chunk).toString('utf8'); }); readable.on('error', error => { reject(error); }); readable.on('end', () => resolve(content)); }); } // @gate experimental it('should call prerenderToNodeStream', async () => { const result = await ReactDOMFizzStatic.prerenderToNodeStream( <div>hello world</div>, ); const prelude = await readContent(result.prelude); expect(prelude).toMatchInlineSnapshot(`"<div>hello world</div>"`); }); // @gate experimental it('should emit DOCTYPE at the root of the document', async () => { const result = await ReactDOMFizzStatic.prerenderToNodeStream( <html> <body>hello world</body> </html>, ); const prelude = await readContent(result.prelude); if (gate(flags => flags.enableFloat)) { expect(prelude).toMatchInlineSnapshot( `"<!DOCTYPE html><html><head></head><body>hello world</body></html>"`, ); } else { expect(prelude).toMatchInlineSnapshot( `"<!DOCTYPE html><html><body>hello world</body></html>"`, ); } }); // @gate experimental it('should emit bootstrap script src at the end', async () => { const result = await ReactDOMFizzStatic.prerenderToNodeStream( <div>hello world</div>, { bootstrapScriptContent: 'INIT();', bootstrapScripts: ['init.js'], bootstrapModules: ['init.mjs'], }, ); const prelude = await readContent(result.prelude); expect(prelude).toMatchInlineSnapshot( `"<link rel="preload" as="script" fetchPriority="low" href="init.js"/><link rel="modulepreload" fetchPriority="low" href="init.mjs"/><div>hello world</div><script>INIT();</script><script src="init.js" async=""></script><script type="module" src="init.mjs" async=""></script>"`, ); }); // @gate experimental it('emits all HTML as one unit', async () => { let hasLoaded = false; let resolve; const promise = new Promise(r => (resolve = r)); function Wait() { if (!hasLoaded) { throw promise; } return 'Done'; } const resultPromise = ReactDOMFizzStatic.prerenderToNodeStream( <div> <Suspense fallback="Loading"> <Wait /> </Suspense> </div>, ); await jest.runAllTimers(); // Resolve the loading. hasLoaded = true; await resolve(); const result = await resultPromise; const prelude = await readContent(result.prelude); expect(prelude).toMatchInlineSnapshot( `"<div><!--$-->Done<!-- --><!--/$--></div>"`, ); }); // @gate experimental it('should reject the promise when an error is thrown at the root', async () => { const reportedErrors = []; let caughtError = null; try { await ReactDOMFizzStatic.prerenderToNodeStream( <div> <Throw /> </div>, { onError(x) { reportedErrors.push(x); }, }, ); } catch (error) { caughtError = error; } expect(caughtError).toBe(theError); expect(reportedErrors).toEqual([theError]); }); // @gate experimental it('should reject the promise when an error is thrown inside a fallback', async () => { const reportedErrors = []; let caughtError = null; try { await ReactDOMFizzStatic.prerenderToNodeStream( <div> <Suspense fallback={<Throw />}> <InfiniteSuspend /> </Suspense> </div>, { onError(x) { reportedErrors.push(x); }, }, ); } catch (error) { caughtError = error; } expect(caughtError).toBe(theError); expect(reportedErrors).toEqual([theError]); }); // @gate experimental it('should not error the stream when an error is thrown inside suspense boundary', async () => { const reportedErrors = []; const result = await ReactDOMFizzStatic.prerenderToNodeStream( <div> <Suspense fallback={<div>Loading</div>}> <Throw /> </Suspense> </div>, { onError(x) { reportedErrors.push(x); }, }, ); const prelude = await readContent(result.prelude); expect(prelude).toContain('Loading'); expect(reportedErrors).toEqual([theError]); }); // @gate experimental it('should be able to complete by aborting even if the promise never resolves', async () => { const errors = []; const controller = new AbortController(); const resultPromise = ReactDOMFizzStatic.prerenderToNodeStream( <div> <Suspense fallback={<div>Loading</div>}> <InfiniteSuspend /> </Suspense> </div>, { signal: controller.signal, onError(x) { errors.push(x.message); }, }, ); await jest.runAllTimers(); controller.abort(); const result = await resultPromise; const prelude = await readContent(result.prelude); expect(prelude).toContain('Loading'); expect(errors).toEqual(['This operation was aborted']); }); // @gate experimental it('should reject if aborting before the shell is complete', async () => { const errors = []; const controller = new AbortController(); const promise = ReactDOMFizzStatic.prerenderToNodeStream( <div> <InfiniteSuspend /> </div>, { signal: controller.signal, onError(x) { errors.push(x.message); }, }, ); await jest.runAllTimers(); const theReason = new Error('aborted for reasons'); controller.abort(theReason); let caughtError = null; try { await promise; } catch (error) { caughtError = error; } expect(caughtError).toBe(theReason); expect(errors).toEqual(['aborted for reasons']); }); // @gate experimental it('should be able to abort before something suspends', async () => { const errors = []; const controller = new AbortController(); function App() { controller.abort(); return ( <Suspense fallback={<div>Loading</div>}> <InfiniteSuspend /> </Suspense> ); } const streamPromise = ReactDOMFizzStatic.prerenderToNodeStream( <div> <App /> </div>, { signal: controller.signal, onError(x) { errors.push(x.message); }, }, ); let caughtError = null; try { await streamPromise; } catch (error) { caughtError = error; } expect(caughtError.message).toBe('This operation was aborted'); expect(errors).toEqual(['This operation was aborted']); }); // @gate experimental it('should reject if passing an already aborted signal', async () => { const errors = []; const controller = new AbortController(); const theReason = new Error('aborted for reasons'); controller.abort(theReason); const promise = ReactDOMFizzStatic.prerenderToNodeStream( <div> <Suspense fallback={<div>Loading</div>}> <InfiniteSuspend /> </Suspense> </div>, { signal: controller.signal, onError(x) { errors.push(x.message); }, }, ); // Technically we could still continue rendering the shell but currently the // semantics mean that we also abort any pending CPU work. let caughtError = null; try { await promise; } catch (error) { caughtError = error; } expect(caughtError).toBe(theReason); expect(errors).toEqual(['aborted for reasons']); }); // @gate experimental it('supports custom abort reasons with a string', async () => { const promise = new Promise(r => {}); function Wait() { throw promise; } function App() { return ( <div> <p> <Suspense fallback={'p'}> <Wait /> </Suspense> </p> <span> <Suspense fallback={'span'}> <Wait /> </Suspense> </span> </div> ); } const errors = []; const controller = new AbortController(); const resultPromise = ReactDOMFizzStatic.prerenderToNodeStream(<App />, { signal: controller.signal, onError(x) { errors.push(x); return 'a digest'; }, }); await jest.runAllTimers(); controller.abort('foobar'); await resultPromise; expect(errors).toEqual(['foobar', 'foobar']); }); // @gate experimental it('supports custom abort reasons with an Error', async () => { const promise = new Promise(r => {}); function Wait() { throw promise; } function App() { return ( <div> <p> <Suspense fallback={'p'}> <Wait /> </Suspense> </p> <span> <Suspense fallback={'span'}> <Wait /> </Suspense> </span> </div> ); } const errors = []; const controller = new AbortController(); const resultPromise = ReactDOMFizzStatic.prerenderToNodeStream(<App />, { signal: controller.signal, onError(x) { errors.push(x.message); return 'a digest'; }, }); await jest.runAllTimers(); controller.abort(new Error('uh oh')); await resultPromise; expect(errors).toEqual(['uh oh', 'uh oh']); }); });
24.695545
283
0.573603
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; const fs = require('fs'); const path = require('path'); const existingErrorMap = JSON.parse( fs.readFileSync(path.resolve(__dirname, '../error-codes/codes.json')) ); const messages = new Set(); Object.keys(existingErrorMap).forEach(key => messages.add(existingErrorMap[key]) ); /** * The warning() function takes format strings as its second * argument. */ module.exports = { meta: { schema: [], }, create(context) { // we also allow literal strings and concatenated literal strings function getLiteralString(node) { if (node.type === 'Literal' && typeof node.value === 'string') { return node.value; } else if (node.type === 'BinaryExpression' && node.operator === '+') { const l = getLiteralString(node.left); const r = getLiteralString(node.right); if (l !== null && r !== null) { return l + r; } } return null; } return { CallExpression: function (node) { // This could be a little smarter by checking context.getScope() to see // how warning/invariant was defined. const isWarning = node.callee.type === 'MemberExpression' && node.callee.object.type === 'Identifier' && node.callee.object.name === 'console' && node.callee.property.type === 'Identifier' && (node.callee.property.name === 'error' || node.callee.property.name === 'warn'); if (!isWarning) { return; } const name = 'console.' + node.callee.property.name; if (node.arguments.length < 1) { context.report(node, '{{name}} takes at least one argument', { name, }); return; } const format = getLiteralString(node.arguments[0]); if (format === null) { context.report( node, 'The first argument to {{name}} must be a string literal', {name} ); return; } if (format.length < 10 || /^[s\W]*$/.test(format)) { context.report( node, 'The {{name}} format should be able to uniquely identify this ' + 'warning. Please, use a more descriptive format than: {{format}}', {name, format} ); return; } // count the number of formatting substitutions, plus the first two args const expectedNArgs = (format.match(/%s/g) || []).length + 1; if (node.arguments.length !== expectedNArgs) { context.report( node, 'Expected {{expectedNArgs}} arguments in call to {{name}} based on ' + 'the number of "%s" substitutions, but got {{length}}', { expectedNArgs: expectedNArgs, name, length: node.arguments.length, } ); } }, }; }, };
29.601942
82
0.545858
Mastering-Machine-Learning-for-Penetration-Testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ /** * Converts nested hooks paths to the format expected by the backend. * e.g. [''] => [''] * e.g. [1, 'value', ...] => [...] * e.g. [2, 'subhooks', 1, 'value', ...] => [...] * e.g. [1, 'subhooks', 3, 'subhooks', 2, 'value', ...] => [...] */ export function parseHookPathForEdit( path: Array<string | number>, ): Array<string | number> { let index = 0; for (let i = 0; i < path.length; i++) { if (path[i] === 'value') { index = i + 1; break; } } return path.slice(index); }
23.689655
69
0.54965
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {DOMEventName} from './DOMEventNames'; import type {EventSystemFlags} from './EventSystemFlags'; import type {AnyNativeEvent} from './PluginModuleType'; import type { KnownReactSyntheticEvent, ReactSyntheticEvent, } from './ReactSyntheticEventType'; import type {Fiber} from 'react-reconciler/src/ReactInternalTypes'; import {allNativeEvents} from './EventRegistry'; import { SHOULD_NOT_DEFER_CLICK_FOR_FB_SUPPORT_MODE, IS_LEGACY_FB_SUPPORT_MODE, SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS, IS_CAPTURE_PHASE, IS_EVENT_HANDLE_NON_MANAGED_NODE, IS_NON_DELEGATED, } from './EventSystemFlags'; import {isReplayingEvent} from './CurrentReplayingEvent'; import { HostRoot, HostPortal, HostComponent, HostHoistable, HostSingleton, HostText, ScopeComponent, } from 'react-reconciler/src/ReactWorkTags'; import getEventTarget from './getEventTarget'; import { getClosestInstanceFromNode, getEventListenerSet, getEventHandlerListeners, } from '../client/ReactDOMComponentTree'; import {COMMENT_NODE, DOCUMENT_NODE} from '../client/HTMLNodeType'; import {batchedUpdates} from './ReactDOMUpdateBatching'; import getListener from './getListener'; import {passiveBrowserEventsSupported} from './checkPassiveEvents'; import { enableLegacyFBSupport, enableCreateEventHandleAPI, enableScopeAPI, enableFloat, enableFormActions, } from 'shared/ReactFeatureFlags'; import { invokeGuardedCallbackAndCatchFirstError, rethrowCaughtError, } from 'shared/ReactErrorUtils'; import {createEventListenerWrapperWithPriority} from './ReactDOMEventListener'; import { removeEventListener, addEventCaptureListener, addEventBubbleListener, addEventBubbleListenerWithPassiveFlag, addEventCaptureListenerWithPassiveFlag, } from './EventListener'; import * as BeforeInputEventPlugin from './plugins/BeforeInputEventPlugin'; import * as ChangeEventPlugin from './plugins/ChangeEventPlugin'; import * as EnterLeaveEventPlugin from './plugins/EnterLeaveEventPlugin'; import * as SelectEventPlugin from './plugins/SelectEventPlugin'; import * as SimpleEventPlugin from './plugins/SimpleEventPlugin'; import * as FormActionEventPlugin from './plugins/FormActionEventPlugin'; type DispatchListener = { instance: null | Fiber, listener: Function, currentTarget: EventTarget, }; type DispatchEntry = { event: ReactSyntheticEvent, listeners: Array<DispatchListener>, }; export type DispatchQueue = Array<DispatchEntry>; // TODO: remove top-level side effect. SimpleEventPlugin.registerEvents(); EnterLeaveEventPlugin.registerEvents(); ChangeEventPlugin.registerEvents(); SelectEventPlugin.registerEvents(); BeforeInputEventPlugin.registerEvents(); function extractEvents( dispatchQueue: DispatchQueue, domEventName: DOMEventName, targetInst: null | Fiber, nativeEvent: AnyNativeEvent, nativeEventTarget: null | EventTarget, eventSystemFlags: EventSystemFlags, targetContainer: EventTarget, ) { // TODO: we should remove the concept of a "SimpleEventPlugin". // This is the basic functionality of the event system. All // the other plugins are essentially polyfills. So the plugin // should probably be inlined somewhere and have its logic // be core the to event system. This would potentially allow // us to ship builds of React without the polyfilled plugins below. SimpleEventPlugin.extractEvents( dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer, ); const shouldProcessPolyfillPlugins = (eventSystemFlags & SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS) === 0; // We don't process these events unless we are in the // event's native "bubble" phase, which means that we're // not in the capture phase. That's because we emulate // the capture phase here still. This is a trade-off, // because in an ideal world we would not emulate and use // the phases properly, like we do with the SimpleEvent // plugin. However, the plugins below either expect // emulation (EnterLeave) or use state localized to that // plugin (BeforeInput, Change, Select). The state in // these modules complicates things, as you'll essentially // get the case where the capture phase event might change // state, only for the following bubble event to come in // later and not trigger anything as the state now // invalidates the heuristics of the event plugin. We // could alter all these plugins to work in such ways, but // that might cause other unknown side-effects that we // can't foresee right now. if (shouldProcessPolyfillPlugins) { EnterLeaveEventPlugin.extractEvents( dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer, ); ChangeEventPlugin.extractEvents( dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer, ); SelectEventPlugin.extractEvents( dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer, ); BeforeInputEventPlugin.extractEvents( dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer, ); if (enableFormActions) { FormActionEventPlugin.extractEvents( dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer, ); } } } // List of events that need to be individually attached to media elements. export const mediaEventTypes: Array<DOMEventName> = [ 'abort', 'canplay', 'canplaythrough', 'durationchange', 'emptied', 'encrypted', 'ended', 'error', 'loadeddata', 'loadedmetadata', 'loadstart', 'pause', 'play', 'playing', 'progress', 'ratechange', 'resize', 'seeked', 'seeking', 'stalled', 'suspend', 'timeupdate', 'volumechange', 'waiting', ]; // We should not delegate these events to the container, but rather // set them on the actual target element itself. This is primarily // because these events do not consistently bubble in the DOM. export const nonDelegatedEvents: Set<DOMEventName> = new Set([ 'cancel', 'close', 'invalid', 'load', 'scroll', 'scrollend', 'toggle', // In order to reduce bytes, we insert the above array of media events // into this Set. Note: the "error" event isn't an exclusive media event, // and can occur on other elements too. Rather than duplicate that event, // we just take it from the media events array. ...mediaEventTypes, ]); function executeDispatch( event: ReactSyntheticEvent, listener: Function, currentTarget: EventTarget, ): void { const type = event.type || 'unknown-event'; event.currentTarget = currentTarget; invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event); event.currentTarget = null; } function processDispatchQueueItemsInOrder( event: ReactSyntheticEvent, dispatchListeners: Array<DispatchListener>, inCapturePhase: boolean, ): void { let previousInstance; if (inCapturePhase) { for (let i = dispatchListeners.length - 1; i >= 0; i--) { const {instance, currentTarget, listener} = dispatchListeners[i]; if (instance !== previousInstance && event.isPropagationStopped()) { return; } executeDispatch(event, listener, currentTarget); previousInstance = instance; } } else { for (let i = 0; i < dispatchListeners.length; i++) { const {instance, currentTarget, listener} = dispatchListeners[i]; if (instance !== previousInstance && event.isPropagationStopped()) { return; } executeDispatch(event, listener, currentTarget); previousInstance = instance; } } } export function processDispatchQueue( dispatchQueue: DispatchQueue, eventSystemFlags: EventSystemFlags, ): void { const inCapturePhase = (eventSystemFlags & IS_CAPTURE_PHASE) !== 0; for (let i = 0; i < dispatchQueue.length; i++) { const {event, listeners} = dispatchQueue[i]; processDispatchQueueItemsInOrder(event, listeners, inCapturePhase); // event system doesn't use pooling. } // This would be a good time to rethrow if any of the event handlers threw. rethrowCaughtError(); } function dispatchEventsForPlugins( domEventName: DOMEventName, eventSystemFlags: EventSystemFlags, nativeEvent: AnyNativeEvent, targetInst: null | Fiber, targetContainer: EventTarget, ): void { const nativeEventTarget = getEventTarget(nativeEvent); const dispatchQueue: DispatchQueue = []; extractEvents( dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer, ); processDispatchQueue(dispatchQueue, eventSystemFlags); } export function listenToNonDelegatedEvent( domEventName: DOMEventName, targetElement: Element, ): void { if (__DEV__) { if (!nonDelegatedEvents.has(domEventName)) { console.error( 'Did not expect a listenToNonDelegatedEvent() call for "%s". ' + 'This is a bug in React. Please file an issue.', domEventName, ); } } const isCapturePhaseListener = false; const listenerSet = getEventListenerSet(targetElement); const listenerSetKey = getListenerSetKey( domEventName, isCapturePhaseListener, ); if (!listenerSet.has(listenerSetKey)) { addTrappedEventListener( targetElement, domEventName, IS_NON_DELEGATED, isCapturePhaseListener, ); listenerSet.add(listenerSetKey); } } export function listenToNativeEvent( domEventName: DOMEventName, isCapturePhaseListener: boolean, target: EventTarget, ): void { if (__DEV__) { if (nonDelegatedEvents.has(domEventName) && !isCapturePhaseListener) { console.error( 'Did not expect a listenToNativeEvent() call for "%s" in the bubble phase. ' + 'This is a bug in React. Please file an issue.', domEventName, ); } } let eventSystemFlags = 0; if (isCapturePhaseListener) { eventSystemFlags |= IS_CAPTURE_PHASE; } addTrappedEventListener( target, domEventName, eventSystemFlags, isCapturePhaseListener, ); } // This is only used by createEventHandle when the // target is not a DOM element. E.g. window. export function listenToNativeEventForNonManagedEventTarget( domEventName: DOMEventName, isCapturePhaseListener: boolean, target: EventTarget, ): void { let eventSystemFlags = IS_EVENT_HANDLE_NON_MANAGED_NODE; const listenerSet = getEventListenerSet(target); const listenerSetKey = getListenerSetKey( domEventName, isCapturePhaseListener, ); if (!listenerSet.has(listenerSetKey)) { if (isCapturePhaseListener) { eventSystemFlags |= IS_CAPTURE_PHASE; } addTrappedEventListener( target, domEventName, eventSystemFlags, isCapturePhaseListener, ); listenerSet.add(listenerSetKey); } } const listeningMarker = '_reactListening' + Math.random().toString(36).slice(2); export function listenToAllSupportedEvents(rootContainerElement: EventTarget) { if (!(rootContainerElement: any)[listeningMarker]) { (rootContainerElement: any)[listeningMarker] = true; allNativeEvents.forEach(domEventName => { // We handle selectionchange separately because it // doesn't bubble and needs to be on the document. if (domEventName !== 'selectionchange') { if (!nonDelegatedEvents.has(domEventName)) { listenToNativeEvent(domEventName, false, rootContainerElement); } listenToNativeEvent(domEventName, true, rootContainerElement); } }); const ownerDocument = (rootContainerElement: any).nodeType === DOCUMENT_NODE ? rootContainerElement : (rootContainerElement: any).ownerDocument; if (ownerDocument !== null) { // The selectionchange event also needs deduplication // but it is attached to the document. if (!(ownerDocument: any)[listeningMarker]) { (ownerDocument: any)[listeningMarker] = true; listenToNativeEvent('selectionchange', false, ownerDocument); } } } } function addTrappedEventListener( targetContainer: EventTarget, domEventName: DOMEventName, eventSystemFlags: EventSystemFlags, isCapturePhaseListener: boolean, isDeferredListenerForLegacyFBSupport?: boolean, ) { let listener = createEventListenerWrapperWithPriority( targetContainer, domEventName, eventSystemFlags, ); // If passive option is not supported, then the event will be // active and not passive. let isPassiveListener: void | boolean = undefined; if (passiveBrowserEventsSupported) { // Browsers introduced an intervention, making these events // passive by default on document. React doesn't bind them // to document anymore, but changing this now would undo // the performance wins from the change. So we emulate // the existing behavior manually on the roots now. // https://github.com/facebook/react/issues/19651 if ( domEventName === 'touchstart' || domEventName === 'touchmove' || domEventName === 'wheel' ) { isPassiveListener = true; } } targetContainer = enableLegacyFBSupport && isDeferredListenerForLegacyFBSupport ? (targetContainer: any).ownerDocument : targetContainer; let unsubscribeListener; // When legacyFBSupport is enabled, it's for when we // want to add a one time event listener to a container. // This should only be used with enableLegacyFBSupport // due to requirement to provide compatibility with // internal FB www event tooling. This works by removing // the event listener as soon as it is invoked. We could // also attempt to use the {once: true} param on // addEventListener, but that requires support and some // browsers do not support this today, and given this is // to support legacy code patterns, it's likely they'll // need support for such browsers. if (enableLegacyFBSupport && isDeferredListenerForLegacyFBSupport) { const originalListener = listener; // $FlowFixMe[missing-this-annot] listener = function (...p) { removeEventListener( targetContainer, domEventName, unsubscribeListener, isCapturePhaseListener, ); return originalListener.apply(this, p); }; } // TODO: There are too many combinations here. Consolidate them. if (isCapturePhaseListener) { if (isPassiveListener !== undefined) { unsubscribeListener = addEventCaptureListenerWithPassiveFlag( targetContainer, domEventName, listener, isPassiveListener, ); } else { unsubscribeListener = addEventCaptureListener( targetContainer, domEventName, listener, ); } } else { if (isPassiveListener !== undefined) { unsubscribeListener = addEventBubbleListenerWithPassiveFlag( targetContainer, domEventName, listener, isPassiveListener, ); } else { unsubscribeListener = addEventBubbleListener( targetContainer, domEventName, listener, ); } } } function deferClickToDocumentForLegacyFBSupport( domEventName: DOMEventName, targetContainer: EventTarget, ): void { // We defer all click events with legacy FB support mode on. // This means we add a one time event listener to trigger // after the FB delegated listeners fire. const isDeferredListenerForLegacyFBSupport = true; addTrappedEventListener( targetContainer, domEventName, IS_LEGACY_FB_SUPPORT_MODE, false, isDeferredListenerForLegacyFBSupport, ); } function isMatchingRootContainer( grandContainer: Element, targetContainer: EventTarget, ): boolean { return ( grandContainer === targetContainer || (grandContainer.nodeType === COMMENT_NODE && grandContainer.parentNode === targetContainer) ); } export function dispatchEventForPluginEventSystem( domEventName: DOMEventName, eventSystemFlags: EventSystemFlags, nativeEvent: AnyNativeEvent, targetInst: null | Fiber, targetContainer: EventTarget, ): void { let ancestorInst = targetInst; if ( (eventSystemFlags & IS_EVENT_HANDLE_NON_MANAGED_NODE) === 0 && (eventSystemFlags & IS_NON_DELEGATED) === 0 ) { const targetContainerNode = ((targetContainer: any): Node); // If we are using the legacy FB support flag, we // defer the event to the null with a one // time event listener so we can defer the event. if ( enableLegacyFBSupport && // If our event flags match the required flags for entering // FB legacy mode and we are processing the "click" event, // then we can defer the event to the "document", to allow // for legacy FB support, where the expected behavior was to // match React < 16 behavior of delegated clicks to the doc. domEventName === 'click' && (eventSystemFlags & SHOULD_NOT_DEFER_CLICK_FOR_FB_SUPPORT_MODE) === 0 && !isReplayingEvent(nativeEvent) ) { deferClickToDocumentForLegacyFBSupport(domEventName, targetContainer); return; } if (targetInst !== null) { // The below logic attempts to work out if we need to change // the target fiber to a different ancestor. We had similar logic // in the legacy event system, except the big difference between // systems is that the modern event system now has an event listener // attached to each React Root and React Portal Root. Together, // the DOM nodes representing these roots are the "rootContainer". // To figure out which ancestor instance we should use, we traverse // up the fiber tree from the target instance and attempt to find // root boundaries that match that of our current "rootContainer". // If we find that "rootContainer", we find the parent fiber // sub-tree for that root and make that our ancestor instance. let node: null | Fiber = targetInst; mainLoop: while (true) { if (node === null) { return; } const nodeTag = node.tag; if (nodeTag === HostRoot || nodeTag === HostPortal) { let container = node.stateNode.containerInfo; if (isMatchingRootContainer(container, targetContainerNode)) { break; } if (nodeTag === HostPortal) { // The target is a portal, but it's not the rootContainer we're looking for. // Normally portals handle their own events all the way down to the root. // So we should be able to stop now. However, we don't know if this portal // was part of *our* root. let grandNode = node.return; while (grandNode !== null) { const grandTag = grandNode.tag; if (grandTag === HostRoot || grandTag === HostPortal) { const grandContainer = grandNode.stateNode.containerInfo; if ( isMatchingRootContainer(grandContainer, targetContainerNode) ) { // This is the rootContainer we're looking for and we found it as // a parent of the Portal. That means we can ignore it because the // Portal will bubble through to us. return; } } grandNode = grandNode.return; } } // Now we need to find it's corresponding host fiber in the other // tree. To do this we can use getClosestInstanceFromNode, but we // need to validate that the fiber is a host instance, otherwise // we need to traverse up through the DOM till we find the correct // node that is from the other tree. while (container !== null) { const parentNode = getClosestInstanceFromNode(container); if (parentNode === null) { return; } const parentTag = parentNode.tag; if ( parentTag === HostComponent || parentTag === HostText || (enableFloat ? parentTag === HostHoistable : false) || parentTag === HostSingleton ) { node = ancestorInst = parentNode; continue mainLoop; } container = container.parentNode; } } node = node.return; } } } batchedUpdates(() => dispatchEventsForPlugins( domEventName, eventSystemFlags, nativeEvent, ancestorInst, targetContainer, ), ); } function createDispatchListener( instance: null | Fiber, listener: Function, currentTarget: EventTarget, ): DispatchListener { return { instance, listener, currentTarget, }; } export function accumulateSinglePhaseListeners( targetFiber: Fiber | null, reactName: string | null, nativeEventType: string, inCapturePhase: boolean, accumulateTargetOnly: boolean, nativeEvent: AnyNativeEvent, ): Array<DispatchListener> { const captureName = reactName !== null ? reactName + 'Capture' : null; const reactEventName = inCapturePhase ? captureName : reactName; let listeners: Array<DispatchListener> = []; let instance = targetFiber; let lastHostComponent = null; // Accumulate all instances and listeners via the target -> root path. while (instance !== null) { const {stateNode, tag} = instance; // Handle listeners that are on HostComponents (i.e. <div>) if ( (tag === HostComponent || (enableFloat ? tag === HostHoistable : false) || tag === HostSingleton) && stateNode !== null ) { lastHostComponent = stateNode; // createEventHandle listeners if (enableCreateEventHandleAPI) { const eventHandlerListeners = getEventHandlerListeners(lastHostComponent); if (eventHandlerListeners !== null) { eventHandlerListeners.forEach(entry => { if ( entry.type === nativeEventType && entry.capture === inCapturePhase ) { listeners.push( createDispatchListener( instance, entry.callback, (lastHostComponent: any), ), ); } }); } } // Standard React on* listeners, i.e. onClick or onClickCapture if (reactEventName !== null) { const listener = getListener(instance, reactEventName); if (listener != null) { listeners.push( createDispatchListener(instance, listener, lastHostComponent), ); } } } else if ( enableCreateEventHandleAPI && enableScopeAPI && tag === ScopeComponent && lastHostComponent !== null && stateNode !== null ) { // Scopes const reactScopeInstance = stateNode; const eventHandlerListeners = getEventHandlerListeners(reactScopeInstance); if (eventHandlerListeners !== null) { eventHandlerListeners.forEach(entry => { if ( entry.type === nativeEventType && entry.capture === inCapturePhase ) { listeners.push( createDispatchListener( instance, entry.callback, (lastHostComponent: any), ), ); } }); } } // If we are only accumulating events for the target, then we don't // continue to propagate through the React fiber tree to find other // listeners. if (accumulateTargetOnly) { break; } // If we are processing the onBeforeBlur event, then we need to take // into consideration that part of the React tree might have been hidden // or deleted (as we're invoking this event during commit). We can find // this out by checking if intercept fiber set on the event matches the // current instance fiber. In which case, we should clear all existing // listeners. if (enableCreateEventHandleAPI && nativeEvent.type === 'beforeblur') { // $FlowFixMe[prop-missing] internal field const detachedInterceptFiber = nativeEvent._detachedInterceptFiber; if ( detachedInterceptFiber !== null && (detachedInterceptFiber === instance || detachedInterceptFiber === instance.alternate) ) { listeners = []; } } instance = instance.return; } return listeners; } // We should only use this function for: // - BeforeInputEventPlugin // - ChangeEventPlugin // - SelectEventPlugin // This is because we only process these plugins // in the bubble phase, so we need to accumulate two // phase event listeners (via emulation). export function accumulateTwoPhaseListeners( targetFiber: Fiber | null, reactName: string, ): Array<DispatchListener> { const captureName = reactName + 'Capture'; const listeners: Array<DispatchListener> = []; let instance = targetFiber; // Accumulate all instances and listeners via the target -> root path. while (instance !== null) { const {stateNode, tag} = instance; // Handle listeners that are on HostComponents (i.e. <div>) if ( (tag === HostComponent || (enableFloat ? tag === HostHoistable : false) || tag === HostSingleton) && stateNode !== null ) { const currentTarget = stateNode; const captureListener = getListener(instance, captureName); if (captureListener != null) { listeners.unshift( createDispatchListener(instance, captureListener, currentTarget), ); } const bubbleListener = getListener(instance, reactName); if (bubbleListener != null) { listeners.push( createDispatchListener(instance, bubbleListener, currentTarget), ); } } instance = instance.return; } return listeners; } function getParent(inst: Fiber | null): Fiber | null { if (inst === null) { return null; } do { // $FlowFixMe[incompatible-use] found when upgrading Flow inst = inst.return; // TODO: If this is a HostRoot we might want to bail out. // That is depending on if we want nested subtrees (layers) to bubble // events to their parent. We could also go through parentNode on the // host node but that wouldn't work for React Native and doesn't let us // do the portal feature. } while (inst && inst.tag !== HostComponent && inst.tag !== HostSingleton); if (inst) { return inst; } return null; } /** * Return the lowest common ancestor of A and B, or null if they are in * different trees. */ function getLowestCommonAncestor(instA: Fiber, instB: Fiber): Fiber | null { let nodeA: null | Fiber = instA; let nodeB: null | Fiber = instB; let depthA = 0; for (let tempA: null | Fiber = nodeA; tempA; tempA = getParent(tempA)) { depthA++; } let depthB = 0; for (let tempB: null | Fiber = nodeB; tempB; tempB = getParent(tempB)) { depthB++; } // If A is deeper, crawl up. while (depthA - depthB > 0) { nodeA = getParent(nodeA); depthA--; } // If B is deeper, crawl up. while (depthB - depthA > 0) { nodeB = getParent(nodeB); depthB--; } // Walk in lockstep until we find a match. let depth = depthA; while (depth--) { if (nodeA === nodeB || (nodeB !== null && nodeA === nodeB.alternate)) { return nodeA; } nodeA = getParent(nodeA); nodeB = getParent(nodeB); } return null; } function accumulateEnterLeaveListenersForEvent( dispatchQueue: DispatchQueue, event: KnownReactSyntheticEvent, target: Fiber, common: Fiber | null, inCapturePhase: boolean, ): void { const registrationName = event._reactName; const listeners: Array<DispatchListener> = []; let instance: null | Fiber = target; while (instance !== null) { if (instance === common) { break; } const {alternate, stateNode, tag} = instance; if (alternate !== null && alternate === common) { break; } if ( (tag === HostComponent || (enableFloat ? tag === HostHoistable : false) || tag === HostSingleton) && stateNode !== null ) { const currentTarget = stateNode; if (inCapturePhase) { const captureListener = getListener(instance, registrationName); if (captureListener != null) { listeners.unshift( createDispatchListener(instance, captureListener, currentTarget), ); } } else if (!inCapturePhase) { const bubbleListener = getListener(instance, registrationName); if (bubbleListener != null) { listeners.push( createDispatchListener(instance, bubbleListener, currentTarget), ); } } } instance = instance.return; } if (listeners.length !== 0) { dispatchQueue.push({event, listeners}); } } // We should only use this function for: // - EnterLeaveEventPlugin // This is because we only process this plugin // in the bubble phase, so we need to accumulate two // phase event listeners. export function accumulateEnterLeaveTwoPhaseListeners( dispatchQueue: DispatchQueue, leaveEvent: KnownReactSyntheticEvent, enterEvent: null | KnownReactSyntheticEvent, from: Fiber | null, to: Fiber | null, ): void { const common = from && to ? getLowestCommonAncestor(from, to) : null; if (from !== null) { accumulateEnterLeaveListenersForEvent( dispatchQueue, leaveEvent, from, common, false, ); } if (to !== null && enterEvent !== null) { accumulateEnterLeaveListenersForEvent( dispatchQueue, enterEvent, to, common, true, ); } } export function accumulateEventHandleNonManagedNodeListeners( reactEventType: DOMEventName, currentTarget: EventTarget, inCapturePhase: boolean, ): Array<DispatchListener> { const listeners: Array<DispatchListener> = []; const eventListeners = getEventHandlerListeners(currentTarget); if (eventListeners !== null) { eventListeners.forEach(entry => { if (entry.type === reactEventType && entry.capture === inCapturePhase) { listeners.push( createDispatchListener(null, entry.callback, currentTarget), ); } }); } return listeners; } export function getListenerSetKey( domEventName: DOMEventName, capture: boolean, ): string { return `${domEventName}__${capture ? 'capture' : 'bubble'}`; }
30.081918
88
0.668102
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import getComponentNameFromType from 'shared/getComponentNameFromType'; import ReactSharedInternals from 'shared/ReactSharedInternals'; import hasOwnProperty from 'shared/hasOwnProperty'; import {REACT_ELEMENT_TYPE} from 'shared/ReactSymbols'; import {checkKeyStringCoercion} from 'shared/CheckStringCoercion'; const ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; const RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true, }; let specialPropKeyWarningShown; let specialPropRefWarningShown; let didWarnAboutStringRefs; if (__DEV__) { didWarnAboutStringRefs = {}; } function hasValidRef(config) { if (__DEV__) { if (hasOwnProperty.call(config, 'ref')) { const getter = Object.getOwnPropertyDescriptor(config, 'ref').get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== undefined; } function hasValidKey(config) { if (__DEV__) { if (hasOwnProperty.call(config, 'key')) { const getter = Object.getOwnPropertyDescriptor(config, 'key').get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== undefined; } function warnIfStringRefCannotBeAutoConverted(config, self) { if (__DEV__) { if ( typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self ) { const componentName = getComponentNameFromType( ReactCurrentOwner.current.type, ); if (!didWarnAboutStringRefs[componentName]) { console.error( 'Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref, ); didWarnAboutStringRefs[componentName] = true; } } } } function defineKeyPropWarningGetter(props, displayName) { if (__DEV__) { const warnAboutAccessingKey = function () { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; console.error( '%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName, ); } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, 'key', { get: warnAboutAccessingKey, configurable: true, }); } } function defineRefPropWarningGetter(props, displayName) { if (__DEV__) { const warnAboutAccessingRef = function () { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; console.error( '%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName, ); } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, 'ref', { get: warnAboutAccessingRef, configurable: true, }); } } /** * Factory method to create a new React element. This no longer adheres to * the class pattern, so do not use new to call it. Also, instanceof check * will not work. Instead test $$typeof field against Symbol.for('react.element') to check * if something is a React Element. * * @param {*} type * @param {*} props * @param {*} key * @param {string|object} ref * @param {*} owner * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @internal */ function ReactElement(type, key, ref, self, source, owner, props) { const element = { // This tag allows us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type, key, ref, props, // Record the component responsible for creating this element. _owner: owner, }; if (__DEV__) { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false, }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self, }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source, }); if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; } /** * https://github.com/reactjs/rfcs/pull/107 * @param {*} type * @param {object} props * @param {string} key */ export function jsx(type, config, maybeKey) { let propName; // Reserved names are extracted const props = {}; let key = null; let ref = null; // Currently, key can be spread in as a prop. This causes a potential // issue if key is also explicitly declared (ie. <div {...props} key="Hi" /> // or <div key="Hi" {...props} /> ). We want to deprecate key spread, // but as an intermediary step, we will use jsxDEV for everything except // <div {...props} key="Hi" />, because we aren't currently able to tell if // key is explicitly declared to be undefined or not. if (maybeKey !== undefined) { if (__DEV__) { checkKeyStringCoercion(maybeKey); } key = '' + maybeKey; } if (hasValidKey(config)) { if (__DEV__) { checkKeyStringCoercion(config.key); } key = '' + config.key; } if (hasValidRef(config)) { ref = config.ref; } // Remaining properties are added to a new props object for (propName in config) { if ( hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName) ) { props[propName] = config[propName]; } } // Resolve default props if (type && type.defaultProps) { const defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } return ReactElement( type, key, ref, undefined, undefined, ReactCurrentOwner.current, props, ); } /** * https://github.com/reactjs/rfcs/pull/107 * @param {*} type * @param {object} props * @param {string} key */ export function jsxDEV(type, config, maybeKey, source, self) { if (__DEV__) { let propName; // Reserved names are extracted const props = {}; let key = null; let ref = null; // Currently, key can be spread in as a prop. This causes a potential // issue if key is also explicitly declared (ie. <div {...props} key="Hi" /> // or <div key="Hi" {...props} /> ). We want to deprecate key spread, // but as an intermediary step, we will use jsxDEV for everything except // <div {...props} key="Hi" />, because we aren't currently able to tell if // key is explicitly declared to be undefined or not. if (maybeKey !== undefined) { if (__DEV__) { checkKeyStringCoercion(maybeKey); } key = '' + maybeKey; } if (hasValidKey(config)) { if (__DEV__) { checkKeyStringCoercion(config.key); } key = '' + config.key; } if (hasValidRef(config)) { ref = config.ref; warnIfStringRefCannotBeAutoConverted(config, self); } // Remaining properties are added to a new props object for (propName in config) { if ( hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName) ) { props[propName] = config[propName]; } } // Resolve default props if (type && type.defaultProps) { const defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } if (key || ref) { const displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } return ReactElement( type, key, ref, self, source, ReactCurrentOwner.current, props, ); } }
27.707521
95
0.630665
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ 'use strict'; export {useSyncExternalStore} from 'use-sync-external-store/src/useSyncExternalStoreShim';
22.923077
90
0.729032
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; const rule = require('../prod-error-codes'); const {RuleTester} = require('eslint'); const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 2017, }, }); ruleTester.run('eslint-rules/prod-error-codes', rule, { valid: [ 'arbitraryFunction(a, b)', 'Error(`Expected ${foo} target to be an array; got ${bar}`)', "Error('Expected ' + foo + ' target to be an array; got ' + bar)", 'Error(`Expected ${foo} target to ` + `be an array; got ${bar}`)', ], invalid: [ { code: "Error('Not in error map')", errors: [ { message: 'Error message does not have a corresponding production error ' + 'code. Add the following message to codes.json so it can be stripped from ' + 'the production builds:\n\n' + 'Not in error map', }, ], }, { code: "Error('Not in ' + 'error map')", errors: [ { message: 'Error message does not have a corresponding production error ' + 'code. Add the following message to codes.json so it can be stripped from ' + 'the production builds:\n\n' + 'Not in error map', }, ], }, { code: 'Error(`Not in ` + `error map`)', errors: [ { message: 'Error message does not have a corresponding production error ' + 'code. Add the following message to codes.json so it can be stripped from ' + 'the production builds:\n\n' + 'Not in error map', }, ], }, { code: "Error(`Not in ${'error'} map`)", errors: [ { message: 'Error message does not have a corresponding production error ' + 'code. Add the following message to codes.json so it can be stripped from ' + 'the production builds:\n\n' + 'Not in %s map', }, ], }, ], });
27.192308
89
0.535032
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; let React; let ReactDOM; let ReactDOMClient; let Scheduler; let act; let waitForAll; let waitFor; let waitForMicrotasks; let assertLog; const setUntrackedInputValue = Object.getOwnPropertyDescriptor( HTMLInputElement.prototype, 'value', ).set; describe('ReactDOMFiberAsync', () => { let container; beforeEach(() => { container = document.createElement('div'); React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); act = require('internal-test-utils').act; Scheduler = require('scheduler'); const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; waitFor = InternalTestUtils.waitFor; waitForMicrotasks = InternalTestUtils.waitForMicrotasks; assertLog = InternalTestUtils.assertLog; document.body.appendChild(container); window.event = undefined; }); afterEach(() => { document.body.removeChild(container); }); it('renders synchronously by default', () => { const ops = []; ReactDOM.render(<div>Hi</div>, container, () => { ops.push(container.textContent); }); ReactDOM.render(<div>Bye</div>, container, () => { ops.push(container.textContent); }); expect(ops).toEqual(['Hi', 'Bye']); }); it('flushSync batches sync updates and flushes them at the end of the batch', () => { const ops = []; let instance; class Component extends React.Component { state = {text: ''}; push(val) { this.setState(state => ({text: state.text + val})); } componentDidUpdate() { ops.push(this.state.text); } render() { instance = this; return <span>{this.state.text}</span>; } } ReactDOM.render(<Component />, container); instance.push('A'); expect(ops).toEqual(['A']); expect(container.textContent).toEqual('A'); ReactDOM.flushSync(() => { instance.push('B'); instance.push('C'); // Not flushed yet expect(container.textContent).toEqual('A'); expect(ops).toEqual(['A']); }); expect(container.textContent).toEqual('ABC'); expect(ops).toEqual(['A', 'ABC']); instance.push('D'); expect(container.textContent).toEqual('ABCD'); expect(ops).toEqual(['A', 'ABC', 'ABCD']); }); it('flushSync flushes updates even if nested inside another flushSync', () => { const ops = []; let instance; class Component extends React.Component { state = {text: ''}; push(val) { this.setState(state => ({text: state.text + val})); } componentDidUpdate() { ops.push(this.state.text); } render() { instance = this; return <span>{this.state.text}</span>; } } ReactDOM.render(<Component />, container); instance.push('A'); expect(ops).toEqual(['A']); expect(container.textContent).toEqual('A'); ReactDOM.flushSync(() => { instance.push('B'); instance.push('C'); // Not flushed yet expect(container.textContent).toEqual('A'); expect(ops).toEqual(['A']); ReactDOM.flushSync(() => { instance.push('D'); }); // The nested flushSync caused everything to flush. expect(container.textContent).toEqual('ABCD'); expect(ops).toEqual(['A', 'ABCD']); }); expect(container.textContent).toEqual('ABCD'); expect(ops).toEqual(['A', 'ABCD']); }); it('flushSync logs an error if already performing work', () => { class Component extends React.Component { componentDidUpdate() { ReactDOM.flushSync(); } render() { return null; } } // Initial mount ReactDOM.render(<Component />, container); // Update expect(() => ReactDOM.render(<Component />, container)).toErrorDev( 'flushSync was called from inside a lifecycle method', ); }); describe('concurrent mode', () => { it('does not perform deferred updates synchronously', async () => { const inputRef = React.createRef(); const asyncValueRef = React.createRef(); const syncValueRef = React.createRef(); class Counter extends React.Component { state = {asyncValue: '', syncValue: ''}; handleChange = e => { const nextValue = e.target.value; React.startTransition(() => { this.setState({ asyncValue: nextValue, }); // It should not be flushed yet. expect(asyncValueRef.current.textContent).toBe(''); }); this.setState({ syncValue: nextValue, }); }; render() { return ( <div> <input ref={inputRef} onChange={this.handleChange} defaultValue="" /> <p ref={asyncValueRef}>{this.state.asyncValue}</p> <p ref={syncValueRef}>{this.state.syncValue}</p> </div> ); } } const root = ReactDOMClient.createRoot(container); await act(() => root.render(<Counter />)); expect(asyncValueRef.current.textContent).toBe(''); expect(syncValueRef.current.textContent).toBe(''); await act(() => { setUntrackedInputValue.call(inputRef.current, 'hello'); inputRef.current.dispatchEvent( new MouseEvent('input', {bubbles: true}), ); // Should only flush non-deferred update. expect(asyncValueRef.current.textContent).toBe(''); expect(syncValueRef.current.textContent).toBe('hello'); }); // Should flush both updates now. expect(asyncValueRef.current.textContent).toBe('hello'); expect(syncValueRef.current.textContent).toBe('hello'); }); it('top-level updates are concurrent', async () => { const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<div>Hi</div>); expect(container.textContent).toEqual(''); }); expect(container.textContent).toEqual('Hi'); await act(() => { root.render(<div>Bye</div>); expect(container.textContent).toEqual('Hi'); }); expect(container.textContent).toEqual('Bye'); }); it('deep updates (setState) are concurrent', async () => { let instance; class Component extends React.Component { state = {step: 0}; render() { instance = this; return <div>{this.state.step}</div>; } } const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<Component />); expect(container.textContent).toEqual(''); }); expect(container.textContent).toEqual('0'); await act(() => { instance.setState({step: 1}); expect(container.textContent).toEqual('0'); }); expect(container.textContent).toEqual('1'); }); it('flushSync flushes updates before end of the tick', async () => { let instance; class Component extends React.Component { state = {text: ''}; push(val) { this.setState(state => ({text: state.text + val})); } componentDidUpdate() { Scheduler.log(this.state.text); } render() { instance = this; return <span>{this.state.text}</span>; } } const root = ReactDOMClient.createRoot(container); await act(() => root.render(<Component />)); // Updates are async by default instance.push('A'); assertLog([]); expect(container.textContent).toEqual(''); ReactDOM.flushSync(() => { instance.push('B'); instance.push('C'); // Not flushed yet expect(container.textContent).toEqual(''); assertLog([]); }); // Only the active updates have flushed if (gate(flags => flags.enableUnifiedSyncLane)) { expect(container.textContent).toEqual('ABC'); assertLog(['ABC']); } else { expect(container.textContent).toEqual('BC'); assertLog(['BC']); } await act(() => { instance.push('D'); if (gate(flags => flags.enableUnifiedSyncLane)) { expect(container.textContent).toEqual('ABC'); } else { expect(container.textContent).toEqual('BC'); } assertLog([]); }); assertLog(['ABCD']); expect(container.textContent).toEqual('ABCD'); }); it('ignores discrete events on a pending removed element', async () => { const disableButtonRef = React.createRef(); const submitButtonRef = React.createRef(); function Form() { const [active, setActive] = React.useState(true); function disableForm() { setActive(false); } return ( <div> <button onClick={disableForm} ref={disableButtonRef}> Disable </button> {active ? <button ref={submitButtonRef}>Submit</button> : null} </div> ); } const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<Form />); }); const disableButton = disableButtonRef.current; expect(disableButton.tagName).toBe('BUTTON'); const submitButton = submitButtonRef.current; expect(submitButton.tagName).toBe('BUTTON'); // Dispatch a click event on the Disable-button. const firstEvent = document.createEvent('Event'); firstEvent.initEvent('click', true, true); disableButton.dispatchEvent(firstEvent); // The click event is flushed synchronously, even in concurrent mode. expect(submitButton.current).toBe(undefined); }); it('ignores discrete events on a pending removed event listener', async () => { const disableButtonRef = React.createRef(); const submitButtonRef = React.createRef(); let formSubmitted = false; function Form() { const [active, setActive] = React.useState(true); function disableForm() { setActive(false); } function submitForm() { formSubmitted = true; // This should not get invoked } function disabledSubmitForm() { // The form is disabled. } return ( <div> <button onClick={disableForm} ref={disableButtonRef}> Disable </button> <button onClick={active ? submitForm : disabledSubmitForm} ref={submitButtonRef}> Submit </button> </div> ); } const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<Form />); }); const disableButton = disableButtonRef.current; expect(disableButton.tagName).toBe('BUTTON'); // Dispatch a click event on the Disable-button. const firstEvent = document.createEvent('Event'); firstEvent.initEvent('click', true, true); await act(() => { disableButton.dispatchEvent(firstEvent); }); // There should now be a pending update to disable the form. // This should not have flushed yet since it's in concurrent mode. const submitButton = submitButtonRef.current; expect(submitButton.tagName).toBe('BUTTON'); // In the meantime, we can dispatch a new client event on the submit button. const secondEvent = document.createEvent('Event'); secondEvent.initEvent('click', true, true); // This should force the pending update to flush which disables the submit button before the event is invoked. await act(() => { submitButton.dispatchEvent(secondEvent); }); // Therefore the form should never have been submitted. expect(formSubmitted).toBe(false); }); it('uses the newest discrete events on a pending changed event listener', async () => { const enableButtonRef = React.createRef(); const submitButtonRef = React.createRef(); let formSubmitted = false; function Form() { const [active, setActive] = React.useState(false); function enableForm() { setActive(true); } function submitForm() { formSubmitted = true; // This should not get invoked } return ( <div> <button onClick={enableForm} ref={enableButtonRef}> Enable </button> <button onClick={active ? submitForm : null} ref={submitButtonRef}> Submit </button> </div> ); } const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<Form />); }); const enableButton = enableButtonRef.current; expect(enableButton.tagName).toBe('BUTTON'); // Dispatch a click event on the Enable-button. const firstEvent = document.createEvent('Event'); firstEvent.initEvent('click', true, true); await act(() => { enableButton.dispatchEvent(firstEvent); }); // There should now be a pending update to enable the form. // This should not have flushed yet since it's in concurrent mode. const submitButton = submitButtonRef.current; expect(submitButton.tagName).toBe('BUTTON'); // In the meantime, we can dispatch a new client event on the submit button. const secondEvent = document.createEvent('Event'); secondEvent.initEvent('click', true, true); // This should force the pending update to flush which enables the submit button before the event is invoked. await act(() => { submitButton.dispatchEvent(secondEvent); }); // Therefore the form should have been submitted. expect(formSubmitted).toBe(true); }); }); it('regression test: does not drop passive effects across roots (#17066)', async () => { const {useState, useEffect} = React; function App({label}) { const [step, setStep] = useState(0); useEffect(() => { if (step < 3) { setStep(step + 1); } }, [step]); // The component should keep re-rendering itself until `step` is 3. return step === 3 ? 'Finished' : 'Unresolved'; } const containerA = document.createElement('div'); const containerB = document.createElement('div'); const containerC = document.createElement('div'); await act(() => { ReactDOM.render(<App label="A" />, containerA); ReactDOM.render(<App label="B" />, containerB); ReactDOM.render(<App label="C" />, containerC); }); expect(containerA.textContent).toEqual('Finished'); expect(containerB.textContent).toEqual('Finished'); expect(containerC.textContent).toEqual('Finished'); }); it('updates flush without yielding in the next event', async () => { const root = ReactDOMClient.createRoot(container); function Text(props) { Scheduler.log(props.text); return props.text; } root.render( <> <Text text="A" /> <Text text="B" /> <Text text="C" /> </>, ); // Nothing should have rendered yet expect(container.textContent).toEqual(''); // Everything should render immediately in the next event await waitForAll(['A', 'B', 'C']); expect(container.textContent).toEqual('ABC'); }); it('unmounted roots should never clear newer root content from a container', async () => { const ref = React.createRef(); function OldApp() { const [value, setValue] = React.useState('old'); function hideOnClick() { // Schedule a discrete update. setValue('update'); // Synchronously unmount this root. ReactDOM.flushSync(() => oldRoot.unmount()); } return ( <button onClick={hideOnClick} ref={ref}> {value} </button> ); } function NewApp() { return <button ref={ref}>new</button>; } const oldRoot = ReactDOMClient.createRoot(container); await act(() => { oldRoot.render(<OldApp />); }); // Invoke discrete event. ref.current.click(); // The root should now be unmounted. expect(container.textContent).toBe(''); // We can now render a new one. const newRoot = ReactDOMClient.createRoot(container); ReactDOM.flushSync(() => { newRoot.render(<NewApp />); }); ref.current.click(); expect(container.textContent).toBe('new'); }); it('should synchronously render the transition lane scheduled in a popState', async () => { function App() { const [syncState, setSyncState] = React.useState(false); const [hasNavigated, setHasNavigated] = React.useState(false); function onPopstate() { Scheduler.log(`popState`); React.startTransition(() => { setHasNavigated(true); }); setSyncState(true); } React.useEffect(() => { window.addEventListener('popstate', onPopstate); return () => { window.removeEventListener('popstate', onPopstate); }; }, []); Scheduler.log(`render:${hasNavigated}/${syncState}`); return null; } const root = ReactDOMClient.createRoot(container); await act(async () => { root.render(<App />); }); assertLog(['render:false/false']); await act(async () => { const popStateEvent = new Event('popstate'); // Jest is not emulating window.event correctly in the microtask window.event = popStateEvent; window.dispatchEvent(popStateEvent); queueMicrotask(() => { window.event = undefined; }); }); assertLog(['popState', 'render:true/true']); await act(() => { root.unmount(); }); }); it('Should not flush transition lanes if there is no transition scheduled in popState', async () => { let setHasNavigated; function App() { const [syncState, setSyncState] = React.useState(false); const [hasNavigated, _setHasNavigated] = React.useState(false); setHasNavigated = _setHasNavigated; function onPopstate() { setSyncState(true); } React.useEffect(() => { window.addEventListener('popstate', onPopstate); return () => { window.removeEventListener('popstate', onPopstate); }; }, []); Scheduler.log(`render:${hasNavigated}/${syncState}`); return null; } const root = ReactDOMClient.createRoot(container); await act(async () => { root.render(<App />); }); assertLog(['render:false/false']); React.startTransition(() => { setHasNavigated(true); }); await act(async () => { const popStateEvent = new Event('popstate'); // Jest is not emulating window.event correctly in the microtask window.event = popStateEvent; window.dispatchEvent(popStateEvent); queueMicrotask(() => { window.event = undefined; }); }); assertLog(['render:false/true', 'render:true/true']); await act(() => { root.unmount(); }); }); it('transition lane in popState should be allowed to suspend', async () => { let resolvePromise; const promise = new Promise(res => { resolvePromise = res; }); function Text({text}) { Scheduler.log(text); return text; } function App() { const [pathname, setPathname] = React.useState('/path/a'); if (pathname !== '/path/a') { try { React.use(promise); } catch (e) { Scheduler.log(`Suspend! [${pathname}]`); throw e; } } React.useEffect(() => { function onPopstate() { React.startTransition(() => { setPathname('/path/b'); }); } window.addEventListener('popstate', onPopstate); return () => window.removeEventListener('popstate', onPopstate); }, []); return ( <> <Text text="Before" /> <div> <Text text={pathname} /> </div> <Text text="After" /> </> ); } const root = ReactDOMClient.createRoot(container); await act(async () => { root.render(<App />); }); assertLog(['Before', '/path/a', 'After']); const div = container.getElementsByTagName('div')[0]; expect(div.textContent).toBe('/path/a'); // Simulate a popstate event await act(async () => { const popStateEvent = new Event('popstate'); // Simulate a popstate event window.event = popStateEvent; window.dispatchEvent(popStateEvent); await waitForMicrotasks(); window.event = undefined; // The transition lane should have been attempted synchronously (in // a microtask) assertLog(['Suspend! [/path/b]']); // Because it suspended, it remains on the current path expect(div.textContent).toBe('/path/a'); }); assertLog(['Suspend! [/path/b]']); await act(async () => { resolvePromise(); // Since the transition previously suspended, there's no need for this // transition to be rendered synchronously on susbequent attempts; if we // fail to commit synchronously the first time, the scroll restoration // state won't be restored anyway. // // Yield in between each child to prove that it's concurrent. await waitForMicrotasks(); assertLog([]); await waitFor(['Before']); await waitFor(['/path/b']); await waitFor(['After']); }); assertLog([]); expect(div.textContent).toBe('/path/b'); await act(() => { root.unmount(); }); }); it('regression: infinite deferral loop caused by unstable useDeferredValue input', async () => { function Text({text}) { Scheduler.log(text); return text; } let i = 0; function App() { const [pathname, setPathname] = React.useState('/path/a'); // This is an unstable input, so it will always cause a deferred render. const {value: deferredPathname} = React.useDeferredValue({ value: pathname, }); if (i++ > 100) { throw new Error('Infinite loop detected'); } React.useEffect(() => { function onPopstate() { React.startTransition(() => { setPathname('/path/b'); }); } window.addEventListener('popstate', onPopstate); return () => window.removeEventListener('popstate', onPopstate); }, []); return <Text text={deferredPathname} />; } const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<App />); }); assertLog(['/path/a']); expect(container.textContent).toBe('/path/a'); // Simulate a popstate event await act(async () => { const popStateEvent = new Event('popstate'); // Simulate a popstate event window.event = popStateEvent; window.dispatchEvent(popStateEvent); await waitForMicrotasks(); window.event = undefined; // The transition lane is attempted synchronously (in a microtask). // Because the input to useDeferredValue is referentially unstable, it // will spawn a deferred task at transition priority. However, even // though it was spawned during a transition event, the spawned task // not also be upgraded to sync. assertLog(['/path/a']); }); assertLog(['/path/b']); expect(container.textContent).toBe('/path/b'); await act(() => { root.unmount(); }); }); });
28.428747
116
0.584328
null
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/use-subscription.production.min.js'); } else { module.exports = require('./cjs/use-subscription.development.js'); }
25.625
71
0.688679
Python-Penetration-Testing-for-Developers
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from './src/ReactFlightDOMClientNode';
22
66
0.702381
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from './ReactDOMFizzServerNode.js'; export {prerenderToNodeStream} from './ReactDOMFizzStaticNode.js';
25.416667
66
0.724684
Python-Penetration-Testing-Cookbook
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = useTheme; exports.ThemeContext = void 0; var _react = require("react"); /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ const ThemeContext = /*#__PURE__*/(0, _react.createContext)('bright'); exports.ThemeContext = ThemeContext; function useTheme() { const theme = (0, _react.useContext)(ThemeContext); (0, _react.useDebugValue)(theme); return theme; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInVzZVRoZW1lLmpzIl0sIm5hbWVzIjpbIlRoZW1lQ29udGV4dCIsInVzZVRoZW1lIiwidGhlbWUiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7O0FBU0E7O0FBVEE7Ozs7Ozs7O0FBV08sTUFBTUEsWUFBWSxnQkFBRywwQkFBYyxRQUFkLENBQXJCOzs7QUFFUSxTQUFTQyxRQUFULEdBQW9CO0FBQ2pDLFFBQU1DLEtBQUssR0FBRyx1QkFBV0YsWUFBWCxDQUFkO0FBQ0EsNEJBQWNFLEtBQWQ7QUFDQSxTQUFPQSxLQUFQO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IHtjcmVhdGVDb250ZXh0LCB1c2VDb250ZXh0LCB1c2VEZWJ1Z1ZhbHVlfSBmcm9tICdyZWFjdCc7XG5cbmV4cG9ydCBjb25zdCBUaGVtZUNvbnRleHQgPSBjcmVhdGVDb250ZXh0KCdicmlnaHQnKTtcblxuZXhwb3J0IGRlZmF1bHQgZnVuY3Rpb24gdXNlVGhlbWUoKSB7XG4gIGNvbnN0IHRoZW1lID0gdXNlQ29udGV4dChUaGVtZUNvbnRleHQpO1xuICB1c2VEZWJ1Z1ZhbHVlKHRoZW1lKTtcbiAgcmV0dXJuIHRoZW1lO1xufVxuIl19
60.703704
1,056
0.87988
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ /** * @param {array} arr an "accumulation" of items which is either an Array or * a single item. Useful when paired with the `accumulate` module. This is a * simple utility that allows us to reason about a collection of items, but * handling the case when there is exactly one item (and we do not need to * allocate an array). * @param {function} cb Callback invoked with each element or a collection. * @param {?} [scope] Scope used as `this` in a callback. */ function forEachAccumulated<T>( arr: ?(Array<T> | T), cb: (elem: T) => void, scope: ?any, ) { if (Array.isArray(arr)) { // $FlowFixMe[incompatible-call] if `T` is an array, `cb` cannot be called arr.forEach(cb, scope); } else if (arr) { cb.call(scope, arr); } } export default forEachAccumulated;
29.212121
78
0.676707
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ // Module provided by RN: import {UIManager} from 'react-native/Libraries/ReactPrivate/ReactNativePrivateInterface'; const ReactNativeGlobalResponderHandler = { onChange: function (from: any, to: any, blockNativeResponder: boolean) { if (to !== null) { const tag = to.stateNode._nativeTag; UIManager.setJSResponder(tag, blockNativeResponder); } else { UIManager.clearJSResponder(); } }, }; export default ReactNativeGlobalResponderHandler;
26.24
90
0.714706
PenetrationTestingScripts
#!/usr/bin/env node 'use strict'; const archiver = require('archiver'); const {execSync} = require('child_process'); const {readFileSync, writeFileSync, createWriteStream} = require('fs'); const {copy, ensureDir, move, remove, pathExistsSync} = require('fs-extra'); const {join, resolve} = require('path'); const {getGitCommit} = require('./utils'); // These files are copied along with Webpack-bundled files // to produce the final web extension const STATIC_FILES = ['icons', 'popups', 'main.html', 'panel.html']; /** * Ensures that a local build of the dependencies exist either by downloading * or running a local build via one of the `react-build-fordevtools*` scripts. */ const ensureLocalBuild = async () => { const buildDir = resolve(__dirname, '..', '..', 'build'); const nodeModulesDir = join(buildDir, 'node_modules'); // TODO: remove this check whenever the CI pipeline is complete. // See build-all-release-channels.js const currentBuildDir = resolve( __dirname, '..', '..', 'build', 'oss-experimental', ); if (pathExistsSync(buildDir)) { return; // all good. } if (pathExistsSync(currentBuildDir)) { await ensureDir(buildDir); await copy(currentBuildDir, nodeModulesDir); return; // all good. } throw Error( 'Could not find build artifacts in repo root. See README for prerequisites.', ); }; const preProcess = async (destinationPath, tempPath) => { await remove(destinationPath); // Clean up from previously completed builds await remove(tempPath); // Clean up from any previously failed builds await ensureDir(tempPath); // Create temp dir for this new build }; const build = async (tempPath, manifestPath, envExtension = {}) => { const binPath = join(tempPath, 'bin'); const zipPath = join(tempPath, 'zip'); const mergedEnv = {...process.env, ...envExtension}; const webpackPath = join(__dirname, 'node_modules', '.bin', 'webpack'); execSync( `${webpackPath} --config webpack.config.js --output-path ${binPath}`, { cwd: __dirname, env: mergedEnv, stdio: 'inherit', }, ); execSync( `${webpackPath} --config webpack.backend.js --output-path ${binPath}`, { cwd: __dirname, env: mergedEnv, stdio: 'inherit', }, ); // Make temp dir await ensureDir(zipPath); const copiedManifestPath = join(zipPath, 'manifest.json'); // Copy unbuilt source files to zip dir to be packaged: await copy(binPath, join(zipPath, 'build')); await copy(manifestPath, copiedManifestPath); await Promise.all( STATIC_FILES.map(file => copy(join(__dirname, file), join(zipPath, file))), ); const commit = getGitCommit(); const dateString = new Date().toLocaleDateString(); const manifest = JSON.parse(readFileSync(copiedManifestPath).toString()); const versionDateString = `${manifest.version} (${dateString})`; if (manifest.version_name) { manifest.version_name = versionDateString; } manifest.description += `\n\nCreated from revision ${commit} on ${dateString}.`; if (process.env.NODE_ENV === 'development') { // When building the local development version of the // extension we want to be able to have a stable extension ID // for the local build (in order to be able to reliably detect // duplicate installations of DevTools). // By specifying a key in the built manifest.json file, // we can make it so the generated extension ID is stable. // For more details see the docs here: https://developer.chrome.com/docs/extensions/mv2/manifest/key/ manifest.key = 'reactdevtoolslocalbuilduniquekey'; } writeFileSync(copiedManifestPath, JSON.stringify(manifest, null, 2)); // Pack the extension const archive = archiver('zip', {zlib: {level: 9}}); const zipStream = createWriteStream(join(tempPath, 'ReactDevTools.zip')); await new Promise((resolvePromise, rejectPromise) => { archive .directory(zipPath, false) .on('error', err => rejectPromise(err)) .pipe(zipStream); archive.finalize(); zipStream.on('close', () => resolvePromise()); }); }; const postProcess = async (tempPath, destinationPath) => { const unpackedSourcePath = join(tempPath, 'zip'); const packedSourcePath = join(tempPath, 'ReactDevTools.zip'); const packedDestPath = join(destinationPath, 'ReactDevTools.zip'); const unpackedDestPath = join(destinationPath, 'unpacked'); await move(unpackedSourcePath, unpackedDestPath); // Copy built files to destination await move(packedSourcePath, packedDestPath); // Copy built files to destination await remove(tempPath); // Clean up temp directory and files }; const SUPPORTED_BUILDS = ['chrome', 'firefox', 'edge']; const main = async buildId => { if (!SUPPORTED_BUILDS.includes(buildId)) { throw new Error( `Unexpected build id - "${buildId}". Use one of ${JSON.stringify( SUPPORTED_BUILDS, )}.`, ); } const root = join(__dirname, buildId); const manifestPath = join(root, 'manifest.json'); const destinationPath = join(root, 'build'); const envExtension = { IS_CHROME: buildId === 'chrome', IS_FIREFOX: buildId === 'firefox', IS_EDGE: buildId === 'edge', }; try { const tempPath = join(__dirname, 'build', buildId); await ensureLocalBuild(); await preProcess(destinationPath, tempPath); await build(tempPath, manifestPath, envExtension); const builtUnpackedPath = join(destinationPath, 'unpacked'); await postProcess(tempPath, destinationPath); return builtUnpackedPath; } catch (error) { console.error(error); process.exit(1); } return null; }; module.exports = main;
31.238636
105
0.679358
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import { importFromChromeTimeline, Flamechart as SpeedscopeFlamechart, } from '@elg/speedscope'; import type {TimelineEvent} from '@elg/speedscope'; import type { ErrorStackFrame, BatchUID, Flamechart, Milliseconds, NativeEvent, NetworkMeasure, Phase, ReactLane, ReactComponentMeasure, ReactComponentMeasureType, ReactMeasure, ReactMeasureType, TimelineData, SchedulingEvent, SuspenseEvent, } from '../types'; import { REACT_TOTAL_NUM_LANES, SCHEDULING_PROFILER_VERSION, SNAPSHOT_MAX_HEIGHT, } from '../constants'; import InvalidProfileError from './InvalidProfileError'; import {getBatchRange} from '../utils/getBatchRange'; import ErrorStackParser from 'error-stack-parser'; type MeasureStackElement = { type: ReactMeasureType, depth: number, measure: ReactMeasure, startTime: Milliseconds, stopTime?: Milliseconds, }; type ProcessorState = { asyncProcessingPromises: Promise<any>[], batchUID: BatchUID, currentReactComponentMeasure: ReactComponentMeasure | null, internalModuleCurrentStackFrame: ErrorStackFrame | null, internalModuleStackStringSet: Set<string>, measureStack: MeasureStackElement[], nativeEventStack: NativeEvent[], nextRenderShouldGenerateNewBatchID: boolean, potentialLongEvents: Array<[NativeEvent, BatchUID]>, potentialLongNestedUpdate: SchedulingEvent | null, potentialLongNestedUpdates: Array<[SchedulingEvent, BatchUID]>, potentialSuspenseEventsOutsideOfTransition: Array< [SuspenseEvent, ReactLane[]], >, requestIdToNetworkMeasureMap: Map<string, NetworkMeasure>, uidCounter: BatchUID, unresolvedSuspenseEvents: Map<string, SuspenseEvent>, }; const NATIVE_EVENT_DURATION_THRESHOLD = 20; const NESTED_UPDATE_DURATION_THRESHOLD = 20; const WARNING_STRINGS = { LONG_EVENT_HANDLER: 'An event handler scheduled a big update with React. Consider using the Transition API to defer some of this work.', NESTED_UPDATE: 'A big nested update was scheduled during layout. ' + 'Nested updates require React to re-render synchronously before the browser can paint. ' + 'Consider delaying this update by moving it to a passive effect (useEffect).', SUSPEND_DURING_UPDATE: 'A component suspended during an update which caused a fallback to be shown. ' + "Consider using the Transition API to avoid hiding components after they've been mounted.", }; // Exported for tests export function getLanesFromTransportDecimalBitmask( laneBitmaskString: string, ): ReactLane[] { const laneBitmask = parseInt(laneBitmaskString, 10); // As negative numbers are stored in two's complement format, our bitmask // checks will be thrown off by them. if (laneBitmask < 0) { return []; } const lanes = []; let powersOfTwo = 0; while (powersOfTwo <= REACT_TOTAL_NUM_LANES) { if ((1 << powersOfTwo) & laneBitmask) { lanes.push(powersOfTwo); } powersOfTwo++; } return lanes; } function updateLaneToLabelMap( profilerData: TimelineData, laneLabelTuplesString: string, ): void { // These marks appear multiple times in the data; // We only need to extact them once. if (profilerData.laneToLabelMap.size === 0) { const laneLabelTuples = laneLabelTuplesString.split(','); for (let laneIndex = 0; laneIndex < laneLabelTuples.length; laneIndex++) { // The numeric lane value (e.g. 64) isn't important. // The profiler parses and stores the lane's position within the bitmap, // (e.g. lane 1 is index 0, lane 16 is index 4). profilerData.laneToLabelMap.set(laneIndex, laneLabelTuples[laneIndex]); } } } let profilerVersion = null; function getLastType(stack: $PropertyType<ProcessorState, 'measureStack'>) { if (stack.length > 0) { const {type} = stack[stack.length - 1]; return type; } return null; } function getDepth(stack: $PropertyType<ProcessorState, 'measureStack'>) { if (stack.length > 0) { const {depth, type} = stack[stack.length - 1]; return type === 'render-idle' ? depth : depth + 1; } return 0; } function markWorkStarted( type: ReactMeasureType, startTime: Milliseconds, lanes: ReactLane[], currentProfilerData: TimelineData, state: ProcessorState, ) { const {batchUID, measureStack} = state; const depth = getDepth(measureStack); const measure: ReactMeasure = { type, batchUID, depth, lanes, timestamp: startTime, duration: 0, }; state.measureStack.push({depth, measure, startTime, type}); // This array is pre-initialized when the batchUID is generated. const measures = currentProfilerData.batchUIDToMeasuresMap.get(batchUID); if (measures != null) { measures.push(measure); } else { currentProfilerData.batchUIDToMeasuresMap.set(state.batchUID, [measure]); } // This array is pre-initialized before processing starts. lanes.forEach(lane => { ((currentProfilerData.laneToReactMeasureMap.get( lane, ): any): ReactMeasure[]).push(measure); }); } function markWorkCompleted( type: ReactMeasureType, stopTime: Milliseconds, currentProfilerData: TimelineData, stack: $PropertyType<ProcessorState, 'measureStack'>, ) { if (stack.length === 0) { console.error( 'Unexpected type "%s" completed at %sms while stack is empty.', type, stopTime, ); // Ignore work "completion" user timing mark that doesn't complete anything return; } const last = stack[stack.length - 1]; if (last.type !== type) { console.error( 'Unexpected type "%s" completed at %sms before "%s" completed.', type, stopTime, last.type, ); } const {measure, startTime} = stack.pop(); if (!measure) { console.error('Could not find matching measure for type "%s".', type); } // $FlowFixMe[cannot-write] This property should not be writable outside of this function. measure.duration = stopTime - startTime; } function throwIfIncomplete( type: ReactMeasureType, stack: $PropertyType<ProcessorState, 'measureStack'>, ) { const lastIndex = stack.length - 1; if (lastIndex >= 0) { const last = stack[lastIndex]; if (last.stopTime === undefined && last.type === type) { throw new InvalidProfileError( `Unexpected type "${type}" started before "${last.type}" completed.`, ); } } } function processEventDispatch( event: TimelineEvent, timestamp: Milliseconds, profilerData: TimelineData, state: ProcessorState, ) { const data = event.args.data; const type = data.type; if (type.startsWith('react-')) { const stackTrace = data.stackTrace; if (stackTrace) { const topFrame = stackTrace[stackTrace.length - 1]; if (topFrame.url.includes('/react-dom.')) { // Filter out fake React events dispatched by invokeGuardedCallbackDev. return; } } } // Reduce noise from events like DOMActivate, load/unload, etc. which are usually not relevant if ( type === 'blur' || type === 'click' || type === 'input' || type.startsWith('focus') || type.startsWith('key') || type.startsWith('mouse') || type.startsWith('pointer') ) { const duration = event.dur / 1000; let depth = 0; while (state.nativeEventStack.length > 0) { const prevNativeEvent = state.nativeEventStack[state.nativeEventStack.length - 1]; const prevStopTime = prevNativeEvent.timestamp + prevNativeEvent.duration; if (timestamp < prevStopTime) { depth = prevNativeEvent.depth + 1; break; } else { state.nativeEventStack.pop(); } } const nativeEvent = { depth, duration, timestamp, type, warning: null, }; profilerData.nativeEvents.push(nativeEvent); // Keep track of curent event in case future ones overlap. // We separate them into different vertical lanes in this case. state.nativeEventStack.push(nativeEvent); } } function processResourceFinish( event: TimelineEvent, timestamp: Milliseconds, profilerData: TimelineData, state: ProcessorState, ) { const requestId = event.args.data.requestId; const networkMeasure = state.requestIdToNetworkMeasureMap.get(requestId); if (networkMeasure != null) { networkMeasure.finishTimestamp = timestamp; if (networkMeasure.firstReceivedDataTimestamp === 0) { networkMeasure.firstReceivedDataTimestamp = timestamp; } if (networkMeasure.lastReceivedDataTimestamp === 0) { networkMeasure.lastReceivedDataTimestamp = timestamp; } // Clean up now that the resource is done. state.requestIdToNetworkMeasureMap.delete(event.args.data.requestId); } } function processResourceReceivedData( event: TimelineEvent, timestamp: Milliseconds, profilerData: TimelineData, state: ProcessorState, ) { const requestId = event.args.data.requestId; const networkMeasure = state.requestIdToNetworkMeasureMap.get(requestId); if (networkMeasure != null) { if (networkMeasure.firstReceivedDataTimestamp === 0) { networkMeasure.firstReceivedDataTimestamp = timestamp; } networkMeasure.lastReceivedDataTimestamp = timestamp; networkMeasure.finishTimestamp = timestamp; } } function processResourceReceiveResponse( event: TimelineEvent, timestamp: Milliseconds, profilerData: TimelineData, state: ProcessorState, ) { const requestId = event.args.data.requestId; const networkMeasure = state.requestIdToNetworkMeasureMap.get(requestId); if (networkMeasure != null) { networkMeasure.receiveResponseTimestamp = timestamp; } } function processScreenshot( event: TimelineEvent, timestamp: Milliseconds, profilerData: TimelineData, state: ProcessorState, ) { const encodedSnapshot = event.args.snapshot; // Base 64 encoded const snapshot = { height: 0, image: null, imageSource: `data:image/png;base64,${encodedSnapshot}`, timestamp, width: 0, }; // Delay processing until we've extracted snapshot dimensions. let resolveFn = ((null: any): Function); state.asyncProcessingPromises.push( new Promise(resolve => { resolveFn = resolve; }), ); // Parse the Base64 image data to determine native size. // This will be used later to scale for display within the thumbnail strip. fetch(snapshot.imageSource) .then(response => response.blob()) .then(blob => { // $FlowFixMe[cannot-resolve-name] createImageBitmap createImageBitmap(blob).then(bitmap => { snapshot.height = bitmap.height; snapshot.width = bitmap.width; resolveFn(); }); }); profilerData.snapshots.push(snapshot); } function processResourceSendRequest( event: TimelineEvent, timestamp: Milliseconds, profilerData: TimelineData, state: ProcessorState, ) { const data = event.args.data; const requestId = data.requestId; const availableDepths = new Array<boolean>( state.requestIdToNetworkMeasureMap.size + 1, ).fill(true); state.requestIdToNetworkMeasureMap.forEach(({depth}) => { availableDepths[depth] = false; }); let depth = 0; for (let i = 0; i < availableDepths.length; i++) { if (availableDepths[i]) { depth = i; break; } } const networkMeasure: NetworkMeasure = { depth, finishTimestamp: 0, firstReceivedDataTimestamp: 0, lastReceivedDataTimestamp: 0, requestId, requestMethod: data.requestMethod, priority: data.priority, sendRequestTimestamp: timestamp, receiveResponseTimestamp: 0, url: data.url, }; state.requestIdToNetworkMeasureMap.set(requestId, networkMeasure); profilerData.networkMeasures.push(networkMeasure); networkMeasure.sendRequestTimestamp = timestamp; } function processTimelineEvent( event: TimelineEvent, /** Finalized profiler data up to `event`. May be mutated. */ currentProfilerData: TimelineData, /** Intermediate processor state. May be mutated. */ state: ProcessorState, ) { const {cat, name, ts, ph} = event; const startTime = (ts - currentProfilerData.startTime) / 1000; switch (cat) { case 'disabled-by-default-devtools.screenshot': processScreenshot(event, startTime, currentProfilerData, state); break; case 'devtools.timeline': switch (name) { case 'EventDispatch': processEventDispatch(event, startTime, currentProfilerData, state); break; case 'ResourceFinish': processResourceFinish(event, startTime, currentProfilerData, state); break; case 'ResourceReceivedData': processResourceReceivedData( event, startTime, currentProfilerData, state, ); break; case 'ResourceReceiveResponse': processResourceReceiveResponse( event, startTime, currentProfilerData, state, ); break; case 'ResourceSendRequest': processResourceSendRequest( event, startTime, currentProfilerData, state, ); break; } break; case 'blink.user_timing': if (name.startsWith('--react-version-')) { const [reactVersion] = name.slice(16).split('-'); currentProfilerData.reactVersion = reactVersion; } else if (name.startsWith('--profiler-version-')) { const [versionString] = name.slice(19).split('-'); profilerVersion = parseInt(versionString, 10); if (profilerVersion !== SCHEDULING_PROFILER_VERSION) { throw new InvalidProfileError( `This version of profiling data (${versionString}) is not supported by the current profiler.`, ); } } else if (name.startsWith('--react-lane-labels-')) { const [laneLabelTuplesString] = name.slice(20).split('-'); updateLaneToLabelMap(currentProfilerData, laneLabelTuplesString); } else if (name.startsWith('--component-')) { processReactComponentMeasure( name, startTime, currentProfilerData, state, ); } else if (name.startsWith('--schedule-render-')) { const [laneBitmaskString] = name.slice(18).split('-'); currentProfilerData.schedulingEvents.push({ type: 'schedule-render', lanes: getLanesFromTransportDecimalBitmask(laneBitmaskString), timestamp: startTime, warning: null, }); } else if (name.startsWith('--schedule-forced-update-')) { const [laneBitmaskString, componentName] = name.slice(25).split('-'); const forceUpdateEvent = { type: 'schedule-force-update', lanes: getLanesFromTransportDecimalBitmask(laneBitmaskString), componentName, timestamp: startTime, warning: null, }; // If this is a nested update, make a note of it. // Once we're done processing events, we'll check to see if it was a long update and warn about it. if (state.measureStack.find(({type}) => type === 'commit')) { state.potentialLongNestedUpdate = forceUpdateEvent; } currentProfilerData.schedulingEvents.push(forceUpdateEvent); } else if (name.startsWith('--schedule-state-update-')) { const [laneBitmaskString, componentName] = name.slice(24).split('-'); const stateUpdateEvent = { type: 'schedule-state-update', lanes: getLanesFromTransportDecimalBitmask(laneBitmaskString), componentName, timestamp: startTime, warning: null, }; // If this is a nested update, make a note of it. // Once we're done processing events, we'll check to see if it was a long update and warn about it. if (state.measureStack.find(({type}) => type === 'commit')) { state.potentialLongNestedUpdate = stateUpdateEvent; } currentProfilerData.schedulingEvents.push(stateUpdateEvent); } else if (name.startsWith('--error-')) { const [componentName, phase, message] = name.slice(8).split('-'); currentProfilerData.thrownErrors.push({ componentName, message, phase: ((phase: any): Phase), timestamp: startTime, type: 'thrown-error', }); } else if (name.startsWith('--suspense-suspend-')) { const [id, componentName, phase, laneBitmaskString, promiseName] = name .slice(19) .split('-'); const lanes = getLanesFromTransportDecimalBitmask(laneBitmaskString); const availableDepths = new Array<boolean>( state.unresolvedSuspenseEvents.size + 1, ).fill(true); state.unresolvedSuspenseEvents.forEach(({depth}) => { availableDepths[depth] = false; }); let depth = 0; for (let i = 0; i < availableDepths.length; i++) { if (availableDepths[i]) { depth = i; break; } } // TODO (timeline) Maybe we should calculate depth in post, // so unresolved Suspense requests don't take up space. // We can't know if they'll be resolved or not at this point. // We'll just give them a default (fake) duration width. const suspenseEvent = { componentName, depth, duration: null, id, phase: ((phase: any): Phase), promiseName: promiseName || null, resolution: 'unresolved', timestamp: startTime, type: 'suspense', warning: null, }; if (phase === 'update') { // If a component suspended during an update, we should verify that it was during a transition. // We need the lane metadata to verify this though. // Since that data is only logged during commit, we may not have it yet. // Store these events for post-processing then. state.potentialSuspenseEventsOutsideOfTransition.push([ suspenseEvent, lanes, ]); } currentProfilerData.suspenseEvents.push(suspenseEvent); state.unresolvedSuspenseEvents.set(id, suspenseEvent); } else if (name.startsWith('--suspense-resolved-')) { const [id] = name.slice(20).split('-'); const suspenseEvent = state.unresolvedSuspenseEvents.get(id); if (suspenseEvent != null) { state.unresolvedSuspenseEvents.delete(id); suspenseEvent.duration = startTime - suspenseEvent.timestamp; suspenseEvent.resolution = 'resolved'; } } else if (name.startsWith('--suspense-rejected-')) { const [id] = name.slice(20).split('-'); const suspenseEvent = state.unresolvedSuspenseEvents.get(id); if (suspenseEvent != null) { state.unresolvedSuspenseEvents.delete(id); suspenseEvent.duration = startTime - suspenseEvent.timestamp; suspenseEvent.resolution = 'rejected'; } } else if (name.startsWith('--render-start-')) { if (state.nextRenderShouldGenerateNewBatchID) { state.nextRenderShouldGenerateNewBatchID = false; state.batchUID = ((state.uidCounter++: any): BatchUID); } // If this render is the result of a nested update, make a note of it. // Once we're done processing events, we'll check to see if it was a long update and warn about it. if (state.potentialLongNestedUpdate !== null) { state.potentialLongNestedUpdates.push([ state.potentialLongNestedUpdate, state.batchUID, ]); state.potentialLongNestedUpdate = null; } const [laneBitmaskString] = name.slice(15).split('-'); throwIfIncomplete('render', state.measureStack); if (getLastType(state.measureStack) !== 'render-idle') { markWorkStarted( 'render-idle', startTime, getLanesFromTransportDecimalBitmask(laneBitmaskString), currentProfilerData, state, ); } markWorkStarted( 'render', startTime, getLanesFromTransportDecimalBitmask(laneBitmaskString), currentProfilerData, state, ); for (let i = 0; i < state.nativeEventStack.length; i++) { const nativeEvent = state.nativeEventStack[i]; const stopTime = nativeEvent.timestamp + nativeEvent.duration; // If React work was scheduled during an event handler, and the event had a long duration, // it might be because the React render was long and stretched the event. // It might also be that the React work was short and that something else stretched the event. // Make a note of this event for now and we'll examine the batch of React render work later. // (We can't know until we're done processing the React update anyway.) if (stopTime > startTime) { state.potentialLongEvents.push([nativeEvent, state.batchUID]); } } } else if ( name.startsWith('--render-stop') || name.startsWith('--render-yield') ) { markWorkCompleted( 'render', startTime, currentProfilerData, state.measureStack, ); } else if (name.startsWith('--commit-start-')) { state.nextRenderShouldGenerateNewBatchID = true; const [laneBitmaskString] = name.slice(15).split('-'); markWorkStarted( 'commit', startTime, getLanesFromTransportDecimalBitmask(laneBitmaskString), currentProfilerData, state, ); } else if (name.startsWith('--commit-stop')) { markWorkCompleted( 'commit', startTime, currentProfilerData, state.measureStack, ); markWorkCompleted( 'render-idle', startTime, currentProfilerData, state.measureStack, ); } else if (name.startsWith('--layout-effects-start-')) { const [laneBitmaskString] = name.slice(23).split('-'); markWorkStarted( 'layout-effects', startTime, getLanesFromTransportDecimalBitmask(laneBitmaskString), currentProfilerData, state, ); } else if (name.startsWith('--layout-effects-stop')) { markWorkCompleted( 'layout-effects', startTime, currentProfilerData, state.measureStack, ); } else if (name.startsWith('--passive-effects-start-')) { const [laneBitmaskString] = name.slice(24).split('-'); markWorkStarted( 'passive-effects', startTime, getLanesFromTransportDecimalBitmask(laneBitmaskString), currentProfilerData, state, ); } else if (name.startsWith('--passive-effects-stop')) { markWorkCompleted( 'passive-effects', startTime, currentProfilerData, state.measureStack, ); } else if (name.startsWith('--react-internal-module-start-')) { const stackFrameStart = name.slice(30); if (!state.internalModuleStackStringSet.has(stackFrameStart)) { state.internalModuleStackStringSet.add(stackFrameStart); const parsedStackFrameStart = parseStackFrame(stackFrameStart); state.internalModuleCurrentStackFrame = parsedStackFrameStart; } } else if (name.startsWith('--react-internal-module-stop-')) { const stackFrameStop = name.slice(29); if (!state.internalModuleStackStringSet.has(stackFrameStop)) { state.internalModuleStackStringSet.add(stackFrameStop); const parsedStackFrameStop = parseStackFrame(stackFrameStop); if ( parsedStackFrameStop !== null && state.internalModuleCurrentStackFrame !== null ) { const parsedStackFrameStart = state.internalModuleCurrentStackFrame; state.internalModuleCurrentStackFrame = null; const range = [parsedStackFrameStart, parsedStackFrameStop]; const ranges = currentProfilerData.internalModuleSourceToRanges.get( parsedStackFrameStart.fileName, ); if (ranges == null) { currentProfilerData.internalModuleSourceToRanges.set( parsedStackFrameStart.fileName, [range], ); } else { ranges.push(range); } } } } else if (ph === 'R' || ph === 'n') { // User Timing mark currentProfilerData.otherUserTimingMarks.push({ name, timestamp: startTime, }); } else if (ph === 'b') { // TODO: Begin user timing measure } else if (ph === 'e') { // TODO: End user timing measure } else if (ph === 'i' || ph === 'I') { // Instant events. // Note that the capital "I" is a deprecated value that exists in Chrome Canary traces. } else { throw new InvalidProfileError( `Unrecognized event ${JSON.stringify( event, )}! This is likely a bug in this profiler tool.`, ); } break; } } function assertNoOverlappingComponentMeasure(state: ProcessorState) { if (state.currentReactComponentMeasure !== null) { console.error( 'Component measure started while another measure in progress:', state.currentReactComponentMeasure, ); } } function assertCurrentComponentMeasureType( state: ProcessorState, type: ReactComponentMeasureType, ): void { if (state.currentReactComponentMeasure === null) { console.error( `Component measure type "${type}" stopped while no measure was in progress`, ); } else if (state.currentReactComponentMeasure.type !== type) { console.error( `Component measure type "${type}" stopped while type ${state.currentReactComponentMeasure.type} in progress`, ); } } function processReactComponentMeasure( name: string, startTime: Milliseconds, currentProfilerData: TimelineData, state: ProcessorState, ): void { if (name.startsWith('--component-render-start-')) { const [componentName] = name.slice(25).split('-'); assertNoOverlappingComponentMeasure(state); state.currentReactComponentMeasure = { componentName, timestamp: startTime, duration: 0, type: 'render', warning: null, }; } else if (name === '--component-render-stop') { assertCurrentComponentMeasureType(state, 'render'); if (state.currentReactComponentMeasure !== null) { const componentMeasure = state.currentReactComponentMeasure; componentMeasure.duration = startTime - componentMeasure.timestamp; state.currentReactComponentMeasure = null; currentProfilerData.componentMeasures.push(componentMeasure); } } else if (name.startsWith('--component-layout-effect-mount-start-')) { const [componentName] = name.slice(38).split('-'); assertNoOverlappingComponentMeasure(state); state.currentReactComponentMeasure = { componentName, timestamp: startTime, duration: 0, type: 'layout-effect-mount', warning: null, }; } else if (name === '--component-layout-effect-mount-stop') { assertCurrentComponentMeasureType(state, 'layout-effect-mount'); if (state.currentReactComponentMeasure !== null) { const componentMeasure = state.currentReactComponentMeasure; componentMeasure.duration = startTime - componentMeasure.timestamp; state.currentReactComponentMeasure = null; currentProfilerData.componentMeasures.push(componentMeasure); } } else if (name.startsWith('--component-layout-effect-unmount-start-')) { const [componentName] = name.slice(40).split('-'); assertNoOverlappingComponentMeasure(state); state.currentReactComponentMeasure = { componentName, timestamp: startTime, duration: 0, type: 'layout-effect-unmount', warning: null, }; } else if (name === '--component-layout-effect-unmount-stop') { assertCurrentComponentMeasureType(state, 'layout-effect-unmount'); if (state.currentReactComponentMeasure !== null) { const componentMeasure = state.currentReactComponentMeasure; componentMeasure.duration = startTime - componentMeasure.timestamp; state.currentReactComponentMeasure = null; currentProfilerData.componentMeasures.push(componentMeasure); } } else if (name.startsWith('--component-passive-effect-mount-start-')) { const [componentName] = name.slice(39).split('-'); assertNoOverlappingComponentMeasure(state); state.currentReactComponentMeasure = { componentName, timestamp: startTime, duration: 0, type: 'passive-effect-mount', warning: null, }; } else if (name === '--component-passive-effect-mount-stop') { assertCurrentComponentMeasureType(state, 'passive-effect-mount'); if (state.currentReactComponentMeasure !== null) { const componentMeasure = state.currentReactComponentMeasure; componentMeasure.duration = startTime - componentMeasure.timestamp; state.currentReactComponentMeasure = null; currentProfilerData.componentMeasures.push(componentMeasure); } } else if (name.startsWith('--component-passive-effect-unmount-start-')) { const [componentName] = name.slice(41).split('-'); assertNoOverlappingComponentMeasure(state); state.currentReactComponentMeasure = { componentName, timestamp: startTime, duration: 0, type: 'passive-effect-unmount', warning: null, }; } else if (name === '--component-passive-effect-unmount-stop') { assertCurrentComponentMeasureType(state, 'passive-effect-unmount'); if (state.currentReactComponentMeasure !== null) { const componentMeasure = state.currentReactComponentMeasure; componentMeasure.duration = startTime - componentMeasure.timestamp; state.currentReactComponentMeasure = null; currentProfilerData.componentMeasures.push(componentMeasure); } } } function preprocessFlamechart(rawData: TimelineEvent[]): Flamechart { let parsedData; try { parsedData = importFromChromeTimeline(rawData, 'react-devtools'); } catch (error) { // Assume any Speedscope errors are caused by bad profiles const errorToRethrow = new InvalidProfileError(error.message); errorToRethrow.stack = error.stack; throw errorToRethrow; } const profile = parsedData.profiles[0]; // TODO: Choose the main CPU thread only const speedscopeFlamechart = new SpeedscopeFlamechart({ // $FlowFixMe[method-unbinding] getTotalWeight: profile.getTotalWeight.bind(profile), // $FlowFixMe[method-unbinding] forEachCall: profile.forEachCall.bind(profile), // $FlowFixMe[method-unbinding] formatValue: profile.formatValue.bind(profile), getColorBucketForFrame: () => 0, }); const flamechart: Flamechart = speedscopeFlamechart.getLayers().map(layer => layer.map( ({ start, end, node: { frame: {name, file, line, col}, }, }) => ({ name, timestamp: start / 1000, duration: (end - start) / 1000, scriptUrl: file, locationLine: line, locationColumn: col, }), ), ); return flamechart; } function parseStackFrame(stackFrame: string): ErrorStackFrame | null { const error = new Error(); error.stack = stackFrame; const frames = ErrorStackParser.parse(error); return frames.length === 1 ? frames[0] : null; } export default async function preprocessData( timeline: TimelineEvent[], ): Promise<TimelineData> { const flamechart = preprocessFlamechart(timeline); const laneToReactMeasureMap: Map<ReactLane, Array<ReactMeasure>> = new Map(); for (let lane: ReactLane = 0; lane < REACT_TOTAL_NUM_LANES; lane++) { laneToReactMeasureMap.set(lane, []); } const profilerData: TimelineData = { batchUIDToMeasuresMap: new Map(), componentMeasures: [], duration: 0, flamechart, internalModuleSourceToRanges: new Map(), laneToLabelMap: new Map(), laneToReactMeasureMap, nativeEvents: [], networkMeasures: [], otherUserTimingMarks: [], reactVersion: null, schedulingEvents: [], snapshots: [], snapshotHeight: 0, startTime: 0, suspenseEvents: [], thrownErrors: [], }; // Sort `timeline`. JSON Array Format trace events need not be ordered. See: // https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview#heading=h.f2f0yd51wi15 timeline = timeline.filter(Boolean).sort((a, b) => (a.ts > b.ts ? 1 : -1)); // Events displayed in flamechart have timestamps relative to the profile // event's startTime. Source: https://github.com/v8/v8/blob/44bd8fd7/src/inspector/js_protocol.json#L1486 // // We'll thus expect there to be a 'Profile' event; if there is not one, we // can deduce that there are no flame chart events. As we expect React // scheduling profiling user timing marks to be recorded together with browser // flame chart events, we can futher deduce that the data is invalid and we // don't bother finding React events. const indexOfProfileEvent = timeline.findIndex( event => event.name === 'Profile', ); if (indexOfProfileEvent === -1) { return profilerData; } // Use Profile event's `startTime` as the start time to align with flame chart. // TODO: Remove assumption that there'll only be 1 'Profile' event. If this // assumption does not hold, the chart may start at the wrong time. profilerData.startTime = timeline[indexOfProfileEvent].args.data.startTime; profilerData.duration = (timeline[timeline.length - 1].ts - profilerData.startTime) / 1000; const state: ProcessorState = { asyncProcessingPromises: [], batchUID: 0, currentReactComponentMeasure: null, internalModuleCurrentStackFrame: null, internalModuleStackStringSet: new Set(), measureStack: [], nativeEventStack: [], nextRenderShouldGenerateNewBatchID: true, potentialLongEvents: [], potentialLongNestedUpdate: null, potentialLongNestedUpdates: [], potentialSuspenseEventsOutsideOfTransition: [], requestIdToNetworkMeasureMap: new Map(), uidCounter: 0, unresolvedSuspenseEvents: new Map(), }; timeline.forEach(event => processTimelineEvent(event, profilerData, state)); if (profilerVersion === null) { if ( profilerData.schedulingEvents.length === 0 && profilerData.batchUIDToMeasuresMap.size === 0 ) { // No profiler version could indicate data was logged using an older build of React, // before an explicitly profiler version was included in the logging data. // But it could also indicate that the website was either not using React, or using a production build. // The easiest way to check for this case is to see if the data contains any scheduled updates or render work. throw new InvalidProfileError( 'No React marks were found in the provided profile.' + ' Please provide profiling data from an React application running in development or profiling mode.', ); } throw new InvalidProfileError( `This version of profiling data is not supported by the current profiler.`, ); } // Validate that all events and measures are complete const {measureStack} = state; if (measureStack.length > 0) { console.error('Incomplete events or measures', measureStack); } // Check for warnings. state.potentialLongEvents.forEach(([nativeEvent, batchUID]) => { // See how long the subsequent batch of React work was. // Ignore any work that was already started. const [startTime, stopTime] = getBatchRange( batchUID, profilerData, nativeEvent.timestamp, ); if (stopTime - startTime > NATIVE_EVENT_DURATION_THRESHOLD) { nativeEvent.warning = WARNING_STRINGS.LONG_EVENT_HANDLER; } }); state.potentialLongNestedUpdates.forEach(([schedulingEvent, batchUID]) => { // See how long the subsequent batch of React work was. const [startTime, stopTime] = getBatchRange(batchUID, profilerData); if (stopTime - startTime > NESTED_UPDATE_DURATION_THRESHOLD) { // Don't warn about transition updates scheduled during the commit phase. // e.g. useTransition, useDeferredValue // These are allowed to be long-running. if ( !schedulingEvent.lanes.some( lane => profilerData.laneToLabelMap.get(lane) === 'Transition', ) ) { // FIXME: This warning doesn't account for "nested updates" that are // spawned by useDeferredValue. Disabling temporarily until we figure // out the right way to handle this. // schedulingEvent.warning = WARNING_STRINGS.NESTED_UPDATE; } } }); state.potentialSuspenseEventsOutsideOfTransition.forEach( ([suspenseEvent, lanes]) => { // HACK This is a bit gross but the numeric lane value might change between render versions. if ( !lanes.some( lane => profilerData.laneToLabelMap.get(lane) === 'Transition', ) ) { suspenseEvent.warning = WARNING_STRINGS.SUSPEND_DURING_UPDATE; } }, ); // Wait for any async processing to complete before returning. // Since processing is done in a worker, async work must complete before data is serialized and returned. await Promise.all(state.asyncProcessingPromises); // Now that all images have been loaded, let's figure out the display size we're going to use for our thumbnails: // both the ones rendered to the canvas and the ones shown on hover. if (profilerData.snapshots.length > 0) { // NOTE We assume a static window size here, which is not necessarily true but should be for most cases. // Regardless, Chrome also sets a single size/ratio and stick with it- so we'll do the same. const snapshot = profilerData.snapshots[0]; profilerData.snapshotHeight = Math.min( snapshot.height, SNAPSHOT_MAX_HEIGHT, ); } return profilerData; }
31.902813
120
0.660232
owtf
/* * Copyright (c) Facebook, Inc. and its affiliates. */ const defaultTheme = require('tailwindcss/defaultTheme'); const colors = require('./colors'); module.exports = { content: [ './src/components/**/*.{js,ts,jsx,tsx}', './src/pages/**/*.{js,ts,jsx,tsx}', './src/styles/**/*.{js,ts,jsx,tsx}', ], darkMode: 'class', theme: { // Override base screen sizes screens: { ...defaultTheme.screens, betterhover: {raw: '(hover: hover)'}, xs: '374px', '3xl': '1919px', }, boxShadow: { sm: '0 1px 2px 0 rgba(0, 0, 0, 0.05)', DEFAULT: '0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)', md: '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)', lg: '0px 0.8px 2px rgba(0, 0, 0, 0.032), 0px 2.7px 6.7px rgba(0, 0, 0, 0.048), 0px 12px 30px rgba(0, 0, 0, 0.08)', 'lg-dark': '0 0 0 1px rgba(255,255,255,.15), 0px 0.8px 2px rgba(0, 0, 0, 0.032), 0px 2.7px 6.7px rgba(0, 0, 0, 0.048), 0px 12px 30px rgba(0, 0, 0, 0.08)', xl: '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)', '2xl': '0 25px 50px -12px rgba(0, 0, 0, 0.25)', '3xl': '0 35px 60px -15px rgba(0, 0, 0, 0.3)', nav: '0 16px 32px -16px rgba(0, 0, 0, 0.1), 0 0 0 1px rgba(0,0,0,.10)', 'nav-dark': '0 16px 32px -16px rgba(0, 0, 0, 0.1), 0 0 0 1px rgba(255,255,255,.05)', inner: 'inset 0 1px 4px 0 rgba(0, 0, 0, 0.05)', 'inner-border': 'inset 0 0 0 1px rgba(0, 0, 0, 0.08)', 'inner-border-dark': 'inset 0 0 0 1px rgba(255, 255, 255, 0.08)', 'outer-border': '0 0 0 1px rgba(0, 0, 0, 0.1)', 'outer-border-dark': '0 0 0 1px rgba(255, 255, 255, 0.1)', 'secondary-button-stroke': 'inset 0 0 0 1px #D9DBE3', 'secondary-button-stroke-dark': 'inset 0 0 0 1px #404756', none: 'none', }, extend: { backgroundImage: { 'gradient-left-dark': 'conic-gradient(from 90deg at -10% 100%, #2B303B 0deg, #2B303B 90deg, #16181D 360deg)', 'gradient-right-dark': 'conic-gradient(from -90deg at 110% 100%, #2B303B 0deg, #16181D 90deg, #16181D 360deg)', 'gradient-left': 'conic-gradient(from 90deg at -10% 100%, #BCC1CD 0deg, #BCC1CD 90deg, #FFFFFF 360deg)', 'gradient-right': 'conic-gradient(from -90deg at 110% 100%, #FFFFFF 0deg, #EBECF0 90deg, #EBECF0 360deg)', 'meta-gradient': "url('/images/meta-gradient.png')", 'meta-gradient-dark': "url('/images/meta-gradient-dark.png')", }, maxWidth: { ...defaultTheme.maxWidth, xs: '21rem', }, minWidth:{ ...defaultTheme.minWidth, 80: '20rem', }, outline: { blue: ['1px auto ' + colors.link, '3px'], }, opacity: { 8: '0.08', }, fontFamily: { display: [ 'Optimistic Display', '-apple-system', ...defaultTheme.fontFamily.sans, ], text: [ 'Optimistic Text', '-apple-system', ...defaultTheme.fontFamily.sans, ], mono: ['"Source Code Pro"', ...defaultTheme.fontFamily.mono], }, lineHeight: { base: '30px', large: '38px', xl: '1.15', }, fontSize: { '6xl': '52px', '5xl': '40px', '4xl': '32px', '3xl': '28px', '2xl': '24px', xl: '20px', lg: '17px', base: '15px', sm: '13px', xs: '11px', code: 'calc(1em - 20%)', }, animation: { marquee: 'marquee 40s linear infinite', marquee2: 'marquee2 40s linear infinite', 'large-marquee': 'large-marquee 80s linear infinite', 'large-marquee2': 'large-marquee2 80s linear infinite', 'fade-up': 'fade-up 1s 100ms both', }, keyframes: { shimmer: { '100%': { transform: 'translateX(100%)', }, }, rotate: { from: {transform: 'rotate(0deg)'}, to: {transform: 'rotate(180deg)'}, }, scale: { from: {transform: 'scale(0.8)'}, '90%': {transform: 'scale(1.05)'}, to: {transform: 'scale(1)'}, }, circle: { from: {transform: 'scale(0)', strokeWidth: '16px'}, '50%': {transform: 'scale(0.5)', strokeWidth: '16px'}, to: {transform: 'scale(1)', strokeWidth: '0px'}, }, marquee: { '0%': {transform: 'translateX(0%)'}, '100%': {transform: 'translateX(-400%)'}, }, marquee2: { '0%': {transform: 'translateX(400%)'}, '100%': {transform: 'translateX(0%)'}, }, 'large-marquee': { '0%': {transform: 'translateX(0%)'}, '100%': {transform: 'translateX(-200%)'}, }, 'large-marquee2': { '0%': {transform: 'translateX(200%)'}, '100%': {transform: 'translateX(0%)'}, }, 'fade-up': { '0%': { opacity: '0', transform: 'translateY(2rem)', }, '100%': { opacity: '1', transform: 'translateY(0)', }, }, }, colors, gridTemplateColumns: { 'only-content': 'auto', 'sidebar-content': '20rem auto', 'sidebar-content-toc': '20rem auto 20rem', }, }, }, plugins: [], };
31.52381
151
0.483983
PenetrationTestingScripts
import {printStore} from 'react-devtools-shared/src/devtools/utils'; // test() is part of Jest's serializer API export function test(maybeStore) { // It's important to lazy-require the Store rather than imported at the head of the module. // Because we reset modules between tests, different Store implementations will be used for each test. // Unfortunately Jest does not reset its own serializer modules. return ( maybeStore instanceof require('react-devtools-shared/src/devtools/store').default ); } // print() is part of Jest's serializer API export function print(store, serialize, indent) { return printStore(store); } // Used for Jest snapshot testing. // May also be useful for visually debugging the tree, so it lives on the Store. export {printStore};
34.727273
104
0.749045
Python-Penetration-Testing-Cookbook
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = useTheme; exports.ThemeContext = void 0; var _react = require("react"); /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ const ThemeContext = /*#__PURE__*/(0, _react.createContext)('bright'); exports.ThemeContext = ThemeContext; function useTheme() { const theme = (0, _react.useContext)(ThemeContext); (0, _react.useDebugValue)(theme); return theme; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInVzZVRoZW1lLmpzIl0sIm5hbWVzIjpbIlRoZW1lQ29udGV4dCIsInVzZVRoZW1lIiwidGhlbWUiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7O0FBU0E7O0FBVEE7Ozs7Ozs7O0FBV08sTUFBTUEsWUFBWSxnQkFBRywwQkFBYyxRQUFkLENBQXJCOzs7QUFFUSxTQUFTQyxRQUFULEdBQW9CO0FBQ2pDLFFBQU1DLEtBQUssR0FBRyx1QkFBV0YsWUFBWCxDQUFkO0FBQ0EsNEJBQWNFLEtBQWQ7QUFDQSxTQUFPQSxLQUFQO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IHtjcmVhdGVDb250ZXh0LCB1c2VDb250ZXh0LCB1c2VEZWJ1Z1ZhbHVlfSBmcm9tICdyZWFjdCc7XG5cbmV4cG9ydCBjb25zdCBUaGVtZUNvbnRleHQgPSBjcmVhdGVDb250ZXh0KCdicmlnaHQnKTtcblxuZXhwb3J0IGRlZmF1bHQgZnVuY3Rpb24gdXNlVGhlbWUoKSB7XG4gIGNvbnN0IHRoZW1lID0gdXNlQ29udGV4dChUaGVtZUNvbnRleHQpO1xuICB1c2VEZWJ1Z1ZhbHVlKHRoZW1lKTtcbiAgcmV0dXJuIHRoZW1lO1xufVxuIl0sInhfcmVhY3Rfc291cmNlcyI6W1t7Im5hbWVzIjpbIjxuby1ob29rPiIsInRoZW1lIl0sIm1hcHBpbmdzIjoiQ0FBRDtlZ0JDQSxBd0JEQSJ9XV19fV19
68.111111
1,256
0.892761
owtf
import React from 'react'; import {useContext} from 'react'; import {connect} from 'react-redux'; import ThemeContext from './shared/ThemeContext'; import lazyLegacyRoot from './lazyLegacyRoot'; // Lazy-load a component from the bundle using legacy React. const Greeting = lazyLegacyRoot(() => import('../legacy/Greeting')); function AboutPage({counter, dispatch}) { const theme = useContext(ThemeContext); return ( <> <h2>src/modern/AboutPage.js</h2> <h3 style={{color: theme}}> This component is rendered by the outer React ({React.version}). </h3> <Greeting /> <br /> <p> Counter: {counter}{' '} <button onClick={() => dispatch({type: 'increment'})}>+</button> </p> </> ); } function mapStateToProps(state) { return {counter: state}; } export default connect(mapStateToProps)(AboutPage);
24.852941
72
0.64123
PenetrationTestingScripts
const chromeManifest = require('../react-devtools-extensions/chrome/manifest.json'); const firefoxManifest = require('../react-devtools-extensions/firefox/manifest.json'); const minChromeVersion = parseInt(chromeManifest.minimum_chrome_version, 10); const minFirefoxVersion = parseInt( firefoxManifest.applications.gecko.strict_min_version, 10, ); validateVersion(minChromeVersion); validateVersion(minFirefoxVersion); function validateVersion(version) { if (version > 0 && version < 200) { return; } throw new Error('Suspicious browser version in manifest: ' + version); } module.exports = api => { const isTest = api.env('test'); const targets = {}; if (isTest) { targets.node = 'current'; } else { targets.chrome = minChromeVersion.toString(); targets.firefox = minFirefoxVersion.toString(); let additionalTargets = process.env.BABEL_CONFIG_ADDITIONAL_TARGETS; if (additionalTargets) { additionalTargets = JSON.parse(additionalTargets); for (const target in additionalTargets) { targets[target] = additionalTargets[target]; } } } const plugins = [ ['@babel/plugin-transform-flow-strip-types'], ['@babel/plugin-proposal-class-properties', {loose: false}], ]; if (process.env.NODE_ENV !== 'production') { plugins.push(['@babel/plugin-transform-react-jsx-source']); } return { plugins, presets: [ ['@babel/preset-env', {targets}], '@babel/preset-react', '@babel/preset-flow', ], }; };
28.192308
86
0.681608
Python-Penetration-Testing-for-Developers
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @jest-environment node */ 'use strict'; describe('ReactIncrementalErrorReplay-test', () => { const React = require('react'); const ReactTestRenderer = require('react-test-renderer'); it('copies all keys when stashing potentially failing work', () => { // Note: this test is fragile and relies on internals. // We almost always try to avoid such tests, but here the cost of // the list getting out of sync (and causing subtle bugs in rare cases) // is higher than the cost of maintaining the test. // This is the method we're going to test. // If this is no longer used, you can delete this test file.; const {assignFiberPropertiesInDEV} = require('../ReactFiber'); // Get a real fiber. const realFiber = ReactTestRenderer.create(<div />).root._currentFiber(); const stash = assignFiberPropertiesInDEV(null, realFiber); // Verify we get all the same fields. expect(realFiber).toEqual(stash); // Mutate the original. for (const key in realFiber) { realFiber[key] = key + '_' + Math.random(); } expect(realFiber).not.toEqual(stash); // Verify we can still "revert" to the stashed properties. expect(assignFiberPropertiesInDEV(realFiber, stash)).toBe(realFiber); expect(realFiber).toEqual(stash); }); });
32.954545
77
0.683858
null
'use strict'; const baseConfig = require('./config.base'); module.exports = Object.assign({}, baseConfig, { modulePathIgnorePatterns: [ ...baseConfig.modulePathIgnorePatterns, 'packages/react-devtools-extensions', 'packages/react-devtools-shared', 'ReactIncrementalPerf', 'ReactIncrementalUpdatesMinimalism', 'ReactIncrementalTriangle', 'ReactIncrementalReflection', 'forwardRef', ], setupFiles: [ ...baseConfig.setupFiles, require.resolve('./setupTests.persistent.js'), require.resolve('./setupHostConfigs.js'), ], });
25.136364
50
0.702091
PenetrationTestingScripts
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import { ElementTypeClass, ElementTypeFunction, ElementTypeRoot, ElementTypeHostComponent, ElementTypeOtherOrUnknown, } from 'react-devtools-shared/src/frontend/types'; import {getUID, utfEncodeString, printOperationsArray} from '../../utils'; import { cleanForBridge, copyWithDelete, copyWithRename, copyWithSet, serializeToString, } from '../utils'; import { deletePathInObject, getDisplayName, getInObject, renamePathInObject, setInObject, } from 'react-devtools-shared/src/utils'; import { __DEBUG__, TREE_OPERATION_ADD, TREE_OPERATION_REMOVE, TREE_OPERATION_REORDER_CHILDREN, } from '../../constants'; import {decorateMany, forceUpdate, restoreMany} from './utils'; import type { DevToolsHook, GetFiberIDForNative, InspectedElementPayload, InstanceAndStyle, NativeType, PathFrame, PathMatch, RendererInterface, } from '../types'; import type { ComponentFilter, ElementType, } from 'react-devtools-shared/src/frontend/types'; import type {InspectedElement, SerializedElement} from '../types'; export type InternalInstance = Object; type LegacyRenderer = Object; function getData(internalInstance: InternalInstance) { let displayName = null; let key = null; // != used deliberately here to catch undefined and null if (internalInstance._currentElement != null) { if (internalInstance._currentElement.key) { key = String(internalInstance._currentElement.key); } const elementType = internalInstance._currentElement.type; if (typeof elementType === 'string') { displayName = elementType; } else if (typeof elementType === 'function') { displayName = getDisplayName(elementType); } } return { displayName, key, }; } function getElementType(internalInstance: InternalInstance): ElementType { // != used deliberately here to catch undefined and null if (internalInstance._currentElement != null) { const elementType = internalInstance._currentElement.type; if (typeof elementType === 'function') { const publicInstance = internalInstance.getPublicInstance(); if (publicInstance !== null) { return ElementTypeClass; } else { return ElementTypeFunction; } } else if (typeof elementType === 'string') { return ElementTypeHostComponent; } } return ElementTypeOtherOrUnknown; } function getChildren(internalInstance: Object): Array<any> { const children = []; // If the parent is a native node without rendered children, but with // multiple string children, then the `element` that gets passed in here is // a plain value -- a string or number. if (typeof internalInstance !== 'object') { // No children } else if ( internalInstance._currentElement === null || internalInstance._currentElement === false ) { // No children } else if (internalInstance._renderedComponent) { const child = internalInstance._renderedComponent; if (getElementType(child) !== ElementTypeOtherOrUnknown) { children.push(child); } } else if (internalInstance._renderedChildren) { const renderedChildren = internalInstance._renderedChildren; for (const name in renderedChildren) { const child = renderedChildren[name]; if (getElementType(child) !== ElementTypeOtherOrUnknown) { children.push(child); } } } // Note: we skip the case where children are just strings or numbers // because the new DevTools skips over host text nodes anyway. return children; } export function attach( hook: DevToolsHook, rendererID: number, renderer: LegacyRenderer, global: Object, ): RendererInterface { const idToInternalInstanceMap: Map<number, InternalInstance> = new Map(); const internalInstanceToIDMap: WeakMap<InternalInstance, number> = new WeakMap(); const internalInstanceToRootIDMap: WeakMap<InternalInstance, number> = new WeakMap(); let getInternalIDForNative: GetFiberIDForNative = ((null: any): GetFiberIDForNative); let findNativeNodeForInternalID: (id: number) => ?NativeType; let getFiberForNative = (node: NativeType) => { // Not implemented. return null; }; if (renderer.ComponentTree) { getInternalIDForNative = (node, findNearestUnfilteredAncestor) => { const internalInstance = renderer.ComponentTree.getClosestInstanceFromNode(node); return internalInstanceToIDMap.get(internalInstance) || null; }; findNativeNodeForInternalID = (id: number) => { const internalInstance = idToInternalInstanceMap.get(id); return renderer.ComponentTree.getNodeFromInstance(internalInstance); }; getFiberForNative = (node: NativeType) => { return renderer.ComponentTree.getClosestInstanceFromNode(node); }; } else if (renderer.Mount.getID && renderer.Mount.getNode) { getInternalIDForNative = (node, findNearestUnfilteredAncestor) => { // Not implemented. return null; }; findNativeNodeForInternalID = (id: number) => { // Not implemented. return null; }; } function getDisplayNameForFiberID(id: number): string | null { const internalInstance = idToInternalInstanceMap.get(id); return internalInstance ? getData(internalInstance).displayName : null; } function getID(internalInstance: InternalInstance): number { if (typeof internalInstance !== 'object' || internalInstance === null) { throw new Error('Invalid internal instance: ' + internalInstance); } if (!internalInstanceToIDMap.has(internalInstance)) { const id = getUID(); internalInstanceToIDMap.set(internalInstance, id); idToInternalInstanceMap.set(id, internalInstance); } return ((internalInstanceToIDMap.get(internalInstance): any): number); } function areEqualArrays(a: Array<any>, b: Array<any>) { if (a.length !== b.length) { return false; } for (let i = 0; i < a.length; i++) { if (a[i] !== b[i]) { return false; } } return true; } // This is shared mutable state that lets us keep track of where we are. let parentIDStack = []; let oldReconcilerMethods = null; if (renderer.Reconciler) { // React 15 oldReconcilerMethods = decorateMany(renderer.Reconciler, { mountComponent(fn, args) { const internalInstance = args[0]; const hostContainerInfo = args[3]; if (getElementType(internalInstance) === ElementTypeOtherOrUnknown) { // $FlowFixMe[object-this-reference] found when upgrading Flow return fn.apply(this, args); } if (hostContainerInfo._topLevelWrapper === undefined) { // SSR // $FlowFixMe[object-this-reference] found when upgrading Flow return fn.apply(this, args); } const id = getID(internalInstance); // Push the operation. const parentID = parentIDStack.length > 0 ? parentIDStack[parentIDStack.length - 1] : 0; recordMount(internalInstance, id, parentID); parentIDStack.push(id); // Remember the root. internalInstanceToRootIDMap.set( internalInstance, getID(hostContainerInfo._topLevelWrapper), ); try { // $FlowFixMe[object-this-reference] found when upgrading Flow const result = fn.apply(this, args); parentIDStack.pop(); return result; } catch (err) { parentIDStack = []; throw err; } finally { if (parentIDStack.length === 0) { const rootID = internalInstanceToRootIDMap.get(internalInstance); if (rootID === undefined) { throw new Error('Expected to find root ID.'); } flushPendingEvents(rootID); } } }, performUpdateIfNecessary(fn, args) { const internalInstance = args[0]; if (getElementType(internalInstance) === ElementTypeOtherOrUnknown) { // $FlowFixMe[object-this-reference] found when upgrading Flow return fn.apply(this, args); } const id = getID(internalInstance); parentIDStack.push(id); const prevChildren = getChildren(internalInstance); try { // $FlowFixMe[object-this-reference] found when upgrading Flow const result = fn.apply(this, args); const nextChildren = getChildren(internalInstance); if (!areEqualArrays(prevChildren, nextChildren)) { // Push the operation recordReorder(internalInstance, id, nextChildren); } parentIDStack.pop(); return result; } catch (err) { parentIDStack = []; throw err; } finally { if (parentIDStack.length === 0) { const rootID = internalInstanceToRootIDMap.get(internalInstance); if (rootID === undefined) { throw new Error('Expected to find root ID.'); } flushPendingEvents(rootID); } } }, receiveComponent(fn, args) { const internalInstance = args[0]; if (getElementType(internalInstance) === ElementTypeOtherOrUnknown) { // $FlowFixMe[object-this-reference] found when upgrading Flow return fn.apply(this, args); } const id = getID(internalInstance); parentIDStack.push(id); const prevChildren = getChildren(internalInstance); try { // $FlowFixMe[object-this-reference] found when upgrading Flow const result = fn.apply(this, args); const nextChildren = getChildren(internalInstance); if (!areEqualArrays(prevChildren, nextChildren)) { // Push the operation recordReorder(internalInstance, id, nextChildren); } parentIDStack.pop(); return result; } catch (err) { parentIDStack = []; throw err; } finally { if (parentIDStack.length === 0) { const rootID = internalInstanceToRootIDMap.get(internalInstance); if (rootID === undefined) { throw new Error('Expected to find root ID.'); } flushPendingEvents(rootID); } } }, unmountComponent(fn, args) { const internalInstance = args[0]; if (getElementType(internalInstance) === ElementTypeOtherOrUnknown) { // $FlowFixMe[object-this-reference] found when upgrading Flow return fn.apply(this, args); } const id = getID(internalInstance); parentIDStack.push(id); try { // $FlowFixMe[object-this-reference] found when upgrading Flow const result = fn.apply(this, args); parentIDStack.pop(); // Push the operation. recordUnmount(internalInstance, id); return result; } catch (err) { parentIDStack = []; throw err; } finally { if (parentIDStack.length === 0) { const rootID = internalInstanceToRootIDMap.get(internalInstance); if (rootID === undefined) { throw new Error('Expected to find root ID.'); } flushPendingEvents(rootID); } } }, }); } function cleanup() { if (oldReconcilerMethods !== null) { if (renderer.Component) { restoreMany(renderer.Component.Mixin, oldReconcilerMethods); } else { restoreMany(renderer.Reconciler, oldReconcilerMethods); } } oldReconcilerMethods = null; } function recordMount( internalInstance: InternalInstance, id: number, parentID: number, ) { const isRoot = parentID === 0; if (__DEBUG__) { console.log( '%crecordMount()', 'color: green; font-weight: bold;', id, getData(internalInstance).displayName, ); } if (isRoot) { // TODO Is this right? For all versions? const hasOwnerMetadata = internalInstance._currentElement != null && internalInstance._currentElement._owner != null; pushOperation(TREE_OPERATION_ADD); pushOperation(id); pushOperation(ElementTypeRoot); pushOperation(0); // StrictMode compliant? pushOperation(0); // Profiling flag pushOperation(0); // StrictMode supported? pushOperation(hasOwnerMetadata ? 1 : 0); } else { const type = getElementType(internalInstance); const {displayName, key} = getData(internalInstance); const ownerID = internalInstance._currentElement != null && internalInstance._currentElement._owner != null ? getID(internalInstance._currentElement._owner) : 0; const displayNameStringID = getStringID(displayName); const keyStringID = getStringID(key); pushOperation(TREE_OPERATION_ADD); pushOperation(id); pushOperation(type); pushOperation(parentID); pushOperation(ownerID); pushOperation(displayNameStringID); pushOperation(keyStringID); } } function recordReorder( internalInstance: InternalInstance, id: number, nextChildren: Array<InternalInstance>, ) { pushOperation(TREE_OPERATION_REORDER_CHILDREN); pushOperation(id); const nextChildIDs = nextChildren.map(getID); pushOperation(nextChildIDs.length); for (let i = 0; i < nextChildIDs.length; i++) { pushOperation(nextChildIDs[i]); } } function recordUnmount(internalInstance: InternalInstance, id: number) { pendingUnmountedIDs.push(id); idToInternalInstanceMap.delete(id); } function crawlAndRecordInitialMounts( id: number, parentID: number, rootID: number, ) { if (__DEBUG__) { console.group('crawlAndRecordInitialMounts() id:', id); } const internalInstance = idToInternalInstanceMap.get(id); if (internalInstance != null) { internalInstanceToRootIDMap.set(internalInstance, rootID); recordMount(internalInstance, id, parentID); getChildren(internalInstance).forEach(child => crawlAndRecordInitialMounts(getID(child), id, rootID), ); } if (__DEBUG__) { console.groupEnd(); } } function flushInitialOperations() { // Crawl roots though and register any nodes that mounted before we were injected. const roots = renderer.Mount._instancesByReactRootID || renderer.Mount._instancesByContainerID; for (const key in roots) { const internalInstance = roots[key]; const id = getID(internalInstance); crawlAndRecordInitialMounts(id, 0, id); flushPendingEvents(id); } } const pendingOperations: Array<number> = []; const pendingStringTable: Map<string, number> = new Map(); let pendingUnmountedIDs: Array<number> = []; let pendingStringTableLength: number = 0; let pendingUnmountedRootID: number | null = null; function flushPendingEvents(rootID: number) { if ( pendingOperations.length === 0 && pendingUnmountedIDs.length === 0 && pendingUnmountedRootID === null ) { return; } const numUnmountIDs = pendingUnmountedIDs.length + (pendingUnmountedRootID === null ? 0 : 1); const operations = new Array<number>( // Identify which renderer this update is coming from. 2 + // [rendererID, rootFiberID] // How big is the string table? 1 + // [stringTableLength] // Then goes the actual string table. pendingStringTableLength + // All unmounts are batched in a single message. // [TREE_OPERATION_REMOVE, removedIDLength, ...ids] (numUnmountIDs > 0 ? 2 + numUnmountIDs : 0) + // Mount operations pendingOperations.length, ); // Identify which renderer this update is coming from. // This enables roots to be mapped to renderers, // Which in turn enables fiber properations, states, and hooks to be inspected. let i = 0; operations[i++] = rendererID; operations[i++] = rootID; // Now fill in the string table. // [stringTableLength, str1Length, ...str1, str2Length, ...str2, ...] operations[i++] = pendingStringTableLength; pendingStringTable.forEach((value, key) => { operations[i++] = key.length; const encodedKey = utfEncodeString(key); for (let j = 0; j < encodedKey.length; j++) { operations[i + j] = encodedKey[j]; } i += key.length; }); if (numUnmountIDs > 0) { // All unmounts except roots are batched in a single message. operations[i++] = TREE_OPERATION_REMOVE; // The first number is how many unmounted IDs we're gonna send. operations[i++] = numUnmountIDs; // Fill in the unmounts for (let j = 0; j < pendingUnmountedIDs.length; j++) { operations[i++] = pendingUnmountedIDs[j]; } // The root ID should always be unmounted last. if (pendingUnmountedRootID !== null) { operations[i] = pendingUnmountedRootID; i++; } } // Fill in the rest of the operations. for (let j = 0; j < pendingOperations.length; j++) { operations[i + j] = pendingOperations[j]; } i += pendingOperations.length; if (__DEBUG__) { printOperationsArray(operations); } // If we've already connected to the frontend, just pass the operations through. hook.emit('operations', operations); pendingOperations.length = 0; pendingUnmountedIDs = []; pendingUnmountedRootID = null; pendingStringTable.clear(); pendingStringTableLength = 0; } function pushOperation(op: number): void { if (__DEV__) { if (!Number.isInteger(op)) { console.error( 'pushOperation() was called but the value is not an integer.', op, ); } } pendingOperations.push(op); } function getStringID(str: string | null): number { if (str === null) { return 0; } const existingID = pendingStringTable.get(str); if (existingID !== undefined) { return existingID; } const stringID = pendingStringTable.size + 1; pendingStringTable.set(str, stringID); // The string table total length needs to account // both for the string length, and for the array item // that contains the length itself. Hence + 1. pendingStringTableLength += str.length + 1; return stringID; } let currentlyInspectedElementID: number | null = null; let currentlyInspectedPaths: Object = {}; // Track the intersection of currently inspected paths, // so that we can send their data along if the element is re-rendered. function mergeInspectedPaths(path: Array<string | number>) { let current = currentlyInspectedPaths; path.forEach(key => { if (!current[key]) { current[key] = {}; } current = current[key]; }); } function createIsPathAllowed(key: string) { // This function helps prevent previously-inspected paths from being dehydrated in updates. // This is important to avoid a bad user experience where expanded toggles collapse on update. return function isPathAllowed(path: Array<string | number>): boolean { let current = currentlyInspectedPaths[key]; if (!current) { return false; } for (let i = 0; i < path.length; i++) { current = current[path[i]]; if (!current) { return false; } } return true; }; } // Fast path props lookup for React Native style editor. function getInstanceAndStyle(id: number): InstanceAndStyle { let instance = null; let style = null; const internalInstance = idToInternalInstanceMap.get(id); if (internalInstance != null) { instance = internalInstance._instance || null; const element = internalInstance._currentElement; if (element != null && element.props != null) { style = element.props.style || null; } } return { instance, style, }; } function updateSelectedElement(id: number): void { const internalInstance = idToInternalInstanceMap.get(id); if (internalInstance == null) { console.warn(`Could not find instance with id "${id}"`); return; } switch (getElementType(internalInstance)) { case ElementTypeClass: global.$r = internalInstance._instance; break; case ElementTypeFunction: const element = internalInstance._currentElement; if (element == null) { console.warn(`Could not find element with id "${id}"`); return; } global.$r = { props: element.props, type: element.type, }; break; default: global.$r = null; break; } } function storeAsGlobal( id: number, path: Array<string | number>, count: number, ): void { const inspectedElement = inspectElementRaw(id); if (inspectedElement !== null) { const value = getInObject(inspectedElement, path); const key = `$reactTemp${count}`; window[key] = value; console.log(key); console.log(value); } } function getSerializedElementValueByPath( id: number, path: Array<string | number>, ): ?string { const inspectedElement = inspectElementRaw(id); if (inspectedElement !== null) { const valueToCopy = getInObject(inspectedElement, path); return serializeToString(valueToCopy); } } function inspectElement( requestID: number, id: number, path: Array<string | number> | null, forceFullData: boolean, ): InspectedElementPayload { if (forceFullData || currentlyInspectedElementID !== id) { currentlyInspectedElementID = id; currentlyInspectedPaths = {}; } const inspectedElement = inspectElementRaw(id); if (inspectedElement === null) { return { id, responseID: requestID, type: 'not-found', }; } if (path !== null) { mergeInspectedPaths(path); } // Any time an inspected element has an update, // we should update the selected $r value as wel. // Do this before dehydration (cleanForBridge). updateSelectedElement(id); inspectedElement.context = cleanForBridge( inspectedElement.context, createIsPathAllowed('context'), ); inspectedElement.props = cleanForBridge( inspectedElement.props, createIsPathAllowed('props'), ); inspectedElement.state = cleanForBridge( inspectedElement.state, createIsPathAllowed('state'), ); return { id, responseID: requestID, type: 'full-data', value: inspectedElement, }; } function inspectElementRaw(id: number): InspectedElement | null { const internalInstance = idToInternalInstanceMap.get(id); if (internalInstance == null) { return null; } const {displayName, key} = getData(internalInstance); const type = getElementType(internalInstance); let context = null; let owners = null; let props = null; let state = null; let source = null; const element = internalInstance._currentElement; if (element !== null) { props = element.props; source = element._source != null ? element._source : null; let owner = element._owner; if (owner) { owners = ([]: Array<SerializedElement>); while (owner != null) { owners.push({ displayName: getData(owner).displayName || 'Unknown', id: getID(owner), key: element.key, type: getElementType(owner), }); if (owner._currentElement) { owner = owner._currentElement._owner; } } } } const publicInstance = internalInstance._instance; if (publicInstance != null) { context = publicInstance.context || null; state = publicInstance.state || null; } // Not implemented const errors: Array<[string, number]> = []; const warnings: Array<[string, number]> = []; return { id, // Does the current renderer support editable hooks and function props? canEditHooks: false, canEditFunctionProps: false, // Does the current renderer support advanced editing interface? canEditHooksAndDeletePaths: false, canEditHooksAndRenamePaths: false, canEditFunctionPropsDeletePaths: false, canEditFunctionPropsRenamePaths: false, // Toggle error boundary did not exist in legacy versions canToggleError: false, isErrored: false, targetErrorBoundaryID: null, // Suspense did not exist in legacy versions canToggleSuspense: false, // Can view component source location. canViewSource: type === ElementTypeClass || type === ElementTypeFunction, // Only legacy context exists in legacy versions. hasLegacyContext: true, displayName: displayName, type: type, key: key != null ? key : null, // Inspectable properties. context, hooks: null, props, state, errors, warnings, // List of owners owners, // Location of component in source code. source, rootType: null, rendererPackageName: null, rendererVersion: null, plugins: { stylex: null, }, }; } function logElementToConsole(id: number): void { const result = inspectElementRaw(id); if (result === null) { console.warn(`Could not find element with id "${id}"`); return; } const supportsGroup = typeof console.groupCollapsed === 'function'; if (supportsGroup) { console.groupCollapsed( `[Click to expand] %c<${result.displayName || 'Component'} />`, // --dom-tag-name-color is the CSS variable Chrome styles HTML elements with in the console. 'color: var(--dom-tag-name-color); font-weight: normal;', ); } if (result.props !== null) { console.log('Props:', result.props); } if (result.state !== null) { console.log('State:', result.state); } if (result.context !== null) { console.log('Context:', result.context); } const nativeNode = findNativeNodeForInternalID(id); if (nativeNode !== null) { console.log('Node:', nativeNode); } if (window.chrome || /firefox/i.test(navigator.userAgent)) { console.log( 'Right-click any value to save it as a global variable for further inspection.', ); } if (supportsGroup) { console.groupEnd(); } } function prepareViewAttributeSource( id: number, path: Array<string | number>, ): void { const inspectedElement = inspectElementRaw(id); if (inspectedElement !== null) { window.$attribute = getInObject(inspectedElement, path); } } function prepareViewElementSource(id: number): void { const internalInstance = idToInternalInstanceMap.get(id); if (internalInstance == null) { console.warn(`Could not find instance with id "${id}"`); return; } const element = internalInstance._currentElement; if (element == null) { console.warn(`Could not find element with id "${id}"`); return; } global.$type = element.type; } function deletePath( type: 'context' | 'hooks' | 'props' | 'state', id: number, hookID: ?number, path: Array<string | number>, ): void { const internalInstance = idToInternalInstanceMap.get(id); if (internalInstance != null) { const publicInstance = internalInstance._instance; if (publicInstance != null) { switch (type) { case 'context': deletePathInObject(publicInstance.context, path); forceUpdate(publicInstance); break; case 'hooks': throw new Error('Hooks not supported by this renderer'); case 'props': const element = internalInstance._currentElement; internalInstance._currentElement = { ...element, props: copyWithDelete(element.props, path), }; forceUpdate(publicInstance); break; case 'state': deletePathInObject(publicInstance.state, path); forceUpdate(publicInstance); break; } } } } function renamePath( type: 'context' | 'hooks' | 'props' | 'state', id: number, hookID: ?number, oldPath: Array<string | number>, newPath: Array<string | number>, ): void { const internalInstance = idToInternalInstanceMap.get(id); if (internalInstance != null) { const publicInstance = internalInstance._instance; if (publicInstance != null) { switch (type) { case 'context': renamePathInObject(publicInstance.context, oldPath, newPath); forceUpdate(publicInstance); break; case 'hooks': throw new Error('Hooks not supported by this renderer'); case 'props': const element = internalInstance._currentElement; internalInstance._currentElement = { ...element, props: copyWithRename(element.props, oldPath, newPath), }; forceUpdate(publicInstance); break; case 'state': renamePathInObject(publicInstance.state, oldPath, newPath); forceUpdate(publicInstance); break; } } } } function overrideValueAtPath( type: 'context' | 'hooks' | 'props' | 'state', id: number, hookID: ?number, path: Array<string | number>, value: any, ): void { const internalInstance = idToInternalInstanceMap.get(id); if (internalInstance != null) { const publicInstance = internalInstance._instance; if (publicInstance != null) { switch (type) { case 'context': setInObject(publicInstance.context, path, value); forceUpdate(publicInstance); break; case 'hooks': throw new Error('Hooks not supported by this renderer'); case 'props': const element = internalInstance._currentElement; internalInstance._currentElement = { ...element, props: copyWithSet(element.props, path, value), }; forceUpdate(publicInstance); break; case 'state': setInObject(publicInstance.state, path, value); forceUpdate(publicInstance); break; } } } } // v16+ only features const getProfilingData = () => { throw new Error('getProfilingData not supported by this renderer'); }; const handleCommitFiberRoot = () => { throw new Error('handleCommitFiberRoot not supported by this renderer'); }; const handleCommitFiberUnmount = () => { throw new Error('handleCommitFiberUnmount not supported by this renderer'); }; const handlePostCommitFiberRoot = () => { throw new Error('handlePostCommitFiberRoot not supported by this renderer'); }; const overrideError = () => { throw new Error('overrideError not supported by this renderer'); }; const overrideSuspense = () => { throw new Error('overrideSuspense not supported by this renderer'); }; const startProfiling = () => { // Do not throw, since this would break a multi-root scenario where v15 and v16 were both present. }; const stopProfiling = () => { // Do not throw, since this would break a multi-root scenario where v15 and v16 were both present. }; function getBestMatchForTrackedPath(): PathMatch | null { // Not implemented. return null; } function getPathForElement(id: number): Array<PathFrame> | null { // Not implemented. return null; } function updateComponentFilters(componentFilters: Array<ComponentFilter>) { // Not implemented. } function setTraceUpdatesEnabled(enabled: boolean) { // Not implemented. } function setTrackedPath(path: Array<PathFrame> | null) { // Not implemented. } function getOwnersList(id: number): Array<SerializedElement> | null { // Not implemented. return null; } function clearErrorsAndWarnings() { // Not implemented } function clearErrorsForFiberID(id: number) { // Not implemented } function clearWarningsForFiberID(id: number) { // Not implemented } function patchConsoleForStrictMode() {} function unpatchConsoleForStrictMode() {} function hasFiberWithId(id: number): boolean { return idToInternalInstanceMap.has(id); } return { clearErrorsAndWarnings, clearErrorsForFiberID, clearWarningsForFiberID, cleanup, getSerializedElementValueByPath, deletePath, flushInitialOperations, getBestMatchForTrackedPath, getDisplayNameForFiberID, getFiberForNative, getFiberIDForNative: getInternalIDForNative, getInstanceAndStyle, findNativeNodesForFiberID: (id: number) => { const nativeNode = findNativeNodeForInternalID(id); return nativeNode == null ? null : [nativeNode]; }, getOwnersList, getPathForElement, getProfilingData, handleCommitFiberRoot, handleCommitFiberUnmount, handlePostCommitFiberRoot, hasFiberWithId, inspectElement, logElementToConsole, overrideError, overrideSuspense, overrideValueAtPath, renamePath, patchConsoleForStrictMode, prepareViewAttributeSource, prepareViewElementSource, renderer, setTraceUpdatesEnabled, setTrackedPath, startProfiling, stopProfiling, storeAsGlobal, unpatchConsoleForStrictMode, updateComponentFilters, }; }
28.653345
102
0.631907
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; describe('ReactDOMIframe', () => { let React; let ReactTestUtils; beforeEach(() => { React = require('react'); ReactTestUtils = require('react-dom/test-utils'); }); it('should trigger load events', () => { const onLoadSpy = jest.fn(); let iframe = React.createElement('iframe', {onLoad: onLoadSpy}); iframe = ReactTestUtils.renderIntoDocument(iframe); const loadEvent = document.createEvent('Event'); loadEvent.initEvent('load', false, false); iframe.dispatchEvent(loadEvent); expect(onLoadSpy).toHaveBeenCalled(); }); });
22.794118
68
0.665842
owtf
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-jsx-runtime.production.min.js'); } else { module.exports = require('./cjs/react-jsx-runtime.development.js'); }
25.875
72
0.682243
Python-Penetration-Testing-for-Developers
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; let React; let ReactNoop; let Scheduler; let act; let assertLog; let waitFor; let waitForAll; let waitForPaint; describe('StrictEffectsMode defaults', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); act = require('internal-test-utils').act; const InternalTestUtils = require('internal-test-utils'); waitFor = InternalTestUtils.waitFor; waitForAll = InternalTestUtils.waitForAll; waitForPaint = InternalTestUtils.waitForPaint; assertLog = InternalTestUtils.assertLog; const ReactFeatureFlags = require('shared/ReactFeatureFlags'); ReactFeatureFlags.createRootStrictEffectsByDefault = __DEV__; }); it('should not double invoke effects in legacy mode', async () => { function App({text}) { React.useEffect(() => { Scheduler.log('useEffect mount'); return () => Scheduler.log('useEffect unmount'); }); React.useLayoutEffect(() => { Scheduler.log('useLayoutEffect mount'); return () => Scheduler.log('useLayoutEffect unmount'); }); return text; } await act(() => { ReactNoop.renderLegacySyncRoot(<App text={'mount'} />); }); assertLog(['useLayoutEffect mount', 'useEffect mount']); }); it('should not double invoke class lifecycles in legacy mode', async () => { class App extends React.PureComponent { componentDidMount() { Scheduler.log('componentDidMount'); } componentDidUpdate() { Scheduler.log('componentDidUpdate'); } componentWillUnmount() { Scheduler.log('componentWillUnmount'); } render() { return this.props.text; } } await act(() => { ReactNoop.renderLegacySyncRoot(<App text={'mount'} />); }); assertLog(['componentDidMount']); }); if (__DEV__) { it('should flush double-invoked effects within the same frame as layout effects if there are no passive effects', async () => { function ComponentWithEffects({label}) { React.useLayoutEffect(() => { Scheduler.log(`useLayoutEffect mount "${label}"`); return () => Scheduler.log(`useLayoutEffect unmount "${label}"`); }); return label; } await act(async () => { ReactNoop.render( <> <ComponentWithEffects label={'one'} /> </>, ); await waitForPaint([ 'useLayoutEffect mount "one"', 'useLayoutEffect unmount "one"', 'useLayoutEffect mount "one"', ]); }); await act(async () => { ReactNoop.render( <> <ComponentWithEffects label={'one'} /> <ComponentWithEffects label={'two'} /> </>, ); assertLog([]); await waitForPaint([ // Cleanup and re-run "one" (and "two") since there is no dependencies array. 'useLayoutEffect unmount "one"', 'useLayoutEffect mount "one"', 'useLayoutEffect mount "two"', // Since "two" is new, it should be double-invoked. 'useLayoutEffect unmount "two"', 'useLayoutEffect mount "two"', ]); }); }); // This test also verifies that double-invoked effects flush synchronously // within the same frame as passive effects. it('should double invoke effects only for newly mounted components', async () => { function ComponentWithEffects({label}) { React.useEffect(() => { Scheduler.log(`useEffect mount "${label}"`); return () => Scheduler.log(`useEffect unmount "${label}"`); }); React.useLayoutEffect(() => { Scheduler.log(`useLayoutEffect mount "${label}"`); return () => Scheduler.log(`useLayoutEffect unmount "${label}"`); }); return label; } await act(async () => { ReactNoop.render( <> <ComponentWithEffects label={'one'} /> </>, ); await waitForAll([ 'useLayoutEffect mount "one"', 'useEffect mount "one"', 'useLayoutEffect unmount "one"', 'useEffect unmount "one"', 'useLayoutEffect mount "one"', 'useEffect mount "one"', ]); }); await act(async () => { ReactNoop.render( <> <ComponentWithEffects label={'one'} /> <ComponentWithEffects label={'two'} /> </>, ); await waitFor([ // Cleanup and re-run "one" (and "two") since there is no dependencies array. 'useLayoutEffect unmount "one"', 'useLayoutEffect mount "one"', 'useLayoutEffect mount "two"', ]); await waitForAll([ 'useEffect unmount "one"', 'useEffect mount "one"', 'useEffect mount "two"', // Since "two" is new, it should be double-invoked. 'useLayoutEffect unmount "two"', 'useEffect unmount "two"', 'useLayoutEffect mount "two"', 'useEffect mount "two"', ]); }); }); it('double invoking for effects for modern roots', async () => { function App({text}) { React.useEffect(() => { Scheduler.log('useEffect mount'); return () => Scheduler.log('useEffect unmount'); }); React.useLayoutEffect(() => { Scheduler.log('useLayoutEffect mount'); return () => Scheduler.log('useLayoutEffect unmount'); }); return text; } await act(() => { ReactNoop.render(<App text={'mount'} />); }); assertLog([ 'useLayoutEffect mount', 'useEffect mount', 'useLayoutEffect unmount', 'useEffect unmount', 'useLayoutEffect mount', 'useEffect mount', ]); await act(() => { ReactNoop.render(<App text={'update'} />); }); assertLog([ 'useLayoutEffect unmount', 'useLayoutEffect mount', 'useEffect unmount', 'useEffect mount', ]); await act(() => { ReactNoop.render(null); }); assertLog(['useLayoutEffect unmount', 'useEffect unmount']); }); it('multiple effects are double invoked in the right order (all mounted, all unmounted, all remounted)', async () => { function App({text}) { React.useEffect(() => { Scheduler.log('useEffect One mount'); return () => Scheduler.log('useEffect One unmount'); }); React.useEffect(() => { Scheduler.log('useEffect Two mount'); return () => Scheduler.log('useEffect Two unmount'); }); return text; } await act(() => { ReactNoop.render(<App text={'mount'} />); }); assertLog([ 'useEffect One mount', 'useEffect Two mount', 'useEffect One unmount', 'useEffect Two unmount', 'useEffect One mount', 'useEffect Two mount', ]); await act(() => { ReactNoop.render(<App text={'update'} />); }); assertLog([ 'useEffect One unmount', 'useEffect Two unmount', 'useEffect One mount', 'useEffect Two mount', ]); await act(() => { ReactNoop.render(null); }); assertLog(['useEffect One unmount', 'useEffect Two unmount']); }); it('multiple layout effects are double invoked in the right order (all mounted, all unmounted, all remounted)', async () => { function App({text}) { React.useLayoutEffect(() => { Scheduler.log('useLayoutEffect One mount'); return () => Scheduler.log('useLayoutEffect One unmount'); }); React.useLayoutEffect(() => { Scheduler.log('useLayoutEffect Two mount'); return () => Scheduler.log('useLayoutEffect Two unmount'); }); return text; } await act(() => { ReactNoop.render(<App text={'mount'} />); }); assertLog([ 'useLayoutEffect One mount', 'useLayoutEffect Two mount', 'useLayoutEffect One unmount', 'useLayoutEffect Two unmount', 'useLayoutEffect One mount', 'useLayoutEffect Two mount', ]); await act(() => { ReactNoop.render(<App text={'update'} />); }); assertLog([ 'useLayoutEffect One unmount', 'useLayoutEffect Two unmount', 'useLayoutEffect One mount', 'useLayoutEffect Two mount', ]); await act(() => { ReactNoop.render(null); }); assertLog(['useLayoutEffect One unmount', 'useLayoutEffect Two unmount']); }); it('useEffect and useLayoutEffect is called twice when there is no unmount', async () => { function App({text}) { React.useEffect(() => { Scheduler.log('useEffect mount'); }); React.useLayoutEffect(() => { Scheduler.log('useLayoutEffect mount'); }); return text; } await act(() => { ReactNoop.render(<App text={'mount'} />); }); assertLog([ 'useLayoutEffect mount', 'useEffect mount', 'useLayoutEffect mount', 'useEffect mount', ]); await act(() => { ReactNoop.render(<App text={'update'} />); }); assertLog(['useLayoutEffect mount', 'useEffect mount']); await act(() => { ReactNoop.render(null); }); assertLog([]); }); //@gate useModernStrictMode it('disconnects refs during double invoking', async () => { const onRefMock = jest.fn(); function App({text}) { return ( <span ref={ref => { onRefMock(ref); }}> text </span> ); } await act(() => { ReactNoop.render(<App text={'mount'} />); }); expect(onRefMock.mock.calls.length).toBe(3); expect(onRefMock.mock.calls[0][0]).not.toBeNull(); expect(onRefMock.mock.calls[1][0]).toBe(null); expect(onRefMock.mock.calls[2][0]).not.toBeNull(); }); it('passes the right context to class component lifecycles', async () => { class App extends React.PureComponent { test() {} componentDidMount() { this.test(); Scheduler.log('componentDidMount'); } componentDidUpdate() { this.test(); Scheduler.log('componentDidUpdate'); } componentWillUnmount() { this.test(); Scheduler.log('componentWillUnmount'); } render() { return null; } } await act(() => { ReactNoop.render(<App />); }); assertLog([ 'componentDidMount', 'componentWillUnmount', 'componentDidMount', ]); }); it('double invoking works for class components', async () => { class App extends React.PureComponent { componentDidMount() { Scheduler.log('componentDidMount'); } componentDidUpdate() { Scheduler.log('componentDidUpdate'); } componentWillUnmount() { Scheduler.log('componentWillUnmount'); } render() { return this.props.text; } } await act(() => { ReactNoop.render(<App text={'mount'} />); }); assertLog([ 'componentDidMount', 'componentWillUnmount', 'componentDidMount', ]); await act(() => { ReactNoop.render(<App text={'update'} />); }); assertLog(['componentDidUpdate']); await act(() => { ReactNoop.render(null); }); assertLog(['componentWillUnmount']); }); it('double flushing passive effects only results in one double invoke', async () => { function App({text}) { const [state, setState] = React.useState(0); React.useEffect(() => { if (state !== 1) { setState(1); } Scheduler.log('useEffect mount'); return () => Scheduler.log('useEffect unmount'); }); React.useLayoutEffect(() => { Scheduler.log('useLayoutEffect mount'); return () => Scheduler.log('useLayoutEffect unmount'); }); Scheduler.log(text); return text; } await act(() => { ReactNoop.render(<App text={'mount'} />); }); assertLog([ 'mount', 'useLayoutEffect mount', 'useEffect mount', 'useLayoutEffect unmount', 'useEffect unmount', 'useLayoutEffect mount', 'useEffect mount', 'mount', 'useLayoutEffect unmount', 'useLayoutEffect mount', 'useEffect unmount', 'useEffect mount', ]); }); it('newly mounted components after initial mount get double invoked', async () => { let _setShowChild; function Child() { React.useEffect(() => { Scheduler.log('Child useEffect mount'); return () => Scheduler.log('Child useEffect unmount'); }); React.useLayoutEffect(() => { Scheduler.log('Child useLayoutEffect mount'); return () => Scheduler.log('Child useLayoutEffect unmount'); }); return null; } function App() { const [showChild, setShowChild] = React.useState(false); _setShowChild = setShowChild; React.useEffect(() => { Scheduler.log('App useEffect mount'); return () => Scheduler.log('App useEffect unmount'); }); React.useLayoutEffect(() => { Scheduler.log('App useLayoutEffect mount'); return () => Scheduler.log('App useLayoutEffect unmount'); }); return showChild && <Child />; } await act(() => { ReactNoop.render(<App />); }); assertLog([ 'App useLayoutEffect mount', 'App useEffect mount', 'App useLayoutEffect unmount', 'App useEffect unmount', 'App useLayoutEffect mount', 'App useEffect mount', ]); await act(() => { _setShowChild(true); }); assertLog([ 'App useLayoutEffect unmount', 'Child useLayoutEffect mount', 'App useLayoutEffect mount', 'App useEffect unmount', 'Child useEffect mount', 'App useEffect mount', 'Child useLayoutEffect unmount', 'Child useEffect unmount', 'Child useLayoutEffect mount', 'Child useEffect mount', ]); }); it('classes and functions are double invoked together correctly', async () => { class ClassChild extends React.PureComponent { componentDidMount() { Scheduler.log('componentDidMount'); } componentWillUnmount() { Scheduler.log('componentWillUnmount'); } render() { return this.props.text; } } function FunctionChild({text}) { React.useEffect(() => { Scheduler.log('useEffect mount'); return () => Scheduler.log('useEffect unmount'); }); React.useLayoutEffect(() => { Scheduler.log('useLayoutEffect mount'); return () => Scheduler.log('useLayoutEffect unmount'); }); return text; } function App({text}) { return ( <> <ClassChild text={text} /> <FunctionChild text={text} /> </> ); } await act(() => { ReactNoop.render(<App text={'mount'} />); }); assertLog([ 'componentDidMount', 'useLayoutEffect mount', 'useEffect mount', 'componentWillUnmount', 'useLayoutEffect unmount', 'useEffect unmount', 'componentDidMount', 'useLayoutEffect mount', 'useEffect mount', ]); await act(() => { ReactNoop.render(<App text={'mount'} />); }); assertLog([ 'useLayoutEffect unmount', 'useLayoutEffect mount', 'useEffect unmount', 'useEffect mount', ]); await act(() => { ReactNoop.render(null); }); assertLog([ 'componentWillUnmount', 'useLayoutEffect unmount', 'useEffect unmount', ]); }); } });
24.890432
131
0.534692
Penetration-Testing-with-Shellcode
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type { Thenable, FulfilledThenable, RejectedThenable, } from 'shared/ReactTypes'; import type {ImportMetadata} from './shared/ReactFlightImportMetadata'; import type {ModuleLoading} from 'react-client/src/ReactFlightClientConfig'; import { ID, CHUNKS, NAME, isAsyncImport, } from './shared/ReactFlightImportMetadata'; import {prepareDestinationWithChunks} from 'react-client/src/ReactFlightClientConfig'; export type SSRModuleMap = { [clientId: string]: { [clientExportName: string]: ClientReference<any>, }, }; export type ServerManifest = void; export type ServerReferenceId = string; export opaque type ClientReferenceMetadata = ImportMetadata; // eslint-disable-next-line no-unused-vars export opaque type ClientReference<T> = { specifier: string, name: string, async?: boolean, }; // The reason this function needs to defined here in this file instead of just // being exported directly from the WebpackDestination... file is because the // ClientReferenceMetadata is opaque and we can't unwrap it there. // This should get inlined and we could also just implement an unwrapping function // though that risks it getting used in places it shouldn't be. This is unfortunate // but currently it seems to be the best option we have. export function prepareDestinationForModule( moduleLoading: ModuleLoading, nonce: ?string, metadata: ClientReferenceMetadata, ) { prepareDestinationWithChunks(moduleLoading, metadata[CHUNKS], nonce); } export function resolveClientReference<T>( bundlerConfig: SSRModuleMap, metadata: ClientReferenceMetadata, ): ClientReference<T> { const moduleExports = bundlerConfig[metadata[ID]]; let resolvedModuleData = moduleExports[metadata[NAME]]; let name; if (resolvedModuleData) { // The potentially aliased name. name = resolvedModuleData.name; } else { // If we don't have this specific name, we might have the full module. resolvedModuleData = moduleExports['*']; if (!resolvedModuleData) { throw new Error( 'Could not find the module "' + metadata[ID] + '" in the React SSR Manifest. ' + 'This is probably a bug in the React Server Components bundler.', ); } name = metadata[NAME]; } return { specifier: resolvedModuleData.specifier, name: name, async: isAsyncImport(metadata), }; } export function resolveServerReference<T>( bundlerConfig: ServerManifest, id: ServerReferenceId, ): ClientReference<T> { const idx = id.lastIndexOf('#'); const specifier = id.slice(0, idx); const name = id.slice(idx + 1); return {specifier, name}; } const asyncModuleCache: Map<string, Thenable<any>> = new Map(); export function preloadModule<T>( metadata: ClientReference<T>, ): null | Thenable<any> { const existingPromise = asyncModuleCache.get(metadata.specifier); if (existingPromise) { if (existingPromise.status === 'fulfilled') { return null; } return existingPromise; } else { // $FlowFixMe[unsupported-syntax] let modulePromise: Promise<T> = import(metadata.specifier); if (metadata.async) { // If the module is async, it must have been a CJS module. // CJS modules are accessed through the default export in // Node.js so we have to get the default export to get the // full module exports. modulePromise = modulePromise.then(function (value) { return (value: any).default; }); } modulePromise.then( value => { const fulfilledThenable: FulfilledThenable<mixed> = (modulePromise: any); fulfilledThenable.status = 'fulfilled'; fulfilledThenable.value = value; }, reason => { const rejectedThenable: RejectedThenable<mixed> = (modulePromise: any); rejectedThenable.status = 'rejected'; rejectedThenable.reason = reason; }, ); asyncModuleCache.set(metadata.specifier, modulePromise); return modulePromise; } } export function requireModule<T>(metadata: ClientReference<T>): T { let moduleExports; // We assume that preloadModule has been called before, which // should have added something to the module cache. const promise: any = asyncModuleCache.get(metadata.specifier); if (promise.status === 'fulfilled') { moduleExports = promise.value; } else { throw promise.reason; } if (metadata.name === '*') { // This is a placeholder value that represents that the caller imported this // as a CommonJS module as is. return moduleExports; } if (metadata.name === '') { // This is a placeholder value that represents that the caller accessed the // default property of this if it was an ESM interop module. return moduleExports.default; } return moduleExports[metadata.name]; }
29.809816
86
0.700856
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; function generateArray(size: number) { return Array.from({length: size}, () => Math.floor(Math.random() * size)); } const arr = generateArray(50000); export default function LargeSubtree(): React.Node { const [showList, setShowList] = React.useState(false); const toggleList = () => { const startTime = performance.now(); setShowList(!showList); // requestAnimationFrame should happen after render+commit is done window.requestAnimationFrame(() => { const afterRenderTime = performance.now(); console.log( `Time spent on ${showList ? 'unmounting' : 'mounting'} the subtree: ${ afterRenderTime - startTime }ms`, ); }); }; return ( <div> <h2>Mount/Unmount a large subtree</h2> <p>Click the button to toggle the state. Open console for results.</p> <button onClick={toggleList}>toggle</button> <ul> <li key="dummy">dummy item</li> {showList && arr.map((num, idx) => <li key={idx}>{num}</li>)} </ul> </div> ); }
27.488889
78
0.626854
Python-for-Offensive-PenTest
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {CommitTree} from './types'; import type {SerializedElement} from 'react-devtools-shared/src/frontend/types'; import * as React from 'react'; import {useContext} from 'react'; import {ProfilerContext} from './ProfilerContext'; import styles from './Updaters.css'; import {ElementTypeRoot} from '../../../frontend/types'; export type Props = { commitTree: CommitTree, updaters: Array<SerializedElement>, }; export default function Updaters({commitTree, updaters}: Props): React.Node { const {selectFiber} = useContext(ProfilerContext); const children = updaters.length > 0 ? ( updaters.map((serializedElement: SerializedElement): React$Node => { const {displayName, id, key, type} = serializedElement; const isVisibleInTree = commitTree.nodes.has(id) && type !== ElementTypeRoot; if (isVisibleInTree) { return ( <button key={id} className={styles.Updater} onClick={() => selectFiber(id, displayName)}> {displayName} {key ? `key="${key}"` : ''} </button> ); } else { return ( <div key={id} className={styles.UnmountedUpdater}> {displayName} {key ? `key="${key}"` : ''} </div> ); } }) ) : ( <div key="none" className={styles.NoUpdaters}> (unknown) </div> ); return <div className={styles.Updaters}>{children}</div>; }
28.293103
80
0.594817
owtf
const React = window.React; const noop = n => n; class RadioNameChangeFixture extends React.Component { state = { updated: false, }; onClick = () => { this.setState(state => { return {updated: !state.updated}; }); }; render() { const {updated} = this.state; const radioName = updated ? 'firstName' : 'secondName'; return ( <div> <label> <input type="radio" name={radioName} onChange={noop} checked={updated === true} /> First Radio </label> <label> <input type="radio" name={radioName} onChange={noop} checked={updated === false} /> Second Radio </label> <div> <button type="button" onClick={this.onClick}> Toggle </button> </div> </div> ); } } export default RadioNameChangeFixture;
19.061224
59
0.476578
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core * @jest-environment node */ 'use strict'; let React; let ReactNoopServer; describe('ReactServer', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoopServer = require('react-noop-renderer/server'); }); function div(...children) { children = children.map(c => typeof c === 'string' ? {text: c, hidden: false} : c, ); return {type: 'div', children, prop: undefined, hidden: false}; } it('can call render', () => { const result = ReactNoopServer.render(<div>hello world</div>); expect(result.root).toEqual(div('hello world')); }); });
22.166667
67
0.630252
owtf
import Fixture from '../../Fixture'; const React = window.React; class JumpingCursorTestCase extends React.Component { state = {value: ''}; onChange = event => { this.setState({value: event.target.value}); }; render() { return ( <Fixture> <div>{this.props.children}</div> <div className="control-box"> <fieldset> <legend>Controlled</legend> <input type="email" value={this.state.value} onChange={this.onChange} /> <span className="hint"> {' '} Value: {JSON.stringify(this.state.value)} </span> </fieldset> <fieldset> <legend>Uncontrolled</legend> <input type="email" defaultValue="" /> </fieldset> </div> </Fixture> ); } } export default JumpingCursorTestCase;
21.975
55
0.507625
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core * @jest-environment ./scripts/jest/ReactDOMServerIntegrationEnvironment */ 'use strict'; const ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegrationTestUtils'); let React; let ReactDOM; let ReactDOMServer; let ReactTestUtils; function initModules() { // Reset warning cache. jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMServer = require('react-dom/server'); ReactTestUtils = require('react-dom/test-utils'); // Make them available to the helpers. return { ReactDOM, ReactDOMServer, ReactTestUtils, }; } const {resetModules, itRenders} = ReactDOMServerIntegrationUtils(initModules); describe('ReactDOMServerIntegrationProgress', () => { beforeEach(() => { resetModules(); }); itRenders('a progress in an indeterminate state', async render => { // Regression test for https://github.com/facebook/react/issues/6119 const e = await render(<progress value={null} />); expect(e.hasAttribute('value')).toBe(false); const e2 = await render(<progress value={50} />); expect(e2.getAttribute('value')).toBe('50'); }); });
25.686275
93
0.704412
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ /** * `charCode` represents the actual "character code" and is safe to use with * `String.fromCharCode`. As such, only keys that correspond to printable * characters produce a valid `charCode`, the only exception to this is Enter. * The Tab-key is considered non-printable and does not have a `charCode`, * presumably because it does not produce a tab-character in browsers. * * @param {object} nativeEvent Native browser event. * @return {number} Normalized `charCode` property. */ function getEventCharCode(nativeEvent: KeyboardEvent): number { let charCode; const keyCode = nativeEvent.keyCode; if ('charCode' in nativeEvent) { charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`. if (charCode === 0 && keyCode === 13) { charCode = 13; } } else { // IE8 does not implement `charCode`, but `keyCode` has the correct value. charCode = keyCode; } // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux) // report Enter as charCode 10 when ctrl is pressed. if (charCode === 10) { charCode = 13; } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. // Must not discard the (non-)printable Enter-key. if (charCode >= 32 || charCode === 13) { return charCode; } return 0; } export default getEventCharCode;
29.5
80
0.685804
owtf
import FixtureSet from '../../FixtureSet'; import TestCase from '../../TestCase'; import NumberTestCase from './NumberTestCase'; import NumberInputDecimal from './NumberInputDecimal'; import NumberInputExtraZeroes from './NumberInputExtraZeroes'; const React = window.React; function NumberInputs() { return ( <FixtureSet title="Number inputs" description="Number inputs inconsistently assign and report the value property depending on the browser."> <TestCase title="Backspacing" description="The decimal place should not be lost"> <TestCase.Steps> <li>Type "3.1"</li> <li>Press backspace, eliminating the "1"</li> </TestCase.Steps> <TestCase.ExpectedResult> The field should read "3.", preserving the decimal place </TestCase.ExpectedResult> <NumberTestCase /> <p className="footnote"> <b>Notes:</b> Modern Chrome and Safari {'<='} 6 clear trailing decimals on blur. React makes this concession so that the value attribute remains in sync with the value property. </p> </TestCase> <TestCase title="Decimal precision" description="Supports decimal precision greater than 2 places"> <TestCase.Steps> <li>Type "0.01"</li> </TestCase.Steps> <TestCase.ExpectedResult> The field should read "0.01" </TestCase.ExpectedResult> <NumberTestCase /> </TestCase> <TestCase title="Exponent form" description="Supports exponent form ('2e4')"> <TestCase.Steps> <li>Type "2e"</li> <li>Type 4, to read "2e4"</li> </TestCase.Steps> <TestCase.ExpectedResult> The field should read "2e4". The parsed value should read "20000" </TestCase.ExpectedResult> <NumberTestCase /> </TestCase> <TestCase title="Exponent Form" description="Pressing 'e' at the end"> <TestCase.Steps> <li>Type "3.14"</li> <li>Press "e", so that the input reads "3.14e"</li> </TestCase.Steps> <TestCase.ExpectedResult> The field should read "3.14e", the parsed value should be empty </TestCase.ExpectedResult> <NumberTestCase /> </TestCase> <TestCase title="Exponent Form" description="Supports pressing 'ee' in the middle of a number"> <TestCase.Steps> <li>Type "3.14"</li> <li>Move the text cursor to after the decimal place</li> <li>Press "e" twice, so that the value reads "3.ee14"</li> </TestCase.Steps> <TestCase.ExpectedResult> The field should read "3.ee14" </TestCase.ExpectedResult> <NumberTestCase /> </TestCase> <TestCase title="Trailing Zeroes" description="Typing '3.0' preserves the trailing zero"> <TestCase.Steps> <li>Type "3.0"</li> </TestCase.Steps> <TestCase.ExpectedResult> The field should read "3.0" </TestCase.ExpectedResult> <NumberTestCase /> </TestCase> <TestCase title="Inserting decimals precision" description="Inserting '.' in to '300' maintains the trailing zeroes"> <TestCase.Steps> <li>Type "300"</li> <li>Move the cursor to after the "3"</li> <li>Type "."</li> </TestCase.Steps> <TestCase.ExpectedResult> The field should read "3.00", not "3" </TestCase.ExpectedResult> <NumberTestCase /> </TestCase> <TestCase title="Replacing numbers with -" description="Replacing a number with the '-' sign should not clear the value"> <TestCase.Steps> <li>Type "3"</li> <li>Select the entire value"</li> <li>Type '-' to replace '3' with '-'</li> </TestCase.Steps> <TestCase.ExpectedResult> The field should read "-", not be blank. </TestCase.ExpectedResult> <NumberTestCase /> </TestCase> <TestCase title="Negative numbers" description="Typing minus when inserting a negative number should work"> <TestCase.Steps> <li>Type "-"</li> <li>Type '3'</li> </TestCase.Steps> <TestCase.ExpectedResult> The field should read "-3". </TestCase.ExpectedResult> <NumberTestCase /> </TestCase> <TestCase title="Decimal numbers" description="eg: initial value is '.98', when format to '0.98', should change to '0.98' "> <TestCase.Steps> <li>initial value is '.98'</li> <li>setState to '0.98'</li> </TestCase.Steps> <TestCase.ExpectedResult> the input value should be '0.98'. </TestCase.ExpectedResult> <NumberInputDecimal /> </TestCase> <TestCase title="Trailing zeroes" description="Extraneous zeroes should be retained when changing the value via setState"> <TestCase.Steps> <li>Change the text to 4.0000</li> <li>Click "Reset to 3.0000"</li> </TestCase.Steps> <TestCase.ExpectedResult> The field should read 3.0000, not 3 </TestCase.ExpectedResult> <NumberInputExtraZeroes /> <p className="footnote"> <b>Notes:</b> Firefox drops extraneous zeroes when assigned. Zeroes are preserved when editing, however directly assigning a new value will drop zeroes. This{' '} <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1003896"> is a bug in Firefox </a>{' '} that we can not control for. </p> </TestCase> </FixtureSet> ); } export default NumberInputs;
29.402062
98
0.581143
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Fiber} from 'react-reconciler/src/ReactInternalTypes'; import type {ReactScopeInstance} from 'shared/ReactTypes'; import type { ReactDOMEventHandle, ReactDOMEventHandleListener, } from './ReactDOMEventHandleTypes'; import type { Container, TextInstance, Instance, SuspenseInstance, Props, HoistableRoot, RootResources, } from './ReactFiberConfigDOM'; import { HostComponent, HostHoistable, HostSingleton, HostText, HostRoot, SuspenseComponent, } from 'react-reconciler/src/ReactWorkTags'; import {getParentSuspenseInstance} from './ReactFiberConfigDOM'; import {enableScopeAPI, enableFloat} from 'shared/ReactFeatureFlags'; const randomKey = Math.random().toString(36).slice(2); const internalInstanceKey = '__reactFiber$' + randomKey; const internalPropsKey = '__reactProps$' + randomKey; const internalContainerInstanceKey = '__reactContainer$' + randomKey; const internalEventHandlersKey = '__reactEvents$' + randomKey; const internalEventHandlerListenersKey = '__reactListeners$' + randomKey; const internalEventHandlesSetKey = '__reactHandles$' + randomKey; const internalRootNodeResourcesKey = '__reactResources$' + randomKey; const internalHoistableMarker = '__reactMarker$' + randomKey; export function detachDeletedInstance(node: Instance): void { // TODO: This function is only called on host components. I don't think all of // these fields are relevant. delete (node: any)[internalInstanceKey]; delete (node: any)[internalPropsKey]; delete (node: any)[internalEventHandlersKey]; delete (node: any)[internalEventHandlerListenersKey]; delete (node: any)[internalEventHandlesSetKey]; } export function precacheFiberNode( hostInst: Fiber, node: Instance | TextInstance | SuspenseInstance | ReactScopeInstance, ): void { (node: any)[internalInstanceKey] = hostInst; } export function markContainerAsRoot(hostRoot: Fiber, node: Container): void { // $FlowFixMe[prop-missing] node[internalContainerInstanceKey] = hostRoot; } export function unmarkContainerAsRoot(node: Container): void { // $FlowFixMe[prop-missing] node[internalContainerInstanceKey] = null; } export function isContainerMarkedAsRoot(node: Container): boolean { // $FlowFixMe[prop-missing] return !!node[internalContainerInstanceKey]; } // Given a DOM node, return the closest HostComponent or HostText fiber ancestor. // If the target node is part of a hydrated or not yet rendered subtree, then // this may also return a SuspenseComponent or HostRoot to indicate that. // Conceptually the HostRoot fiber is a child of the Container node. So if you // pass the Container node as the targetNode, you will not actually get the // HostRoot back. To get to the HostRoot, you need to pass a child of it. // The same thing applies to Suspense boundaries. export function getClosestInstanceFromNode(targetNode: Node): null | Fiber { let targetInst = (targetNode: any)[internalInstanceKey]; if (targetInst) { // Don't return HostRoot or SuspenseComponent here. return targetInst; } // If the direct event target isn't a React owned DOM node, we need to look // to see if one of its parents is a React owned DOM node. let parentNode = targetNode.parentNode; while (parentNode) { // We'll check if this is a container root that could include // React nodes in the future. We need to check this first because // if we're a child of a dehydrated container, we need to first // find that inner container before moving on to finding the parent // instance. Note that we don't check this field on the targetNode // itself because the fibers are conceptually between the container // node and the first child. It isn't surrounding the container node. // If it's not a container, we check if it's an instance. targetInst = (parentNode: any)[internalContainerInstanceKey] || (parentNode: any)[internalInstanceKey]; if (targetInst) { // Since this wasn't the direct target of the event, we might have // stepped past dehydrated DOM nodes to get here. However they could // also have been non-React nodes. We need to answer which one. // If we the instance doesn't have any children, then there can't be // a nested suspense boundary within it. So we can use this as a fast // bailout. Most of the time, when people add non-React children to // the tree, it is using a ref to a child-less DOM node. // Normally we'd only need to check one of the fibers because if it // has ever gone from having children to deleting them or vice versa // it would have deleted the dehydrated boundary nested inside already. // However, since the HostRoot starts out with an alternate it might // have one on the alternate so we need to check in case this was a // root. const alternate = targetInst.alternate; if ( targetInst.child !== null || (alternate !== null && alternate.child !== null) ) { // Next we need to figure out if the node that skipped past is // nested within a dehydrated boundary and if so, which one. let suspenseInstance = getParentSuspenseInstance(targetNode); while (suspenseInstance !== null) { // We found a suspense instance. That means that we haven't // hydrated it yet. Even though we leave the comments in the // DOM after hydrating, and there are boundaries in the DOM // that could already be hydrated, we wouldn't have found them // through this pass since if the target is hydrated it would // have had an internalInstanceKey on it. // Let's get the fiber associated with the SuspenseComponent // as the deepest instance. // $FlowFixMe[prop-missing] const targetSuspenseInst = suspenseInstance[internalInstanceKey]; if (targetSuspenseInst) { return targetSuspenseInst; } // If we don't find a Fiber on the comment, it might be because // we haven't gotten to hydrate it yet. There might still be a // parent boundary that hasn't above this one so we need to find // the outer most that is known. suspenseInstance = getParentSuspenseInstance(suspenseInstance); // If we don't find one, then that should mean that the parent // host component also hasn't hydrated yet. We can return it // below since it will bail out on the isMounted check later. } } return targetInst; } targetNode = parentNode; parentNode = targetNode.parentNode; } return null; } /** * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent * instance, or null if the node was not rendered by this React. */ export function getInstanceFromNode(node: Node): Fiber | null { const inst = (node: any)[internalInstanceKey] || (node: any)[internalContainerInstanceKey]; if (inst) { const tag = inst.tag; if ( tag === HostComponent || tag === HostText || tag === SuspenseComponent || (enableFloat ? tag === HostHoistable : false) || tag === HostSingleton || tag === HostRoot ) { return inst; } else { return null; } } return null; } /** * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding * DOM node. */ export function getNodeFromInstance(inst: Fiber): Instance | TextInstance { const tag = inst.tag; if ( tag === HostComponent || (enableFloat ? tag === HostHoistable : false) || tag === HostSingleton || tag === HostText ) { // In Fiber this, is just the state node right now. We assume it will be // a host component or host text. return inst.stateNode; } // Without this first invariant, passing a non-DOM-component triggers the next // invariant for a missing parent, which is super confusing. throw new Error('getNodeFromInstance: Invalid argument.'); } export function getFiberCurrentPropsFromNode( node: Instance | TextInstance | SuspenseInstance, ): Props { return (node: any)[internalPropsKey] || null; } export function updateFiberProps( node: Instance | TextInstance | SuspenseInstance, props: Props, ): void { (node: any)[internalPropsKey] = props; } export function getEventListenerSet(node: EventTarget): Set<string> { let elementListenerSet = (node: any)[internalEventHandlersKey]; if (elementListenerSet === undefined) { elementListenerSet = (node: any)[internalEventHandlersKey] = new Set(); } return elementListenerSet; } export function getFiberFromScopeInstance( scope: ReactScopeInstance, ): null | Fiber { if (enableScopeAPI) { return (scope: any)[internalInstanceKey] || null; } return null; } export function setEventHandlerListeners( scope: EventTarget | ReactScopeInstance, listeners: Set<ReactDOMEventHandleListener>, ): void { (scope: any)[internalEventHandlerListenersKey] = listeners; } export function getEventHandlerListeners( scope: EventTarget | ReactScopeInstance, ): null | Set<ReactDOMEventHandleListener> { return (scope: any)[internalEventHandlerListenersKey] || null; } export function addEventHandleToTarget( target: EventTarget | ReactScopeInstance, eventHandle: ReactDOMEventHandle, ): void { let eventHandles = (target: any)[internalEventHandlesSetKey]; if (eventHandles === undefined) { eventHandles = (target: any)[internalEventHandlesSetKey] = new Set(); } eventHandles.add(eventHandle); } export function doesTargetHaveEventHandle( target: EventTarget | ReactScopeInstance, eventHandle: ReactDOMEventHandle, ): boolean { const eventHandles = (target: any)[internalEventHandlesSetKey]; if (eventHandles === undefined) { return false; } return eventHandles.has(eventHandle); } export function getResourcesFromRoot(root: HoistableRoot): RootResources { let resources = (root: any)[internalRootNodeResourcesKey]; if (!resources) { resources = (root: any)[internalRootNodeResourcesKey] = { hoistableStyles: new Map(), hoistableScripts: new Map(), }; } return resources; } export function isMarkedHoistable(node: Node): boolean { return !!(node: any)[internalHoistableMarker]; } export function markNodeAsHoistable(node: Node) { (node: any)[internalHoistableMarker] = true; } export function isOwnedInstance(node: Node): boolean { return !!( (node: any)[internalHoistableMarker] || (node: any)[internalInstanceKey] ); }
34.750831
81
0.709201
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core * @jest-environment node */ 'use strict'; let React; let ReactNative; let createReactNativeComponentClass; let computeComponentStackForErrorReporting; function normalizeCodeLocInfo(str) { return ( str && str.replace(/\n +(?:at|in) ([\S]+)[^\n]*/g, function (m, name) { return '\n in ' + name + ' (at **)'; }) ); } describe('ReactNativeError', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNative = require('react-native-renderer'); createReactNativeComponentClass = require('react-native/Libraries/ReactPrivate/ReactNativePrivateInterface') .ReactNativeViewConfigRegistry.register; computeComponentStackForErrorReporting = ReactNative.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED .computeComponentStackForErrorReporting; }); it('should throw error if null component registration getter is used', () => { expect(() => { try { createReactNativeComponentClass('View', null); } catch (e) { throw new Error(e.toString()); } }).toThrow( 'View config getter callback for component `View` must be a function (received `null`)', ); }); it('should be able to extract a component stack from a native view', () => { const View = createReactNativeComponentClass('View', () => ({ validAttributes: {foo: true}, uiViewClassName: 'View', })); const ref = React.createRef(); function FunctionComponent(props) { return props.children; } class ClassComponent extends React.Component { render() { return ( <FunctionComponent> <View foo="test" ref={ref} /> </FunctionComponent> ); } } ReactNative.render(<ClassComponent />, 1); const reactTag = ReactNative.findNodeHandle(ref.current); const componentStack = normalizeCodeLocInfo( computeComponentStackForErrorReporting(reactTag), ); expect(componentStack).toBe( '\n' + ' in View (at **)\n' + ' in FunctionComponent (at **)\n' + ' in ClassComponent (at **)', ); }); });
25.131868
94
0.624316
owtf
var React = require('react'); var ReactDOM = require('react-dom'); ReactDOM.render( React.createElement('h1', null, 'Hello World!'), document.getElementById('container') );
21.375
50
0.702247
Python-Penetration-Testing-for-Developers
let React; let ReactNoop; let Scheduler; let act; let LegacyHidden; let Activity; let Suspense; let useState; let useEffect; let startTransition; let textCache; let waitFor; let waitForPaint; let assertLog; describe('Activity Suspense', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); act = require('internal-test-utils').act; LegacyHidden = React.unstable_LegacyHidden; Activity = React.unstable_Activity; Suspense = React.Suspense; useState = React.useState; useEffect = React.useEffect; startTransition = React.startTransition; const InternalTestUtils = require('internal-test-utils'); waitFor = InternalTestUtils.waitFor; waitForPaint = InternalTestUtils.waitForPaint; assertLog = InternalTestUtils.assertLog; textCache = new Map(); }); function resolveText(text) { const record = textCache.get(text); if (record === undefined) { const newRecord = { status: 'resolved', value: text, }; textCache.set(text, newRecord); } else if (record.status === 'pending') { const thenable = record.value; record.status = 'resolved'; record.value = text; thenable.pings.forEach(t => t()); } } function readText(text) { const record = textCache.get(text); if (record !== undefined) { switch (record.status) { case 'pending': Scheduler.log(`Suspend! [${text}]`); throw record.value; case 'rejected': throw record.value; case 'resolved': return record.value; } } else { Scheduler.log(`Suspend! [${text}]`); const thenable = { pings: [], then(resolve) { if (newRecord.status === 'pending') { thenable.pings.push(resolve); } else { Promise.resolve().then(() => resolve(newRecord.value)); } }, }; const newRecord = { status: 'pending', value: thenable, }; textCache.set(text, newRecord); throw thenable; } } function Text({text}) { Scheduler.log(text); return text; } function AsyncText({text}) { readText(text); Scheduler.log(text); return text; } // @gate enableActivity test('basic example of suspending inside hidden tree', async () => { const root = ReactNoop.createRoot(); function App() { return ( <Suspense fallback={<Text text="Loading..." />}> <span> <Text text="Visible" /> </span> <Activity mode="hidden"> <span> <AsyncText text="Hidden" /> </span> </Activity> </Suspense> ); } // The hidden tree hasn't finished loading, but we should still be able to // show the surrounding contents. The outer Suspense boundary // isn't affected. await act(() => { root.render(<App />); }); assertLog(['Visible', 'Suspend! [Hidden]']); expect(root).toMatchRenderedOutput(<span>Visible</span>); // When the data resolves, we should be able to finish prerendering // the hidden tree. await act(async () => { await resolveText('Hidden'); }); assertLog(['Hidden']); expect(root).toMatchRenderedOutput( <> <span>Visible</span> <span hidden={true}>Hidden</span> </>, ); }); // @gate www test('LegacyHidden does not handle suspense', async () => { const root = ReactNoop.createRoot(); function App() { return ( <Suspense fallback={<Text text="Loading..." />}> <span> <Text text="Visible" /> </span> <LegacyHidden mode="hidden"> <span> <AsyncText text="Hidden" /> </span> </LegacyHidden> </Suspense> ); } // Unlike Activity, LegacyHidden never captures if something suspends await act(() => { root.render(<App />); }); assertLog(['Visible', 'Suspend! [Hidden]', 'Loading...']); // Nearest Suspense boundary switches to a fallback even though the // suspended content is hidden. expect(root).toMatchRenderedOutput( <> <span hidden={true}>Visible</span> Loading... </>, ); }); // @gate experimental || www test("suspending inside currently hidden tree that's switching to visible", async () => { const root = ReactNoop.createRoot(); function Details({open, children}) { return ( <Suspense fallback={<Text text="Loading..." />}> <span> <Text text={open ? 'Open' : 'Closed'} /> </span> <Activity mode={open ? 'visible' : 'hidden'}> <span>{children}</span> </Activity> </Suspense> ); } // The hidden tree hasn't finished loading, but we should still be able to // show the surrounding contents. It doesn't matter that there's no // Suspense boundary because the unfinished content isn't visible. await act(() => { root.render( <Details open={false}> <AsyncText text="Async" /> </Details>, ); }); assertLog(['Closed', 'Suspend! [Async]']); expect(root).toMatchRenderedOutput(<span>Closed</span>); // But when we switch the boundary from hidden to visible, it should // now bubble to the nearest Suspense boundary. await act(() => { startTransition(() => { root.render( <Details open={true}> <AsyncText text="Async" /> </Details>, ); }); }); assertLog(['Open', 'Suspend! [Async]', 'Loading...']); // It should suspend with delay to prevent the already-visible Suspense // boundary from switching to a fallback expect(root).toMatchRenderedOutput(<span>Closed</span>); // Resolve the data and finish rendering await act(async () => { await resolveText('Async'); }); assertLog(['Open', 'Async']); expect(root).toMatchRenderedOutput( <> <span>Open</span> <span>Async</span> </>, ); }); // @gate enableActivity test("suspending inside currently visible tree that's switching to hidden", async () => { const root = ReactNoop.createRoot(); function Details({open, children}) { return ( <Suspense fallback={<Text text="Loading..." />}> <span> <Text text={open ? 'Open' : 'Closed'} /> </span> <Activity mode={open ? 'visible' : 'hidden'}> <span>{children}</span> </Activity> </Suspense> ); } // Initial mount. Nothing suspends await act(() => { root.render( <Details open={true}> <Text text="(empty)" /> </Details>, ); }); assertLog(['Open', '(empty)']); expect(root).toMatchRenderedOutput( <> <span>Open</span> <span>(empty)</span> </>, ); // Update that suspends inside the currently visible tree await act(() => { startTransition(() => { root.render( <Details open={true}> <AsyncText text="Async" /> </Details>, ); }); }); assertLog(['Open', 'Suspend! [Async]', 'Loading...']); // It should suspend with delay to prevent the already-visible Suspense // boundary from switching to a fallback expect(root).toMatchRenderedOutput( <> <span>Open</span> <span>(empty)</span> </>, ); // Update that hides the suspended tree await act(() => { startTransition(() => { root.render( <Details open={false}> <AsyncText text="Async" /> </Details>, ); }); }); // Now the visible part of the tree can commit without being blocked // by the suspended content, which is hidden. assertLog(['Closed', 'Suspend! [Async]']); expect(root).toMatchRenderedOutput( <> <span>Closed</span> <span hidden={true}>(empty)</span> </>, ); // Resolve the data and finish rendering await act(async () => { await resolveText('Async'); }); assertLog(['Async']); expect(root).toMatchRenderedOutput( <> <span>Closed</span> <span hidden={true}>Async</span> </>, ); }); // @gate experimental || www test('update that suspends inside hidden tree', async () => { let setText; function Child() { const [text, _setText] = useState('A'); setText = _setText; return <AsyncText text={text} />; } function App({show}) { return ( <Activity mode={show ? 'visible' : 'hidden'}> <span> <Child /> </span> </Activity> ); } const root = ReactNoop.createRoot(); resolveText('A'); await act(() => { root.render(<App show={false} />); }); assertLog(['A']); await act(() => { startTransition(() => { setText('B'); }); }); }); // @gate experimental || www test('updates at multiple priorities that suspend inside hidden tree', async () => { let setText; let setStep; function Child() { const [text, _setText] = useState('A'); setText = _setText; const [step, _setStep] = useState(0); setStep = _setStep; return <AsyncText text={text + step} />; } function App({show}) { return ( <Activity mode={show ? 'visible' : 'hidden'}> <span> <Child /> </span> </Activity> ); } const root = ReactNoop.createRoot(); resolveText('A0'); await act(() => { root.render(<App show={false} />); }); assertLog(['A0']); expect(root).toMatchRenderedOutput(<span hidden={true}>A0</span>); await act(() => { React.startTransition(() => { setStep(1); }); ReactNoop.flushSync(() => { setText('B'); }); }); assertLog([ // The high priority render suspends again 'Suspend! [B0]', // There's still pending work in another lane, so we should attempt // that, too. 'Suspend! [B1]', ]); expect(root).toMatchRenderedOutput(<span hidden={true}>A0</span>); // Resolve the data and finish rendering await act(() => { resolveText('B1'); }); assertLog(['B1']); expect(root).toMatchRenderedOutput(<span hidden={true}>B1</span>); }); // @gate enableActivity test('detect updates to a hidden tree during a concurrent event', async () => { // This is a pretty complex test case. It relates to how we detect if an // update is made to a hidden tree: when scheduling the update, we walk up // the fiber return path to see if any of the parents is a hidden Activity // component. This doesn't work if there's already a render in progress, // because the tree might be about to flip to hidden. To avoid a data race, // queue updates atomically: wait to queue the update until after the // current render has finished. let setInner; function Child({outer}) { const [inner, _setInner] = useState(0); setInner = _setInner; useEffect(() => { // Inner and outer values are always updated simultaneously, so they // should always be consistent. if (inner !== outer) { Scheduler.log('Tearing! Inner and outer are inconsistent!'); } else { Scheduler.log('Inner and outer are consistent'); } }, [inner, outer]); return <Text text={'Inner: ' + inner} />; } let setOuter; function App({show}) { const [outer, _setOuter] = useState(0); setOuter = _setOuter; return ( <> <Activity mode={show ? 'visible' : 'hidden'}> <span> <Child outer={outer} /> </span> </Activity> <span> <Text text={'Outer: ' + outer} /> </span> <Suspense fallback={<Text text="Loading..." />}> <span> <Text text={'Sibling: ' + outer} /> </span> </Suspense> </> ); } // Render a hidden tree const root = ReactNoop.createRoot(); resolveText('Async: 0'); await act(() => { root.render(<App show={true} />); }); assertLog([ 'Inner: 0', 'Outer: 0', 'Sibling: 0', 'Inner and outer are consistent', ]); expect(root).toMatchRenderedOutput( <> <span>Inner: 0</span> <span>Outer: 0</span> <span>Sibling: 0</span> </>, ); await act(async () => { // Update a value both inside and outside the hidden tree. These values // must always be consistent. startTransition(() => { setOuter(1); setInner(1); // In the same render, also hide the offscreen tree. root.render(<App show={false} />); }); await waitFor([ // The outer update will commit, but the inner update is deferred until // a later render. 'Outer: 1', ]); // Assert that we haven't committed quite yet expect(root).toMatchRenderedOutput( <> <span>Inner: 0</span> <span>Outer: 0</span> <span>Sibling: 0</span> </>, ); // Before the tree commits, schedule a concurrent event. The inner update // is to a tree that's just about to be hidden. startTransition(() => { setOuter(2); setInner(2); }); // Finish rendering and commit the in-progress render. await waitForPaint(['Sibling: 1']); expect(root).toMatchRenderedOutput( <> <span hidden={true}>Inner: 0</span> <span>Outer: 1</span> <span>Sibling: 1</span> </>, ); // Now reveal the hidden tree at high priority. ReactNoop.flushSync(() => { root.render(<App show={true} />); }); assertLog([ // There are two pending updates on Inner, but only the first one // is processed, even though they share the same lane. If the second // update were erroneously processed, then Inner would be inconsistent // with Outer. 'Inner: 1', 'Outer: 1', 'Sibling: 1', 'Inner and outer are consistent', ]); }); assertLog([ 'Inner: 2', 'Outer: 2', 'Sibling: 2', 'Inner and outer are consistent', ]); expect(root).toMatchRenderedOutput( <> <span>Inner: 2</span> <span>Outer: 2</span> <span>Sibling: 2</span> </>, ); }); });
25.744144
91
0.542986
owtf
import TestCase from '../../TestCase'; const React = window.React; const ReactDOM = window.ReactDOM; const MouseEnter = () => { const containerRef = React.useRef(); React.useEffect(function () { const hostEl = containerRef.current; ReactDOM.render(<MouseEnterDetect />, hostEl, () => { ReactDOM.render(<MouseEnterDetect />, hostEl.childNodes[1]); }); }, []); return ( <TestCase title="Mouse Enter" description="" affectedBrowsers="Chrome, Safari, Firefox"> <TestCase.Steps> <li>Mouse enter the boxes below, from different borders</li> </TestCase.Steps> <TestCase.ExpectedResult> Mouse enter call count should equal to 1; <br /> Issue{' '} <a rel="noopener noreferrer" target="_blank" href="https://github.com/facebook/react/issues/16763"> #16763 </a>{' '} should not happen. <br /> </TestCase.ExpectedResult> <div ref={containerRef} /> </TestCase> ); }; const MouseEnterDetect = () => { const [log, setLog] = React.useState({}); const firstEl = React.useRef(); const siblingEl = React.useRef(); const onMouseEnter = e => { const timeStamp = e.timeStamp; setLog(log => { const callCount = 1 + (log.timeStamp === timeStamp ? log.callCount : 0); return { timeStamp, callCount, }; }); }; return ( <React.Fragment> <div ref={firstEl} onMouseEnter={onMouseEnter} style={{ border: '1px solid #d9d9d9', padding: '20px 20px', }}> Mouse enter call count: {log.callCount || ''} </div> <div ref={siblingEl} /> </React.Fragment> ); }; export default MouseEnter;
23.108108
78
0.5659
Penetration-Testing-Study-Notes
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core * @jest-environment node */ 'use strict'; const React = require('react'); const {startTransition, useDeferredValue} = React; const ReactNoop = require('react-noop-renderer'); const { waitFor, waitForAll, waitForPaint, waitForThrow, assertLog, } = require('internal-test-utils'); const act = require('internal-test-utils').act; const Scheduler = require('scheduler/unstable_mock'); describe('ReactInternalTestUtils', () => { test('waitFor', async () => { const Yield = ({id}) => { Scheduler.log(id); return id; }; const root = ReactNoop.createRoot(); startTransition(() => { root.render( <div> <Yield id="foo" /> <Yield id="bar" /> <Yield id="baz" /> </div> ); }); await waitFor(['foo', 'bar']); expect(root).toMatchRenderedOutput(null); await waitFor(['baz']); expect(root).toMatchRenderedOutput(null); await waitForAll([]); expect(root).toMatchRenderedOutput(<div>foobarbaz</div>); }); test('waitForAll', async () => { const Yield = ({id}) => { Scheduler.log(id); return id; }; const root = ReactNoop.createRoot(); startTransition(() => { root.render( <div> <Yield id="foo" /> <Yield id="bar" /> <Yield id="baz" /> </div> ); }); await waitForAll(['foo', 'bar', 'baz']); expect(root).toMatchRenderedOutput(<div>foobarbaz</div>); }); test('waitForThrow', async () => { const Yield = ({id}) => { Scheduler.log(id); return id; }; function BadRender() { throw new Error('Oh no!'); } function App() { return ( <div> <Yield id="A" /> <Yield id="B" /> <BadRender /> <Yield id="C" /> <Yield id="D" /> </div> ); } const root = ReactNoop.createRoot(); root.render(<App />); await waitForThrow('Oh no!'); assertLog([ 'A', 'B', // React will try one more time before giving up. 'A', 'B', ]); }); test('waitForPaint', async () => { function App({prop}) { const deferred = useDeferredValue(prop); const text = `Urgent: ${prop}, Deferred: ${deferred}`; Scheduler.log(text); return text; } const root = ReactNoop.createRoot(); root.render(<App prop="A" />); await waitForAll(['Urgent: A, Deferred: A']); expect(root).toMatchRenderedOutput('Urgent: A, Deferred: A'); // This update will result in two separate paints: an urgent one, and a // deferred one. root.render(<App prop="B" />); // Urgent paint await waitForPaint(['Urgent: B, Deferred: A']); expect(root).toMatchRenderedOutput('Urgent: B, Deferred: A'); // Deferred paint await waitForPaint(['Urgent: B, Deferred: B']); expect(root).toMatchRenderedOutput('Urgent: B, Deferred: B'); }); test('assertLog', async () => { const Yield = ({id}) => { Scheduler.log(id); return id; }; function App() { return ( <div> <Yield id="A" /> <Yield id="B" /> <Yield id="C" /> </div> ); } const root = ReactNoop.createRoot(); await act(() => { root.render(<App />); }); assertLog(['A', 'B', 'C']); }); });
21.745223
75
0.539776
Python-Penetration-Testing-for-Developers
let React; let ReactNoop; let Scheduler; let act; let assertLog; describe('ReactClassSetStateCallback', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); act = require('internal-test-utils').act; const InternalTestUtils = require('internal-test-utils'); assertLog = InternalTestUtils.assertLog; }); function Text({text}) { Scheduler.log(text); return text; } test('regression: setState callback (2nd arg) should only fire once, even after a rebase', async () => { let app; class App extends React.Component { state = {step: 0}; render() { app = this; return <Text text={this.state.step} />; } } const root = ReactNoop.createRoot(); await act(() => { root.render(<App />); }); assertLog([0]); await act(() => { if (gate(flags => flags.enableUnifiedSyncLane)) { React.startTransition(() => { app.setState({step: 1}, () => Scheduler.log('Callback 1')); }); } else { app.setState({step: 1}, () => Scheduler.log('Callback 1')); } ReactNoop.flushSync(() => { app.setState({step: 2}, () => Scheduler.log('Callback 2')); }); }); assertLog([2, 'Callback 2', 2, 'Callback 1']); }); });
23.75
106
0.566065
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = useTheme; exports.ThemeContext = void 0; var _react = require("react"); /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ const ThemeContext = /*#__PURE__*/(0, _react.createContext)('bright'); exports.ThemeContext = ThemeContext; function useTheme() { const theme = (0, _react.useContext)(ThemeContext); (0, _react.useDebugValue)(theme); return theme; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInVzZVRoZW1lLmpzIl0sIm5hbWVzIjpbIlRoZW1lQ29udGV4dCIsInVzZVRoZW1lIiwidGhlbWUiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7O0FBU0E7O0FBVEE7Ozs7Ozs7O0FBV08sTUFBTUEsWUFBWSxnQkFBRywwQkFBYyxRQUFkLENBQXJCOzs7QUFFUSxTQUFTQyxRQUFULEdBQW9CO0FBQ2pDLFFBQU1DLEtBQUssR0FBRyx1QkFBV0YsWUFBWCxDQUFkO0FBQ0EsNEJBQWNFLEtBQWQ7QUFDQSxTQUFPQSxLQUFQO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IHtjcmVhdGVDb250ZXh0LCB1c2VDb250ZXh0LCB1c2VEZWJ1Z1ZhbHVlfSBmcm9tICdyZWFjdCc7XG5cbmV4cG9ydCBjb25zdCBUaGVtZUNvbnRleHQgPSBjcmVhdGVDb250ZXh0KCdicmlnaHQnKTtcblxuZXhwb3J0IGRlZmF1bHQgZnVuY3Rpb24gdXNlVGhlbWUoKSB7XG4gIGNvbnN0IHRoZW1lID0gdXNlQ29udGV4dChUaGVtZUNvbnRleHQpO1xuICB1c2VEZWJ1Z1ZhbHVlKHRoZW1lKTtcbiAgcmV0dXJuIHRoZW1lO1xufVxuIl0sInhfZmFjZWJvb2tfc291cmNlcyI6W1tudWxsLFt7Im5hbWVzIjpbIjxuby1ob29rPiIsInRoZW1lIl0sIm1hcHBpbmdzIjoiQ0FBRDtlZ0JDQSxBd0JEQSJ9XV1dfX1dfQ==
68.703704
1,272
0.89261
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; module.exports = { meta: { schema: [], }, create(context) { return { Identifier(node) { if (node.name === 'toWarnDev' || node.name === 'toErrorDev') { let current = node; while (current.parent) { if (current.type === 'CallExpression') { if ( current && current.callee && current.callee.property && current.callee.property.name === 'toThrow' ) { context.report( node, node.name + '() matcher should not be nested' ); } } current = current.parent; } } }, }; }, };
22.404762
70
0.464358
Hands-On-Penetration-Testing-with-Python
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ /** * WARNING: * This file contains types that are designed for React DevTools UI and how it interacts with the backend. * They might be used in different versions of DevTools backends. * Be mindful of backwards compatibility when making changes. */ import type {Source} from 'shared/ReactElementType'; import type { Dehydrated, Unserializable, } from 'react-devtools-shared/src/hydration'; export type BrowserTheme = 'dark' | 'light'; export type Wall = { // `listen` returns the "unlisten" function. listen: (fn: Function) => Function, send: (event: string, payload: any, transferable?: Array<any>) => void, }; // WARNING // The values below are referenced by ComponentFilters (which are saved via localStorage). // Do not change them or it will break previously saved user customizations. // If new element types are added, use new numbers rather than re-ordering existing ones. // // Changing these types is also a backwards breaking change for the standalone shell, // since the frontend and backend must share the same values- // and the backend is embedded in certain environments (like React Native). export const ElementTypeClass = 1; export const ElementTypeContext = 2; export const ElementTypeFunction = 5; export const ElementTypeForwardRef = 6; export const ElementTypeHostComponent = 7; export const ElementTypeMemo = 8; export const ElementTypeOtherOrUnknown = 9; export const ElementTypeProfiler = 10; export const ElementTypeRoot = 11; export const ElementTypeSuspense = 12; export const ElementTypeSuspenseList = 13; export const ElementTypeTracingMarker = 14; // Different types of elements displayed in the Elements tree. // These types may be used to visually distinguish types, // or to enable/disable certain functionality. export type ElementType = 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14; // WARNING // The values below are referenced by ComponentFilters (which are saved via localStorage). // Do not change them or it will break previously saved user customizations. // If new filter types are added, use new numbers rather than re-ordering existing ones. export const ComponentFilterElementType = 1; export const ComponentFilterDisplayName = 2; export const ComponentFilterLocation = 3; export const ComponentFilterHOC = 4; export type ComponentFilterType = 1 | 2 | 3 | 4; // Hide all elements of types in this Set. // We hide host components only by default. export type ElementTypeComponentFilter = { isEnabled: boolean, type: 1, value: ElementType, }; // Hide all elements with displayNames or paths matching one or more of the RegExps in this Set. // Path filters are only used when elements include debug source location. export type RegExpComponentFilter = { isEnabled: boolean, isValid: boolean, type: 2 | 3, value: string, }; export type BooleanComponentFilter = { isEnabled: boolean, isValid: boolean, type: 4, }; export type ComponentFilter = | BooleanComponentFilter | ElementTypeComponentFilter | RegExpComponentFilter; export type HookName = string | null; // Map of hook source ("<filename>:<line-number>:<column-number>") to name. // Hook source is used instead of the hook itself because the latter is not stable between element inspections. // We use a Map rather than an Array because of nested hooks and traversal ordering. export type HookSourceLocationKey = string; export type HookNames = Map<HookSourceLocationKey, HookName>; export type LRUCache<K, V> = { del: (key: K) => void, get: (key: K) => V, has: (key: K) => boolean, reset: () => void, set: (key: K, value: V) => void, }; export type StyleXPlugin = { sources: Array<string>, resolvedStyles: Object, }; export type Plugins = { stylex: StyleXPlugin | null, }; export const StrictMode = 1; // Each element on the frontend corresponds to a Fiber on the backend. // Some of its information (e.g. id, type, displayName) come from the backend. // Other bits (e.g. weight and depth) are computed on the frontend for windowing and display purposes. // Elements are updated on a push basis– meaning the backend pushes updates to the frontend when needed. export type Element = { id: number, parentID: number, children: Array<number>, type: ElementType, displayName: string | null, key: number | string | null, hocDisplayNames: null | Array<string>, // Should the elements children be visible in the tree? isCollapsed: boolean, // Owner (if available) ownerID: number, // How many levels deep within the tree is this element? // This determines how much indentation (left padding) should be used in the Elements tree. depth: number, // How many nodes (including itself) are below this Element within the tree. // This property is used to quickly determine the total number of Elements, // and the Element at any given index (for windowing purposes). weight: number, // This element is not in a StrictMode compliant subtree. // Only true for React versions supporting StrictMode. isStrictModeNonCompliant: boolean, // If component is compiled with Forget, the backend will send its name as Forget(...) // Later, on the frontend side, we will strip HOC names and Forget prefix. compiledWithForget: boolean, }; export type SerializedElement = { displayName: string | null, id: number, key: number | string | null, hocDisplayNames: Array<string> | null, compiledWithForget: boolean, type: ElementType, }; export type OwnersList = { id: number, owners: Array<SerializedElement> | null, }; export type InspectedElementResponseType = | 'error' | 'full-data' | 'hydrated-path' | 'no-change' | 'not-found'; export type InspectedElementPath = Array<string | number>; export type InspectedElement = { id: number, // Does the current renderer support editable hooks and function props? canEditHooks: boolean, canEditFunctionProps: boolean, // Does the current renderer support advanced editing interface? canEditHooksAndDeletePaths: boolean, canEditHooksAndRenamePaths: boolean, canEditFunctionPropsDeletePaths: boolean, canEditFunctionPropsRenamePaths: boolean, // Is this Error, and can its value be overridden now? isErrored: boolean, canToggleError: boolean, targetErrorBoundaryID: ?number, // Is this Suspense, and can its value be overridden now? canToggleSuspense: boolean, // Can view component source location. canViewSource: boolean, // Does the component have legacy context attached to it. hasLegacyContext: boolean, // Inspectable properties. context: Object | null, hooks: Object | null, props: Object | null, state: Object | null, key: number | string | null, errors: Array<[string, number]>, warnings: Array<[string, number]>, // List of owners owners: Array<SerializedElement> | null, // Location of component in source code. source: Source | null, type: ElementType, // Meta information about the root this element belongs to. rootType: string | null, // Meta information about the renderer that created this element. rendererPackageName: string | null, rendererVersion: string | null, // UI plugins/visualizations for the inspected element. plugins: Plugins, }; // TODO: Add profiling type type Data = | string | Dehydrated | Unserializable | Array<Dehydrated> | Array<Unserializable> | {[string]: Data}; export type DehydratedData = { cleaned: Array<Array<string | number>>, data: Data, unserializable: Array<Array<string | number>>, };
29.561265
111
0.733928
Penetration-Testing-Study-Notes
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ export * from './src/index';
23.666667
66
0.696833
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from './src/ReactFiberReconciler';
21.636364
66
0.697581
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Rect} from './geometry'; import type {View} from './View'; export type LayoutInfo = {view: View, frame: Rect}; export type Layout = LayoutInfo[]; /** * A function that takes a list of subviews, currently laid out in * `existingLayout`, and lays them out into `containingFrame`. */ export type Layouter = ( existingLayout: Layout, containingFrame: Rect, ) => Layout; function viewToLayoutInfo(view: View): LayoutInfo { return {view, frame: view.frame}; } export function viewsToLayout(views: View[]): Layout { return views.map(viewToLayoutInfo); } /** * Applies `layout`'s `frame`s to its corresponding `view`. */ export function collapseLayoutIntoViews(layout: Layout) { layout.forEach(({view, frame}) => view.setFrame(frame)); } /** * A no-operation layout; does not modify the layout. */ export const noopLayout: Layouter = layout => layout; /** * Layer views on top of each other. All views' frames will be set to `containerFrame`. * * Equivalent to composing: * - `alignToContainerXLayout`, * - `alignToContainerYLayout`, * - `containerWidthLayout`, and * - `containerHeightLayout`. */ export const layeredLayout: Layouter = (layout, containerFrame) => { return layout.map(layoutInfo => ({...layoutInfo, frame: containerFrame})); }; /** * Stacks `views` vertically in `frame`. * All views in `views` will have their widths set to the frame's width. */ export const verticallyStackedLayout: Layouter = (layout, containerFrame) => { let currentY = containerFrame.origin.y; return layout.map(layoutInfo => { const desiredSize = layoutInfo.view.desiredSize(); const height = desiredSize ? desiredSize.height : containerFrame.origin.y + containerFrame.size.height - currentY; const proposedFrame = { origin: {x: containerFrame.origin.x, y: currentY}, size: {width: containerFrame.size.width, height}, }; currentY += height; return { ...layoutInfo, frame: proposedFrame, }; }); }; /** * A layouter that aligns all frames' lefts to the container frame's left. */ export const alignToContainerXLayout: Layouter = (layout, containerFrame) => { return layout.map(layoutInfo => ({ ...layoutInfo, frame: { origin: { x: containerFrame.origin.x, y: layoutInfo.frame.origin.y, }, size: layoutInfo.frame.size, }, })); }; /** * A layouter that aligns all frames' tops to the container frame's top. */ export const alignToContainerYLayout: Layouter = (layout, containerFrame) => { return layout.map(layoutInfo => ({ ...layoutInfo, frame: { origin: { x: layoutInfo.frame.origin.x, y: containerFrame.origin.y, }, size: layoutInfo.frame.size, }, })); }; /** * A layouter that sets all frames' widths to `containerFrame.size.width`. */ export const containerWidthLayout: Layouter = (layout, containerFrame) => { return layout.map(layoutInfo => ({ ...layoutInfo, frame: { origin: layoutInfo.frame.origin, size: { width: containerFrame.size.width, height: layoutInfo.frame.size.height, }, }, })); }; /** * A layouter that sets all frames' heights to `containerFrame.size.height`. */ export const containerHeightLayout: Layouter = (layout, containerFrame) => { return layout.map(layoutInfo => ({ ...layoutInfo, frame: { origin: layoutInfo.frame.origin, size: { width: layoutInfo.frame.size.width, height: containerFrame.size.height, }, }, })); }; /** * A layouter that sets all frames' heights to the desired height of its view. * If the view has no desired size, the frame's height is set to 0. */ export const desiredHeightLayout: Layouter = layout => { return layout.map(layoutInfo => { const desiredSize = layoutInfo.view.desiredSize(); const height = desiredSize ? desiredSize.height : 0; return { ...layoutInfo, frame: { origin: layoutInfo.frame.origin, size: { width: layoutInfo.frame.size.width, height, }, }, }; }); }; /** * A layouter that sets all frames' heights to the height of the tallest frame. */ export const uniformMaxSubviewHeightLayout: Layouter = layout => { const maxHeight = Math.max( ...layout.map(layoutInfo => layoutInfo.frame.size.height), ); return layout.map(layoutInfo => ({ ...layoutInfo, frame: { origin: layoutInfo.frame.origin, size: { width: layoutInfo.frame.size.width, height: maxHeight, }, }, })); }; /** * A layouter that sets heights in this fashion: * - If a frame's height >= `containerFrame.size.height`, the frame is left unchanged. * - Otherwise, sets the frame's height to `containerFrame.size.height`. */ export const atLeastContainerHeightLayout: Layouter = ( layout, containerFrame, ) => { return layout.map(layoutInfo => ({ ...layoutInfo, frame: { origin: layoutInfo.frame.origin, size: { width: layoutInfo.frame.size.width, height: Math.max( containerFrame.size.height, layoutInfo.frame.size.height, ), }, }, })); }; /** * Create a layouter that applies each layouter in `layouters` in sequence. */ export function createComposedLayout(...layouters: Layouter[]): Layouter { if (layouters.length === 0) { return noopLayout; } const composedLayout: Layouter = (layout, containerFrame) => { return layouters.reduce( (intermediateLayout, layouter) => layouter(intermediateLayout, containerFrame), layout, ); }; return composedLayout; }
25.022124
87
0.647959
Hands-On-Penetration-Testing-with-Python
/** * Install the hook on window, which is an event emitter. * Note: this global hook __REACT_DEVTOOLS_GLOBAL_HOOK__ is a de facto public API. * It's especially important to avoid creating direct dependency on the DevTools Backend. * That's why we still inline the whole event emitter implementation, * the string format implementation, and part of the console implementation here. * * @flow */ import type {BrowserTheme} from './frontend/types'; import type { DevToolsHook, Handler, ReactRenderer, RendererID, RendererInterface, DevToolsBackend, } from './backend/types'; declare var window: any; export function installHook(target: any): DevToolsHook | null { if (target.hasOwnProperty('__REACT_DEVTOOLS_GLOBAL_HOOK__')) { return null; } let targetConsole: Object = console; let targetConsoleMethods: {[string]: $FlowFixMe} = {}; for (const method in console) { targetConsoleMethods[method] = console[method]; } function dangerous_setTargetConsoleForTesting( targetConsoleForTesting: Object, ): void { targetConsole = targetConsoleForTesting; targetConsoleMethods = ({}: {[string]: $FlowFixMe}); for (const method in targetConsole) { targetConsoleMethods[method] = console[method]; } } function detectReactBuildType(renderer: ReactRenderer) { try { if (typeof renderer.version === 'string') { // React DOM Fiber (16+) if (renderer.bundleType > 0) { // This is not a production build. // We are currently only using 0 (PROD) and 1 (DEV) // but might add 2 (PROFILE) in the future. return 'development'; } // React 16 uses flat bundles. If we report the bundle as production // version, it means we also minified and envified it ourselves. return 'production'; // Note: There is still a risk that the CommonJS entry point has not // been envified or uglified. In this case the user would have *both* // development and production bundle, but only the prod one would run. // This would be really bad. We have a separate check for this because // it happens *outside* of the renderer injection. See `checkDCE` below. } // $FlowFixMe[method-unbinding] const toString = Function.prototype.toString; if (renderer.Mount && renderer.Mount._renderNewRootComponent) { // React DOM Stack const renderRootCode = toString.call( renderer.Mount._renderNewRootComponent, ); // Filter out bad results (if that is even possible): if (renderRootCode.indexOf('function') !== 0) { // Hope for the best if we're not sure. return 'production'; } // Check for React DOM Stack < 15.1.0 in development. // If it contains "storedMeasure" call, it's wrapped in ReactPerf (DEV only). // This would be true even if it's minified, as method name still matches. if (renderRootCode.indexOf('storedMeasure') !== -1) { return 'development'; } // For other versions (and configurations) it's not so easy. // Let's quickly exclude proper production builds. // If it contains a warning message, it's either a DEV build, // or an PROD build without proper dead code elimination. if (renderRootCode.indexOf('should be a pure function') !== -1) { // Now how do we tell a DEV build from a bad PROD build? // If we see NODE_ENV, we're going to assume this is a dev build // because most likely it is referring to an empty shim. if (renderRootCode.indexOf('NODE_ENV') !== -1) { return 'development'; } // If we see "development", we're dealing with an envified DEV build // (such as the official React DEV UMD). if (renderRootCode.indexOf('development') !== -1) { return 'development'; } // I've seen process.env.NODE_ENV !== 'production' being smartly // replaced by `true` in DEV by Webpack. I don't know how that // works but we can safely guard against it because `true` was // never used in the function source since it was written. if (renderRootCode.indexOf('true') !== -1) { return 'development'; } // By now either it is a production build that has not been minified, // or (worse) this is a minified development build using non-standard // environment (e.g. "staging"). We're going to look at whether // the function argument name is mangled: if ( // 0.13 to 15 renderRootCode.indexOf('nextElement') !== -1 || // 0.12 renderRootCode.indexOf('nextComponent') !== -1 ) { // We can't be certain whether this is a development build or not, // but it is definitely unminified. return 'unminified'; } else { // This is likely a minified development build. return 'development'; } } // By now we know that it's envified and dead code elimination worked, // but what if it's still not minified? (Is this even possible?) // Let's check matches for the first argument name. if ( // 0.13 to 15 renderRootCode.indexOf('nextElement') !== -1 || // 0.12 renderRootCode.indexOf('nextComponent') !== -1 ) { return 'unminified'; } // Seems like we're using the production version. // However, the branch above is Stack-only so this is 15 or earlier. return 'outdated'; } } catch (err) { // Weird environments may exist. // This code needs a higher fault tolerance // because it runs even with closed DevTools. // TODO: should we catch errors in all injected code, and not just this part? } return 'production'; } function checkDCE(fn: Function) { // This runs for production versions of React. // Needs to be super safe. try { // $FlowFixMe[method-unbinding] const toString = Function.prototype.toString; const code = toString.call(fn); // This is a string embedded in the passed function under DEV-only // condition. However the function executes only in PROD. Therefore, // if we see it, dead code elimination did not work. if (code.indexOf('^_^') > -1) { // Remember to report during next injection. hasDetectedBadDCE = true; // Bonus: throw an exception hoping that it gets picked up by a reporting system. // Not synchronously so that it doesn't break the calling code. setTimeout(function () { throw new Error( 'React is running in production mode, but dead code ' + 'elimination has not been applied. Read how to correctly ' + 'configure React for production: ' + 'https://reactjs.org/link/perf-use-production-build', ); }); } } catch (err) {} } // NOTE: KEEP IN SYNC with src/backend/utils.js function formatWithStyles( inputArgs: $ReadOnlyArray<any>, style?: string, ): $ReadOnlyArray<any> { if ( inputArgs === undefined || inputArgs === null || inputArgs.length === 0 || // Matches any of %c but not %%c (typeof inputArgs[0] === 'string' && inputArgs[0].match(/([^%]|^)(%c)/g)) || style === undefined ) { return inputArgs; } // Matches any of %(o|O|d|i|s|f), but not %%(o|O|d|i|s|f) const REGEXP = /([^%]|^)((%%)*)(%([oOdisf]))/g; if (typeof inputArgs[0] === 'string' && inputArgs[0].match(REGEXP)) { return [`%c${inputArgs[0]}`, style, ...inputArgs.slice(1)]; } else { const firstArg = inputArgs.reduce((formatStr, elem, i) => { if (i > 0) { formatStr += ' '; } switch (typeof elem) { case 'string': case 'boolean': case 'symbol': return (formatStr += '%s'); case 'number': const formatting = Number.isInteger(elem) ? '%i' : '%f'; return (formatStr += formatting); default: return (formatStr += '%o'); } }, '%c'); return [firstArg, style, ...inputArgs]; } } let unpatchFn = null; // NOTE: KEEP IN SYNC with src/backend/console.js:patchForStrictMode // This function hides or dims console logs during the initial double renderer // in Strict Mode. We need this function because during initial render, // React and DevTools are connecting and the renderer interface isn't avaiable // and we want to be able to have consistent logging behavior for double logs // during the initial renderer. function patchConsoleForInitialRenderInStrictMode({ hideConsoleLogsInStrictMode, browserTheme, }: { hideConsoleLogsInStrictMode: boolean, browserTheme: BrowserTheme, }) { const overrideConsoleMethods = [ 'error', 'group', 'groupCollapsed', 'info', 'log', 'trace', 'warn', ]; if (unpatchFn !== null) { // Don't patch twice. return; } const originalConsoleMethods: {[string]: $FlowFixMe} = {}; unpatchFn = () => { for (const method in originalConsoleMethods) { try { targetConsole[method] = originalConsoleMethods[method]; } catch (error) {} } }; overrideConsoleMethods.forEach(method => { try { const originalMethod = (originalConsoleMethods[method] = targetConsole[ method ].__REACT_DEVTOOLS_STRICT_MODE_ORIGINAL_METHOD__ ? targetConsole[method].__REACT_DEVTOOLS_STRICT_MODE_ORIGINAL_METHOD__ : targetConsole[method]); const overrideMethod = (...args: $ReadOnlyArray<any>) => { if (!hideConsoleLogsInStrictMode) { // Dim the text color of the double logs if we're not // hiding them. let color; switch (method) { case 'warn': color = browserTheme === 'light' ? process.env.LIGHT_MODE_DIMMED_WARNING_COLOR : process.env.DARK_MODE_DIMMED_WARNING_COLOR; break; case 'error': color = browserTheme === 'light' ? process.env.LIGHT_MODE_DIMMED_ERROR_COLOR : process.env.DARK_MODE_DIMMED_ERROR_COLOR; break; case 'log': default: color = browserTheme === 'light' ? process.env.LIGHT_MODE_DIMMED_LOG_COLOR : process.env.DARK_MODE_DIMMED_LOG_COLOR; break; } if (color) { originalMethod(...formatWithStyles(args, `color: ${color}`)); } else { throw Error('Console color is not defined'); } } }; overrideMethod.__REACT_DEVTOOLS_STRICT_MODE_ORIGINAL_METHOD__ = originalMethod; originalMethod.__REACT_DEVTOOLS_STRICT_MODE_OVERRIDE_METHOD__ = overrideMethod; targetConsole[method] = overrideMethod; } catch (error) {} }); } // NOTE: KEEP IN SYNC with src/backend/console.js:unpatchForStrictMode function unpatchConsoleForInitialRenderInStrictMode() { if (unpatchFn !== null) { unpatchFn(); unpatchFn = null; } } let uidCounter = 0; function inject(renderer: ReactRenderer): number { const id = ++uidCounter; renderers.set(id, renderer); const reactBuildType = hasDetectedBadDCE ? 'deadcode' : detectReactBuildType(renderer); // Patching the console enables DevTools to do a few useful things: // * Append component stacks to warnings and error messages // * Disabling or marking logs during a double render in Strict Mode // * Disable logging during re-renders to inspect hooks (see inspectHooksOfFiber) // // Allow patching console early (during injection) to // provide developers with components stacks even if they don't run DevTools. if (target.hasOwnProperty('__REACT_DEVTOOLS_CONSOLE_FUNCTIONS__')) { const {registerRendererWithConsole, patchConsoleUsingWindowValues} = target.__REACT_DEVTOOLS_CONSOLE_FUNCTIONS__; if ( typeof registerRendererWithConsole === 'function' && typeof patchConsoleUsingWindowValues === 'function' ) { registerRendererWithConsole(renderer); patchConsoleUsingWindowValues(); } } // If we have just reloaded to profile, we need to inject the renderer interface before the app loads. // Otherwise the renderer won't yet exist and we can skip this step. const attach = target.__REACT_DEVTOOLS_ATTACH__; if (typeof attach === 'function') { const rendererInterface = attach(hook, id, renderer, target); hook.rendererInterfaces.set(id, rendererInterface); } hook.emit('renderer', { id, renderer, reactBuildType, }); return id; } let hasDetectedBadDCE = false; function sub(event: string, fn: Handler) { hook.on(event, fn); return () => hook.off(event, fn); } function on(event: string, fn: Handler) { if (!listeners[event]) { listeners[event] = []; } listeners[event].push(fn); } function off(event: string, fn: Handler) { if (!listeners[event]) { return; } const index = listeners[event].indexOf(fn); if (index !== -1) { listeners[event].splice(index, 1); } if (!listeners[event].length) { delete listeners[event]; } } function emit(event: string, data: any) { if (listeners[event]) { listeners[event].map(fn => fn(data)); } } function getFiberRoots(rendererID: RendererID) { const roots = fiberRoots; if (!roots[rendererID]) { roots[rendererID] = new Set(); } return roots[rendererID]; } function onCommitFiberUnmount(rendererID: RendererID, fiber: any) { const rendererInterface = rendererInterfaces.get(rendererID); if (rendererInterface != null) { rendererInterface.handleCommitFiberUnmount(fiber); } } function onCommitFiberRoot( rendererID: RendererID, root: any, priorityLevel: void | number, ) { const mountedRoots = hook.getFiberRoots(rendererID); const current = root.current; const isKnownRoot = mountedRoots.has(root); const isUnmounting = current.memoizedState == null || current.memoizedState.element == null; // Keep track of mounted roots so we can hydrate when DevTools connect. if (!isKnownRoot && !isUnmounting) { mountedRoots.add(root); } else if (isKnownRoot && isUnmounting) { mountedRoots.delete(root); } const rendererInterface = rendererInterfaces.get(rendererID); if (rendererInterface != null) { rendererInterface.handleCommitFiberRoot(root, priorityLevel); } } function onPostCommitFiberRoot(rendererID: RendererID, root: any) { const rendererInterface = rendererInterfaces.get(rendererID); if (rendererInterface != null) { rendererInterface.handlePostCommitFiberRoot(root); } } function setStrictMode(rendererID: RendererID, isStrictMode: any) { const rendererInterface = rendererInterfaces.get(rendererID); if (rendererInterface != null) { if (isStrictMode) { rendererInterface.patchConsoleForStrictMode(); } else { rendererInterface.unpatchConsoleForStrictMode(); } } else { // This should only happen during initial render in the extension before DevTools // finishes its handshake with the injected renderer if (isStrictMode) { const hideConsoleLogsInStrictMode = window.__REACT_DEVTOOLS_HIDE_CONSOLE_LOGS_IN_STRICT_MODE__ === true; const browserTheme = window.__REACT_DEVTOOLS_BROWSER_THEME__; patchConsoleForInitialRenderInStrictMode({ hideConsoleLogsInStrictMode, browserTheme, }); } else { unpatchConsoleForInitialRenderInStrictMode(); } } } type StackFrameString = string; const openModuleRangesStack: Array<StackFrameString> = []; const moduleRanges: Array<[StackFrameString, StackFrameString]> = []; function getTopStackFrameString(error: Error): StackFrameString | null { const frames = error.stack.split('\n'); const frame = frames.length > 1 ? frames[1] : null; return frame; } function getInternalModuleRanges(): Array< [StackFrameString, StackFrameString], > { return moduleRanges; } function registerInternalModuleStart(error: Error) { const startStackFrame = getTopStackFrameString(error); if (startStackFrame !== null) { openModuleRangesStack.push(startStackFrame); } } function registerInternalModuleStop(error: Error) { if (openModuleRangesStack.length > 0) { const startStackFrame = openModuleRangesStack.pop(); const stopStackFrame = getTopStackFrameString(error); if (stopStackFrame !== null) { moduleRanges.push([startStackFrame, stopStackFrame]); } } } // TODO: More meaningful names for "rendererInterfaces" and "renderers". const fiberRoots: {[RendererID]: Set<mixed>} = {}; const rendererInterfaces = new Map<RendererID, RendererInterface>(); const listeners: {[string]: Array<Handler>} = {}; const renderers = new Map<RendererID, ReactRenderer>(); const backends = new Map<string, DevToolsBackend>(); const hook: DevToolsHook = { rendererInterfaces, listeners, backends, // Fast Refresh for web relies on this. renderers, emit, getFiberRoots, inject, on, off, sub, // This is a legacy flag. // React v16 checks the hook for this to ensure DevTools is new enough. supportsFiber: true, // React calls these methods. checkDCE, onCommitFiberUnmount, onCommitFiberRoot, onPostCommitFiberRoot, setStrictMode, // Schedule Profiler runtime helpers. // These internal React modules to report their own boundaries // which in turn enables the profiler to dim or filter internal frames. getInternalModuleRanges, registerInternalModuleStart, registerInternalModuleStop, }; if (__TEST__) { hook.dangerous_setTargetConsoleForTesting = dangerous_setTargetConsoleForTesting; } Object.defineProperty( target, '__REACT_DEVTOOLS_GLOBAL_HOOK__', ({ // This property needs to be configurable for the test environment, // else we won't be able to delete and recreate it between tests. configurable: __DEV__, enumerable: false, get() { return hook; }, }: Object), ); return hook; }
32.508803
106
0.61922
cybersecurity-penetration-testing
const {resolve} = require('path'); const Webpack = require('webpack'); const WebpackDevServer = require('webpack-dev-server'); const fs = require('fs'); const { DARK_MODE_DIMMED_WARNING_COLOR, DARK_MODE_DIMMED_ERROR_COLOR, DARK_MODE_DIMMED_LOG_COLOR, LIGHT_MODE_DIMMED_WARNING_COLOR, LIGHT_MODE_DIMMED_ERROR_COLOR, LIGHT_MODE_DIMMED_LOG_COLOR, GITHUB_URL, getVersionString, } = require('react-devtools-extensions/utils'); const {resolveFeatureFlags} = require('react-devtools-shared/buildUtils'); const semver = require('semver'); const {SUCCESSFUL_COMPILATION_MESSAGE} = require('./constants'); const ReactVersionSrc = fs.readFileSync(require.resolve('shared/ReactVersion')); const currentReactVersion = /export default '([^']+)';/.exec( ReactVersionSrc, )[1]; const NODE_ENV = process.env.NODE_ENV; if (!NODE_ENV) { console.error('NODE_ENV not set'); process.exit(1); } const EDITOR_URL = process.env.EDITOR_URL || null; const builtModulesDir = resolve( __dirname, '..', '..', 'build', 'oss-experimental', ); const __DEV__ = NODE_ENV === 'development'; const DEVTOOLS_VERSION = getVersionString(); // If the React version isn't set, we will use the // current React version instead. Likewise if the // React version isnt' set, we'll use the build folder // for both React DevTools and React const REACT_VERSION = process.env.REACT_VERSION ? semver.coerce(process.env.REACT_VERSION).version : currentReactVersion; const E2E_APP_BUILD_DIR = process.env.REACT_VERSION ? resolve(__dirname, '..', '..', 'build-regression', 'node_modules') : builtModulesDir; const makeConfig = (entry, alias) => ({ mode: __DEV__ ? 'development' : 'production', devtool: __DEV__ ? 'cheap-source-map' : 'source-map', stats: 'normal', entry, output: { publicPath: '/dist/', }, node: { global: false, }, resolve: { alias, }, optimization: { minimize: false, }, plugins: [ new Webpack.ProvidePlugin({ process: 'process/browser', }), new Webpack.DefinePlugin({ __DEV__, __EXPERIMENTAL__: true, __EXTENSION__: false, __PROFILE__: false, __TEST__: NODE_ENV === 'test', 'process.env.GITHUB_URL': `"${GITHUB_URL}"`, 'process.env.EDITOR_URL': EDITOR_URL != null ? `"${EDITOR_URL}"` : null, 'process.env.DEVTOOLS_PACKAGE': `"react-devtools-shell"`, 'process.env.DEVTOOLS_VERSION': `"${DEVTOOLS_VERSION}"`, 'process.env.DARK_MODE_DIMMED_WARNING_COLOR': `"${DARK_MODE_DIMMED_WARNING_COLOR}"`, 'process.env.DARK_MODE_DIMMED_ERROR_COLOR': `"${DARK_MODE_DIMMED_ERROR_COLOR}"`, 'process.env.DARK_MODE_DIMMED_LOG_COLOR': `"${DARK_MODE_DIMMED_LOG_COLOR}"`, 'process.env.LIGHT_MODE_DIMMED_WARNING_COLOR': `"${LIGHT_MODE_DIMMED_WARNING_COLOR}"`, 'process.env.LIGHT_MODE_DIMMED_ERROR_COLOR': `"${LIGHT_MODE_DIMMED_ERROR_COLOR}"`, 'process.env.LIGHT_MODE_DIMMED_LOG_COLOR': `"${LIGHT_MODE_DIMMED_LOG_COLOR}"`, 'process.env.E2E_APP_REACT_VERSION': `"${REACT_VERSION}"`, }), ], module: { rules: [ { test: /\.js$/, loader: 'babel-loader', options: { configFile: resolve( __dirname, '..', 'react-devtools-shared', 'babel.config.js', ), }, }, { test: /\.css$/, use: [ { loader: 'style-loader', }, { loader: 'css-loader', options: { sourceMap: true, modules: true, localIdentName: '[local]', }, }, ], }, ], }, }); const app = makeConfig( { 'app-index': './src/app/index.js', 'app-devtools': './src/app/devtools.js', 'e2e-app': './src/e2e/app.js', 'e2e-devtools': './src/e2e/devtools.js', 'e2e-devtools-regression': './src/e2e-regression/devtools.js', 'multi-left': './src/multi/left.js', 'multi-devtools': './src/multi/devtools.js', 'multi-right': './src/multi/right.js', 'e2e-regression': './src/e2e-regression/app.js', 'perf-regression-app': './src/perf-regression/app.js', 'perf-regression-devtools': './src/perf-regression/devtools.js', }, { react: resolve(builtModulesDir, 'react'), 'react-debug-tools': resolve(builtModulesDir, 'react-debug-tools'), 'react-devtools-feature-flags': resolveFeatureFlags('shell'), 'react-dom/client': resolve(builtModulesDir, 'react-dom/client'), 'react-dom': resolve(builtModulesDir, 'react-dom/unstable_testing'), 'react-is': resolve(builtModulesDir, 'react-is'), scheduler: resolve(builtModulesDir, 'scheduler'), }, ); // Prior to React 18, we use ReactDOM.render rather than // createRoot. // We also use a separate build folder to build the React App // so that we can test the current DevTools against older version of React const e2eRegressionApp = semver.lt(REACT_VERSION, '18.0.0') ? makeConfig( { 'e2e-app-regression': './src/e2e-regression/app-legacy.js', }, { react: resolve(E2E_APP_BUILD_DIR, 'react'), 'react-dom': resolve(E2E_APP_BUILD_DIR, 'react-dom'), ...(semver.satisfies(REACT_VERSION, '16.5') ? {schedule: resolve(E2E_APP_BUILD_DIR, 'schedule')} : {scheduler: resolve(E2E_APP_BUILD_DIR, 'scheduler')}), }, ) : makeConfig( { 'e2e-app-regression': './src/e2e-regression/app.js', }, { react: resolve(E2E_APP_BUILD_DIR, 'react'), 'react-dom': resolve(E2E_APP_BUILD_DIR, 'react-dom'), 'react-dom/client': resolve(E2E_APP_BUILD_DIR, 'react-dom/client'), scheduler: resolve(E2E_APP_BUILD_DIR, 'scheduler'), }, ); const appCompiler = Webpack(app); const appServer = new WebpackDevServer( { hot: true, open: true, port: 8080, client: { logging: 'warn', }, static: { directory: __dirname, publicPath: '/', }, }, appCompiler, ); const e2eRegressionAppCompiler = Webpack(e2eRegressionApp); const e2eRegressionAppServer = new WebpackDevServer( { port: 8181, client: { logging: 'warn', }, static: { publicPath: '/dist/', }, headers: { 'Access-Control-Allow-Origin': '*', }, }, e2eRegressionAppCompiler, ); const runServer = async () => { console.log('Starting server...'); appServer.compiler.hooks.done.tap('done', () => console.log(SUCCESSFUL_COMPILATION_MESSAGE), ); await e2eRegressionAppServer.start(); await appServer.start(); }; runServer();
27.584416
92
0.606937
PenetrationTestingScripts
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from 'react-client/src/ReactFlightClientConfigBrowser'; export * from 'react-server-dom-webpack/src/ReactFlightClientConfigBundlerWebpack'; export * from 'react-server-dom-webpack/src/ReactFlightClientConfigBundlerWebpackBrowser'; export * from 'react-server-dom-webpack/src/ReactFlightClientConfigTargetWebpackBrowser'; export * from 'react-dom-bindings/src/shared/ReactFlightClientConfigDOM'; export const usedWithSSR = false;
39.1875
90
0.791277
owtf
import Fixture from '../../Fixture'; const React = window.React; class EmailAttributesTestCase extends React.Component { state = {value: 'a@fb.com'}; onChange = event => { this.setState({value: event.target.value}); }; render() { return ( <Fixture> <div>{this.props.children}</div> <div className="control-box"> <fieldset> <legend>Controlled</legend> <input type="email" pattern=".+@fb.com" maxlength={17} multiple={true} value={this.state.value} onChange={this.onChange} /> <span className="hint"> {' '} Value: {JSON.stringify(this.state.value)} </span> </fieldset> <fieldset> <legend>Uncontrolled</legend> <input type="email" defaultValue="" pattern=".+@fb.com" maxlength={17} multiple={true} /> </fieldset> </div> </Fixture> ); } } export default EmailAttributesTestCase;
22.612245
55
0.472318
PenetrationTestingScripts
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ 'use strict'; import {normalizeCodeLocInfo} from './utils'; describe('Timeline profiler', () => { let React; let ReactDOM; let ReactDOMClient; let Scheduler; let utils; let assertLog; let waitFor; describe('User Timing API', () => { let clearedMarks; let featureDetectionMarkName = null; let marks; let setPerformanceMock; function createUserTimingPolyfill() { featureDetectionMarkName = null; clearedMarks = []; marks = []; // Remove file-system specific bits or version-specific bits of information from the module range marks. function filterMarkData(markName) { if (markName.startsWith('--react-internal-module-start')) { return '--react-internal-module-start- at filtered (<anonymous>:0:0)'; } else if (markName.startsWith('--react-internal-module-stop')) { return '--react-internal-module-stop- at filtered (<anonymous>:1:1)'; } else if (markName.startsWith('--react-version')) { return '--react-version-<filtered-version>'; } else { return markName; } } // This is not a true polyfill, but it gives us enough to capture marks. // Reference: https://developer.mozilla.org/en-US/docs/Web/API/User_Timing_API return { clearMarks(markName) { markName = filterMarkData(markName); clearedMarks.push(markName); marks = marks.filter(mark => mark !== markName); }, mark(markName, markOptions) { markName = filterMarkData(markName); if (featureDetectionMarkName === null) { featureDetectionMarkName = markName; } marks.push(markName); if (markOptions != null) { // This is triggers the feature detection. markOptions.startTime++; } }, }; } function clearPendingMarks() { clearedMarks.splice(0); } beforeEach(() => { utils = require('./utils'); utils.beforeEachProfiling(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); Scheduler = require('scheduler'); const InternalTestUtils = require('internal-test-utils'); assertLog = InternalTestUtils.assertLog; waitFor = InternalTestUtils.waitFor; setPerformanceMock = require('react-devtools-shared/src/backend/profilingHooks').setPerformanceMock_ONLY_FOR_TESTING; setPerformanceMock(createUserTimingPolyfill()); const store = global.store; // Start profiling so that data will actually be recorded. utils.act(() => store.profilerStore.startProfiling()); global.IS_REACT_ACT_ENVIRONMENT = true; }); afterEach(() => { // Verify all logged marks also get cleared. expect(marks).toHaveLength(0); setPerformanceMock(null); }); describe('getLanesFromTransportDecimalBitmask', () => { let getLanesFromTransportDecimalBitmask; beforeEach(() => { getLanesFromTransportDecimalBitmask = require('react-devtools-timeline/src/import-worker/preprocessData').getLanesFromTransportDecimalBitmask; }); // @reactVersion >= 18.0 it('should return array of lane numbers from bitmask string', () => { expect(getLanesFromTransportDecimalBitmask('1')).toEqual([0]); expect(getLanesFromTransportDecimalBitmask('512')).toEqual([9]); expect(getLanesFromTransportDecimalBitmask('3')).toEqual([0, 1]); expect(getLanesFromTransportDecimalBitmask('1234')).toEqual([ 1, 4, 6, 7, 10, ]); // 2 + 16 + 64 + 128 + 1024 expect( getLanesFromTransportDecimalBitmask('1073741824'), // 0b1000000000000000000000000000000 ).toEqual([30]); expect( getLanesFromTransportDecimalBitmask('2147483647'), // 0b1111111111111111111111111111111 ).toEqual(Array.from(Array(31).keys())); }); // @reactVersion >= 18.0 it('should return empty array if laneBitmaskString is not a bitmask', () => { expect(getLanesFromTransportDecimalBitmask('')).toEqual([]); expect(getLanesFromTransportDecimalBitmask('hello')).toEqual([]); expect(getLanesFromTransportDecimalBitmask('-1')).toEqual([]); expect(getLanesFromTransportDecimalBitmask('-0')).toEqual([]); }); // @reactVersion >= 18.0 it('should ignore lanes outside REACT_TOTAL_NUM_LANES', () => { const REACT_TOTAL_NUM_LANES = require('react-devtools-timeline/src/constants').REACT_TOTAL_NUM_LANES; // Sanity check; this test may need to be updated when the no. of fiber lanes are changed. expect(REACT_TOTAL_NUM_LANES).toBe(31); expect( getLanesFromTransportDecimalBitmask( '4294967297', // 2^32 + 1 ), ).toEqual([0]); }); }); describe('preprocessData', () => { let preprocessData; beforeEach(() => { preprocessData = require('react-devtools-timeline/src/import-worker/preprocessData').default; }); // These should be dynamic to mimic a real profile, // but reprooducible between test runs. let pid = 0; let tid = 0; let startTime = 0; function createUserTimingEntry(data) { return { pid: ++pid, tid: ++tid, ts: ++startTime, ...data, }; } function createProfilerVersionEntry() { const SCHEDULING_PROFILER_VERSION = require('react-devtools-timeline/src/constants').SCHEDULING_PROFILER_VERSION; return createUserTimingEntry({ cat: 'blink.user_timing', name: '--profiler-version-' + SCHEDULING_PROFILER_VERSION, }); } function createReactVersionEntry() { return createUserTimingEntry({ cat: 'blink.user_timing', name: '--react-version-<filtered-version>', }); } function createLaneLabelsEntry() { return createUserTimingEntry({ cat: 'blink.user_timing', name: '--react-lane-labels-Sync,InputContinuousHydration,InputContinuous,DefaultHydration,Default,TransitionHydration,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Retry,Retry,Retry,Retry,Retry,SelectiveHydration,IdleHydration,Idle,Offscreen', }); } function createNativeEventEntry(type, duration) { return createUserTimingEntry({ cat: 'devtools.timeline', name: 'EventDispatch', args: {data: {type}}, dur: duration, tdur: duration, }); } function creactCpuProfilerSample() { return createUserTimingEntry({ args: {data: {startTime: ++startTime}}, cat: 'disabled-by-default-v8.cpu_profiler', id: '0x1', name: 'Profile', ph: 'P', }); } function createBoilerplateEntries() { return [ createProfilerVersionEntry(), createReactVersionEntry(), createLaneLabelsEntry(), ]; } function createUserTimingData(sampleMarks) { const cpuProfilerSample = creactCpuProfilerSample(); const randomSample = createUserTimingEntry({ dur: 100, tdur: 200, ph: 'X', cat: 'disabled-by-default-devtools.timeline', name: 'RunTask', args: {}, }); const userTimingData = [cpuProfilerSample, randomSample]; sampleMarks.forEach(markName => { userTimingData.push({ pid: ++pid, tid: ++tid, ts: ++startTime, args: {data: {}}, cat: 'blink.user_timing', name: markName, ph: 'R', }); }); return userTimingData; } beforeEach(() => { tid = 0; pid = 0; startTime = 0; }); // @reactVersion >= 18.0 it('should throw given an empty timeline', async () => { await expect(async () => preprocessData([])).rejects.toThrow(); }); // @reactVersion >= 18.0 it('should throw given a timeline with no Profile event', async () => { const randomSample = createUserTimingEntry({ dur: 100, tdur: 200, ph: 'X', cat: 'disabled-by-default-devtools.timeline', name: 'RunTask', args: {}, }); await expect(async () => preprocessData([randomSample]), ).rejects.toThrow(); }); // @reactVersion >= 18.0 it('should throw given a timeline without an explicit profiler version mark nor any other React marks', async () => { const cpuProfilerSample = creactCpuProfilerSample(); await expect( async () => await preprocessData([cpuProfilerSample]), ).rejects.toThrow( 'Please provide profiling data from an React application', ); }); // @reactVersion >= 18.0 it('should throw given a timeline with React scheduling marks, but without an explicit profiler version mark', async () => { const cpuProfilerSample = creactCpuProfilerSample(); const scheduleRenderSample = createUserTimingEntry({ cat: 'blink.user_timing', name: '--schedule-render-512-', }); const samples = [cpuProfilerSample, scheduleRenderSample]; await expect(async () => await preprocessData(samples)).rejects.toThrow( 'This version of profiling data is not supported', ); }); // @reactVersion >= 18.0 it('should return empty data given a timeline with no React scheduling profiling marks', async () => { const cpuProfilerSample = creactCpuProfilerSample(); const randomSample = createUserTimingEntry({ dur: 100, tdur: 200, ph: 'X', cat: 'disabled-by-default-devtools.timeline', name: 'RunTask', args: {}, }); const data = await preprocessData([ ...createBoilerplateEntries(), cpuProfilerSample, randomSample, ]); expect(data).toMatchInlineSnapshot(` { "batchUIDToMeasuresMap": Map {}, "componentMeasures": [], "duration": 0.005, "flamechart": [], "internalModuleSourceToRanges": Map {}, "laneToLabelMap": Map { 0 => "Sync", 1 => "InputContinuousHydration", 2 => "InputContinuous", 3 => "DefaultHydration", 4 => "Default", 5 => "TransitionHydration", 6 => "Transition", 7 => "Transition", 8 => "Transition", 9 => "Transition", 10 => "Transition", 11 => "Transition", 12 => "Transition", 13 => "Transition", 14 => "Transition", 15 => "Transition", 16 => "Transition", 17 => "Transition", 18 => "Transition", 19 => "Transition", 20 => "Transition", 21 => "Transition", 22 => "Retry", 23 => "Retry", 24 => "Retry", 25 => "Retry", 26 => "Retry", 27 => "SelectiveHydration", 28 => "IdleHydration", 29 => "Idle", 30 => "Offscreen", }, "laneToReactMeasureMap": Map { 0 => [], 1 => [], 2 => [], 3 => [], 4 => [], 5 => [], 6 => [], 7 => [], 8 => [], 9 => [], 10 => [], 11 => [], 12 => [], 13 => [], 14 => [], 15 => [], 16 => [], 17 => [], 18 => [], 19 => [], 20 => [], 21 => [], 22 => [], 23 => [], 24 => [], 25 => [], 26 => [], 27 => [], 28 => [], 29 => [], 30 => [], }, "nativeEvents": [], "networkMeasures": [], "otherUserTimingMarks": [], "reactVersion": "<filtered-version>", "schedulingEvents": [], "snapshotHeight": 0, "snapshots": [], "startTime": 1, "suspenseEvents": [], "thrownErrors": [], } `); }); // @reactVersion >= 18.0 it('should process legacy data format (before lane labels were added)', async () => { const cpuProfilerSample = creactCpuProfilerSample(); // Data below is hard-coded based on an older profile sample. // Should be fine since this is explicitly a legacy-format test. const data = await preprocessData([ ...createBoilerplateEntries(), cpuProfilerSample, createUserTimingEntry({ cat: 'blink.user_timing', name: '--schedule-render-512-', }), createUserTimingEntry({ cat: 'blink.user_timing', name: '--render-start-512', }), createUserTimingEntry({ cat: 'blink.user_timing', name: '--render-stop', }), createUserTimingEntry({ cat: 'blink.user_timing', name: '--commit-start-512', }), createUserTimingEntry({ cat: 'blink.user_timing', name: '--layout-effects-start-512', }), createUserTimingEntry({ cat: 'blink.user_timing', name: '--layout-effects-stop', }), createUserTimingEntry({ cat: 'blink.user_timing', name: '--commit-stop', }), ]); expect(data).toMatchInlineSnapshot(` { "batchUIDToMeasuresMap": Map { 0 => [ { "batchUID": 0, "depth": 0, "duration": 0.005, "lanes": "0b0000000000000000000000000001001", "timestamp": 0.006, "type": "render-idle", }, { "batchUID": 0, "depth": 0, "duration": 0.001, "lanes": "0b0000000000000000000000000001001", "timestamp": 0.006, "type": "render", }, { "batchUID": 0, "depth": 0, "duration": 0.003, "lanes": "0b0000000000000000000000000001001", "timestamp": 0.008, "type": "commit", }, { "batchUID": 0, "depth": 1, "duration": 0.001, "lanes": "0b0000000000000000000000000001001", "timestamp": 0.009, "type": "layout-effects", }, ], }, "componentMeasures": [], "duration": 0.011, "flamechart": [], "internalModuleSourceToRanges": Map {}, "laneToLabelMap": Map { 0 => "Sync", 1 => "InputContinuousHydration", 2 => "InputContinuous", 3 => "DefaultHydration", 4 => "Default", 5 => "TransitionHydration", 6 => "Transition", 7 => "Transition", 8 => "Transition", 9 => "Transition", 10 => "Transition", 11 => "Transition", 12 => "Transition", 13 => "Transition", 14 => "Transition", 15 => "Transition", 16 => "Transition", 17 => "Transition", 18 => "Transition", 19 => "Transition", 20 => "Transition", 21 => "Transition", 22 => "Retry", 23 => "Retry", 24 => "Retry", 25 => "Retry", 26 => "Retry", 27 => "SelectiveHydration", 28 => "IdleHydration", 29 => "Idle", 30 => "Offscreen", }, "laneToReactMeasureMap": Map { 0 => [], 1 => [], 2 => [], 3 => [], 4 => [], 5 => [], 6 => [], 7 => [], 8 => [], 9 => [ { "batchUID": 0, "depth": 0, "duration": 0.005, "lanes": "0b0000000000000000000000000001001", "timestamp": 0.006, "type": "render-idle", }, { "batchUID": 0, "depth": 0, "duration": 0.001, "lanes": "0b0000000000000000000000000001001", "timestamp": 0.006, "type": "render", }, { "batchUID": 0, "depth": 0, "duration": 0.003, "lanes": "0b0000000000000000000000000001001", "timestamp": 0.008, "type": "commit", }, { "batchUID": 0, "depth": 1, "duration": 0.001, "lanes": "0b0000000000000000000000000001001", "timestamp": 0.009, "type": "layout-effects", }, ], 10 => [], 11 => [], 12 => [], 13 => [], 14 => [], 15 => [], 16 => [], 17 => [], 18 => [], 19 => [], 20 => [], 21 => [], 22 => [], 23 => [], 24 => [], 25 => [], 26 => [], 27 => [], 28 => [], 29 => [], 30 => [], }, "nativeEvents": [], "networkMeasures": [], "otherUserTimingMarks": [], "reactVersion": "<filtered-version>", "schedulingEvents": [ { "lanes": "0b0000000000000000000000000001001", "timestamp": 0.005, "type": "schedule-render", "warning": null, }, ], "snapshotHeight": 0, "snapshots": [], "startTime": 1, "suspenseEvents": [], "thrownErrors": [], } `); }); it('should process a sample legacy render sequence', async () => { utils.legacyRender(<div />, document.createElement('div')); const data = await preprocessData([ ...createBoilerplateEntries(), ...createUserTimingData(clearedMarks), ]); expect(data).toMatchInlineSnapshot(` { "batchUIDToMeasuresMap": Map { 0 => [ { "batchUID": 0, "depth": 0, "duration": 0.01, "lanes": "0b0000000000000000000000000000001", "timestamp": 0.006, "type": "render-idle", }, { "batchUID": 0, "depth": 0, "duration": 0.001, "lanes": "0b0000000000000000000000000000001", "timestamp": 0.006, "type": "render", }, { "batchUID": 0, "depth": 0, "duration": 0.008, "lanes": "0b0000000000000000000000000000001", "timestamp": 0.008, "type": "commit", }, { "batchUID": 0, "depth": 1, "duration": 0.001, "lanes": "0b0000000000000000000000000000001", "timestamp": 0.014, "type": "layout-effects", }, ], }, "componentMeasures": [], "duration": 0.016, "flamechart": [], "internalModuleSourceToRanges": Map { undefined => [ [ { "columnNumber": 0, "functionName": "filtered", "lineNumber": 0, "source": " at filtered (<anonymous>:0:0)", }, { "columnNumber": 1, "functionName": "filtered", "lineNumber": 1, "source": " at filtered (<anonymous>:1:1)", }, ], ], }, "laneToLabelMap": Map { 0 => "Sync", 1 => "InputContinuousHydration", 2 => "InputContinuous", 3 => "DefaultHydration", 4 => "Default", 5 => "TransitionHydration", 6 => "Transition", 7 => "Transition", 8 => "Transition", 9 => "Transition", 10 => "Transition", 11 => "Transition", 12 => "Transition", 13 => "Transition", 14 => "Transition", 15 => "Transition", 16 => "Transition", 17 => "Transition", 18 => "Transition", 19 => "Transition", 20 => "Transition", 21 => "Transition", 22 => "Retry", 23 => "Retry", 24 => "Retry", 25 => "Retry", 26 => "Retry", 27 => "SelectiveHydration", 28 => "IdleHydration", 29 => "Idle", 30 => "Offscreen", }, "laneToReactMeasureMap": Map { 0 => [], 1 => [ { "batchUID": 0, "depth": 0, "duration": 0.01, "lanes": "0b0000000000000000000000000000001", "timestamp": 0.006, "type": "render-idle", }, { "batchUID": 0, "depth": 0, "duration": 0.001, "lanes": "0b0000000000000000000000000000001", "timestamp": 0.006, "type": "render", }, { "batchUID": 0, "depth": 0, "duration": 0.008, "lanes": "0b0000000000000000000000000000001", "timestamp": 0.008, "type": "commit", }, { "batchUID": 0, "depth": 1, "duration": 0.001, "lanes": "0b0000000000000000000000000000001", "timestamp": 0.014, "type": "layout-effects", }, ], 2 => [], 3 => [], 4 => [], 5 => [], 6 => [], 7 => [], 8 => [], 9 => [], 10 => [], 11 => [], 12 => [], 13 => [], 14 => [], 15 => [], 16 => [], 17 => [], 18 => [], 19 => [], 20 => [], 21 => [], 22 => [], 23 => [], 24 => [], 25 => [], 26 => [], 27 => [], 28 => [], 29 => [], 30 => [], }, "nativeEvents": [], "networkMeasures": [], "otherUserTimingMarks": [], "reactVersion": "<filtered-version>", "schedulingEvents": [ { "lanes": "0b0000000000000000000000000000001", "timestamp": 0.005, "type": "schedule-render", "warning": null, }, ], "snapshotHeight": 0, "snapshots": [], "startTime": 4, "suspenseEvents": [], "thrownErrors": [], } `); }); it('should process a sample createRoot render sequence', async () => { function App() { const [didMount, setDidMount] = React.useState(false); React.useEffect(() => { if (!didMount) { setDidMount(true); } }); return true; } const root = ReactDOMClient.createRoot(document.createElement('div')); utils.act(() => root.render(<App />)); const data = await preprocessData([ ...createBoilerplateEntries(), ...createUserTimingData(clearedMarks), ]); expect(data).toMatchInlineSnapshot(` { "batchUIDToMeasuresMap": Map { 0 => [ { "batchUID": 0, "depth": 0, "duration": 0.012, "lanes": "0b0000000000000000000000000000101", "timestamp": 0.006, "type": "render-idle", }, { "batchUID": 0, "depth": 0, "duration": 0.003, "lanes": "0b0000000000000000000000000000101", "timestamp": 0.006, "type": "render", }, { "batchUID": 0, "depth": 0, "duration": 0.008, "lanes": "0b0000000000000000000000000000101", "timestamp": 0.01, "type": "commit", }, { "batchUID": 0, "depth": 1, "duration": 0.001, "lanes": "0b0000000000000000000000000000101", "timestamp": 0.016, "type": "layout-effects", }, { "batchUID": 0, "depth": 0, "duration": 0.004, "lanes": "0b0000000000000000000000000000101", "timestamp": 0.019, "type": "passive-effects", }, ], 1 => [ { "batchUID": 1, "depth": 0, "duration": 0.012, "lanes": "0b0000000000000000000000000000101", "timestamp": 0.024, "type": "render-idle", }, { "batchUID": 1, "depth": 0, "duration": 0.003, "lanes": "0b0000000000000000000000000000101", "timestamp": 0.024, "type": "render", }, { "batchUID": 1, "depth": 0, "duration": 0.008, "lanes": "0b0000000000000000000000000000101", "timestamp": 0.028, "type": "commit", }, { "batchUID": 1, "depth": 1, "duration": 0.001, "lanes": "0b0000000000000000000000000000101", "timestamp": 0.034, "type": "layout-effects", }, { "batchUID": 1, "depth": 0, "duration": 0.003, "lanes": "0b0000000000000000000000000000101", "timestamp": 0.037, "type": "passive-effects", }, ], }, "componentMeasures": [ { "componentName": "App", "duration": 0.001, "timestamp": 0.007, "type": "render", "warning": null, }, { "componentName": "App", "duration": 0.002, "timestamp": 0.02, "type": "passive-effect-mount", "warning": null, }, { "componentName": "App", "duration": 0.001, "timestamp": 0.025, "type": "render", "warning": null, }, { "componentName": "App", "duration": 0.001, "timestamp": 0.038, "type": "passive-effect-mount", "warning": null, }, ], "duration": 0.04, "flamechart": [], "internalModuleSourceToRanges": Map { undefined => [ [ { "columnNumber": 0, "functionName": "filtered", "lineNumber": 0, "source": " at filtered (<anonymous>:0:0)", }, { "columnNumber": 1, "functionName": "filtered", "lineNumber": 1, "source": " at filtered (<anonymous>:1:1)", }, ], ], }, "laneToLabelMap": Map { 0 => "Sync", 1 => "InputContinuousHydration", 2 => "InputContinuous", 3 => "DefaultHydration", 4 => "Default", 5 => "TransitionHydration", 6 => "Transition", 7 => "Transition", 8 => "Transition", 9 => "Transition", 10 => "Transition", 11 => "Transition", 12 => "Transition", 13 => "Transition", 14 => "Transition", 15 => "Transition", 16 => "Transition", 17 => "Transition", 18 => "Transition", 19 => "Transition", 20 => "Transition", 21 => "Transition", 22 => "Retry", 23 => "Retry", 24 => "Retry", 25 => "Retry", 26 => "Retry", 27 => "SelectiveHydration", 28 => "IdleHydration", 29 => "Idle", 30 => "Offscreen", }, "laneToReactMeasureMap": Map { 0 => [], 1 => [], 2 => [], 3 => [], 4 => [], 5 => [ { "batchUID": 0, "depth": 0, "duration": 0.012, "lanes": "0b0000000000000000000000000000101", "timestamp": 0.006, "type": "render-idle", }, { "batchUID": 0, "depth": 0, "duration": 0.003, "lanes": "0b0000000000000000000000000000101", "timestamp": 0.006, "type": "render", }, { "batchUID": 0, "depth": 0, "duration": 0.008, "lanes": "0b0000000000000000000000000000101", "timestamp": 0.01, "type": "commit", }, { "batchUID": 0, "depth": 1, "duration": 0.001, "lanes": "0b0000000000000000000000000000101", "timestamp": 0.016, "type": "layout-effects", }, { "batchUID": 0, "depth": 0, "duration": 0.004, "lanes": "0b0000000000000000000000000000101", "timestamp": 0.019, "type": "passive-effects", }, { "batchUID": 1, "depth": 0, "duration": 0.012, "lanes": "0b0000000000000000000000000000101", "timestamp": 0.024, "type": "render-idle", }, { "batchUID": 1, "depth": 0, "duration": 0.003, "lanes": "0b0000000000000000000000000000101", "timestamp": 0.024, "type": "render", }, { "batchUID": 1, "depth": 0, "duration": 0.008, "lanes": "0b0000000000000000000000000000101", "timestamp": 0.028, "type": "commit", }, { "batchUID": 1, "depth": 1, "duration": 0.001, "lanes": "0b0000000000000000000000000000101", "timestamp": 0.034, "type": "layout-effects", }, { "batchUID": 1, "depth": 0, "duration": 0.003, "lanes": "0b0000000000000000000000000000101", "timestamp": 0.037, "type": "passive-effects", }, ], 6 => [], 7 => [], 8 => [], 9 => [], 10 => [], 11 => [], 12 => [], 13 => [], 14 => [], 15 => [], 16 => [], 17 => [], 18 => [], 19 => [], 20 => [], 21 => [], 22 => [], 23 => [], 24 => [], 25 => [], 26 => [], 27 => [], 28 => [], 29 => [], 30 => [], }, "nativeEvents": [], "networkMeasures": [], "otherUserTimingMarks": [], "reactVersion": "<filtered-version>", "schedulingEvents": [ { "lanes": "0b0000000000000000000000000000101", "timestamp": 0.005, "type": "schedule-render", "warning": null, }, { "componentName": "App", "lanes": "0b0000000000000000000000000000101", "timestamp": 0.021, "type": "schedule-state-update", "warning": null, }, ], "snapshotHeight": 0, "snapshots": [], "startTime": 4, "suspenseEvents": [], "thrownErrors": [], } `); }); // @reactVersion >= 18.0 it('should error if events and measures are incomplete', async () => { const container = document.createElement('div'); utils.legacyRender(<div />, container); const invalidMarks = clearedMarks.filter( mark => !mark.includes('render-stop'), ); const invalidUserTimingData = createUserTimingData(invalidMarks); const error = jest.spyOn(console, 'error').mockImplementation(() => {}); preprocessData([ ...createBoilerplateEntries(), ...invalidUserTimingData, ]); expect(error).toHaveBeenCalled(); }); // @reactVersion >= 18.0 it('should error if work is completed without being started', async () => { const container = document.createElement('div'); utils.legacyRender(<div />, container); const invalidMarks = clearedMarks.filter( mark => !mark.includes('render-start'), ); const invalidUserTimingData = createUserTimingData(invalidMarks); const error = jest.spyOn(console, 'error').mockImplementation(() => {}); preprocessData([ ...createBoilerplateEntries(), ...invalidUserTimingData, ]); expect(error).toHaveBeenCalled(); }); // @reactVersion >= 18.0 it('should populate other user timing marks', async () => { const userTimingData = createUserTimingData([]); userTimingData.push( createUserTimingEntry({ args: {}, cat: 'blink.user_timing', id: '0xcdf75f7c', name: 'VCWithoutImage: root', ph: 'n', scope: 'blink.user_timing', }), ); userTimingData.push( createUserTimingEntry({ cat: 'blink.user_timing', name: '--a-mark-that-looks-like-one-of-ours', ph: 'R', }), ); userTimingData.push( createUserTimingEntry({ cat: 'blink.user_timing', name: 'Some other mark', ph: 'R', }), ); const data = await preprocessData([ ...createBoilerplateEntries(), ...userTimingData, ]); expect(data.otherUserTimingMarks).toMatchInlineSnapshot(` [ { "name": "VCWithoutImage: root", "timestamp": 0.003, }, { "name": "--a-mark-that-looks-like-one-of-ours", "timestamp": 0.004, }, { "name": "Some other mark", "timestamp": 0.005, }, ] `); }); // @reactVersion >= 18.0 it('should include a suspended resource "displayName" if one is set', async () => { let promise = null; let resolvedValue = null; function readValue(value) { if (resolvedValue !== null) { return resolvedValue; } else if (promise === null) { promise = Promise.resolve(true).then(() => { resolvedValue = value; }); promise.displayName = 'Testing displayName'; } throw promise; } function Component() { const value = readValue(123); return value; } const testMarks = [creactCpuProfilerSample()]; const root = ReactDOMClient.createRoot(document.createElement('div')); utils.act(() => root.render( <React.Suspense fallback="Loading..."> <Component /> </React.Suspense>, ), ); testMarks.push(...createUserTimingData(clearedMarks)); let data; await utils.actAsync(async () => { data = await preprocessData(testMarks); }); expect(data.suspenseEvents).toHaveLength(1); expect(data.suspenseEvents[0].promiseName).toBe('Testing displayName'); }); describe('warnings', () => { describe('long event handlers', () => { // @reactVersion >= 18.0 it('should not warn when React scedules a (sync) update inside of a short event handler', async () => { function App() { return null; } const testMarks = [ creactCpuProfilerSample(), ...createBoilerplateEntries(), createNativeEventEntry('click', 5), ]; clearPendingMarks(); utils.legacyRender(<App />, document.createElement('div')); testMarks.push(...createUserTimingData(clearedMarks)); const data = await preprocessData(testMarks); const event = data.nativeEvents.find(({type}) => type === 'click'); expect(event.warning).toBe(null); }); // @reactVersion >= 18.0 it('should not warn about long events if the cause was non-React JavaScript', async () => { function App() { return null; } const testMarks = [ creactCpuProfilerSample(), ...createBoilerplateEntries(), createNativeEventEntry('click', 25000), ]; startTime += 2000; clearPendingMarks(); utils.legacyRender(<App />, document.createElement('div')); testMarks.push(...createUserTimingData(clearedMarks)); const data = await preprocessData(testMarks); const event = data.nativeEvents.find(({type}) => type === 'click'); expect(event.warning).toBe(null); }); // @reactVersion >= 18.0 it('should warn when React scedules a long (sync) update inside of an event', async () => { function App() { return null; } const testMarks = [ creactCpuProfilerSample(), ...createBoilerplateEntries(), createNativeEventEntry('click', 25000), ]; clearPendingMarks(); utils.legacyRender(<App />, document.createElement('div')); clearedMarks.forEach(markName => { if (markName === '--render-stop') { // Fake a long running render startTime += 20000; } testMarks.push({ pid: ++pid, tid: ++tid, ts: ++startTime, args: {data: {}}, cat: 'blink.user_timing', name: markName, ph: 'R', }); }); const data = await preprocessData(testMarks); const event = data.nativeEvents.find(({type}) => type === 'click'); expect(event.warning).toMatchInlineSnapshot( `"An event handler scheduled a big update with React. Consider using the Transition API to defer some of this work."`, ); }); // @reactVersion >= 18.2 it('should not warn when React finishes a previously long (async) update with a short (sync) update inside of an event', async () => { function Yield({id, value}) { Scheduler.log(`${id}:${value}`); return null; } const testMarks = [ creactCpuProfilerSample(), ...createBoilerplateEntries(), ]; // Advance the clock by some arbitrary amount. startTime += 50000; const root = ReactDOMClient.createRoot( document.createElement('div'), ); // Temporarily turn off the act environment, since we're intentionally using Scheduler instead. global.IS_REACT_ACT_ENVIRONMENT = false; React.startTransition(() => { // Start rendering an async update (but don't finish). root.render( <> <Yield id="A" value={1} /> <Yield id="B" value={1} /> </>, ); }); await waitFor(['A:1']); testMarks.push(...createUserTimingData(clearedMarks)); clearPendingMarks(); // Advance the clock some more to make the pending React update seem long. startTime += 20000; // Fake a long "click" event in the middle // and schedule a sync update that will also flush the previous work. testMarks.push(createNativeEventEntry('click', 25000)); ReactDOM.flushSync(() => { root.render( <> <Yield id="A" value={2} /> <Yield id="B" value={2} /> </>, ); }); assertLog(['A:2', 'B:2']); testMarks.push(...createUserTimingData(clearedMarks)); const data = await preprocessData(testMarks); const event = data.nativeEvents.find(({type}) => type === 'click'); expect(event.warning).toBe(null); }); }); describe('nested updates', () => { // @reactVersion >= 18.2 it('should not warn about short nested (state) updates during layout effects', async () => { function Component() { const [didMount, setDidMount] = React.useState(false); Scheduler.log(`Component ${didMount ? 'update' : 'mount'}`); React.useLayoutEffect(() => { setDidMount(true); }, []); return didMount; } const root = ReactDOMClient.createRoot( document.createElement('div'), ); utils.act(() => { root.render(<Component />); }); assertLog(['Component mount', 'Component update']); const data = await preprocessData([ ...createBoilerplateEntries(), ...createUserTimingData(clearedMarks), ]); const event = data.schedulingEvents.find( ({type}) => type === 'schedule-state-update', ); expect(event.warning).toBe(null); }); // @reactVersion >= 18.2 it('should not warn about short (forced) updates during layout effects', async () => { class Component extends React.Component { _didMount: boolean = false; componentDidMount() { this._didMount = true; this.forceUpdate(); } render() { Scheduler.log( `Component ${this._didMount ? 'update' : 'mount'}`, ); return null; } } const root = ReactDOMClient.createRoot( document.createElement('div'), ); utils.act(() => { root.render(<Component />); }); assertLog(['Component mount', 'Component update']); const data = await preprocessData([ ...createBoilerplateEntries(), ...createUserTimingData(clearedMarks), ]); const event = data.schedulingEvents.find( ({type}) => type === 'schedule-force-update', ); expect(event.warning).toBe(null); }); // This is temporarily disabled because the warning doesn't work // with useDeferredValue it.skip('should warn about long nested (state) updates during layout effects', async () => { function Component() { const [didMount, setDidMount] = React.useState(false); Scheduler.log(`Component ${didMount ? 'update' : 'mount'}`); // Fake a long render startTime += 20000; React.useLayoutEffect(() => { setDidMount(true); }, []); return didMount; } const cpuProfilerSample = creactCpuProfilerSample(); const root = ReactDOMClient.createRoot( document.createElement('div'), ); utils.act(() => { root.render(<Component />); }); assertLog(['Component mount', 'Component update']); const testMarks = []; clearedMarks.forEach(markName => { if (markName === '--component-render-start-Component') { // Fake a long running render startTime += 20000; } testMarks.push({ pid: ++pid, tid: ++tid, ts: ++startTime, args: {data: {}}, cat: 'blink.user_timing', name: markName, ph: 'R', }); }); const data = await preprocessData([ cpuProfilerSample, ...createBoilerplateEntries(), ...testMarks, ]); const event = data.schedulingEvents.find( ({type}) => type === 'schedule-state-update', ); expect(event.warning).toMatchInlineSnapshot( `"A big nested update was scheduled during layout. Nested updates require React to re-render synchronously before the browser can paint. Consider delaying this update by moving it to a passive effect (useEffect)."`, ); }); // This is temporarily disabled because the warning doesn't work // with useDeferredValue it.skip('should warn about long nested (forced) updates during layout effects', async () => { class Component extends React.Component { _didMount: boolean = false; componentDidMount() { this._didMount = true; this.forceUpdate(); } render() { Scheduler.log( `Component ${this._didMount ? 'update' : 'mount'}`, ); return null; } } const cpuProfilerSample = creactCpuProfilerSample(); const root = ReactDOMClient.createRoot( document.createElement('div'), ); utils.act(() => { root.render(<Component />); }); assertLog(['Component mount', 'Component update']); const testMarks = []; clearedMarks.forEach(markName => { if (markName === '--component-render-start-Component') { // Fake a long running render startTime += 20000; } testMarks.push({ pid: ++pid, tid: ++tid, ts: ++startTime, args: {data: {}}, cat: 'blink.user_timing', name: markName, ph: 'R', }); }); const data = await preprocessData([ cpuProfilerSample, ...createBoilerplateEntries(), ...testMarks, ]); const event = data.schedulingEvents.find( ({type}) => type === 'schedule-force-update', ); expect(event.warning).toMatchInlineSnapshot( `"A big nested update was scheduled during layout. Nested updates require React to re-render synchronously before the browser can paint. Consider delaying this update by moving it to a passive effect (useEffect)."`, ); }); // @reactVersion >= 18.2 it('should not warn about transition updates scheduled during commit phase', async () => { function Component() { const [value, setValue] = React.useState(0); // eslint-disable-next-line no-unused-vars const [isPending, startTransition] = React.useTransition(); Scheduler.log(`Component rendered with value ${value}`); // Fake a long render if (value !== 0) { Scheduler.log('Long render'); startTime += 20000; } React.useLayoutEffect(() => { startTransition(() => { setValue(1); }); }, []); return value; } const cpuProfilerSample = creactCpuProfilerSample(); const root = ReactDOMClient.createRoot( document.createElement('div'), ); utils.act(() => { root.render(<Component />); }); assertLog([ 'Component rendered with value 0', 'Component rendered with value 0', 'Component rendered with value 1', 'Long render', ]); const testMarks = []; clearedMarks.forEach(markName => { if (markName === '--component-render-start-Component') { // Fake a long running render startTime += 20000; } testMarks.push({ pid: ++pid, tid: ++tid, ts: ++startTime, args: {data: {}}, cat: 'blink.user_timing', name: markName, ph: 'R', }); }); const data = await preprocessData([ cpuProfilerSample, ...createBoilerplateEntries(), ...testMarks, ]); data.schedulingEvents.forEach(event => { expect(event.warning).toBeNull(); }); }); // This is temporarily disabled because the warning doesn't work // with useDeferredValue it.skip('should not warn about deferred value updates scheduled during commit phase', async () => { function Component() { const [value, setValue] = React.useState(0); const deferredValue = React.useDeferredValue(value); Scheduler.log( `Component rendered with value ${value} and deferredValue ${deferredValue}`, ); // Fake a long render if (deferredValue !== 0) { Scheduler.log('Long render'); startTime += 20000; } React.useLayoutEffect(() => { setValue(1); }, []); return value + deferredValue; } const cpuProfilerSample = creactCpuProfilerSample(); const root = ReactDOMClient.createRoot( document.createElement('div'), ); utils.act(() => { root.render(<Component />); }); assertLog([ 'Component rendered with value 0 and deferredValue 0', 'Component rendered with value 1 and deferredValue 0', 'Component rendered with value 1 and deferredValue 1', 'Long render', ]); const testMarks = []; clearedMarks.forEach(markName => { if (markName === '--component-render-start-Component') { // Fake a long running render startTime += 20000; } testMarks.push({ pid: ++pid, tid: ++tid, ts: ++startTime, args: {data: {}}, cat: 'blink.user_timing', name: markName, ph: 'R', }); }); const data = await preprocessData([ cpuProfilerSample, ...createBoilerplateEntries(), ...testMarks, ]); data.schedulingEvents.forEach(event => { expect(event.warning).toBeNull(); }); }); }); describe('errors thrown while rendering', () => { // @reactVersion >= 18.0 it('shoult parse Errors thrown during render', async () => { jest.spyOn(console, 'error'); class ErrorBoundary extends React.Component { state = {error: null}; componentDidCatch(error) { this.setState({error}); } render() { if (this.state.error) { return null; } return this.props.children; } } function ExampleThatThrows() { throw Error('Expected error'); } const testMarks = [creactCpuProfilerSample()]; // Mount and commit the app const root = ReactDOMClient.createRoot( document.createElement('div'), ); utils.act(() => root.render( <ErrorBoundary> <ExampleThatThrows /> </ErrorBoundary>, ), ); testMarks.push(...createUserTimingData(clearedMarks)); const data = await preprocessData(testMarks); expect(data.thrownErrors).toHaveLength(2); expect(data.thrownErrors[0].message).toMatchInlineSnapshot( '"Expected error"', ); }); }); describe('suspend during an update', () => { // This also tests an edge case where a component suspends while profiling // before the first commit is logged (so the lane-to-labels map will not yet exist). // @reactVersion >= 18.2 it('should warn about suspending during an update', async () => { let promise = null; let resolvedValue = null; function readValue(value) { if (resolvedValue !== null) { return resolvedValue; } else if (promise === null) { promise = Promise.resolve(true).then(() => { resolvedValue = value; }); } throw promise; } function Component({shouldSuspend}) { Scheduler.log(`Component ${shouldSuspend}`); if (shouldSuspend) { readValue(123); } return null; } // Mount and commit the app const root = ReactDOMClient.createRoot( document.createElement('div'), ); utils.act(() => root.render( <React.Suspense fallback="Loading..."> <Component shouldSuspend={false} /> </React.Suspense>, ), ); const testMarks = [creactCpuProfilerSample()]; // Start profiling and suspend during a render. utils.act(() => root.render( <React.Suspense fallback="Loading..."> <Component shouldSuspend={true} /> </React.Suspense>, ), ); testMarks.push(...createUserTimingData(clearedMarks)); let data; await utils.actAsync(async () => { data = await preprocessData(testMarks); }); expect(data.suspenseEvents).toHaveLength(1); expect(data.suspenseEvents[0].warning).toMatchInlineSnapshot( `"A component suspended during an update which caused a fallback to be shown. Consider using the Transition API to avoid hiding components after they've been mounted."`, ); }); // @reactVersion >= 18.2 it('should not warn about suspending during an transition', async () => { let promise = null; let resolvedValue = null; function readValue(value) { if (resolvedValue !== null) { return resolvedValue; } else if (promise === null) { promise = Promise.resolve(true).then(() => { resolvedValue = value; }); } throw promise; } function Component({shouldSuspend}) { Scheduler.log(`Component ${shouldSuspend}`); if (shouldSuspend) { readValue(123); } return null; } // Mount and commit the app const root = ReactDOMClient.createRoot( document.createElement('div'), ); utils.act(() => root.render( <React.Suspense fallback="Loading..."> <Component shouldSuspend={false} /> </React.Suspense>, ), ); const testMarks = [creactCpuProfilerSample()]; // Start profiling and suspend during a render. await utils.actAsync(async () => React.startTransition(() => root.render( <React.Suspense fallback="Loading..."> <Component shouldSuspend={true} /> </React.Suspense>, ), ), ); testMarks.push(...createUserTimingData(clearedMarks)); let data; await utils.actAsync(async () => { data = await preprocessData(testMarks); }); expect(data.suspenseEvents).toHaveLength(1); expect(data.suspenseEvents[0].warning).toBe(null); }); }); }); // TODO: Add test for snapshot base64 parsing // TODO: Add test for flamechart parsing }); }); // Note the in-memory tests vary slightly (e.g. timestamp values, lane numbers) from the above tests. // That's okay; the important thing is the lane-to-label matches the subsequent events/measures. describe('DevTools hook (in memory)', () => { let store; beforeEach(() => { utils = require('./utils'); utils.beforeEachProfiling(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); Scheduler = require('scheduler'); store = global.store; // Start profiling so that data will actually be recorded. utils.act(() => store.profilerStore.startProfiling()); global.IS_REACT_ACT_ENVIRONMENT = true; }); it('should process a sample legacy render sequence', async () => { utils.legacyRender(<div />, document.createElement('div')); utils.act(() => store.profilerStore.stopProfiling()); const data = store.profilerStore.profilingData?.timelineData; expect(data).toHaveLength(1); const timelineData = data[0]; expect(timelineData).toMatchInlineSnapshot(` { "batchUIDToMeasuresMap": Map { 1 => [ { "batchUID": 1, "depth": 0, "duration": 0, "lanes": "0b0000000000000000000000000000010", "timestamp": 10, "type": "render-idle", }, { "batchUID": 1, "depth": 0, "duration": 0, "lanes": "0b0000000000000000000000000000010", "timestamp": 10, "type": "render", }, { "batchUID": 1, "depth": 0, "duration": 0, "lanes": "0b0000000000000000000000000000010", "timestamp": 10, "type": "commit", }, { "batchUID": 1, "depth": 1, "duration": 0, "lanes": "0b0000000000000000000000000000010", "timestamp": 10, "type": "layout-effects", }, ], }, "componentMeasures": [], "duration": 20, "flamechart": [], "internalModuleSourceToRanges": Map {}, "laneToLabelMap": Map { 1 => "SyncHydrationLane", 2 => "Sync", 4 => "InputContinuousHydration", 8 => "InputContinuous", 16 => "DefaultHydration", 32 => "Default", 64 => "TransitionHydration", 128 => "Transition", 256 => "Transition", 512 => "Transition", 1024 => "Transition", 2048 => "Transition", 4096 => "Transition", 8192 => "Transition", 16384 => "Transition", 32768 => "Transition", 65536 => "Transition", 131072 => "Transition", 262144 => "Transition", 524288 => "Transition", 1048576 => "Transition", 2097152 => "Transition", 4194304 => "Retry", 8388608 => "Retry", 16777216 => "Retry", 33554432 => "Retry", 67108864 => "SelectiveHydration", 134217728 => "IdleHydration", 268435456 => "Idle", 536870912 => "Offscreen", 1073741824 => "Deferred", }, "laneToReactMeasureMap": Map { 1 => [], 2 => [ { "batchUID": 1, "depth": 0, "duration": 0, "lanes": "0b0000000000000000000000000000010", "timestamp": 10, "type": "render-idle", }, { "batchUID": 1, "depth": 0, "duration": 0, "lanes": "0b0000000000000000000000000000010", "timestamp": 10, "type": "render", }, { "batchUID": 1, "depth": 0, "duration": 0, "lanes": "0b0000000000000000000000000000010", "timestamp": 10, "type": "commit", }, { "batchUID": 1, "depth": 1, "duration": 0, "lanes": "0b0000000000000000000000000000010", "timestamp": 10, "type": "layout-effects", }, ], 4 => [], 8 => [], 16 => [], 32 => [], 64 => [], 128 => [], 256 => [], 512 => [], 1024 => [], 2048 => [], 4096 => [], 8192 => [], 16384 => [], 32768 => [], 65536 => [], 131072 => [], 262144 => [], 524288 => [], 1048576 => [], 2097152 => [], 4194304 => [], 8388608 => [], 16777216 => [], 33554432 => [], 67108864 => [], 134217728 => [], 268435456 => [], 536870912 => [], 1073741824 => [], }, "nativeEvents": [], "networkMeasures": [], "otherUserTimingMarks": [], "reactVersion": "<filtered-version>", "schedulingEvents": [ { "lanes": "0b0000000000000000000000000000010", "timestamp": 10, "type": "schedule-render", "warning": null, }, ], "snapshotHeight": 0, "snapshots": [], "startTime": -10, "suspenseEvents": [], "thrownErrors": [], } `); }); it('should process a sample createRoot render sequence', async () => { function App() { const [didMount, setDidMount] = React.useState(false); React.useEffect(() => { if (!didMount) { setDidMount(true); } }); return true; } const root = ReactDOMClient.createRoot(document.createElement('div')); utils.act(() => root.render(<App />)); utils.act(() => store.profilerStore.stopProfiling()); const data = store.profilerStore.profilingData?.timelineData; expect(data).toHaveLength(1); const timelineData = data[0]; // normalize the location for component stack source // for snapshot testing timelineData.schedulingEvents.forEach(event => { if (event.componentStack) { event.componentStack = normalizeCodeLocInfo(event.componentStack); } }); expect(timelineData).toMatchInlineSnapshot(` { "batchUIDToMeasuresMap": Map { 1 => [ { "batchUID": 1, "depth": 0, "duration": 0, "lanes": "0b0000000000000000000000000100000", "timestamp": 10, "type": "render-idle", }, { "batchUID": 1, "depth": 0, "duration": 0, "lanes": "0b0000000000000000000000000100000", "timestamp": 10, "type": "render", }, { "batchUID": 1, "depth": 0, "duration": 0, "lanes": "0b0000000000000000000000000100000", "timestamp": 10, "type": "commit", }, { "batchUID": 1, "depth": 1, "duration": 0, "lanes": "0b0000000000000000000000000100000", "timestamp": 10, "type": "layout-effects", }, { "batchUID": 1, "depth": 0, "duration": 0, "lanes": "0b0000000000000000000000000100000", "timestamp": 10, "type": "passive-effects", }, ], 2 => [ { "batchUID": 2, "depth": 0, "duration": 0, "lanes": "0b0000000000000000000000000100000", "timestamp": 10, "type": "render-idle", }, { "batchUID": 2, "depth": 0, "duration": 0, "lanes": "0b0000000000000000000000000100000", "timestamp": 10, "type": "render", }, { "batchUID": 2, "depth": 0, "duration": 0, "lanes": "0b0000000000000000000000000100000", "timestamp": 10, "type": "commit", }, { "batchUID": 2, "depth": 1, "duration": 0, "lanes": "0b0000000000000000000000000100000", "timestamp": 10, "type": "layout-effects", }, { "batchUID": 2, "depth": 0, "duration": 0, "lanes": "0b0000000000000000000000000100000", "timestamp": 10, "type": "passive-effects", }, ], }, "componentMeasures": [ { "componentName": "App", "duration": 0, "timestamp": 10, "type": "render", "warning": null, }, { "componentName": "App", "duration": 0, "timestamp": 10, "type": "passive-effect-mount", "warning": null, }, { "componentName": "App", "duration": 0, "timestamp": 10, "type": "render", "warning": null, }, { "componentName": "App", "duration": 0, "timestamp": 10, "type": "passive-effect-mount", "warning": null, }, ], "duration": 20, "flamechart": [], "internalModuleSourceToRanges": Map {}, "laneToLabelMap": Map { 1 => "SyncHydrationLane", 2 => "Sync", 4 => "InputContinuousHydration", 8 => "InputContinuous", 16 => "DefaultHydration", 32 => "Default", 64 => "TransitionHydration", 128 => "Transition", 256 => "Transition", 512 => "Transition", 1024 => "Transition", 2048 => "Transition", 4096 => "Transition", 8192 => "Transition", 16384 => "Transition", 32768 => "Transition", 65536 => "Transition", 131072 => "Transition", 262144 => "Transition", 524288 => "Transition", 1048576 => "Transition", 2097152 => "Transition", 4194304 => "Retry", 8388608 => "Retry", 16777216 => "Retry", 33554432 => "Retry", 67108864 => "SelectiveHydration", 134217728 => "IdleHydration", 268435456 => "Idle", 536870912 => "Offscreen", 1073741824 => "Deferred", }, "laneToReactMeasureMap": Map { 1 => [], 2 => [], 4 => [], 8 => [], 16 => [], 32 => [ { "batchUID": 1, "depth": 0, "duration": 0, "lanes": "0b0000000000000000000000000100000", "timestamp": 10, "type": "render-idle", }, { "batchUID": 1, "depth": 0, "duration": 0, "lanes": "0b0000000000000000000000000100000", "timestamp": 10, "type": "render", }, { "batchUID": 1, "depth": 0, "duration": 0, "lanes": "0b0000000000000000000000000100000", "timestamp": 10, "type": "commit", }, { "batchUID": 1, "depth": 1, "duration": 0, "lanes": "0b0000000000000000000000000100000", "timestamp": 10, "type": "layout-effects", }, { "batchUID": 1, "depth": 0, "duration": 0, "lanes": "0b0000000000000000000000000100000", "timestamp": 10, "type": "passive-effects", }, { "batchUID": 2, "depth": 0, "duration": 0, "lanes": "0b0000000000000000000000000100000", "timestamp": 10, "type": "render-idle", }, { "batchUID": 2, "depth": 0, "duration": 0, "lanes": "0b0000000000000000000000000100000", "timestamp": 10, "type": "render", }, { "batchUID": 2, "depth": 0, "duration": 0, "lanes": "0b0000000000000000000000000100000", "timestamp": 10, "type": "commit", }, { "batchUID": 2, "depth": 1, "duration": 0, "lanes": "0b0000000000000000000000000100000", "timestamp": 10, "type": "layout-effects", }, { "batchUID": 2, "depth": 0, "duration": 0, "lanes": "0b0000000000000000000000000100000", "timestamp": 10, "type": "passive-effects", }, ], 64 => [], 128 => [], 256 => [], 512 => [], 1024 => [], 2048 => [], 4096 => [], 8192 => [], 16384 => [], 32768 => [], 65536 => [], 131072 => [], 262144 => [], 524288 => [], 1048576 => [], 2097152 => [], 4194304 => [], 8388608 => [], 16777216 => [], 33554432 => [], 67108864 => [], 134217728 => [], 268435456 => [], 536870912 => [], 1073741824 => [], }, "nativeEvents": [], "networkMeasures": [], "otherUserTimingMarks": [], "reactVersion": "<filtered-version>", "schedulingEvents": [ { "lanes": "0b0000000000000000000000000100000", "timestamp": 10, "type": "schedule-render", "warning": null, }, { "componentName": "App", "componentStack": " in App (at **)", "lanes": "0b0000000000000000000000000100000", "timestamp": 10, "type": "schedule-state-update", "warning": null, }, ], "snapshotHeight": 0, "snapshots": [], "startTime": -10, "suspenseEvents": [], "thrownErrors": [], } `); }); }); });
31.337042
383
0.423172
Mastering-Machine-Learning-for-Penetration-Testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; import { useContext, unstable_useCacheRefresh as useCacheRefresh, useTransition, } from 'react'; import Button from '../Button'; import ButtonIcon from '../ButtonIcon'; import Store from '../../store'; import sharedStyles from './InspectedElementSharedStyles.css'; import styles from './InspectedElementErrorsAndWarningsTree.css'; import {SettingsContext} from '../Settings/SettingsContext'; import { clearErrorsForElement as clearErrorsForElementAPI, clearWarningsForElement as clearWarningsForElementAPI, } from 'react-devtools-shared/src/backendAPI'; import type {InspectedElement} from 'react-devtools-shared/src/frontend/types'; import type {FrontendBridge} from 'react-devtools-shared/src/bridge'; type Props = { bridge: FrontendBridge, inspectedElement: InspectedElement, store: Store, }; export default function InspectedElementErrorsAndWarningsTree({ bridge, inspectedElement, store, }: Props): React.Node { const refresh = useCacheRefresh(); const [isErrorsTransitionPending, startClearErrorsTransition] = useTransition(); const clearErrorsForInspectedElement = () => { const {id} = inspectedElement; const rendererID = store.getRendererIDForElement(id); if (rendererID !== null) { startClearErrorsTransition(() => { clearErrorsForElementAPI({ bridge, id, rendererID, }); refresh(); }); } }; const [isWarningsTransitionPending, startClearWarningsTransition] = useTransition(); const clearWarningsForInspectedElement = () => { const {id} = inspectedElement; const rendererID = store.getRendererIDForElement(id); if (rendererID !== null) { startClearWarningsTransition(() => { clearWarningsForElementAPI({ bridge, id, rendererID, }); refresh(); }); } }; const {showInlineWarningsAndErrors} = useContext(SettingsContext); if (!showInlineWarningsAndErrors) { return null; } const {errors, warnings} = inspectedElement; return ( <React.Fragment> {errors.length > 0 && ( <Tree badgeClassName={styles.ErrorBadge} bridge={bridge} className={styles.ErrorTree} clearMessages={clearErrorsForInspectedElement} entries={errors} isTransitionPending={isErrorsTransitionPending} label="errors" messageClassName={styles.Error} /> )} {warnings.length > 0 && ( <Tree badgeClassName={styles.WarningBadge} bridge={bridge} className={styles.WarningTree} clearMessages={clearWarningsForInspectedElement} entries={warnings} isTransitionPending={isWarningsTransitionPending} label="warnings" messageClassName={styles.Warning} /> )} </React.Fragment> ); } type TreeProps = { badgeClassName: string, actions: React$Node, className: string, clearMessages: () => void, entries: Array<[string, number]>, isTransitionPending: boolean, label: string, messageClassName: string, }; function Tree({ badgeClassName, actions, className, clearMessages, entries, isTransitionPending, label, messageClassName, }: TreeProps) { if (entries.length === 0) { return null; } return ( <div className={`${sharedStyles.InspectedElementTree} ${className}`}> <div className={`${sharedStyles.HeaderRow} ${styles.HeaderRow}`}> <div className={sharedStyles.Header}>{label}</div> <Button disabled={isTransitionPending} onClick={clearMessages} title={`Clear all ${label} for this component`}> <ButtonIcon type="clear" /> </Button> </div> {entries.map(([message, count], index) => ( <ErrorOrWarningView key={`${label}-${index}`} badgeClassName={badgeClassName} className={messageClassName} count={count} message={message} /> ))} </div> ); } type ErrorOrWarningViewProps = { badgeClassName: string, className: string, count: number, message: string, }; function ErrorOrWarningView({ className, badgeClassName, count, message, }: ErrorOrWarningViewProps) { return ( <div className={className}> {count > 1 && <div className={badgeClassName}>{count}</div>} <div className={styles.Message} title={message}> {message} </div> </div> ); }
24.766304
79
0.647679
Python-Penetration-Testing-for-Developers
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @jest-environment node */ // sanity tests for act() let React; let ReactNoop; let act; let use; let Suspense; let DiscreteEventPriority; let startTransition; let waitForMicrotasks; let Scheduler; let assertLog; describe('isomorphic act()', () => { beforeEach(() => { React = require('react'); Scheduler = require('scheduler'); ReactNoop = require('react-noop-renderer'); DiscreteEventPriority = require('react-reconciler/constants').DiscreteEventPriority; act = React.unstable_act; use = React.use; Suspense = React.Suspense; startTransition = React.startTransition; waitForMicrotasks = require('internal-test-utils').waitForMicrotasks; assertLog = require('internal-test-utils').assertLog; }); beforeEach(() => { global.IS_REACT_ACT_ENVIRONMENT = true; }); afterEach(() => { jest.restoreAllMocks(); }); function Text({text}) { Scheduler.log(text); return text; } // @gate __DEV__ test('bypasses queueMicrotask', async () => { const root = ReactNoop.createRoot(); // First test what happens without wrapping in act. This update would // normally be queued in a microtask. global.IS_REACT_ACT_ENVIRONMENT = false; ReactNoop.unstable_runWithPriority(DiscreteEventPriority, () => { root.render('A'); }); // Nothing has rendered yet expect(root).toMatchRenderedOutput(null); // Flush the microtasks by awaiting await waitForMicrotasks(); expect(root).toMatchRenderedOutput('A'); // Now do the same thing but wrap the update with `act`. No // `await` necessary. global.IS_REACT_ACT_ENVIRONMENT = true; act(() => { ReactNoop.unstable_runWithPriority(DiscreteEventPriority, () => { root.render('B'); }); }); expect(root).toMatchRenderedOutput('B'); }); // @gate __DEV__ test('return value – sync callback', async () => { expect(await act(() => 'hi')).toEqual('hi'); }); // @gate __DEV__ test('return value – sync callback, nested', async () => { const returnValue = await act(() => { return act(() => 'hi'); }); expect(returnValue).toEqual('hi'); }); // @gate __DEV__ test('return value – async callback', async () => { const returnValue = await act(async () => { return await Promise.resolve('hi'); }); expect(returnValue).toEqual('hi'); }); // @gate __DEV__ test('return value – async callback, nested', async () => { const returnValue = await act(async () => { return await act(async () => { return await Promise.resolve('hi'); }); }); expect(returnValue).toEqual('hi'); }); // @gate __DEV__ test('in legacy mode, updates are batched', () => { const root = ReactNoop.createLegacyRoot(); // Outside of `act`, legacy updates are flushed completely synchronously root.render('A'); expect(root).toMatchRenderedOutput('A'); // `act` will batch the updates and flush them at the end act(() => { root.render('B'); // Hasn't flushed yet expect(root).toMatchRenderedOutput('A'); // Confirm that a nested `batchedUpdates` call won't cause the updates // to flush early. ReactNoop.batchedUpdates(() => { root.render('C'); }); // Still hasn't flushed expect(root).toMatchRenderedOutput('A'); }); // Now everything renders in a single batch. expect(root).toMatchRenderedOutput('C'); }); // @gate __DEV__ test('in legacy mode, in an async scope, updates are batched until the first `await`', async () => { const root = ReactNoop.createLegacyRoot(); await act(async () => { queueMicrotask(() => { Scheduler.log('Current tree in microtask: ' + root.getChildrenAsJSX()); root.render(<Text text="C" />); }); root.render(<Text text="A" />); root.render(<Text text="B" />); await null; assertLog([ // A and B should render in a single batch _before_ the microtask queue // has run. This replicates the behavior of the original `act` // implementation, for compatibility. 'B', 'Current tree in microtask: B', // C isn't scheduled until a microtask, so it's rendered separately. 'C', ]); // Subsequent updates should also render in separate batches. root.render(<Text text="D" />); root.render(<Text text="E" />); assertLog(['D', 'E']); }); }); // @gate __DEV__ test('in legacy mode, in an async scope, updates are batched until the first `await` (regression test: batchedUpdates)', async () => { const root = ReactNoop.createLegacyRoot(); await act(async () => { queueMicrotask(() => { Scheduler.log('Current tree in microtask: ' + root.getChildrenAsJSX()); root.render(<Text text="C" />); }); // This is a regression test. The presence of `batchedUpdates` would cause // these updates to not flush until a microtask. The correct behavior is // that they flush before the microtask queue, regardless of whether // they are wrapped with `batchedUpdates`. ReactNoop.batchedUpdates(() => { root.render(<Text text="A" />); root.render(<Text text="B" />); }); await null; assertLog([ // A and B should render in a single batch _before_ the microtask queue // has run. This replicates the behavior of the original `act` // implementation, for compatibility. 'B', 'Current tree in microtask: B', // C isn't scheduled until a microtask, so it's rendered separately. 'C', ]); // Subsequent updates should also render in separate batches. root.render(<Text text="D" />); root.render(<Text text="E" />); assertLog(['D', 'E']); }); }); // @gate __DEV__ test('unwraps promises by yielding to microtasks (async act scope)', async () => { const promise = Promise.resolve('Async'); function Fallback() { throw new Error('Fallback should never be rendered'); } function App() { return use(promise); } const root = ReactNoop.createRoot(); await act(async () => { startTransition(() => { root.render( <Suspense fallback={<Fallback />}> <App /> </Suspense>, ); }); }); expect(root).toMatchRenderedOutput('Async'); }); // @gate __DEV__ test('unwraps promises by yielding to microtasks (non-async act scope)', async () => { const promise = Promise.resolve('Async'); function Fallback() { throw new Error('Fallback should never be rendered'); } function App() { return use(promise); } const root = ReactNoop.createRoot(); // Note that the scope function is not an async function await act(() => { startTransition(() => { root.render( <Suspense fallback={<Fallback />}> <App /> </Suspense>, ); }); }); expect(root).toMatchRenderedOutput('Async'); }); // @gate __DEV__ test('warns if a promise is used in a non-awaited `act` scope', async () => { const promise = new Promise(() => {}); function Fallback() { throw new Error('Fallback should never be rendered'); } function App() { return use(promise); } spyOnDev(console, 'error').mockImplementation(() => {}); const root = ReactNoop.createRoot(); act(() => { startTransition(() => { root.render( <Suspense fallback={<Fallback />}> <App /> </Suspense>, ); }); }); // `act` warns after a few microtasks, instead of a macrotask, so that it's // more likely to be attributed to the correct test case. // // The exact number of microtasks is an implementation detail; just needs // to happen when the microtask queue is flushed. await waitForMicrotasks(); expect(console.error).toHaveBeenCalledTimes(1); expect(console.error.mock.calls[0][0]).toContain( 'Warning: A component suspended inside an `act` scope, but the `act` ' + 'call was not awaited. When testing React components that ' + 'depend on asynchronous data, you must await the result:\n\n' + 'await act(() => ...)', ); }); // @gate __DEV__ test('does not warn when suspending via legacy `throw` API in non-awaited `act` scope', async () => { let didResolve = false; let resolvePromise; const promise = new Promise(r => { resolvePromise = () => { didResolve = true; r(); }; }); function Fallback() { return 'Loading...'; } function App() { if (!didResolve) { throw promise; } return 'Async'; } spyOnDev(console, 'error').mockImplementation(() => {}); const root = ReactNoop.createRoot(); act(() => { startTransition(() => { root.render( <Suspense fallback={<Fallback />}> <App /> </Suspense>, ); }); }); expect(root).toMatchRenderedOutput('Loading...'); // `act` warns after a few microtasks, instead of a macrotask, so that it's // more likely to be attributed to the correct test case. // // The exact number of microtasks is an implementation detail; just needs // to happen when the microtask queue is flushed. await waitForMicrotasks(); expect(console.error).toHaveBeenCalledTimes(0); // Finish loading the data await act(async () => { resolvePromise(); }); expect(root).toMatchRenderedOutput('Async'); }); });
27.182336
136
0.591548
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import getNodeForCharacterOffset from './getNodeForCharacterOffset'; import {TEXT_NODE} from './HTMLNodeType'; /** * @param {DOMElement} outerNode * @return {?object} */ export function getOffsets(outerNode) { const {ownerDocument} = outerNode; const win = (ownerDocument && ownerDocument.defaultView) || window; const selection = win.getSelection && win.getSelection(); if (!selection || selection.rangeCount === 0) { return null; } const {anchorNode, anchorOffset, focusNode, focusOffset} = selection; // In Firefox, anchorNode and focusNode can be "anonymous divs", e.g. the // up/down buttons on an <input type="number">. Anonymous divs do not seem to // expose properties, triggering a "Permission denied error" if any of its // properties are accessed. The only seemingly possible way to avoid erroring // is to access a property that typically works for non-anonymous divs and // catch any error that may otherwise arise. See // https://bugzilla.mozilla.org/show_bug.cgi?id=208427 try { /* eslint-disable ft-flow/no-unused-expressions */ anchorNode.nodeType; focusNode.nodeType; /* eslint-enable ft-flow/no-unused-expressions */ } catch (e) { return null; } return getModernOffsetsFromPoints( outerNode, anchorNode, anchorOffset, focusNode, focusOffset, ); } /** * Returns {start, end} where `start` is the character/codepoint index of * (anchorNode, anchorOffset) within the textContent of `outerNode`, and * `end` is the index of (focusNode, focusOffset). * * Returns null if you pass in garbage input but we should probably just crash. * * Exported only for testing. */ export function getModernOffsetsFromPoints( outerNode, anchorNode, anchorOffset, focusNode, focusOffset, ) { let length = 0; let start = -1; let end = -1; let indexWithinAnchor = 0; let indexWithinFocus = 0; let node = outerNode; let parentNode = null; outer: while (true) { let next = null; while (true) { if ( node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE) ) { start = length + anchorOffset; } if ( node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE) ) { end = length + focusOffset; } if (node.nodeType === TEXT_NODE) { length += node.nodeValue.length; } if ((next = node.firstChild) === null) { break; } // Moving from `node` to its first child `next`. parentNode = node; node = next; } while (true) { if (node === outerNode) { // If `outerNode` has children, this is always the second time visiting // it. If it has no children, this is still the first loop, and the only // valid selection is anchorNode and focusNode both equal to this node // and both offsets 0, in which case we will have handled above. break outer; } if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) { start = length; } if (parentNode === focusNode && ++indexWithinFocus === focusOffset) { end = length; } if ((next = node.nextSibling) !== null) { break; } node = parentNode; parentNode = node.parentNode; } // Moving from `node` to its next sibling `next`. node = next; } if (start === -1 || end === -1) { // This should never happen. (Would happen if the anchor/focus nodes aren't // actually inside the passed-in node.) return null; } return { start: start, end: end, }; } /** * In modern non-IE browsers, we can support both forward and backward * selections. * * Note: IE10+ supports the Selection object, but it does not support * the `extend` method, which means that even in modern IE, it's not possible * to programmatically create a backward selection. Thus, for all IE * versions, we use the old IE API to create our selections. * * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ export function setOffsets(node, offsets) { const doc = node.ownerDocument || document; const win = (doc && doc.defaultView) || window; // Edge fails with "Object expected" in some scenarios. // (For instance: TinyMCE editor used in a list component that supports pasting to add more, // fails when pasting 100+ items) if (!win.getSelection) { return; } const selection = win.getSelection(); const length = node.textContent.length; let start = Math.min(offsets.start, length); let end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method. // Flip backward selections, so we can set with a single range. if (!selection.extend && start > end) { const temp = end; end = start; start = temp; } const startMarker = getNodeForCharacterOffset(node, start); const endMarker = getNodeForCharacterOffset(node, end); if (startMarker && endMarker) { if ( selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset ) { return; } const range = doc.createRange(); range.setStart(startMarker.node, startMarker.offset); selection.removeAllRanges(); if (start > end) { selection.addRange(range); selection.extend(endMarker.node, endMarker.offset); } else { range.setEnd(endMarker.node, endMarker.offset); selection.addRange(range); } } }
28.108374
94
0.647766
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Fiber} from './ReactInternalTypes'; import { HostComponent, HostHoistable, HostSingleton, LazyComponent, SuspenseComponent, SuspenseListComponent, FunctionComponent, IndeterminateComponent, ForwardRef, SimpleMemoComponent, ClassComponent, } from './ReactWorkTags'; import { describeBuiltInComponentFrame, describeFunctionComponentFrame, describeClassComponentFrame, } from 'shared/ReactComponentStackFrame'; function describeFiber(fiber: Fiber): string { const owner: null | Function = __DEV__ ? fiber._debugOwner ? fiber._debugOwner.type : null : null; const source = __DEV__ ? fiber._debugSource : null; switch (fiber.tag) { case HostHoistable: case HostSingleton: case HostComponent: return describeBuiltInComponentFrame(fiber.type, source, owner); case LazyComponent: return describeBuiltInComponentFrame('Lazy', source, owner); case SuspenseComponent: return describeBuiltInComponentFrame('Suspense', source, owner); case SuspenseListComponent: return describeBuiltInComponentFrame('SuspenseList', source, owner); case FunctionComponent: case IndeterminateComponent: case SimpleMemoComponent: return describeFunctionComponentFrame(fiber.type, source, owner); case ForwardRef: return describeFunctionComponentFrame(fiber.type.render, source, owner); case ClassComponent: return describeClassComponentFrame(fiber.type, source, owner); default: return ''; } } export function getStackByFiberInDevAndProd(workInProgress: Fiber): string { try { let info = ''; let node: Fiber = workInProgress; do { info += describeFiber(node); // $FlowFixMe[incompatible-type] we bail out when we get a null node = node.return; } while (node); return info; } catch (x) { return '\nError generating stack: ' + x.message + '\n' + x.stack; } }
27.236842
78
0.709091
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @noflow */ import {REACT_FORWARD_REF_TYPE, REACT_MEMO_TYPE} from 'shared/ReactSymbols'; export function forwardRef<Props, ElementType: React$ElementType>( render: (props: Props, ref: React$Ref<ElementType>) => React$Node, ) { if (__DEV__) { if (render != null && render.$$typeof === REACT_MEMO_TYPE) { console.error( 'forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).', ); } else if (typeof render !== 'function') { console.error( 'forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render, ); } else { if (render.length !== 0 && render.length !== 2) { console.error( 'forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.', ); } } if (render != null) { if (render.defaultProps != null || render.propTypes != null) { console.error( 'forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?', ); } } } const elementType = { $$typeof: REACT_FORWARD_REF_TYPE, render, }; if (__DEV__) { let ownName; Object.defineProperty(elementType, 'displayName', { enumerable: false, configurable: true, get: function () { return ownName; }, set: function (name) { ownName = name; // The inner component shouldn't inherit this display name in most cases, // because the component may be used elsewhere. // But it's nice for anonymous functions to inherit the name, // so that our component-stack generation logic will display their frames. // An anonymous function generally suggests a pattern like: // React.forwardRef((props, ref) => {...}); // This kind of inner function is not used elsewhere so the side effect is okay. if (!render.name && !render.displayName) { render.displayName = name; } }, }); } return elementType; }
31.435897
89
0.595492
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import SyntheticEvent from './SyntheticEvent'; /** * `touchHistory` isn't actually on the native event, but putting it in the * interface will ensure that it is cleaned up when pooled/destroyed. The * `ResponderEventPlugin` will populate it appropriately. */ const ResponderSyntheticEvent = SyntheticEvent.extend({ touchHistory: function (nativeEvent) { return null; // Actually doesn't even look at the native event. }, }); export default ResponderSyntheticEvent;
29.545455
75
0.743666
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = require("react"); /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ const A = /*#__PURE__*/(0, _react.createContext)(1); const B = /*#__PURE__*/(0, _react.createContext)(2); function Component() { const a = (0, _react.useContext)(A); const b = (0, _react.useContext)(B); // prettier-ignore const c = (0, _react.useContext)(A), d = (0, _react.useContext)(B); // eslint-disable-line one-var return a + b + c + d; } //# sourceMappingURL=ComponentWithMultipleHooksPerLine.js.map?foo=bar&param=some_value
25.433333
86
0.655303
null
'use strict'; throw new Error("Don't run `jest` directly. Run `yarn test` instead.");
21
71
0.678161
owtf
import { resolve, load as reactLoad, getSource as getSourceImpl, transformSource as reactTransformSource, } from 'react-server-dom-webpack/node-loader'; export {resolve}; import babel from '@babel/core'; const babelOptions = { babelrc: false, ignore: [/\/(build|node_modules)\//], plugins: [ '@babel/plugin-syntax-import-meta', '@babel/plugin-transform-react-jsx', ], }; async function babelLoad(url, context, defaultLoad) { const {format} = context; const result = await defaultLoad(url, context, defaultLoad); if (result.format === 'module') { const opt = Object.assign({filename: url}, babelOptions); const newResult = await babel.transformAsync(result.source, opt); if (!newResult) { if (typeof result.source === 'string') { return result; } return { source: Buffer.from(result.source).toString('utf8'), format: 'module', }; } return {source: newResult.code, format: 'module'}; } return defaultLoad(url, context, defaultLoad); } export async function load(url, context, defaultLoad) { return await reactLoad(url, context, (u, c) => { return babelLoad(u, c, defaultLoad); }); } async function babelTransformSource(source, context, defaultTransformSource) { const {format} = context; if (format === 'module') { const opt = Object.assign({filename: context.url}, babelOptions); const newResult = await babel.transformAsync(source, opt); if (!newResult) { if (typeof source === 'string') { return {source}; } return { source: Buffer.from(source).toString('utf8'), }; } return {source: newResult.code}; } return defaultTransformSource(source, context, defaultTransformSource); } async function transformSourceImpl(source, context, defaultTransformSource) { return await reactTransformSource(source, context, (s, c) => { return babelTransformSource(s, c, defaultTransformSource); }); } export const transformSource = process.version < 'v16' ? transformSourceImpl : undefined; export const getSource = process.version < 'v16' ? getSourceImpl : undefined;
28.040541
78
0.673184
Python-Penetration-Testing-for-Developers
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {ReactContext, ReactProviderType} from 'shared/ReactTypes'; import type {Fiber} from './ReactInternalTypes'; import {enableLegacyHidden} from 'shared/ReactFeatureFlags'; import { FunctionComponent, ClassComponent, IndeterminateComponent, HostRoot, HostPortal, HostComponent, HostHoistable, HostSingleton, HostText, Fragment, Mode, ContextConsumer, ContextProvider, ForwardRef, Profiler, SuspenseComponent, MemoComponent, SimpleMemoComponent, LazyComponent, IncompleteClassComponent, DehydratedFragment, SuspenseListComponent, ScopeComponent, OffscreenComponent, LegacyHiddenComponent, CacheComponent, TracingMarkerComponent, } from 'react-reconciler/src/ReactWorkTags'; import getComponentNameFromType from 'shared/getComponentNameFromType'; import {REACT_STRICT_MODE_TYPE} from 'shared/ReactSymbols'; // Keep in sync with shared/getComponentNameFromType function getWrappedName( outerType: mixed, innerType: any, wrapperName: string, ): string { const functionName = innerType.displayName || innerType.name || ''; return ( (outerType: any).displayName || (functionName !== '' ? `${wrapperName}(${functionName})` : wrapperName) ); } // Keep in sync with shared/getComponentNameFromType function getContextName(type: ReactContext<any>) { return type.displayName || 'Context'; } export default function getComponentNameFromFiber(fiber: Fiber): string | null { const {tag, type} = fiber; switch (tag) { case CacheComponent: return 'Cache'; case ContextConsumer: const context: ReactContext<any> = (type: any); return getContextName(context) + '.Consumer'; case ContextProvider: const provider: ReactProviderType<any> = (type: any); return getContextName(provider._context) + '.Provider'; case DehydratedFragment: return 'DehydratedFragment'; case ForwardRef: return getWrappedName(type, type.render, 'ForwardRef'); case Fragment: return 'Fragment'; case HostHoistable: case HostSingleton: case HostComponent: // Host component type is the display name (e.g. "div", "View") return type; case HostPortal: return 'Portal'; case HostRoot: return 'Root'; case HostText: return 'Text'; case LazyComponent: // Name comes from the type in this case; we don't have a tag. return getComponentNameFromType(type); case Mode: if (type === REACT_STRICT_MODE_TYPE) { // Don't be less specific than shared/getComponentNameFromType return 'StrictMode'; } return 'Mode'; case OffscreenComponent: return 'Offscreen'; case Profiler: return 'Profiler'; case ScopeComponent: return 'Scope'; case SuspenseComponent: return 'Suspense'; case SuspenseListComponent: return 'SuspenseList'; case TracingMarkerComponent: return 'TracingMarker'; // The display name for this tags come from the user-provided type: case ClassComponent: case FunctionComponent: case IncompleteClassComponent: case IndeterminateComponent: case MemoComponent: case SimpleMemoComponent: if (typeof type === 'function') { return (type: any).displayName || type.name || null; } if (typeof type === 'string') { return type; } break; case LegacyHiddenComponent: if (enableLegacyHidden) { return 'LegacyHidden'; } } return null; }
26.323529
80
0.690713
Penetration_Testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {ReactNodeList, Wakeable} from 'shared/ReactTypes'; import type {Fiber} from './ReactInternalTypes'; import type {SuspenseInstance} from './ReactFiberConfig'; import type {Lane} from './ReactFiberLane'; import type {TreeContext} from './ReactFiberTreeContext'; import {SuspenseComponent, SuspenseListComponent} from './ReactWorkTags'; import {NoFlags, DidCapture} from './ReactFiberFlags'; import { isSuspenseInstancePending, isSuspenseInstanceFallback, } from './ReactFiberConfig'; export type SuspenseProps = { children?: ReactNodeList, fallback?: ReactNodeList, // TODO: Add "unstable_" prefix? suspenseCallback?: (Set<Wakeable> | null) => mixed, unstable_avoidThisFallback?: boolean, unstable_expectedLoadTime?: number, unstable_name?: string, }; // A null SuspenseState represents an unsuspended normal Suspense boundary. // A non-null SuspenseState means that it is blocked for one reason or another. // - A non-null dehydrated field means it's blocked pending hydration. // - A non-null dehydrated field can use isSuspenseInstancePending or // isSuspenseInstanceFallback to query the reason for being dehydrated. // - A null dehydrated field means it's blocked by something suspending and // we're currently showing a fallback instead. export type SuspenseState = { // If this boundary is still dehydrated, we store the SuspenseInstance // here to indicate that it is dehydrated (flag) and for quick access // to check things like isSuspenseInstancePending. dehydrated: null | SuspenseInstance, treeContext: null | TreeContext, // Represents the lane we should attempt to hydrate a dehydrated boundary at. // OffscreenLane is the default for dehydrated boundaries. // NoLane is the default for normal boundaries, which turns into "normal" pri. retryLane: Lane, }; export type SuspenseListTailMode = 'collapsed' | 'hidden' | void; export type SuspenseListRenderState = { isBackwards: boolean, // The currently rendering tail row. rendering: null | Fiber, // The absolute time when we started rendering the most recent tail row. renderingStartTime: number, // The last of the already rendered children. last: null | Fiber, // Remaining rows on the tail of the list. tail: null | Fiber, // Tail insertions setting. tailMode: SuspenseListTailMode, }; export type RetryQueue = Set<Wakeable>; export function findFirstSuspended(row: Fiber): null | Fiber { let node = row; while (node !== null) { if (node.tag === SuspenseComponent) { const state: SuspenseState | null = node.memoizedState; if (state !== null) { const dehydrated: null | SuspenseInstance = state.dehydrated; if ( dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated) ) { return node; } } } else if ( node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't // keep track of whether it suspended or not. node.memoizedProps.revealOrder !== undefined ) { const didSuspend = (node.flags & DidCapture) !== NoFlags; if (didSuspend) { return node; } } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } if (node === row) { return null; } while (node.sibling === null) { if (node.return === null || node.return === row) { return null; } node = node.return; } node.sibling.return = node.return; node = node.sibling; } return null; }
32.206897
80
0.689172
null
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-server.production.min.js'); } else { module.exports = require('./cjs/react-server.development.js'); }
24.625
67
0.676471
null
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react.shared-subset.production.min.js'); } else { module.exports = require('./cjs/react.shared-subset.development.js'); }
26.375
74
0.688073
owtf
/** * Copyright (c) Facebook, Inc. and its affiliates. */ // Do not delete or move this file. // Many fiddles reference it so we have to keep it here. (function() { var tag = document.querySelector( 'script[type="application/javascript;version=1.7"]' ); if (!tag || tag.textContent.indexOf('window.onload=function(){') !== -1) { alert('Bad JSFiddle configuration, please fork the original React JSFiddle'); } tag.setAttribute('type', 'text/jsx;harmony=true'); tag.textContent = tag.textContent.replace(/^\/\/<!\[CDATA\[/, ''); })();
31.764706
81
0.658273
PenetrationTestingScripts
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from 'react-client/src/ReactFlightClientConfigNode'; export * from 'react-server-dom-webpack/src/ReactFlightClientConfigBundlerNode'; export * from 'react-server-dom-webpack/src/ReactFlightClientConfigTargetWebpackServer'; export * from 'react-dom-bindings/src/shared/ReactFlightClientConfigDOM'; export const usedWithSSR = true;
35.266667
88
0.777164
null
'use strict'; module.exports = function shouldIgnoreConsoleError(format, args) { if (__DEV__) { if (typeof format === 'string') { if (format.indexOf('Error: Uncaught [') === 0) { // This looks like an uncaught error from invokeGuardedCallback() wrapper // in development that is reported by jsdom. Ignore because it's noisy. return true; } if (format.indexOf('The above error occurred') === 0) { // This looks like an error addendum from ReactFiberErrorLogger. // Ignore it too. return true; } if ( format.indexOf('ReactDOM.render is no longer supported in React 18') !== -1 || format.indexOf( 'ReactDOM.hydrate is no longer supported in React 18' ) !== -1 ) { // We haven't finished migrating our tests to use createRoot. return true; } } else if ( format != null && typeof format.message === 'string' && typeof format.stack === 'string' && args.length === 0 ) { if (format.stack.indexOf('Error: Uncaught [') === 0) { // This looks like an uncaught error from invokeGuardedCallback() wrapper // in development that is reported by jest-environment-jsdom. Ignore because it's noisy. return true; } } } else { if ( format != null && typeof format.message === 'string' && typeof format.stack === 'string' && args.length === 0 ) { // In production, ReactFiberErrorLogger logs error objects directly. // They are noisy too so we'll try to ignore them. return true; } } // Looks legit return false; };
30.849057
96
0.577949
Hands-On-Penetration-Testing-with-Python
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import ErrorStackParser from 'error-stack-parser'; import testErrorStack, { SOURCE_STACK_FRAME_LINE_NUMBER, } from './ErrorTesterCompiled'; let sourceMapsAreAppliedToErrors: boolean | null = null; // Source maps are automatically applied to Error stack frames. export function areSourceMapsAppliedToErrors(): boolean { if (sourceMapsAreAppliedToErrors === null) { try { testErrorStack(); sourceMapsAreAppliedToErrors = false; } catch (error) { const parsed = ErrorStackParser.parse(error); const topStackFrame = parsed[0]; const lineNumber = topStackFrame.lineNumber; if (lineNumber === SOURCE_STACK_FRAME_LINE_NUMBER) { sourceMapsAreAppliedToErrors = true; } } } return sourceMapsAreAppliedToErrors === true; }
27.285714
66
0.706775
Hands-On-Penetration-Testing-with-Python
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {ReactContext} from 'shared/ReactTypes'; import * as React from 'react'; import {createContext, useMemo, useState} from 'react'; export type DisplayDensity = 'comfortable' | 'compact'; export type Theme = 'auto' | 'light' | 'dark'; type Context = { isModalShowing: boolean, setIsModalShowing: (value: boolean) => void, ... }; const SettingsModalContext: ReactContext<Context> = createContext<Context>( ((null: any): Context), ); SettingsModalContext.displayName = 'SettingsModalContext'; function SettingsModalContextController({ children, }: { children: React$Node, }): React.Node { const [isModalShowing, setIsModalShowing] = useState<boolean>(false); const value = useMemo( () => ({isModalShowing, setIsModalShowing}), [isModalShowing, setIsModalShowing], ); return ( <SettingsModalContext.Provider value={value}> {children} </SettingsModalContext.Provider> ); } export {SettingsModalContext, SettingsModalContextController};
23.44898
75
0.71345
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from './src/ReactFizzServer';
21.181818
66
0.691358
null
'use strict'; module.exports = { globalSetup: require.resolve('./setupGlobal.js'), modulePathIgnorePatterns: [ '<rootDir>/scripts/rollup/shims/', '<rootDir>/scripts/bench/', ], transform: { '.*': require.resolve('./preprocessor.js'), }, setupFiles: [require.resolve('./setupEnvironment.js')], setupFilesAfterEnv: [require.resolve('./setupTests.js')], // Only include files directly in __tests__, not in nested folders. testRegex: '/__tests__/[^/]*(\\.js|\\.coffee|[^d]\\.ts)$', moduleFileExtensions: ['js', 'json', 'node', 'coffee', 'ts'], rootDir: process.cwd(), roots: ['<rootDir>/packages', '<rootDir>/scripts'], collectCoverageFrom: ['packages/**/*.js'], fakeTimers: { enableGlobally: true, legacyFakeTimers: true, }, snapshotSerializers: [require.resolve('jest-snapshot-serializer-raw')], testSequencer: require.resolve('./jestSequencer'), testEnvironment: 'jsdom', testRunner: 'jest-circus/runner', };
29.34375
73
0.654639
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export {default as __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED} from './src/ReactDOMSharedInternals'; export { createPortal, createRoot, hydrateRoot, findDOMNode, flushSync, hydrate, render, unmountComponentAtNode, unstable_batchedUpdates, unstable_renderSubtreeIntoContainer, useFormStatus, useFormState, prefetchDNS, preconnect, preload, preloadModule, preinit, preinitModule, version, } from './src/client/ReactDOM';
19.9375
108
0.729447
Python-Penetration-Testing-for-Developers
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import {preinitModuleForSSR} from 'react-client/src/ReactFlightClientConfig'; export type ModuleLoading = | null | string | { prefix: string, crossOrigin?: string, }; export function prepareDestinationForModuleImpl( moduleLoading: ModuleLoading, // Chunks are double-indexed [..., idx, filenamex, idy, filenamey, ...] mod: string, nonce: ?string, ) { if (typeof moduleLoading === 'string') { preinitModuleForSSR(moduleLoading + mod, nonce, undefined); } else if (moduleLoading !== null) { preinitModuleForSSR( moduleLoading.prefix + mod, nonce, moduleLoading.crossOrigin, ); } }
22.666667
77
0.674501
cybersecurity-penetration-testing
let ReactDOM = require('react-dom'); describe('ReactDOMRoot', () => { let container; beforeEach(() => { jest.resetModules(); container = document.createElement('div'); ReactDOM = require('react-dom'); }); afterEach(() => { jest.restoreAllMocks(); }); test('deprecation warning for ReactDOM.render', () => { spyOnDev(console, 'error'); ReactDOM.render('Hi', container); expect(container.textContent).toEqual('Hi'); if (__DEV__) { expect(console.error).toHaveBeenCalledTimes(1); expect(console.error.mock.calls[0][0]).toContain( 'ReactDOM.render is no longer supported', ); } }); test('deprecation warning for ReactDOM.hydrate', () => { spyOnDev(console, 'error'); container.innerHTML = 'Hi'; ReactDOM.hydrate('Hi', container); expect(container.textContent).toEqual('Hi'); if (__DEV__) { expect(console.error).toHaveBeenCalledTimes(1); expect(console.error.mock.calls[0][0]).toContain( 'ReactDOM.hydrate is no longer supported', ); } }); });
24.069767
58
0.613742
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core * @jest-environment ./scripts/jest/ReactDOMServerIntegrationEnvironment */ 'use strict'; import { insertNodesAndExecuteScripts, mergeOptions, withLoadingReadyState, } from '../test-utils/FizzTestUtils'; let JSDOM; let Stream; let React; let ReactDOM; let ReactDOMClient; let ReactDOMFizzServer; let Suspense; let textCache; let loadCache; let writable; const CSPnonce = null; let container; let buffer = ''; let hasErrored = false; let fatalError = undefined; let renderOptions; let waitForAll; let waitForThrow; let assertLog; let Scheduler; let clientAct; let streamingContainer; describe('ReactDOMFloat', () => { beforeEach(() => { jest.resetModules(); JSDOM = require('jsdom').JSDOM; const jsdom = new JSDOM( '<!DOCTYPE html><html><head></head><body><div id="container">', { runScripts: 'dangerously', }, ); // We mock matchMedia. for simplicity it only matches 'all' or '' and misses everything else Object.defineProperty(jsdom.window, 'matchMedia', { writable: true, value: jest.fn().mockImplementation(query => ({ matches: query === 'all' || query === '', media: query, })), }); streamingContainer = null; global.window = jsdom.window; global.document = global.window.document; global.navigator = global.window.navigator; global.Node = global.window.Node; global.addEventListener = global.window.addEventListener; global.MutationObserver = global.window.MutationObserver; container = document.getElementById('container'); React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); ReactDOMFizzServer = require('react-dom/server'); Stream = require('stream'); Suspense = React.Suspense; Scheduler = require('scheduler/unstable_mock'); const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; waitForThrow = InternalTestUtils.waitForThrow; assertLog = InternalTestUtils.assertLog; clientAct = InternalTestUtils.act; textCache = new Map(); loadCache = new Set(); buffer = ''; hasErrored = false; writable = new Stream.PassThrough(); writable.setEncoding('utf8'); writable.on('data', chunk => { buffer += chunk; }); writable.on('error', error => { hasErrored = true; fatalError = error; }); renderOptions = {}; if (gate(flags => flags.enableFizzExternalRuntime)) { renderOptions.unstable_externalRuntimeSrc = 'react-dom/unstable_server-external-runtime'; } }); const bodyStartMatch = /<body(?:>| .*?>)/; const headStartMatch = /<head(?:>| .*?>)/; async function act(callback) { await callback(); // Await one turn around the event loop. // This assumes that we'll flush everything we have so far. await new Promise(resolve => { setImmediate(resolve); }); if (hasErrored) { throw fatalError; } // JSDOM doesn't support stream HTML parser so we need to give it a proper fragment. // We also want to execute any scripts that are embedded. // We assume that we have now received a proper fragment of HTML. let bufferedContent = buffer; buffer = ''; if (!bufferedContent) { return; } await withLoadingReadyState(async () => { const bodyMatch = bufferedContent.match(bodyStartMatch); const headMatch = bufferedContent.match(headStartMatch); if (streamingContainer === null) { // This is the first streamed content. We decide here where to insert it. If we get <html>, <head>, or <body> // we abandon the pre-built document and start from scratch. If we get anything else we assume it goes into the // container. This is not really production behavior because you can't correctly stream into a deep div effectively // but it's pragmatic for tests. if ( bufferedContent.startsWith('<head>') || bufferedContent.startsWith('<head ') || bufferedContent.startsWith('<body>') || bufferedContent.startsWith('<body ') ) { // wrap in doctype to normalize the parsing process bufferedContent = '<!DOCTYPE html><html>' + bufferedContent; } else if ( bufferedContent.startsWith('<html>') || bufferedContent.startsWith('<html ') ) { throw new Error( 'Recieved <html> without a <!DOCTYPE html> which is almost certainly a bug in React', ); } if (bufferedContent.startsWith('<!DOCTYPE html>')) { // we can just use the whole document const tempDom = new JSDOM(bufferedContent); // Wipe existing head and body content document.head.innerHTML = ''; document.body.innerHTML = ''; // Copy the <html> attributes over const tempHtmlNode = tempDom.window.document.documentElement; for (let i = 0; i < tempHtmlNode.attributes.length; i++) { const attr = tempHtmlNode.attributes[i]; document.documentElement.setAttribute(attr.name, attr.value); } if (headMatch) { // We parsed a head open tag. we need to copy head attributes and insert future // content into <head> streamingContainer = document.head; const tempHeadNode = tempDom.window.document.head; for (let i = 0; i < tempHeadNode.attributes.length; i++) { const attr = tempHeadNode.attributes[i]; document.head.setAttribute(attr.name, attr.value); } const source = document.createElement('head'); source.innerHTML = tempHeadNode.innerHTML; await insertNodesAndExecuteScripts(source, document.head, CSPnonce); } if (bodyMatch) { // We parsed a body open tag. we need to copy head attributes and insert future // content into <body> streamingContainer = document.body; const tempBodyNode = tempDom.window.document.body; for (let i = 0; i < tempBodyNode.attributes.length; i++) { const attr = tempBodyNode.attributes[i]; document.body.setAttribute(attr.name, attr.value); } const source = document.createElement('body'); source.innerHTML = tempBodyNode.innerHTML; await insertNodesAndExecuteScripts(source, document.body, CSPnonce); } if (!headMatch && !bodyMatch) { throw new Error('expected <head> or <body> after <html>'); } } else { // we assume we are streaming into the default container' streamingContainer = container; const div = document.createElement('div'); div.innerHTML = bufferedContent; await insertNodesAndExecuteScripts(div, container, CSPnonce); } } else if (streamingContainer === document.head) { bufferedContent = '<!DOCTYPE html><html><head>' + bufferedContent; const tempDom = new JSDOM(bufferedContent); const tempHeadNode = tempDom.window.document.head; const source = document.createElement('head'); source.innerHTML = tempHeadNode.innerHTML; await insertNodesAndExecuteScripts(source, document.head, CSPnonce); if (bodyMatch) { streamingContainer = document.body; const tempBodyNode = tempDom.window.document.body; for (let i = 0; i < tempBodyNode.attributes.length; i++) { const attr = tempBodyNode.attributes[i]; document.body.setAttribute(attr.name, attr.value); } const bodySource = document.createElement('body'); bodySource.innerHTML = tempBodyNode.innerHTML; await insertNodesAndExecuteScripts( bodySource, document.body, CSPnonce, ); } } else { const div = document.createElement('div'); div.innerHTML = bufferedContent; await insertNodesAndExecuteScripts(div, streamingContainer, CSPnonce); } }, document); } function getMeaningfulChildren(element) { const children = []; let node = element.firstChild; while (node) { if (node.nodeType === 1) { if ( // some tags are ambiguous and might be hidden because they look like non-meaningful children // so we have a global override where if this data attribute is included we also include the node node.hasAttribute('data-meaningful') || (node.tagName === 'SCRIPT' && node.hasAttribute('src') && node.getAttribute('src') !== renderOptions.unstable_externalRuntimeSrc && node.hasAttribute('async')) || (node.tagName !== 'SCRIPT' && node.tagName !== 'TEMPLATE' && node.tagName !== 'template' && !node.hasAttribute('hidden') && !node.hasAttribute('aria-hidden')) ) { const props = {}; const attributes = node.attributes; for (let i = 0; i < attributes.length; i++) { if ( attributes[i].name === 'id' && attributes[i].value.includes(':') ) { // We assume this is a React added ID that's a non-visual implementation detail. continue; } props[attributes[i].name] = attributes[i].value; } props.children = getMeaningfulChildren(node); children.push(React.createElement(node.tagName.toLowerCase(), props)); } } else if (node.nodeType === 3) { children.push(node.data); } node = node.nextSibling; } return children.length === 0 ? undefined : children.length === 1 ? children[0] : children; } function BlockedOn({value, children}) { readText(value); return children; } function resolveText(text) { const record = textCache.get(text); if (record === undefined) { const newRecord = { status: 'resolved', value: text, }; textCache.set(text, newRecord); } else if (record.status === 'pending') { const thenable = record.value; record.status = 'resolved'; record.value = text; thenable.pings.forEach(t => t()); } } function readText(text) { const record = textCache.get(text); if (record !== undefined) { switch (record.status) { case 'pending': throw record.value; case 'rejected': throw record.value; case 'resolved': return record.value; } } else { const thenable = { pings: [], then(resolve) { if (newRecord.status === 'pending') { thenable.pings.push(resolve); } else { Promise.resolve().then(() => resolve(newRecord.value)); } }, }; const newRecord = { status: 'pending', value: thenable, }; textCache.set(text, newRecord); throw thenable; } } function AsyncText({text}) { return readText(text); } function renderToPipeableStream(jsx, options) { // Merge options with renderOptions, which may contain featureFlag specific behavior return ReactDOMFizzServer.renderToPipeableStream( jsx, mergeOptions(options, renderOptions), ); } function loadPreloads(hrefs) { const event = new window.Event('load'); const nodes = document.querySelectorAll('link[rel="preload"]'); resolveLoadables(hrefs, nodes, event, href => Scheduler.log('load preload: ' + href), ); } function errorPreloads(hrefs) { const event = new window.Event('error'); const nodes = document.querySelectorAll('link[rel="preload"]'); resolveLoadables(hrefs, nodes, event, href => Scheduler.log('error preload: ' + href), ); } function loadStylesheets(hrefs) { const event = new window.Event('load'); const nodes = document.querySelectorAll('link[rel="stylesheet"]'); resolveLoadables(hrefs, nodes, event, href => Scheduler.log('load stylesheet: ' + href), ); } function errorStylesheets(hrefs) { const event = new window.Event('error'); const nodes = document.querySelectorAll('link[rel="stylesheet"]'); resolveLoadables(hrefs, nodes, event, href => { Scheduler.log('error stylesheet: ' + href); }); } function resolveLoadables(hrefs, nodes, event, onLoad) { const hrefSet = hrefs ? new Set(hrefs) : null; for (let i = 0; i < nodes.length; i++) { const node = nodes[i]; if (loadCache.has(node)) { continue; } const href = node.getAttribute('href'); if (!hrefSet || hrefSet.has(href)) { loadCache.add(node); onLoad(href); node.dispatchEvent(event); } } } // @gate enableFloat it('can render resources before singletons', async () => { const root = ReactDOMClient.createRoot(document); root.render( <> <title>foo</title> <html> <head> <link rel="foo" href="foo" /> </head> <body>hello world</body> </html> </>, ); try { await waitForAll([]); } catch (e) { // for DOMExceptions that happen when expecting this test to fail we need // to clear the scheduler first otherwise the expected failure will fail await waitForAll([]); throw e; } expect(getMeaningfulChildren(document)).toEqual( <html> <head> <title>foo</title> <link rel="foo" href="foo" /> </head> <body>hello world</body> </html>, ); }); // @gate enableFloat it('can hydrate non Resources in head when Resources are also inserted there', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <head> <meta property="foo" content="bar" /> <link rel="foo" href="bar" onLoad={() => {}} /> <title>foo</title> <noscript> <link rel="icon" href="icon" /> </noscript> <base target="foo" href="bar" /> <script async={true} src="foo" onLoad={() => {}} /> </head> <body>foo</body> </html>, ); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <meta property="foo" content="bar" /> <title>foo</title> <link rel="foo" href="bar" /> <noscript>&lt;link rel="icon" href="icon"&gt;</noscript> <base target="foo" href="bar" /> <script async="" src="foo" /> </head> <body>foo</body> </html>, ); ReactDOMClient.hydrateRoot( document, <html> <head> <meta property="foo" content="bar" /> <link rel="foo" href="bar" onLoad={() => {}} /> <title>foo</title> <noscript> <link rel="icon" href="icon" /> </noscript> <base target="foo" href="bar" /> <script async={true} src="foo" onLoad={() => {}} /> </head> <body>foo</body> </html>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <meta property="foo" content="bar" /> <title>foo</title> <link rel="foo" href="bar" /> <noscript>&lt;link rel="icon" href="icon"&gt;</noscript> <base target="foo" href="bar" /> <script async="" src="foo" /> </head> <body>foo</body> </html>, ); }); // @gate enableFloat || !__DEV__ it('warns if you render resource-like elements above <head> or <body>', async () => { const root = ReactDOMClient.createRoot(document); await expect(async () => { root.render( <> <noscript>foo</noscript> <html> <body>foo</body> </html> </>, ); const aggregateError = await waitForThrow(); expect(aggregateError.errors.length).toBe(2); expect(aggregateError.errors[0].message).toContain( 'Invalid insertion of NOSCRIPT', ); expect(aggregateError.errors[1].message).toContain( 'The node to be removed is not a child of this node', ); }).toErrorDev( [ 'Cannot render <noscript> outside the main document. Try moving it into the root <head> tag.', 'Warning: validateDOMNesting(...): <noscript> cannot appear as a child of <#document>.', ], {withoutStack: 1}, ); await expect(async () => { root.render( <html> <template>foo</template> <body>foo</body> </html>, ); await waitForAll([]); }).toErrorDev([ 'Cannot render <template> outside the main document. Try moving it into the root <head> tag.', 'Warning: validateDOMNesting(...): <template> cannot appear as a child of <html>.', ]); await expect(async () => { root.render( <html> <body>foo</body> <style>foo</style> </html>, ); await waitForAll([]); }).toErrorDev([ 'Cannot render a <style> outside the main document without knowing its precedence and a unique href key. React can hoist and deduplicate <style> tags if you provide a `precedence` prop along with an `href` prop that does not conflic with the `href` values used in any other hoisted <style> or <link rel="stylesheet" ...> tags. Note that hoisting <style> tags is considered an advanced feature that most will not use directly. Consider moving the <style> tag to the <head> or consider adding a `precedence="default"` and `href="some unique resource identifier"`, or move the <style> to the <style> tag.', 'Warning: validateDOMNesting(...): <style> cannot appear as a child of <html>.', ]); await expect(async () => { root.render( <> <html> <body>foo</body> </html> <link rel="stylesheet" href="foo" /> </>, ); const aggregateError = await waitForThrow(); expect(aggregateError.errors.length).toBe(2); expect(aggregateError.errors[0].message).toContain( 'Invalid insertion of LINK', ); expect(aggregateError.errors[1].message).toContain( 'The node to be removed is not a child of this node', ); }).toErrorDev( [ 'Cannot render a <link rel="stylesheet" /> outside the main document without knowing its precedence. Consider adding precedence="default" or moving it into the root <head> tag.', 'Warning: validateDOMNesting(...): <link> cannot appear as a child of <#document>.', ], {withoutStack: 1}, ); await expect(async () => { root.render( <> <html> <body>foo</body> <script href="foo" /> </html> </>, ); await waitForAll([]); }).toErrorDev([ 'Cannot render a sync or defer <script> outside the main document without knowing its order. Try adding async="" or moving it into the root <head> tag.', 'Warning: validateDOMNesting(...): <script> cannot appear as a child of <html>.', ]); await expect(async () => { root.render( <html> <script async={true} onLoad={() => {}} href="bar" /> <body>foo</body> </html>, ); await waitForAll([]); }).toErrorDev([ 'Cannot render a <script> with onLoad or onError listeners outside the main document. Try removing onLoad={...} and onError={...} or moving it into the root <head> tag or somewhere in the <body>.', ]); await expect(async () => { root.render( <> <link rel="foo" onLoad={() => {}} href="bar" /> <html> <body>foo</body> </html> </>, ); const aggregateError = await waitForThrow(); expect(aggregateError.errors.length).toBe(2); expect(aggregateError.errors[0].message).toContain( 'Invalid insertion of LINK', ); expect(aggregateError.errors[1].message).toContain( 'The node to be removed is not a child of this node', ); }).toErrorDev( [ 'Cannot render a <link> with onLoad or onError listeners outside the main document. Try removing onLoad={...} and onError={...} or moving it into the root <head> tag or somewhere in the <body>.', ], {withoutStack: 1}, ); }); // @gate enableFloat it('can acquire a resource after releasing it in the same commit', async () => { const root = ReactDOMClient.createRoot(container); root.render( <> <script async={true} src="foo" /> </>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <script async="" src="foo" /> </head> <body> <div id="container" /> </body> </html>, ); root.render( <> {null} <script data-new="new" async={true} src="foo" /> </>, ); await waitForAll([]); // we don't see the attribute because the resource is the same and was not reconstructed expect(getMeaningfulChildren(document)).toEqual( <html> <head> <script async="" src="foo" /> </head> <body> <div id="container" /> </body> </html>, ); }); // @gate enableFloat it('emits resources before everything else when rendering with no head', async () => { function App() { return ( <> <title>foo</title> <link rel="preload" href="foo" as="style" /> </> ); } await act(() => { buffer = `<!DOCTYPE html><html><head>${ReactDOMFizzServer.renderToString( <App />, )}</head><body>foo</body></html>`; }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" href="foo" as="style" /> <title>foo</title> </head> <body>foo</body> </html>, ); }); // @gate enableFloat it('emits resources before everything else when rendering with just a head', async () => { function App() { return ( <head> <title>foo</title> <link rel="preload" href="foo" as="style" /> </head> ); } await act(() => { buffer = `<!DOCTYPE html><html>${ReactDOMFizzServer.renderToString( <App />, )}<body>foo</body></html>`; }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" href="foo" as="style" /> <title>foo</title> </head> <body>foo</body> </html>, ); }); // @gate enableFloat it('emits an implicit <head> element to hold resources when none is rendered but an <html> is rendered', async () => { const chunks = []; writable.on('data', chunk => { chunks.push(chunk); }); await act(() => { const {pipe} = renderToPipeableStream( <> <title>foo</title> <html> <body>bar</body> </html> <script async={true} src="foo" /> </>, ); pipe(writable); }); expect(chunks).toEqual([ '<!DOCTYPE html><html><head><script async="" src="foo"></script><title>foo</title></head><body>bar', '</body></html>', ]); }); // @gate enableFloat it('dedupes if the external runtime is explicitly loaded using preinit', async () => { const unstable_externalRuntimeSrc = 'src-of-external-runtime'; function App() { ReactDOM.preinit(unstable_externalRuntimeSrc, {as: 'script'}); return ( <div> <Suspense fallback={<h1>Loading...</h1>}> <AsyncText text="Hello" /> </Suspense> </div> ); } await act(() => { const {pipe} = renderToPipeableStream( <html> <head /> <body> <App /> </body> </html>, { unstable_externalRuntimeSrc, }, ); pipe(writable); }); expect( Array.from(document.getElementsByTagName('script')).map(n => n.outerHTML), ).toEqual(['<script src="src-of-external-runtime" async=""></script>']); }); // @gate enableFloat it('can avoid inserting a late stylesheet if it already rendered on the client', async () => { await act(() => { renderToPipeableStream( <html> <body> <Suspense fallback="loading foo..."> <BlockedOn value="foo"> <link rel="stylesheet" href="foo" precedence="foo" /> foo </BlockedOn> </Suspense> <Suspense fallback="loading bar..."> <BlockedOn value="bar"> <link rel="stylesheet" href="bar" precedence="bar" /> bar </BlockedOn> </Suspense> </body> </html>, ).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body> {'loading foo...'} {'loading bar...'} </body> </html>, ); ReactDOMClient.hydrateRoot( document, <html> <body> <link rel="stylesheet" href="foo" precedence="foo" /> <Suspense fallback="loading foo..."> <link rel="stylesheet" href="foo" precedence="foo" /> foo </Suspense> <Suspense fallback="loading bar..."> <link rel="stylesheet" href="bar" precedence="bar" /> bar </Suspense> </body> </html>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="foo" /> <link as="style" href="foo" rel="preload" /> </head> <body> {'loading foo...'} {'loading bar...'} </body> </html>, ); await act(() => { resolveText('bar'); }); await act(() => { const sheets = document.querySelectorAll( 'link[rel="stylesheet"][data-precedence]', ); const event = document.createEvent('Event'); event.initEvent('load', true, true); for (let i = 0; i < sheets.length; i++) { sheets[i].dispatchEvent(event); } }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="foo" /> <link rel="stylesheet" href="bar" data-precedence="bar" /> <link as="style" href="foo" rel="preload" /> </head> <body> {'loading foo...'} {'bar'} <link as="style" href="bar" rel="preload" /> </body> </html>, ); await act(() => { resolveText('foo'); }); await act(() => { const sheets = document.querySelectorAll( 'link[rel="stylesheet"][data-precedence]', ); const event = document.createEvent('Event'); event.initEvent('load', true, true); for (let i = 0; i < sheets.length; i++) { sheets[i].dispatchEvent(event); } }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="foo" /> <link rel="stylesheet" href="bar" data-precedence="bar" /> <link as="style" href="foo" rel="preload" /> </head> <body> {'foo'} {'bar'} <link as="style" href="bar" rel="preload" /> <link as="style" href="foo" rel="preload" /> </body> </html>, ); }); // @gate enableFloat it('can hoist <link rel="stylesheet" .../> and <style /> tags together, respecting order of discovery', async () => { const css = ` body { background-color: red; }`; await act(() => { renderToPipeableStream( <html> <body> <link rel="stylesheet" href="one1" precedence="one" /> <style href="two1" precedence="two"> {css} </style> <link rel="stylesheet" href="three1" precedence="three" /> <style href="four1" precedence="four"> {css} </style> <Suspense> <BlockedOn value="block"> <link rel="stylesheet" href="one2" precedence="one" /> <link rel="stylesheet" href="two2" precedence="two" /> <style href="three2" precedence="three"> {css} </style> <style href="four2" precedence="four"> {css} </style> <link rel="stylesheet" href="five1" precedence="five" /> </BlockedOn> </Suspense> <Suspense> <BlockedOn value="block2"> <style href="one3" precedence="one"> {css} </style> <style href="two3" precedence="two"> {css} </style> <link rel="stylesheet" href="three3" precedence="three" /> <link rel="stylesheet" href="four3" precedence="four" /> <style href="six1" precedence="six"> {css} </style> </BlockedOn> </Suspense> <Suspense> <BlockedOn value="block again"> <link rel="stylesheet" href="one2" precedence="one" /> <link rel="stylesheet" href="two2" precedence="two" /> <style href="three2" precedence="three"> {css} </style> <style href="four2" precedence="four"> {css} </style> <link rel="stylesheet" href="five1" precedence="five" /> </BlockedOn> </Suspense> </body> </html>, ).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="one1" data-precedence="one" /> <style data-href="two1" data-precedence="two"> {css} </style> <link rel="stylesheet" href="three1" data-precedence="three" /> <style data-href="four1" data-precedence="four"> {css} </style> </head> <body /> </html>, ); await act(() => { resolveText('block'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="one1" data-precedence="one" /> <link rel="stylesheet" href="one2" data-precedence="one" /> <style data-href="two1" data-precedence="two"> {css} </style> <link rel="stylesheet" href="two2" data-precedence="two" /> <link rel="stylesheet" href="three1" data-precedence="three" /> <style data-href="three2" data-precedence="three"> {css} </style> <style data-href="four1" data-precedence="four"> {css} </style> <style data-href="four2" data-precedence="four"> {css} </style> <link rel="stylesheet" href="five1" data-precedence="five" /> </head> <body> <link rel="preload" href="one2" as="style" /> <link rel="preload" href="two2" as="style" /> <link rel="preload" href="five1" as="style" /> </body> </html>, ); await act(() => { resolveText('block2'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="one1" data-precedence="one" /> <link rel="stylesheet" href="one2" data-precedence="one" /> <style data-href="one3" data-precedence="one"> {css} </style> <style data-href="two1" data-precedence="two"> {css} </style> <link rel="stylesheet" href="two2" data-precedence="two" /> <style data-href="two3" data-precedence="two"> {css} </style> <link rel="stylesheet" href="three1" data-precedence="three" /> <style data-href="three2" data-precedence="three"> {css} </style> <link rel="stylesheet" href="three3" data-precedence="three" /> <style data-href="four1" data-precedence="four"> {css} </style> <style data-href="four2" data-precedence="four"> {css} </style> <link rel="stylesheet" href="four3" data-precedence="four" /> <link rel="stylesheet" href="five1" data-precedence="five" /> <style data-href="six1" data-precedence="six"> {css} </style> </head> <body> <link rel="preload" href="one2" as="style" /> <link rel="preload" href="two2" as="style" /> <link rel="preload" href="five1" as="style" /> <link rel="preload" href="three3" as="style" /> <link rel="preload" href="four3" as="style" /> </body> </html>, ); await act(() => { resolveText('block again'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="one1" data-precedence="one" /> <link rel="stylesheet" href="one2" data-precedence="one" /> <style data-href="one3" data-precedence="one"> {css} </style> <style data-href="two1" data-precedence="two"> {css} </style> <link rel="stylesheet" href="two2" data-precedence="two" /> <style data-href="two3" data-precedence="two"> {css} </style> <link rel="stylesheet" href="three1" data-precedence="three" /> <style data-href="three2" data-precedence="three"> {css} </style> <link rel="stylesheet" href="three3" data-precedence="three" /> <style data-href="four1" data-precedence="four"> {css} </style> <style data-href="four2" data-precedence="four"> {css} </style> <link rel="stylesheet" href="four3" data-precedence="four" /> <link rel="stylesheet" href="five1" data-precedence="five" /> <style data-href="six1" data-precedence="six"> {css} </style> </head> <body> <link rel="preload" href="one2" as="style" /> <link rel="preload" href="two2" as="style" /> <link rel="preload" href="five1" as="style" /> <link rel="preload" href="three3" as="style" /> <link rel="preload" href="four3" as="style" /> </body> </html>, ); ReactDOMClient.hydrateRoot( document, <html> <body> <link rel="stylesheet" href="one4" precedence="one" /> <style href="two4" precedence="two"> {css} </style> <link rel="stylesheet" href="three4" precedence="three" /> <style href="four4" precedence="four"> {css} </style> <link rel="stylesheet" href="seven1" precedence="seven" /> <style href="eight1" precedence="eight"> {css} </style> </body> </html>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="one1" data-precedence="one" /> <link rel="stylesheet" href="one2" data-precedence="one" /> <style data-href="one3" data-precedence="one"> {css} </style> <link rel="stylesheet" href="one4" data-precedence="one" /> <style data-href="two1" data-precedence="two"> {css} </style> <link rel="stylesheet" href="two2" data-precedence="two" /> <style data-href="two3" data-precedence="two"> {css} </style> <style data-href="two4" data-precedence="two"> {css} </style> <link rel="stylesheet" href="three1" data-precedence="three" /> <style data-href="three2" data-precedence="three"> {css} </style> <link rel="stylesheet" href="three3" data-precedence="three" /> <link rel="stylesheet" href="three4" data-precedence="three" /> <style data-href="four1" data-precedence="four"> {css} </style> <style data-href="four2" data-precedence="four"> {css} </style> <link rel="stylesheet" href="four3" data-precedence="four" /> <style data-href="four4" data-precedence="four"> {css} </style> <link rel="stylesheet" href="five1" data-precedence="five" /> <style data-href="six1" data-precedence="six"> {css} </style> <link rel="stylesheet" href="seven1" data-precedence="seven" /> <style data-href="eight1" data-precedence="eight"> {css} </style> <link rel="preload" href="one4" as="style" /> <link rel="preload" href="three4" as="style" /> <link rel="preload" href="seven1" as="style" /> </head> <body> <link rel="preload" href="one2" as="style" /> <link rel="preload" href="two2" as="style" /> <link rel="preload" href="five1" as="style" /> <link rel="preload" href="three3" as="style" /> <link rel="preload" href="four3" as="style" /> </body> </html>, ); }); // @gate enableFloat it('client renders a boundary if a style Resource dependency fails to load', async () => { function App() { return ( <html> <head /> <body> <Suspense fallback="loading..."> <BlockedOn value="unblock"> <link rel="stylesheet" href="foo" precedence="arbitrary" /> <link rel="stylesheet" href="bar" precedence="arbitrary" /> Hello </BlockedOn> </Suspense> </body> </html> ); } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); await act(() => { resolveText('unblock'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="arbitrary" /> <link rel="stylesheet" href="bar" data-precedence="arbitrary" /> </head> <body> loading... <link rel="preload" href="foo" as="style" /> <link rel="preload" href="bar" as="style" /> </body> </html>, ); errorStylesheets(['bar']); assertLog(['error stylesheet: bar']); await waitForAll([]); const boundaryTemplateInstance = document.getElementById('B:0'); const suspenseInstance = boundaryTemplateInstance.previousSibling; expect(suspenseInstance.data).toEqual('$!'); expect(boundaryTemplateInstance.dataset.dgst).toBe( 'Resource failed to load', ); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="arbitrary" /> <link rel="stylesheet" href="bar" data-precedence="arbitrary" /> </head> <body> loading... <link rel="preload" href="foo" as="style" /> <link rel="preload" href="bar" as="style" /> </body> </html>, ); const errors = []; ReactDOMClient.hydrateRoot(document, <App />, { onRecoverableError(err, errInfo) { errors.push(err.message); errors.push(err.digest); }, }); await waitForAll([]); // When binding a stylesheet that was SSR'd in a boundary reveal there is a loadingState promise // We need to use that promise to resolve the suspended commit because we don't know if the load or error // events have already fired. This requires the load to be awaited for the commit to have a chance to flush // We could change this by tracking the loadingState's fulfilled status directly on the loadingState similar // to thenables however this slightly increases the fizz runtime code size. await clientAct(() => loadStylesheets()); assertLog(['load stylesheet: foo']); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="arbitrary" /> <link rel="stylesheet" href="bar" data-precedence="arbitrary" /> </head> <body> <link rel="preload" href="foo" as="style" /> <link rel="preload" href="bar" as="style" /> Hello </body> </html>, ); expect(errors).toEqual([ 'The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering.', 'Resource failed to load', ]); }); // @gate enableFloat it('treats stylesheet links with a precedence as a resource', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <head /> <body> <link rel="stylesheet" href="foo" precedence="arbitrary" /> Hello </body> </html>, ); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="arbitrary" /> </head> <body>Hello</body> </html>, ); ReactDOMClient.hydrateRoot( document, <html> <head /> <body>Hello</body> </html>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="arbitrary" /> </head> <body>Hello</body> </html>, ); }); // @gate enableFloat it('inserts text separators following text when followed by an element that is converted to a resource and thus removed from the html inline', async () => { // If you render many of these as siblings the values get emitted as a single text with no separator sometimes // because the link gets elided as a resource function AsyncTextWithResource({text, href, precedence}) { const value = readText(text); return ( <> {value} <link rel="stylesheet" href={href} precedence={precedence} /> </> ); } await act(() => { const {pipe} = renderToPipeableStream( <html> <head /> <body> <AsyncTextWithResource text="foo" href="foo" precedence="one" /> <AsyncTextWithResource text="bar" href="bar" precedence="two" /> <AsyncTextWithResource text="baz" href="baz" precedence="three" /> </body> </html>, ); pipe(writable); resolveText('foo'); resolveText('bar'); resolveText('baz'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="one" /> <link rel="stylesheet" href="bar" data-precedence="two" /> <link rel="stylesheet" href="baz" data-precedence="three" /> </head> <body> {'foo'} {'bar'} {'baz'} </body> </html>, ); }); // @gate enableFloat it('hoists late stylesheets the correct precedence', async () => { function PresetPrecedence() { ReactDOM.preinit('preset', {as: 'style', precedence: 'preset'}); } await act(() => { const {pipe} = renderToPipeableStream( <html> <head /> <body> <link rel="stylesheet" href="initial" precedence="one" /> <PresetPrecedence /> <div> <Suspense fallback="loading foo bar..."> <div>foo</div> <link rel="stylesheet" href="foo" precedence="one" /> <BlockedOn value="bar"> <div>bar</div> <link rel="stylesheet" href="bar" precedence="default" /> </BlockedOn> </Suspense> </div> <div> <Suspense fallback="loading bar baz qux..."> <BlockedOn value="bar"> <div>bar</div> <link rel="stylesheet" href="bar" precedence="default" /> </BlockedOn> <BlockedOn value="baz"> <div>baz</div> <link rel="stylesheet" href="baz" precedence="two" /> </BlockedOn> <BlockedOn value="qux"> <div>qux</div> <link rel="stylesheet" href="qux" precedence="one" /> </BlockedOn> </Suspense> </div> <div> <Suspense fallback="loading bar baz qux..."> <BlockedOn value="unblock"> <BlockedOn value="bar"> <div>bar</div> <link rel="stylesheet" href="bar" precedence="default" /> </BlockedOn> <BlockedOn value="baz"> <div>baz</div> <link rel="stylesheet" href="baz" precedence="two" /> </BlockedOn> <BlockedOn value="qux"> <div>qux</div> <link rel="stylesheet" href="qux" precedence="one" /> </BlockedOn> </BlockedOn> </Suspense> </div> </body> </html>, ); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="initial" data-precedence="one" /> <link rel="stylesheet" href="foo" data-precedence="one" /> <link rel="stylesheet" href="preset" data-precedence="preset" /> </head> <body> <div>loading foo bar...</div> <div>loading bar baz qux...</div> <div>loading bar baz qux...</div> </body> </html>, ); await act(() => { resolveText('foo'); resolveText('bar'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="initial" data-precedence="one" /> <link rel="stylesheet" href="foo" data-precedence="one" /> <link rel="stylesheet" href="preset" data-precedence="preset" /> <link rel="stylesheet" href="bar" data-precedence="default" /> </head> <body> <div>loading foo bar...</div> <div>loading bar baz qux...</div> <div>loading bar baz qux...</div> <link rel="preload" href="bar" as="style" /> </body> </html>, ); await act(() => { const link = document.querySelector('link[rel="stylesheet"][href="foo"]'); const event = document.createEvent('Events'); event.initEvent('load', true, true); link.dispatchEvent(event); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="initial" data-precedence="one" /> <link rel="stylesheet" href="foo" data-precedence="one" /> <link rel="stylesheet" href="preset" data-precedence="preset" /> <link rel="stylesheet" href="bar" data-precedence="default" /> </head> <body> <div>loading foo bar...</div> <div>loading bar baz qux...</div> <div>loading bar baz qux...</div> <link rel="preload" href="bar" as="style" /> </body> </html>, ); await act(() => { const link = document.querySelector('link[rel="stylesheet"][href="bar"]'); const event = document.createEvent('Events'); event.initEvent('load', true, true); link.dispatchEvent(event); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="initial" data-precedence="one" /> <link rel="stylesheet" href="foo" data-precedence="one" /> <link rel="stylesheet" href="preset" data-precedence="preset" /> <link rel="stylesheet" href="bar" data-precedence="default" /> </head> <body> <div> <div>foo</div> <div>bar</div> </div> <div>loading bar baz qux...</div> <div>loading bar baz qux...</div> <link rel="preload" href="bar" as="style" /> </body> </html>, ); await act(() => { resolveText('baz'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="initial" data-precedence="one" /> <link rel="stylesheet" href="foo" data-precedence="one" /> <link rel="stylesheet" href="preset" data-precedence="preset" /> <link rel="stylesheet" href="bar" data-precedence="default" /> </head> <body> <div> <div>foo</div> <div>bar</div> </div> <div>loading bar baz qux...</div> <div>loading bar baz qux...</div> <link rel="preload" as="style" href="bar" /> <link rel="preload" as="style" href="baz" /> </body> </html>, ); await act(() => { resolveText('qux'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="initial" data-precedence="one" /> <link rel="stylesheet" href="foo" data-precedence="one" /> <link rel="stylesheet" href="qux" data-precedence="one" /> <link rel="stylesheet" href="preset" data-precedence="preset" /> <link rel="stylesheet" href="bar" data-precedence="default" /> <link rel="stylesheet" href="baz" data-precedence="two" /> </head> <body> <div> <div>foo</div> <div>bar</div> </div> <div>loading bar baz qux...</div> <div>loading bar baz qux...</div> <link rel="preload" as="style" href="bar" /> <link rel="preload" as="style" href="baz" /> <link rel="preload" as="style" href="qux" /> </body> </html>, ); await act(() => { const bazlink = document.querySelector( 'link[rel="stylesheet"][href="baz"]', ); const quxlink = document.querySelector( 'link[rel="stylesheet"][href="qux"]', ); const presetLink = document.querySelector( 'link[rel="stylesheet"][href="preset"]', ); const event = document.createEvent('Events'); event.initEvent('load', true, true); bazlink.dispatchEvent(event); quxlink.dispatchEvent(event); presetLink.dispatchEvent(event); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="initial" data-precedence="one" /> <link rel="stylesheet" href="foo" data-precedence="one" /> <link rel="stylesheet" href="qux" data-precedence="one" /> <link rel="stylesheet" href="preset" data-precedence="preset" /> <link rel="stylesheet" href="bar" data-precedence="default" /> <link rel="stylesheet" href="baz" data-precedence="two" /> </head> <body> <div> <div>foo</div> <div>bar</div> </div> <div> <div>bar</div> <div>baz</div> <div>qux</div> </div> <div>loading bar baz qux...</div> <link rel="preload" as="style" href="bar" /> <link rel="preload" as="style" href="baz" /> <link rel="preload" as="style" href="qux" /> </body> </html>, ); await act(() => { resolveText('unblock'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="initial" data-precedence="one" /> <link rel="stylesheet" href="foo" data-precedence="one" /> <link rel="stylesheet" href="qux" data-precedence="one" /> <link rel="stylesheet" href="preset" data-precedence="preset" /> <link rel="stylesheet" href="bar" data-precedence="default" /> <link rel="stylesheet" href="baz" data-precedence="two" /> </head> <body> <div> <div>foo</div> <div>bar</div> </div> <div> <div>bar</div> <div>baz</div> <div>qux</div> </div> <div> <div>bar</div> <div>baz</div> <div>qux</div> </div> <link rel="preload" as="style" href="bar" /> <link rel="preload" as="style" href="baz" /> <link rel="preload" as="style" href="qux" /> </body> </html>, ); }); // @gate enableFloat it('normalizes stylesheet resource precedence for all boundaries inlined as part of the shell flush', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <head /> <body> <div> outer <link rel="stylesheet" href="1one" precedence="one" /> <link rel="stylesheet" href="1two" precedence="two" /> <link rel="stylesheet" href="1three" precedence="three" /> <link rel="stylesheet" href="1four" precedence="four" /> <Suspense fallback={null}> <div> middle <link rel="stylesheet" href="2one" precedence="one" /> <link rel="stylesheet" href="2two" precedence="two" /> <link rel="stylesheet" href="2three" precedence="three" /> <link rel="stylesheet" href="2four" precedence="four" /> <Suspense fallback={null}> <div> inner <link rel="stylesheet" href="3five" precedence="five" /> <link rel="stylesheet" href="3one" precedence="one" /> <link rel="stylesheet" href="3two" precedence="two" /> <link rel="stylesheet" href="3three" precedence="three" /> <link rel="stylesheet" href="3four" precedence="four" /> </div> </Suspense> </div> </Suspense> <Suspense fallback={null}> <div>middle</div> <link rel="stylesheet" href="4one" precedence="one" /> <link rel="stylesheet" href="4two" precedence="two" /> <link rel="stylesheet" href="4three" precedence="three" /> <link rel="stylesheet" href="4four" precedence="four" /> </Suspense> </div> </body> </html>, ); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="1one" data-precedence="one" /> <link rel="stylesheet" href="2one" data-precedence="one" /> <link rel="stylesheet" href="3one" data-precedence="one" /> <link rel="stylesheet" href="4one" data-precedence="one" /> <link rel="stylesheet" href="1two" data-precedence="two" /> <link rel="stylesheet" href="2two" data-precedence="two" /> <link rel="stylesheet" href="3two" data-precedence="two" /> <link rel="stylesheet" href="4two" data-precedence="two" /> <link rel="stylesheet" href="1three" data-precedence="three" /> <link rel="stylesheet" href="2three" data-precedence="three" /> <link rel="stylesheet" href="3three" data-precedence="three" /> <link rel="stylesheet" href="4three" data-precedence="three" /> <link rel="stylesheet" href="1four" data-precedence="four" /> <link rel="stylesheet" href="2four" data-precedence="four" /> <link rel="stylesheet" href="3four" data-precedence="four" /> <link rel="stylesheet" href="4four" data-precedence="four" /> <link rel="stylesheet" href="3five" data-precedence="five" /> </head> <body> <div> outer <div> middle<div>inner</div> </div> <div>middle</div> </div> </body> </html>, ); }); // @gate enableFloat it('stylesheet resources are inserted according to precedence order on the client', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <head /> <body> <div> <link rel="stylesheet" href="foo" precedence="one" /> <link rel="stylesheet" href="bar" precedence="two" /> Hello </div> </body> </html>, ); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="one" /> <link rel="stylesheet" href="bar" data-precedence="two" /> </head> <body> <div>Hello</div> </body> </html>, ); const root = ReactDOMClient.hydrateRoot( document, <html> <head /> <body> <div> <link rel="stylesheet" href="foo" precedence="one" /> <link rel="stylesheet" href="bar" precedence="two" /> Hello </div> </body> </html>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="one" /> <link rel="stylesheet" href="bar" data-precedence="two" /> </head> <body> <div>Hello</div> </body> </html>, ); root.render( <html> <head /> <body> <div>Goodbye</div> <link rel="stylesheet" href="baz" precedence="one" /> </body> </html>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="one" /> <link rel="stylesheet" href="baz" data-precedence="one" /> <link rel="stylesheet" href="bar" data-precedence="two" /> <link rel="preload" as="style" href="baz" /> </head> <body> <div>Goodbye</div> </body> </html>, ); }); // @gate enableFloat it('inserts preloads in render phase eagerly', async () => { function Throw() { throw new Error('Uh oh!'); } class ErrorBoundary extends React.Component { state = {hasError: false, error: null}; static getDerivedStateFromError(error) { return { hasError: true, error, }; } render() { if (this.state.hasError) { return this.state.error.message; } return this.props.children; } } const root = ReactDOMClient.createRoot(container); root.render( <ErrorBoundary> <link rel="stylesheet" href="foo" precedence="default" /> <div>foo</div> <Throw /> </ErrorBoundary>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" href="foo" as="style" /> </head> <body> <div id="container">Uh oh!</div> </body> </html>, ); }); // @gate enableFloat it('will include child boundary stylesheet resources in the boundary reveal instruction', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <head /> <body> <div> <Suspense fallback="loading foo..."> <BlockedOn value="foo"> <div>foo</div> <link rel="stylesheet" href="foo" precedence="default" /> <Suspense fallback="loading bar..."> <BlockedOn value="bar"> <div>bar</div> <link rel="stylesheet" href="bar" precedence="default" /> <Suspense fallback="loading baz..."> <BlockedOn value="baz"> <div>baz</div> <link rel="stylesheet" href="baz" precedence="default" /> </BlockedOn> </Suspense> </BlockedOn> </Suspense> </BlockedOn> </Suspense> </div> </body> </html>, ); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body> <div>loading foo...</div> </body> </html>, ); await act(() => { resolveText('bar'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body> <div>loading foo...</div> </body> </html>, ); await act(() => { resolveText('baz'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body> <div>loading foo...</div> </body> </html>, ); await act(() => { resolveText('foo'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" /> <link rel="stylesheet" href="bar" data-precedence="default" /> <link rel="stylesheet" href="baz" data-precedence="default" /> </head> <body> <div>loading foo...</div> <link rel="preload" href="foo" as="style" /> <link rel="preload" href="bar" as="style" /> <link rel="preload" href="baz" as="style" /> </body> </html>, ); await act(() => { const event = document.createEvent('Events'); event.initEvent('load', true, true); Array.from(document.querySelectorAll('link[rel="stylesheet"]')).forEach( el => { el.dispatchEvent(event); }, ); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" /> <link rel="stylesheet" href="bar" data-precedence="default" /> <link rel="stylesheet" href="baz" data-precedence="default" /> </head> <body> <div> <div>foo</div> <div>bar</div> <div>baz</div> </div> <link rel="preload" href="foo" as="style" /> <link rel="preload" href="bar" as="style" /> <link rel="preload" href="baz" as="style" /> </body> </html>, ); }); // @gate enableFloat it('will hoist resources of child boundaries emitted as part of a partial boundary to the parent boundary', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <head /> <body> <div> <Suspense fallback="loading..."> <div> <BlockedOn value="foo"> <div>foo</div> <link rel="stylesheet" href="foo" precedence="default" /> <Suspense fallback="loading bar..."> <BlockedOn value="bar"> <div>bar</div> <link rel="stylesheet" href="bar" precedence="default" /> <Suspense fallback="loading baz..."> <div> <BlockedOn value="baz"> <div>baz</div> <link rel="stylesheet" href="baz" precedence="default" /> </BlockedOn> </div> </Suspense> </BlockedOn> </Suspense> </BlockedOn> <BlockedOn value="qux"> <div>qux</div> <link rel="stylesheet" href="qux" precedence="default" /> </BlockedOn> </div> </Suspense> </div> </body> </html>, ); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body> <div>loading...</div> </body> </html>, ); // This will enqueue a stylesheet resource in a deep blocked boundary (loading baz...). await act(() => { resolveText('baz'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body> <div>loading...</div> </body> </html>, ); // This will enqueue a stylesheet resource in the intermediate blocked boundary (loading bar...). await act(() => { resolveText('bar'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body> <div>loading...</div> </body> </html>, ); // This will complete a segment in the top level boundary that is still blocked on another segment. // It will flush the completed segment however the inner boundaries should not emit their style dependencies // because they are not going to be revealed yet. instead their dependencies are hoisted to the blocked // boundary (top level). await act(() => { resolveText('foo'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body> <div>loading...</div> <link rel="preload" href="foo" as="style" /> <link rel="preload" href="bar" as="style" /> <link rel="preload" href="baz" as="style" /> </body> </html>, ); // This resolves the last blocked segment on the top level boundary so we see all dependencies of the // nested boundaries emitted at this level await act(() => { resolveText('qux'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" /> <link rel="stylesheet" href="bar" data-precedence="default" /> <link rel="stylesheet" href="baz" data-precedence="default" /> <link rel="stylesheet" href="qux" data-precedence="default" /> </head> <body> <div>loading...</div> <link rel="preload" href="foo" as="style" /> <link rel="preload" href="bar" as="style" /> <link rel="preload" href="baz" as="style" /> <link rel="preload" href="qux" as="style" /> </body> </html>, ); // We load all stylesheets and confirm the content is revealed await act(() => { const event = document.createEvent('Events'); event.initEvent('load', true, true); Array.from(document.querySelectorAll('link[rel="stylesheet"]')).forEach( el => { el.dispatchEvent(event); }, ); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" /> <link rel="stylesheet" href="bar" data-precedence="default" /> <link rel="stylesheet" href="baz" data-precedence="default" /> <link rel="stylesheet" href="qux" data-precedence="default" /> </head> <body> <div> <div> <div>foo</div> <div>bar</div> <div> <div>baz</div> </div> <div>qux</div> </div> </div> <link rel="preload" href="foo" as="style" /> <link rel="preload" href="bar" as="style" /> <link rel="preload" href="baz" as="style" /> <link rel="preload" href="qux" as="style" /> </body> </html>, ); }); // @gate enableFloat it('encodes attributes consistently whether resources are flushed in shell or in late boundaries', async () => { function App() { return ( <html> <head /> <body> <div> <link // This preload is explicit so it can flush with a lot of potential attrs // We will duplicate this as a style that flushes after the shell rel="stylesheet" href="foo" // precedence is not a special attribute for preloads so this will just flush as is precedence="default" // Some standard link props crossOrigin="anonymous" media="all" integrity="somehash" referrerPolicy="origin" // data and non starndard attributes that should flush data-foo={'"quoted"'} nonStandardAttr="attr" properlyformattednonstandardattr="attr" // attributes that should be filtered out for violating certain rules onSomething="this should be removed b/c event handler" shouldnotincludefunctions={() => {}} norsymbols={Symbol('foo')} /> <Suspense fallback={'loading...'}> <BlockedOn value="unblock"> <link // This preload is explicit so it can flush with a lot of potential attrs // We will duplicate this as a style that flushes after the shell rel="stylesheet" href="bar" // opt-in property to get this treated as a resource precedence="default" // Some standard link props crossOrigin="anonymous" media="all" integrity="somehash" referrerPolicy="origin" // data and non starndard attributes that should flush data-foo={'"quoted"'} nonStandardAttr="attr" properlyformattednonstandardattr="attr" // attributes that should be filtered out for violating certain rules onSomething="this should be removed b/c event handler" shouldnotincludefunctions={() => {}} norsymbols={Symbol('foo')} /> </BlockedOn> </Suspense> </div> </body> </html> ); } await expect(async () => { await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" crossorigin="anonymous" media="all" integrity="somehash" referrerpolicy="origin" data-foo={'"quoted"'} nonstandardattr="attr" properlyformattednonstandardattr="attr" /> </head> <body> <div>loading...</div> </body> </html>, ); }).toErrorDev([ 'React does not recognize the `nonStandardAttr` prop on a DOM element.' + ' If you intentionally want it to appear in the DOM as a custom attribute,' + ' spell it as lowercase `nonstandardattr` instead. If you accidentally passed it from a' + ' parent component, remove it from the DOM element.', 'Invalid values for props `shouldnotincludefunctions`, `norsymbols` on <link> tag. Either remove them from' + ' the element, or pass a string or number value to keep them in the DOM. For' + ' details, see https://reactjs.org/link/attribute-behavior', ]); // Now we flush the stylesheet with the boundary await act(() => { resolveText('unblock'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" crossorigin="anonymous" media="all" integrity="somehash" referrerpolicy="origin" data-foo={'"quoted"'} nonstandardattr="attr" properlyformattednonstandardattr="attr" /> <link rel="stylesheet" href="bar" data-precedence="default" crossorigin="anonymous" media="all" integrity="somehash" referrerpolicy="origin" data-foo={'"quoted"'} nonstandardattr="attr" properlyformattednonstandardattr="attr" /> </head> <body> <div>loading...</div> <link rel="preload" as="style" href="bar" crossorigin="anonymous" media="all" integrity="somehash" referrerpolicy="origin" /> </body> </html>, ); }); // @gate enableFloat it('boundary stylesheet resource dependencies hoist to a parent boundary when flushed inline', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <head /> <body> <div> <Suspense fallback="loading A..."> <BlockedOn value="unblock"> <AsyncText text="A" /> <link rel="stylesheet" href="A" precedence="A" /> <Suspense fallback="loading AA..."> <AsyncText text="AA" /> <link rel="stylesheet" href="AA" precedence="AA" /> <Suspense fallback="loading AAA..."> <AsyncText text="AAA" /> <link rel="stylesheet" href="AAA" precedence="AAA" /> <Suspense fallback="loading AAAA..."> <AsyncText text="AAAA" /> <link rel="stylesheet" href="AAAA" precedence="AAAA" /> </Suspense> </Suspense> </Suspense> </BlockedOn> </Suspense> </div> </body> </html>, ); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body> <div>loading A...</div> </body> </html>, ); await act(() => { resolveText('unblock'); resolveText('AAAA'); resolveText('AA'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body> <div>loading A...</div> <link rel="preload" as="style" href="A" /> <link rel="preload" as="style" href="AA" /> <link rel="preload" as="style" href="AAA" /> <link rel="preload" as="style" href="AAAA" /> </body> </html>, ); await act(() => { resolveText('A'); }); await act(() => { document.querySelectorAll('link[rel="stylesheet"]').forEach(l => { const event = document.createEvent('Events'); event.initEvent('load', true, true); l.dispatchEvent(event); }); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="A" data-precedence="A" /> <link rel="stylesheet" href="AA" data-precedence="AA" /> </head> <body> <div> {'A'} {'AA'} {'loading AAA...'} </div> <link rel="preload" as="style" href="A" /> <link rel="preload" as="style" href="AA" /> <link rel="preload" as="style" href="AAA" /> <link rel="preload" as="style" href="AAAA" /> </body> </html>, ); await act(() => { resolveText('AAA'); }); await act(() => { document.querySelectorAll('link[rel="stylesheet"]').forEach(l => { const event = document.createEvent('Events'); event.initEvent('load', true, true); l.dispatchEvent(event); }); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="A" data-precedence="A" /> <link rel="stylesheet" href="AA" data-precedence="AA" /> <link rel="stylesheet" href="AAA" data-precedence="AAA" /> <link rel="stylesheet" href="AAAA" data-precedence="AAAA" /> </head> <body> <div> {'A'} {'AA'} {'AAA'} {'AAAA'} </div> <link rel="preload" as="style" href="A" /> <link rel="preload" as="style" href="AA" /> <link rel="preload" as="style" href="AAA" /> <link rel="preload" as="style" href="AAAA" /> </body> </html>, ); }); // @gate enableFloat it('always enforces crossOrigin "anonymous" for font preloads', async () => { function App() { ReactDOM.preload('foo', {as: 'font', type: 'font/woff2'}); ReactDOM.preload('bar', {as: 'font', crossOrigin: 'foo'}); ReactDOM.preload('baz', {as: 'font', crossOrigin: 'use-credentials'}); ReactDOM.preload('qux', {as: 'font', crossOrigin: 'anonymous'}); return ( <html> <head /> <body /> </html> ); } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" as="font" href="foo" crossorigin="" type="font/woff2" /> <link rel="preload" as="font" href="bar" crossorigin="" /> <link rel="preload" as="font" href="baz" crossorigin="" /> <link rel="preload" as="font" href="qux" crossorigin="" /> </head> <body /> </html>, ); }); it('does not hoist anything with an itemprop prop', async () => { function App() { return ( <html> <head> <meta itemProp="outside" content="unscoped" /> <link itemProp="link" rel="foo" href="foo" /> <title itemProp="outside-title">title</title> <link itemProp="outside-stylesheet" rel="stylesheet" href="bar" precedence="default" /> <style itemProp="outside-style" href="baz" precedence="default"> outside style </style> <script itemProp="outside-script" async={true} src="qux" /> </head> <body> <div itemScope={true}> <div> <meta itemProp="inside-meta" content="scoped" /> <link itemProp="inside-link" rel="foo" href="foo" /> <title itemProp="inside-title">title</title> <link itemProp="inside-stylesheet" rel="stylesheet" href="bar" precedence="default" /> <style itemProp="inside-style" href="baz" precedence="default"> inside style </style> <script itemProp="inside-script" async={true} src="qux" /> </div> </div> </body> </html> ); } await act(() => { renderToPipeableStream(<App />).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <meta itemprop="outside" content="unscoped" /> <link itemprop="link" rel="foo" href="foo" /> <title itemprop="outside-title">title</title> <link itemprop="outside-stylesheet" rel="stylesheet" href="bar" precedence="default" /> <style itemprop="outside-style" href="baz" precedence="default"> outside style </style> <script itemprop="outside-script" async="" src="qux" /> </head> <body> <div itemscope=""> <div> <meta itemprop="inside-meta" content="scoped" /> <link itemprop="inside-link" rel="foo" href="foo" /> <title itemprop="inside-title">title</title> <link itemprop="inside-stylesheet" rel="stylesheet" href="bar" precedence="default" /> <style itemprop="inside-style" href="baz" precedence="default"> inside style </style> <script itemprop="inside-script" async="" src="qux" /> </div> </div> </body> </html>, ); ReactDOMClient.hydrateRoot(document, <App />); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <meta itemprop="outside" content="unscoped" /> <link itemprop="link" rel="foo" href="foo" /> <title itemprop="outside-title">title</title> <link itemprop="outside-stylesheet" rel="stylesheet" href="bar" precedence="default" /> <style itemprop="outside-style" href="baz" precedence="default"> outside style </style> <script itemprop="outside-script" async="" src="qux" /> </head> <body> <div itemscope=""> <div> <meta itemprop="inside-meta" content="scoped" /> <link itemprop="inside-link" rel="foo" href="foo" /> <title itemprop="inside-title">title</title> <link itemprop="inside-stylesheet" rel="stylesheet" href="bar" precedence="default" /> <style itemprop="inside-style" href="baz" precedence="default"> inside style </style> <script itemprop="inside-script" async="" src="qux" /> </div> </div> </body> </html>, ); }); it('warns if you render a tag with itemProp outside <body> or <head>', async () => { const root = ReactDOMClient.createRoot(document); root.render( <html> <meta itemProp="foo" /> <title itemProp="foo">title</title> <style itemProp="foo">style</style> <link itemProp="foo" /> <script itemProp="foo" /> </html>, ); await expect(async () => { await waitForAll([]); }).toErrorDev([ 'Cannot render a <meta> outside the main document if it has an `itemProp` prop. `itemProp` suggests the tag belongs to an `itemScope` which can appear anywhere in the DOM. If you were intending for React to hoist this <meta> remove the `itemProp` prop. Otherwise, try moving this tag into the <head> or <body> of the Document.', 'Cannot render a <title> outside the main document if it has an `itemProp` prop. `itemProp` suggests the tag belongs to an `itemScope` which can appear anywhere in the DOM. If you were intending for React to hoist this <title> remove the `itemProp` prop. Otherwise, try moving this tag into the <head> or <body> of the Document.', 'Cannot render a <style> outside the main document if it has an `itemProp` prop. `itemProp` suggests the tag belongs to an `itemScope` which can appear anywhere in the DOM. If you were intending for React to hoist this <style> remove the `itemProp` prop. Otherwise, try moving this tag into the <head> or <body> of the Document.', 'Cannot render a <link> outside the main document if it has an `itemProp` prop. `itemProp` suggests the tag belongs to an `itemScope` which can appear anywhere in the DOM. If you were intending for React to hoist this <link> remove the `itemProp` prop. Otherwise, try moving this tag into the <head> or <body> of the Document.', 'Cannot render a <script> outside the main document if it has an `itemProp` prop. `itemProp` suggests the tag belongs to an `itemScope` which can appear anywhere in the DOM. If you were intending for React to hoist this <script> remove the `itemProp` prop. Otherwise, try moving this tag into the <head> or <body> of the Document.', 'validateDOMNesting(...): <meta> cannot appear as a child of <html>', 'validateDOMNesting(...): <title> cannot appear as a child of <html>', 'validateDOMNesting(...): <style> cannot appear as a child of <html>', 'validateDOMNesting(...): <link> cannot appear as a child of <html>', 'validateDOMNesting(...): <script> cannot appear as a child of <html>', ]); }); // @gate enableFloat it('can hydrate resources and components in the head and body even if a browser or 3rd party script injects extra html nodes', async () => { // This is a stress test case for hydrating a complex combination of hoistable elements, hoistable resources and host components // in an environment that has been manipulated by 3rd party scripts/extensions to modify the <head> and <body> function App() { return ( <> <link rel="foo" href="foo" /> <script async={true} src="rendered" /> <link rel="stylesheet" href="stylesheet" precedence="default" /> <html itemScope={true}> <head> {/* Component */} <link rel="stylesheet" href="stylesheet" /> <script src="sync rendered" data-meaningful="" /> <style>{'body { background-color: red; }'}</style> <script src="async rendered" async={true} onLoad={() => {}} /> <noscript> <meta name="noscript" content="noscript" /> </noscript> <link rel="foo" href="foo" onLoad={() => {}} /> </head> <body> {/* Component because it has itemProp */} <meta name="foo" content="foo" itemProp="a prop" /> {/* regular Hoistable */} <meta name="foo" content="foo" /> {/* regular Hoistable */} <title>title</title> <div itemScope={true}> <div> <div>deep hello</div> {/* Component because it has itemProp */} <meta name="foo" content="foo" itemProp="a prop" /> </div> </div> </body> </html> <link rel="foo" href="foo" /> </> ); } await act(() => { renderToPipeableStream(<App />).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html itemscope=""> <head> {/* Hoisted Resources and elements */} <link rel="stylesheet" href="stylesheet" data-precedence="default" /> <script async="" src="rendered" /> <link rel="foo" href="foo" /> <meta name="foo" content="foo" /> <title>title</title> <link rel="foo" href="foo" /> {/* rendered host components */} <link rel="stylesheet" href="stylesheet" /> <script src="sync rendered" data-meaningful="" /> <style>{'body { background-color: red; }'}</style> <script src="async rendered" async="" /> <noscript>&lt;meta name="noscript" content="noscript"&gt;</noscript> <link rel="foo" href="foo" /> </head> <body> <meta name="foo" content="foo" itemprop="a prop" /> <div itemscope=""> <div> <div>deep hello</div> <meta name="foo" content="foo" itemprop="a prop" /> </div> </div> </body> </html>, ); // We inject some styles, divs, scripts into the begginning, middle, and end // of the head / body. const injectedStyle = document.createElement('style'); injectedStyle.textContent = 'body { background-color: blue; }'; document.head.prepend(injectedStyle.cloneNode(true)); document.head.appendChild(injectedStyle.cloneNode(true)); document.body.prepend(injectedStyle.cloneNode(true)); document.body.appendChild(injectedStyle.cloneNode(true)); const injectedDiv = document.createElement('div'); document.head.prepend(injectedDiv); document.head.appendChild(injectedDiv.cloneNode(true)); // We do not prepend a <div> in body because this will conflict with hyration // We still mostly hydrate by matchign tag and <div> does not have any attributes to // differentiate between likely-inject and likely-rendered cases. If a <div> is prepended // in the <body> and you render a <div> as the first child of <body> there will be a conflict. // We consider this a rare edge case and even if it does happen the fallback to client rendering // should patch up the DOM correctly document.body.appendChild(injectedDiv.cloneNode(true)); const injectedScript = document.createElement('script'); injectedScript.setAttribute('async', ''); injectedScript.setAttribute('src', 'injected'); document.head.prepend(injectedScript); document.head.appendChild(injectedScript.cloneNode(true)); document.body.prepend(injectedScript.cloneNode(true)); document.body.appendChild(injectedScript.cloneNode(true)); // We hydrate the same App and confirm the output is identical except for the async // script insertion that happens because we do not SSR async scripts with load handlers. // All the extra inject nodes are preset const root = ReactDOMClient.hydrateRoot(document, <App />); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html itemscope=""> <head> <script async="" src="injected" /> <div /> <style>{'body { background-color: blue; }'}</style> <link rel="stylesheet" href="stylesheet" data-precedence="default" /> <script async="" src="rendered" /> <link rel="foo" href="foo" /> <meta name="foo" content="foo" /> <title>title</title> <link rel="foo" href="foo" /> <link rel="stylesheet" href="stylesheet" /> <script src="sync rendered" data-meaningful="" /> <style>{'body { background-color: red; }'}</style> <script src="async rendered" async="" /> <noscript>&lt;meta name="noscript" content="noscript"&gt;</noscript> <link rel="foo" href="foo" /> <style>{'body { background-color: blue; }'}</style> <div /> <script async="" src="injected" /> </head> <body> <script async="" src="injected" /> <style>{'body { background-color: blue; }'}</style> <meta name="foo" content="foo" itemprop="a prop" /> <div itemscope=""> <div> <div>deep hello</div> <meta name="foo" content="foo" itemprop="a prop" /> </div> </div> <style>{'body { background-color: blue; }'}</style> <div /> <script async="" src="injected" /> </body> </html>, ); // We unmount. The nodes that remain are // 1. Hoisted resources (we don't clean these up on unmount to address races with streaming suspense and navigation) // 2. preloads that are injected to hint the browser to load a resource but are not associated to Fibers directly // 3. Nodes that React skipped over during hydration root.unmount(); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <script async="" src="injected" /> <div /> <style>{'body { background-color: blue; }'}</style> <link rel="stylesheet" href="stylesheet" data-precedence="default" /> <script async="" src="rendered" /> <style>{'body { background-color: blue; }'}</style> <div /> <script async="" src="injected" /> </head> <body> <script async="" src="injected" /> <style>{'body { background-color: blue; }'}</style> <style>{'body { background-color: blue; }'}</style> <div /> <script async="" src="injected" /> </body> </html>, ); }); it('does not preload nomodule scripts', async () => { await act(() => { renderToPipeableStream( <html> <body> <script src="foo" noModule={true} data-meaningful="" /> <script async={true} src="bar" noModule={true} data-meaningful="" /> </body> </html>, ).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <script async="" src="bar" nomodule="" data-meaningful="" /> </head> <body> <script src="foo" nomodule="" data-meaningful="" /> </body> </html>, ); }); it('can delay commit until css resources load', async () => { const root = ReactDOMClient.createRoot(container); expect(getMeaningfulChildren(container)).toBe(undefined); React.startTransition(() => { root.render( <> <link rel="stylesheet" href="foo" precedence="default" /> <div>hello</div> </>, ); }); await waitForAll([]); expect(getMeaningfulChildren(container)).toBe(undefined); expect(getMeaningfulChildren(document.head)).toEqual( <link rel="preload" as="style" href="foo" />, ); loadPreloads(); assertLog(['load preload: foo']); // We expect that the stylesheet is inserted now but the commit has not happened yet. expect(getMeaningfulChildren(container)).toBe(undefined); expect(getMeaningfulChildren(document.head)).toEqual([ <link rel="stylesheet" href="foo" data-precedence="default" />, <link rel="preload" as="style" href="foo" />, ]); loadStylesheets(); assertLog(['load stylesheet: foo']); // We expect that the commit finishes synchronously after the stylesheet loads. expect(getMeaningfulChildren(container)).toEqual(<div>hello</div>); expect(getMeaningfulChildren(document.head)).toEqual([ <link rel="stylesheet" href="foo" data-precedence="default" />, <link rel="preload" as="style" href="foo" />, ]); }); // https://github.com/facebook/react/issues/27585 it('does not reinsert already inserted stylesheets during a delayed commit', async () => { await act(() => { renderToPipeableStream( <html> <body> <link rel="stylesheet" href="first" precedence="default" /> <link rel="stylesheet" href="second" precedence="default" /> server </body> </html>, ).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="first" data-precedence="default" /> <link rel="stylesheet" href="second" data-precedence="default" /> </head> <body>server</body> </html>, ); const root = ReactDOMClient.createRoot(document.body); expect(getMeaningfulChildren(container)).toBe(undefined); root.render( <> <link rel="stylesheet" href="first" precedence="default" /> <link rel="stylesheet" href="third" precedence="default" /> <div>client</div> </>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="first" data-precedence="default" /> <link rel="stylesheet" href="second" data-precedence="default" /> <link rel="stylesheet" href="third" data-precedence="default" /> <link rel="preload" href="third" as="style" /> </head> <body> <div>client</div> </body> </html>, ); // In a transition we add another reference to an already loaded resource // https://github.com/facebook/react/issues/27585 React.startTransition(() => { root.render( <> <link rel="stylesheet" href="first" precedence="default" /> <link rel="stylesheet" href="third" precedence="default" /> <div>client</div> <link rel="stylesheet" href="first" precedence="default" /> </>, ); }); await waitForAll([]); // In https://github.com/facebook/react/issues/27585 the order updated // to second, third, first expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="first" data-precedence="default" /> <link rel="stylesheet" href="second" data-precedence="default" /> <link rel="stylesheet" href="third" data-precedence="default" /> <link rel="preload" href="third" as="style" /> </head> <body> <div>client</div> </body> </html>, ); }); xit('can delay commit until css resources error', async () => { // TODO: This test fails and crashes jest. need to figure out why before unskipping. const root = ReactDOMClient.createRoot(container); expect(getMeaningfulChildren(container)).toBe(undefined); React.startTransition(() => { root.render( <> <link rel="stylesheet" href="foo" precedence="default" /> <link rel="stylesheet" href="bar" precedence="default" /> <div>hello</div> </>, ); }); await waitForAll([]); expect(getMeaningfulChildren(container)).toBe(undefined); expect(getMeaningfulChildren(document.head)).toEqual([ <link rel="preload" as="style" href="foo" />, <link rel="preload" as="style" href="bar" />, ]); loadPreloads(['foo']); errorPreloads(['bar']); assertLog(['load preload: foo', 'error preload: bar']); // We expect that the stylesheet is inserted now but the commit has not happened yet. expect(getMeaningfulChildren(container)).toBe(undefined); expect(getMeaningfulChildren(document.head)).toEqual([ <link rel="stylesheet" href="foo" data-precedence="default" />, <link rel="stylesheet" href="bar" data-precedence="default" />, <link rel="preload" as="style" href="foo" />, <link rel="preload" as="style" href="bar" />, ]); // Try just this and crash all of Jest errorStylesheets(['bar']); // // Try this and it fails the test when it shouldn't // await act(() => { // errorStylesheets(['bar']); // }); // // Try this there is nothing throwing here which is not really surprising since // // the error is bubbling up through some kind of unhandled promise rejection thingy but // // still I thought it was worth confirming // try { // await act(() => { // errorStylesheets(['bar']); // }); // } catch (e) { // console.log(e); // } loadStylesheets(['foo']); assertLog(['load stylesheet: foo', 'error stylesheet: bar']); // We expect that the commit finishes synchronously after the stylesheet loads. expect(getMeaningfulChildren(container)).toEqual(<div>hello</div>); expect(getMeaningfulChildren(document.head)).toEqual([ <link rel="stylesheet" href="foo" data-precedence="default" />, <link rel="stylesheet" href="bar" data-precedence="default" />, <link rel="preload" as="style" href="foo" />, <link rel="preload" as="style" href="bar" />, ]); }); it('assumes stylesheets that load in the shell loaded already', async () => { await act(() => { renderToPipeableStream( <html> <body> <link rel="stylesheet" href="foo" precedence="default" /> hello </body> </html>, ).pipe(writable); }); let root; React.startTransition(() => { root = ReactDOMClient.hydrateRoot( document, <html> <body> <link rel="stylesheet" href="foo" precedence="default" /> hello </body> </html>, ); }); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" /> </head> <body>hello</body> </html>, ); React.startTransition(() => { root.render( <html> <body> <link rel="stylesheet" href="foo" precedence="default" /> hello2 </body> </html>, ); }); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" /> </head> <body>hello2</body> </html>, ); React.startTransition(() => { root.render( <html> <body> <link rel="stylesheet" href="foo" precedence="default" /> hello3 <link rel="stylesheet" href="bar" precedence="default" /> </body> </html>, ); }); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" /> <link rel="preload" href="bar" as="style" /> </head> <body>hello2</body> </html>, ); loadPreloads(); assertLog(['load preload: bar']); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" /> <link rel="stylesheet" href="bar" data-precedence="default" /> <link rel="preload" href="bar" as="style" /> </head> <body>hello2</body> </html>, ); loadStylesheets(['bar']); assertLog(['load stylesheet: bar']); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" /> <link rel="stylesheet" href="bar" data-precedence="default" /> <link rel="preload" href="bar" as="style" /> </head> <body>hello3</body> </html>, ); }); it('can interrupt a suspended commit with a new update', async () => { function App({children}) { return ( <html> <body>{children}</body> </html> ); } const root = ReactDOMClient.createRoot(document); // Do an initial render. This means subsequent insertions will suspend, // unless they are wrapped inside a fresh Suspense boundary. root.render(<App />); await waitForAll([]); // Insert a stylesheet. This will suspend because it's a transition. React.startTransition(() => { root.render( <App> hello <link rel="stylesheet" href="foo" precedence="default" /> </App>, ); }); await waitForAll([]); // Although the commit suspended, a preload was inserted. expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" href="foo" as="style" /> </head> <body /> </html>, ); // Before the stylesheet has loaded, do an urgent update. This will insert a // different stylesheet, and cancel the first one. This stylesheet will not // suspend, even though it hasn't loaded, because it's an urgent update. root.render( <App> hello2 {null} <link rel="stylesheet" href="bar" precedence="default" /> </App>, ); await waitForAll([]); // The bar stylesheet was inserted. There's still a "foo" preload, even // though that update was superseded. expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="bar" data-precedence="default" /> <link rel="preload" href="foo" as="style" /> <link rel="preload" href="bar" as="style" /> </head> <body>hello2</body> </html>, ); // When "foo" finishes loading, nothing happens, because "foo" was not // included in the last root update. However, if we insert "foo" again // later, it should immediately commit without suspending, because it's // been preloaded. loadPreloads(['foo']); assertLog(['load preload: foo']); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="bar" data-precedence="default" /> <link rel="preload" href="foo" as="style" /> <link rel="preload" href="bar" as="style" /> </head> <body>hello2</body> </html>, ); // Now insert "foo" again. React.startTransition(() => { root.render( <App> hello3 <link rel="stylesheet" href="foo" precedence="default" /> <link rel="stylesheet" href="bar" precedence="default" /> </App>, ); }); await waitForAll([]); // Commits without suspending because "foo" was preloaded. expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="bar" data-precedence="default" /> <link rel="stylesheet" href="foo" data-precedence="default" /> <link rel="preload" href="foo" as="style" /> <link rel="preload" href="bar" as="style" /> </head> <body>hello3</body> </html>, ); loadStylesheets(['foo']); assertLog(['load stylesheet: foo']); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="bar" data-precedence="default" /> <link rel="stylesheet" href="foo" data-precedence="default" /> <link rel="preload" href="foo" as="style" /> <link rel="preload" href="bar" as="style" /> </head> <body>hello3</body> </html>, ); }); it('can suspend commits on more than one root for the same resource at the same time', async () => { document.body.innerHTML = ''; const container1 = document.createElement('div'); const container2 = document.createElement('div'); document.body.appendChild(container1); document.body.appendChild(container2); const root1 = ReactDOMClient.createRoot(container1); const root2 = ReactDOMClient.createRoot(container2); React.startTransition(() => { root1.render( <div> one <link rel="stylesheet" href="foo" precedence="default" /> <link rel="stylesheet" href="one" precedence="default" /> </div>, ); }); await waitForAll([]); React.startTransition(() => { root2.render( <div> two <link rel="stylesheet" href="foo" precedence="default" /> <link rel="stylesheet" href="two" precedence="default" /> </div>, ); }); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" href="foo" as="style" /> <link rel="preload" href="one" as="style" /> <link rel="preload" href="two" as="style" /> </head> <body> <div /> <div /> </body> </html>, ); loadPreloads(['foo', 'two']); assertLog(['load preload: foo', 'load preload: two']); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" /> <link rel="stylesheet" href="two" data-precedence="default" /> <link rel="preload" href="foo" as="style" /> <link rel="preload" href="one" as="style" /> <link rel="preload" href="two" as="style" /> </head> <body> <div /> <div /> </body> </html>, ); loadStylesheets(['foo', 'two']); assertLog(['load stylesheet: foo', 'load stylesheet: two']); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" /> <link rel="stylesheet" href="two" data-precedence="default" /> <link rel="preload" href="foo" as="style" /> <link rel="preload" href="one" as="style" /> <link rel="preload" href="two" as="style" /> </head> <body> <div /> <div> <div>two</div> </div> </body> </html>, ); loadPreloads(); loadStylesheets(); assertLog(['load preload: one', 'load stylesheet: one']); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" /> <link rel="stylesheet" href="two" data-precedence="default" /> <link rel="stylesheet" href="one" data-precedence="default" /> <link rel="preload" href="foo" as="style" /> <link rel="preload" href="one" as="style" /> <link rel="preload" href="two" as="style" /> </head> <body> <div> <div>one</div> </div> <div> <div>two</div> </div> </body> </html>, ); }); it('stylesheets block render, with a really long timeout', async () => { function App({children}) { return ( <html> <body>{children}</body> </html> ); } const root = ReactDOMClient.createRoot(document); root.render(<App />); React.startTransition(() => { root.render( <App> hello <link rel="stylesheet" href="foo" precedence="default" /> </App>, ); }); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" href="foo" as="style" /> </head> <body /> </html>, ); // Advance time by 50 seconds. Even still, the transition is suspended. jest.advanceTimersByTime(50000); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" href="foo" as="style" /> </head> <body /> </html>, ); // Advance time by 10 seconds more. A full minute total has elapsed. At this // point, something must have really gone wrong, so we time out and allow // unstyled content to be displayed. jest.advanceTimersByTime(10000); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" /> <link rel="preload" href="foo" as="style" /> </head> <body>hello</body> </html>, ); // We will load these after the commit finishes to ensure nothing errors and nothing new inserts loadPreloads(['foo']); loadStylesheets(['foo']); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" /> <link rel="preload" href="foo" as="style" /> </head> <body>hello</body> </html>, ); }); it('can interrupt a suspended commit with a new transition', async () => { function App({children}) { return ( <html> <body>{children}</body> </html> ); } const root = ReactDOMClient.createRoot(document); root.render(<App>(empty)</App>); // Start a transition to "A" React.startTransition(() => { root.render( <App> A <link rel="stylesheet" href="A" precedence="default" /> </App>, ); }); await waitForAll([]); // "A" hasn't loaded yet, so we remain on the initial UI. Its preload // has been inserted into the head, though. expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" href="A" as="style" /> </head> <body>(empty)</body> </html>, ); // Interrupt the "A" transition with a new one, "B" React.startTransition(() => { root.render( <App> B <link rel="stylesheet" href="B" precedence="default" /> </App>, ); }); await waitForAll([]); // Still on the initial UI because "B" hasn't loaded, but its preload // is now in the head, too. expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" href="A" as="style" /> <link rel="preload" href="B" as="style" /> </head> <body>(empty)</body> </html>, ); // Finish loading loadPreloads(); loadStylesheets(); assertLog(['load preload: A', 'load preload: B', 'load stylesheet: B']); // The "B" transition has finished. expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="B" data-precedence="default" /> <link rel="preload" href="A" as="style" /> <link rel="preload" href="B" as="style" /> </head> <body>B</body> </html>, ); }); it('loading a stylesheet as part of an error boundary UI, during initial render', async () => { class ErrorBoundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { const error = this.state.error; if (error !== null) { return ( <> <link rel="stylesheet" href="A" precedence="default" /> {error.message} </> ); } return this.props.children; } } function Throws() { throw new Error('Oops!'); } function App() { return ( <html> <body> <ErrorBoundary> <Suspense fallback="Loading..."> <Throws /> </Suspense> </ErrorBoundary> </body> </html> ); } // Initial server render. Because something threw, a Suspense fallback // is shown. await act(() => { renderToPipeableStream(<App />, { onError(x) { Scheduler.log('Caught server error: ' + x.message); }, }).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body>Loading...</body> </html>, ); assertLog(['Caught server error: Oops!']); // Hydrate the tree. The error boundary will capture the error and attempt // to show an error screen. However, the error screen includes a stylesheet, // so the commit should suspend until the stylesheet loads. ReactDOMClient.hydrateRoot(document, <App />); await waitForAll([]); // A preload for the stylesheet is inserted, but we still haven't committed // the error screen. expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link as="style" href="A" rel="preload" /> </head> <body>Loading...</body> </html>, ); // Finish loading the stylesheets. The commit should be unblocked, and the // error screen should appear. await clientAct(() => loadStylesheets()); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link data-precedence="default" href="A" rel="stylesheet" /> <link as="style" href="A" rel="preload" /> </head> <body>Oops!</body> </html>, ); }); it('will not flush a preload for a new rendered Stylesheet Resource if one was already flushed', async () => { function Component() { ReactDOM.preload('foo', {as: 'style'}); return ( <div> <Suspense fallback="loading..."> <BlockedOn value="blocked"> <link rel="stylesheet" href="foo" precedence="default" /> hello </BlockedOn> </Suspense> </div> ); } await act(() => { renderToPipeableStream( <html> <body> <Component /> </body> </html>, ).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" as="style" href="foo" /> </head> <body> <div>loading...</div> </body> </html>, ); await act(() => { resolveText('blocked'); }); await act(loadStylesheets); assertLog(['load stylesheet: foo']); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" /> <link rel="preload" as="style" href="foo" /> </head> <body> <div>hello</div> </body> </html>, ); }); it('will not flush a preload for a new preinitialized Stylesheet Resource if one was already flushed', async () => { function Component() { ReactDOM.preload('foo', {as: 'style'}); return ( <div> <Suspense fallback="loading..."> <BlockedOn value="blocked"> <Preinit /> hello </BlockedOn> </Suspense> </div> ); } function Preinit() { ReactDOM.preinit('foo', {as: 'style'}); } await act(() => { renderToPipeableStream( <html> <body> <Component /> </body> </html>, ).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" as="style" href="foo" /> </head> <body> <div>loading...</div> </body> </html>, ); await act(() => { resolveText('blocked'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" as="style" href="foo" /> </head> <body> <div>hello</div> </body> </html>, ); }); it('will not insert a preload if the underlying resource already exists in the Document', async () => { await act(() => { renderToPipeableStream( <html> <head> <link rel="stylesheet" href="foo" precedence="default" /> <script async={true} src="bar" /> <link rel="preload" href="baz" as="font" /> </head> <body> <div id="container" /> </body> </html>, ).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" /> <script async="" src="bar" /> <link rel="preload" href="baz" as="font" /> </head> <body> <div id="container" /> </body> </html>, ); container = document.getElementById('container'); function ClientApp() { ReactDOM.preload('foo', {as: 'style'}); ReactDOM.preload('bar', {as: 'script'}); ReactDOM.preload('baz', {as: 'font'}); return 'foo'; } const root = ReactDOMClient.createRoot(container); await clientAct(() => root.render(<ClientApp />)); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" /> <script async="" src="bar" /> <link rel="preload" href="baz" as="font" /> </head> <body> <div id="container">foo</div> </body> </html>, ); }); it('uses imageSrcSet and imageSizes when keying image preloads', async () => { function App({isClient}) { // Will key off href in absense of imageSrcSet ReactDOM.preload('foo', {as: 'image'}); ReactDOM.preload('foo', {as: 'image'}); // Will key off imageSrcSet + imageSizes ReactDOM.preload('foo', {as: 'image', imageSrcSet: 'fooset'}); ReactDOM.preload('foo2', {as: 'image', imageSrcSet: 'fooset'}); // Will key off imageSrcSet + imageSizes ReactDOM.preload('foo', { as: 'image', imageSrcSet: 'fooset', imageSizes: 'foosizes', }); ReactDOM.preload('foo2', { as: 'image', imageSrcSet: 'fooset', imageSizes: 'foosizes', }); // Will key off href in absense of imageSrcSet, imageSizes is ignored. these should match the // first preloads not not emit a new preload tag ReactDOM.preload('foo', {as: 'image', imageSizes: 'foosizes'}); ReactDOM.preload('foo', {as: 'image', imageSizes: 'foosizes'}); // These preloads are for something that isn't an image // They should all key off the href ReactDOM.preload('bar', {as: 'somethingelse'}); ReactDOM.preload('bar', { as: 'somethingelse', imageSrcSet: 'makes no sense', }); ReactDOM.preload('bar', { as: 'somethingelse', imageSrcSet: 'makes no sense', imageSizes: 'makes no sense', }); if (isClient) { // Will key off href in absense of imageSrcSet ReactDOM.preload('client', {as: 'image'}); ReactDOM.preload('client', {as: 'image'}); // Will key off imageSrcSet + imageSizes ReactDOM.preload('client', {as: 'image', imageSrcSet: 'clientset'}); ReactDOM.preload('client2', {as: 'image', imageSrcSet: 'clientset'}); // Will key off imageSrcSet + imageSizes ReactDOM.preload('client', { as: 'image', imageSrcSet: 'clientset', imageSizes: 'clientsizes', }); ReactDOM.preload('client2', { as: 'image', imageSrcSet: 'clientset', imageSizes: 'clientsizes', }); // Will key off href in absense of imageSrcSet, imageSizes is ignored. these should match the // first preloads not not emit a new preload tag ReactDOM.preload('client', {as: 'image', imageSizes: 'clientsizes'}); ReactDOM.preload('client', {as: 'image', imageSizes: 'clientsizes'}); } return ( <html> <body>hello</body> </html> ); } await act(() => { renderToPipeableStream(<App />).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" as="image" href="foo" /> <link rel="preload" as="image" imagesrcset="fooset" /> <link rel="preload" as="image" imagesrcset="fooset" imagesizes="foosizes" /> <link rel="preload" as="somethingelse" href="bar" /> </head> <body>hello</body> </html>, ); const root = ReactDOMClient.hydrateRoot(document, <App />); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" as="image" href="foo" /> <link rel="preload" as="image" imagesrcset="fooset" /> <link rel="preload" as="image" imagesrcset="fooset" imagesizes="foosizes" /> <link rel="preload" as="somethingelse" href="bar" /> </head> <body>hello</body> </html>, ); root.render(<App isClient={true} />); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" as="image" href="foo" /> <link rel="preload" as="image" imagesrcset="fooset" /> <link rel="preload" as="image" imagesrcset="fooset" imagesizes="foosizes" /> <link rel="preload" as="somethingelse" href="bar" /> <link rel="preload" as="image" href="client" /> <link rel="preload" as="image" imagesrcset="clientset" /> <link rel="preload" as="image" imagesrcset="clientset" imagesizes="clientsizes" /> </head> <body>hello</body> </html>, ); }); it('should handle referrerPolicy on image preload', async () => { function App({isClient}) { ReactDOM.preload('/server', { as: 'image', imageSrcSet: '/server', imageSizes: '100vw', referrerPolicy: 'no-referrer', }); if (isClient) { ReactDOM.preload('/client', { as: 'image', imageSrcSet: '/client', imageSizes: '100vw', referrerPolicy: 'no-referrer', }); } return ( <html> <body>hello</body> </html> ); } await act(() => { renderToPipeableStream(<App />).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" as="image" imagesrcset="/server" imagesizes="100vw" referrerpolicy="no-referrer" /> </head> <body>hello</body> </html>, ); const root = ReactDOMClient.hydrateRoot(document, <App />); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" as="image" imagesrcset="/server" imagesizes="100vw" referrerpolicy="no-referrer" /> </head> <body>hello</body> </html>, ); root.render(<App isClient={true} />); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" as="image" imagesrcset="/server" imagesizes="100vw" referrerpolicy="no-referrer" /> <link rel="preload" as="image" imagesrcset="/client" imagesizes="100vw" referrerpolicy="no-referrer" /> </head> <body>hello</body> </html>, ); }); it('can emit preloads for non-lazy images that are rendered', async () => { function App() { ReactDOM.preload('script', {as: 'script'}); ReactDOM.preload('a', {as: 'image'}); ReactDOM.preload('b', {as: 'image'}); return ( <html> <body> <img src="a" /> <img src="b" loading="lazy" /> <img src="b2" loading="lazy" /> <img src="c" srcSet="srcsetc" /> <img src="d" srcSet="srcsetd" sizes="sizesd" /> <img src="d" srcSet="srcsetd" sizes="sizesd2" /> </body> </html> ); } await act(() => { renderToPipeableStream(<App />).pipe(writable); }); // non-lazy images are first, then arbitrary preloads like for the script and lazy images expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" href="a" as="image" /> <link rel="preload" as="image" imagesrcset="srcsetc" /> <link rel="preload" as="image" imagesrcset="srcsetd" imagesizes="sizesd" /> <link rel="preload" as="image" imagesrcset="srcsetd" imagesizes="sizesd2" /> <link rel="preload" href="script" as="script" /> <link rel="preload" href="b" as="image" /> </head> <body> <img src="a" /> <img src="b" loading="lazy" /> <img src="b2" loading="lazy" /> <img src="c" srcset="srcsetc" /> <img src="d" srcset="srcsetd" sizes="sizesd" /> <img src="d" srcset="srcsetd" sizes="sizesd2" /> </body> </html>, ); }); it('Does not preload lazy images', async () => { function App() { ReactDOM.preload('a', {as: 'image'}); return ( <html> <body> <img src="a" fetchPriority="low" /> <img src="b" fetchPriority="low" /> </body> </html> ); } await act(() => { renderToPipeableStream(<App />).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" as="image" href="a" /> </head> <body> <img src="a" fetchpriority="low" /> <img src="b" fetchpriority="low" /> </body> </html>, ); }); it('preloads up to 10 suspensey images as high priority when fetchPriority is not specified', async () => { function App() { ReactDOM.preload('1', {as: 'image', fetchPriority: 'high'}); ReactDOM.preload('auto', {as: 'image'}); ReactDOM.preload('low', {as: 'image', fetchPriority: 'low'}); ReactDOM.preload('9', {as: 'image', fetchPriority: 'high'}); ReactDOM.preload('10', {as: 'image', fetchPriority: 'high'}); return ( <html> <body> {/* skipping 1 */} <img src="2" /> <img src="3" fetchPriority="auto" /> <img src="4" fetchPriority="high" /> <img src="5" /> <img src="5low" fetchPriority="low" /> <img src="6" /> <img src="7" /> <img src="8" /> <img src="9" /> {/* skipping 10 */} <img src="11" /> <img src="12" fetchPriority="high" /> </body> </html> ); } await act(() => { renderToPipeableStream(<App />).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> {/* First we see the preloads calls that made it to the high priority image queue */} <link rel="preload" as="image" href="1" fetchpriority="high" /> <link rel="preload" as="image" href="9" fetchpriority="high" /> <link rel="preload" as="image" href="10" fetchpriority="high" /> {/* Next we see up to 7 more images qualify for high priority image queue */} <link rel="preload" as="image" href="2" /> <link rel="preload" as="image" href="3" fetchpriority="auto" /> <link rel="preload" as="image" href="4" fetchpriority="high" /> <link rel="preload" as="image" href="5" /> <link rel="preload" as="image" href="6" /> <link rel="preload" as="image" href="7" /> <link rel="preload" as="image" href="8" /> {/* Next we see images that are explicitly high priority and thus make it to the high priority image queue */} <link rel="preload" as="image" href="12" fetchpriority="high" /> {/* Next we see the remaining preloads that did not make it to the high priority image queue */} <link rel="preload" as="image" href="auto" /> <link rel="preload" as="image" href="low" fetchpriority="low" /> <link rel="preload" as="image" href="11" /> </head> <body> {/* skipping 1 */} <img src="2" /> <img src="3" fetchpriority="auto" /> <img src="4" fetchpriority="high" /> <img src="5" /> <img src="5low" fetchpriority="low" /> <img src="6" /> <img src="7" /> <img src="8" /> <img src="9" /> {/* skipping 10 */} <img src="11" /> <img src="12" fetchpriority="high" /> </body> </html>, ); }); it('can promote images to high priority when at least one instance specifies a high fetchPriority', async () => { function App() { // If a ends up in a higher priority queue than b it will flush first ReactDOM.preload('a', {as: 'image'}); ReactDOM.preload('b', {as: 'image'}); return ( <html> <body> <link rel="stylesheet" href="foo" precedence="default" /> <img src="1" /> <img src="2" /> <img src="3" /> <img src="4" /> <img src="5" /> <img src="6" /> <img src="7" /> <img src="8" /> <img src="9" /> <img src="10" /> <img src="11" /> <img src="12" /> <img src="a" fetchPriority="low" /> <img src="a" /> <img src="a" fetchPriority="high" /> <img src="a" /> <img src="a" /> </body> </html> ); } await act(() => { renderToPipeableStream(<App />).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> {/* The First 10 high priority images were just the first 10 rendered images */} <link rel="preload" as="image" href="1" /> <link rel="preload" as="image" href="2" /> <link rel="preload" as="image" href="3" /> <link rel="preload" as="image" href="4" /> <link rel="preload" as="image" href="5" /> <link rel="preload" as="image" href="6" /> <link rel="preload" as="image" href="7" /> <link rel="preload" as="image" href="8" /> <link rel="preload" as="image" href="9" /> <link rel="preload" as="image" href="10" /> {/* The "a" image was rendered a few times but since at least one of those was with fetchPriorty="high" it ends up in the high priority queue */} <link rel="preload" as="image" href="a" /> {/* Stylesheets come in between high priority images and regular preloads */} <link rel="stylesheet" href="foo" data-precedence="default" /> {/* The remainig images that preloaded at regular priority */} <link rel="preload" as="image" href="b" /> <link rel="preload" as="image" href="11" /> <link rel="preload" as="image" href="12" /> </head> <body> <img src="1" /> <img src="2" /> <img src="3" /> <img src="4" /> <img src="5" /> <img src="6" /> <img src="7" /> <img src="8" /> <img src="9" /> <img src="10" /> <img src="11" /> <img src="12" /> <img src="a" fetchpriority="low" /> <img src="a" /> <img src="a" fetchpriority="high" /> <img src="a" /> <img src="a" /> </body> </html>, ); }); it('preloads from rendered images properly use srcSet and sizes', async () => { function App() { ReactDOM.preload('1', {as: 'image', imageSrcSet: 'ss1'}); ReactDOM.preload('2', { as: 'image', imageSrcSet: 'ss2', imageSizes: 's2', }); return ( <html> <body> <img src="1" srcSet="ss1" /> <img src="2" srcSet="ss2" sizes="s2" /> <img src="3" srcSet="ss3" /> <img src="4" srcSet="ss4" sizes="s4" /> </body> </html> ); } await act(() => { renderToPipeableStream(<App />).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" as="image" imagesrcset="ss1" /> <link rel="preload" as="image" imagesrcset="ss2" imagesizes="s2" /> <link rel="preload" as="image" imagesrcset="ss3" /> <link rel="preload" as="image" imagesrcset="ss4" imagesizes="s4" /> </head> <body> <img src="1" srcset="ss1" /> <img src="2" srcset="ss2" sizes="s2" /> <img src="3" srcset="ss3" /> <img src="4" srcset="ss4" sizes="s4" /> </body> </html>, ); }); it('should not preload images that have a data URIs for src or srcSet', async () => { function App() { return ( <html> <body> <img src="data:1" /> <img src="data:2" srcSet="ss2" /> <img srcSet="data:3a, data:3b 2x" /> <img src="4" srcSet="data:4a, data4b 2x" /> </body> </html> ); } await act(() => { renderToPipeableStream(<App />).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body> <img src="data:1" /> <img src="data:2" srcset="ss2" /> <img srcset="data:3a, data:3b 2x" /> <img src="4" srcset="data:4a, data4b 2x" /> </body> </html>, ); }); // https://github.com/vercel/next.js/discussions/54799 it('omits preloads when an <img> is inside a <picture>', async () => { await act(() => { renderToPipeableStream( <html> <body> <picture> <img src="foo" /> </picture> <picture> <source type="image/webp" srcSet="webpsrc" /> <img src="jpg fallback" /> </picture> </body> </html>, ).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body> <picture> <img src="foo" /> </picture> <picture> <source type="image/webp" srcset="webpsrc" /> <img src="jpg fallback" /> </picture> </body> </html>, ); }); it('should warn if you preload a stylesheet and then render a style tag with the same href', async () => { const style = 'body { color: red; }'; function App() { ReactDOM.preload('foo', {as: 'style'}); return ( <html> <body> hello <style precedence="default" href="foo"> {style} </style> </body> </html> ); } await expect(async () => { await act(() => { renderToPipeableStream(<App />).pipe(writable); }); }).toErrorDev([ 'React encountered a hoistable style tag for the same href as a preload: "foo". When using a style tag to inline styles you should not also preload it as a stylsheet.', ]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <style data-precedence="default" data-href="foo"> {style} </style> <link rel="preload" as="style" href="foo" /> </head> <body>hello</body> </html>, ); }); it('should preload only once even if you discover a stylesheet, script, or moduleScript late', async () => { function App() { // We start with preinitializing some resources first ReactDOM.preinit('shell preinit/shell', {as: 'style'}); ReactDOM.preinit('shell preinit/shell', {as: 'script'}); ReactDOM.preinitModule('shell preinit/shell', {as: 'script'}); // We initiate all the shell preloads ReactDOM.preload('shell preinit/shell', {as: 'style'}); ReactDOM.preload('shell preinit/shell', {as: 'script'}); ReactDOM.preloadModule('shell preinit/shell', {as: 'script'}); ReactDOM.preload('shell/shell preinit', {as: 'style'}); ReactDOM.preload('shell/shell preinit', {as: 'script'}); ReactDOM.preloadModule('shell/shell preinit', {as: 'script'}); ReactDOM.preload('shell/shell render', {as: 'style'}); ReactDOM.preload('shell/shell render', {as: 'script'}); ReactDOM.preloadModule('shell/shell render'); ReactDOM.preload('shell/late preinit', {as: 'style'}); ReactDOM.preload('shell/late preinit', {as: 'script'}); ReactDOM.preloadModule('shell/late preinit'); ReactDOM.preload('shell/late render', {as: 'style'}); ReactDOM.preload('shell/late render', {as: 'script'}); ReactDOM.preloadModule('shell/late render'); // we preinit later ones that should be created by ReactDOM.preinit('shell/shell preinit', {as: 'style'}); ReactDOM.preinit('shell/shell preinit', {as: 'script'}); ReactDOM.preinitModule('shell/shell preinit'); ReactDOM.preinit('late/shell preinit', {as: 'style'}); ReactDOM.preinit('late/shell preinit', {as: 'script'}); ReactDOM.preinitModule('late/shell preinit'); return ( <html> <body> <link rel="stylesheet" precedence="default" href="shell/shell render" /> <script async={true} src="shell/shell render" /> <script type="module" async={true} src="shell/shell render" /> <link rel="stylesheet" precedence="default" href="late/shell render" /> <script async={true} src="late/shell render" /> <script type="module" async={true} src="late/shell render" /> <Suspense fallback="late..."> <BlockedOn value="late"> <Late /> </BlockedOn> </Suspense> <Suspense fallback="later..."> <BlockedOn value="later"> <Later /> </BlockedOn> </Suspense> </body> </html> ); } function Late() { ReactDOM.preload('late/later preinit', {as: 'style'}); ReactDOM.preload('late/later preinit', {as: 'script'}); ReactDOM.preloadModule('late/later preinit'); ReactDOM.preload('late/later render', {as: 'style'}); ReactDOM.preload('late/later render', {as: 'script'}); ReactDOM.preloadModule('late/later render'); ReactDOM.preload('late/shell preinit', {as: 'style'}); ReactDOM.preload('late/shell preinit', {as: 'script'}); ReactDOM.preloadModule('late/shell preinit'); ReactDOM.preload('late/shell render', {as: 'style'}); ReactDOM.preload('late/shell render', {as: 'script'}); ReactDOM.preloadModule('late/shell render'); // late preinits don't actually flush so we won't see this in the DOM as a stylesehet but we should see // the preload for this resource ReactDOM.preinit('shell/late preinit', {as: 'style'}); ReactDOM.preinit('shell/late preinit', {as: 'script'}); ReactDOM.preinitModule('shell/late preinit'); return ( <> Late <link rel="stylesheet" precedence="default" href="shell/late render" /> <script async={true} src="shell/late render" /> <script type="module" async={true} src="shell/late render" /> </> ); } function Later() { // late preinits don't actually flush so we won't see this in the DOM as a stylesehet but we should see // the preload for this resource ReactDOM.preinit('late/later preinit', {as: 'style'}); ReactDOM.preinit('late/later preinit', {as: 'script'}); ReactDOM.preinitModule('late/later preinit'); return ( <> Later <link rel="stylesheet" precedence="default" href="late/later render" /> <script async={true} src="late/later render" /> <script type="module" async={true} src="late/later render" /> </> ); } await act(() => { renderToPipeableStream(<App />).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" data-precedence="default" href="shell preinit/shell" /> <link rel="stylesheet" data-precedence="default" href="shell/shell preinit" /> <link rel="stylesheet" data-precedence="default" href="late/shell preinit" /> <link rel="stylesheet" data-precedence="default" href="shell/shell render" /> <link rel="stylesheet" data-precedence="default" href="late/shell render" /> <script async="" src="shell preinit/shell" /> <script async="" src="shell preinit/shell" type="module" /> <script async="" src="shell/shell preinit" /> <script async="" src="shell/shell preinit" type="module" /> <script async="" src="late/shell preinit" /> <script async="" src="late/shell preinit" type="module" /> <script async="" src="shell/shell render" /> <script async="" src="shell/shell render" type="module" /> <script async="" src="late/shell render" /> <script async="" src="late/shell render" type="module" /> <link rel="preload" as="style" href="shell/late preinit" /> <link rel="preload" as="script" href="shell/late preinit" /> <link rel="modulepreload" href="shell/late preinit" /> <link rel="preload" as="style" href="shell/late render" /> <link rel="preload" as="script" href="shell/late render" /> <link rel="modulepreload" href="shell/late render" /> </head> <body> {'late...'} {'later...'} </body> </html>, ); await act(() => { resolveText('late'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" data-precedence="default" href="shell preinit/shell" /> <link rel="stylesheet" data-precedence="default" href="shell/shell preinit" /> <link rel="stylesheet" data-precedence="default" href="late/shell preinit" /> <link rel="stylesheet" data-precedence="default" href="shell/shell render" /> <link rel="stylesheet" data-precedence="default" href="late/shell render" /> {/* FROM HERE */} <link rel="stylesheet" data-precedence="default" href="shell/late render" /> {/** TO HERE: * This was hoisted by boundary complete instruction. The preload was already emitted in the * shell but we see it below because this was inserted clientside by precedence. * We don't observe the "shell/late preinit" because these do not flush unless they are flushing * with the shell * */} <script async="" src="shell preinit/shell" /> <script async="" src="shell preinit/shell" type="module" /> <script async="" src="shell/shell preinit" /> <script async="" src="shell/shell preinit" type="module" /> <script async="" src="late/shell preinit" /> <script async="" src="late/shell preinit" type="module" /> <script async="" src="shell/shell render" /> <script async="" src="shell/shell render" type="module" /> <script async="" src="late/shell render" /> <script async="" src="late/shell render" type="module" /> <link rel="preload" as="style" href="shell/late preinit" /> <link rel="preload" as="script" href="shell/late preinit" /> <link rel="modulepreload" href="shell/late preinit" /> <link rel="preload" as="style" href="shell/late render" /> <link rel="preload" as="script" href="shell/late render" /> <link rel="modulepreload" href="shell/late render" /> </head> <body> {'late...'} {'later...'} {/* FROM HERE */} <script async="" src="shell/late preinit" /> <script async="" src="shell/late preinit" type="module" /> <script async="" src="shell/late render" /> <script async="" src="shell/late render" type="module" /> <link rel="preload" as="style" href="late/later preinit" /> <link rel="preload" as="script" href="late/later preinit" /> <link rel="modulepreload" href="late/later preinit" /> <link rel="preload" as="style" href="late/later render" /> <link rel="preload" as="script" href="late/later render" /> <link rel="modulepreload" href="late/later render" /> {/** TO HERE: * These resources streamed into the body during the boundary flush. Scripts go first then * preloads according to our streaming queue priorities. Note also that late/shell resources * where the resource already emitted in the shell and the preload is invoked later do not * end up with a preload in the document at all. * */} </body> </html>, ); await act(() => { resolveText('later'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" data-precedence="default" href="shell preinit/shell" /> <link rel="stylesheet" data-precedence="default" href="shell/shell preinit" /> <link rel="stylesheet" data-precedence="default" href="late/shell preinit" /> <link rel="stylesheet" data-precedence="default" href="shell/shell render" /> <link rel="stylesheet" data-precedence="default" href="late/shell render" /> <link rel="stylesheet" data-precedence="default" href="shell/late render" /> {/* FROM HERE */} <link rel="stylesheet" data-precedence="default" href="late/later render" /> {/** TO HERE: * This was hoisted by boundary complete instruction. The preload was already emitted in the * shell but we see it below because this was inserted clientside by precedence * We don't observe the "late/later preinit" because these do not flush unless they are flushing * with the shell * */} <script async="" src="shell preinit/shell" /> <script async="" src="shell preinit/shell" type="module" /> <script async="" src="shell/shell preinit" /> <script async="" src="shell/shell preinit" type="module" /> <script async="" src="late/shell preinit" /> <script async="" src="late/shell preinit" type="module" /> <script async="" src="shell/shell render" /> <script async="" src="shell/shell render" type="module" /> <script async="" src="late/shell render" /> <script async="" src="late/shell render" type="module" /> <link rel="preload" as="style" href="shell/late preinit" /> <link rel="preload" as="script" href="shell/late preinit" /> <link rel="modulepreload" href="shell/late preinit" /> <link rel="preload" as="style" href="shell/late render" /> <link rel="preload" as="script" href="shell/late render" /> <link rel="modulepreload" href="shell/late render" /> </head> <body> {'late...'} {'later...'} <script async="" src="shell/late preinit" /> <script async="" src="shell/late preinit" type="module" /> <script async="" src="shell/late render" /> <script async="" src="shell/late render" type="module" /> <link rel="preload" as="style" href="late/later preinit" /> <link rel="preload" as="script" href="late/later preinit" /> <link rel="modulepreload" href="late/later preinit" /> <link rel="preload" as="style" href="late/later render" /> <link rel="preload" as="script" href="late/later render" /> <link rel="modulepreload" href="late/later render" /> {/* FROM HERE */} <script async="" src="late/later preinit" /> <script async="" src="late/later preinit" type="module" /> <script async="" src="late/later render" /> <script async="" src="late/later render" type="module" /> {/** TO HERE: * These resources streamed into the body during the boundary flush. Scripts go first then * preloads according to our streaming queue priorities * */} </body> </html>, ); loadStylesheets(); assertLog([ 'load stylesheet: shell preinit/shell', 'load stylesheet: shell/shell preinit', 'load stylesheet: late/shell preinit', 'load stylesheet: shell/shell render', 'load stylesheet: late/shell render', 'load stylesheet: shell/late render', 'load stylesheet: late/later render', ]); ReactDOMClient.hydrateRoot(document, <App />); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" data-precedence="default" href="shell preinit/shell" /> <link rel="stylesheet" data-precedence="default" href="shell/shell preinit" /> <link rel="stylesheet" data-precedence="default" href="late/shell preinit" /> <link rel="stylesheet" data-precedence="default" href="shell/shell render" /> <link rel="stylesheet" data-precedence="default" href="late/shell render" /> <link rel="stylesheet" data-precedence="default" href="shell/late render" /> <link rel="stylesheet" data-precedence="default" href="late/later render" /> {/* FROM HERE */} <link rel="stylesheet" data-precedence="default" href="shell/late preinit" /> <link rel="stylesheet" data-precedence="default" href="late/later preinit" /> {/** TO HERE: * The client render patches in the two missing preinit stylesheets when hydration happens * Note that this is only because we repeated the calls to preinit on the client * */} <script async="" src="shell preinit/shell" /> <script async="" src="shell preinit/shell" type="module" /> <script async="" src="shell/shell preinit" /> <script async="" src="shell/shell preinit" type="module" /> <script async="" src="late/shell preinit" /> <script async="" src="late/shell preinit" type="module" /> <script async="" src="shell/shell render" /> <script async="" src="shell/shell render" type="module" /> <script async="" src="late/shell render" /> <script async="" src="late/shell render" type="module" /> <link rel="preload" as="style" href="shell/late preinit" /> <link rel="preload" as="script" href="shell/late preinit" /> <link rel="modulepreload" href="shell/late preinit" /> <link rel="preload" as="style" href="shell/late render" /> <link rel="preload" as="script" href="shell/late render" /> <link rel="modulepreload" href="shell/late render" /> </head> <body> {'Late'} {'Later'} <script async="" src="shell/late preinit" /> <script async="" src="shell/late preinit" type="module" /> <script async="" src="shell/late render" /> <script async="" src="shell/late render" type="module" /> <link rel="preload" as="style" href="late/later preinit" /> <link rel="preload" as="script" href="late/later preinit" /> <link rel="modulepreload" href="late/later preinit" /> <link rel="preload" as="style" href="late/later render" /> <link rel="preload" as="script" href="late/later render" /> <link rel="modulepreload" href="late/later render" /> <script async="" src="late/later preinit" /> <script async="" src="late/later preinit" type="module" /> <script async="" src="late/later render" /> <script async="" src="late/later render" type="module" /> </body> </html>, ); }); describe('ReactDOM.prefetchDNS(href)', () => { it('creates a dns-prefetch resource when called', async () => { function App({url}) { ReactDOM.prefetchDNS(url); ReactDOM.prefetchDNS(url); ReactDOM.prefetchDNS(url, {}); ReactDOM.prefetchDNS(url, {crossOrigin: 'use-credentials'}); return ( <html> <body>hello world</body> </html> ); } await expect(async () => { await act(() => { renderToPipeableStream(<App url="foo" />).pipe(writable); }); }).toErrorDev([ 'ReactDOM.prefetchDNS(): Expected only one argument, `href`, but encountered something with type "object" as a second argument instead. This argument is reserved for future options and is currently disallowed. Try calling ReactDOM.prefetchDNS() with just a single string argument, `href`.', 'ReactDOM.prefetchDNS(): Expected only one argument, `href`, but encountered something with type "object" as a second argument instead. This argument is reserved for future options and is currently disallowed. It looks like the you are attempting to set a crossOrigin property for this DNS lookup hint. Browsers do not perform DNS queries using CORS and setting this attribute on the resource hint has no effect. Try calling ReactDOM.prefetchDNS() with just a single string argument, `href`.', ]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="dns-prefetch" href="foo" /> </head> <body>hello world</body> </html>, ); const root = ReactDOMClient.hydrateRoot(document, <App url="foo" />); await expect(async () => { await waitForAll([]); }).toErrorDev([ 'ReactDOM.prefetchDNS(): Expected only one argument, `href`, but encountered something with type "object" as a second argument instead. This argument is reserved for future options and is currently disallowed. Try calling ReactDOM.prefetchDNS() with just a single string argument, `href`.', 'ReactDOM.prefetchDNS(): Expected only one argument, `href`, but encountered something with type "object" as a second argument instead. This argument is reserved for future options and is currently disallowed. It looks like the you are attempting to set a crossOrigin property for this DNS lookup hint. Browsers do not perform DNS queries using CORS and setting this attribute on the resource hint has no effect. Try calling ReactDOM.prefetchDNS() with just a single string argument, `href`.', ]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="dns-prefetch" href="foo" /> </head> <body>hello world</body> </html>, ); root.render(<App url="bar" />); await expect(async () => { await waitForAll([]); }).toErrorDev([ 'ReactDOM.prefetchDNS(): Expected only one argument, `href`, but encountered something with type "object" as a second argument instead. This argument is reserved for future options and is currently disallowed. Try calling ReactDOM.prefetchDNS() with just a single string argument, `href`.', 'ReactDOM.prefetchDNS(): Expected only one argument, `href`, but encountered something with type "object" as a second argument instead. This argument is reserved for future options and is currently disallowed. It looks like the you are attempting to set a crossOrigin property for this DNS lookup hint. Browsers do not perform DNS queries using CORS and setting this attribute on the resource hint has no effect. Try calling ReactDOM.prefetchDNS() with just a single string argument, `href`.', ]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="dns-prefetch" href="foo" /> <link rel="dns-prefetch" href="bar" /> </head> <body>hello world</body> </html>, ); }); }); describe('ReactDOM.preconnect(href, { crossOrigin })', () => { it('creates a preconnect resource when called', async () => { function App({url}) { ReactDOM.preconnect(url); ReactDOM.preconnect(url); ReactDOM.preconnect(url, {crossOrigin: true}); ReactDOM.preconnect(url, {crossOrigin: ''}); ReactDOM.preconnect(url, {crossOrigin: 'anonymous'}); ReactDOM.preconnect(url, {crossOrigin: 'use-credentials'}); return ( <html> <body>hello world</body> </html> ); } await expect(async () => { await act(() => { renderToPipeableStream(<App url="foo" />).pipe(writable); }); }).toErrorDev( 'ReactDOM.preconnect(): Expected the `crossOrigin` option (second argument) to be a string but encountered something with type "boolean" instead. Try removing this option or passing a string value instead.', ); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preconnect" href="foo" /> <link rel="preconnect" href="foo" crossorigin="" /> <link rel="preconnect" href="foo" crossorigin="use-credentials" /> </head> <body>hello world</body> </html>, ); const root = ReactDOMClient.hydrateRoot(document, <App url="foo" />); await expect(async () => { await waitForAll([]); }).toErrorDev( 'ReactDOM.preconnect(): Expected the `crossOrigin` option (second argument) to be a string but encountered something with type "boolean" instead. Try removing this option or passing a string value instead.', ); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preconnect" href="foo" /> <link rel="preconnect" href="foo" crossorigin="" /> <link rel="preconnect" href="foo" crossorigin="use-credentials" /> </head> <body>hello world</body> </html>, ); root.render(<App url="bar" />); await expect(async () => { await waitForAll([]); }).toErrorDev( 'ReactDOM.preconnect(): Expected the `crossOrigin` option (second argument) to be a string but encountered something with type "boolean" instead. Try removing this option or passing a string value instead.', ); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preconnect" href="foo" /> <link rel="preconnect" href="foo" crossorigin="" /> <link rel="preconnect" href="foo" crossorigin="use-credentials" /> <link rel="preconnect" href="bar" /> <link rel="preconnect" href="bar" crossorigin="" /> <link rel="preconnect" href="bar" crossorigin="use-credentials" /> </head> <body>hello world</body> </html>, ); }); }); describe('ReactDOM.preload(href, { as: ... })', () => { // @gate enableFloat it('creates a preload resource when called', async () => { function App() { ReactDOM.preload('foo', {as: 'style'}); return ( <html> <body> <Suspense fallback="loading..."> <BlockedOn value="blocked"> <Component /> </BlockedOn> </Suspense> </body> </html> ); } function Component() { ReactDOM.preload('bar', {as: 'script'}); return <div>hello</div>; } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" as="style" href="foo" /> </head> <body>loading...</body> </html>, ); await act(() => { resolveText('blocked'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" as="style" href="foo" /> </head> <body> <div>hello</div> <link rel="preload" as="script" href="bar" /> </body> </html>, ); function ClientApp() { ReactDOM.preload('foo', {as: 'style'}); ReactDOM.preload('font', {as: 'font', type: 'font/woff2'}); React.useInsertionEffect(() => ReactDOM.preload('bar', {as: 'script'})); React.useLayoutEffect(() => ReactDOM.preload('baz', {as: 'font'})); React.useEffect(() => ReactDOM.preload('qux', {as: 'style'})); return ( <html> <body> <Suspense fallback="loading..."> <div>hello</div> </Suspense> </body> </html> ); } ReactDOMClient.hydrateRoot(document, <ClientApp />); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" as="style" href="foo" /> <link rel="preload" as="font" href="font" crossorigin="" type="font/woff2" /> <link rel="preload" as="font" href="baz" crossorigin="" /> <link rel="preload" as="style" href="qux" /> </head> <body> <div>hello</div> <link rel="preload" as="script" href="bar" /> </body> </html>, ); }); // @gate enableFloat it('can seed connection props for stylesheet and script resources', async () => { function App() { ReactDOM.preload('foo', { as: 'style', crossOrigin: 'use-credentials', integrity: 'some hash', fetchPriority: 'low', }); return ( <html> <body> <div>hello</div> <link rel="stylesheet" href="foo" precedence="default" /> </body> </html> ); } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" crossorigin="use-credentials" integrity="some hash" /> </head> <body> <div>hello</div> </body> </html>, ); }); // @gate enableFloat it('warns if you do not pass in a valid href argument or options argument', async () => { function App() { ReactDOM.preload(); ReactDOM.preload(''); ReactDOM.preload('foo', null); ReactDOM.preload('foo', {}); ReactDOM.preload('foo', {as: 'foo'}); return <div>foo</div>; } await expect(async () => { await act(() => { renderToPipeableStream(<App />).pipe(writable); }); }).toErrorDev([ 'ReactDOM.preload(): Expected two arguments, a non-empty `href` string and an `options` object with an `as` property valid for a `<link rel="preload" as="..." />` tag. The `href` argument encountered was `undefined`. The `options` argument encountered was `undefined`.', 'ReactDOM.preload(): Expected two arguments, a non-empty `href` string and an `options` object with an `as` property valid for a `<link rel="preload" as="..." />` tag. The `href` argument encountered was an empty string. The `options` argument encountered was `undefined`.', 'ReactDOM.preload(): Expected two arguments, a non-empty `href` string and an `options` object with an `as` property valid for a `<link rel="preload" as="..." />` tag. The `options` argument encountered was `null`.', 'ReactDOM.preload(): Expected two arguments, a non-empty `href` string and an `options` object with an `as` property valid for a `<link rel="preload" as="..." />` tag. The `as` option encountered was `undefined`.', ]); }); it('supports fetchPriority', async () => { function Component({isServer}) { ReactDOM.preload(isServer ? 'highserver' : 'highclient', { as: 'script', fetchPriority: 'high', }); ReactDOM.preload(isServer ? 'lowserver' : 'lowclient', { as: 'style', fetchPriority: 'low', }); ReactDOM.preload(isServer ? 'autoserver' : 'autoclient', { as: 'style', fetchPriority: 'auto', }); return 'hello'; } await act(() => { renderToPipeableStream( <html> <body> <Component isServer={true} /> </body> </html>, ).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" as="script" href="highserver" fetchpriority="high" /> <link rel="preload" as="style" href="lowserver" fetchpriority="low" /> <link rel="preload" as="style" href="autoserver" fetchpriority="auto" /> </head> <body>hello</body> </html>, ); ReactDOMClient.hydrateRoot( document, <html> <body> <Component /> </body> </html>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" as="script" href="highserver" fetchpriority="high" /> <link rel="preload" as="style" href="lowserver" fetchpriority="low" /> <link rel="preload" as="style" href="autoserver" fetchpriority="auto" /> <link rel="preload" as="script" href="highclient" fetchpriority="high" /> <link rel="preload" as="style" href="lowclient" fetchpriority="low" /> <link rel="preload" as="style" href="autoclient" fetchpriority="auto" /> </head> <body>hello</body> </html>, ); }); it('supports nonce', async () => { function App({url}) { ReactDOM.preload(url, {as: 'script', nonce: 'abc'}); return 'hello'; } await act(() => { renderToPipeableStream(<App url="server" />).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body> <div id="container"> <link rel="preload" as="script" href="server" nonce="abc" /> hello </div> </body> </html>, ); ReactDOMClient.hydrateRoot(container, <App url="client" />); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="preload" as="script" href="client" nonce="abc" /> </head> <body> <div id="container"> <link rel="preload" as="script" href="server" nonce="abc" /> hello </div> </body> </html>, ); }); }); describe('ReactDOM.preloadModule(href, options)', () => { it('preloads scripts as modules', async () => { function App({ssr}) { const prefix = ssr ? 'ssr ' : 'browser '; ReactDOM.preloadModule(prefix + 'plain'); ReactDOM.preloadModule(prefix + 'default', {as: 'script'}); ReactDOM.preloadModule(prefix + 'cors', { crossOrigin: 'use-credentials', }); ReactDOM.preloadModule(prefix + 'integrity', {integrity: 'some hash'}); ReactDOM.preloadModule(prefix + 'serviceworker', {as: 'serviceworker'}); return <div>hello</div>; } await act(() => { renderToPipeableStream(<App ssr={true} />).pipe(writable); }); expect(getMeaningfulChildren(document.body)).toEqual( <div id="container"> <link rel="modulepreload" href="ssr plain" /> <link rel="modulepreload" href="ssr default" /> <link rel="modulepreload" href="ssr cors" crossorigin="use-credentials" /> <link rel="modulepreload" href="ssr integrity" integrity="some hash" /> <link rel="modulepreload" href="ssr serviceworker" as="serviceworker" /> <div>hello</div> </div>, ); ReactDOMClient.hydrateRoot(container, <App />); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="modulepreload" href="browser plain" /> <link rel="modulepreload" href="browser default" /> <link rel="modulepreload" href="browser cors" crossorigin="use-credentials" /> <link rel="modulepreload" href="browser integrity" integrity="some hash" /> <link rel="modulepreload" href="browser serviceworker" as="serviceworker" /> </head> <body> <div id="container"> <link rel="modulepreload" href="ssr plain" /> <link rel="modulepreload" href="ssr default" /> <link rel="modulepreload" href="ssr cors" crossorigin="use-credentials" /> <link rel="modulepreload" href="ssr integrity" integrity="some hash" /> <link rel="modulepreload" href="ssr serviceworker" as="serviceworker" /> <div>hello</div> </div> </body> </html>, ); }); it('warns if you provide invalid arguments', async () => { function App() { ReactDOM.preloadModule(); ReactDOM.preloadModule(() => {}); ReactDOM.preloadModule(''); ReactDOM.preloadModule('1', true); ReactDOM.preloadModule('2', {as: true}); return <div>hello</div>; } await expect(async () => { await act(() => { renderToPipeableStream(<App />).pipe(writable); }); }).toErrorDev([ 'ReactDOM.preloadModule(): Expected two arguments, a non-empty `href` string and, optionally, an `options` object with an `as` property valid for a `<link rel="modulepreload" as="..." />` tag. The `href` argument encountered was `undefined`', 'ReactDOM.preloadModule(): Expected two arguments, a non-empty `href` string and, optionally, an `options` object with an `as` property valid for a `<link rel="modulepreload" as="..." />` tag. The `href` argument encountered was something with type "function"', 'ReactDOM.preloadModule(): Expected two arguments, a non-empty `href` string and, optionally, an `options` object with an `as` property valid for a `<link rel="modulepreload" as="..." />` tag. The `href` argument encountered was an empty string', 'ReactDOM.preloadModule(): Expected two arguments, a non-empty `href` string and, optionally, an `options` object with an `as` property valid for a `<link rel="modulepreload" as="..." />` tag. The `options` argument encountered was something with type "boolean"', 'ReactDOM.preloadModule(): Expected two arguments, a non-empty `href` string and, optionally, an `options` object with an `as` property valid for a `<link rel="modulepreload" as="..." />` tag. The `as` option encountered was something with type "boolean"', ]); expect(getMeaningfulChildren(document.body)).toEqual( <div id="container"> <link rel="modulepreload" href="1" /> <link rel="modulepreload" href="2" /> <div>hello</div> </div>, ); const root = ReactDOMClient.createRoot( document.getElementById('container'), ); root.render(<App />); await expect(async () => { await waitForAll([]); }).toErrorDev([ 'ReactDOM.preloadModule(): Expected two arguments, a non-empty `href` string and, optionally, an `options` object with an `as` property valid for a `<link rel="modulepreload" as="..." />` tag. The `href` argument encountered was `undefined`', 'ReactDOM.preloadModule(): Expected two arguments, a non-empty `href` string and, optionally, an `options` object with an `as` property valid for a `<link rel="modulepreload" as="..." />` tag. The `href` argument encountered was something with type "function"', 'ReactDOM.preloadModule(): Expected two arguments, a non-empty `href` string and, optionally, an `options` object with an `as` property valid for a `<link rel="modulepreload" as="..." />` tag. The `href` argument encountered was an empty string', 'ReactDOM.preloadModule(): Expected two arguments, a non-empty `href` string and, optionally, an `options` object with an `as` property valid for a `<link rel="modulepreload" as="..." />` tag. The `options` argument encountered was something with type "boolean"', 'ReactDOM.preloadModule(): Expected two arguments, a non-empty `href` string and, optionally, an `options` object with an `as` property valid for a `<link rel="modulepreload" as="..." />` tag. The `as` option encountered was something with type "boolean"', ]); }); }); describe('ReactDOM.preinit(href, { as: ... })', () => { // @gate enableFloat it('creates a stylesheet resource when ReactDOM.preinit(..., {as: "style" }) is called', async () => { function App() { ReactDOM.preinit('foo', {as: 'style'}); return ( <html> <body> <Suspense fallback="loading..."> <BlockedOn value="bar"> <Component /> </BlockedOn> </Suspense> </body> </html> ); } function Component() { ReactDOM.preinit('bar', {as: 'style'}); return <div>hello</div>; } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" /> </head> <body>loading...</body> </html>, ); await act(() => { resolveText('bar'); }); // The reason we do not see the "bar" stylesheet here is that ReactDOM.preinit is not about // encoding a resource dependency but is a hint that a resource will be used in the near future. // If we call preinit on the server after the shell has flushed the best we can do is emit a preload // because any flushing suspense boundaries are not actually dependent on that resource and we don't // want to delay reveal based on when that resource loads. expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" /> </head> <body> <div>hello</div> <link rel="preload" href="bar" as="style" /> </body> </html>, ); function ClientApp() { ReactDOM.preinit('bar', {as: 'style'}); return ( <html> <body> <Suspense fallback="loading..."> <div>hello</div> </Suspense> </body> </html> ); } ReactDOMClient.hydrateRoot(document, <ClientApp />); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" /> <link rel="stylesheet" href="bar" data-precedence="default" /> </head> <body> <div>hello</div> <link rel="preload" href="bar" as="style" /> </body> </html>, ); }); // @gate enableFloat it('creates a stylesheet resource in the ownerDocument when ReactDOM.preinit(..., {as: "style" }) is called outside of render on the client', async () => { function App() { React.useEffect(() => { ReactDOM.preinit('foo', {as: 'style'}); }, []); return ( <html> <body>foo</body> </html> ); } const root = ReactDOMClient.createRoot(document); root.render(<App />); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" /> </head> <body>foo</body> </html>, ); }); // @gate enableFloat it('creates a stylesheet resource in the ownerDocument when ReactDOM.preinit(..., {as: "style" }) is called outside of render on the client', async () => { // This is testing behavior, but it shows that it is not a good idea to preinit inside a shadowRoot. The point is we are asserting a behavior // you would want to avoid in a real app. const shadow = document.body.attachShadow({mode: 'open'}); function ShadowComponent() { ReactDOM.preinit('bar', {as: 'style'}); return null; } function App() { React.useEffect(() => { ReactDOM.preinit('foo', {as: 'style'}); }, []); return ( <html> <body> foo {ReactDOM.createPortal( <div> <ShadowComponent /> shadow </div>, shadow, )} </body> </html> ); } const root = ReactDOMClient.createRoot(document); root.render(<App />); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="bar" data-precedence="default" /> <link rel="stylesheet" href="foo" data-precedence="default" /> </head> <body>foo</body> </html>, ); expect(getMeaningfulChildren(shadow)).toEqual(<div>shadow</div>); }); // @gate enableFloat it('creates a script resource when ReactDOM.preinit(..., {as: "script" }) is called', async () => { function App() { ReactDOM.preinit('foo', {as: 'script'}); return ( <html> <body> <Suspense fallback="loading..."> <BlockedOn value="bar"> <Component /> </BlockedOn> </Suspense> </body> </html> ); } function Component() { ReactDOM.preinit('bar', {as: 'script'}); return <div>hello</div>; } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <script async="" src="foo" /> </head> <body>loading...</body> </html>, ); await act(() => { resolveText('bar'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <script async="" src="foo" /> </head> <body> <div>hello</div> <script async="" src="bar" /> </body> </html>, ); function ClientApp() { ReactDOM.preinit('bar', {as: 'script'}); return ( <html> <body> <Suspense fallback="loading..."> <div>hello</div> </Suspense> </body> </html> ); } ReactDOMClient.hydrateRoot(document, <ClientApp />); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <script async="" src="foo" /> </head> <body> <div>hello</div> <script async="" src="bar" /> </body> </html>, ); }); // @gate enableFloat it('creates a script resource when ReactDOM.preinit(..., {as: "script" }) is called outside of render on the client', async () => { function App() { React.useEffect(() => { ReactDOM.preinit('foo', {as: 'script'}); }, []); return ( <html> <body>foo</body> </html> ); } const root = ReactDOMClient.createRoot(document); root.render(<App />); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <script async="" src="foo" /> </head> <body>foo</body> </html>, ); }); // @gate enableFloat it('warns if you do not pass in a valid href argument or options argument', async () => { function App() { ReactDOM.preinit(); ReactDOM.preinit(''); ReactDOM.preinit('foo', null); ReactDOM.preinit('foo', {}); ReactDOM.preinit('foo', {as: 'foo'}); return <div>foo</div>; } await expect(async () => { await act(() => { renderToPipeableStream(<App />).pipe(writable); }); }).toErrorDev([ 'ReactDOM.preinit(): Expected the `href` argument (first) to be a non-empty string but encountered `undefined` instead', 'ReactDOM.preinit(): Expected the `href` argument (first) to be a non-empty string but encountered an empty string instead', 'ReactDOM.preinit(): Expected the `options` argument (second) to be an object with an `as` property describing the type of resource to be preinitialized but encountered `null` instead', 'ReactDOM.preinit(): Expected the `as` property in the `options` argument (second) to contain a valid value describing the type of resource to be preinitialized but encountered `undefined` instead. Valid values for `as` are "style" and "script".', 'ReactDOM.preinit(): Expected the `as` property in the `options` argument (second) to contain a valid value describing the type of resource to be preinitialized but encountered "foo" instead. Valid values for `as` are "style" and "script".', ]); }); it('accepts a `nonce` option for `as: "script"`', async () => { function Component({src}) { ReactDOM.preinit(src, {as: 'script', nonce: 'R4nD0m'}); return 'hello'; } await act(() => { renderToPipeableStream( <html> <body> <Component src="foo" /> </body> </html>, { nonce: 'R4nD0m', }, ).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <script async="" src="foo" nonce="R4nD0m" /> </head> <body>hello</body> </html>, ); await clientAct(() => { ReactDOMClient.hydrateRoot( document, <html> <body> <Component src="bar" /> </body> </html>, ); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <script async="" src="foo" nonce="R4nD0m" /> <script async="" src="bar" nonce="R4nD0m" /> </head> <body>hello</body> </html>, ); }); it('accepts an `integrity` option for `as: "script"`', async () => { function Component({src, hash}) { ReactDOM.preinit(src, {as: 'script', integrity: hash}); return 'hello'; } await act(() => { renderToPipeableStream( <html> <body> <Component src="foo" hash="foo hash" /> </body> </html>, { nonce: 'R4nD0m', }, ).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <script async="" src="foo" integrity="foo hash" /> </head> <body>hello</body> </html>, ); await clientAct(() => { ReactDOMClient.hydrateRoot( document, <html> <body> <Component src="bar" hash="bar hash" /> </body> </html>, ); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <script async="" src="foo" integrity="foo hash" /> <script async="" src="bar" integrity="bar hash" /> </head> <body>hello</body> </html>, ); }); it('accepts an `integrity` option for `as: "style"`', async () => { function Component({src, hash}) { ReactDOM.preinit(src, {as: 'style', integrity: hash}); return 'hello'; } await act(() => { renderToPipeableStream( <html> <body> <Component src="foo" hash="foo hash" /> </body> </html>, { nonce: 'R4nD0m', }, ).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" integrity="foo hash" data-precedence="default" /> </head> <body>hello</body> </html>, ); await clientAct(() => { ReactDOMClient.hydrateRoot( document, <html> <body> <Component src="bar" hash="bar hash" /> </body> </html>, ); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" integrity="foo hash" data-precedence="default" /> <link rel="stylesheet" href="bar" integrity="bar hash" data-precedence="default" /> </head> <body>hello</body> </html>, ); }); it('supports fetchPriority', async () => { function Component({isServer}) { ReactDOM.preinit(isServer ? 'highserver' : 'highclient', { as: 'script', fetchPriority: 'high', }); ReactDOM.preinit(isServer ? 'lowserver' : 'lowclient', { as: 'style', fetchPriority: 'low', }); ReactDOM.preinit(isServer ? 'autoserver' : 'autoclient', { as: 'style', fetchPriority: 'auto', }); return 'hello'; } await act(() => { renderToPipeableStream( <html> <body> <Component isServer={true} /> </body> </html>, ).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="lowserver" fetchpriority="low" data-precedence="default" /> <link rel="stylesheet" href="autoserver" fetchpriority="auto" data-precedence="default" /> <script async="" src="highserver" fetchpriority="high" /> </head> <body>hello</body> </html>, ); ReactDOMClient.hydrateRoot( document, <html> <body> <Component /> </body> </html>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="lowserver" fetchpriority="low" data-precedence="default" /> <link rel="stylesheet" href="autoserver" fetchpriority="auto" data-precedence="default" /> <link rel="stylesheet" href="lowclient" fetchpriority="low" data-precedence="default" /> <link rel="stylesheet" href="autoclient" fetchpriority="auto" data-precedence="default" /> <script async="" src="highserver" fetchpriority="high" /> <script async="" src="highclient" fetchpriority="high" /> </head> <body>hello</body> </html>, ); }); }); describe('ReactDOM.preinitModule(href, options)', () => { it('creates a script module resources', async () => { function App({ssr}) { const prefix = ssr ? 'ssr ' : 'browser '; ReactDOM.preinitModule(prefix + 'plain'); ReactDOM.preinitModule(prefix + 'default', {as: 'script'}); ReactDOM.preinitModule(prefix + 'cors', { crossOrigin: 'use-credentials', }); ReactDOM.preinitModule(prefix + 'integrity', {integrity: 'some hash'}); ReactDOM.preinitModule(prefix + 'warning', {as: 'style'}); return <div>hello</div>; } await expect(async () => { await act(() => { renderToPipeableStream(<App ssr={true} />).pipe(writable); }); }).toErrorDev([ 'ReactDOM.preinitModule(): Expected up to two arguments, a non-empty `href` string and, optionally, an `options` object with a valid `as` property. The `as` option encountered was "style"', ]); expect(getMeaningfulChildren(document.body)).toEqual( <div id="container"> <script type="module" src="ssr plain" async="" /> <script type="module" src="ssr default" async="" /> <script type="module" src="ssr cors" crossorigin="use-credentials" async="" /> <script type="module" src="ssr integrity" integrity="some hash" async="" /> <div>hello</div> </div>, ); ReactDOMClient.hydrateRoot(container, <App />); await expect(async () => { await waitForAll([]); }).toErrorDev([ 'ReactDOM.preinitModule(): Expected up to two arguments, a non-empty `href` string and, optionally, an `options` object with a valid `as` property. The `as` option encountered was "style"', ]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <script type="module" src="browser plain" async="" /> <script type="module" src="browser default" async="" /> <script type="module" src="browser cors" crossorigin="use-credentials" async="" /> <script type="module" src="browser integrity" integrity="some hash" async="" /> </head> <body> <div id="container"> <script type="module" src="ssr plain" async="" /> <script type="module" src="ssr default" async="" /> <script type="module" src="ssr cors" crossorigin="use-credentials" async="" /> <script type="module" src="ssr integrity" integrity="some hash" async="" /> <div>hello</div> </div> </body> </html>, ); }); it('warns if you provide invalid arguments', async () => { function App() { ReactDOM.preinitModule(); ReactDOM.preinitModule(() => {}); ReactDOM.preinitModule(''); ReactDOM.preinitModule('1', true); ReactDOM.preinitModule('2', {as: true}); return <div>hello</div>; } await expect(async () => { await act(() => { renderToPipeableStream(<App />).pipe(writable); }); }).toErrorDev([ 'ReactDOM.preinitModule(): Expected up to two arguments, a non-empty `href` string and, optionally, an `options` object with a valid `as` property. The `href` argument encountered was `undefined`', 'ReactDOM.preinitModule(): Expected up to two arguments, a non-empty `href` string and, optionally, an `options` object with a valid `as` property. The `href` argument encountered was something with type "function"', 'ReactDOM.preinitModule(): Expected up to two arguments, a non-empty `href` string and, optionally, an `options` object with a valid `as` property. The `href` argument encountered was an empty string', 'ReactDOM.preinitModule(): Expected up to two arguments, a non-empty `href` string and, optionally, an `options` object with a valid `as` property. The `options` argument encountered was something with type "boolean"', 'ReactDOM.preinitModule(): Expected up to two arguments, a non-empty `href` string and, optionally, an `options` object with a valid `as` property. The `as` option encountered was something with type "boolean"', ]); expect(getMeaningfulChildren(document.body)).toEqual( <div id="container"> <div>hello</div> </div>, ); const root = ReactDOMClient.createRoot( document.getElementById('container'), ); root.render(<App />); await expect(async () => { await waitForAll([]); }).toErrorDev([ 'ReactDOM.preinitModule(): Expected up to two arguments, a non-empty `href` string and, optionally, an `options` object with a valid `as` property. The `href` argument encountered was `undefined`', 'ReactDOM.preinitModule(): Expected up to two arguments, a non-empty `href` string and, optionally, an `options` object with a valid `as` property. The `href` argument encountered was something with type "function"', 'ReactDOM.preinitModule(): Expected up to two arguments, a non-empty `href` string and, optionally, an `options` object with a valid `as` property. The `href` argument encountered was an empty string', 'ReactDOM.preinitModule(): Expected up to two arguments, a non-empty `href` string and, optionally, an `options` object with a valid `as` property. The `options` argument encountered was something with type "boolean"', 'ReactDOM.preinitModule(): Expected up to two arguments, a non-empty `href` string and, optionally, an `options` object with a valid `as` property. The `as` option encountered was something with type "boolean"', ]); }); }); describe('Stylesheet Resources', () => { // @gate enableFloat it('treats link rel stylesheet elements as a stylesheet resource when it includes a precedence when server rendering', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <head /> <body> <link rel="stylesheet" href="aresource" precedence="foo" /> <div>hello world</div> </body> </html>, ); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="aresource" data-precedence="foo" /> </head> <body> <div>hello world</div> </body> </html>, ); }); // @gate enableFloat it('treats link rel stylesheet elements as a stylesheet resource when it includes a precedence when client rendering', async () => { const root = ReactDOMClient.createRoot(document); root.render( <html> <head /> <body> <link rel="stylesheet" href="aresource" precedence="foo" /> <div>hello world</div> </body> </html>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="aresource" data-precedence="foo" /> </head> <body> <div>hello world</div> </body> </html>, ); }); // @gate enableFloat it('treats link rel stylesheet elements as a stylesheet resource when it includes a precedence when hydrating', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <head /> <body> <link rel="stylesheet" href="aresource" precedence="foo" /> <div>hello world</div> </body> </html>, ); pipe(writable); }); ReactDOMClient.hydrateRoot( document, <html> <head /> <body> <link rel="stylesheet" href="aresource" precedence="foo" /> <div>hello world</div> </body> </html>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="aresource" data-precedence="foo" /> </head> <body> <div>hello world</div> </body> </html>, ); }); // @gate enableFloat it('hoists stylesheet resources to the correct precedence', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <head /> <body> <link rel="stylesheet" href="foo1" precedence="foo" /> <link rel="stylesheet" href="default1" precedence="default" /> <link rel="stylesheet" href="foo2" precedence="foo" /> <div>hello world</div> </body> </html>, ); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo1" data-precedence="foo" /> <link rel="stylesheet" href="foo2" data-precedence="foo" /> <link rel="stylesheet" href="default1" data-precedence="default" /> </head> <body> <div>hello world</div> </body> </html>, ); ReactDOMClient.hydrateRoot( document, <html> <head /> <body> <link rel="stylesheet" href="bar1" precedence="bar" /> <link rel="stylesheet" href="foo3" precedence="foo" /> <link rel="stylesheet" href="default2" precedence="default" /> <div>hello world</div> </body> </html>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo1" data-precedence="foo" /> <link rel="stylesheet" href="foo2" data-precedence="foo" /> <link rel="stylesheet" href="foo3" data-precedence="foo" /> <link rel="stylesheet" href="default1" data-precedence="default" /> <link rel="stylesheet" href="default2" data-precedence="default" /> <link rel="stylesheet" href="bar1" data-precedence="bar" /> <link rel="preload" as="style" href="bar1" /> <link rel="preload" as="style" href="foo3" /> <link rel="preload" as="style" href="default2" /> </head> <body> <div>hello world</div> </body> </html>, ); }); // @gate enableFloat it('retains styles even after the last referring Resource unmounts', async () => { // This test is true until a future update where there is some form of garbage collection. const root = ReactDOMClient.createRoot(document); root.render( <html> <head /> <body> hello world <link rel="stylesheet" href="foo" precedence="foo" /> </body> </html>, ); await waitForAll([]); root.render( <html> <head /> <body>hello world</body> </html>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="foo" /> </head> <body>hello world</body> </html>, ); }); // @gate enableFloat && enableClientRenderFallbackOnTextMismatch it('retains styles even when a new html, head, and/body mount', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <head /> <body> <link rel="stylesheet" href="foo" precedence="foo" /> <link rel="stylesheet" href="bar" precedence="bar" /> server </body> </html>, ); pipe(writable); }); const errors = []; ReactDOMClient.hydrateRoot( document, <html> <head> <link rel="stylesheet" href="qux" precedence="qux" /> <link rel="stylesheet" href="foo" precedence="foo" /> </head> <body>client</body> </html>, { onRecoverableError(error) { errors.push(error.message); }, }, ); await expect(async () => { await waitForAll([]); }).toErrorDev( [ 'Warning: Text content did not match. Server: "server" Client: "client"', 'Warning: An error occurred during hydration. The server HTML was replaced with client content in <#document>.', ], {withoutStack: 1}, ); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="foo" /> <link rel="stylesheet" href="bar" data-precedence="bar" /> <link rel="stylesheet" href="qux" data-precedence="qux" /> </head> <body>client</body> </html>, ); }); // @gate enableFloat it('retains styles in head through head remounts', async () => { const root = ReactDOMClient.createRoot(document); root.render( <html> <head key={1} /> <body> <link rel="stylesheet" href="foo" precedence="foo" /> <link rel="stylesheet" href="bar" precedence="bar" /> {null} hello </body> </html>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="foo" /> <link rel="stylesheet" href="bar" data-precedence="bar" /> </head> <body>hello</body> </html>, ); root.render( <html> <head key={2} /> <body> <link rel="stylesheet" href="foo" precedence="foo" /> {null} <link rel="stylesheet" href="baz" precedence="baz" /> hello </body> </html>, ); await waitForAll([]); // The reason we do not see preloads in the head is they are inserted synchronously // during render and then when the new singleton mounts it resets it's content, retaining only styles expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="foo" /> <link rel="stylesheet" href="bar" data-precedence="bar" /> <link rel="stylesheet" href="baz" data-precedence="baz" /> <link rel="preload" href="baz" as="style" /> </head> <body>hello</body> </html>, ); }); // @gate enableFloat it('can support styles inside portals to a shadowRoot', async () => { const shadow = document.body.attachShadow({mode: 'open'}); const root = ReactDOMClient.createRoot(container); root.render( <> <link rel="stylesheet" href="foo" precedence="default" /> {ReactDOM.createPortal( <div> <link rel="stylesheet" href="foo" data-extra-prop="foo" precedence="different" /> shadow </div>, shadow, )} container </>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" /> <link rel="preload" href="foo" as="style" /> </head> <body> <div id="container">container</div> </body> </html>, ); expect(getMeaningfulChildren(shadow)).toEqual([ <link rel="stylesheet" href="foo" data-precedence="different" data-extra-prop="foo" />, <div>shadow</div>, ]); }); // @gate enableFloat it('can support styles inside portals to an element in shadowRoots', async () => { const template = document.createElement('template'); template.innerHTML = "<div><div id='shadowcontainer1'></div><div id='shadowcontainer2'></div></div>"; const shadow = document.body.attachShadow({mode: 'open'}); shadow.appendChild(template.content); const shadowContainer1 = shadow.getElementById('shadowcontainer1'); const shadowContainer2 = shadow.getElementById('shadowcontainer2'); const root = ReactDOMClient.createRoot(container); root.render( <> <link rel="stylesheet" href="foo" precedence="default" /> {ReactDOM.createPortal( <div> <link rel="stylesheet" href="foo" precedence="one" /> <link rel="stylesheet" href="bar" precedence="two" />1 </div>, shadow, )} {ReactDOM.createPortal( <div> <link rel="stylesheet" href="foo" precedence="one" /> <link rel="stylesheet" href="baz" precedence="one" />2 </div>, shadowContainer1, )} {ReactDOM.createPortal( <div> <link rel="stylesheet" href="bar" precedence="two" /> <link rel="stylesheet" href="qux" precedence="three" />3 </div>, shadowContainer2, )} container </>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="foo" data-precedence="default" /> <link rel="preload" href="foo" as="style" /> <link rel="preload" href="bar" as="style" /> <link rel="preload" href="baz" as="style" /> <link rel="preload" href="qux" as="style" /> </head> <body> <div id="container">container</div> </body> </html>, ); expect(getMeaningfulChildren(shadow)).toEqual([ <link rel="stylesheet" href="foo" data-precedence="one" />, <link rel="stylesheet" href="baz" data-precedence="one" />, <link rel="stylesheet" href="bar" data-precedence="two" />, <link rel="stylesheet" href="qux" data-precedence="three" />, <div> <div id="shadowcontainer1"> <div>2</div> </div> <div id="shadowcontainer2"> <div>3</div> </div> </div>, <div>1</div>, ]); }); // @gate enableFloat it('escapes hrefs when selecting matching elements in the document when rendering Resources', async () => { function App() { ReactDOM.preload('preload', {as: 'style'}); ReactDOM.preload('with\nnewline', {as: 'style'}); return ( <html> <head /> <body> <link rel="stylesheet" href="style" precedence="style" /> <link rel="stylesheet" href="with\slashes" precedence="style" /> <div id="container" /> </body> </html> ); } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); container = document.getElementById('container'); const root = ReactDOMClient.createRoot(container); function ClientApp() { ReactDOM.preload('preload', {as: 'style'}); ReactDOM.preload('with\nnewline', {as: 'style'}); return ( <div> <link rel="stylesheet" href={'style"][rel="stylesheet'} precedence="style" /> <link rel="stylesheet" href="with\slashes" precedence="style" /> foo </div> ); } root.render(<ClientApp />); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="style" data-precedence="style" /> <link rel="stylesheet" href="with\slashes" data-precedence="style" /> <link rel="stylesheet" href={'style"][rel="stylesheet'} data-precedence="style" /> <link rel="preload" as="style" href="preload" /> <link rel="preload" href={'with\nnewline'} as="style" /> <link rel="preload" href={'style"][rel="stylesheet'} as="style" /> </head> <body> <div id="container"> <div>foo</div> </div> </body> </html>, ); }); // @gate enableFloat it('escapes hrefs when selecting matching elements in the document when using preload and preinit', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <head /> <body> <link rel="preload" href="preload" as="style" /> <link rel="stylesheet" href="style" precedence="style" /> <link rel="stylesheet" href="with\slashes" precedence="style" /> <link rel="preload" href={'with\nnewline'} as="style" /> <div id="container" /> </body> </html>, ); pipe(writable); }); function App() { ReactDOM.preload('preload"][rel="preload', {as: 'style'}); ReactDOM.preinit('style"][rel="stylesheet', { as: 'style', precedence: 'style', }); ReactDOM.preinit('with\\slashes', { as: 'style', precedence: 'style', }); ReactDOM.preload('with\nnewline', {as: 'style'}); return <div>foo</div>; } container = document.getElementById('container'); const root = ReactDOMClient.createRoot(container); root.render(<App />); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="style" data-precedence="style" /> <link rel="stylesheet" href="with\slashes" data-precedence="style" /> <link rel="stylesheet" href={'style"][rel="stylesheet'} data-precedence="style" /> <link rel="preload" as="style" href="preload" /> <link rel="preload" href={'with\nnewline'} as="style" /> <link rel="preload" href={'preload"][rel="preload'} as="style" /> </head> <body> <div id="container"> <div>foo</div> </div> </body> </html>, ); }); // @gate enableFloat it('does not create stylesheet resources when inside an <svg> context', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <body> <svg> <path> <link rel="stylesheet" href="foo" precedence="default" /> </path> <foreignObject> <link rel="stylesheet" href="bar" precedence="default" /> </foreignObject> </svg> </body> </html>, ); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="bar" data-precedence="default" /> </head> <body> <svg> <path> <link rel="stylesheet" href="foo" precedence="default" /> </path> <foreignobject /> </svg> </body> </html>, ); const root = ReactDOMClient.createRoot(document.body); root.render( <div> <svg> <path> <link rel="stylesheet" href="foo" precedence="default" /> </path> <foreignObject> <link rel="stylesheet" href="bar" precedence="default" /> </foreignObject> </svg> </div>, ); await waitForAll([]); expect(getMeaningfulChildren(document.body)).toEqual( <div> <svg> <path> <link rel="stylesheet" href="foo" precedence="default" /> </path> <foreignobject /> </svg> </div>, ); }); // @gate enableFloat it('does not create stylesheet resources when inside a <noscript> context', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <body> <noscript> <link rel="stylesheet" href="foo" precedence="default" /> </noscript> </body> </html>, ); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body> <noscript> &lt;link rel="stylesheet" href="foo" precedence="default"&gt; </noscript> </body> </html>, ); const root = ReactDOMClient.createRoot(document.body); root.render( <div> <noscript> <link rel="stylesheet" href="foo" precedence="default" /> </noscript> </div>, ); await waitForAll([]); expect(getMeaningfulChildren(document.body)).toEqual( <div> {/* On the client, <noscript> never renders children */} <noscript /> </div>, ); }); // @gate enableFloat it('warns if you provide a `precedence` prop with other props that invalidate the creation of a stylesheet resource', async () => { await expect(async () => { await act(() => { renderToPipeableStream( <html> <body> <link rel="stylesheet" precedence="default" /> <link rel="stylesheet" href="" precedence="default" /> <link rel="stylesheet" href="foo" precedence="default" onLoad={() => {}} onError={() => {}} /> <link rel="stylesheet" href="foo" precedence="default" onLoad={() => {}} /> <link rel="stylesheet" href="foo" precedence="default" onError={() => {}} /> <link rel="stylesheet" href="foo" precedence="default" disabled={false} /> </body> </html>, ).pipe(writable); }); }).toErrorDev( [ gate(flags => flags.enableFilterEmptyStringAttributesDOM) ? 'An empty string ("") was passed to the href attribute. To fix this, either do not render the element at all or pass null to href instead of an empty string.' : undefined, 'React encountered a `<link rel="stylesheet" .../>` with a `precedence` prop and expected the `href` prop to be a non-empty string but ecountered `undefined` instead. If your intent was to have React hoist and deduplciate this stylesheet using the `precedence` prop ensure there is a non-empty string `href` prop as well, otherwise remove the `precedence` prop.', 'React encountered a `<link rel="stylesheet" .../>` with a `precedence` prop and expected the `href` prop to be a non-empty string but ecountered an empty string instead. If your intent was to have React hoist and deduplciate this stylesheet using the `precedence` prop ensure there is a non-empty string `href` prop as well, otherwise remove the `precedence` prop.', 'React encountered a `<link rel="stylesheet" .../>` with a `precedence` prop and `onLoad` and `onError` props. The presence of loading and error handlers indicates an intent to manage the stylesheet loading state from your from your Component code and React will not hoist or deduplicate this stylesheet. If your intent was to have React hoist and deduplciate this stylesheet using the `precedence` prop remove the `onLoad` and `onError` props, otherwise remove the `precedence` prop.', 'React encountered a `<link rel="stylesheet" .../>` with a `precedence` prop and `onLoad` prop. The presence of loading and error handlers indicates an intent to manage the stylesheet loading state from your from your Component code and React will not hoist or deduplicate this stylesheet. If your intent was to have React hoist and deduplciate this stylesheet using the `precedence` prop remove the `onLoad` prop, otherwise remove the `precedence` prop.', 'React encountered a `<link rel="stylesheet" .../>` with a `precedence` prop and `onError` prop. The presence of loading and error handlers indicates an intent to manage the stylesheet loading state from your from your Component code and React will not hoist or deduplicate this stylesheet. If your intent was to have React hoist and deduplciate this stylesheet using the `precedence` prop remove the `onError` prop, otherwise remove the `precedence` prop.', 'React encountered a `<link rel="stylesheet" .../>` with a `precedence` prop and a `disabled` prop. The presence of the `disabled` prop indicates an intent to manage the stylesheet active state from your from your Component code and React will not hoist or deduplicate this stylesheet. If your intent was to have React hoist and deduplciate this stylesheet using the `precedence` prop remove the `disabled` prop, otherwise remove the `precedence` prop.', ].filter(Boolean), ); ReactDOMClient.hydrateRoot( document, <html> <body> <link rel="stylesheet" href="foo" precedence="default" onLoad={() => {}} onError={() => {}} /> </body> </html>, ); await expect(async () => { await waitForAll([]); }).toErrorDev([ 'React encountered a <link rel="stylesheet" href="foo" ... /> with a `precedence` prop that also included the `onLoad` and `onError` props. The presence of loading and error handlers indicates an intent to manage the stylesheet loading state from your from your Component code and React will not hoist or deduplicate this stylesheet. If your intent was to have React hoist and deduplciate this stylesheet using the `precedence` prop remove the `onLoad` and `onError` props, otherwise remove the `precedence` prop.', ]); }); // @gate enableFloat it('will not block displaying a Suspense boundary on a stylesheet with media that does not match', async () => { await act(() => { renderToPipeableStream( <html> <body> <Suspense fallback="loading..."> <BlockedOn value="block"> foo <link rel="stylesheet" href="print" media="print" precedence="print" /> <link rel="stylesheet" href="all" media="all" precedence="all" /> </BlockedOn> </Suspense> <Suspense fallback="loading..."> <BlockedOn value="block"> bar <link rel="stylesheet" href="print" media="print" precedence="print" /> <link rel="stylesheet" href="all" media="all" precedence="all" /> </BlockedOn> </Suspense> </body> </html>, ).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body> {'loading...'} {'loading...'} </body> </html>, ); await act(() => { resolveText('block'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="print" media="print" data-precedence="print" /> <link rel="stylesheet" href="all" media="all" data-precedence="all" /> </head> <body> {'loading...'} {'loading...'} <link rel="preload" href="print" media="print" as="style" /> <link rel="preload" href="all" media="all" as="style" /> </body> </html>, ); await act(() => { const allStyle = document.querySelector('link[href="all"]'); const event = document.createEvent('Events'); event.initEvent('load', true, true); allStyle.dispatchEvent(event); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="print" media="print" data-precedence="print" /> <link rel="stylesheet" href="all" media="all" data-precedence="all" /> </head> <body> {'foo'} {'bar'} <link rel="preload" href="print" media="print" as="style" /> <link rel="preload" href="all" media="all" as="style" /> </body> </html>, ); }); }); describe('Style Resource', () => { // @gate enableFloat it('treats <style href="..." precedence="..."> elements as a style resource when server rendering', async () => { const css = ` body { background-color: red; }`; await act(() => { renderToPipeableStream( <html> <body> <style href="foo" precedence="foo"> {css} </style> </body> </html>, ).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <style data-href="foo" data-precedence="foo"> {css} </style> </head> <body /> </html>, ); }); // @gate enableFloat it('can insert style resources as part of a boundary reveal', async () => { const cssRed = ` body { background-color: red; }`; const cssBlue = ` body { background-color: blue; }`; const cssGreen = ` body { background-color: green; }`; await act(() => { renderToPipeableStream( <html> <body> <Suspense fallback="loading..."> <BlockedOn value="blocked"> <style href="foo" precedence="foo"> {cssRed} </style> loaded </BlockedOn> </Suspense> </body> </html>, ).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body>loading...</body> </html>, ); await act(() => { resolveText('blocked'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <style data-href="foo" data-precedence="foo"> {cssRed} </style> </head> <body>loaded</body> </html>, ); const root = ReactDOMClient.hydrateRoot( document, <html> <body> <Suspense fallback="loading..."> <style href="foo" precedence="foo"> {cssRed} </style> loaded </Suspense> </body> </html>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <style data-href="foo" data-precedence="foo"> {cssRed} </style> </head> <body>loaded</body> </html>, ); root.render( <html> <body> <Suspense fallback="loading..."> <style href="foo" precedence="foo"> {cssRed} </style> loaded </Suspense> <style href="bar" precedence="bar"> {cssBlue} </style> <style href="baz" precedence="foo"> {cssGreen} </style> </body> </html>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <style data-href="foo" data-precedence="foo"> {cssRed} </style> <style data-href="baz" data-precedence="foo"> {cssGreen} </style> <style data-href="bar" data-precedence="bar"> {cssBlue} </style> </head> <body>loaded</body> </html>, ); }); // @gate enableFloat it('can emit styles early when a partial boundary flushes', async () => { const css = 'body { background-color: red; }'; await act(() => { renderToPipeableStream( <html> <body> <Suspense> <BlockedOn value="first"> <div>first</div> <style href="foo" precedence="default"> {css} </style> <BlockedOn value="second"> <div>second</div> <style href="bar" precedence="default"> {css} </style> </BlockedOn> </BlockedOn> </Suspense> </body> </html>, ).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body /> </html>, ); await act(() => { resolveText('first'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body> <style data-href="foo" data-precedence="default" media="not all"> {css} </style> </body> </html>, ); await act(() => { resolveText('second'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <style data-href="foo" data-precedence="default"> {css} </style> <style data-href="bar" data-precedence="default"> {css} </style> </head> <body> <div>first</div> <div>second</div> </body> </html>, ); }); it('can hoist styles flushed early even when no other style dependencies are flushed on completion', async () => { await act(() => { renderToPipeableStream( <html> <body> <Suspense fallback="loading..."> <BlockedOn value="first"> <style href="foo" precedence="default"> some css </style> <div>first</div> <BlockedOn value="second"> <div>second</div> </BlockedOn> </BlockedOn> </Suspense> </body> </html>, ).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body>loading...</body> </html>, ); // When we resolve first we flush the style tag because it is ready but we aren't yet ready to // flush the entire boundary and reveal it. await act(() => { resolveText('first'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body> loading... <style data-href="foo" data-precedence="default" media="not all"> some css </style> </body> </html>, ); // When we resolve second we flush the rest of the boundary segments and reveal the boundary. The style tag // is hoisted during this reveal process even though no other styles flushed during this tick await act(() => { resolveText('second'); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <style data-href="foo" data-precedence="default"> some css </style> </head> <body> <div>first</div> <div>second</div> </body> </html>, ); }); it('can emit multiple style rules into a single style tag for a given precedence', async () => { await act(() => { renderToPipeableStream( <html> <body> <style href="1" precedence="default"> 1 </style> <style href="2" precedence="foo"> foo2 </style> <style href="3" precedence="default"> 3 </style> <style href="4" precedence="default"> 4 </style> <style href="5" precedence="foo"> foo5 </style> <div>initial</div> <Suspense fallback="loading..."> <BlockedOn value="first"> <style href="6" precedence="default"> 6 </style> <style href="7" precedence="foo"> foo7 </style> <style href="8" precedence="default"> 8 </style> <style href="9" precedence="default"> 9 </style> <style href="10" precedence="foo"> foo10 </style> <div>first</div> <BlockedOn value="second"> <style href="11" precedence="default"> 11 </style> <style href="12" precedence="foo"> foo12 </style> <style href="13" precedence="default"> 13 </style> <style href="14" precedence="default"> 14 </style> <style href="15" precedence="foo"> foo15 </style> <div>second</div> </BlockedOn> </BlockedOn> </Suspense> </body> </html>, ).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <style data-href="1 3 4" data-precedence="default"> 134 </style> <style data-href="2 5" data-precedence="foo"> foo2foo5 </style> </head> <body> <div>initial</div>loading... </body> </html>, ); // When we resolve first we flush the style tag because it is ready but we aren't yet ready to // flush the entire boundary and reveal it. await act(() => { resolveText('first'); }); await act(() => { resolveText('second'); }); // Some sets of styles were ready before the entire boundary and they got emitted as early as they were // ready. The remaining styles were ready when the boundary finished and they got grouped as well expect(getMeaningfulChildren(document)).toEqual( <html> <head> <style data-href="1 3 4" data-precedence="default"> 134 </style> <style data-href="6 8 9" data-precedence="default"> 689 </style> <style data-href="11 13 14" data-precedence="default"> 111314 </style> <style data-href="2 5" data-precedence="foo"> foo2foo5 </style> <style data-href="7 10" data-precedence="foo"> foo7foo10 </style> <style data-href="12 15" data-precedence="foo"> foo12foo15 </style> </head> <body> <div>initial</div> <div>first</div> <div>second</div> </body> </html>, ); // Client inserted style tags are not grouped together but can hydrate against a grouped set ReactDOMClient.hydrateRoot( document, <html> <body> <style href="1" precedence="default"> 1 </style> <style href="2" precedence="foo"> foo2 </style> <style href="16" precedence="default"> 16 </style> <style href="17" precedence="default"> 17 </style> </body> </html>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <style data-href="1 3 4" data-precedence="default"> 134 </style> <style data-href="6 8 9" data-precedence="default"> 689 </style> <style data-href="11 13 14" data-precedence="default"> 111314 </style> <style data-href="16" data-precedence="default"> 16 </style> <style data-href="17" data-precedence="default"> 17 </style> <style data-href="2 5" data-precedence="foo"> foo2foo5 </style> <style data-href="7 10" data-precedence="foo"> foo7foo10 </style> <style data-href="12 15" data-precedence="foo"> foo12foo15 </style> </head> <body> <div>initial</div> <div>first</div> <div>second</div> </body> </html>, ); }); it('warns if you render a <style> with an href with a space on the server', async () => { await expect(async () => { await act(() => { renderToPipeableStream( <html> <body> <style href="foo bar" precedence="default"> style </style> </body> </html>, ).pipe(writable); }); }).toErrorDev( 'React expected the `href` prop for a <style> tag opting into hoisting semantics using the `precedence` prop to not have any spaces but ecountered spaces instead. using spaces in this prop will cause hydration of this style to fail on the client. The href for the <style> where this ocurred is "foo bar".', ); }); }); describe('Script Resources', () => { // @gate enableFloat it('treats async scripts without onLoad or onError as Resources', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <head /> <body> <script src="foo" async={true} /> <script src="bar" async={true} onLoad={() => {}} /> <script src="baz" data-meaningful="" /> <script src="qux" defer={true} data-meaningful="" /> hello world </body> </html>, ); pipe(writable); }); // The plain async script is converted to a resource and emitted as part of the shell // The async script with onLoad is preloaded in the shell but is expecting to be added // during hydration. This is novel, the script is NOT a HostHoistable but it also will // never hydrate // The regular script is just a normal html that should hydrate with a HostComponent expect(getMeaningfulChildren(document)).toEqual( <html> <head> <script src="foo" async="" /> </head> <body> <script src="bar" async="" /> <script src="baz" data-meaningful="" /> <script src="qux" defer="" data-meaningful="" /> hello world </body> </html>, ); const root = ReactDOMClient.hydrateRoot( document, <html> <head /> <body> <script src="foo" async={true} /> <script src="bar" async={true} onLoad={() => {}} /> <script src="baz" data-meaningful="" /> <script src="qux" defer={true} data-meaningful="" /> hello world </body> </html>, ); await waitForAll([]); // The async script with onLoad is inserted in the right place but does not cause the hydration // to fail. expect(getMeaningfulChildren(document)).toEqual( <html> <head> <script src="foo" async="" /> </head> <body> <script src="bar" async="" /> <script src="baz" data-meaningful="" /> <script src="qux" defer="" data-meaningful="" /> hello world </body> </html>, ); root.unmount(); // When we unmount we expect to retain singletons and any content that is not cleared within them. // The foo script is a resource so it sticks around. The other scripts are regular HostComponents // so they unmount and are removed from the DOM. expect(getMeaningfulChildren(document)).toEqual( <html> <head> <script src="foo" async="" /> </head> <body /> </html>, ); }); // @gate enableFloat it('does not create script resources when inside an <svg> context', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <body> <svg> <path> <script async={true} src="foo" /> </path> <foreignObject> <script async={true} src="bar" /> </foreignObject> </svg> </body> </html>, ); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <script async="" src="bar" /> </head> <body> <svg> <path> <script async="" src="foo" /> </path> <foreignobject /> </svg> </body> </html>, ); const root = ReactDOMClient.createRoot(document.body); root.render( <div> <svg> <path> <script async={true} src="foo" /> </path> <foreignObject> <script async={true} src="bar" /> </foreignObject> </svg> </div>, ); await waitForAll([]); expect(getMeaningfulChildren(document.body)).toEqual( <div> <svg> <path> <script async="" src="foo" /> </path> <foreignobject /> </svg> </div>, ); }); // @gate enableFloat it('does not create script resources when inside a <noscript> context', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <body> <noscript> <script async={true} src="foo" /> </noscript> </body> </html>, ); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body> <noscript> &lt;script async="" src="foo"&gt;&lt;/script&gt; </noscript> </body> </html>, ); const root = ReactDOMClient.createRoot(document.body); root.render( <div> <noscript> <script async={true} src="foo" /> </noscript> </div>, ); await waitForAll([]); expect(getMeaningfulChildren(document.body)).toEqual( <div> {/* On the client, <noscript> never renders children */} <noscript /> </div>, ); }); }); describe('Hoistables', () => { // @gate enableFloat it('can hoist meta tags on the server and hydrate them on the client', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <body> <meta name="foo" data-foo="data" content="bar" /> </body> </html>, ); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <meta name="foo" data-foo="data" content="bar" /> </head> <body /> </html>, ); const root = ReactDOMClient.hydrateRoot( document, <html> <body> <meta name="foo" data-foo="data" content="bar" /> </body> </html>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <meta name="foo" data-foo="data" content="bar" /> </head> <body /> </html>, ); root.render( <html> <body /> </html>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body /> </html>, ); }); // @gate enableFloat it('can hoist meta tags on the client', async () => { const root = ReactDOMClient.createRoot(container); await act(() => { root.render( <div> <meta name="foo" data-foo="data" content="bar" /> </div>, ); }); await waitForAll([]); expect(getMeaningfulChildren(document.head)).toEqual( <meta name="foo" data-foo="data" content="bar" />, ); expect(getMeaningfulChildren(container)).toEqual(<div />); root.render(<div />); await waitForAll([]); expect(getMeaningfulChildren(document.head)).toEqual(undefined); }); // @gate enableFloat it('can hoist link (non-stylesheet) tags on the server and hydrate them on the client', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <body> <link rel="foo" data-foo="data" href="foo" /> </body> </html>, ); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="foo" data-foo="data" href="foo" /> </head> <body /> </html>, ); const root = ReactDOMClient.hydrateRoot( document, <html> <body> <link rel="foo" data-foo="data" href="foo" /> </body> </html>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="foo" data-foo="data" href="foo" /> </head> <body /> </html>, ); root.render( <html> <body /> </html>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body /> </html>, ); }); // @gate enableFloat it('can hoist link (non-stylesheet) tags on the client', async () => { const root = ReactDOMClient.createRoot(container); await act(() => { root.render( <div> <link rel="foo" data-foo="data" href="foo" /> </div>, ); }); await waitForAll([]); expect(getMeaningfulChildren(document.head)).toEqual( <link rel="foo" data-foo="data" href="foo" />, ); expect(getMeaningfulChildren(container)).toEqual(<div />); root.render(<div />); await waitForAll([]); expect(getMeaningfulChildren(document.head)).toEqual(undefined); }); // @gate enableFloat it('can hoist title tags on the server and hydrate them on the client', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <body> <title data-foo="foo">a title</title> </body> </html>, ); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <title data-foo="foo">a title</title> </head> <body /> </html>, ); const root = ReactDOMClient.hydrateRoot( document, <html> <body> <title data-foo="foo">a title</title> </body> </html>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <title data-foo="foo">a title</title> </head> <body /> </html>, ); root.render( <html> <body /> </html>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body /> </html>, ); }); // @gate enableFloat it('can hoist title tags on the client', async () => { const root = ReactDOMClient.createRoot(container); await act(() => { root.render( <div> <title data-foo="foo">a title</title> </div>, ); }); await waitForAll([]); expect(getMeaningfulChildren(document.head)).toEqual( <title data-foo="foo">a title</title>, ); expect(getMeaningfulChildren(container)).toEqual(<div />); root.render(<div />); await waitForAll([]); expect(getMeaningfulChildren(document.head)).toEqual(undefined); }); // @gate enableFloat it('prioritizes ordering for certain hoistables over others when rendering on the server', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <body> <link rel="foo" href="foo" /> <meta name="bar" /> <title>a title</title> <link rel="preload" href="foo" as="style" /> <link rel="preconnect" href="bar" /> <link rel="dns-prefetch" href="baz" /> <meta charSet="utf-8" /> </body> </html>, ); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> {/* charset first */} <meta charset="utf-8" /> {/* preconnect links next */} <link rel="preconnect" href="bar" /> <link rel="dns-prefetch" href="baz" /> {/* preloads next */} <link rel="preload" href="foo" as="style" /> {/* Everything else last */} <link rel="foo" href="foo" /> <meta name="bar" /> <title>a title</title> </head> <body /> </html>, ); }); // @gate enableFloat it('emits hoistables before other content when streaming in late', async () => { let content = ''; writable.on('data', chunk => (content += chunk)); await act(() => { const {pipe} = renderToPipeableStream( <html> <body> <meta name="early" /> <Suspense fallback={null}> <BlockedOn value="foo"> <div>foo</div> <meta name="late" /> </BlockedOn> </Suspense> </body> </html>, ); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <meta name="early" /> </head> <body /> </html>, ); content = ''; await act(() => { resolveText('foo'); }); expect(content.slice(0, 30)).toEqual('<meta name="late"/><div hidden'); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <meta name="early" /> </head> <body> <div>foo</div> <meta name="late" /> </body> </html>, ); }); // @gate enableFloat it('supports rendering hoistables outside of <html> scope', async () => { await act(() => { const {pipe} = renderToPipeableStream( <> <meta name="before" /> <html> <body>foo</body> </html> <meta name="after" /> </>, ); pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <meta name="before" /> <meta name="after" /> </head> <body>foo</body> </html>, ); const root = ReactDOMClient.hydrateRoot( document, <> <meta name="before" /> <html> <body>foo</body> </html> <meta name="after" /> </>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <meta name="before" /> <meta name="after" /> </head> <body>foo</body> </html>, ); root.render( <> {null} <html> <body>foo</body> </html> {null} </>, ); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body>foo</body> </html>, ); }); it('can hydrate hoistable tags inside late suspense boundaries', async () => { function App() { return ( <html> <body> <link rel="rel1" href="linkhref" /> <link rel="rel2" href="linkhref" /> <meta name="name1" content="metacontent" /> <meta name="name2" content="metacontent" /> <Suspense fallback="loading..."> <link rel="rel3" href="linkhref" /> <link rel="rel4" href="linkhref" /> <meta name="name3" content="metacontent" /> <meta name="name4" content="metacontent" /> <BlockedOn value="release"> <link rel="rel5" href="linkhref" /> <link rel="rel6" href="linkhref" /> <meta name="name5" content="metacontent" /> <meta name="name6" content="metacontent" /> <div>hello world</div> </BlockedOn> </Suspense> </body> </html> ); } await act(() => { renderToPipeableStream(<App />).pipe(writable); }); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="rel1" href="linkhref" /> <link rel="rel2" href="linkhref" /> <meta name="name1" content="metacontent" /> <meta name="name2" content="metacontent" /> <link rel="rel3" href="linkhref" /> <link rel="rel4" href="linkhref" /> <meta name="name3" content="metacontent" /> <meta name="name4" content="metacontent" /> </head> <body>loading...</body> </html>, ); const root = ReactDOMClient.hydrateRoot(document, <App />); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="rel1" href="linkhref" /> <link rel="rel2" href="linkhref" /> <meta name="name1" content="metacontent" /> <meta name="name2" content="metacontent" /> <link rel="rel3" href="linkhref" /> <link rel="rel4" href="linkhref" /> <meta name="name3" content="metacontent" /> <meta name="name4" content="metacontent" /> </head> <body>loading...</body> </html>, ); const thirdPartyLink = document.createElement('link'); thirdPartyLink.setAttribute('href', 'linkhref'); thirdPartyLink.setAttribute('rel', '3rdparty'); document.body.prepend(thirdPartyLink); const thirdPartyMeta = document.createElement('meta'); thirdPartyMeta.setAttribute('content', 'metacontent'); thirdPartyMeta.setAttribute('name', '3rdparty'); document.body.prepend(thirdPartyMeta); await act(() => { resolveText('release'); }); await waitForAll([]); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <link rel="rel1" href="linkhref" /> <link rel="rel2" href="linkhref" /> <meta name="name1" content="metacontent" /> <meta name="name2" content="metacontent" /> <link rel="rel3" href="linkhref" /> <link rel="rel4" href="linkhref" /> <meta name="name3" content="metacontent" /> <meta name="name4" content="metacontent" /> </head> <body> <meta name="3rdparty" content="metacontent" /> <link rel="3rdparty" href="linkhref" /> <div>hello world</div> <link rel="rel5" href="linkhref" /> <link rel="rel6" href="linkhref" /> <meta name="name5" content="metacontent" /> <meta name="name6" content="metacontent" /> </body> </html>, ); root.unmount(); expect(getMeaningfulChildren(document)).toEqual( <html> <head /> <body> <meta name="3rdparty" content="metacontent" /> <link rel="3rdparty" href="linkhref" /> </body> </html>, ); }); // @gate enableFloat it('does not hoist inside an <svg> context', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <body> <svg> <title>svg title</title> <link rel="svg link" href="a" /> <meta name="svg meta" /> <path> <title>deep svg title</title> <meta name="deep svg meta" /> <link rel="deep svg link" href="a" /> </path> <foreignObject> <title>hoistable title</title> <meta name="hoistable" /> <link rel="hoistable" href="a" /> </foreignObject> </svg> </body> </html>, ); pipe(writable); }); expect(getMeaningfulChildren(document.head)).toEqual([ <title>hoistable title</title>, <meta name="hoistable" />, <link rel="hoistable" href="a" />, ]); }); // @gate enableFloat it('does not hoist inside noscript context', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <body> <title>title</title> <link rel="link" href="a" /> <meta name="meta" /> <noscript> <title>noscript title</title> <link rel="noscript link" href="a" /> <meta name="noscript meta" /> </noscript> </body> </html>, ); pipe(writable); }); expect(getMeaningfulChildren(document.head)).toEqual([ <title>title</title>, <link rel="link" href="a" />, <meta name="meta" />, ]); }); // @gate enableFloat && (enableClientRenderFallbackOnTextMismatch || !__DEV__) it('can render a title before a singleton even if that singleton clears its contents', async () => { await act(() => { const {pipe} = renderToPipeableStream( <> <title>foo</title> <html> <head /> <body> <div>server</div> </body> </html> </>, ); pipe(writable); }); const errors = []; ReactDOMClient.hydrateRoot( document, <> <title>foo</title> <html> <head /> <body> <div>client</div> </body> </html> </>, { onRecoverableError(err) { errors.push(err.message); }, }, ); await expect(async () => { await waitForAll([]); }).toErrorDev( [ 'Warning: Text content did not match. Server: "server" Client: "client"', 'Warning: An error occurred during hydration. The server HTML was replaced with client content in <#document>.', ], {withoutStack: 1}, ); expect(getMeaningfulChildren(document)).toEqual( <html> <head> <title>foo</title> </head> <body> <div>client</div> </body> </html>, ); }); // @gate enableFloat it('can update title tags', async () => { const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<title data-foo="foo">a title</title>); }); await waitForAll([]); expect(getMeaningfulChildren(document.head)).toEqual( <title data-foo="foo">a title</title>, ); await act(() => { root.render(<title data-foo="bar">another title</title>); }); await waitForAll([]); expect(getMeaningfulChildren(document.head)).toEqual( <title data-foo="bar">another title</title>, ); }); }); });
31.986618
610
0.514834
GWT-Penetration-Testing-Toolset
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; import {Component, Suspense} from 'react'; import Store from 'react-devtools-shared/src/devtools/store'; import UnsupportedBridgeOperationView from './UnsupportedBridgeOperationView'; import ErrorView from './ErrorView'; import SearchingGitHubIssues from './SearchingGitHubIssues'; import SuspendingErrorView from './SuspendingErrorView'; import TimeoutView from './TimeoutView'; import CaughtErrorView from './CaughtErrorView'; import UnsupportedBridgeOperationError from 'react-devtools-shared/src/UnsupportedBridgeOperationError'; import TimeoutError from 'react-devtools-shared/src/errors/TimeoutError'; import UserError from 'react-devtools-shared/src/errors/UserError'; import UnknownHookError from 'react-devtools-shared/src/errors/UnknownHookError'; import {logEvent} from 'react-devtools-shared/src/Logger'; type Props = { children: React$Node, canDismiss?: boolean, onBeforeDismissCallback?: () => void, store?: Store, }; type State = { callStack: string | null, canDismiss: boolean, componentStack: string | null, errorMessage: string | null, hasError: boolean, isUnsupportedBridgeOperationError: boolean, isTimeout: boolean, isUserError: boolean, isUnknownHookError: boolean, }; const InitialState: State = { callStack: null, canDismiss: false, componentStack: null, errorMessage: null, hasError: false, isUnsupportedBridgeOperationError: false, isTimeout: false, isUserError: false, isUnknownHookError: false, }; export default class ErrorBoundary extends Component<Props, State> { state: State = InitialState; static getDerivedStateFromError(error: any): { callStack: string | null, errorMessage: string | null, hasError: boolean, isTimeout: boolean, isUnknownHookError: boolean, isUnsupportedBridgeOperationError: boolean, isUserError: boolean, } { const errorMessage = typeof error === 'object' && error !== null && typeof error.message === 'string' ? error.message : null; const isTimeout = error instanceof TimeoutError; const isUserError = error instanceof UserError; const isUnknownHookError = error instanceof UnknownHookError; const isUnsupportedBridgeOperationError = error instanceof UnsupportedBridgeOperationError; const callStack = typeof error === 'object' && error !== null && typeof error.stack === 'string' ? error.stack.split('\n').slice(1).join('\n') : null; return { callStack, errorMessage, hasError: true, isUnsupportedBridgeOperationError, isUnknownHookError, isTimeout, isUserError, }; } componentDidCatch(error: any, {componentStack}: any) { this._logError(error, componentStack); this.setState({ componentStack, }); } componentDidMount() { const {store} = this.props; if (store != null) { store.addListener('error', this._onStoreError); } } componentWillUnmount() { const {store} = this.props; if (store != null) { store.removeListener('error', this._onStoreError); } } render(): React.Node { const {canDismiss: canDismissProp, children} = this.props; const { callStack, canDismiss: canDismissState, componentStack, errorMessage, hasError, isUnsupportedBridgeOperationError, isTimeout, isUserError, isUnknownHookError, } = this.state; if (hasError) { if (isTimeout) { return ( <TimeoutView callStack={callStack} componentStack={componentStack} dismissError={ canDismissProp || canDismissState ? this._dismissError : null } errorMessage={errorMessage} /> ); } else if (isUnsupportedBridgeOperationError) { return ( <UnsupportedBridgeOperationView callStack={callStack} componentStack={componentStack} errorMessage={errorMessage} /> ); } else if (isUserError) { return ( <CaughtErrorView callStack={callStack} componentStack={componentStack} errorMessage={errorMessage || 'Error occured in inspected element'} info={ <> React DevTools encountered an error while trying to inspect the hooks. This is most likely caused by a developer error in the currently inspected element. Please see your console for logged error. </> } /> ); } else if (isUnknownHookError) { return ( <CaughtErrorView callStack={callStack} componentStack={componentStack} errorMessage={errorMessage || 'Encountered an unknown hook'} info={ <> React DevTools encountered an unknown hook. This is probably because the react-debug-tools package is out of date. To fix, upgrade the React DevTools to the most recent version. </> } /> ); } else { return ( <ErrorView callStack={callStack} componentStack={componentStack} dismissError={ canDismissProp || canDismissState ? this._dismissError : null } errorMessage={errorMessage}> <Suspense fallback={<SearchingGitHubIssues />}> <SuspendingErrorView callStack={callStack} componentStack={componentStack} errorMessage={errorMessage} /> </Suspense> </ErrorView> ); } } return children; } _logError: (error: any, componentStack: string | null) => void = ( error, componentStack, ) => { logEvent({ event_name: 'error', error_message: error.message ?? null, error_stack: error.stack ?? null, error_component_stack: componentStack ?? null, }); }; _dismissError: () => void = () => { const onBeforeDismissCallback = this.props.onBeforeDismissCallback; if (typeof onBeforeDismissCallback === 'function') { onBeforeDismissCallback(); } this.setState(InitialState); }; _onStoreError: (error: Error) => void = error => { if (!this.state.hasError) { this._logError(error, null); this.setState({ ...ErrorBoundary.getDerivedStateFromError(error), canDismiss: true, }); } }; }
27.541667
104
0.622865
owtf
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ // These tests are based on ReactJSXElement-test, // ReactJSXElementValidator-test, ReactComponent-test, // and ReactElementJSX-test. jest.mock('react/jsx-runtime', () => require('./jsx-runtime'), {virtual: true}); jest.mock('react/jsx-dev-runtime', () => require('./jsx-dev-runtime'), { virtual: true, }); let React = require('react'); let ReactDOM = require('react-dom'); let ReactTestUtils = { renderIntoDocument(el) { const container = document.createElement('div'); return ReactDOM.render(el, container); }, }; let PropTypes = require('prop-types'); let Component = class Component extends React.Component { render() { return <div />; } }; let RequiredPropComponent = class extends React.Component { render() { return <span>{this.props.prop}</span>; } }; RequiredPropComponent.displayName = 'RequiredPropComponent'; RequiredPropComponent.propTypes = {prop: PropTypes.string.isRequired}; it('works', () => { const container = document.createElement('div'); ReactDOM.render(<h1>hello</h1>, container); expect(container.textContent).toBe('hello'); }); it('returns a complete element according to spec', () => { const element = <Component />; expect(element.type).toBe(Component); expect(element.key).toBe(null); expect(element.ref).toBe(null); const expectation = {}; Object.freeze(expectation); expect(element.props).toEqual(expectation); }); it('allows a lower-case to be passed as the string type', () => { const element = <div />; expect(element.type).toBe('div'); expect(element.key).toBe(null); expect(element.ref).toBe(null); const expectation = {}; Object.freeze(expectation); expect(element.props).toEqual(expectation); }); it('allows a string to be passed as the type', () => { const TagName = 'div'; const element = <TagName />; expect(element.type).toBe('div'); expect(element.key).toBe(null); expect(element.ref).toBe(null); const expectation = {}; Object.freeze(expectation); expect(element.props).toEqual(expectation); }); it('returns an immutable element', () => { const element = <Component />; if (process.env.NODE_ENV === 'development') { expect(() => (element.type = 'div')).toThrow(); } else { expect(() => (element.type = 'div')).not.toThrow(); } }); it('does not reuse the object that is spread into props', () => { const config = {foo: 1}; const element = <Component {...config} />; expect(element.props.foo).toBe(1); config.foo = 2; expect(element.props.foo).toBe(1); }); it('extracts key and ref from the rest of the props', () => { const element = <Component key="12" ref="34" foo="56" />; expect(element.type).toBe(Component); expect(element.key).toBe('12'); expect(element.ref).toBe('34'); const expectation = {foo: '56'}; Object.freeze(expectation); expect(element.props).toEqual(expectation); }); it('coerces the key to a string', () => { const element = <Component key={12} foo="56" />; expect(element.type).toBe(Component); expect(element.key).toBe('12'); expect(element.ref).toBe(null); const expectation = {foo: '56'}; Object.freeze(expectation); expect(element.props).toEqual(expectation); }); it('merges JSX children onto the children prop', () => { const a = 1; const element = <Component children="text">{a}</Component>; expect(element.props.children).toBe(a); }); it('does not override children if no JSX children are provided', () => { const element = <Component children="text" />; expect(element.props.children).toBe('text'); }); it('overrides children if null is provided as a JSX child', () => { const element = <Component children="text">{null}</Component>; expect(element.props.children).toBe(null); }); it('overrides children if undefined is provided as an argument', () => { const element = <Component children="text">{undefined}</Component>; expect(element.props.children).toBe(undefined); const element2 = React.cloneElement( <Component children="text" />, {}, undefined ); expect(element2.props.children).toBe(undefined); }); it('merges JSX children onto the children prop in an array', () => { const a = 1; const b = 2; const c = 3; const element = ( <Component> {a} {b} {c} </Component> ); expect(element.props.children).toEqual([1, 2, 3]); }); it('allows static methods to be called using the type property', () => { class StaticMethodComponent { static someStaticMethod() { return 'someReturnValue'; } render() { return <div />; } } const element = <StaticMethodComponent />; expect(element.type.someStaticMethod()).toBe('someReturnValue'); }); it('identifies valid elements', () => { expect(React.isValidElement(<div />)).toEqual(true); expect(React.isValidElement(<Component />)).toEqual(true); expect(React.isValidElement(null)).toEqual(false); expect(React.isValidElement(true)).toEqual(false); expect(React.isValidElement({})).toEqual(false); expect(React.isValidElement('string')).toEqual(false); expect(React.isValidElement(Component)).toEqual(false); expect(React.isValidElement({type: 'div', props: {}})).toEqual(false); }); it('is indistinguishable from a plain object', () => { const element = <div className="foo" />; const object = {}; expect(element.constructor).toBe(object.constructor); }); it('should use default prop value when removing a prop', () => { Component.defaultProps = {fruit: 'persimmon'}; const container = document.createElement('div'); const instance = ReactDOM.render(<Component fruit="mango" />, container); expect(instance.props.fruit).toBe('mango'); ReactDOM.render(<Component />, container); expect(instance.props.fruit).toBe('persimmon'); }); it('should normalize props with default values', () => { class NormalizingComponent extends React.Component { render() { return <span>{this.props.prop}</span>; } } NormalizingComponent.defaultProps = {prop: 'testKey'}; const container = document.createElement('div'); const instance = ReactDOM.render(<NormalizingComponent />, container); expect(instance.props.prop).toBe('testKey'); const inst2 = ReactDOM.render( <NormalizingComponent prop={null} />, container ); expect(inst2.props.prop).toBe(null); }); it('warns for keys for arrays of elements in children position', () => { expect(() => ReactTestUtils.renderIntoDocument( <Component>{[<Component />, <Component />]}</Component> ) ).toErrorDev('Each child in a list should have a unique "key" prop.'); }); it('warns for keys for arrays of elements with owner info', () => { class InnerComponent extends React.Component { render() { return <Component>{this.props.childSet}</Component>; } } class ComponentWrapper extends React.Component { render() { return <InnerComponent childSet={[<Component />, <Component />]} />; } } expect(() => ReactTestUtils.renderIntoDocument(<ComponentWrapper />) ).toErrorDev( 'Each child in a list should have a unique "key" prop.' + '\n\nCheck the render method of `InnerComponent`. ' + 'It was passed a child from ComponentWrapper. ' ); }); it('does not warn for arrays of elements with keys', () => { ReactTestUtils.renderIntoDocument( <Component>{[<Component key="#1" />, <Component key="#2" />]}</Component> ); }); it('does not warn for iterable elements with keys', () => { const iterable = { '@@iterator': function () { let i = 0; return { next: function () { const done = ++i > 2; return { value: done ? undefined : <Component key={'#' + i} />, done: done, }; }, }; }, }; ReactTestUtils.renderIntoDocument(<Component>{iterable}</Component>); }); it('does not warn for numeric keys in entry iterable as a child', () => { const iterable = { '@@iterator': function () { let i = 0; return { next: function () { const done = ++i > 2; return {value: done ? undefined : [i, <Component />], done: done}; }, }; }, }; iterable.entries = iterable['@@iterator']; ReactTestUtils.renderIntoDocument(<Component>{iterable}</Component>); }); it('does not warn when the element is directly as children', () => { ReactTestUtils.renderIntoDocument( <Component> <Component /> <Component /> </Component> ); }); it('does not warn when the child array contains non-elements', () => { void (<Component>{[{}, {}]}</Component>); }); it('should give context for PropType errors in nested components.', () => { // In this test, we're making sure that if a proptype error is found in a // component, we give a small hint as to which parent instantiated that // component as per warnings about key usage in ReactElementValidator. function MyComp({color}) { return <div>My color is {color}</div>; } MyComp.propTypes = { color: PropTypes.string, }; class ParentComp extends React.Component { render() { return <MyComp color={123} />; } } expect(() => ReactTestUtils.renderIntoDocument(<ParentComp />)).toErrorDev( 'Warning: Failed prop type: ' + 'Invalid prop `color` of type `number` supplied to `MyComp`, ' + 'expected `string`.\n' + ' in MyComp (at **)\n' + ' in ParentComp (at **)' ); }); it('gives a helpful error when passing null, undefined, or boolean', () => { const Undefined = undefined; const Null = null; const True = true; const Div = 'div'; expect(() => void (<Undefined />)).toErrorDev( 'Warning: React.jsx: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: undefined. You likely forgot to export your ' + "component from the file it's defined in, or you might have mixed up " + 'default and named imports.' + (process.env.BABEL_ENV === 'development' ? '\n\nCheck your code at **.' : ''), {withoutStack: true} ); expect(() => void (<Null />)).toErrorDev( 'Warning: React.jsx: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: null.' + (process.env.BABEL_ENV === 'development' ? '\n\nCheck your code at **.' : ''), {withoutStack: true} ); expect(() => void (<True />)).toErrorDev( 'Warning: React.jsx: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: boolean.' + (process.env.BABEL_ENV === 'development' ? '\n\nCheck your code at **.' : ''), {withoutStack: true} ); // No error expected void (<Div />); }); it('should check default prop values', () => { RequiredPropComponent.defaultProps = {prop: null}; expect(() => ReactTestUtils.renderIntoDocument(<RequiredPropComponent />) ).toErrorDev( 'Warning: Failed prop type: The prop `prop` is marked as required in ' + '`RequiredPropComponent`, but its value is `null`.\n' + ' in RequiredPropComponent (at **)' ); }); it('should warn on invalid prop types', () => { // Since there is no prevalidation step for ES6 classes, there is no hook // for us to issue a warning earlier than element creation when the error // actually occurs. Since this step is skipped in production, we should just // warn instead of throwing for this case. class NullPropTypeComponent extends React.Component { render() { return <span>{this.props.prop}</span>; } } NullPropTypeComponent.propTypes = { prop: null, }; expect(() => ReactTestUtils.renderIntoDocument(<NullPropTypeComponent />) ).toErrorDev( 'NullPropTypeComponent: prop type `prop` is invalid; it must be a ' + 'function, usually from the `prop-types` package,' ); }); it('should warn on invalid context types', () => { class NullContextTypeComponent extends React.Component { render() { return <span>{this.props.prop}</span>; } } NullContextTypeComponent.contextTypes = { prop: null, }; expect(() => ReactTestUtils.renderIntoDocument(<NullContextTypeComponent />) ).toErrorDev( 'NullContextTypeComponent: context type `prop` is invalid; it must ' + 'be a function, usually from the `prop-types` package,' ); }); it('should warn if getDefaultProps is specified on the class', () => { class GetDefaultPropsComponent extends React.Component { render() { return <span>{this.props.prop}</span>; } } GetDefaultPropsComponent.getDefaultProps = () => ({ prop: 'foo', }); expect(() => ReactTestUtils.renderIntoDocument(<GetDefaultPropsComponent />) ).toErrorDev( 'getDefaultProps is only used on classic React.createClass definitions.' + ' Use a static property named `defaultProps` instead.', {withoutStack: true} ); }); it('should warn if component declares PropTypes instead of propTypes', () => { class MisspelledPropTypesComponent extends React.Component { render() { return <span>{this.props.prop}</span>; } } MisspelledPropTypesComponent.PropTypes = { prop: PropTypes.string, }; expect(() => ReactTestUtils.renderIntoDocument( <MisspelledPropTypesComponent prop="hi" /> ) ).toErrorDev( 'Warning: Component MisspelledPropTypesComponent declared `PropTypes` ' + 'instead of `propTypes`. Did you misspell the property assignment?', {withoutStack: true} ); }); it('warns for fragments with illegal attributes', () => { class Foo extends React.Component { render() { return <React.Fragment a={1}>hello</React.Fragment>; } } expect(() => ReactTestUtils.renderIntoDocument(<Foo />)).toErrorDev( 'Invalid prop `a` supplied to `React.Fragment`. React.Fragment ' + 'can only have `key` and `children` props.' ); }); it('warns for fragments with refs', () => { class Foo extends React.Component { render() { return ( <React.Fragment ref={bar => { this.foo = bar; }}> hello </React.Fragment> ); } } expect(() => ReactTestUtils.renderIntoDocument(<Foo />)).toErrorDev( 'Invalid attribute `ref` supplied to `React.Fragment`.' ); }); it('does not warn for fragments of multiple elements without keys', () => { ReactTestUtils.renderIntoDocument( <> <span>1</span> <span>2</span> </> ); }); it('warns for fragments of multiple elements with same key', () => { expect(() => ReactTestUtils.renderIntoDocument( <> <span key="a">1</span> <span key="a">2</span> <span key="b">3</span> </> ) ).toErrorDev('Encountered two children with the same key, `a`.', { withoutStack: true, }); }); it('does not call lazy initializers eagerly', () => { let didCall = false; const Lazy = React.lazy(() => { didCall = true; return {then() {}}; }); <Lazy />; expect(didCall).toBe(false); }); it('supports classic refs', () => { class Foo extends React.Component { render() { return <div className="foo" ref="inner" />; } } const container = document.createElement('div'); const instance = ReactDOM.render(<Foo />, container); expect(instance.refs.inner.className).toBe('foo'); }); it('should support refs on owned components', () => { const innerObj = {}; const outerObj = {}; class Wrapper extends React.Component { getObject = () => { return this.props.object; }; render() { return <div>{this.props.children}</div>; } } class Component extends React.Component { render() { const inner = <Wrapper object={innerObj} ref="inner" />; const outer = ( <Wrapper object={outerObj} ref="outer"> {inner} </Wrapper> ); return outer; } componentDidMount() { expect(this.refs.inner.getObject()).toEqual(innerObj); expect(this.refs.outer.getObject()).toEqual(outerObj); } } ReactTestUtils.renderIntoDocument(<Component />); }); it('should support callback-style refs', () => { const innerObj = {}; const outerObj = {}; class Wrapper extends React.Component { getObject = () => { return this.props.object; }; render() { return <div>{this.props.children}</div>; } } let mounted = false; class Component extends React.Component { render() { const inner = ( <Wrapper object={innerObj} ref={c => (this.innerRef = c)} /> ); const outer = ( <Wrapper object={outerObj} ref={c => (this.outerRef = c)}> {inner} </Wrapper> ); return outer; } componentDidMount() { expect(this.innerRef.getObject()).toEqual(innerObj); expect(this.outerRef.getObject()).toEqual(outerObj); mounted = true; } } ReactTestUtils.renderIntoDocument(<Component />); expect(mounted).toBe(true); }); it('should support object-style refs', () => { const innerObj = {}; const outerObj = {}; class Wrapper extends React.Component { getObject = () => { return this.props.object; }; render() { return <div>{this.props.children}</div>; } } let mounted = false; class Component extends React.Component { constructor() { super(); this.innerRef = React.createRef(); this.outerRef = React.createRef(); } render() { const inner = <Wrapper object={innerObj} ref={this.innerRef} />; const outer = ( <Wrapper object={outerObj} ref={this.outerRef}> {inner} </Wrapper> ); return outer; } componentDidMount() { expect(this.innerRef.current.getObject()).toEqual(innerObj); expect(this.outerRef.current.getObject()).toEqual(outerObj); mounted = true; } } ReactTestUtils.renderIntoDocument(<Component />); expect(mounted).toBe(true); }); it('should support new-style refs with mixed-up owners', () => { class Wrapper extends React.Component { getTitle = () => { return this.props.title; }; render() { return this.props.getContent(); } } let mounted = false; class Component extends React.Component { getInner = () => { // (With old-style refs, it's impossible to get a ref to this div // because Wrapper is the current owner when this function is called.) return <div className="inner" ref={c => (this.innerRef = c)} />; }; render() { return ( <Wrapper title="wrapper" ref={c => (this.wrapperRef = c)} getContent={this.getInner} /> ); } componentDidMount() { // Check .props.title to make sure we got the right elements back expect(this.wrapperRef.getTitle()).toBe('wrapper'); expect(this.innerRef.className).toBe('inner'); mounted = true; } } ReactTestUtils.renderIntoDocument(<Component />); expect(mounted).toBe(true); }); it('should warn when `key` is being accessed on composite element', () => { const container = document.createElement('div'); class Child extends React.Component { render() { return <div> {this.props.key} </div>; } } class Parent extends React.Component { render() { return ( <div> <Child key="0" /> <Child key="1" /> <Child key="2" /> </div> ); } } expect(() => ReactDOM.render(<Parent />, container)).toErrorDev( 'Child: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)' ); }); it('should warn when `ref` is being accessed', () => { const container = document.createElement('div'); class Child extends React.Component { render() { return <div> {this.props.ref} </div>; } } class Parent extends React.Component { render() { return ( <div> <Child ref="childElement" /> </div> ); } } expect(() => ReactDOM.render(<Parent />, container)).toErrorDev( 'Child: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)' ); }); it('should warn when owner and self are different for string refs', () => { class ClassWithRenderProp extends React.Component { render() { return this.props.children(); } } class ClassParent extends React.Component { render() { return ( <ClassWithRenderProp>{() => <div ref="myRef" />}</ClassWithRenderProp> ); } } const container = document.createElement('div'); if (process.env.BABEL_ENV === 'development') { expect(() => ReactDOM.render(<ClassParent />, container)).toErrorDev([ 'Warning: Component "ClassWithRenderProp" contains the string ref "myRef". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', ]); } else { ReactDOM.render(<ClassParent />, container); } });
27.583333
91
0.625894
Python-for-Offensive-PenTest
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type { ElementType, SerializedElement, } from 'react-devtools-shared/src/frontend/types'; import type { TimelineData, TimelineDataExport, } from 'react-devtools-timeline/src/types'; export type CommitTreeNode = { id: number, children: Array<number>, displayName: string | null, hocDisplayNames: Array<string> | null, key: number | string | null, parentID: number, treeBaseDuration: number, type: ElementType, }; export type CommitTree = { nodes: Map<number, CommitTreeNode>, rootID: number, }; export type SnapshotNode = { id: number, children: Array<number>, displayName: string | null, hocDisplayNames: Array<string> | null, key: number | string | null, type: ElementType, }; export type ChangeDescription = { context: Array<string> | boolean | null, didHooksChange: boolean, isFirstMount: boolean, props: Array<string> | null, state: Array<string> | null, hooks?: Array<number> | null, }; export type CommitDataFrontend = { // Map of Fiber (ID) to a description of what changed in this commit. changeDescriptions: Map<number, ChangeDescription> | null, // How long was the render phase? duration: number, // How long was the layout commit phase? // Note that not all builds of React expose this property. effectDuration: number | null, // Map of Fiber (ID) to actual duration for this commit; // Fibers that did not render will not have entries in this Map. fiberActualDurations: Map<number, number>, // Map of Fiber (ID) to "self duration" for this commit; // Fibers that did not render will not have entries in this Map. fiberSelfDurations: Map<number, number>, // How long was the passive commit phase? // Note that not all builds of React expose this property. passiveEffectDuration: number | null, // Priority level of the commit (if React provided this info) priorityLevel: string | null, // When did this commit occur (relative to the start of profiling) timestamp: number, // Fiber(s) responsible for scheduling this update. updaters: Array<SerializedElement> | null, }; export type ProfilingDataForRootFrontend = { // Timing, duration, and other metadata about each commit. commitData: Array<CommitDataFrontend>, // Display name of the nearest descendant component (ideally a function or class component). // This value is used by the root selector UI. displayName: string, // Map of fiber id to (initial) tree base duration when Profiling session was started. // This info can be used along with commitOperations to reconstruct the tree for any commit. initialTreeBaseDurations: Map<number, number>, // List of tree mutation that occur during profiling. // These mutations can be used along with initial snapshots to reconstruct the tree for any commit. operations: Array<Array<number>>, // Identifies the root this profiler data corresponds to. rootID: number, // Map of fiber id to node when the Profiling session was started. // This info can be used along with commitOperations to reconstruct the tree for any commit. snapshots: Map<number, SnapshotNode>, }; // Combination of profiling data collected by the renderer interface (backend) and Store (frontend). export type ProfilingDataFrontend = { // Legacy profiling data is per renderer + root. dataForRoots: Map<number, ProfilingDataForRootFrontend>, // Timeline data is per rederer. timelineData: Array<TimelineData>, // Some functionality should be disabled for imported data. // e.g. DevTools should not try to sync selection between Components and Profiler tabs, // even if there are Fibers with the same IDs. imported: boolean, }; export type CommitDataExport = { changeDescriptions: Array<[number, ChangeDescription]> | null, duration: number, effectDuration: number | null, // Tuple of fiber ID and actual duration fiberActualDurations: Array<[number, number]>, // Tuple of fiber ID and computed "self" duration fiberSelfDurations: Array<[number, number]>, passiveEffectDuration: number | null, priorityLevel: string | null, timestamp: number, updaters: Array<SerializedElement> | null, }; export type ProfilingDataForRootExport = { commitData: Array<CommitDataExport>, displayName: string, // Tuple of Fiber ID and base duration initialTreeBaseDurations: Array<[number, number]>, operations: Array<Array<number>>, rootID: number, snapshots: Array<[number, SnapshotNode]>, }; // Serializable version of ProfilingDataFrontend data. export type ProfilingDataExport = { version: 5, // Legacy profiling data is per renderer + root. dataForRoots: Array<ProfilingDataForRootExport>, // Timeline data is per rederer. // Note that old exported profiles won't contain this key. timelineData?: Array<TimelineDataExport>, };
30.584906
101
0.733519
PenetrationTestingScripts
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ const {resolve} = require('path'); function resolveFeatureFlags(target) { let flagsPath; switch (target) { case 'inline': case 'shell': flagsPath = 'DevToolsFeatureFlags.default'; break; case 'core/backend-oss': case 'core/standalone-oss': flagsPath = 'DevToolsFeatureFlags.core-oss'; break; case 'core/backend-fb': case 'core/standalone-fb': flagsPath = 'DevToolsFeatureFlags.core-fb'; break; case 'extension-oss': flagsPath = 'DevToolsFeatureFlags.extension-oss'; break; case 'extension-fb': flagsPath = 'DevToolsFeatureFlags.extension-fb'; break; default: console.error(`Invalid target "${target}"`); process.exit(1); } return resolve(__dirname, 'src/config/', flagsPath); } module.exports = { resolveFeatureFlags, };
23.139535
66
0.650916
Hands-On-Penetration-Testing-with-Python
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export function Component() { const [count] = require('react').useState(0); return count; }
19.133333
66
0.681063
cybersecurity-penetration-testing
import * as React from 'react'; import {createRoot} from 'react-dom/client'; import { activate as activateBackend, initialize as initializeBackend, } from 'react-devtools-inline/backend'; import {initialize as createDevTools} from 'react-devtools-inline/frontend'; // This is a pretty gross hack to make the runtime loaded named-hooks-code work. // TODO (Webpack 5) Hoepfully we can remove this once we upgrade to Webpack 5. __webpack_public_path__ = '/dist/'; // eslint-disable-line no-undef // TODO (Webpack 5) Hopefully we can remove this prop after the Webpack 5 migration. function hookNamesModuleLoaderFunction() { return import('react-devtools-inline/hookNames'); } function inject(contentDocument, sourcePath) { const script = contentDocument.createElement('script'); script.src = sourcePath; ((contentDocument.body: any): HTMLBodyElement).appendChild(script); } function init( appSource: string, appIframe: HTMLIFrameElement, devtoolsContainer: HTMLElement, loadDevToolsButton: HTMLButtonElement, ) { const {contentDocument, contentWindow} = appIframe; initializeBackend(contentWindow); inject(contentDocument, appSource); loadDevToolsButton.addEventListener('click', () => { const DevTools = createDevTools(contentWindow); createRoot(devtoolsContainer).render( <DevTools hookNamesModuleLoaderFunction={hookNamesModuleLoaderFunction} showTabBar={true} />, ); activateBackend(contentWindow); }); } init( 'dist/perf-regression-app.js', document.getElementById('iframe'), document.getElementById('devtools'), document.getElementById('load-devtools'), );
29.036364
84
0.745609
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from './ReactDOMFizzServerBrowser.js'; export {prerender} from './ReactDOMFizzStaticBrowser.js';
24.916667
66
0.719355
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = require("react"); /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ const A = /*#__PURE__*/(0, _react.createContext)(1); const B = /*#__PURE__*/(0, _react.createContext)(2); function Component() { const a = (0, _react.useContext)(A); const b = (0, _react.useContext)(B); // prettier-ignore const c = (0, _react.useContext)(A), d = (0, _react.useContext)(B); // eslint-disable-line one-var return a + b + c + d; } //# sourceMappingURL=ComponentWithMultipleHooksPerLine.js.map?foo=bar&param=some_value
25.433333
86
0.655303
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type { ReactContext, StartTransitionOptions, Usable, Thenable, RejectedThenable, Awaited, } from 'shared/ReactTypes'; import type { Fiber, FiberRoot, Dispatcher, HookType, MemoCache, } from './ReactInternalTypes'; import type {Lanes, Lane} from './ReactFiberLane'; import type {HookFlags} from './ReactHookEffectTags'; import type {Flags} from './ReactFiberFlags'; import type {TransitionStatus} from './ReactFiberConfig'; import {NotPendingTransition as NoPendingHostTransition} from './ReactFiberConfig'; import ReactSharedInternals from 'shared/ReactSharedInternals'; import { enableDebugTracing, enableSchedulingProfiler, enableCache, enableUseRefAccessWarning, enableLazyContextPropagation, enableTransitionTracing, enableUseMemoCacheHook, enableUseEffectEventHook, enableLegacyCache, debugRenderPhaseSideEffectsForStrictMode, enableAsyncActions, enableFormActions, enableUseDeferredValueInitialArg, } from 'shared/ReactFeatureFlags'; import { REACT_CONTEXT_TYPE, REACT_SERVER_CONTEXT_TYPE, REACT_MEMO_CACHE_SENTINEL, } from 'shared/ReactSymbols'; import { NoMode, ConcurrentMode, DebugTracingMode, StrictEffectsMode, StrictLegacyMode, NoStrictPassiveEffectsMode, } from './ReactTypeOfMode'; import { NoLane, SyncLane, OffscreenLane, DeferredLane, NoLanes, isSubsetOfLanes, includesBlockingLane, includesOnlyNonUrgentLanes, mergeLanes, removeLanes, intersectLanes, isTransitionLane, markRootEntangled, includesSomeLane, } from './ReactFiberLane'; import { ContinuousEventPriority, getCurrentUpdatePriority, setCurrentUpdatePriority, higherEventPriority, } from './ReactEventPriorities'; import {readContext, checkIfContextChanged} from './ReactFiberNewContext'; import {HostRoot, CacheComponent, HostComponent} from './ReactWorkTags'; import { LayoutStatic as LayoutStaticEffect, Passive as PassiveEffect, PassiveStatic as PassiveStaticEffect, StaticMask as StaticMaskEffect, Update as UpdateEffect, StoreConsistency, MountLayoutDev as MountLayoutDevEffect, MountPassiveDev as MountPassiveDevEffect, } from './ReactFiberFlags'; import { HasEffect as HookHasEffect, Layout as HookLayout, Passive as HookPassive, Insertion as HookInsertion, } from './ReactHookEffectTags'; import { getWorkInProgressRoot, getWorkInProgressRootRenderLanes, scheduleUpdateOnFiber, requestUpdateLane, requestDeferredLane, markSkippedUpdateLanes, isInvalidExecutionContextForEventFunction, } from './ReactFiberWorkLoop'; import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber'; import is from 'shared/objectIs'; import isArray from 'shared/isArray'; import { markWorkInProgressReceivedUpdate, checkIfWorkInProgressReceivedUpdate, } from './ReactFiberBeginWork'; import { getIsHydrating, tryToClaimNextHydratableFormMarkerInstance, } from './ReactFiberHydrationContext'; import {logStateUpdateScheduled} from './DebugTracing'; import { markStateUpdateScheduled, setIsStrictModeForDevtools, } from './ReactFiberDevToolsHook'; import {createCache} from './ReactFiberCacheComponent'; import { createUpdate as createLegacyQueueUpdate, enqueueUpdate as enqueueLegacyQueueUpdate, entangleTransitions as entangleLegacyQueueTransitions, } from './ReactFiberClassUpdateQueue'; import { enqueueConcurrentHookUpdate, enqueueConcurrentHookUpdateAndEagerlyBailout, enqueueConcurrentRenderForLane, } from './ReactFiberConcurrentUpdates'; import {getTreeId} from './ReactFiberTreeContext'; import {now} from './Scheduler'; import { trackUsedThenable, checkIfUseWrappedInTryCatch, createThenableState, } from './ReactFiberThenable'; import type {ThenableState} from './ReactFiberThenable'; import type {BatchConfigTransition} from './ReactFiberTracingMarkerComponent'; import { requestAsyncActionContext, requestSyncActionContext, peekEntangledActionLane, } from './ReactFiberAsyncAction'; import {HostTransitionContext} from './ReactFiberHostContext'; import {requestTransitionLane} from './ReactFiberRootScheduler'; import {isCurrentTreeHidden} from './ReactFiberHiddenContext'; const {ReactCurrentDispatcher, ReactCurrentBatchConfig} = ReactSharedInternals; export type Update<S, A> = { lane: Lane, revertLane: Lane, action: A, hasEagerState: boolean, eagerState: S | null, next: Update<S, A>, }; export type UpdateQueue<S, A> = { pending: Update<S, A> | null, lanes: Lanes, dispatch: (A => mixed) | null, lastRenderedReducer: ((S, A) => S) | null, lastRenderedState: S | null, }; let didWarnAboutMismatchedHooksForComponent; let didWarnUncachedGetSnapshot: void | true; let didWarnAboutUseWrappedInTryCatch; let didWarnAboutAsyncClientComponent; if (__DEV__) { didWarnAboutMismatchedHooksForComponent = new Set<string | null>(); didWarnAboutUseWrappedInTryCatch = new Set<string | null>(); didWarnAboutAsyncClientComponent = new Set<string | null>(); } export type Hook = { memoizedState: any, baseState: any, baseQueue: Update<any, any> | null, queue: any, next: Hook | null, }; // The effect "instance" is a shared object that remains the same for the entire // lifetime of an effect. In Rust terms, a RefCell. We use it to store the // "destroy" function that is returned from an effect, because that is stateful. // The field is `undefined` if the effect is unmounted, or if the effect ran // but is not stateful. We don't explicitly track whether the effect is mounted // or unmounted because that can be inferred by the hiddenness of the fiber in // the tree, i.e. whether there is a hidden Offscreen fiber above it. // // It's unfortunate that this is stored on a separate object, because it adds // more memory per effect instance, but it's conceptually sound. I think there's // likely a better data structure we could use for effects; perhaps just one // array of effect instances per fiber. But I think this is OK for now despite // the additional memory and we can follow up with performance // optimizations later. type EffectInstance = { destroy: void | (() => void), }; export type Effect = { tag: HookFlags, create: () => (() => void) | void, inst: EffectInstance, deps: Array<mixed> | null, next: Effect, }; type StoreInstance<T> = { value: T, getSnapshot: () => T, }; type StoreConsistencyCheck<T> = { value: T, getSnapshot: () => T, }; type EventFunctionPayload<Args, Return, F: (...Array<Args>) => Return> = { ref: { eventFn: F, impl: F, }, nextImpl: F, }; export type FunctionComponentUpdateQueue = { lastEffect: Effect | null, events: Array<EventFunctionPayload<any, any, any>> | null, stores: Array<StoreConsistencyCheck<any>> | null, // NOTE: optional, only set when enableUseMemoCacheHook is enabled memoCache?: MemoCache | null, }; type BasicStateAction<S> = (S => S) | S; type Dispatch<A> = A => void; // These are set right before calling the component. let renderLanes: Lanes = NoLanes; // The work-in-progress fiber. I've named it differently to distinguish it from // the work-in-progress hook. let currentlyRenderingFiber: Fiber = (null: any); // Hooks are stored as a linked list on the fiber's memoizedState field. The // current hook list is the list that belongs to the current fiber. The // work-in-progress hook list is a new list that will be added to the // work-in-progress fiber. let currentHook: Hook | null = null; let workInProgressHook: Hook | null = null; // Whether an update was scheduled at any point during the render phase. This // does not get reset if we do another render pass; only when we're completely // finished evaluating this component. This is an optimization so we know // whether we need to clear render phase updates after a throw. let didScheduleRenderPhaseUpdate: boolean = false; // Where an update was scheduled only during the current render pass. This // gets reset after each attempt. // TODO: Maybe there's some way to consolidate this with // `didScheduleRenderPhaseUpdate`. Or with `numberOfReRenders`. let didScheduleRenderPhaseUpdateDuringThisPass: boolean = false; let shouldDoubleInvokeUserFnsInHooksDEV: boolean = false; // Counts the number of useId hooks in this component. let localIdCounter: number = 0; // Counts number of `use`-d thenables let thenableIndexCounter: number = 0; let thenableState: ThenableState | null = null; // Used for ids that are generated completely client-side (i.e. not during // hydration). This counter is global, so client ids are not stable across // render attempts. let globalClientIdCounter: number = 0; const RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook let currentHookNameInDev: ?HookType = null; // In DEV, this list ensures that hooks are called in the same order between renders. // The list stores the order of hooks used during the initial render (mount). // Subsequent renders (updates) reference this list. let hookTypesDev: Array<HookType> | null = null; let hookTypesUpdateIndexDev: number = -1; // In DEV, this tracks whether currently rendering component needs to ignore // the dependencies for Hooks that need them (e.g. useEffect or useMemo). // When true, such Hooks will always be "remounted". Only used during hot reload. let ignorePreviousDependencies: boolean = false; function mountHookTypesDev(): void { if (__DEV__) { const hookName = ((currentHookNameInDev: any): HookType); if (hookTypesDev === null) { hookTypesDev = [hookName]; } else { hookTypesDev.push(hookName); } } } function updateHookTypesDev(): void { if (__DEV__) { const hookName = ((currentHookNameInDev: any): HookType); if (hookTypesDev !== null) { hookTypesUpdateIndexDev++; if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) { warnOnHookMismatchInDev(hookName); } } } } function checkDepsAreArrayDev(deps: mixed): void { if (__DEV__) { if (deps !== undefined && deps !== null && !isArray(deps)) { // Verify deps, but only on mount to avoid extra checks. // It's unlikely their type would change as usually you define them inline. console.error( '%s received a final argument that is not an array (instead, received `%s`). When ' + 'specified, the final argument must be an array.', currentHookNameInDev, typeof deps, ); } } } function warnOnHookMismatchInDev(currentHookName: HookType): void { if (__DEV__) { const componentName = getComponentNameFromFiber(currentlyRenderingFiber); if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) { didWarnAboutMismatchedHooksForComponent.add(componentName); if (hookTypesDev !== null) { let table = ''; const secondColumnStart = 30; for (let i = 0; i <= ((hookTypesUpdateIndexDev: any): number); i++) { const oldHookName = hookTypesDev[i]; const newHookName = i === ((hookTypesUpdateIndexDev: any): number) ? currentHookName : oldHookName; let row = `${i + 1}. ${oldHookName}`; // Extra space so second column lines up // lol @ IE not supporting String#repeat while (row.length < secondColumnStart) { row += ' '; } row += newHookName + '\n'; table += row; } console.error( 'React has detected a change in the order of Hooks called by %s. ' + 'This will lead to bugs and errors if not fixed. ' + 'For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks\n\n' + ' Previous render Next render\n' + ' ------------------------------------------------------\n' + '%s' + ' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n', componentName, table, ); } } } } function warnIfAsyncClientComponent( Component: Function, componentDoesIncludeHooks: boolean, ) { if (__DEV__) { // This dev-only check only works for detecting native async functions, // not transpiled ones. There's also a prod check that we use to prevent // async client components from crashing the app; the prod one works even // for transpiled async functions. Neither mechanism is completely // bulletproof but together they cover the most common cases. const isAsyncFunction = // $FlowIgnore[method-unbinding] Object.prototype.toString.call(Component) === '[object AsyncFunction]'; if (isAsyncFunction) { // Encountered an async Client Component. This is not yet supported, // except in certain constrained cases, like during a route navigation. const componentName = getComponentNameFromFiber(currentlyRenderingFiber); if (!didWarnAboutAsyncClientComponent.has(componentName)) { didWarnAboutAsyncClientComponent.add(componentName); // Check if this is a sync update. We use the "root" render lanes here // because the "subtree" render lanes may include additional entangled // lanes related to revealing previously hidden content. const root = getWorkInProgressRoot(); const rootRenderLanes = getWorkInProgressRootRenderLanes(); if (root !== null && includesBlockingLane(root, rootRenderLanes)) { console.error( 'async/await is not yet supported in Client Components, only ' + 'Server Components. This error is often caused by accidentally ' + "adding `'use client'` to a module that was originally written " + 'for the server.', ); } else { // This is a concurrent (Transition, Retry, etc) render. We don't // warn in these cases. // // However, Async Components are forbidden to include hooks, even // during a transition, so let's check for that here. // // TODO: Add a corresponding warning to Server Components runtime. if (componentDoesIncludeHooks) { console.error( 'Hooks are not supported inside an async component. This ' + "error is often caused by accidentally adding `'use client'` " + 'to a module that was originally written for the server.', ); } } } } } } function throwInvalidHookError() { 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.', ); } function areHookInputsEqual( nextDeps: Array<mixed>, prevDeps: Array<mixed> | null, ): boolean { if (__DEV__) { if (ignorePreviousDependencies) { // Only true when this component is being hot reloaded. return false; } } if (prevDeps === null) { if (__DEV__) { console.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, ); } return false; } if (__DEV__) { // Don't bother comparing lengths in prod because these arrays should be // passed inline. if (nextDeps.length !== prevDeps.length) { console.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, `[${prevDeps.join(', ')}]`, `[${nextDeps.join(', ')}]`, ); } } // $FlowFixMe[incompatible-use] found when upgrading Flow for (let i = 0; i < prevDeps.length && i < nextDeps.length; i++) { // $FlowFixMe[incompatible-use] found when upgrading Flow if (is(nextDeps[i], prevDeps[i])) { continue; } return false; } return true; } export function renderWithHooks<Props, SecondArg>( current: Fiber | null, workInProgress: Fiber, Component: (p: Props, arg: SecondArg) => any, props: Props, secondArg: SecondArg, nextRenderLanes: Lanes, ): any { renderLanes = nextRenderLanes; currentlyRenderingFiber = workInProgress; if (__DEV__) { hookTypesDev = current !== null ? ((current._debugHookTypes: any): Array<HookType>) : null; hookTypesUpdateIndexDev = -1; // Used for hot reloading: ignorePreviousDependencies = current !== null && current.type !== workInProgress.type; } workInProgress.memoizedState = null; workInProgress.updateQueue = null; workInProgress.lanes = NoLanes; // The following should have already been reset // currentHook = null; // workInProgressHook = null; // didScheduleRenderPhaseUpdate = false; // localIdCounter = 0; // thenableIndexCounter = 0; // thenableState = null; // TODO Warn if no hooks are used at all during mount, then some are used during update. // Currently we will identify the update render as a mount because memoizedState === null. // This is tricky because it's valid for certain types of components (e.g. React.lazy) // Using memoizedState to differentiate between mount/update only works if at least one stateful hook is used. // Non-stateful hooks (e.g. context) don't get added to memoizedState, // so memoizedState would be null during updates and mounts. if (__DEV__) { if (current !== null && current.memoizedState !== null) { ReactCurrentDispatcher.current = HooksDispatcherOnUpdateInDEV; } else if (hookTypesDev !== null) { // This dispatcher handles an edge case where a component is updating, // but no stateful hooks have been used. // We want to match the production code behavior (which will use HooksDispatcherOnMount), // but with the extra DEV validation to ensure hooks ordering hasn't changed. // This dispatcher does that. ReactCurrentDispatcher.current = HooksDispatcherOnMountWithHookTypesInDEV; } else { ReactCurrentDispatcher.current = HooksDispatcherOnMountInDEV; } } else { ReactCurrentDispatcher.current = current === null || current.memoizedState === null ? HooksDispatcherOnMount : HooksDispatcherOnUpdate; } // In Strict Mode, during development, user functions are double invoked to // help detect side effects. The logic for how this is implemented for in // hook components is a bit complex so let's break it down. // // We will invoke the entire component function twice. However, during the // second invocation of the component, the hook state from the first // invocation will be reused. That means things like `useMemo` functions won't // run again, because the deps will match and the memoized result will // be reused. // // We want memoized functions to run twice, too, so account for this, user // functions are double invoked during the *first* invocation of the component // function, and are *not* double invoked during the second incovation: // // - First execution of component function: user functions are double invoked // - Second execution of component function (in Strict Mode, during // development): user functions are not double invoked. // // This is intentional for a few reasons; most importantly, it's because of // how `use` works when something suspends: it reuses the promise that was // passed during the first attempt. This is itself a form of memoization. // We need to be able to memoize the reactive inputs to the `use` call using // a hook (i.e. `useMemo`), which means, the reactive inputs to `use` must // come from the same component invocation as the output. // // There are plenty of tests to ensure this behavior is correct. const shouldDoubleRenderDEV = __DEV__ && debugRenderPhaseSideEffectsForStrictMode && (workInProgress.mode & StrictLegacyMode) !== NoMode; shouldDoubleInvokeUserFnsInHooksDEV = shouldDoubleRenderDEV; let children = Component(props, secondArg); shouldDoubleInvokeUserFnsInHooksDEV = false; // Check if there was a render phase update if (didScheduleRenderPhaseUpdateDuringThisPass) { // Keep rendering until the component stabilizes (there are no more render // phase updates). children = renderWithHooksAgain( workInProgress, Component, props, secondArg, ); } if (shouldDoubleRenderDEV) { // In development, components are invoked twice to help detect side effects. setIsStrictModeForDevtools(true); try { children = renderWithHooksAgain( workInProgress, Component, props, secondArg, ); } finally { setIsStrictModeForDevtools(false); } } finishRenderingHooks(current, workInProgress, Component); return children; } function finishRenderingHooks<Props, SecondArg>( current: Fiber | null, workInProgress: Fiber, Component: (p: Props, arg: SecondArg) => any, ): void { if (__DEV__) { workInProgress._debugHookTypes = hookTypesDev; const componentDoesIncludeHooks = workInProgressHook !== null || thenableIndexCounter !== 0; warnIfAsyncClientComponent(Component, componentDoesIncludeHooks); } // We can assume the previous dispatcher is always this one, since we set it // at the beginning of the render phase and there's no re-entrance. ReactCurrentDispatcher.current = ContextOnlyDispatcher; // This check uses currentHook so that it works the same in DEV and prod bundles. // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles. const didRenderTooFewHooks = currentHook !== null && currentHook.next !== null; renderLanes = NoLanes; currentlyRenderingFiber = (null: any); currentHook = null; workInProgressHook = null; if (__DEV__) { currentHookNameInDev = null; hookTypesDev = null; hookTypesUpdateIndexDev = -1; // Confirm that a static flag was not added or removed since the last // render. If this fires, it suggests that we incorrectly reset the static // flags in some other part of the codebase. This has happened before, for // example, in the SuspenseList implementation. if ( current !== null && (current.flags & StaticMaskEffect) !== (workInProgress.flags & StaticMaskEffect) && // Disable this warning in legacy mode, because legacy Suspense is weird // and creates false positives. To make this work in legacy mode, we'd // need to mark fibers that commit in an incomplete state, somehow. For // now I'll disable the warning that most of the bugs that would trigger // it are either exclusive to concurrent mode or exist in both. (current.mode & ConcurrentMode) !== NoMode ) { console.error( 'Internal React error: Expected static flag was missing. Please ' + 'notify the React team.', ); } } didScheduleRenderPhaseUpdate = false; // This is reset by checkDidRenderIdHook // localIdCounter = 0; thenableIndexCounter = 0; thenableState = null; if (didRenderTooFewHooks) { throw new Error( 'Rendered fewer hooks than expected. This may be caused by an accidental ' + 'early return statement.', ); } if (enableLazyContextPropagation) { if (current !== null) { if (!checkIfWorkInProgressReceivedUpdate()) { // If there were no changes to props or state, we need to check if there // was a context change. We didn't already do this because there's no // 1:1 correspondence between dependencies and hooks. Although, because // there almost always is in the common case (`readContext` is an // internal API), we could compare in there. OTOH, we only hit this case // if everything else bails out, so on the whole it might be better to // keep the comparison out of the common path. const currentDependencies = current.dependencies; if ( currentDependencies !== null && checkIfContextChanged(currentDependencies) ) { markWorkInProgressReceivedUpdate(); } } } } if (__DEV__) { if (checkIfUseWrappedInTryCatch()) { const componentName = getComponentNameFromFiber(workInProgress) || 'Unknown'; if ( !didWarnAboutUseWrappedInTryCatch.has(componentName) && // This warning also fires if you suspend with `use` inside an // async component. Since we warn for that above, we'll silence this // second warning by checking here. !didWarnAboutAsyncClientComponent.has(componentName) ) { didWarnAboutUseWrappedInTryCatch.add(componentName); console.error( '`use` was called from inside a try/catch block. This is not allowed ' + 'and can lead to unexpected behavior. To handle errors triggered ' + 'by `use`, wrap your component in a error boundary.', ); } } } } export function replaySuspendedComponentWithHooks<Props, SecondArg>( current: Fiber | null, workInProgress: Fiber, Component: (p: Props, arg: SecondArg) => any, props: Props, secondArg: SecondArg, ): any { // This function is used to replay a component that previously suspended, // after its data resolves. // // It's a simplified version of renderWithHooks, but it doesn't need to do // most of the set up work because they weren't reset when we suspended; they // only get reset when the component either completes (finishRenderingHooks) // or unwinds (resetHooksOnUnwind). if (__DEV__) { hookTypesUpdateIndexDev = -1; // Used for hot reloading: ignorePreviousDependencies = current !== null && current.type !== workInProgress.type; } const children = renderWithHooksAgain( workInProgress, Component, props, secondArg, ); finishRenderingHooks(current, workInProgress, Component); return children; } function renderWithHooksAgain<Props, SecondArg>( workInProgress: Fiber, Component: (p: Props, arg: SecondArg) => any, props: Props, secondArg: SecondArg, ): any { // This is used to perform another render pass. It's used when setState is // called during render, and for double invoking components in Strict Mode // during development. // // The state from the previous pass is reused whenever possible. So, state // updates that were already processed are not processed again, and memoized // functions (`useMemo`) are not invoked again. // // Keep rendering in a loop for as long as render phase updates continue to // be scheduled. Use a counter to prevent infinite loops. currentlyRenderingFiber = workInProgress; let numberOfReRenders: number = 0; let children; do { if (didScheduleRenderPhaseUpdateDuringThisPass) { // It's possible that a use() value depended on a state that was updated in // this rerender, so we need to watch for different thenables this time. thenableState = null; } thenableIndexCounter = 0; didScheduleRenderPhaseUpdateDuringThisPass = false; if (numberOfReRenders >= RE_RENDER_LIMIT) { throw new Error( 'Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.', ); } numberOfReRenders += 1; if (__DEV__) { // Even when hot reloading, allow dependencies to stabilize // after first render to prevent infinite render phase updates. ignorePreviousDependencies = false; } // Start over from the beginning of the list currentHook = null; workInProgressHook = null; workInProgress.updateQueue = null; if (__DEV__) { // Also validate hook order for cascading updates. hookTypesUpdateIndexDev = -1; } ReactCurrentDispatcher.current = __DEV__ ? HooksDispatcherOnRerenderInDEV : HooksDispatcherOnRerender; children = Component(props, secondArg); } while (didScheduleRenderPhaseUpdateDuringThisPass); return children; } export function renderTransitionAwareHostComponentWithHooks( current: Fiber | null, workInProgress: Fiber, lanes: Lanes, ): TransitionStatus { if (!(enableFormActions && enableAsyncActions)) { throw new Error('Not implemented.'); } return renderWithHooks( current, workInProgress, TransitionAwareHostComponent, null, null, lanes, ); } export function TransitionAwareHostComponent(): TransitionStatus { if (!(enableFormActions && enableAsyncActions)) { throw new Error('Not implemented.'); } const dispatcher = ReactCurrentDispatcher.current; const [maybeThenable] = dispatcher.useState(); if (typeof maybeThenable.then === 'function') { const thenable: Thenable<TransitionStatus> = (maybeThenable: any); return useThenable(thenable); } else { const status: TransitionStatus = maybeThenable; return status; } } export function checkDidRenderIdHook(): boolean { // This should be called immediately after every renderWithHooks call. // Conceptually, it's part of the return value of renderWithHooks; it's only a // separate function to avoid using an array tuple. const didRenderIdHook = localIdCounter !== 0; localIdCounter = 0; return didRenderIdHook; } export function bailoutHooks( current: Fiber, workInProgress: Fiber, lanes: Lanes, ): void { workInProgress.updateQueue = current.updateQueue; // TODO: Don't need to reset the flags here, because they're reset in the // complete phase (bubbleProperties). if (__DEV__ && (workInProgress.mode & StrictEffectsMode) !== NoMode) { workInProgress.flags &= ~( MountPassiveDevEffect | MountLayoutDevEffect | PassiveEffect | UpdateEffect ); } else { workInProgress.flags &= ~(PassiveEffect | UpdateEffect); } current.lanes = removeLanes(current.lanes, lanes); } export function resetHooksAfterThrow(): void { // This is called immediaetly after a throw. It shouldn't reset the entire // module state, because the work loop might decide to replay the component // again without rewinding. // // It should only reset things like the current dispatcher, to prevent hooks // from being called outside of a component. currentlyRenderingFiber = (null: any); // We can assume the previous dispatcher is always this one, since we set it // at the beginning of the render phase and there's no re-entrance. ReactCurrentDispatcher.current = ContextOnlyDispatcher; } export function resetHooksOnUnwind(workInProgress: Fiber): void { if (didScheduleRenderPhaseUpdate) { // There were render phase updates. These are only valid for this render // phase, which we are now aborting. Remove the updates from the queues so // they do not persist to the next render. Do not remove updates from hooks // that weren't processed. // // Only reset the updates from the queue if it has a clone. If it does // not have a clone, that means it wasn't processed, and the updates were // scheduled before we entered the render phase. let hook: Hook | null = workInProgress.memoizedState; while (hook !== null) { const queue = hook.queue; if (queue !== null) { queue.pending = null; } hook = hook.next; } didScheduleRenderPhaseUpdate = false; } renderLanes = NoLanes; currentlyRenderingFiber = (null: any); currentHook = null; workInProgressHook = null; if (__DEV__) { hookTypesDev = null; hookTypesUpdateIndexDev = -1; currentHookNameInDev = null; } didScheduleRenderPhaseUpdateDuringThisPass = false; localIdCounter = 0; thenableIndexCounter = 0; thenableState = null; } function mountWorkInProgressHook(): Hook { const hook: Hook = { memoizedState: null, baseState: null, baseQueue: null, queue: null, next: null, }; if (workInProgressHook === null) { // This is the first hook in the list currentlyRenderingFiber.memoizedState = workInProgressHook = hook; } else { // Append to the end of the list workInProgressHook = workInProgressHook.next = hook; } return workInProgressHook; } function updateWorkInProgressHook(): Hook { // This function is used both for updates and for re-renders triggered by a // render phase update. It assumes there is either a current hook we can // clone, or a work-in-progress hook from a previous render pass that we can // use as a base. let nextCurrentHook: null | Hook; if (currentHook === null) { const current = currentlyRenderingFiber.alternate; if (current !== null) { nextCurrentHook = current.memoizedState; } else { nextCurrentHook = null; } } else { nextCurrentHook = currentHook.next; } let nextWorkInProgressHook: null | Hook; if (workInProgressHook === null) { nextWorkInProgressHook = currentlyRenderingFiber.memoizedState; } else { nextWorkInProgressHook = workInProgressHook.next; } if (nextWorkInProgressHook !== null) { // There's already a work-in-progress. Reuse it. workInProgressHook = nextWorkInProgressHook; nextWorkInProgressHook = workInProgressHook.next; currentHook = nextCurrentHook; } else { // Clone from the current hook. if (nextCurrentHook === null) { const currentFiber = currentlyRenderingFiber.alternate; if (currentFiber === null) { // This is the initial render. This branch is reached when the component // suspends, resumes, then renders an additional hook. // Should never be reached because we should switch to the mount dispatcher first. throw new Error( 'Update hook called on initial render. This is likely a bug in React. Please file an issue.', ); } else { // This is an update. We should always have a current hook. throw new Error('Rendered more hooks than during the previous render.'); } } currentHook = nextCurrentHook; const newHook: Hook = { memoizedState: currentHook.memoizedState, baseState: currentHook.baseState, baseQueue: currentHook.baseQueue, queue: currentHook.queue, next: null, }; if (workInProgressHook === null) { // This is the first hook in the list. currentlyRenderingFiber.memoizedState = workInProgressHook = newHook; } else { // Append to the end of the list. workInProgressHook = workInProgressHook.next = newHook; } } return workInProgressHook; } // NOTE: defining two versions of this function to avoid size impact when this feature is disabled. // Previously this function was inlined, the additional `memoCache` property makes it not inlined. let createFunctionComponentUpdateQueue: () => FunctionComponentUpdateQueue; if (enableUseMemoCacheHook) { createFunctionComponentUpdateQueue = () => { return { lastEffect: null, events: null, stores: null, memoCache: null, }; }; } else { createFunctionComponentUpdateQueue = () => { return { lastEffect: null, events: null, stores: null, }; }; } function useThenable<T>(thenable: Thenable<T>): T { // Track the position of the thenable within this fiber. const index = thenableIndexCounter; thenableIndexCounter += 1; if (thenableState === null) { thenableState = createThenableState(); } const result = trackUsedThenable(thenableState, thenable, index); if ( currentlyRenderingFiber.alternate === null && (workInProgressHook === null ? currentlyRenderingFiber.memoizedState === null : workInProgressHook.next === null) ) { // Initial render, and either this is the first time the component is // called, or there were no Hooks called after this use() the previous // time (perhaps because it threw). Subsequent Hook calls should use the // mount dispatcher. if (__DEV__) { ReactCurrentDispatcher.current = HooksDispatcherOnMountInDEV; } else { ReactCurrentDispatcher.current = HooksDispatcherOnMount; } } return result; } function use<T>(usable: Usable<T>): T { if (usable !== null && typeof usable === 'object') { // $FlowFixMe[method-unbinding] if (typeof usable.then === 'function') { // This is a thenable. const thenable: Thenable<T> = (usable: any); return useThenable(thenable); } else if ( usable.$$typeof === REACT_CONTEXT_TYPE || usable.$$typeof === REACT_SERVER_CONTEXT_TYPE ) { const context: ReactContext<T> = (usable: any); return readContext(context); } } // eslint-disable-next-line react-internal/safe-string-coercion throw new Error('An unsupported type was passed to use(): ' + String(usable)); } function useMemoCache(size: number): Array<any> { let memoCache = null; // Fast-path, load memo cache from wip fiber if already prepared let updateQueue: FunctionComponentUpdateQueue | null = (currentlyRenderingFiber.updateQueue: any); if (updateQueue !== null) { memoCache = updateQueue.memoCache; } // Otherwise clone from the current fiber if (memoCache == null) { const current: Fiber | null = currentlyRenderingFiber.alternate; if (current !== null) { const currentUpdateQueue: FunctionComponentUpdateQueue | null = (current.updateQueue: any); if (currentUpdateQueue !== null) { const currentMemoCache: ?MemoCache = currentUpdateQueue.memoCache; if (currentMemoCache != null) { memoCache = { data: currentMemoCache.data.map(array => array.slice()), index: 0, }; } } } } // Finally fall back to allocating a fresh instance of the cache if (memoCache == null) { memoCache = { data: [], index: 0, }; } if (updateQueue === null) { updateQueue = createFunctionComponentUpdateQueue(); currentlyRenderingFiber.updateQueue = updateQueue; } updateQueue.memoCache = memoCache; let data = memoCache.data[memoCache.index]; if (data === undefined) { data = memoCache.data[memoCache.index] = new Array(size); for (let i = 0; i < size; i++) { data[i] = REACT_MEMO_CACHE_SENTINEL; } } else if (data.length !== size) { // TODO: consider warning or throwing here if (__DEV__) { console.error( 'Expected a constant size argument for each invocation of useMemoCache. ' + 'The previous cache was allocated with size %s but size %s was requested.', data.length, size, ); } } memoCache.index++; return data; } function basicStateReducer<S>(state: S, action: BasicStateAction<S>): S { // $FlowFixMe[incompatible-use]: Flow doesn't like mixed types return typeof action === 'function' ? action(state) : action; } function mountReducer<S, I, A>( reducer: (S, A) => S, initialArg: I, init?: I => S, ): [S, Dispatch<A>] { const hook = mountWorkInProgressHook(); let initialState; if (init !== undefined) { initialState = init(initialArg); } else { initialState = ((initialArg: any): S); } hook.memoizedState = hook.baseState = initialState; const queue: UpdateQueue<S, A> = { pending: null, lanes: NoLanes, dispatch: null, lastRenderedReducer: reducer, lastRenderedState: (initialState: any), }; hook.queue = queue; const dispatch: Dispatch<A> = (queue.dispatch = (dispatchReducerAction.bind( null, currentlyRenderingFiber, queue, ): any)); return [hook.memoizedState, dispatch]; } function updateReducer<S, I, A>( reducer: (S, A) => S, initialArg: I, init?: I => S, ): [S, Dispatch<A>] { const hook = updateWorkInProgressHook(); return updateReducerImpl(hook, ((currentHook: any): Hook), reducer); } function updateReducerImpl<S, A>( hook: Hook, current: Hook, reducer: (S, A) => S, ): [S, Dispatch<A>] { const queue = hook.queue; if (queue === null) { throw new Error( 'Should have a queue. This is likely a bug in React. Please file an issue.', ); } queue.lastRenderedReducer = reducer; // The last rebase update that is NOT part of the base state. let baseQueue = hook.baseQueue; // The last pending update that hasn't been processed yet. const pendingQueue = queue.pending; if (pendingQueue !== null) { // We have new updates that haven't been processed yet. // We'll add them to the base queue. if (baseQueue !== null) { // Merge the pending queue and the base queue. const baseFirst = baseQueue.next; const pendingFirst = pendingQueue.next; baseQueue.next = pendingFirst; pendingQueue.next = baseFirst; } if (__DEV__) { if (current.baseQueue !== baseQueue) { // Internal invariant that should never happen, but feasibly could in // the future if we implement resuming, or some form of that. console.error( 'Internal error: Expected work-in-progress queue to be a clone. ' + 'This is a bug in React.', ); } } current.baseQueue = baseQueue = pendingQueue; queue.pending = null; } if (baseQueue !== null) { // We have a queue to process. const first = baseQueue.next; let newState = hook.baseState; let newBaseState = null; let newBaseQueueFirst = null; let newBaseQueueLast: Update<S, A> | null = null; let update = first; do { // An extra OffscreenLane bit is added to updates that were made to // a hidden tree, so that we can distinguish them from updates that were // already there when the tree was hidden. const updateLane = removeLanes(update.lane, OffscreenLane); const isHiddenUpdate = updateLane !== update.lane; // Check if this update was made while the tree was hidden. If so, then // it's not a "base" update and we should disregard the extra base lanes // that were added to renderLanes when we entered the Offscreen tree. const shouldSkipUpdate = isHiddenUpdate ? !isSubsetOfLanes(getWorkInProgressRootRenderLanes(), updateLane) : !isSubsetOfLanes(renderLanes, updateLane); if (shouldSkipUpdate) { // Priority is insufficient. Skip this update. If this is the first // skipped update, the previous update/state is the new base // update/state. const clone: Update<S, A> = { lane: updateLane, revertLane: update.revertLane, action: update.action, hasEagerState: update.hasEagerState, eagerState: update.eagerState, next: (null: any), }; if (newBaseQueueLast === null) { newBaseQueueFirst = newBaseQueueLast = clone; newBaseState = newState; } else { newBaseQueueLast = newBaseQueueLast.next = clone; } // Update the remaining priority in the queue. // TODO: Don't need to accumulate this. Instead, we can remove // renderLanes from the original lanes. currentlyRenderingFiber.lanes = mergeLanes( currentlyRenderingFiber.lanes, updateLane, ); markSkippedUpdateLanes(updateLane); } else { // This update does have sufficient priority. // Check if this is an optimistic update. const revertLane = update.revertLane; if (!enableAsyncActions || revertLane === NoLane) { // This is not an optimistic update, and we're going to apply it now. // But, if there were earlier updates that were skipped, we need to // leave this update in the queue so it can be rebased later. if (newBaseQueueLast !== null) { const clone: Update<S, A> = { // This update is going to be committed so we never want uncommit // it. Using NoLane works because 0 is a subset of all bitmasks, so // this will never be skipped by the check above. lane: NoLane, revertLane: NoLane, action: update.action, hasEagerState: update.hasEagerState, eagerState: update.eagerState, next: (null: any), }; newBaseQueueLast = newBaseQueueLast.next = clone; } } else { // This is an optimistic update. If the "revert" priority is // sufficient, don't apply the update. Otherwise, apply the update, // but leave it in the queue so it can be either reverted or // rebased in a subsequent render. if (isSubsetOfLanes(renderLanes, revertLane)) { // The transition that this optimistic update is associated with // has finished. Pretend the update doesn't exist by skipping // over it. update = update.next; continue; } else { const clone: Update<S, A> = { // Once we commit an optimistic update, we shouldn't uncommit it // until the transition it is associated with has finished // (represented by revertLane). Using NoLane here works because 0 // is a subset of all bitmasks, so this will never be skipped by // the check above. lane: NoLane, // Reuse the same revertLane so we know when the transition // has finished. revertLane: update.revertLane, action: update.action, hasEagerState: update.hasEagerState, eagerState: update.eagerState, next: (null: any), }; if (newBaseQueueLast === null) { newBaseQueueFirst = newBaseQueueLast = clone; newBaseState = newState; } else { newBaseQueueLast = newBaseQueueLast.next = clone; } // Update the remaining priority in the queue. // TODO: Don't need to accumulate this. Instead, we can remove // renderLanes from the original lanes. currentlyRenderingFiber.lanes = mergeLanes( currentlyRenderingFiber.lanes, revertLane, ); markSkippedUpdateLanes(revertLane); } } // Process this update. const action = update.action; if (shouldDoubleInvokeUserFnsInHooksDEV) { reducer(newState, action); } if (update.hasEagerState) { // If this update is a state update (not a reducer) and was processed eagerly, // we can use the eagerly computed state newState = ((update.eagerState: any): S); } else { newState = reducer(newState, action); } } update = update.next; } while (update !== null && update !== first); if (newBaseQueueLast === null) { newBaseState = newState; } else { newBaseQueueLast.next = (newBaseQueueFirst: any); } // Mark that the fiber performed work, but only if the new state is // different from the current state. if (!is(newState, hook.memoizedState)) { markWorkInProgressReceivedUpdate(); } hook.memoizedState = newState; hook.baseState = newBaseState; hook.baseQueue = newBaseQueueLast; queue.lastRenderedState = newState; } if (baseQueue === null) { // `queue.lanes` is used for entangling transitions. We can set it back to // zero once the queue is empty. queue.lanes = NoLanes; } const dispatch: Dispatch<A> = (queue.dispatch: any); return [hook.memoizedState, dispatch]; } function rerenderReducer<S, I, A>( reducer: (S, A) => S, initialArg: I, init?: I => S, ): [S, Dispatch<A>] { const hook = updateWorkInProgressHook(); const queue = hook.queue; if (queue === null) { throw new Error( 'Should have a queue. This is likely a bug in React. Please file an issue.', ); } queue.lastRenderedReducer = reducer; // This is a re-render. Apply the new render phase updates to the previous // work-in-progress hook. const dispatch: Dispatch<A> = (queue.dispatch: any); const lastRenderPhaseUpdate = queue.pending; let newState = hook.memoizedState; if (lastRenderPhaseUpdate !== null) { // The queue doesn't persist past this render pass. queue.pending = null; const firstRenderPhaseUpdate = lastRenderPhaseUpdate.next; let update = firstRenderPhaseUpdate; 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. const action = update.action; newState = reducer(newState, action); update = update.next; } while (update !== firstRenderPhaseUpdate); // Mark that the fiber performed work, but only if the new state is // different from the current state. if (!is(newState, hook.memoizedState)) { markWorkInProgressReceivedUpdate(); } hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to // the base state unless the queue is empty. // TODO: Not sure if this is the desired semantics, but it's what we // do for gDSFP. I can't remember why. if (hook.baseQueue === null) { hook.baseState = newState; } queue.lastRenderedState = newState; } return [newState, dispatch]; } function mountSyncExternalStore<T>( subscribe: (() => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T, ): T { const fiber = currentlyRenderingFiber; const hook = mountWorkInProgressHook(); let nextSnapshot; const isHydrating = getIsHydrating(); if (isHydrating) { if (getServerSnapshot === undefined) { throw new Error( 'Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.', ); } nextSnapshot = getServerSnapshot(); if (__DEV__) { if (!didWarnUncachedGetSnapshot) { if (nextSnapshot !== getServerSnapshot()) { console.error( 'The result of getServerSnapshot should be cached to avoid an infinite loop', ); didWarnUncachedGetSnapshot = true; } } } } else { nextSnapshot = getSnapshot(); if (__DEV__) { if (!didWarnUncachedGetSnapshot) { const cachedSnapshot = getSnapshot(); if (!is(nextSnapshot, cachedSnapshot)) { console.error( 'The result of getSnapshot should be cached to avoid an infinite loop', ); didWarnUncachedGetSnapshot = true; } } } // Unless we're rendering a blocking lane, schedule a consistency check. // Right before committing, we will walk the tree and check if any of the // stores were mutated. // // We won't do this if we're hydrating server-rendered content, because if // the content is stale, it's already visible anyway. Instead we'll patch // it up in a passive effect. const root: FiberRoot | null = getWorkInProgressRoot(); if (root === null) { throw new Error( 'Expected a work-in-progress root. This is a bug in React. Please file an issue.', ); } const rootRenderLanes = getWorkInProgressRootRenderLanes(); if (!includesBlockingLane(root, rootRenderLanes)) { pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot); } } // Read the current snapshot from the store on every render. This breaks the // normal rules of React, and only works because store updates are // always synchronous. hook.memoizedState = nextSnapshot; const inst: StoreInstance<T> = { value: nextSnapshot, getSnapshot, }; hook.queue = inst; // Schedule an effect to subscribe to the store. mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Schedule an effect to update the mutable instance fields. We will update // this whenever subscribe, getSnapshot, or value changes. Because there's no // clean-up function, and we track the deps correctly, we can call pushEffect // directly, without storing any additional state. For the same reason, we // don't need to set a static flag, either. fiber.flags |= PassiveEffect; pushEffect( HookHasEffect | HookPassive, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), createEffectInstance(), null, ); return nextSnapshot; } function updateSyncExternalStore<T>( subscribe: (() => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T, ): T { const fiber = currentlyRenderingFiber; const hook = updateWorkInProgressHook(); // Read the current snapshot from the store on every render. This breaks the // normal rules of React, and only works because store updates are // always synchronous. let nextSnapshot; const isHydrating = getIsHydrating(); if (isHydrating) { // Needed for strict mode double render if (getServerSnapshot === undefined) { throw new Error( 'Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.', ); } nextSnapshot = getServerSnapshot(); } else { nextSnapshot = getSnapshot(); if (__DEV__) { if (!didWarnUncachedGetSnapshot) { const cachedSnapshot = getSnapshot(); if (!is(nextSnapshot, cachedSnapshot)) { console.error( 'The result of getSnapshot should be cached to avoid an infinite loop', ); didWarnUncachedGetSnapshot = true; } } } } const prevSnapshot = (currentHook || hook).memoizedState; const snapshotChanged = !is(prevSnapshot, nextSnapshot); if (snapshotChanged) { hook.memoizedState = nextSnapshot; markWorkInProgressReceivedUpdate(); } const inst = hook.queue; updateEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [ subscribe, ]); // Whenever getSnapshot or subscribe changes, we need to check in the // commit phase if there was an interleaved mutation. In concurrent mode // this can happen all the time, but even in synchronous mode, an earlier // effect may have mutated the store. if ( inst.getSnapshot !== getSnapshot || snapshotChanged || // Check if the subscribe function changed. We can save some memory by // checking whether we scheduled a subscription effect above. (workInProgressHook !== null && workInProgressHook.memoizedState.tag & HookHasEffect) ) { fiber.flags |= PassiveEffect; pushEffect( HookHasEffect | HookPassive, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), createEffectInstance(), null, ); // Unless we're rendering a blocking lane, schedule a consistency check. // Right before committing, we will walk the tree and check if any of the // stores were mutated. const root: FiberRoot | null = getWorkInProgressRoot(); if (root === null) { throw new Error( 'Expected a work-in-progress root. This is a bug in React. Please file an issue.', ); } if (!isHydrating && !includesBlockingLane(root, renderLanes)) { pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot); } } return nextSnapshot; } function pushStoreConsistencyCheck<T>( fiber: Fiber, getSnapshot: () => T, renderedSnapshot: T, ): void { fiber.flags |= StoreConsistency; const check: StoreConsistencyCheck<T> = { getSnapshot, value: renderedSnapshot, }; let componentUpdateQueue: null | FunctionComponentUpdateQueue = (currentlyRenderingFiber.updateQueue: any); if (componentUpdateQueue === null) { componentUpdateQueue = createFunctionComponentUpdateQueue(); currentlyRenderingFiber.updateQueue = (componentUpdateQueue: any); componentUpdateQueue.stores = [check]; } else { const stores = componentUpdateQueue.stores; if (stores === null) { componentUpdateQueue.stores = [check]; } else { stores.push(check); } } } function updateStoreInstance<T>( fiber: Fiber, inst: StoreInstance<T>, nextSnapshot: T, getSnapshot: () => T, ): void { // These are updated in the passive phase inst.value = nextSnapshot; inst.getSnapshot = getSnapshot; // Something may have been mutated in between render and commit. This could // have been in an event that fired before the passive effects, or it could // have been in a layout effect. In that case, we would have used the old // snapsho and getSnapshot values to bail out. We need to check one more time. if (checkIfSnapshotChanged(inst)) { // Force a re-render. forceStoreRerender(fiber); } } function subscribeToStore<T>( fiber: Fiber, inst: StoreInstance<T>, subscribe: (() => void) => () => void, ): any { const handleStoreChange = () => { // The store changed. Check if the snapshot changed since the last time we // read from the store. if (checkIfSnapshotChanged(inst)) { // Force a re-render. forceStoreRerender(fiber); } }; // Subscribe to the store and return a clean-up function. return subscribe(handleStoreChange); } function checkIfSnapshotChanged<T>(inst: StoreInstance<T>): boolean { const latestGetSnapshot = inst.getSnapshot; const prevValue = inst.value; try { const nextValue = latestGetSnapshot(); return !is(prevValue, nextValue); } catch (error) { return true; } } function forceStoreRerender(fiber: Fiber) { const root = enqueueConcurrentRenderForLane(fiber, SyncLane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, SyncLane); } } function mountStateImpl<S>(initialState: (() => S) | S): Hook { const hook = mountWorkInProgressHook(); if (typeof initialState === 'function') { // $FlowFixMe[incompatible-use]: Flow doesn't like mixed types initialState = initialState(); } hook.memoizedState = hook.baseState = initialState; const queue: UpdateQueue<S, BasicStateAction<S>> = { pending: null, lanes: NoLanes, dispatch: null, lastRenderedReducer: basicStateReducer, lastRenderedState: (initialState: any), }; hook.queue = queue; return hook; } function mountState<S>( initialState: (() => S) | S, ): [S, Dispatch<BasicStateAction<S>>] { const hook = mountStateImpl(initialState); const queue = hook.queue; const dispatch: Dispatch<BasicStateAction<S>> = (dispatchSetState.bind( null, currentlyRenderingFiber, queue, ): any); queue.dispatch = dispatch; return [hook.memoizedState, dispatch]; } function updateState<S>( initialState: (() => S) | S, ): [S, Dispatch<BasicStateAction<S>>] { return updateReducer(basicStateReducer, initialState); } function rerenderState<S>( initialState: (() => S) | S, ): [S, Dispatch<BasicStateAction<S>>] { return rerenderReducer(basicStateReducer, initialState); } function mountOptimistic<S, A>( passthrough: S, reducer: ?(S, A) => S, ): [S, (A) => void] { const hook = mountWorkInProgressHook(); hook.memoizedState = hook.baseState = passthrough; const queue: UpdateQueue<S, A> = { pending: null, lanes: NoLanes, dispatch: null, // Optimistic state does not use the eager update optimization. lastRenderedReducer: null, lastRenderedState: null, }; hook.queue = queue; // This is different than the normal setState function. const dispatch: A => void = (dispatchOptimisticSetState.bind( null, currentlyRenderingFiber, true, queue, ): any); queue.dispatch = dispatch; return [passthrough, dispatch]; } function updateOptimistic<S, A>( passthrough: S, reducer: ?(S, A) => S, ): [S, (A) => void] { const hook = updateWorkInProgressHook(); return updateOptimisticImpl( hook, ((currentHook: any): Hook), passthrough, reducer, ); } function updateOptimisticImpl<S, A>( hook: Hook, current: Hook | null, passthrough: S, reducer: ?(S, A) => S, ): [S, (A) => void] { // Optimistic updates are always rebased on top of the latest value passed in // as an argument. It's called a passthrough because if there are no pending // updates, it will be returned as-is. // // Reset the base state to the passthrough. Future updates will be applied // on top of this. hook.baseState = passthrough; // If a reducer is not provided, default to the same one used by useState. const resolvedReducer: (S, A) => S = typeof reducer === 'function' ? reducer : (basicStateReducer: any); return updateReducerImpl(hook, ((currentHook: any): Hook), resolvedReducer); } function rerenderOptimistic<S, A>( passthrough: S, reducer: ?(S, A) => S, ): [S, (A) => void] { // Unlike useState, useOptimistic doesn't support render phase updates. // Also unlike useState, we need to replay all pending updates again in case // the passthrough value changed. // // So instead of a forked re-render implementation that knows how to handle // render phase udpates, we can use the same implementation as during a // regular mount or update. const hook = updateWorkInProgressHook(); if (currentHook !== null) { // This is an update. Process the update queue. return updateOptimisticImpl( hook, ((currentHook: any): Hook), passthrough, reducer, ); } // This is a mount. No updates to process. // Reset the base state to the passthrough. Future updates will be applied // on top of this. hook.baseState = passthrough; const dispatch = hook.queue.dispatch; return [passthrough, dispatch]; } // useFormState actions run sequentially, because each action receives the // previous state as an argument. We store pending actions on a queue. type FormStateActionQueue<S, P> = { // This is the most recent state returned from an action. It's updated as // soon as the action finishes running. state: Awaited<S>, // A stable dispatch method, passed to the user. dispatch: Dispatch<P>, // This is the most recent action function that was rendered. It's updated // during the commit phase. action: (Awaited<S>, P) => S, // This is a circular linked list of pending action payloads. It incudes the // action that is currently running. pending: FormStateActionQueueNode<P> | null, }; type FormStateActionQueueNode<P> = { payload: P, // This is never null because it's part of a circular linked list. next: FormStateActionQueueNode<P>, }; function dispatchFormState<S, P>( fiber: Fiber, actionQueue: FormStateActionQueue<S, P>, setState: Dispatch<S | Awaited<S>>, payload: P, ): void { if (isRenderPhaseUpdate(fiber)) { throw new Error('Cannot update form state while rendering.'); } const last = actionQueue.pending; if (last === null) { // There are no pending actions; this is the first one. We can run // it immediately. const newLast: FormStateActionQueueNode<P> = { payload, next: (null: any), // circular }; newLast.next = actionQueue.pending = newLast; runFormStateAction(actionQueue, (setState: any), payload); } else { // There's already an action running. Add to the queue. const first = last.next; const newLast: FormStateActionQueueNode<P> = { payload, next: first, }; actionQueue.pending = last.next = newLast; } } function runFormStateAction<S, P>( actionQueue: FormStateActionQueue<S, P>, setState: Dispatch<S | Awaited<S>>, payload: P, ) { const action = actionQueue.action; const prevState = actionQueue.state; // This is a fork of startTransition const prevTransition = ReactCurrentBatchConfig.transition; ReactCurrentBatchConfig.transition = ({}: BatchConfigTransition); const currentTransition = ReactCurrentBatchConfig.transition; if (__DEV__) { ReactCurrentBatchConfig.transition._updatedFibers = new Set(); } try { const returnValue = action(prevState, payload); if ( returnValue !== null && typeof returnValue === 'object' && // $FlowFixMe[method-unbinding] typeof returnValue.then === 'function' ) { const thenable = ((returnValue: any): Thenable<Awaited<S>>); // Attach a listener to read the return state of the action. As soon as // this resolves, we can run the next action in the sequence. thenable.then( (nextState: Awaited<S>) => { actionQueue.state = nextState; finishRunningFormStateAction(actionQueue, (setState: any)); }, () => finishRunningFormStateAction(actionQueue, (setState: any)), ); const entangledResult = requestAsyncActionContext<S>(thenable, null); setState((entangledResult: any)); } else { // This is either `returnValue` or a thenable that resolves to // `returnValue`, depending on whether we're inside an async action scope. const entangledResult = requestSyncActionContext<S>(returnValue, null); setState((entangledResult: any)); const nextState = ((returnValue: any): Awaited<S>); actionQueue.state = nextState; finishRunningFormStateAction(actionQueue, (setState: any)); } } catch (error) { // This is a trick to get the `useFormState` hook to rethrow the error. // When it unwraps the thenable with the `use` algorithm, the error // will be thrown. const rejectedThenable: S = ({ then() {}, status: 'rejected', reason: error, // $FlowFixMe: Not sure why this doesn't work }: RejectedThenable<Awaited<S>>); setState(rejectedThenable); finishRunningFormStateAction(actionQueue, (setState: any)); } finally { ReactCurrentBatchConfig.transition = prevTransition; if (__DEV__) { if (prevTransition === null && currentTransition._updatedFibers) { const updatedFibersCount = currentTransition._updatedFibers.size; currentTransition._updatedFibers.clear(); if (updatedFibersCount > 10) { console.warn( 'Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.', ); } } } } } function finishRunningFormStateAction<S, P>( actionQueue: FormStateActionQueue<S, P>, setState: Dispatch<S | Awaited<S>>, ) { // The action finished running. Pop it from the queue and run the next pending // action, if there are any. const last = actionQueue.pending; if (last !== null) { const first = last.next; if (first === last) { // This was the last action in the queue. actionQueue.pending = null; } else { // Remove the first node from the circular queue. const next = first.next; last.next = next; // Run the next action. runFormStateAction(actionQueue, (setState: any), next.payload); } } } function formStateReducer<S>(oldState: S, newState: S): S { return newState; } function mountFormState<S, P>( action: (Awaited<S>, P) => S, initialStateProp: Awaited<S>, permalink?: string, ): [Awaited<S>, (P) => void] { let initialState: Awaited<S> = initialStateProp; if (getIsHydrating()) { const root: FiberRoot = (getWorkInProgressRoot(): any); const ssrFormState = root.formState; // If a formState option was passed to the root, there are form state // markers that we need to hydrate. These indicate whether the form state // matches this hook instance. if (ssrFormState !== null) { const isMatching = tryToClaimNextHydratableFormMarkerInstance( currentlyRenderingFiber, ); if (isMatching) { initialState = ssrFormState[0]; } } } // State hook. The state is stored in a thenable which is then unwrapped by // the `use` algorithm during render. const stateHook = mountWorkInProgressHook(); stateHook.memoizedState = stateHook.baseState = initialState; // TODO: Typing this "correctly" results in recursion limit errors // const stateQueue: UpdateQueue<S | Awaited<S>, S | Awaited<S>> = { const stateQueue = { pending: null, lanes: NoLanes, dispatch: (null: any), lastRenderedReducer: formStateReducer, lastRenderedState: initialState, }; stateHook.queue = stateQueue; const setState: Dispatch<S | Awaited<S>> = (dispatchSetState.bind( null, currentlyRenderingFiber, ((stateQueue: any): UpdateQueue<S | Awaited<S>, S | Awaited<S>>), ): any); stateQueue.dispatch = setState; // Action queue hook. This is used to queue pending actions. The queue is // shared between all instances of the hook. Similar to a regular state queue, // but different because the actions are run sequentially, and they run in // an event instead of during render. const actionQueueHook = mountWorkInProgressHook(); const actionQueue: FormStateActionQueue<S, P> = { state: initialState, dispatch: (null: any), // circular action, pending: null, }; actionQueueHook.queue = actionQueue; const dispatch = (dispatchFormState: any).bind( null, currentlyRenderingFiber, actionQueue, setState, ); actionQueue.dispatch = dispatch; // Stash the action function on the memoized state of the hook. We'll use this // to detect when the action function changes so we can update it in // an effect. actionQueueHook.memoizedState = action; return [initialState, dispatch]; } function updateFormState<S, P>( action: (Awaited<S>, P) => S, initialState: Awaited<S>, permalink?: string, ): [Awaited<S>, (P) => void] { const stateHook = updateWorkInProgressHook(); const currentStateHook = ((currentHook: any): Hook); return updateFormStateImpl( stateHook, currentStateHook, action, initialState, permalink, ); } function updateFormStateImpl<S, P>( stateHook: Hook, currentStateHook: Hook, action: (Awaited<S>, P) => S, initialState: Awaited<S>, permalink?: string, ): [Awaited<S>, (P) => void] { const [actionResult] = updateReducerImpl<S | Thenable<S>, S | Thenable<S>>( stateHook, currentStateHook, formStateReducer, ); // This will suspend until the action finishes. const state: Awaited<S> = typeof actionResult === 'object' && actionResult !== null && // $FlowFixMe[method-unbinding] typeof actionResult.then === 'function' ? useThenable(((actionResult: any): Thenable<Awaited<S>>)) : (actionResult: any); const actionQueueHook = updateWorkInProgressHook(); const actionQueue = actionQueueHook.queue; const dispatch = actionQueue.dispatch; // Check if a new action was passed. If so, update it in an effect. const prevAction = actionQueueHook.memoizedState; if (action !== prevAction) { currentlyRenderingFiber.flags |= PassiveEffect; pushEffect( HookHasEffect | HookPassive, formStateActionEffect.bind(null, actionQueue, action), createEffectInstance(), null, ); } return [state, dispatch]; } function formStateActionEffect<S, P>( actionQueue: FormStateActionQueue<S, P>, action: (Awaited<S>, P) => S, ): void { actionQueue.action = action; } function rerenderFormState<S, P>( action: (Awaited<S>, P) => S, initialState: Awaited<S>, permalink?: string, ): [Awaited<S>, (P) => void] { // Unlike useState, useFormState doesn't support render phase updates. // Also unlike useState, we need to replay all pending updates again in case // the passthrough value changed. // // So instead of a forked re-render implementation that knows how to handle // render phase udpates, we can use the same implementation as during a // regular mount or update. const stateHook = updateWorkInProgressHook(); const currentStateHook = currentHook; if (currentStateHook !== null) { // This is an update. Process the update queue. return updateFormStateImpl( stateHook, currentStateHook, action, initialState, permalink, ); } // This is a mount. No updates to process. const state: Awaited<S> = stateHook.memoizedState; const actionQueueHook = updateWorkInProgressHook(); const actionQueue = actionQueueHook.queue; const dispatch = actionQueue.dispatch; // This may have changed during the rerender. actionQueueHook.memoizedState = action; return [state, dispatch]; } function pushEffect( tag: HookFlags, create: () => (() => void) | void, inst: EffectInstance, deps: Array<mixed> | null, ): Effect { const effect: Effect = { tag, create, inst, deps, // Circular next: (null: any), }; let componentUpdateQueue: null | FunctionComponentUpdateQueue = (currentlyRenderingFiber.updateQueue: any); if (componentUpdateQueue === null) { componentUpdateQueue = createFunctionComponentUpdateQueue(); currentlyRenderingFiber.updateQueue = (componentUpdateQueue: any); componentUpdateQueue.lastEffect = effect.next = effect; } else { const lastEffect = componentUpdateQueue.lastEffect; if (lastEffect === null) { componentUpdateQueue.lastEffect = effect.next = effect; } else { const firstEffect = lastEffect.next; lastEffect.next = effect; effect.next = firstEffect; componentUpdateQueue.lastEffect = effect; } } return effect; } function createEffectInstance(): EffectInstance { return {destroy: undefined}; } let stackContainsErrorMessage: boolean | null = null; function getCallerStackFrame(): string { // eslint-disable-next-line react-internal/prod-error-codes const stackFrames = new Error('Error message').stack.split('\n'); // Some browsers (e.g. Chrome) include the error message in the stack // but others (e.g. Firefox) do not. if (stackContainsErrorMessage === null) { stackContainsErrorMessage = stackFrames[0].includes('Error message'); } return stackContainsErrorMessage ? stackFrames.slice(3, 4).join('\n') : stackFrames.slice(2, 3).join('\n'); } function mountRef<T>(initialValue: T): {current: T} { const hook = mountWorkInProgressHook(); if (enableUseRefAccessWarning) { if (__DEV__) { // Support lazy initialization pattern shown in docs. // We need to store the caller stack frame so that we don't warn on subsequent renders. let hasBeenInitialized = initialValue != null; let lazyInitGetterStack = null; let didCheckForLazyInit = false; // Only warn once per component+hook. let didWarnAboutRead = false; let didWarnAboutWrite = false; let current = initialValue; const ref = { get current() { if (!hasBeenInitialized) { didCheckForLazyInit = true; lazyInitGetterStack = getCallerStackFrame(); } else if (currentlyRenderingFiber !== null && !didWarnAboutRead) { if ( lazyInitGetterStack === null || lazyInitGetterStack !== getCallerStackFrame() ) { didWarnAboutRead = true; console.warn( '%s: Unsafe read of a mutable value during render.\n\n' + 'Reading from a ref during render is only safe if:\n' + '1. The ref value has not been updated, or\n' + '2. The ref holds a lazily-initialized value that is only set once.\n', getComponentNameFromFiber(currentlyRenderingFiber) || 'Unknown', ); } } return current; }, set current(value: any) { if (currentlyRenderingFiber !== null && !didWarnAboutWrite) { if (hasBeenInitialized || !didCheckForLazyInit) { didWarnAboutWrite = true; console.warn( '%s: Unsafe write of a mutable value during render.\n\n' + 'Writing to a ref during render is only safe if the ref holds ' + 'a lazily-initialized value that is only set once.\n', getComponentNameFromFiber(currentlyRenderingFiber) || 'Unknown', ); } } hasBeenInitialized = true; current = value; }, }; Object.seal(ref); hook.memoizedState = ref; return ref; } else { const ref = {current: initialValue}; hook.memoizedState = ref; return ref; } } else { const ref = {current: initialValue}; hook.memoizedState = ref; return ref; } } function updateRef<T>(initialValue: T): {current: T} { const hook = updateWorkInProgressHook(); return hook.memoizedState; } function mountEffectImpl( fiberFlags: Flags, hookFlags: HookFlags, create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { const hook = mountWorkInProgressHook(); const nextDeps = deps === undefined ? null : deps; currentlyRenderingFiber.flags |= fiberFlags; hook.memoizedState = pushEffect( HookHasEffect | hookFlags, create, createEffectInstance(), nextDeps, ); } function updateEffectImpl( fiberFlags: Flags, hookFlags: HookFlags, create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { const hook = updateWorkInProgressHook(); const nextDeps = deps === undefined ? null : deps; const effect: Effect = hook.memoizedState; const inst = effect.inst; // currentHook is null on initial mount when rerendering after a render phase // state update or for strict mode. if (currentHook !== null) { if (nextDeps !== null) { const prevEffect: Effect = currentHook.memoizedState; const prevDeps = prevEffect.deps; if (areHookInputsEqual(nextDeps, prevDeps)) { hook.memoizedState = pushEffect(hookFlags, create, inst, nextDeps); return; } } } currentlyRenderingFiber.flags |= fiberFlags; hook.memoizedState = pushEffect( HookHasEffect | hookFlags, create, inst, nextDeps, ); } function mountEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { if ( __DEV__ && (currentlyRenderingFiber.mode & StrictEffectsMode) !== NoMode && (currentlyRenderingFiber.mode & NoStrictPassiveEffectsMode) === NoMode ) { mountEffectImpl( MountPassiveDevEffect | PassiveEffect | PassiveStaticEffect, HookPassive, create, deps, ); } else { mountEffectImpl( PassiveEffect | PassiveStaticEffect, HookPassive, create, deps, ); } } function updateEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { updateEffectImpl(PassiveEffect, HookPassive, create, deps); } function useEffectEventImpl<Args, Return, F: (...Array<Args>) => Return>( payload: EventFunctionPayload<Args, Return, F>, ) { currentlyRenderingFiber.flags |= UpdateEffect; let componentUpdateQueue: null | FunctionComponentUpdateQueue = (currentlyRenderingFiber.updateQueue: any); if (componentUpdateQueue === null) { componentUpdateQueue = createFunctionComponentUpdateQueue(); currentlyRenderingFiber.updateQueue = (componentUpdateQueue: any); componentUpdateQueue.events = [payload]; } else { const events = componentUpdateQueue.events; if (events === null) { componentUpdateQueue.events = [payload]; } else { events.push(payload); } } } function mountEvent<Args, Return, F: (...Array<Args>) => Return>( callback: F, ): F { const hook = mountWorkInProgressHook(); const ref = {impl: callback}; hook.memoizedState = ref; // $FlowIgnore[incompatible-return] return function eventFn() { if (isInvalidExecutionContextForEventFunction()) { throw new Error( "A function wrapped in useEffectEvent can't be called during rendering.", ); } return ref.impl.apply(undefined, arguments); }; } function updateEvent<Args, Return, F: (...Array<Args>) => Return>( callback: F, ): F { const hook = updateWorkInProgressHook(); const ref = hook.memoizedState; useEffectEventImpl({ref, nextImpl: callback}); // $FlowIgnore[incompatible-return] return function eventFn() { if (isInvalidExecutionContextForEventFunction()) { throw new Error( "A function wrapped in useEffectEvent can't be called during rendering.", ); } return ref.impl.apply(undefined, arguments); }; } function mountInsertionEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { mountEffectImpl(UpdateEffect, HookInsertion, create, deps); } function updateInsertionEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { return updateEffectImpl(UpdateEffect, HookInsertion, create, deps); } function mountLayoutEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { let fiberFlags: Flags = UpdateEffect | LayoutStaticEffect; if ( __DEV__ && (currentlyRenderingFiber.mode & StrictEffectsMode) !== NoMode ) { fiberFlags |= MountLayoutDevEffect; } return mountEffectImpl(fiberFlags, HookLayout, create, deps); } function updateLayoutEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { return updateEffectImpl(UpdateEffect, HookLayout, create, deps); } function imperativeHandleEffect<T>( create: () => T, ref: {current: T | null} | ((inst: T | null) => mixed) | null | void, ): void | (() => void) { if (typeof ref === 'function') { const refCallback = ref; const inst = create(); refCallback(inst); return () => { refCallback(null); }; } else if (ref !== null && ref !== undefined) { const refObject = ref; if (__DEV__) { if (!refObject.hasOwnProperty('current')) { console.error( 'Expected useImperativeHandle() first argument to either be a ' + 'ref callback or React.createRef() object. Instead received: %s.', 'an object with keys {' + Object.keys(refObject).join(', ') + '}', ); } } const inst = create(); refObject.current = inst; return () => { refObject.current = null; }; } } function mountImperativeHandle<T>( ref: {current: T | null} | ((inst: T | null) => mixed) | null | void, create: () => T, deps: Array<mixed> | void | null, ): void { if (__DEV__) { if (typeof create !== 'function') { console.error( 'Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null', ); } } // TODO: If deps are provided, should we skip comparing the ref itself? const effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; let fiberFlags: Flags = UpdateEffect | LayoutStaticEffect; if ( __DEV__ && (currentlyRenderingFiber.mode & StrictEffectsMode) !== NoMode ) { fiberFlags |= MountLayoutDevEffect; } mountEffectImpl( fiberFlags, HookLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps, ); } function updateImperativeHandle<T>( ref: {current: T | null} | ((inst: T | null) => mixed) | null | void, create: () => T, deps: Array<mixed> | void | null, ): void { if (__DEV__) { if (typeof create !== 'function') { console.error( 'Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null', ); } } // TODO: If deps are provided, should we skip comparing the ref itself? const effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; updateEffectImpl( UpdateEffect, HookLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps, ); } function mountDebugValue<T>(value: T, formatterFn: ?(value: T) => mixed): void { // This hook is normally a no-op. // The react-debug-hooks package injects its own implementation // so that e.g. DevTools can display custom hook values. } const updateDebugValue = mountDebugValue; function mountCallback<T>(callback: T, deps: Array<mixed> | void | null): T { const hook = mountWorkInProgressHook(); const nextDeps = deps === undefined ? null : deps; hook.memoizedState = [callback, nextDeps]; return callback; } function updateCallback<T>(callback: T, deps: Array<mixed> | void | null): T { const hook = updateWorkInProgressHook(); const nextDeps = deps === undefined ? null : deps; const prevState = hook.memoizedState; if (nextDeps !== null) { const prevDeps: Array<mixed> | null = prevState[1]; if (areHookInputsEqual(nextDeps, prevDeps)) { return prevState[0]; } } hook.memoizedState = [callback, nextDeps]; return callback; } function mountMemo<T>( nextCreate: () => T, deps: Array<mixed> | void | null, ): T { const hook = mountWorkInProgressHook(); const nextDeps = deps === undefined ? null : deps; if (shouldDoubleInvokeUserFnsInHooksDEV) { nextCreate(); } const nextValue = nextCreate(); hook.memoizedState = [nextValue, nextDeps]; return nextValue; } function updateMemo<T>( nextCreate: () => T, deps: Array<mixed> | void | null, ): T { const hook = updateWorkInProgressHook(); const nextDeps = deps === undefined ? null : deps; const prevState = hook.memoizedState; // Assume these are defined. If they're not, areHookInputsEqual will warn. if (nextDeps !== null) { const prevDeps: Array<mixed> | null = prevState[1]; if (areHookInputsEqual(nextDeps, prevDeps)) { return prevState[0]; } } if (shouldDoubleInvokeUserFnsInHooksDEV) { nextCreate(); } const nextValue = nextCreate(); hook.memoizedState = [nextValue, nextDeps]; return nextValue; } function mountDeferredValue<T>(value: T, initialValue?: T): T { const hook = mountWorkInProgressHook(); return mountDeferredValueImpl(hook, value, initialValue); } function updateDeferredValue<T>(value: T, initialValue?: T): T { const hook = updateWorkInProgressHook(); const resolvedCurrentHook: Hook = (currentHook: any); const prevValue: T = resolvedCurrentHook.memoizedState; return updateDeferredValueImpl(hook, prevValue, value, initialValue); } function rerenderDeferredValue<T>(value: T, initialValue?: T): T { const hook = updateWorkInProgressHook(); if (currentHook === null) { // This is a rerender during a mount. return mountDeferredValueImpl(hook, value, initialValue); } else { // This is a rerender during an update. const prevValue: T = currentHook.memoizedState; return updateDeferredValueImpl(hook, prevValue, value, initialValue); } } function mountDeferredValueImpl<T>(hook: Hook, value: T, initialValue?: T): T { if ( enableUseDeferredValueInitialArg && // When `initialValue` is provided, we defer the initial render even if the // current render is not synchronous. initialValue !== undefined && // However, to avoid waterfalls, we do not defer if this render // was itself spawned by an earlier useDeferredValue. Check if DeferredLane // is part of the render lanes. !includesSomeLane(renderLanes, DeferredLane) ) { // Render with the initial value hook.memoizedState = initialValue; // Schedule a deferred render to switch to the final value. const deferredLane = requestDeferredLane(); currentlyRenderingFiber.lanes = mergeLanes( currentlyRenderingFiber.lanes, deferredLane, ); markSkippedUpdateLanes(deferredLane); return initialValue; } else { hook.memoizedState = value; return value; } } function updateDeferredValueImpl<T>( hook: Hook, prevValue: T, value: T, initialValue?: T, ): T { if (is(value, prevValue)) { // The incoming value is referentially identical to the currently rendered // value, so we can bail out quickly. return value; } else { // Received a new value that's different from the current value. // Check if we're inside a hidden tree if (isCurrentTreeHidden()) { // Revealing a prerendered tree is considered the same as mounting new // one, so we reuse the "mount" path in this case. const resultValue = mountDeferredValueImpl(hook, value, initialValue); // Unlike during an actual mount, we need to mark this as an update if // the value changed. if (!is(resultValue, prevValue)) { markWorkInProgressReceivedUpdate(); } return resultValue; } const shouldDeferValue = !includesOnlyNonUrgentLanes(renderLanes); if (shouldDeferValue) { // This is an urgent update. Since the value has changed, keep using the // previous value and spawn a deferred render to update it later. // Schedule a deferred render const deferredLane = requestDeferredLane(); currentlyRenderingFiber.lanes = mergeLanes( currentlyRenderingFiber.lanes, deferredLane, ); markSkippedUpdateLanes(deferredLane); // Reuse the previous value. We do not need to mark this as an update, // because we did not render a new value. return prevValue; } else { // This is not an urgent update, so we can use the latest value regardless // of what it is. No need to defer it. // Mark this as an update to prevent the fiber from bailing out. markWorkInProgressReceivedUpdate(); hook.memoizedState = value; return value; } } } function startTransition<S>( fiber: Fiber, queue: UpdateQueue<S | Thenable<S>, BasicStateAction<S | Thenable<S>>>, pendingState: S, finishedState: S, callback: () => mixed, options?: StartTransitionOptions, ): void { const previousPriority = getCurrentUpdatePriority(); setCurrentUpdatePriority( higherEventPriority(previousPriority, ContinuousEventPriority), ); const prevTransition = ReactCurrentBatchConfig.transition; const currentTransition: BatchConfigTransition = {}; if (enableAsyncActions) { // We don't really need to use an optimistic update here, because we // schedule a second "revert" update below (which we use to suspend the // transition until the async action scope has finished). But we'll use an // optimistic update anyway to make it less likely the behavior accidentally // diverges; for example, both an optimistic update and this one should // share the same lane. ReactCurrentBatchConfig.transition = currentTransition; dispatchOptimisticSetState(fiber, false, queue, pendingState); } else { ReactCurrentBatchConfig.transition = null; dispatchSetState(fiber, queue, pendingState); ReactCurrentBatchConfig.transition = currentTransition; } if (enableTransitionTracing) { if (options !== undefined && options.name !== undefined) { ReactCurrentBatchConfig.transition.name = options.name; ReactCurrentBatchConfig.transition.startTime = now(); } } if (__DEV__) { ReactCurrentBatchConfig.transition._updatedFibers = new Set(); } try { if (enableAsyncActions) { const returnValue = callback(); // Check if we're inside an async action scope. If so, we'll entangle // this new action with the existing scope. // // If we're not already inside an async action scope, and this action is // async, then we'll create a new async scope. // // In the async case, the resulting render will suspend until the async // action scope has finished. if ( returnValue !== null && typeof returnValue === 'object' && typeof returnValue.then === 'function' ) { const thenable = ((returnValue: any): Thenable<mixed>); // This is a thenable that resolves to `finishedState` once the async // action scope has finished. const entangledResult = requestAsyncActionContext( thenable, finishedState, ); dispatchSetState(fiber, queue, entangledResult); } else { // This is either `finishedState` or a thenable that resolves to // `finishedState`, depending on whether we're inside an async // action scope. const entangledResult = requestSyncActionContext( returnValue, finishedState, ); dispatchSetState(fiber, queue, entangledResult); } } else { // Async actions are not enabled. dispatchSetState(fiber, queue, finishedState); callback(); } } catch (error) { if (enableAsyncActions) { // This is a trick to get the `useTransition` hook to rethrow the error. // When it unwraps the thenable with the `use` algorithm, the error // will be thrown. const rejectedThenable: RejectedThenable<S> = { then() {}, status: 'rejected', reason: error, }; dispatchSetState(fiber, queue, rejectedThenable); } else { // The error rethrowing behavior is only enabled when the async actions // feature is on, even for sync actions. throw error; } } finally { setCurrentUpdatePriority(previousPriority); ReactCurrentBatchConfig.transition = prevTransition; if (__DEV__) { if (prevTransition === null && currentTransition._updatedFibers) { const updatedFibersCount = currentTransition._updatedFibers.size; currentTransition._updatedFibers.clear(); if (updatedFibersCount > 10) { console.warn( 'Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.', ); } } } } } export function startHostTransition<F>( formFiber: Fiber, pendingState: TransitionStatus, callback: F => mixed, formData: F, ): void { if (!enableFormActions) { // Not implemented. return; } if (!enableAsyncActions) { // Form actions are enabled, but async actions are not. Call the function, // but don't handle any pending or error states. callback(formData); return; } if (formFiber.tag !== HostComponent) { throw new Error( 'Expected the form instance to be a HostComponent. This ' + 'is a bug in React.', ); } let queue: UpdateQueue< Thenable<TransitionStatus> | TransitionStatus, BasicStateAction<Thenable<TransitionStatus> | TransitionStatus>, >; if (formFiber.memoizedState === null) { // Upgrade this host component fiber to be stateful. We're going to pretend // it was stateful all along so we can reuse most of the implementation // for function components and useTransition. // // Create the state hook used by TransitionAwareHostComponent. This is // essentially an inlined version of mountState. const newQueue: UpdateQueue< Thenable<TransitionStatus> | TransitionStatus, BasicStateAction<Thenable<TransitionStatus> | TransitionStatus>, > = { pending: null, lanes: NoLanes, // We're going to cheat and intentionally not create a bound dispatch // method, because we can call it directly in startTransition. dispatch: (null: any), lastRenderedReducer: basicStateReducer, lastRenderedState: NoPendingHostTransition, }; queue = newQueue; const stateHook: Hook = { memoizedState: NoPendingHostTransition, baseState: NoPendingHostTransition, baseQueue: null, queue: newQueue, next: null, }; // Add the state hook to both fiber alternates. The idea is that the fiber // had this hook all along. formFiber.memoizedState = stateHook; const alternate = formFiber.alternate; if (alternate !== null) { alternate.memoizedState = stateHook; } } else { // This fiber was already upgraded to be stateful. const stateHook: Hook = formFiber.memoizedState; queue = stateHook.queue; } startTransition( formFiber, queue, pendingState, NoPendingHostTransition, // TODO: We can avoid this extra wrapper, somehow. Figure out layering // once more of this function is implemented. () => callback(formData), ); } function mountTransition(): [ boolean, (callback: () => void, options?: StartTransitionOptions) => void, ] { const stateHook = mountStateImpl((false: Thenable<boolean> | boolean)); // The `start` method never changes. const start = startTransition.bind( null, currentlyRenderingFiber, stateHook.queue, true, false, ); const hook = mountWorkInProgressHook(); hook.memoizedState = start; return [false, start]; } function updateTransition(): [ boolean, (callback: () => void, options?: StartTransitionOptions) => void, ] { const [booleanOrThenable] = updateState(false); const hook = updateWorkInProgressHook(); const start = hook.memoizedState; const isPending = typeof booleanOrThenable === 'boolean' ? booleanOrThenable : // This will suspend until the async action scope has finished. useThenable(booleanOrThenable); return [isPending, start]; } function rerenderTransition(): [ boolean, (callback: () => void, options?: StartTransitionOptions) => void, ] { const [booleanOrThenable] = rerenderState(false); const hook = updateWorkInProgressHook(); const start = hook.memoizedState; const isPending = typeof booleanOrThenable === 'boolean' ? booleanOrThenable : // This will suspend until the async action scope has finished. useThenable(booleanOrThenable); return [isPending, start]; } function useHostTransitionStatus(): TransitionStatus { if (!(enableFormActions && enableAsyncActions)) { throw new Error('Not implemented.'); } const status: TransitionStatus | null = readContext(HostTransitionContext); return status !== null ? status : NoPendingHostTransition; } function mountId(): string { const hook = mountWorkInProgressHook(); const root = ((getWorkInProgressRoot(): any): FiberRoot); // TODO: In Fizz, id generation is specific to each server config. Maybe we // should do this in Fiber, too? Deferring this decision for now because // there's no other place to store the prefix except for an internal field on // the public createRoot object, which the fiber tree does not currently have // a reference to. const identifierPrefix = root.identifierPrefix; let id; if (getIsHydrating()) { const treeId = getTreeId(); // Use a captial R prefix for server-generated ids. id = ':' + identifierPrefix + 'R' + treeId; // Unless this is the first id at this level, append a number at the end // that represents the position of this useId hook among all the useId // hooks for this fiber. const localId = localIdCounter++; if (localId > 0) { id += 'H' + localId.toString(32); } id += ':'; } else { // Use a lowercase r prefix for client-generated ids. const globalClientId = globalClientIdCounter++; id = ':' + identifierPrefix + 'r' + globalClientId.toString(32) + ':'; } hook.memoizedState = id; return id; } function updateId(): string { const hook = updateWorkInProgressHook(); const id: string = hook.memoizedState; return id; } function mountRefresh(): any { const hook = mountWorkInProgressHook(); const refresh = (hook.memoizedState = refreshCache.bind( null, currentlyRenderingFiber, )); return refresh; } function updateRefresh(): any { const hook = updateWorkInProgressHook(); return hook.memoizedState; } function refreshCache<T>(fiber: Fiber, seedKey: ?() => T, seedValue: T): void { if (!enableCache) { return; } // TODO: Does Cache work in legacy mode? Should decide and write a test. // TODO: Consider warning if the refresh is at discrete priority, or if we // otherwise suspect that it wasn't batched properly. let provider = fiber.return; while (provider !== null) { switch (provider.tag) { case CacheComponent: case HostRoot: { // Schedule an update on the cache boundary to trigger a refresh. const lane = requestUpdateLane(provider); const refreshUpdate = createLegacyQueueUpdate(lane); const root = enqueueLegacyQueueUpdate(provider, refreshUpdate, lane); if (root !== null) { scheduleUpdateOnFiber(root, provider, lane); entangleLegacyQueueTransitions(root, provider, lane); } // TODO: If a refresh never commits, the new cache created here must be // released. A simple case is start refreshing a cache boundary, but then // unmount that boundary before the refresh completes. const seededCache = createCache(); if (seedKey !== null && seedKey !== undefined && root !== null) { if (enableLegacyCache) { // Seed the cache with the value passed by the caller. This could be // from a server mutation, or it could be a streaming response. seededCache.data.set(seedKey, seedValue); } else { if (__DEV__) { console.error( 'The seed argument is not enabled outside experimental channels.', ); } } } const payload = { cache: seededCache, }; refreshUpdate.payload = payload; return; } } provider = provider.return; } // TODO: Warn if unmounted? } function dispatchReducerAction<S, A>( fiber: Fiber, queue: UpdateQueue<S, A>, action: A, ): void { if (__DEV__) { if (typeof arguments[3] === 'function') { console.error( "State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().', ); } } const lane = requestUpdateLane(fiber); const update: Update<S, A> = { lane, revertLane: NoLane, action, hasEagerState: false, eagerState: null, next: (null: any), }; if (isRenderPhaseUpdate(fiber)) { enqueueRenderPhaseUpdate(queue, update); } else { const root = enqueueConcurrentHookUpdate(fiber, queue, update, lane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, lane); entangleTransitionUpdate(root, queue, lane); } } markUpdateInDevTools(fiber, lane, action); } function dispatchSetState<S, A>( fiber: Fiber, queue: UpdateQueue<S, A>, action: A, ): void { if (__DEV__) { if (typeof arguments[3] === 'function') { console.error( "State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().', ); } } const lane = requestUpdateLane(fiber); const update: Update<S, A> = { lane, revertLane: NoLane, action, hasEagerState: false, eagerState: null, next: (null: any), }; if (isRenderPhaseUpdate(fiber)) { enqueueRenderPhaseUpdate(queue, update); } else { const alternate = fiber.alternate; if ( fiber.lanes === NoLanes && (alternate === null || alternate.lanes === NoLanes) ) { // The queue is currently empty, which means we can eagerly compute the // next state before entering the render phase. If the new state is the // same as the current state, we may be able to bail out entirely. const lastRenderedReducer = queue.lastRenderedReducer; if (lastRenderedReducer !== null) { let prevDispatcher; if (__DEV__) { prevDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV; } try { const currentState: S = (queue.lastRenderedState: any); const eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute // it, on the update object. If the reducer hasn't changed by the // time we enter the render phase, then the eager state can be used // without calling the reducer again. update.hasEagerState = true; update.eagerState = eagerState; if (is(eagerState, currentState)) { // Fast path. We can bail out without scheduling React to re-render. // It's still possible that we'll need to rebase this update later, // if the component re-renders for a different reason and by that // time the reducer has changed. // TODO: Do we still need to entangle transitions in this case? enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue, update); return; } } catch (error) { // Suppress the error. It will throw again in the render phase. } finally { if (__DEV__) { ReactCurrentDispatcher.current = prevDispatcher; } } } } const root = enqueueConcurrentHookUpdate(fiber, queue, update, lane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, lane); entangleTransitionUpdate(root, queue, lane); } } markUpdateInDevTools(fiber, lane, action); } function dispatchOptimisticSetState<S, A>( fiber: Fiber, throwIfDuringRender: boolean, queue: UpdateQueue<S, A>, action: A, ): void { if (__DEV__) { if (ReactCurrentBatchConfig.transition === null) { // An optimistic update occurred, but startTransition is not on the stack. // There are two likely scenarios. // One possibility is that the optimistic update is triggered by a regular // event handler (e.g. `onSubmit`) instead of an action. This is a mistake // and we will warn. // The other possibility is the optimistic update is inside an async // action, but after an `await`. In this case, we can make it "just work" // by associating the optimistic update with the pending async action. // Technically it's possible that the optimistic update is unrelated to // the pending action, but we don't have a way of knowing this for sure // because browsers currently do not provide a way to track async scope. // (The AsyncContext proposal, if it lands, will solve this in the // future.) However, this is no different than the problem of unrelated // transitions being grouped together — it's not wrong per se, but it's // not ideal. // Once AsyncContext starts landing in browsers, we will provide better // warnings in development for these cases. if (peekEntangledActionLane() !== NoLane) { // There is a pending async action. Don't warn. } else { // There's no pending async action. The most likely cause is that we're // inside a regular event handler (e.g. onSubmit) instead of an action. console.error( 'An optimistic state update occurred outside a transition or ' + 'action. To fix, move the update to an action, or wrap ' + 'with startTransition.', ); } } } const update: Update<S, A> = { // An optimistic update commits synchronously. lane: SyncLane, // After committing, the optimistic update is "reverted" using the same // lane as the transition it's associated with. revertLane: requestTransitionLane(), action, hasEagerState: false, eagerState: null, next: (null: any), }; if (isRenderPhaseUpdate(fiber)) { // When calling startTransition during render, this warns instead of // throwing because throwing would be a breaking change. setOptimisticState // is a new API so it's OK to throw. if (throwIfDuringRender) { throw new Error('Cannot update optimistic state while rendering.'); } else { // startTransition was called during render. We don't need to do anything // besides warn here because the render phase update would be overidden by // the second update, anyway. We can remove this branch and make it throw // in a future release. if (__DEV__) { console.error('Cannot call startTransition while rendering.'); } } } else { const root = enqueueConcurrentHookUpdate(fiber, queue, update, SyncLane); if (root !== null) { // NOTE: The optimistic update implementation assumes that the transition // will never be attempted before the optimistic update. This currently // holds because the optimistic update is always synchronous. If we ever // change that, we'll need to account for this. scheduleUpdateOnFiber(root, fiber, SyncLane); // Optimistic updates are always synchronous, so we don't need to call // entangleTransitionUpdate here. } } markUpdateInDevTools(fiber, SyncLane, action); } function isRenderPhaseUpdate(fiber: Fiber): boolean { const alternate = fiber.alternate; return ( fiber === currentlyRenderingFiber || (alternate !== null && alternate === currentlyRenderingFiber) ); } function enqueueRenderPhaseUpdate<S, A>( queue: UpdateQueue<S, A>, update: Update<S, A>, ): void { // 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. didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true; const pending = queue.pending; if (pending === null) { // This is the first update. Create a circular list. update.next = update; } else { update.next = pending.next; pending.next = update; } queue.pending = update; } // TODO: Move to ReactFiberConcurrentUpdates? function entangleTransitionUpdate<S, A>( root: FiberRoot, queue: UpdateQueue<S, A>, lane: Lane, ): void { if (isTransitionLane(lane)) { let queueLanes = queue.lanes; // If any entangled lanes are no longer pending on the root, then they // must have finished. We can remove them from the shared queue, which // represents a superset of the actually pending lanes. In some cases we // may entangle more than we need to, but that's OK. In fact it's worse if // we *don't* entangle when we should. queueLanes = intersectLanes(queueLanes, root.pendingLanes); // Entangle the new transition lane with the other transition lanes. const newQueueLanes = mergeLanes(queueLanes, lane); queue.lanes = newQueueLanes; // Even if queue.lanes already include lane, we don't know for certain if // the lane finished since the last time we entangled it. So we need to // entangle it again, just to be sure. markRootEntangled(root, newQueueLanes); } } function markUpdateInDevTools<A>(fiber: Fiber, lane: Lane, action: A): void { if (__DEV__) { if (enableDebugTracing) { if (fiber.mode & DebugTracingMode) { const name = getComponentNameFromFiber(fiber) || 'Unknown'; logStateUpdateScheduled(name, lane, action); } } } if (enableSchedulingProfiler) { markStateUpdateScheduled(fiber, lane); } } export const ContextOnlyDispatcher: Dispatcher = { readContext, use, useCallback: throwInvalidHookError, useContext: throwInvalidHookError, useEffect: throwInvalidHookError, useImperativeHandle: throwInvalidHookError, useInsertionEffect: throwInvalidHookError, useLayoutEffect: throwInvalidHookError, useMemo: throwInvalidHookError, useReducer: throwInvalidHookError, useRef: throwInvalidHookError, useState: throwInvalidHookError, useDebugValue: throwInvalidHookError, useDeferredValue: throwInvalidHookError, useTransition: throwInvalidHookError, useSyncExternalStore: throwInvalidHookError, useId: throwInvalidHookError, }; if (enableCache) { (ContextOnlyDispatcher: Dispatcher).useCacheRefresh = throwInvalidHookError; } if (enableUseMemoCacheHook) { (ContextOnlyDispatcher: Dispatcher).useMemoCache = throwInvalidHookError; } if (enableUseEffectEventHook) { (ContextOnlyDispatcher: Dispatcher).useEffectEvent = throwInvalidHookError; } if (enableFormActions && enableAsyncActions) { (ContextOnlyDispatcher: Dispatcher).useHostTransitionStatus = throwInvalidHookError; (ContextOnlyDispatcher: Dispatcher).useFormState = throwInvalidHookError; } if (enableAsyncActions) { (ContextOnlyDispatcher: Dispatcher).useOptimistic = throwInvalidHookError; } const HooksDispatcherOnMount: Dispatcher = { readContext, use, useCallback: mountCallback, useContext: readContext, useEffect: mountEffect, useImperativeHandle: mountImperativeHandle, useLayoutEffect: mountLayoutEffect, useInsertionEffect: mountInsertionEffect, useMemo: mountMemo, useReducer: mountReducer, useRef: mountRef, useState: mountState, useDebugValue: mountDebugValue, useDeferredValue: mountDeferredValue, useTransition: mountTransition, useSyncExternalStore: mountSyncExternalStore, useId: mountId, }; if (enableCache) { (HooksDispatcherOnMount: Dispatcher).useCacheRefresh = mountRefresh; } if (enableUseMemoCacheHook) { (HooksDispatcherOnMount: Dispatcher).useMemoCache = useMemoCache; } if (enableUseEffectEventHook) { (HooksDispatcherOnMount: Dispatcher).useEffectEvent = mountEvent; } if (enableFormActions && enableAsyncActions) { (HooksDispatcherOnMount: Dispatcher).useHostTransitionStatus = useHostTransitionStatus; (HooksDispatcherOnMount: Dispatcher).useFormState = mountFormState; } if (enableAsyncActions) { (HooksDispatcherOnMount: Dispatcher).useOptimistic = mountOptimistic; } const HooksDispatcherOnUpdate: Dispatcher = { readContext, use, useCallback: updateCallback, useContext: readContext, useEffect: updateEffect, useImperativeHandle: updateImperativeHandle, useInsertionEffect: updateInsertionEffect, useLayoutEffect: updateLayoutEffect, useMemo: updateMemo, useReducer: updateReducer, useRef: updateRef, useState: updateState, useDebugValue: updateDebugValue, useDeferredValue: updateDeferredValue, useTransition: updateTransition, useSyncExternalStore: updateSyncExternalStore, useId: updateId, }; if (enableCache) { (HooksDispatcherOnUpdate: Dispatcher).useCacheRefresh = updateRefresh; } if (enableUseMemoCacheHook) { (HooksDispatcherOnUpdate: Dispatcher).useMemoCache = useMemoCache; } if (enableUseEffectEventHook) { (HooksDispatcherOnUpdate: Dispatcher).useEffectEvent = updateEvent; } if (enableFormActions && enableAsyncActions) { (HooksDispatcherOnUpdate: Dispatcher).useHostTransitionStatus = useHostTransitionStatus; (HooksDispatcherOnUpdate: Dispatcher).useFormState = updateFormState; } if (enableAsyncActions) { (HooksDispatcherOnUpdate: Dispatcher).useOptimistic = updateOptimistic; } const HooksDispatcherOnRerender: Dispatcher = { readContext, use, useCallback: updateCallback, useContext: readContext, useEffect: updateEffect, useImperativeHandle: updateImperativeHandle, useInsertionEffect: updateInsertionEffect, useLayoutEffect: updateLayoutEffect, useMemo: updateMemo, useReducer: rerenderReducer, useRef: updateRef, useState: rerenderState, useDebugValue: updateDebugValue, useDeferredValue: rerenderDeferredValue, useTransition: rerenderTransition, useSyncExternalStore: updateSyncExternalStore, useId: updateId, }; if (enableCache) { (HooksDispatcherOnRerender: Dispatcher).useCacheRefresh = updateRefresh; } if (enableUseMemoCacheHook) { (HooksDispatcherOnRerender: Dispatcher).useMemoCache = useMemoCache; } if (enableUseEffectEventHook) { (HooksDispatcherOnRerender: Dispatcher).useEffectEvent = updateEvent; } if (enableFormActions && enableAsyncActions) { (HooksDispatcherOnRerender: Dispatcher).useHostTransitionStatus = useHostTransitionStatus; (HooksDispatcherOnRerender: Dispatcher).useFormState = rerenderFormState; } if (enableAsyncActions) { (HooksDispatcherOnRerender: Dispatcher).useOptimistic = rerenderOptimistic; } let HooksDispatcherOnMountInDEV: Dispatcher | null = null; let HooksDispatcherOnMountWithHookTypesInDEV: Dispatcher | null = null; let HooksDispatcherOnUpdateInDEV: Dispatcher | null = null; let HooksDispatcherOnRerenderInDEV: Dispatcher | null = null; let InvalidNestedHooksDispatcherOnMountInDEV: Dispatcher | null = null; let InvalidNestedHooksDispatcherOnUpdateInDEV: Dispatcher | null = null; let InvalidNestedHooksDispatcherOnRerenderInDEV: Dispatcher | null = null; if (__DEV__) { const warnInvalidContextAccess = () => { console.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().', ); }; const warnInvalidHookAccess = () => { console.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', ); }; HooksDispatcherOnMountInDEV = { readContext<T>(context: ReactContext<T>): T { return readContext(context); }, use, useCallback<T>(callback: T, deps: Array<mixed> | void | null): T { currentHookNameInDev = 'useCallback'; mountHookTypesDev(); checkDepsAreArrayDev(deps); return mountCallback(callback, deps); }, useContext<T>(context: ReactContext<T>): T { currentHookNameInDev = 'useContext'; mountHookTypesDev(); return readContext(context); }, useEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useEffect'; mountHookTypesDev(); checkDepsAreArrayDev(deps); return mountEffect(create, deps); }, useImperativeHandle<T>( ref: {current: T | null} | ((inst: T | null) => mixed) | null | void, create: () => T, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useImperativeHandle'; mountHookTypesDev(); checkDepsAreArrayDev(deps); return mountImperativeHandle(ref, create, deps); }, useInsertionEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useInsertionEffect'; mountHookTypesDev(); checkDepsAreArrayDev(deps); return mountInsertionEffect(create, deps); }, useLayoutEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useLayoutEffect'; mountHookTypesDev(); checkDepsAreArrayDev(deps); return mountLayoutEffect(create, deps); }, useMemo<T>(create: () => T, deps: Array<mixed> | void | null): T { currentHookNameInDev = 'useMemo'; mountHookTypesDev(); checkDepsAreArrayDev(deps); const prevDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountMemo(create, deps); } finally { ReactCurrentDispatcher.current = prevDispatcher; } }, useReducer<S, I, A>( reducer: (S, A) => S, initialArg: I, init?: I => S, ): [S, Dispatch<A>] { currentHookNameInDev = 'useReducer'; mountHookTypesDev(); const prevDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher.current = prevDispatcher; } }, useRef<T>(initialValue: T): {current: T} { currentHookNameInDev = 'useRef'; mountHookTypesDev(); return mountRef(initialValue); }, useState<S>( initialState: (() => S) | S, ): [S, Dispatch<BasicStateAction<S>>] { currentHookNameInDev = 'useState'; mountHookTypesDev(); const prevDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountState(initialState); } finally { ReactCurrentDispatcher.current = prevDispatcher; } }, useDebugValue<T>(value: T, formatterFn: ?(value: T) => mixed): void { currentHookNameInDev = 'useDebugValue'; mountHookTypesDev(); return mountDebugValue(value, formatterFn); }, useDeferredValue<T>(value: T, initialValue?: T): T { currentHookNameInDev = 'useDeferredValue'; mountHookTypesDev(); return mountDeferredValue(value, initialValue); }, useTransition(): [boolean, (() => void) => void] { currentHookNameInDev = 'useTransition'; mountHookTypesDev(); return mountTransition(); }, useSyncExternalStore<T>( subscribe: (() => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T, ): T { currentHookNameInDev = 'useSyncExternalStore'; mountHookTypesDev(); return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); }, useId(): string { currentHookNameInDev = 'useId'; mountHookTypesDev(); return mountId(); }, }; if (enableCache) { (HooksDispatcherOnMountInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() { currentHookNameInDev = 'useCacheRefresh'; mountHookTypesDev(); return mountRefresh(); }; } if (enableUseMemoCacheHook) { (HooksDispatcherOnMountInDEV: Dispatcher).useMemoCache = useMemoCache; } if (enableUseEffectEventHook) { (HooksDispatcherOnMountInDEV: Dispatcher).useEffectEvent = function useEffectEvent<Args, Return, F: (...Array<Args>) => Return>( callback: F, ): F { currentHookNameInDev = 'useEffectEvent'; mountHookTypesDev(); return mountEvent(callback); }; } if (enableFormActions && enableAsyncActions) { (HooksDispatcherOnMountInDEV: Dispatcher).useHostTransitionStatus = useHostTransitionStatus; (HooksDispatcherOnMountInDEV: Dispatcher).useFormState = function useFormState<S, P>( action: (Awaited<S>, P) => S, initialState: Awaited<S>, permalink?: string, ): [Awaited<S>, (P) => void] { currentHookNameInDev = 'useFormState'; mountHookTypesDev(); return mountFormState(action, initialState, permalink); }; } if (enableAsyncActions) { (HooksDispatcherOnMountInDEV: Dispatcher).useOptimistic = function useOptimistic<S, A>( passthrough: S, reducer: ?(S, A) => S, ): [S, (A) => void] { currentHookNameInDev = 'useOptimistic'; mountHookTypesDev(); return mountOptimistic(passthrough, reducer); }; } HooksDispatcherOnMountWithHookTypesInDEV = { readContext<T>(context: ReactContext<T>): T { return readContext(context); }, use, useCallback<T>(callback: T, deps: Array<mixed> | void | null): T { currentHookNameInDev = 'useCallback'; updateHookTypesDev(); return mountCallback(callback, deps); }, useContext<T>(context: ReactContext<T>): T { currentHookNameInDev = 'useContext'; updateHookTypesDev(); return readContext(context); }, useEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useEffect'; updateHookTypesDev(); return mountEffect(create, deps); }, useImperativeHandle<T>( ref: {current: T | null} | ((inst: T | null) => mixed) | null | void, create: () => T, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useImperativeHandle'; updateHookTypesDev(); return mountImperativeHandle(ref, create, deps); }, useInsertionEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useInsertionEffect'; updateHookTypesDev(); return mountInsertionEffect(create, deps); }, useLayoutEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useLayoutEffect'; updateHookTypesDev(); return mountLayoutEffect(create, deps); }, useMemo<T>(create: () => T, deps: Array<mixed> | void | null): T { currentHookNameInDev = 'useMemo'; updateHookTypesDev(); const prevDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountMemo(create, deps); } finally { ReactCurrentDispatcher.current = prevDispatcher; } }, useReducer<S, I, A>( reducer: (S, A) => S, initialArg: I, init?: I => S, ): [S, Dispatch<A>] { currentHookNameInDev = 'useReducer'; updateHookTypesDev(); const prevDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher.current = prevDispatcher; } }, useRef<T>(initialValue: T): {current: T} { currentHookNameInDev = 'useRef'; updateHookTypesDev(); return mountRef(initialValue); }, useState<S>( initialState: (() => S) | S, ): [S, Dispatch<BasicStateAction<S>>] { currentHookNameInDev = 'useState'; updateHookTypesDev(); const prevDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountState(initialState); } finally { ReactCurrentDispatcher.current = prevDispatcher; } }, useDebugValue<T>(value: T, formatterFn: ?(value: T) => mixed): void { currentHookNameInDev = 'useDebugValue'; updateHookTypesDev(); return mountDebugValue(value, formatterFn); }, useDeferredValue<T>(value: T, initialValue?: T): T { currentHookNameInDev = 'useDeferredValue'; updateHookTypesDev(); return mountDeferredValue(value, initialValue); }, useTransition(): [boolean, (() => void) => void] { currentHookNameInDev = 'useTransition'; updateHookTypesDev(); return mountTransition(); }, useSyncExternalStore<T>( subscribe: (() => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T, ): T { currentHookNameInDev = 'useSyncExternalStore'; updateHookTypesDev(); return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); }, useId(): string { currentHookNameInDev = 'useId'; updateHookTypesDev(); return mountId(); }, }; if (enableCache) { (HooksDispatcherOnMountWithHookTypesInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() { currentHookNameInDev = 'useCacheRefresh'; updateHookTypesDev(); return mountRefresh(); }; } if (enableUseMemoCacheHook) { (HooksDispatcherOnMountWithHookTypesInDEV: Dispatcher).useMemoCache = useMemoCache; } if (enableUseEffectEventHook) { (HooksDispatcherOnMountWithHookTypesInDEV: Dispatcher).useEffectEvent = function useEffectEvent<Args, Return, F: (...Array<Args>) => Return>( callback: F, ): F { currentHookNameInDev = 'useEffectEvent'; updateHookTypesDev(); return mountEvent(callback); }; } if (enableFormActions && enableAsyncActions) { (HooksDispatcherOnMountWithHookTypesInDEV: Dispatcher).useHostTransitionStatus = useHostTransitionStatus; (HooksDispatcherOnMountWithHookTypesInDEV: Dispatcher).useFormState = function useFormState<S, P>( action: (Awaited<S>, P) => S, initialState: Awaited<S>, permalink?: string, ): [Awaited<S>, (P) => void] { currentHookNameInDev = 'useFormState'; updateHookTypesDev(); return mountFormState(action, initialState, permalink); }; } if (enableAsyncActions) { (HooksDispatcherOnMountWithHookTypesInDEV: Dispatcher).useOptimistic = function useOptimistic<S, A>( passthrough: S, reducer: ?(S, A) => S, ): [S, (A) => void] { currentHookNameInDev = 'useOptimistic'; updateHookTypesDev(); return mountOptimistic(passthrough, reducer); }; } HooksDispatcherOnUpdateInDEV = { readContext<T>(context: ReactContext<T>): T { return readContext(context); }, use, useCallback<T>(callback: T, deps: Array<mixed> | void | null): T { currentHookNameInDev = 'useCallback'; updateHookTypesDev(); return updateCallback(callback, deps); }, useContext<T>(context: ReactContext<T>): T { currentHookNameInDev = 'useContext'; updateHookTypesDev(); return readContext(context); }, useEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useEffect'; updateHookTypesDev(); return updateEffect(create, deps); }, useImperativeHandle<T>( ref: {current: T | null} | ((inst: T | null) => mixed) | null | void, create: () => T, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useImperativeHandle'; updateHookTypesDev(); return updateImperativeHandle(ref, create, deps); }, useInsertionEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useInsertionEffect'; updateHookTypesDev(); return updateInsertionEffect(create, deps); }, useLayoutEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useLayoutEffect'; updateHookTypesDev(); return updateLayoutEffect(create, deps); }, useMemo<T>(create: () => T, deps: Array<mixed> | void | null): T { currentHookNameInDev = 'useMemo'; updateHookTypesDev(); const prevDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateMemo(create, deps); } finally { ReactCurrentDispatcher.current = prevDispatcher; } }, useReducer<S, I, A>( reducer: (S, A) => S, initialArg: I, init?: I => S, ): [S, Dispatch<A>] { currentHookNameInDev = 'useReducer'; updateHookTypesDev(); const prevDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher.current = prevDispatcher; } }, useRef<T>(initialValue: T): {current: T} { currentHookNameInDev = 'useRef'; updateHookTypesDev(); return updateRef(initialValue); }, useState<S>( initialState: (() => S) | S, ): [S, Dispatch<BasicStateAction<S>>] { currentHookNameInDev = 'useState'; updateHookTypesDev(); const prevDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateState(initialState); } finally { ReactCurrentDispatcher.current = prevDispatcher; } }, useDebugValue<T>(value: T, formatterFn: ?(value: T) => mixed): void { currentHookNameInDev = 'useDebugValue'; updateHookTypesDev(); return updateDebugValue(value, formatterFn); }, useDeferredValue<T>(value: T, initialValue?: T): T { currentHookNameInDev = 'useDeferredValue'; updateHookTypesDev(); return updateDeferredValue(value, initialValue); }, useTransition(): [boolean, (() => void) => void] { currentHookNameInDev = 'useTransition'; updateHookTypesDev(); return updateTransition(); }, useSyncExternalStore<T>( subscribe: (() => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T, ): T { currentHookNameInDev = 'useSyncExternalStore'; updateHookTypesDev(); return updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); }, useId(): string { currentHookNameInDev = 'useId'; updateHookTypesDev(); return updateId(); }, }; if (enableCache) { (HooksDispatcherOnUpdateInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() { currentHookNameInDev = 'useCacheRefresh'; updateHookTypesDev(); return updateRefresh(); }; } if (enableUseMemoCacheHook) { (HooksDispatcherOnUpdateInDEV: Dispatcher).useMemoCache = useMemoCache; } if (enableUseEffectEventHook) { (HooksDispatcherOnUpdateInDEV: Dispatcher).useEffectEvent = function useEffectEvent<Args, Return, F: (...Array<Args>) => Return>( callback: F, ): F { currentHookNameInDev = 'useEffectEvent'; updateHookTypesDev(); return updateEvent(callback); }; } if (enableFormActions && enableAsyncActions) { (HooksDispatcherOnUpdateInDEV: Dispatcher).useHostTransitionStatus = useHostTransitionStatus; (HooksDispatcherOnUpdateInDEV: Dispatcher).useFormState = function useFormState<S, P>( action: (Awaited<S>, P) => S, initialState: Awaited<S>, permalink?: string, ): [Awaited<S>, (P) => void] { currentHookNameInDev = 'useFormState'; updateHookTypesDev(); return updateFormState(action, initialState, permalink); }; } if (enableAsyncActions) { (HooksDispatcherOnUpdateInDEV: Dispatcher).useOptimistic = function useOptimistic<S, A>( passthrough: S, reducer: ?(S, A) => S, ): [S, (A) => void] { currentHookNameInDev = 'useOptimistic'; updateHookTypesDev(); return updateOptimistic(passthrough, reducer); }; } HooksDispatcherOnRerenderInDEV = { readContext<T>(context: ReactContext<T>): T { return readContext(context); }, use, useCallback<T>(callback: T, deps: Array<mixed> | void | null): T { currentHookNameInDev = 'useCallback'; updateHookTypesDev(); return updateCallback(callback, deps); }, useContext<T>(context: ReactContext<T>): T { currentHookNameInDev = 'useContext'; updateHookTypesDev(); return readContext(context); }, useEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useEffect'; updateHookTypesDev(); return updateEffect(create, deps); }, useImperativeHandle<T>( ref: {current: T | null} | ((inst: T | null) => mixed) | null | void, create: () => T, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useImperativeHandle'; updateHookTypesDev(); return updateImperativeHandle(ref, create, deps); }, useInsertionEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useInsertionEffect'; updateHookTypesDev(); return updateInsertionEffect(create, deps); }, useLayoutEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useLayoutEffect'; updateHookTypesDev(); return updateLayoutEffect(create, deps); }, useMemo<T>(create: () => T, deps: Array<mixed> | void | null): T { currentHookNameInDev = 'useMemo'; updateHookTypesDev(); const prevDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnRerenderInDEV; try { return updateMemo(create, deps); } finally { ReactCurrentDispatcher.current = prevDispatcher; } }, useReducer<S, I, A>( reducer: (S, A) => S, initialArg: I, init?: I => S, ): [S, Dispatch<A>] { currentHookNameInDev = 'useReducer'; updateHookTypesDev(); const prevDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnRerenderInDEV; try { return rerenderReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher.current = prevDispatcher; } }, useRef<T>(initialValue: T): {current: T} { currentHookNameInDev = 'useRef'; updateHookTypesDev(); return updateRef(initialValue); }, useState<S>( initialState: (() => S) | S, ): [S, Dispatch<BasicStateAction<S>>] { currentHookNameInDev = 'useState'; updateHookTypesDev(); const prevDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnRerenderInDEV; try { return rerenderState(initialState); } finally { ReactCurrentDispatcher.current = prevDispatcher; } }, useDebugValue<T>(value: T, formatterFn: ?(value: T) => mixed): void { currentHookNameInDev = 'useDebugValue'; updateHookTypesDev(); return updateDebugValue(value, formatterFn); }, useDeferredValue<T>(value: T, initialValue?: T): T { currentHookNameInDev = 'useDeferredValue'; updateHookTypesDev(); return rerenderDeferredValue(value, initialValue); }, useTransition(): [boolean, (() => void) => void] { currentHookNameInDev = 'useTransition'; updateHookTypesDev(); return rerenderTransition(); }, useSyncExternalStore<T>( subscribe: (() => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T, ): T { currentHookNameInDev = 'useSyncExternalStore'; updateHookTypesDev(); return updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); }, useId(): string { currentHookNameInDev = 'useId'; updateHookTypesDev(); return updateId(); }, }; if (enableCache) { (HooksDispatcherOnRerenderInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() { currentHookNameInDev = 'useCacheRefresh'; updateHookTypesDev(); return updateRefresh(); }; } if (enableUseMemoCacheHook) { (HooksDispatcherOnRerenderInDEV: Dispatcher).useMemoCache = useMemoCache; } if (enableUseEffectEventHook) { (HooksDispatcherOnRerenderInDEV: Dispatcher).useEffectEvent = function useEffectEvent<Args, Return, F: (...Array<Args>) => Return>( callback: F, ): F { currentHookNameInDev = 'useEffectEvent'; updateHookTypesDev(); return updateEvent(callback); }; } if (enableFormActions && enableAsyncActions) { (HooksDispatcherOnRerenderInDEV: Dispatcher).useHostTransitionStatus = useHostTransitionStatus; (HooksDispatcherOnRerenderInDEV: Dispatcher).useFormState = function useFormState<S, P>( action: (Awaited<S>, P) => S, initialState: Awaited<S>, permalink?: string, ): [Awaited<S>, (P) => void] { currentHookNameInDev = 'useFormState'; updateHookTypesDev(); return rerenderFormState(action, initialState, permalink); }; } if (enableAsyncActions) { (HooksDispatcherOnRerenderInDEV: Dispatcher).useOptimistic = function useOptimistic<S, A>( passthrough: S, reducer: ?(S, A) => S, ): [S, (A) => void] { currentHookNameInDev = 'useOptimistic'; updateHookTypesDev(); return rerenderOptimistic(passthrough, reducer); }; } InvalidNestedHooksDispatcherOnMountInDEV = { readContext<T>(context: ReactContext<T>): T { warnInvalidContextAccess(); return readContext(context); }, use<T>(usable: Usable<T>): T { warnInvalidHookAccess(); return use(usable); }, useCallback<T>(callback: T, deps: Array<mixed> | void | null): T { currentHookNameInDev = 'useCallback'; warnInvalidHookAccess(); mountHookTypesDev(); return mountCallback(callback, deps); }, useContext<T>(context: ReactContext<T>): T { currentHookNameInDev = 'useContext'; warnInvalidHookAccess(); mountHookTypesDev(); return readContext(context); }, useEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useEffect'; warnInvalidHookAccess(); mountHookTypesDev(); return mountEffect(create, deps); }, useImperativeHandle<T>( ref: {current: T | null} | ((inst: T | null) => mixed) | null | void, create: () => T, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useImperativeHandle'; warnInvalidHookAccess(); mountHookTypesDev(); return mountImperativeHandle(ref, create, deps); }, useInsertionEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useInsertionEffect'; warnInvalidHookAccess(); mountHookTypesDev(); return mountInsertionEffect(create, deps); }, useLayoutEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useLayoutEffect'; warnInvalidHookAccess(); mountHookTypesDev(); return mountLayoutEffect(create, deps); }, useMemo<T>(create: () => T, deps: Array<mixed> | void | null): T { currentHookNameInDev = 'useMemo'; warnInvalidHookAccess(); mountHookTypesDev(); const prevDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountMemo(create, deps); } finally { ReactCurrentDispatcher.current = prevDispatcher; } }, useReducer<S, I, A>( reducer: (S, A) => S, initialArg: I, init?: I => S, ): [S, Dispatch<A>] { currentHookNameInDev = 'useReducer'; warnInvalidHookAccess(); mountHookTypesDev(); const prevDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher.current = prevDispatcher; } }, useRef<T>(initialValue: T): {current: T} { currentHookNameInDev = 'useRef'; warnInvalidHookAccess(); mountHookTypesDev(); return mountRef(initialValue); }, useState<S>( initialState: (() => S) | S, ): [S, Dispatch<BasicStateAction<S>>] { currentHookNameInDev = 'useState'; warnInvalidHookAccess(); mountHookTypesDev(); const prevDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountState(initialState); } finally { ReactCurrentDispatcher.current = prevDispatcher; } }, useDebugValue<T>(value: T, formatterFn: ?(value: T) => mixed): void { currentHookNameInDev = 'useDebugValue'; warnInvalidHookAccess(); mountHookTypesDev(); return mountDebugValue(value, formatterFn); }, useDeferredValue<T>(value: T, initialValue?: T): T { currentHookNameInDev = 'useDeferredValue'; warnInvalidHookAccess(); mountHookTypesDev(); return mountDeferredValue(value, initialValue); }, useTransition(): [boolean, (() => void) => void] { currentHookNameInDev = 'useTransition'; warnInvalidHookAccess(); mountHookTypesDev(); return mountTransition(); }, useSyncExternalStore<T>( subscribe: (() => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T, ): T { currentHookNameInDev = 'useSyncExternalStore'; warnInvalidHookAccess(); mountHookTypesDev(); return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); }, useId(): string { currentHookNameInDev = 'useId'; warnInvalidHookAccess(); mountHookTypesDev(); return mountId(); }, }; if (enableCache) { (InvalidNestedHooksDispatcherOnMountInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() { currentHookNameInDev = 'useCacheRefresh'; mountHookTypesDev(); return mountRefresh(); }; } if (enableUseMemoCacheHook) { (InvalidNestedHooksDispatcherOnMountInDEV: Dispatcher).useMemoCache = function (size: number): Array<any> { warnInvalidHookAccess(); return useMemoCache(size); }; } if (enableUseEffectEventHook) { (InvalidNestedHooksDispatcherOnMountInDEV: Dispatcher).useEffectEvent = function useEffectEvent<Args, Return, F: (...Array<Args>) => Return>( callback: F, ): F { currentHookNameInDev = 'useEffectEvent'; warnInvalidHookAccess(); mountHookTypesDev(); return mountEvent(callback); }; } if (enableFormActions && enableAsyncActions) { (InvalidNestedHooksDispatcherOnMountInDEV: Dispatcher).useHostTransitionStatus = useHostTransitionStatus; (InvalidNestedHooksDispatcherOnMountInDEV: Dispatcher).useFormState = function useFormState<S, P>( action: (Awaited<S>, P) => S, initialState: Awaited<S>, permalink?: string, ): [Awaited<S>, (P) => void] { currentHookNameInDev = 'useFormState'; warnInvalidHookAccess(); mountHookTypesDev(); return mountFormState(action, initialState, permalink); }; } if (enableAsyncActions) { (InvalidNestedHooksDispatcherOnMountInDEV: Dispatcher).useOptimistic = function useOptimistic<S, A>( passthrough: S, reducer: ?(S, A) => S, ): [S, (A) => void] { currentHookNameInDev = 'useOptimistic'; warnInvalidHookAccess(); mountHookTypesDev(); return mountOptimistic(passthrough, reducer); }; } InvalidNestedHooksDispatcherOnUpdateInDEV = { readContext<T>(context: ReactContext<T>): T { warnInvalidContextAccess(); return readContext(context); }, use<T>(usable: Usable<T>): T { warnInvalidHookAccess(); return use(usable); }, useCallback<T>(callback: T, deps: Array<mixed> | void | null): T { currentHookNameInDev = 'useCallback'; warnInvalidHookAccess(); updateHookTypesDev(); return updateCallback(callback, deps); }, useContext<T>(context: ReactContext<T>): T { currentHookNameInDev = 'useContext'; warnInvalidHookAccess(); updateHookTypesDev(); return readContext(context); }, useEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useEffect'; warnInvalidHookAccess(); updateHookTypesDev(); return updateEffect(create, deps); }, useImperativeHandle<T>( ref: {current: T | null} | ((inst: T | null) => mixed) | null | void, create: () => T, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useImperativeHandle'; warnInvalidHookAccess(); updateHookTypesDev(); return updateImperativeHandle(ref, create, deps); }, useInsertionEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useInsertionEffect'; warnInvalidHookAccess(); updateHookTypesDev(); return updateInsertionEffect(create, deps); }, useLayoutEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useLayoutEffect'; warnInvalidHookAccess(); updateHookTypesDev(); return updateLayoutEffect(create, deps); }, useMemo<T>(create: () => T, deps: Array<mixed> | void | null): T { currentHookNameInDev = 'useMemo'; warnInvalidHookAccess(); updateHookTypesDev(); const prevDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateMemo(create, deps); } finally { ReactCurrentDispatcher.current = prevDispatcher; } }, useReducer<S, I, A>( reducer: (S, A) => S, initialArg: I, init?: I => S, ): [S, Dispatch<A>] { currentHookNameInDev = 'useReducer'; warnInvalidHookAccess(); updateHookTypesDev(); const prevDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher.current = prevDispatcher; } }, useRef<T>(initialValue: T): {current: T} { currentHookNameInDev = 'useRef'; warnInvalidHookAccess(); updateHookTypesDev(); return updateRef(initialValue); }, useState<S>( initialState: (() => S) | S, ): [S, Dispatch<BasicStateAction<S>>] { currentHookNameInDev = 'useState'; warnInvalidHookAccess(); updateHookTypesDev(); const prevDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateState(initialState); } finally { ReactCurrentDispatcher.current = prevDispatcher; } }, useDebugValue<T>(value: T, formatterFn: ?(value: T) => mixed): void { currentHookNameInDev = 'useDebugValue'; warnInvalidHookAccess(); updateHookTypesDev(); return updateDebugValue(value, formatterFn); }, useDeferredValue<T>(value: T, initialValue?: T): T { currentHookNameInDev = 'useDeferredValue'; warnInvalidHookAccess(); updateHookTypesDev(); return updateDeferredValue(value, initialValue); }, useTransition(): [boolean, (() => void) => void] { currentHookNameInDev = 'useTransition'; warnInvalidHookAccess(); updateHookTypesDev(); return updateTransition(); }, useSyncExternalStore<T>( subscribe: (() => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T, ): T { currentHookNameInDev = 'useSyncExternalStore'; warnInvalidHookAccess(); updateHookTypesDev(); return updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); }, useId(): string { currentHookNameInDev = 'useId'; warnInvalidHookAccess(); updateHookTypesDev(); return updateId(); }, }; if (enableCache) { (InvalidNestedHooksDispatcherOnUpdateInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() { currentHookNameInDev = 'useCacheRefresh'; updateHookTypesDev(); return updateRefresh(); }; } if (enableUseMemoCacheHook) { (InvalidNestedHooksDispatcherOnUpdateInDEV: Dispatcher).useMemoCache = function (size: number): Array<any> { warnInvalidHookAccess(); return useMemoCache(size); }; } if (enableUseEffectEventHook) { (InvalidNestedHooksDispatcherOnUpdateInDEV: Dispatcher).useEffectEvent = function useEffectEvent<Args, Return, F: (...Array<Args>) => Return>( callback: F, ): F { currentHookNameInDev = 'useEffectEvent'; warnInvalidHookAccess(); updateHookTypesDev(); return updateEvent(callback); }; } if (enableFormActions && enableAsyncActions) { (InvalidNestedHooksDispatcherOnUpdateInDEV: Dispatcher).useHostTransitionStatus = useHostTransitionStatus; (InvalidNestedHooksDispatcherOnUpdateInDEV: Dispatcher).useFormState = function useFormState<S, P>( action: (Awaited<S>, P) => S, initialState: Awaited<S>, permalink?: string, ): [Awaited<S>, (P) => void] { currentHookNameInDev = 'useFormState'; warnInvalidHookAccess(); updateHookTypesDev(); return updateFormState(action, initialState, permalink); }; } if (enableAsyncActions) { (InvalidNestedHooksDispatcherOnUpdateInDEV: Dispatcher).useOptimistic = function useOptimistic<S, A>( passthrough: S, reducer: ?(S, A) => S, ): [S, (A) => void] { currentHookNameInDev = 'useOptimistic'; warnInvalidHookAccess(); updateHookTypesDev(); return updateOptimistic(passthrough, reducer); }; } InvalidNestedHooksDispatcherOnRerenderInDEV = { readContext<T>(context: ReactContext<T>): T { warnInvalidContextAccess(); return readContext(context); }, use<T>(usable: Usable<T>): T { warnInvalidHookAccess(); return use(usable); }, useCallback<T>(callback: T, deps: Array<mixed> | void | null): T { currentHookNameInDev = 'useCallback'; warnInvalidHookAccess(); updateHookTypesDev(); return updateCallback(callback, deps); }, useContext<T>(context: ReactContext<T>): T { currentHookNameInDev = 'useContext'; warnInvalidHookAccess(); updateHookTypesDev(); return readContext(context); }, useEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useEffect'; warnInvalidHookAccess(); updateHookTypesDev(); return updateEffect(create, deps); }, useImperativeHandle<T>( ref: {current: T | null} | ((inst: T | null) => mixed) | null | void, create: () => T, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useImperativeHandle'; warnInvalidHookAccess(); updateHookTypesDev(); return updateImperativeHandle(ref, create, deps); }, useInsertionEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useInsertionEffect'; warnInvalidHookAccess(); updateHookTypesDev(); return updateInsertionEffect(create, deps); }, useLayoutEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void { currentHookNameInDev = 'useLayoutEffect'; warnInvalidHookAccess(); updateHookTypesDev(); return updateLayoutEffect(create, deps); }, useMemo<T>(create: () => T, deps: Array<mixed> | void | null): T { currentHookNameInDev = 'useMemo'; warnInvalidHookAccess(); updateHookTypesDev(); const prevDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateMemo(create, deps); } finally { ReactCurrentDispatcher.current = prevDispatcher; } }, useReducer<S, I, A>( reducer: (S, A) => S, initialArg: I, init?: I => S, ): [S, Dispatch<A>] { currentHookNameInDev = 'useReducer'; warnInvalidHookAccess(); updateHookTypesDev(); const prevDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return rerenderReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher.current = prevDispatcher; } }, useRef<T>(initialValue: T): {current: T} { currentHookNameInDev = 'useRef'; warnInvalidHookAccess(); updateHookTypesDev(); return updateRef(initialValue); }, useState<S>( initialState: (() => S) | S, ): [S, Dispatch<BasicStateAction<S>>] { currentHookNameInDev = 'useState'; warnInvalidHookAccess(); updateHookTypesDev(); const prevDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return rerenderState(initialState); } finally { ReactCurrentDispatcher.current = prevDispatcher; } }, useDebugValue<T>(value: T, formatterFn: ?(value: T) => mixed): void { currentHookNameInDev = 'useDebugValue'; warnInvalidHookAccess(); updateHookTypesDev(); return updateDebugValue(value, formatterFn); }, useDeferredValue<T>(value: T, initialValue?: T): T { currentHookNameInDev = 'useDeferredValue'; warnInvalidHookAccess(); updateHookTypesDev(); return rerenderDeferredValue(value, initialValue); }, useTransition(): [boolean, (() => void) => void] { currentHookNameInDev = 'useTransition'; warnInvalidHookAccess(); updateHookTypesDev(); return rerenderTransition(); }, useSyncExternalStore<T>( subscribe: (() => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T, ): T { currentHookNameInDev = 'useSyncExternalStore'; warnInvalidHookAccess(); updateHookTypesDev(); return updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); }, useId(): string { currentHookNameInDev = 'useId'; warnInvalidHookAccess(); updateHookTypesDev(); return updateId(); }, }; if (enableCache) { (InvalidNestedHooksDispatcherOnRerenderInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() { currentHookNameInDev = 'useCacheRefresh'; updateHookTypesDev(); return updateRefresh(); }; } if (enableUseMemoCacheHook) { (InvalidNestedHooksDispatcherOnRerenderInDEV: Dispatcher).useMemoCache = function (size: number): Array<any> { warnInvalidHookAccess(); return useMemoCache(size); }; } if (enableUseEffectEventHook) { (InvalidNestedHooksDispatcherOnRerenderInDEV: Dispatcher).useEffectEvent = function useEffectEvent<Args, Return, F: (...Array<Args>) => Return>( callback: F, ): F { currentHookNameInDev = 'useEffectEvent'; warnInvalidHookAccess(); updateHookTypesDev(); return updateEvent(callback); }; } if (enableFormActions && enableAsyncActions) { (InvalidNestedHooksDispatcherOnRerenderInDEV: Dispatcher).useHostTransitionStatus = useHostTransitionStatus; (InvalidNestedHooksDispatcherOnRerenderInDEV: Dispatcher).useFormState = function useFormState<S, P>( action: (Awaited<S>, P) => S, initialState: Awaited<S>, permalink?: string, ): [Awaited<S>, (P) => void] { currentHookNameInDev = 'useFormState'; warnInvalidHookAccess(); updateHookTypesDev(); return rerenderFormState(action, initialState, permalink); }; } if (enableAsyncActions) { (InvalidNestedHooksDispatcherOnRerenderInDEV: Dispatcher).useOptimistic = function useOptimistic<S, A>( passthrough: S, reducer: ?(S, A) => S, ): [S, (A) => void] { currentHookNameInDev = 'useOptimistic'; warnInvalidHookAccess(); updateHookTypesDev(); return rerenderOptimistic(passthrough, reducer); }; } }
32.114239
117
0.661715
Penetration-Testing-Study-Notes
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/jest-react.production.min.js'); } else { module.exports = require('./cjs/jest-react.development.js'); }
24.125
65
0.67
owtf
/** @license React v16.14.0 * react-jsx-dev-runtime.production.min.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict';require("react");exports.Fragment=60107;if("function"===typeof Symbol&&Symbol.for){var a=Symbol.for;exports.Fragment=a("react.fragment")}exports.jsxDEV=void 0;
42.5
172
0.735023
Python-Penetration-Testing-for-Developers
let React; let Suspense; let ReactNoop; let Scheduler; let act; let ReactFeatureFlags; let Random; const SEED = process.env.FUZZ_TEST_SEED || 'default'; const prettyFormatPkg = require('pretty-format'); function prettyFormat(thing) { return prettyFormatPkg.format(thing, { plugins: [ prettyFormatPkg.plugins.ReactElement, prettyFormatPkg.plugins.ReactTestComponent, ], }); } describe('ReactSuspenseFuzz', () => { beforeEach(() => { jest.resetModules(); ReactFeatureFlags = require('shared/ReactFeatureFlags'); ReactFeatureFlags.replayFailedUnitOfWorkWithInvokeGuardedCallback = false; React = require('react'); Suspense = React.Suspense; ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); act = require('internal-test-utils').act; Random = require('random-seed'); }); jest.setTimeout(20000); function createFuzzer() { const {useState, useContext, useLayoutEffect} = React; const ShouldSuspendContext = React.createContext(true); let pendingTasks = new Set(); let cache = new Map(); function resetCache() { pendingTasks = new Set(); cache = new Map(); } function Container({children, updates}) { const [step, setStep] = useState(0); useLayoutEffect(() => { if (updates !== undefined) { const cleanUps = new Set(); updates.forEach(({remountAfter}, i) => { const task = { label: `Remount children after ${remountAfter}ms`, }; const timeoutID = setTimeout(() => { pendingTasks.delete(task); setStep(i + 1); }, remountAfter); pendingTasks.add(task); cleanUps.add(() => { pendingTasks.delete(task); clearTimeout(timeoutID); }); }); return () => { cleanUps.forEach(cleanUp => cleanUp()); }; } }, [updates]); return <React.Fragment key={step}>{children}</React.Fragment>; } function Text({text, initialDelay = 0, updates}) { const [[step, delay], setStep] = useState([0, initialDelay]); useLayoutEffect(() => { if (updates !== undefined) { const cleanUps = new Set(); updates.forEach(({beginAfter, suspendFor}, i) => { const task = { label: `Update ${beginAfter}ms after mount and suspend for ${suspendFor}ms [${text}]`, }; const timeoutID = setTimeout(() => { pendingTasks.delete(task); setStep([i + 1, suspendFor]); }, beginAfter); pendingTasks.add(task); cleanUps.add(() => { pendingTasks.delete(task); clearTimeout(timeoutID); }); }); return () => { cleanUps.forEach(cleanUp => cleanUp()); }; } }, [updates]); const fullText = `[${text}:${step}]`; const shouldSuspend = useContext(ShouldSuspendContext); let resolvedText; if (shouldSuspend && delay > 0) { resolvedText = cache.get(fullText); if (resolvedText === undefined) { const thenable = { then(resolve) { const task = {label: `Promise resolved [${fullText}]`}; pendingTasks.add(task); setTimeout(() => { cache.set(fullText, fullText); pendingTasks.delete(task); Scheduler.log(task.label); resolve(); }, delay); }, }; cache.set(fullText, thenable); Scheduler.log(`Suspended! [${fullText}]`); throw thenable; } else if (typeof resolvedText.then === 'function') { const thenable = resolvedText; Scheduler.log(`Suspended! [${fullText}]`); throw thenable; } } else { resolvedText = fullText; } Scheduler.log(resolvedText); return resolvedText; } async function testResolvedOutput(unwrappedChildren) { const children = ( <Suspense fallback="Loading...">{unwrappedChildren}</Suspense> ); // Render the app multiple times: once without suspending (as if all the // data was already preloaded), and then again with suspensey data. resetCache(); const expectedRoot = ReactNoop.createRoot(); await act(() => { expectedRoot.render( <ShouldSuspendContext.Provider value={false}> {children} </ShouldSuspendContext.Provider>, ); }); const expectedOutput = expectedRoot.getChildrenAsJSX(); resetCache(); const concurrentRootThatSuspends = ReactNoop.createRoot(); await act(() => { concurrentRootThatSuspends.render(children); }); resetCache(); // Do it again in legacy mode. const legacyRootThatSuspends = ReactNoop.createLegacyRoot(); await act(() => { legacyRootThatSuspends.render(children); }); // Now compare the final output. It should be the same. expect(concurrentRootThatSuspends.getChildrenAsJSX()).toEqual( expectedOutput, ); expect(legacyRootThatSuspends.getChildrenAsJSX()).toEqual(expectedOutput); // TODO: There are Scheduler logs in this test file but they were only // added for debugging purposes; we don't make any assertions on them. // Should probably just delete. Scheduler.unstable_clearLog(); } function pickRandomWeighted(rand, options) { let totalWeight = 0; for (let i = 0; i < options.length; i++) { totalWeight += options[i].weight; } let remainingWeight = rand.floatBetween(0, totalWeight); for (let i = 0; i < options.length; i++) { const {value, weight} = options[i]; remainingWeight -= weight; if (remainingWeight <= 0) { return value; } } } function generateTestCase(rand, numberOfElements) { let remainingElements = numberOfElements; function createRandomChild(hasSibling) { const possibleActions = [ {value: 'return', weight: 1}, {value: 'text', weight: 1}, ]; if (hasSibling) { possibleActions.push({value: 'container', weight: 1}); possibleActions.push({value: 'suspense', weight: 1}); } const action = pickRandomWeighted(rand, possibleActions); switch (action) { case 'text': { remainingElements--; const numberOfUpdates = pickRandomWeighted(rand, [ {value: 0, weight: 8}, {value: 1, weight: 4}, {value: 2, weight: 1}, ]); const updates = []; for (let i = 0; i < numberOfUpdates; i++) { updates.push({ beginAfter: rand.intBetween(0, 10000), suspendFor: rand.intBetween(0, 10000), }); } return ( <Text text={(remainingElements + 9).toString(36).toUpperCase()} initialDelay={rand.intBetween(0, 10000)} updates={updates} /> ); } case 'container': { const numberOfUpdates = pickRandomWeighted(rand, [ {value: 0, weight: 8}, {value: 1, weight: 4}, {value: 2, weight: 1}, ]); const updates = []; for (let i = 0; i < numberOfUpdates; i++) { updates.push({ remountAfter: rand.intBetween(0, 10000), }); } remainingElements--; const children = createRandomChildren(3); return React.createElement(Container, {updates}, ...children); } case 'suspense': { remainingElements--; const children = createRandomChildren(3); const fallbackType = pickRandomWeighted(rand, [ {value: 'none', weight: 1}, {value: 'normal', weight: 1}, {value: 'nested suspense', weight: 1}, ]); let fallback; if (fallbackType === 'normal') { fallback = 'Loading...'; } else if (fallbackType === 'nested suspense') { fallback = React.createElement( React.Fragment, null, ...createRandomChildren(3), ); } return React.createElement(Suspense, {fallback}, ...children); } case 'return': default: return null; } } function createRandomChildren(limit) { const children = []; while (remainingElements > 0 && children.length < limit) { children.push(createRandomChild(children.length > 0)); } return children; } const children = createRandomChildren(Infinity); return React.createElement(React.Fragment, null, ...children); } return {Container, Text, testResolvedOutput, generateTestCase}; } it('basic cases', async () => { // This demonstrates that the testing primitives work const {Container, Text, testResolvedOutput} = createFuzzer(); await testResolvedOutput( <Container updates={[{remountAfter: 150}]}> <Text text="Hi" initialDelay={2000} updates={[{beginAfter: 100, suspendFor: 200}]} /> </Container>, ); }); it(`generative tests (random seed: ${SEED})`, async () => { const {generateTestCase, testResolvedOutput} = createFuzzer(); const rand = Random.create(SEED); // If this is too large the test will time out. We use a scheduled CI // workflow to run these tests with a random seed. const NUMBER_OF_TEST_CASES = 250; const ELEMENTS_PER_CASE = 12; for (let i = 0; i < NUMBER_OF_TEST_CASES; i++) { const randomTestCase = generateTestCase(rand, ELEMENTS_PER_CASE); try { await testResolvedOutput(randomTestCase); } catch (e) { console.log(` Failed fuzzy test case: ${prettyFormat(randomTestCase)} Random seed is ${SEED} `); throw e; } } }); describe('hard-coded cases', () => { it('1', async () => { const {Text, testResolvedOutput} = createFuzzer(); await testResolvedOutput( <> <Text initialDelay={20} text="A" updates={[{beginAfter: 10, suspendFor: 20}]} /> <Suspense fallback="Loading... (B)"> <Text initialDelay={10} text="B" updates={[{beginAfter: 30, suspendFor: 50}]} /> <Text text="C" /> </Suspense> </>, ); }); it('2', async () => { const {Text, Container, testResolvedOutput} = createFuzzer(); await testResolvedOutput( <> <Suspense fallback="Loading..."> <Text initialDelay={7200} text="A" /> </Suspense> <Suspense fallback="Loading..."> <Container> <Text initialDelay={1000} text="B" /> <Text initialDelay={7200} text="C" /> <Text initialDelay={9000} text="D" /> </Container> </Suspense> </>, ); }); it('3', async () => { const {Text, Container, testResolvedOutput} = createFuzzer(); await testResolvedOutput( <> <Suspense fallback="Loading..."> <Text initialDelay={3183} text="A" updates={[ { beginAfter: 2256, suspendFor: 6696, }, ]} /> <Text initialDelay={3251} text="B" /> </Suspense> <Container> <Text initialDelay={2700} text="C" updates={[ { beginAfter: 3266, suspendFor: 9139, }, ]} /> <Text initialDelay={6732} text="D" /> </Container> </>, ); }); it('4', async () => { const {Text, testResolvedOutput} = createFuzzer(); await testResolvedOutput( <React.Suspense fallback="Loading..."> <React.Suspense> <React.Suspense> <Text initialDelay={9683} text="E" updates={[]} /> </React.Suspense> <Text initialDelay={4053} text="C" updates={[ { beginAfter: 1566, suspendFor: 4142, }, { beginAfter: 9572, suspendFor: 4832, }, ]} /> </React.Suspense> </React.Suspense>, ); }); }); });
28.144444
100
0.516776
Hands-On-AWS-Penetration-Testing-with-Kali-Linux
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export type GitHubIssue = { title: string, url: string, }; const GITHUB_ISSUES_API = 'https://api.github.com/search/issues'; export function searchGitHubIssuesURL(message: string): string { // Remove Fiber IDs from error message (as those will be unique). message = message.replace(/"[0-9]+"/g, ''); const filters = [ 'in:title', 'is:issue', 'is:open', 'is:public', 'label:"Component: Developer Tools"', 'repo:facebook/react', ]; return ( GITHUB_ISSUES_API + '?q=' + encodeURIComponent(message) + '%20' + filters.map(encodeURIComponent).join('%20') ); } export async function searchGitHubIssues( message: string, ): Promise<GitHubIssue | null> { const response = await fetch(searchGitHubIssuesURL(message)); const data = await response.json(); if (data.items.length > 0) { const item = data.items[0]; return { title: item.title, url: item.html_url, }; } else { return null; } }
21
67
0.639427
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; let React; let ReactDOMServer; describe('quoteAttributeValueForBrowser', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOMServer = require('react-dom/server'); }); it('ampersand is escaped inside attributes', () => { const response = ReactDOMServer.renderToString(<img data-attr="&" />); expect(response).toMatch('<img data-attr="&amp;"/>'); }); it('double quote is escaped inside attributes', () => { const response = ReactDOMServer.renderToString(<img data-attr={'"'} />); expect(response).toMatch('<img data-attr="&quot;"/>'); }); it('single quote is escaped inside attributes', () => { const response = ReactDOMServer.renderToString(<img data-attr="'" />); expect(response).toMatch('<img data-attr="&#x27;"/>'); }); it('greater than entity is escaped inside attributes', () => { const response = ReactDOMServer.renderToString(<img data-attr=">" />); expect(response).toMatch('<img data-attr="&gt;"/>'); }); it('lower than entity is escaped inside attributes', () => { const response = ReactDOMServer.renderToString(<img data-attr="<" />); expect(response).toMatch('<img data-attr="&lt;"/>'); }); it('number is escaped to string inside attributes', () => { const response = ReactDOMServer.renderToString(<img data-attr={42} />); expect(response).toMatch('<img data-attr="42"/>'); }); it('object is passed to a string inside attributes', () => { const sampleObject = { toString: function () { return 'ponys'; }, }; const response = ReactDOMServer.renderToString( <img data-attr={sampleObject} />, ); expect(response).toMatch('<img data-attr="ponys"/>'); }); it('script tag is escaped inside attributes', () => { const response = ReactDOMServer.renderToString( <img data-attr={'<script type=\'\' src=""></script>'} />, ); expect(response).toMatch( '<img data-attr="&lt;script type=&#x27;&#x27; ' + 'src=&quot;&quot;&gt;&lt;/script&gt;"/>', ); }); });
29.746667
76
0.619089
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type { PostponedState, ErrorInfo, PostponeInfo, } from 'react-server/src/ReactFizzServer'; import type {ReactNodeList, ReactFormState} from 'shared/ReactTypes'; import type { BootstrapScriptDescriptor, HeadersDescriptor, } from 'react-dom-bindings/src/server/ReactFizzConfigDOM'; import type {ImportMap} from '../shared/ReactDOMTypes'; import ReactVersion from 'shared/ReactVersion'; import { createRequest, resumeRequest, startWork, startFlowing, stopFlowing, abort, } from 'react-server/src/ReactFizzServer'; import { createResumableState, createRenderState, resumeRenderState, createRootFormatContext, } from 'react-dom-bindings/src/server/ReactFizzConfigDOM'; type Options = { identifierPrefix?: string, namespaceURI?: string, nonce?: string, bootstrapScriptContent?: string, bootstrapScripts?: Array<string | BootstrapScriptDescriptor>, bootstrapModules?: Array<string | BootstrapScriptDescriptor>, progressiveChunkSize?: number, signal?: AbortSignal, onError?: (error: mixed, errorInfo: ErrorInfo) => ?string, onPostpone?: (reason: string, postponeInfo: PostponeInfo) => void, unstable_externalRuntimeSrc?: string | BootstrapScriptDescriptor, importMap?: ImportMap, formState?: ReactFormState<any, any> | null, onHeaders?: (headers: Headers) => void, maxHeadersLength?: number, }; type ResumeOptions = { nonce?: string, signal?: AbortSignal, onError?: (error: mixed) => ?string, onPostpone?: (reason: string) => void, unstable_externalRuntimeSrc?: string | BootstrapScriptDescriptor, }; // TODO: Move to sub-classing ReadableStream. type ReactDOMServerReadableStream = ReadableStream & { allReady: Promise<void>, }; function renderToReadableStream( children: ReactNodeList, options?: Options, ): Promise<ReactDOMServerReadableStream> { return new Promise((resolve, reject) => { let onFatalError; let onAllReady; const allReady = new Promise<void>((res, rej) => { onAllReady = res; onFatalError = rej; }); function onShellReady() { const stream: ReactDOMServerReadableStream = (new ReadableStream( { type: 'bytes', pull: (controller): ?Promise<void> => { startFlowing(request, controller); }, cancel: (reason): ?Promise<void> => { stopFlowing(request); abort(request, reason); }, }, // $FlowFixMe[prop-missing] size() methods are not allowed on byte streams. {highWaterMark: 0}, ): any); // TODO: Move to sub-classing ReadableStream. stream.allReady = allReady; resolve(stream); } function onShellError(error: mixed) { // If the shell errors the caller of `renderToReadableStream` won't have access to `allReady`. // However, `allReady` will be rejected by `onFatalError` as well. // So we need to catch the duplicate, uncatchable fatal error in `allReady` to prevent a `UnhandledPromiseRejection`. allReady.catch(() => {}); reject(error); } const onHeaders = options ? options.onHeaders : undefined; let onHeadersImpl; if (onHeaders) { onHeadersImpl = (headersDescriptor: HeadersDescriptor) => { onHeaders(new Headers(headersDescriptor)); }; } const resumableState = createResumableState( options ? options.identifierPrefix : undefined, options ? options.unstable_externalRuntimeSrc : undefined, options ? options.bootstrapScriptContent : undefined, options ? options.bootstrapScripts : undefined, options ? options.bootstrapModules : undefined, ); const request = createRequest( children, resumableState, createRenderState( resumableState, options ? options.nonce : undefined, options ? options.unstable_externalRuntimeSrc : undefined, options ? options.importMap : undefined, onHeadersImpl, options ? options.maxHeadersLength : undefined, ), createRootFormatContext(options ? options.namespaceURI : undefined), options ? options.progressiveChunkSize : undefined, options ? options.onError : undefined, onAllReady, onShellReady, onShellError, onFatalError, options ? options.onPostpone : undefined, options ? options.formState : undefined, ); if (options && options.signal) { const signal = options.signal; if (signal.aborted) { abort(request, (signal: any).reason); } else { const listener = () => { abort(request, (signal: any).reason); signal.removeEventListener('abort', listener); }; signal.addEventListener('abort', listener); } } startWork(request); }); } function resume( children: ReactNodeList, postponedState: PostponedState, options?: ResumeOptions, ): Promise<ReactDOMServerReadableStream> { return new Promise((resolve, reject) => { let onFatalError; let onAllReady; const allReady = new Promise<void>((res, rej) => { onAllReady = res; onFatalError = rej; }); function onShellReady() { const stream: ReactDOMServerReadableStream = (new ReadableStream( { type: 'bytes', pull: (controller): ?Promise<void> => { startFlowing(request, controller); }, cancel: (reason): ?Promise<void> => { stopFlowing(request); abort(request, reason); }, }, // $FlowFixMe[prop-missing] size() methods are not allowed on byte streams. {highWaterMark: 0}, ): any); // TODO: Move to sub-classing ReadableStream. stream.allReady = allReady; resolve(stream); } function onShellError(error: mixed) { // If the shell errors the caller of `renderToReadableStream` won't have access to `allReady`. // However, `allReady` will be rejected by `onFatalError` as well. // So we need to catch the duplicate, uncatchable fatal error in `allReady` to prevent a `UnhandledPromiseRejection`. allReady.catch(() => {}); reject(error); } const request = resumeRequest( children, postponedState, resumeRenderState( postponedState.resumableState, options ? options.nonce : undefined, ), options ? options.onError : undefined, onAllReady, onShellReady, onShellError, onFatalError, options ? options.onPostpone : undefined, ); if (options && options.signal) { const signal = options.signal; if (signal.aborted) { abort(request, (signal: any).reason); } else { const listener = () => { abort(request, (signal: any).reason); signal.removeEventListener('abort', listener); }; signal.addEventListener('abort', listener); } } startWork(request); }); } export {renderToReadableStream, resume, ReactVersion as version};
30.099138
123
0.653313
owtf
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ import Html from './Html'; import BigComponent from './BigComponent'; export default function App({assets, title}) { const components = []; for (let i = 0; i <= 250; i++) { components.push(<BigComponent key={i} />); } return ( <Html assets={assets} title={title}> <h1>{title}</h1> {components} <h1>all done</h1> </Html> ); }
19.888889
66
0.616341
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {ElementRef} from 'react'; import type { HostComponent, MeasureInWindowOnSuccessCallback, MeasureLayoutOnSuccessCallback, MeasureOnSuccessCallback, INativeMethods, ViewConfig, } from './ReactNativeTypes'; import type {Instance} from './ReactFiberConfigNative'; // Modules provided by RN: import { TextInputState, UIManager, } from 'react-native/Libraries/ReactPrivate/ReactNativePrivateInterface'; import {create} from './ReactNativeAttributePayload'; import { mountSafeCallback_NOT_REALLY_SAFE, warnForStyleProps, } from './NativeMethodsMixinUtils'; class ReactNativeFiberHostComponent implements INativeMethods { _children: Array<Instance | number>; _nativeTag: number; _internalFiberInstanceHandleDEV: Object; viewConfig: ViewConfig; constructor( tag: number, viewConfig: ViewConfig, internalInstanceHandleDEV: Object, ) { this._nativeTag = tag; this._children = []; this.viewConfig = viewConfig; if (__DEV__) { this._internalFiberInstanceHandleDEV = internalInstanceHandleDEV; } } blur() { TextInputState.blurTextInput(this); } focus() { TextInputState.focusTextInput(this); } measure(callback: MeasureOnSuccessCallback) { UIManager.measure( this._nativeTag, mountSafeCallback_NOT_REALLY_SAFE(this, callback), ); } measureInWindow(callback: MeasureInWindowOnSuccessCallback) { UIManager.measureInWindow( this._nativeTag, mountSafeCallback_NOT_REALLY_SAFE(this, callback), ); } measureLayout( relativeToNativeNode: number | ElementRef<HostComponent<mixed>>, onSuccess: MeasureLayoutOnSuccessCallback, onFail?: () => void /* currently unused */, ) { let relativeNode: ?number; if (typeof relativeToNativeNode === 'number') { // Already a node handle relativeNode = relativeToNativeNode; } else { const nativeNode: ReactNativeFiberHostComponent = (relativeToNativeNode: any); if (nativeNode._nativeTag) { relativeNode = nativeNode._nativeTag; } } if (relativeNode == null) { if (__DEV__) { console.error( 'Warning: ref.measureLayout must be called with a node handle or a ref to a native component.', ); } return; } UIManager.measureLayout( this._nativeTag, relativeNode, mountSafeCallback_NOT_REALLY_SAFE(this, onFail), mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess), ); } setNativeProps(nativeProps: Object) { if (__DEV__) { warnForStyleProps(nativeProps, this.viewConfig.validAttributes); } const updatePayload = create(nativeProps, this.viewConfig.validAttributes); // Avoid the overhead of bridge calls if there's no update. // This is an expensive no-op for Android, and causes an unnecessary // view invalidation for certain components (eg RCTTextInput) on iOS. if (updatePayload != null) { UIManager.updateView( this._nativeTag, this.viewConfig.uiViewClassName, updatePayload, ); } } } export default ReactNativeFiberHostComponent;
24.625954
105
0.687723
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {ScrollState} from './view-base/utils/scrollState'; // Source: https://github.com/facebook/flow/issues/4002#issuecomment-323612798 // eslint-disable-next-line no-unused-vars type Return_<R, F: (...args: Array<any>) => R> = R; /** Get return type of a function. */ export type Return<T> = Return_<mixed, T>; // Project types export type ErrorStackFrame = { fileName: string, lineNumber: number, columnNumber: number, }; export type Milliseconds = number; export type ReactLane = number; export type NativeEvent = { +depth: number, +duration: Milliseconds, +timestamp: Milliseconds, +type: string, warning: string | null, }; type BaseReactEvent = { +componentName?: string, +timestamp: Milliseconds, warning: string | null, }; type BaseReactScheduleEvent = { ...BaseReactEvent, +lanes: ReactLane[], }; export type ReactScheduleRenderEvent = { ...BaseReactScheduleEvent, +type: 'schedule-render', }; export type ReactScheduleStateUpdateEvent = { ...BaseReactScheduleEvent, +componentStack?: string, +type: 'schedule-state-update', }; export type ReactScheduleForceUpdateEvent = { ...BaseReactScheduleEvent, +type: 'schedule-force-update', }; export type Phase = 'mount' | 'update'; export type SuspenseEvent = { ...BaseReactEvent, depth: number, duration: number | null, +id: string, +phase: Phase | null, promiseName: string | null, resolution: 'rejected' | 'resolved' | 'unresolved', +type: 'suspense', }; export type ThrownError = { +componentName?: string, +message: string, +phase: Phase, +timestamp: Milliseconds, +type: 'thrown-error', }; export type SchedulingEvent = | ReactScheduleRenderEvent | ReactScheduleStateUpdateEvent | ReactScheduleForceUpdateEvent; export type SchedulingEventType = $PropertyType<SchedulingEvent, 'type'>; export type ReactMeasureType = | 'commit' // render-idle: A measure spanning the time when a render starts, through all // yields and restarts, and ends when commit stops OR render is cancelled. | 'render-idle' | 'render' | 'layout-effects' | 'passive-effects'; export type BatchUID = number; export type ReactMeasure = { +type: ReactMeasureType, +lanes: ReactLane[], +timestamp: Milliseconds, +duration: Milliseconds, +batchUID: BatchUID, +depth: number, }; export type NetworkMeasure = { +depth: number, finishTimestamp: Milliseconds, firstReceivedDataTimestamp: Milliseconds, lastReceivedDataTimestamp: Milliseconds, priority: string, receiveResponseTimestamp: Milliseconds, +requestId: string, requestMethod: string, sendRequestTimestamp: Milliseconds, url: string, }; export type ReactComponentMeasureType = | 'render' | 'layout-effect-mount' | 'layout-effect-unmount' | 'passive-effect-mount' | 'passive-effect-unmount'; export type ReactComponentMeasure = { +componentName: string, duration: Milliseconds, +timestamp: Milliseconds, +type: ReactComponentMeasureType, warning: string | null, }; /** * A flamechart stack frame belonging to a stack trace. */ export type FlamechartStackFrame = { name: string, timestamp: Milliseconds, duration: Milliseconds, scriptUrl?: string, locationLine?: number, locationColumn?: number, }; export type UserTimingMark = { name: string, timestamp: Milliseconds, }; export type Snapshot = { height: number, image: Image | null, +imageSource: string, +timestamp: Milliseconds, width: number, }; /** * A "layer" of stack frames in the profiler UI, i.e. all stack frames of the * same depth across all stack traces. Displayed as a flamechart row in the UI. */ export type FlamechartStackLayer = FlamechartStackFrame[]; export type Flamechart = FlamechartStackLayer[]; export type HorizontalScrollStateChangeCallback = ( scrollState: ScrollState, ) => void; export type SearchRegExpStateChangeCallback = ( searchRegExp: RegExp | null, ) => void; // Imperative view state that corresponds to profiler data. // This state lives outside of React's lifecycle // and should be erased/reset whenever new profiler data is loaded. export type ViewState = { horizontalScrollState: ScrollState, onHorizontalScrollStateChange: ( callback: HorizontalScrollStateChangeCallback, ) => void, onSearchRegExpStateChange: ( callback: SearchRegExpStateChangeCallback, ) => void, searchRegExp: RegExp | null, updateHorizontalScrollState: (scrollState: ScrollState) => void, updateSearchRegExpState: (searchRegExp: RegExp | null) => void, viewToMutableViewStateMap: Map<string, mixed>, }; export type InternalModuleSourceToRanges = Map< string, Array<[ErrorStackFrame, ErrorStackFrame]>, >; export type LaneToLabelMap = Map<ReactLane, string>; export type TimelineData = { batchUIDToMeasuresMap: Map<BatchUID, ReactMeasure[]>, componentMeasures: ReactComponentMeasure[], duration: number, flamechart: Flamechart, internalModuleSourceToRanges: InternalModuleSourceToRanges, laneToLabelMap: LaneToLabelMap, laneToReactMeasureMap: Map<ReactLane, ReactMeasure[]>, nativeEvents: NativeEvent[], networkMeasures: NetworkMeasure[], otherUserTimingMarks: UserTimingMark[], reactVersion: string | null, schedulingEvents: SchedulingEvent[], snapshots: Snapshot[], snapshotHeight: number, startTime: number, suspenseEvents: SuspenseEvent[], thrownErrors: ThrownError[], }; export type TimelineDataExport = { batchUIDToMeasuresKeyValueArray: Array<[BatchUID, ReactMeasure[]]>, componentMeasures: ReactComponentMeasure[], duration: number, flamechart: Flamechart, internalModuleSourceToRanges: Array< [string, Array<[ErrorStackFrame, ErrorStackFrame]>], >, laneToLabelKeyValueArray: Array<[ReactLane, string]>, laneToReactMeasureKeyValueArray: Array<[ReactLane, ReactMeasure[]]>, nativeEvents: NativeEvent[], networkMeasures: NetworkMeasure[], otherUserTimingMarks: UserTimingMark[], reactVersion: string | null, schedulingEvents: SchedulingEvent[], snapshots: Snapshot[], snapshotHeight: number, startTime: number, suspenseEvents: SuspenseEvent[], thrownErrors: ThrownError[], }; export type ReactEventInfo = { componentMeasure: ReactComponentMeasure | null, flamechartStackFrame: FlamechartStackFrame | null, measure: ReactMeasure | null, nativeEvent: NativeEvent | null, networkMeasure: NetworkMeasure | null, schedulingEvent: SchedulingEvent | null, suspenseEvent: SuspenseEvent | null, snapshot: Snapshot | null, thrownError: ThrownError | null, userTimingMark: UserTimingMark | null, };
25.572549
79
0.73786
PenetrationTestingScripts
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from 'react-client/src/ReactFlightClientConfigBrowser'; export * from 'react-server-dom-turbopack/src/ReactFlightClientConfigBundlerTurbopack'; export * from 'react-server-dom-turbopack/src/ReactFlightClientConfigBundlerTurbopackBrowser'; export * from 'react-server-dom-turbopack/src/ReactFlightClientConfigTargetTurbopackBrowser'; export * from 'react-dom-bindings/src/shared/ReactFlightClientConfigDOM'; export const usedWithSSR = false;
39.9375
94
0.795107
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ // Patch fetch import './ReactFetch'; export {default as __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED} from './ReactSharedInternalsServer'; export {default as __SECRET_SERVER_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED} from './ReactServerSharedInternals'; export { Children, Fragment, Profiler, StrictMode, Suspense, cloneElement, createElement, createRef, createServerContext, use, forwardRef, isValidElement, lazy, memo, cache, startTransition, useId, useCallback, useContext, useDebugValue, useMemo, version, } from './React';
18.195122
114
0.709924