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
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. * * @noflow */ const hasReadOnlyValue = { button: true, checkbox: true, image: true, hidden: true, radio: true, reset: true, submit: true, }; export function checkControlledValueProps( tagName: string, props: Object, ): void { if (__DEV__) { if ( !( hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null ) ) { if (tagName === 'select') { console.error( 'You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, set `onChange`.', ); } else { console.error( 'You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.', ); } } if ( !( props.onChange || props.readOnly || props.disabled || props.checked == null ) ) { console.error( 'You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.', ); } } }
24.955224
110
0.563291
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 strict-local */ import type { BasicSourceMap, MixedSourceMap, IndexSourceMap, } from './SourceMapTypes'; export function sourceMapIncludesSource( sourcemap: MixedSourceMap, source: ?string, ): boolean { if (source == null) { return false; } if (sourcemap.mappings === undefined) { const indexSourceMap: IndexSourceMap = sourcemap; return indexSourceMap.sections.some(section => { return sourceMapIncludesSource(section.map, source); }); } const basicMap: BasicSourceMap = sourcemap; return basicMap.sources.some( s => s === 'Inline Babel script' || source.endsWith(s), ); }
22.628571
66
0.692494
PenetrationTestingScripts
// test() is part of Jest's serializer API export function test(maybeInspectedElement) { if ( maybeInspectedElement === null || typeof maybeInspectedElement !== 'object' ) { return false; } const hasOwnProperty = Object.prototype.hasOwnProperty.bind( maybeInspectedElement, ); return ( hasOwnProperty('canEditFunctionProps') && hasOwnProperty('canEditHooks') && hasOwnProperty('canToggleSuspense') && hasOwnProperty('canToggleError') && hasOwnProperty('canViewSource') ); } // print() is part of Jest's serializer API export function print(inspectedElement, serialize, indent) { // Don't stringify this object; that would break nested serializers. return serialize({ context: inspectedElement.context, events: inspectedElement.events, hooks: inspectedElement.hooks, id: inspectedElement.id, owners: inspectedElement.owners, props: inspectedElement.props, rootType: inspectedElement.rootType, state: inspectedElement.state, }); }
26.594595
70
0.716667
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 waitForAll; let act; describe('ReactSuspense', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; act = InternalTestUtils.act; }); function createThenable() { let completed = false; let resolve; const promise = new Promise(res => { resolve = () => { completed = true; res(); }; }); const PromiseComp = () => { if (!completed) { throw promise; } return 'Done'; }; return {promise, resolve, PromiseComp}; } // Warning don't fire in production, so this test passes in prod even if // the suspenseCallback feature is not enabled // @gate www || !__DEV__ it('check type', async () => { const {PromiseComp} = createThenable(); const elementBadType = ( <React.Suspense suspenseCallback={1} fallback={'Waiting'}> <PromiseComp /> </React.Suspense> ); ReactNoop.render(elementBadType); await expect(async () => await waitForAll([])).toErrorDev([ 'Warning: Unexpected type for suspenseCallback.', ]); const elementMissingCallback = ( <React.Suspense fallback={'Waiting'}> <PromiseComp /> </React.Suspense> ); ReactNoop.render(elementMissingCallback); await expect(async () => await waitForAll([])).toErrorDev([]); }); // @gate www it('1 then 0 suspense callback', async () => { const {promise, resolve, PromiseComp} = createThenable(); let ops = []; const suspenseCallback = thenables => { ops.push(thenables); }; const element = ( <React.Suspense suspenseCallback={suspenseCallback} fallback={'Waiting'}> <PromiseComp /> </React.Suspense> ); ReactNoop.render(element); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput('Waiting'); expect(ops).toEqual([new Set([promise])]); ops = []; await act(() => resolve()); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput('Done'); expect(ops).toEqual([]); }); // @gate www it('2 then 1 then 0 suspense callback', async () => { const { promise: promise1, resolve: resolve1, PromiseComp: PromiseComp1, } = createThenable(); const { promise: promise2, resolve: resolve2, PromiseComp: PromiseComp2, } = createThenable(); let ops = []; const suspenseCallback1 = thenables => { ops.push(thenables); }; const element = ( <React.Suspense suspenseCallback={suspenseCallback1} fallback={'Waiting Tier 1'}> <PromiseComp1 /> <PromiseComp2 /> </React.Suspense> ); ReactNoop.render(element); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput('Waiting Tier 1'); expect(ops).toEqual([new Set([promise1])]); ops = []; await act(() => resolve1()); ReactNoop.render(element); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput('Waiting Tier 1'); expect(ops).toEqual([new Set([promise2])]); ops = []; await act(() => resolve2()); ReactNoop.render(element); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput('DoneDone'); expect(ops).toEqual([]); }); // @gate www it('nested suspense promises are reported only for their tier', async () => { const {promise, PromiseComp} = createThenable(); const ops1 = []; const suspenseCallback1 = thenables => { ops1.push(thenables); }; const ops2 = []; const suspenseCallback2 = thenables => { ops2.push(thenables); }; const element = ( <React.Suspense suspenseCallback={suspenseCallback1} fallback={'Waiting Tier 1'}> <React.Suspense suspenseCallback={suspenseCallback2} fallback={'Waiting Tier 2'}> <PromiseComp /> </React.Suspense> </React.Suspense> ); ReactNoop.render(element); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput('Waiting Tier 2'); expect(ops1).toEqual([]); expect(ops2).toEqual([new Set([promise])]); }); // @gate www it('competing suspense promises', async () => { const { promise: promise1, resolve: resolve1, PromiseComp: PromiseComp1, } = createThenable(); const { promise: promise2, resolve: resolve2, PromiseComp: PromiseComp2, } = createThenable(); let ops1 = []; const suspenseCallback1 = thenables => { ops1.push(thenables); }; let ops2 = []; const suspenseCallback2 = thenables => { ops2.push(thenables); }; const element = ( <React.Suspense suspenseCallback={suspenseCallback1} fallback={'Waiting Tier 1'}> <React.Suspense suspenseCallback={suspenseCallback2} fallback={'Waiting Tier 2'}> <PromiseComp2 /> </React.Suspense> <PromiseComp1 /> </React.Suspense> ); ReactNoop.render(element); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput('Waiting Tier 1'); expect(ops1).toEqual([new Set([promise1])]); expect(ops2).toEqual([]); ops1 = []; ops2 = []; await act(() => resolve1()); expect(ReactNoop).toMatchRenderedOutput('Waiting Tier 2Done'); expect(ops1).toEqual([]); expect(ops2).toEqual([new Set([promise2])]); ops1 = []; ops2 = []; await act(() => resolve2()); expect(ReactNoop).toMatchRenderedOutput('DoneDone'); expect(ops1).toEqual([]); expect(ops2).toEqual([]); }); });
24.504237
79
0.601363
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 */ let JSDOM; let React; let startTransition; let ReactDOMClient; let Scheduler; let clientAct; let ReactDOMFizzServer; let Stream; let document; let writable; let container; let buffer = ''; let hasErrored = false; let fatalError = undefined; let textCache; let assertLog; describe('ReactDOMFizzShellHydration', () => { beforeEach(() => { jest.resetModules(); JSDOM = require('jsdom').JSDOM; React = require('react'); ReactDOMClient = require('react-dom/client'); Scheduler = require('scheduler'); clientAct = require('internal-test-utils').act; ReactDOMFizzServer = require('react-dom/server'); Stream = require('stream'); const InternalTestUtils = require('internal-test-utils'); assertLog = InternalTestUtils.assertLog; startTransition = React.startTransition; textCache = new Map(); // Test Environment const jsdom = new JSDOM( '<!DOCTYPE html><html><head></head><body><div id="container">', { runScripts: 'dangerously', }, ); document = jsdom.window.document; container = document.getElementById('container'); buffer = ''; hasErrored = false; writable = new Stream.PassThrough(); writable.setEncoding('utf8'); writable.on('data', chunk => { buffer += chunk; }); writable.on('error', error => { hasErrored = true; fatalError = error; }); }); afterEach(() => { jest.restoreAllMocks(); }); async function serverAct(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. const bufferedContent = buffer; buffer = ''; const fakeBody = document.createElement('body'); fakeBody.innerHTML = bufferedContent; while (fakeBody.firstChild) { const node = fakeBody.firstChild; if (node.nodeName === 'SCRIPT') { const script = document.createElement('script'); script.textContent = node.textContent; fakeBody.removeChild(node); container.appendChild(script); } else { container.appendChild(node); } } } 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 { 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; } function resetTextCache() { textCache = new Map(); } test('suspending in the shell during hydration', async () => { const div = React.createRef(null); function App() { return ( <div ref={div}> <AsyncText text="Shell" /> </div> ); } // Server render await resolveText('Shell'); await serverAct(async () => { const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />); pipe(writable); }); assertLog(['Shell']); const dehydratedDiv = container.getElementsByTagName('div')[0]; // Clear the cache and start rendering on the client resetTextCache(); // Hydration suspends because the data for the shell hasn't loaded yet await clientAct(async () => { ReactDOMClient.hydrateRoot(container, <App />); }); assertLog(['Suspend! [Shell]']); expect(div.current).toBe(null); expect(container.textContent).toBe('Shell'); // The shell loads and hydration finishes await clientAct(async () => { await resolveText('Shell'); }); assertLog(['Shell']); expect(div.current).toBe(dehydratedDiv); expect(container.textContent).toBe('Shell'); }); test('suspending in the shell during a normal client render', async () => { // Same as previous test but during a normal client render, no hydration function App() { return <AsyncText text="Shell" />; } const root = ReactDOMClient.createRoot(container); await clientAct(async () => { root.render(<App />); }); assertLog(['Suspend! [Shell]']); await clientAct(async () => { await resolveText('Shell'); }); assertLog(['Shell']); expect(container.textContent).toBe('Shell'); }); test( 'updating the root at lower priority than initial hydration does not ' + 'force a client render', async () => { function App() { return <Text text="Initial" />; } // Server render await resolveText('Initial'); await serverAct(async () => { const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />); pipe(writable); }); assertLog(['Initial']); await clientAct(async () => { const root = ReactDOMClient.hydrateRoot(container, <App />); // This has lower priority than the initial hydration, so the update // won't be processed until after hydration finishes. startTransition(() => { root.render(<Text text="Updated" />); }); }); assertLog(['Initial', 'Updated']); expect(container.textContent).toBe('Updated'); }, ); test('updating the root while the shell is suspended forces a client render', async () => { function App() { return <AsyncText text="Shell" />; } // Server render await resolveText('Shell'); await serverAct(async () => { const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />); pipe(writable); }); assertLog(['Shell']); // Clear the cache and start rendering on the client resetTextCache(); // Hydration suspends because the data for the shell hasn't loaded yet const root = await clientAct(async () => { return ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error) { Scheduler.log(error.message); }, }); }); assertLog(['Suspend! [Shell]']); expect(container.textContent).toBe('Shell'); await clientAct(async () => { root.render(<Text text="New screen" />); }); assertLog([ 'New screen', 'This root received an early update, before anything was able ' + 'hydrate. Switched the entire root to client rendering.', ]); expect(container.textContent).toBe('New screen'); }); test('TODO: A large component stack causes SSR to stack overflow', async () => { spyOnDevAndProd(console, 'error').mockImplementation(() => {}); function NestedComponent({depth}: {depth: number}) { if (depth <= 0) { return <AsyncText text="Shell" />; } return <NestedComponent depth={depth - 1} />; } // Server render await serverAct(async () => { ReactDOMFizzServer.renderToPipeableStream( <NestedComponent depth={3000} />, ); }); expect(console.error).toHaveBeenCalledTimes(1); expect(console.error.mock.calls[0][0].toString()).toBe( 'RangeError: Maximum call stack size exceeded', ); }); });
26.235849
93
0.606582
owtf
/* eslint-disable react/react-in-jsx-scope, react/jsx-no-undef */ /* global React ReactCache ReactDOM SchedulerTracing ScheduleTracing */ const apps = []; const pieces = React.version.split('.'); const major = pieces[0] === '0' ? parseInt(pieces[1], 10) : parseInt(pieces[0], 10); const minor = pieces[0] === '0' ? parseInt(pieces[2], 10) : parseInt(pieces[1], 10); // Convenience wrapper to organize API features in DevTools. function Feature({children, label, version}) { return ( <div className="Feature"> <div className="FeatureHeader"> <code className="FeatureCode">{label}</code> <small>{version}</small> </div> {children} </div> ); } // Simplify interaction tracing for tests below. let trace = null; if (typeof SchedulerTracing !== 'undefined') { trace = SchedulerTracing.unstable_trace; } else if (typeof ScheduleTracing !== 'undefined') { trace = ScheduleTracing.unstable_trace; } else { trace = (_, __, callback) => callback(); } // https://github.com/facebook/react/blob/main/CHANGELOG.md switch (major) { case 16: switch (minor) { case 7: if (typeof React.useState === 'function') { // Hooks function Hooks() { const [count, setCount] = React.useState(0); const incrementCount = React.useCallback( () => setCount(count + 1), [count] ); return ( <div> count: {count}{' '} <button onClick={incrementCount}>increment</button> </div> ); } apps.push( <Feature key="Hooks" label="Hooks" version="16.7+"> <Hooks /> </Feature> ); } case 6: // memo function LabelComponent({label}) { return <label>{label}</label>; } const AnonymousMemoized = React.memo(({label}) => ( <label>{label}</label> )); const Memoized = React.memo(LabelComponent); const CustomMemoized = React.memo(LabelComponent); CustomMemoized.displayName = 'MemoizedLabelFunction'; apps.push( <Feature key="memo" label="memo" version="16.6+"> <AnonymousMemoized label="AnonymousMemoized" /> <Memoized label="Memoized" /> <CustomMemoized label="CustomMemoized" /> </Feature> ); // Suspense const loadResource = ([text, ms]) => { return new Promise((resolve, reject) => { setTimeout(() => { resolve(text); }, ms); }); }; const getResourceKey = ([text, ms]) => text; const Resource = ReactCache.unstable_createResource( loadResource, getResourceKey ); class Suspending extends React.Component { state = {useSuspense: false}; useSuspense = () => this.setState({useSuspense: true}); render() { if (this.state.useSuspense) { const text = Resource.read(['loaded', 2000]); return text; } else { return <button onClick={this.useSuspense}>load data</button>; } } } apps.push( <Feature key="Suspense" label="Suspense" version="16.6+"> <React.Suspense fallback={<div>loading...</div>}> <Suspending /> </React.Suspense> </Feature> ); // lazy const LazyWithDefaultProps = React.lazy( () => new Promise(resolve => { function FooWithDefaultProps(props) { return ( <h1> {props.greeting}, {props.name} </h1> ); } FooWithDefaultProps.defaultProps = { name: 'World', greeting: 'Bonjour', }; resolve({ default: FooWithDefaultProps, }); }) ); apps.push( <Feature key="lazy" label="lazy" version="16.6+"> <React.Suspense fallback={<div>loading...</div>}> <LazyWithDefaultProps greeting="Hello" /> </React.Suspense> </Feature> ); case 5: case 4: // unstable_Profiler class ProfilerChild extends React.Component { state = {count: 0}; incrementCount = () => this.setState(prevState => ({count: prevState.count + 1})); render() { return ( <div> count: {this.state.count}{' '} <button onClick={this.incrementCount}>increment</button> </div> ); } } const onRender = (...args) => {}; const Profiler = React.unstable_Profiler || React.Profiler; apps.push( <Feature key="unstable_Profiler" label="unstable_Profiler" version="16.4+"> <Profiler id="count" onRender={onRender}> <div> <ProfilerChild /> </div> </Profiler> </Feature> ); case 3: // createContext() const LocaleContext = React.createContext(); LocaleContext.displayName = 'LocaleContext'; const ThemeContext = React.createContext(); apps.push( <Feature key="createContext" label="createContext" version="16.3+"> <ThemeContext.Provider value="blue"> <ThemeContext.Consumer> {theme => <div>theme: {theme}</div>} </ThemeContext.Consumer> </ThemeContext.Provider> <LocaleContext.Provider value="en-US"> <LocaleContext.Consumer> {locale => <div>locale: {locale}</div>} </LocaleContext.Consumer> </LocaleContext.Provider> </Feature> ); // forwardRef() const AnonymousFunction = React.forwardRef((props, ref) => ( <div ref={ref}>{props.children}</div> )); const NamedFunction = React.forwardRef(function named(props, ref) { return <div ref={ref}>{props.children}</div>; }); const CustomName = React.forwardRef((props, ref) => ( <div ref={ref}>{props.children}</div> )); CustomName.displayName = 'CustomNameForwardRef'; apps.push( <Feature key="forwardRef" label="forwardRef" version="16.3+"> <AnonymousFunction>AnonymousFunction</AnonymousFunction> <NamedFunction>NamedFunction</NamedFunction> <CustomName>CustomName</CustomName> </Feature> ); // StrictMode class StrictModeChild extends React.Component { render() { return 'StrictModeChild'; } } apps.push( <Feature key="StrictMode" label="StrictMode" version="16.3+"> <React.StrictMode> <StrictModeChild /> </React.StrictMode> </Feature> ); // unstable_AsyncMode (later renamed to unstable_ConcurrentMode, then ConcurrentMode) const ConcurrentMode = React.ConcurrentMode || React.unstable_ConcurrentMode || React.unstable_AsyncMode; apps.push( <Feature key="AsyncMode/ConcurrentMode" label="AsyncMode/ConcurrentMode" version="16.3+"> <ConcurrentMode> <div> unstable_AsyncMode was added in 16.3, renamed to unstable_ConcurrentMode in 16.5, and then renamed to ConcurrentMode in 16.7 </div> </ConcurrentMode> </Feature> ); case 2: // Fragment apps.push( <Feature key="Fragment" label="Fragment" version="16.4+"> <React.Fragment> <div>one</div> <div>two</div> </React.Fragment> </Feature> ); case 1: case 0: default: break; } break; case 15: break; case 14: break; default: break; } function Even() { return <small>(even)</small>; } // Simple stateful app shared by all React versions class SimpleApp extends React.Component { state = {count: 0}; incrementCount = () => { const updaterFn = prevState => ({count: prevState.count + 1}); trace('Updating count', performance.now(), () => this.setState(updaterFn)); }; render() { const {count} = this.state; return ( <div> {count % 2 === 0 ? ( <span> count: {count} <Even /> </span> ) : ( <span>count: {count}</span> )}{' '} <button onClick={this.incrementCount}>increment</button> </div> ); } } apps.push( <Feature key="Simple stateful app" label="Simple stateful app" version="any"> <SimpleApp /> </Feature> ); // This component, with the version prop, helps organize DevTools at a glance. function TopLevelWrapperForDevTools({version}) { let header = <h1>React {version}</h1>; if (version.includes('canary')) { const commitSha = version.match(/.+canary-(.+)/)[1]; header = ( <h1> React canary{' '} <a href={`https://github.com/facebook/react/commit/${commitSha}`}> {commitSha} </a> </h1> ); } else if (version.includes('alpha')) { header = <h1>React next</h1>; } return ( <div> {header} {apps} </div> ); } TopLevelWrapperForDevTools.displayName = 'React'; ReactDOM.render( <TopLevelWrapperForDevTools version={React.version} />, document.getElementById('root') );
28.984802
93
0.518958
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
PenTesting
'use strict'; module.exports = require('./cjs/react-server-dom-webpack-node-register.js');
22.25
76
0.728261
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 */ describe('useEditableValue', () => { let act; let React; let legacyRender; let useEditableValue; beforeEach(() => { const utils = require('./utils'); act = utils.act; legacyRender = utils.legacyRender; React = require('react'); useEditableValue = require('../devtools/views/hooks').useEditableValue; }); it('should not cause a loop with values like NaN', () => { let state; function Example({value = NaN}) { const tuple = useEditableValue(value); state = tuple[0]; return null; } const container = document.createElement('div'); legacyRender(<Example />, container); expect(state.editableValue).toEqual('NaN'); expect(state.externalValue).toEqual(NaN); expect(state.parsedValue).toEqual(NaN); expect(state.hasPendingChanges).toBe(false); expect(state.isValid).toBe(true); }); it('should override editable state when external props are updated', () => { let state; function Example({value}) { const tuple = useEditableValue(value); state = tuple[0]; return null; } const container = document.createElement('div'); legacyRender(<Example value={1} />, container); expect(state.editableValue).toEqual('1'); expect(state.externalValue).toEqual(1); expect(state.parsedValue).toEqual(1); expect(state.hasPendingChanges).toBe(false); expect(state.isValid).toBe(true); // If there are NO pending changes, // an update to the external prop value should override the local/pending value. legacyRender(<Example value={2} />, container); expect(state.editableValue).toEqual('2'); expect(state.externalValue).toEqual(2); expect(state.parsedValue).toEqual(2); expect(state.hasPendingChanges).toBe(false); expect(state.isValid).toBe(true); }); it('should not override editable state when external props are updated if there are pending changes', () => { let dispatch, state; function Example({value}) { const tuple = useEditableValue(value); state = tuple[0]; dispatch = tuple[1]; return null; } const container = document.createElement('div'); legacyRender(<Example value={1} />, container); expect(state.editableValue).toEqual('1'); expect(state.externalValue).toEqual(1); expect(state.parsedValue).toEqual(1); expect(state.hasPendingChanges).toBe(false); expect(state.isValid).toBe(true); // Update (local) editable state. act(() => dispatch({ type: 'UPDATE', editableValue: '2', externalValue: 1, }), ); expect(state.editableValue).toEqual('2'); expect(state.externalValue).toEqual(1); expect(state.parsedValue).toEqual(2); expect(state.hasPendingChanges).toBe(true); expect(state.isValid).toBe(true); // If there ARE pending changes, // an update to the external prop value should NOT override the local/pending value. legacyRender(<Example value={3} />, container); expect(state.editableValue).toEqual('2'); expect(state.externalValue).toEqual(3); expect(state.parsedValue).toEqual(2); expect(state.hasPendingChanges).toBe(true); expect(state.isValid).toBe(true); }); it('should parse edits to ensure valid JSON', () => { let dispatch, state; function Example({value}) { const tuple = useEditableValue(value); state = tuple[0]; dispatch = tuple[1]; return null; } const container = document.createElement('div'); legacyRender(<Example value={1} />, container); expect(state.editableValue).toEqual('1'); expect(state.externalValue).toEqual(1); expect(state.parsedValue).toEqual(1); expect(state.hasPendingChanges).toBe(false); expect(state.isValid).toBe(true); // Update (local) editable state. act(() => dispatch({ type: 'UPDATE', editableValue: '"a', externalValue: 1, }), ); expect(state.editableValue).toEqual('"a'); expect(state.externalValue).toEqual(1); expect(state.parsedValue).toEqual(1); expect(state.hasPendingChanges).toBe(true); expect(state.isValid).toBe(false); }); it('should reset to external value upon request', () => { let dispatch, state; function Example({value}) { const tuple = useEditableValue(value); state = tuple[0]; dispatch = tuple[1]; return null; } const container = document.createElement('div'); legacyRender(<Example value={1} />, container); expect(state.editableValue).toEqual('1'); expect(state.externalValue).toEqual(1); expect(state.parsedValue).toEqual(1); expect(state.hasPendingChanges).toBe(false); expect(state.isValid).toBe(true); // Update (local) editable state. act(() => dispatch({ type: 'UPDATE', editableValue: '2', externalValue: 1, }), ); expect(state.editableValue).toEqual('2'); expect(state.externalValue).toEqual(1); expect(state.parsedValue).toEqual(2); expect(state.hasPendingChanges).toBe(true); expect(state.isValid).toBe(true); // Reset editable state act(() => dispatch({ type: 'RESET', externalValue: 1, }), ); expect(state.editableValue).toEqual('1'); expect(state.externalValue).toEqual(1); expect(state.parsedValue).toEqual(1); expect(state.hasPendingChanges).toBe(false); expect(state.isValid).toBe(true); }); });
28.635417
111
0.647214
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 * as React from 'react'; import * as ReactDOM from 'react-dom'; const {useLayoutEffect, useRef} = React; const {unstable_createEventHandle} = ReactDOM; type UseEventHandle = { setListener: ( target: EventTarget, null | ((SyntheticEvent<EventTarget>) => void), ) => void, clear: () => void, }; export default function useEvent( event: string, options?: { capture?: boolean, }, ): UseEventHandle { const handleRef = useRef<UseEventHandle | null>(null); let useEventHandle = handleRef.current; if (useEventHandle === null) { const setEventHandle = unstable_createEventHandle(event, options); const clears = new Map<EventTarget, () => void>(); useEventHandle = { setListener( target: EventTarget, callback: null | ((SyntheticEvent<EventTarget>) => void), ): void { let clear = clears.get(target); if (clear !== undefined) { clear(); } if (callback === null) { clears.delete(target); return; } clear = setEventHandle(target, callback); clears.set(target, clear); }, clear(): void { clears.forEach(c => { c(); }); clears.clear(); }, }; handleRef.current = useEventHandle; } useLayoutEffect(() => { return () => { if (useEventHandle !== null) { useEventHandle.clear(); } handleRef.current = null; }; }, [useEventHandle]); return useEventHandle; }
22.506849
70
0.588921
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'; // TODO: All these warnings should become static errors using Flow instead // of dynamic errors when using JSX with Flow. let React; let ReactDOM; let ReactTestUtils; let PropTypes; describe('ReactJSXElementValidator', () => { let Component; let RequiredPropComponent; beforeEach(() => { jest.resetModules(); PropTypes = require('prop-types'); React = require('react'); ReactDOM = require('react-dom'); ReactTestUtils = require('react-dom/test-utils'); Component = class extends React.Component { render() { return <div />; } }; RequiredPropComponent = class extends React.Component { render() { return <span>{this.props.prop}</span>; } }; RequiredPropComponent.displayName = 'RequiredPropComponent'; RequiredPropComponent.propTypes = {prop: PropTypes.string.isRequired}; }); 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('warns for keys for iterables of elements in rest args', () => { const iterable = { '@@iterator': function () { let i = 0; return { next: function () { const done = ++i > 2; return {value: done ? undefined : <Component />, done: done}; }, }; }, }; expect(() => ReactTestUtils.renderIntoDocument(<Component>{iterable}</Component>), ).toErrorDev('Each child in a list should have a unique "key" prop.'); }); 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. class MyComp extends React.Component { render() { return <div>My color is {this.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('should update component stack after receiving next element', () => { function MyComp() { return null; } MyComp.propTypes = { color: PropTypes.string, }; function MiddleComp(props) { return <MyComp color={props.color} />; } function ParentComp(props) { if (props.warn) { // This element has a source thanks to JSX. return <MiddleComp color={42} />; } // This element has no source. return React.createElement(MiddleComp, {color: 'blue'}); } const container = document.createElement('div'); ReactDOM.render(<ParentComp warn={false} />, container); expect(() => ReactDOM.render(<ParentComp warn={true} />, container), ).toErrorDev( 'Warning: Failed prop type: ' + 'Invalid prop `color` of type `number` supplied to `MyComp`, ' + 'expected `string`.\n' + ' in MyComp (at **)\n' + ' in MiddleComp (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.createElement: 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.' + '\n\nCheck your code at **.', {withoutStack: true}, ); expect(() => void (<Null />)).toErrorDev( 'Warning: React.createElement: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: null.' + '\n\nCheck your code at **.', {withoutStack: true}, ); expect(() => void (<True />)).toErrorDev( 'Warning: React.createElement: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: boolean.' + '\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 not check the default for explicit null', () => { expect(() => ReactTestUtils.renderIntoDocument(<RequiredPropComponent prop={null} />), ).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 check declared prop types', () => { expect(() => ReactTestUtils.renderIntoDocument(<RequiredPropComponent />), ).toErrorDev( 'Warning: Failed prop type: ' + 'The prop `prop` is marked as required in `RequiredPropComponent`, but ' + 'its value is `undefined`.\n' + ' in RequiredPropComponent (at **)', ); expect(() => ReactTestUtils.renderIntoDocument(<RequiredPropComponent prop={42} />), ).toErrorDev( 'Warning: Failed prop type: ' + 'Invalid prop `prop` of type `number` supplied to ' + '`RequiredPropComponent`, expected `string`.\n' + ' in RequiredPropComponent (at **)', ); // Should not error for strings ReactTestUtils.renderIntoDocument(<RequiredPropComponent prop="string" />); }); 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,', ); }); // @gate !disableLegacyContext || !__DEV__ 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); }); });
29.960094
82
0.587352
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = _interopRequireWildcard(require("react")); var _jsxFileName = ""; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function Component() { const [count, setCount] = (0, _react.useState)(0); const isDarkMode = useIsDarkMode(); const { foo } = useFoo(); (0, _react.useEffect)(() => {// ... }, []); const handleClick = () => setCount(count + 1); return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 25, columnNumber: 7 } }, "Dark mode? ", isDarkMode), /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 26, columnNumber: 7 } }, "Count: ", count), /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 27, columnNumber: 7 } }, "Foo: ", foo), /*#__PURE__*/_react.default.createElement("button", { onClick: handleClick, __source: { fileName: _jsxFileName, lineNumber: 28, columnNumber: 7 } }, "Update count")); } function useIsDarkMode() { const [isDarkMode] = (0, _react.useState)(false); (0, _react.useEffect)(function useEffectCreate() {// Here is where we may listen to a "theme" event... }, []); return isDarkMode; } function useFoo() { (0, _react.useDebugValue)('foo'); return { foo: true }; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhDdXN0b21Ib29rLmpzIl0sIm5hbWVzIjpbIkNvbXBvbmVudCIsImNvdW50Iiwic2V0Q291bnQiLCJpc0RhcmtNb2RlIiwidXNlSXNEYXJrTW9kZSIsImZvbyIsInVzZUZvbyIsImhhbmRsZUNsaWNrIiwidXNlRWZmZWN0Q3JlYXRlIl0sIm1hcHBpbmdzIjoiOzs7Ozs7O0FBU0E7Ozs7Ozs7O0FBRU8sU0FBU0EsU0FBVCxHQUFxQjtBQUMxQixRQUFNLENBQUNDLEtBQUQsRUFBUUMsUUFBUixJQUFvQixxQkFBUyxDQUFULENBQTFCO0FBQ0EsUUFBTUMsVUFBVSxHQUFHQyxhQUFhLEVBQWhDO0FBQ0EsUUFBTTtBQUFDQyxJQUFBQTtBQUFELE1BQVFDLE1BQU0sRUFBcEI7QUFFQSx3QkFBVSxNQUFNLENBQ2Q7QUFDRCxHQUZELEVBRUcsRUFGSDs7QUFJQSxRQUFNQyxXQUFXLEdBQUcsTUFBTUwsUUFBUSxDQUFDRCxLQUFLLEdBQUcsQ0FBVCxDQUFsQzs7QUFFQSxzQkFDRSx5RUFDRTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxvQkFBaUJFLFVBQWpCLENBREYsZUFFRTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxnQkFBYUYsS0FBYixDQUZGLGVBR0U7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsY0FBV0ksR0FBWCxDQUhGLGVBSUU7QUFBUSxJQUFBLE9BQU8sRUFBRUUsV0FBakI7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsb0JBSkYsQ0FERjtBQVFEOztBQUVELFNBQVNILGFBQVQsR0FBeUI7QUFDdkIsUUFBTSxDQUFDRCxVQUFELElBQWUscUJBQVMsS0FBVCxDQUFyQjtBQUVBLHdCQUFVLFNBQVNLLGVBQVQsR0FBMkIsQ0FDbkM7QUFDRCxHQUZELEVBRUcsRUFGSDtBQUlBLFNBQU9MLFVBQVA7QUFDRDs7QUFFRCxTQUFTRyxNQUFULEdBQWtCO0FBQ2hCLDRCQUFjLEtBQWQ7QUFDQSxTQUFPO0FBQUNELElBQUFBLEdBQUcsRUFBRTtBQUFOLEdBQVA7QUFDRCIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogQ29weXJpZ2h0IChjKSBGYWNlYm9vaywgSW5jLiBhbmQgaXRzIGFmZmlsaWF0ZXMuXG4gKlxuICogVGhpcyBzb3VyY2UgY29kZSBpcyBsaWNlbnNlZCB1bmRlciB0aGUgTUlUIGxpY2Vuc2UgZm91bmQgaW4gdGhlXG4gKiBMSUNFTlNFIGZpbGUgaW4gdGhlIHJvb3QgZGlyZWN0b3J5IG9mIHRoaXMgc291cmNlIHRyZWUuXG4gKlxuICogQGZsb3dcbiAqL1xuXG5pbXBvcnQgUmVhY3QsIHt1c2VEZWJ1Z1ZhbHVlLCB1c2VFZmZlY3QsIHVzZVN0YXRlfSBmcm9tICdyZWFjdCc7XG5cbmV4cG9ydCBmdW5jdGlvbiBDb21wb25lbnQoKSB7XG4gIGNvbnN0IFtjb3VudCwgc2V0Q291bnRdID0gdXNlU3RhdGUoMCk7XG4gIGNvbnN0IGlzRGFya01vZGUgPSB1c2VJc0RhcmtNb2RlKCk7XG4gIGNvbnN0IHtmb299ID0gdXNlRm9vKCk7XG5cbiAgdXNlRWZmZWN0KCgpID0+IHtcbiAgICAvLyAuLi5cbiAgfSwgW10pO1xuXG4gIGNvbnN0IGhhbmRsZUNsaWNrID0gKCkgPT4gc2V0Q291bnQoY291bnQgKyAxKTtcblxuICByZXR1cm4gKFxuICAgIDw+XG4gICAgICA8ZGl2PkRhcmsgbW9kZT8ge2lzRGFya01vZGV9PC9kaXY+XG4gICAgICA8ZGl2PkNvdW50OiB7Y291bnR9PC9kaXY+XG4gICAgICA8ZGl2PkZvbzoge2Zvb308L2Rpdj5cbiAgICAgIDxidXR0b24gb25DbGljaz17aGFuZGxlQ2xpY2t9PlVwZGF0ZSBjb3VudDwvYnV0dG9uPlxuICAgIDwvPlxuICApO1xufVxuXG5mdW5jdGlvbiB1c2VJc0RhcmtNb2RlKCkge1xuICBjb25zdCBbaXNEYXJrTW9kZV0gPSB1c2VTdGF0ZShmYWxzZSk7XG5cbiAgdXNlRWZmZWN0KGZ1bmN0aW9uIHVzZUVmZmVjdENyZWF0ZSgpIHtcbiAgICAvLyBIZXJlIGlzIHdoZXJlIHdlIG1heSBsaXN0ZW4gdG8gYSBcInRoZW1lXCIgZXZlbnQuLi5cbiAgfSwgW10pO1xuXG4gIHJldHVybiBpc0RhcmtNb2RlO1xufVxuXG5mdW5jdGlvbiB1c2VGb28oKSB7XG4gIHVzZURlYnVnVmFsdWUoJ2ZvbycpO1xuICByZXR1cm4ge2ZvbzogdHJ1ZX07XG59XG4iXX0=
74.970588
2,684
0.818974
Mastering-Kali-Linux-for-Advanced-Penetration-Testing-4E
// @flow // Pulled from react-compat // https://github.com/developit/preact-compat/blob/7c5de00e7c85e2ffd011bf3af02899b63f699d3a/src/index.js#L349 export default function shallowDiffers(prev: Object, next: Object): boolean { for (let attribute in prev) { if (!(attribute in next)) { return true; } } for (let attribute in next) { if (prev[attribute] !== next[attribute]) { return true; } } return false; }
23.777778
109
0.669663
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 isArray from 'shared/isArray'; import {getCurrentFiberOwnerNameInDevOrNull} from 'react-reconciler/src/ReactCurrentFiber'; import {getToStringValue, toString} from './ToStringValue'; import {disableTextareaChildren} from 'shared/ReactFeatureFlags'; let didWarnValDefaultVal = false; /** * Implements a <textarea> host component that allows setting `value`, and * `defaultValue`. This differs from the traditional DOM API because value is * usually set as PCDATA children. * * If `value` is not supplied (or null/undefined), user actions that affect the * value will trigger updates to the element. * * If `value` is supplied (and not null/undefined), the rendered element will * not trigger updates to the element. Instead, the `value` prop must change in * order for the rendered element to be updated. * * The rendered element will be initialized with an empty value, the prop * `defaultValue` if specified, or the children content (deprecated). */ export function validateTextareaProps(element: Element, props: Object) { if (__DEV__) { if ( props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal ) { console.error( '%s contains a textarea with both value and defaultValue props. ' + 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', ); didWarnValDefaultVal = true; } if (props.children != null && props.value == null) { console.error( 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.', ); } } } export function updateTextarea( element: Element, value: ?string, defaultValue: ?string, ) { const node: HTMLTextAreaElement = (element: any); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. const newValue = toString(getToStringValue(value)); // To avoid side effects (such as losing text selection), only set value if changed if (newValue !== node.value) { node.value = newValue; } // TOOO: This should respect disableInputAttributeSyncing flag. if (defaultValue == null) { if (node.defaultValue !== newValue) { node.defaultValue = newValue; } return; } } if (defaultValue != null) { node.defaultValue = toString(getToStringValue(defaultValue)); } else { node.defaultValue = ''; } } export function initTextarea( element: Element, value: ?string, defaultValue: ?string, children: ?string, ) { const node: HTMLTextAreaElement = (element: any); let initialValue = value; // Only bother fetching default value if we're going to use it if (initialValue == null) { if (children != null) { if (!disableTextareaChildren) { if (defaultValue != null) { throw new Error( 'If you supply `defaultValue` on a <textarea>, do not pass children.', ); } if (isArray(children)) { if (children.length > 1) { throw new Error('<textarea> can only have at most one child.'); } children = children[0]; } defaultValue = children; } } if (defaultValue == null) { defaultValue = ''; } initialValue = defaultValue; } const stringValue = getToStringValue(initialValue); node.defaultValue = (stringValue: any); // This will be toString:ed. // This is in postMount because we need access to the DOM node, which is not // available until after the component has mounted. const textContent = node.textContent; // Only set node.value if textContent is equal to the expected // initial value. In IE10/IE11 there is a bug where the placeholder attribute // will populate textContent as well. // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/ if (textContent === stringValue) { if (textContent !== '' && textContent !== null) { node.value = textContent; } } } export function restoreControlledTextareaState( element: Element, props: Object, ) { // DOM component is still mounted; update updateTextarea(element, props.value, props.defaultValue); }
30.743421
91
0.664801
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 */ /** * This is a renderer of React that doesn't have a render target output. * It is useful to demonstrate the internals of the reconciler in isolation * and for testing semantics of reconciliation separate from the host * environment. */ import ReactFiberReconciler from 'react-reconciler'; import createReactNoop from './createReactNoop'; export const { _Scheduler, getChildren, dangerouslyGetChildren, getPendingChildren, dangerouslyGetPendingChildren, getOrCreateRootContainer, createRoot, createLegacyRoot, getChildrenAsJSX, getPendingChildrenAsJSX, getSuspenseyThingStatus, resolveSuspenseyThing, resetSuspenseyThingCache, createPortal, render, renderLegacySyncRoot, renderToRootWithID, unmountRootWithID, findInstance, flushNextYield, startTrackingHostCounters, stopTrackingHostCounters, expire, flushExpired, batchedUpdates, deferredUpdates, discreteUpdates, idleUpdates, flushSync, flushPassiveEffects, act, dumpTree, getRoot, // TODO: Remove this after callers migrate to alternatives. unstable_runWithPriority, } = createReactNoop( ReactFiberReconciler, // reconciler true, // useMutation );
22.133333
75
0.766402
null
#!/usr/bin/env node 'use strict'; const semver = require('semver'); const {execRead, logPromise} = require('../utils'); const run = async ({cwd, packages, skipPackages}, versionsMap) => { const branch = await execRead('git branch | grep \\* | cut -d " " -f2', { cwd, }); for (let i = 0; i < packages.length; i++) { const packageName = packages[i]; try { // In case local package JSONs are outdated, // guess the next version based on the latest NPM release. const version = await execRead(`npm show ${packageName} version`); if (skipPackages.includes(packageName)) { versionsMap.set(packageName, version); } else { const {major, minor, patch} = semver(version); // Guess the next version by incrementing patch. // The script will confirm this later. // By default, new releases from mains should increment the minor version number, // and patch releases should be done from branches. if (branch === 'main') { versionsMap.set(packageName, `${major}.${minor + 1}.0`); } else { versionsMap.set(packageName, `${major}.${minor}.${patch + 1}`); } } } catch (error) { // If the package has not yet been published, // we'll require a version number to be entered later. versionsMap.set(packageName, null); } } }; module.exports = async (params, versionsMap) => { return logPromise( run(params, versionsMap), 'Guessing stable version numbers' ); };
29.7
89
0.610169
Effective-Python-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 { Fragment, Suspense, useEffect, useLayoutEffect, useReducer, useRef, } from 'react'; import Tree from './Tree'; import {OwnersListContextController} from './OwnersListContext'; import portaledContent from '../portaledContent'; import {SettingsModalContextController} from 'react-devtools-shared/src/devtools/views/Settings/SettingsModalContext'; import { localStorageGetItem, localStorageSetItem, } from 'react-devtools-shared/src/storage'; import InspectedElementErrorBoundary from './InspectedElementErrorBoundary'; import InspectedElement from './InspectedElement'; import {InspectedElementContextController} from './InspectedElementContext'; import {ModalDialog} from '../ModalDialog'; import SettingsModal from 'react-devtools-shared/src/devtools/views/Settings/SettingsModal'; import {NativeStyleContextController} from './NativeStyleEditor/context'; import styles from './Components.css'; type Orientation = 'horizontal' | 'vertical'; type ResizeActionType = | 'ACTION_SET_DID_MOUNT' | 'ACTION_SET_IS_RESIZING' | 'ACTION_SET_HORIZONTAL_PERCENTAGE' | 'ACTION_SET_VERTICAL_PERCENTAGE'; type ResizeAction = { type: ResizeActionType, payload: any, }; type ResizeState = { horizontalPercentage: number, isResizing: boolean, verticalPercentage: number, }; function Components(_: {}) { const wrapperElementRef = useRef<null | HTMLElement>(null); const resizeElementRef = useRef<null | HTMLElement>(null); const [state, dispatch] = useReducer<ResizeState, any, ResizeAction>( resizeReducer, null, initResizeState, ); const {horizontalPercentage, verticalPercentage} = state; useLayoutEffect(() => { const resizeElement = resizeElementRef.current; setResizeCSSVariable( resizeElement, 'horizontal', horizontalPercentage * 100, ); setResizeCSSVariable(resizeElement, 'vertical', verticalPercentage * 100); }, []); useEffect(() => { const timeoutID = setTimeout(() => { localStorageSetItem( LOCAL_STORAGE_KEY, JSON.stringify({ horizontalPercentage, verticalPercentage, }), ); }, 500); return () => clearTimeout(timeoutID); }, [horizontalPercentage, verticalPercentage]); const {isResizing} = state; const onResizeStart = () => dispatch({type: 'ACTION_SET_IS_RESIZING', payload: true}); let onResize; let onResizeEnd; if (isResizing) { onResizeEnd = () => dispatch({type: 'ACTION_SET_IS_RESIZING', payload: false}); // $FlowFixMe[missing-local-annot] onResize = event => { const resizeElement = resizeElementRef.current; const wrapperElement = wrapperElementRef.current; if (!isResizing || wrapperElement === null || resizeElement === null) { return; } event.preventDefault(); const orientation = getOrientation(wrapperElement); const {height, width, left, top} = wrapperElement.getBoundingClientRect(); const currentMousePosition = orientation === 'horizontal' ? event.clientX - left : event.clientY - top; const boundaryMin = MINIMUM_SIZE; const boundaryMax = orientation === 'horizontal' ? width - MINIMUM_SIZE : height - MINIMUM_SIZE; const isMousePositionInBounds = currentMousePosition > boundaryMin && currentMousePosition < boundaryMax; if (isMousePositionInBounds) { const resizedElementDimension = orientation === 'horizontal' ? width : height; const actionType = orientation === 'horizontal' ? 'ACTION_SET_HORIZONTAL_PERCENTAGE' : 'ACTION_SET_VERTICAL_PERCENTAGE'; const percentage = (currentMousePosition / resizedElementDimension) * 100; setResizeCSSVariable(resizeElement, orientation, percentage); dispatch({ type: actionType, payload: currentMousePosition / resizedElementDimension, }); } }; } return ( <SettingsModalContextController> <OwnersListContextController> <div ref={wrapperElementRef} className={styles.Components} onMouseMove={onResize} onMouseLeave={onResizeEnd} onMouseUp={onResizeEnd}> <Fragment> <div ref={resizeElementRef} className={styles.TreeWrapper}> <Tree /> </div> <div className={styles.ResizeBarWrapper}> <div onMouseDown={onResizeStart} className={styles.ResizeBar} /> </div> <div className={styles.InspectedElementWrapper}> <NativeStyleContextController> <InspectedElementErrorBoundary> <Suspense fallback={<Loading />}> <InspectedElementContextController> <InspectedElement /> </InspectedElementContextController> </Suspense> </InspectedElementErrorBoundary> </NativeStyleContextController> </div> <ModalDialog /> <SettingsModal /> </Fragment> </div> </OwnersListContextController> </SettingsModalContextController> ); } function Loading() { return <div className={styles.Loading}>Loading...</div>; } const LOCAL_STORAGE_KEY = 'React::DevTools::createResizeReducer'; const VERTICAL_MODE_MAX_WIDTH = 600; const MINIMUM_SIZE = 50; function initResizeState(): ResizeState { let horizontalPercentage = 0.65; let verticalPercentage = 0.5; try { let data = localStorageGetItem(LOCAL_STORAGE_KEY); if (data != null) { data = JSON.parse(data); horizontalPercentage = data.horizontalPercentage; verticalPercentage = data.verticalPercentage; } } catch (error) {} return { horizontalPercentage, isResizing: false, verticalPercentage, }; } function resizeReducer(state: ResizeState, action: ResizeAction): ResizeState { switch (action.type) { case 'ACTION_SET_IS_RESIZING': return { ...state, isResizing: action.payload, }; case 'ACTION_SET_HORIZONTAL_PERCENTAGE': return { ...state, horizontalPercentage: action.payload, }; case 'ACTION_SET_VERTICAL_PERCENTAGE': return { ...state, verticalPercentage: action.payload, }; default: return state; } } function getOrientation( wrapperElement: null | HTMLElement, ): null | Orientation { if (wrapperElement != null) { const {width} = wrapperElement.getBoundingClientRect(); return width > VERTICAL_MODE_MAX_WIDTH ? 'horizontal' : 'vertical'; } return null; } function setResizeCSSVariable( resizeElement: null | HTMLElement, orientation: null | Orientation, percentage: number, ): void { if (resizeElement !== null && orientation !== null) { resizeElement.style.setProperty( `--${orientation}-resize-percentage`, `${percentage}%`, ); } } export default (portaledContent(Components): React$AbstractComponent<{}>);
26.961977
118
0.651979
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'; global.IS_REACT_ACT_ENVIRONMENT = true; // Our current version of JSDOM doesn't implement the event dispatching // so we polyfill it. const NativeFormData = global.FormData; const FormDataPolyfill = function FormData(form) { const formData = new NativeFormData(form); const formDataEvent = new Event('formdata', { bubbles: true, cancelable: false, }); formDataEvent.formData = formData; form.dispatchEvent(formDataEvent); return formData; }; NativeFormData.prototype.constructor = FormDataPolyfill; global.FormData = FormDataPolyfill; describe('ReactDOMForm', () => { let act; let container; let React; let ReactDOM; let ReactDOMClient; let Scheduler; let assertLog; let waitForThrow; let useState; let Suspense; let startTransition; let textCache; let useFormStatus; let useFormState; beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); Scheduler = require('scheduler'); act = require('internal-test-utils').act; assertLog = require('internal-test-utils').assertLog; waitForThrow = require('internal-test-utils').waitForThrow; useState = React.useState; Suspense = React.Suspense; startTransition = React.startTransition; useFormStatus = ReactDOM.useFormStatus; useFormState = ReactDOM.useFormState; container = document.createElement('div'); document.body.appendChild(container); 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 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(text)); } } 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 getText(text) { const record = textCache.get(text); if (record === undefined) { 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); return thenable; } else { switch (record.status) { case 'pending': return record.value; case 'rejected': return Promise.reject(record.value); case 'resolved': return Promise.resolve(record.value); } } } function Text({text}) { Scheduler.log(text); return text; } function AsyncText({text}) { readText(text); Scheduler.log(text); return text; } afterEach(() => { document.body.removeChild(container); }); async function submit(submitter) { await act(() => { const form = submitter.form || submitter; if (!submitter.form) { submitter = undefined; } const submitEvent = new Event('submit', { bubbles: true, cancelable: true, }); submitEvent.submitter = submitter; const returnValue = form.dispatchEvent(submitEvent); if (!returnValue) { return; } const action = (submitter && submitter.getAttribute('formaction')) || form.action; if (!/\s*javascript:/i.test(action)) { throw new Error('Navigate to: ' + action); } }); } // @gate enableFormActions it('should allow passing a function to form action', async () => { const ref = React.createRef(); let foo; function action(formData) { foo = formData.get('foo'); } const root = ReactDOMClient.createRoot(container); await act(async () => { root.render( <form action={action} ref={ref}> <input type="text" name="foo" defaultValue="bar" /> </form>, ); }); await submit(ref.current); expect(foo).toBe('bar'); // Try updating the action function action2(formData) { foo = formData.get('foo') + '2'; } await act(async () => { root.render( <form action={action2} ref={ref}> <input type="text" name="foo" defaultValue="bar" /> </form>, ); }); await submit(ref.current); expect(foo).toBe('bar2'); }); // @gate enableFormActions it('should allow passing a function to an input/button formAction', async () => { const inputRef = React.createRef(); const buttonRef = React.createRef(); let rootActionCalled = false; let savedTitle = null; let deletedTitle = null; function action(formData) { rootActionCalled = true; } function saveItem(formData) { savedTitle = formData.get('title'); } function deleteItem(formData) { deletedTitle = formData.get('title'); } const root = ReactDOMClient.createRoot(container); await act(async () => { root.render( <form action={action}> <input type="text" name="title" defaultValue="Hello" /> <input type="submit" formAction={saveItem} value="Save" ref={inputRef} /> <button formAction={deleteItem} ref={buttonRef}> Delete </button> </form>, ); }); expect(savedTitle).toBe(null); expect(deletedTitle).toBe(null); await submit(inputRef.current); expect(savedTitle).toBe('Hello'); expect(deletedTitle).toBe(null); savedTitle = null; await submit(buttonRef.current); expect(savedTitle).toBe(null); expect(deletedTitle).toBe('Hello'); deletedTitle = null; // Try updating the actions function saveItem2(formData) { savedTitle = formData.get('title') + '2'; } function deleteItem2(formData) { deletedTitle = formData.get('title') + '2'; } await act(async () => { root.render( <form action={action}> <input type="text" name="title" defaultValue="Hello" /> <input type="submit" formAction={saveItem2} value="Save" ref={inputRef} /> <button formAction={deleteItem2} ref={buttonRef}> Delete </button> </form>, ); }); expect(savedTitle).toBe(null); expect(deletedTitle).toBe(null); await submit(inputRef.current); expect(savedTitle).toBe('Hello2'); expect(deletedTitle).toBe(null); savedTitle = null; await submit(buttonRef.current); expect(savedTitle).toBe(null); expect(deletedTitle).toBe('Hello2'); expect(rootActionCalled).toBe(false); }); // @gate enableFormActions || !__DEV__ it('should allow preventing default to block the action', async () => { const ref = React.createRef(); let actionCalled = false; function action(formData) { actionCalled = true; } const root = ReactDOMClient.createRoot(container); await act(async () => { root.render( <form action={action} ref={ref} onSubmit={e => e.preventDefault()}> <input type="text" name="foo" defaultValue="bar" /> </form>, ); }); await submit(ref.current); expect(actionCalled).toBe(false); }); // @gate enableFormActions it('should only submit the inner of nested forms', async () => { const ref = React.createRef(); let data; function outerAction(formData) { data = formData.get('data') + 'outer'; } function innerAction(formData) { data = formData.get('data') + 'inner'; } const root = ReactDOMClient.createRoot(container); await expect(async () => { await act(async () => { // This isn't valid HTML but just in case. root.render( <form action={outerAction}> <input type="text" name="data" defaultValue="outer" /> <form action={innerAction} ref={ref}> <input type="text" name="data" defaultValue="inner" /> </form> </form>, ); }); }).toErrorDev([ 'Warning: validateDOMNesting(...): <form> cannot appear as a descendant of <form>.' + '\n in form (at **)' + '\n in form (at **)', ]); await submit(ref.current); expect(data).toBe('innerinner'); }); // @gate enableFormActions it('should only submit once if one root is nested inside the other', async () => { const ref = React.createRef(); let outerCalled = 0; let innerCalled = 0; let bubbledSubmit = false; function outerAction(formData) { outerCalled++; } function innerAction(formData) { innerCalled++; } const innerContainerRef = React.createRef(); const outerRoot = ReactDOMClient.createRoot(container); await act(async () => { outerRoot.render( // Nesting forms isn't valid HTML but just in case. <div onSubmit={() => (bubbledSubmit = true)}> <form action={outerAction}> <div ref={innerContainerRef} /> </form> </div>, ); }); const innerRoot = ReactDOMClient.createRoot(innerContainerRef.current); await act(async () => { innerRoot.render( <form action={innerAction} ref={ref}> <input type="text" name="data" defaultValue="inner" /> </form>, ); }); await submit(ref.current); expect(bubbledSubmit).toBe(true); expect(outerCalled).toBe(0); expect(innerCalled).toBe(1); }); // @gate enableFormActions it('should only submit once if a portal is nested inside its own root', async () => { const ref = React.createRef(); let outerCalled = 0; let innerCalled = 0; let bubbledSubmit = false; function outerAction(formData) { outerCalled++; } function innerAction(formData) { innerCalled++; } const innerContainer = document.createElement('div'); const innerContainerRef = React.createRef(); const outerRoot = ReactDOMClient.createRoot(container); await act(async () => { outerRoot.render( // Nesting forms isn't valid HTML but just in case. <div onSubmit={() => (bubbledSubmit = true)}> <form action={outerAction}> <div ref={innerContainerRef} /> {ReactDOM.createPortal( <form action={innerAction} ref={ref}> <input type="text" name="data" defaultValue="inner" /> </form>, innerContainer, )} </form> </div>, ); }); innerContainerRef.current.appendChild(innerContainer); await submit(ref.current); expect(bubbledSubmit).toBe(true); expect(outerCalled).toBe(0); expect(innerCalled).toBe(1); }); // @gate enableFormActions it('can read the clicked button in the formdata event', async () => { const inputRef = React.createRef(); const buttonRef = React.createRef(); let button; let title; function action(formData) { button = formData.get('button'); title = formData.get('title'); } const root = ReactDOMClient.createRoot(container); await act(async () => { root.render( <form action={action}> <input type="text" name="title" defaultValue="hello" /> <input type="submit" name="button" value="save" /> <input type="submit" name="button" value="delete" ref={inputRef} /> <button name="button" value="edit" ref={buttonRef}> Edit </button> </form>, ); }); container.addEventListener('formdata', e => { // Process in the formdata event somehow if (e.formData.get('button') === 'delete') { e.formData.delete('title'); } }); await submit(inputRef.current); expect(button).toBe('delete'); expect(title).toBe(null); await submit(buttonRef.current); expect(button).toBe('edit'); expect(title).toBe('hello'); // Ensure that the type field got correctly restored expect(inputRef.current.getAttribute('type')).toBe('submit'); expect(buttonRef.current.getAttribute('type')).toBe(null); }); // @gate enableFormActions it('excludes the submitter name when the submitter is a function action', async () => { const inputRef = React.createRef(); const buttonRef = React.createRef(); let button; function action(formData) { // A function action cannot control the name since it might be controlled by the server // so we need to make sure it doesn't get into the FormData. button = formData.get('button'); } const root = ReactDOMClient.createRoot(container); await expect(async () => { await act(async () => { root.render( <form> <input type="submit" name="button" value="delete" ref={inputRef} formAction={action} /> <button name="button" value="edit" ref={buttonRef} formAction={action}> Edit </button> </form>, ); }); }).toErrorDev([ 'Cannot specify a "name" prop for a button that specifies a function as a formAction.', ]); await submit(inputRef.current); expect(button).toBe(null); await submit(buttonRef.current); expect(button).toBe(null); // Ensure that the type field got correctly restored expect(inputRef.current.getAttribute('type')).toBe('submit'); expect(buttonRef.current.getAttribute('type')).toBe(null); }); // @gate enableFormActions || !__DEV__ it('allows a non-function formaction to override a function one', async () => { const ref = React.createRef(); let actionCalled = false; function action(formData) { actionCalled = true; } const root = ReactDOMClient.createRoot(container); await act(async () => { root.render( <form action={action}> <input type="submit" formAction="http://example.com/submit" ref={ref} /> </form>, ); }); let nav; try { await submit(ref.current); } catch (x) { nav = x.message; } expect(nav).toBe('Navigate to: http://example.com/submit'); expect(actionCalled).toBe(false); }); // @gate enableFormActions || !__DEV__ it('allows a non-react html formaction to be invoked', async () => { let actionCalled = false; function action(formData) { actionCalled = true; } const root = ReactDOMClient.createRoot(container); await act(async () => { root.render( <form action={action} dangerouslySetInnerHTML={{ __html: ` <input type="submit" formAction="http://example.com/submit" /> `, }} />, ); }); const node = container.getElementsByTagName('input')[0]; let nav; try { await submit(node); } catch (x) { nav = x.message; } expect(nav).toBe('Navigate to: http://example.com/submit'); expect(actionCalled).toBe(false); }); // @gate enableFormActions // @gate enableAsyncActions it('form actions are transitions', async () => { const formRef = React.createRef(); function Status() { const {pending} = useFormStatus(); return pending ? <Text text="Pending..." /> : null; } function App() { const [state, setState] = useState('Initial'); return ( <form action={() => setState('Updated')} ref={formRef}> <Status /> <Suspense fallback={<Text text="Loading..." />}> <AsyncText text={state} /> </Suspense> </form> ); } const root = ReactDOMClient.createRoot(container); await resolveText('Initial'); await act(() => root.render(<App />)); assertLog(['Initial']); expect(container.textContent).toBe('Initial'); // This should suspend because form actions are implicitly wrapped // in startTransition. await submit(formRef.current); assertLog(['Pending...', 'Suspend! [Updated]', 'Loading...']); expect(container.textContent).toBe('Pending...Initial'); await act(() => resolveText('Updated')); assertLog(['Updated']); expect(container.textContent).toBe('Updated'); }); // @gate enableFormActions // @gate enableAsyncActions it('multiple form actions', async () => { const formRef = React.createRef(); function Status() { const {pending} = useFormStatus(); return pending ? <Text text="Pending..." /> : null; } function App() { const [state, setState] = useState(0); return ( <form action={() => setState(n => n + 1)} ref={formRef}> <Status /> <Suspense fallback={<Text text="Loading..." />}> <AsyncText text={'Count: ' + state} /> </Suspense> </form> ); } const root = ReactDOMClient.createRoot(container); await resolveText('Count: 0'); await act(() => root.render(<App />)); assertLog(['Count: 0']); expect(container.textContent).toBe('Count: 0'); // Update await submit(formRef.current); assertLog(['Pending...', 'Suspend! [Count: 1]', 'Loading...']); expect(container.textContent).toBe('Pending...Count: 0'); await act(() => resolveText('Count: 1')); assertLog(['Count: 1']); expect(container.textContent).toBe('Count: 1'); // Update again await submit(formRef.current); assertLog(['Pending...', 'Suspend! [Count: 2]', 'Loading...']); expect(container.textContent).toBe('Pending...Count: 1'); await act(() => resolveText('Count: 2')); assertLog(['Count: 2']); expect(container.textContent).toBe('Count: 2'); }); // @gate enableFormActions it('form actions can be asynchronous', async () => { const formRef = React.createRef(); function Status() { const {pending} = useFormStatus(); return pending ? <Text text="Pending..." /> : null; } function App() { const [state, setState] = useState('Initial'); return ( <form action={async () => { Scheduler.log('Async action started'); await getText('Wait'); startTransition(() => setState('Updated')); }} ref={formRef}> <Status /> <Suspense fallback={<Text text="Loading..." />}> <AsyncText text={state} /> </Suspense> </form> ); } const root = ReactDOMClient.createRoot(container); await resolveText('Initial'); await act(() => root.render(<App />)); assertLog(['Initial']); expect(container.textContent).toBe('Initial'); await submit(formRef.current); assertLog(['Async action started', 'Pending...']); await act(() => resolveText('Wait')); assertLog(['Suspend! [Updated]', 'Loading...']); expect(container.textContent).toBe('Pending...Initial'); await act(() => resolveText('Updated')); assertLog(['Updated']); expect(container.textContent).toBe('Updated'); }); it('sync errors in form actions can be captured by an error boundary', async () => { if (gate(flags => !(flags.enableFormActions && flags.enableAsyncActions))) { // TODO: Uncaught JSDOM errors fail the test after the scope has finished // so don't work with the `gate` mechanism. return; } class ErrorBoundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { if (this.state.error !== null) { return <Text text={this.state.error.message} />; } return this.props.children; } } const formRef = React.createRef(); function App() { return ( <ErrorBoundary> <form action={() => { throw new Error('Oh no!'); }} ref={formRef}> <Text text="Everything is fine" /> </form> </ErrorBoundary> ); } const root = ReactDOMClient.createRoot(container); await act(() => root.render(<App />)); assertLog(['Everything is fine']); expect(container.textContent).toBe('Everything is fine'); await submit(formRef.current); assertLog(['Oh no!', 'Oh no!']); expect(container.textContent).toBe('Oh no!'); }); it('async errors in form actions can be captured by an error boundary', async () => { if (gate(flags => !(flags.enableFormActions && flags.enableAsyncActions))) { // TODO: Uncaught JSDOM errors fail the test after the scope has finished // so don't work with the `gate` mechanism. return; } class ErrorBoundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { if (this.state.error !== null) { return <Text text={this.state.error.message} />; } return this.props.children; } } const formRef = React.createRef(); function App() { return ( <ErrorBoundary> <form action={async () => { Scheduler.log('Async action started'); await getText('Wait'); throw new Error('Oh no!'); }} ref={formRef}> <Text text="Everything is fine" /> </form> </ErrorBoundary> ); } const root = ReactDOMClient.createRoot(container); await act(() => root.render(<App />)); assertLog(['Everything is fine']); expect(container.textContent).toBe('Everything is fine'); await submit(formRef.current); assertLog(['Async action started']); expect(container.textContent).toBe('Everything is fine'); await act(() => resolveText('Wait')); assertLog(['Oh no!', 'Oh no!']); expect(container.textContent).toBe('Oh no!'); }); // @gate enableFormActions // @gate enableAsyncActions it('useFormStatus reads the status of a pending form action', async () => { const formRef = React.createRef(); function Status() { const {pending, data, action, method} = useFormStatus(); if (!pending) { return <Text text="No pending action" />; } else { const foo = data.get('foo'); return ( <Text text={`Pending action ${action.name}: foo is ${foo}, method is ${method}`} /> ); } } async function myAction() { Scheduler.log('Async action started'); await getText('Wait'); Scheduler.log('Async action finished'); } function App() { return ( <form action={myAction} ref={formRef}> <input type="text" name="foo" defaultValue="bar" /> <Status /> </form> ); } const root = ReactDOMClient.createRoot(container); await act(() => root.render(<App />)); assertLog(['No pending action']); expect(container.textContent).toBe('No pending action'); await submit(formRef.current); assertLog([ 'Async action started', 'Pending action myAction: foo is bar, method is get', ]); expect(container.textContent).toBe( 'Pending action myAction: foo is bar, method is get', ); await act(() => resolveText('Wait')); assertLog(['Async action finished', 'No pending action']); }); // @gate enableFormActions it('should error if submitting a form manually', async () => { const ref = React.createRef(); let error = null; let result = null; function emulateForceSubmit(submitter) { const form = submitter.form || submitter; const action = (submitter && submitter.getAttribute('formaction')) || form.action; try { if (!/\s*javascript:/i.test(action)) { throw new Error('Navigate to: ' + action); } else { // eslint-disable-next-line no-new-func result = Function(action.slice(11))(); } } catch (x) { error = x; } } const root = ReactDOMClient.createRoot(container); await act(async () => { root.render( <form action={() => {}} ref={ref} onSubmit={e => { e.preventDefault(); emulateForceSubmit(e.target); }}> <input type="text" name="foo" defaultValue="bar" /> </form>, ); }); // This submits the form, which gets blocked and then resubmitted. It's a somewhat // common idiom but we don't support this pattern unless it uses requestSubmit(). await submit(ref.current); expect(result).toBe(null); expect(error.message).toContain( 'A React form was unexpectedly submitted. If you called form.submit()', ); }); // @gate enableFormActions // @gate enableAsyncActions test('useFormState updates state asynchronously and queues multiple actions', async () => { let actionCounter = 0; async function action(state, type) { actionCounter++; Scheduler.log(`Async action started [${actionCounter}]`); await getText(`Wait [${actionCounter}]`); switch (type) { case 'increment': return state + 1; case 'decrement': return state - 1; default: return state; } } let dispatch; function App() { const [state, _dispatch] = useFormState(action, 0); dispatch = _dispatch; return <Text text={state} />; } const root = ReactDOMClient.createRoot(container); await act(() => root.render(<App />)); assertLog([0]); expect(container.textContent).toBe('0'); await act(() => dispatch('increment')); assertLog(['Async action started [1]']); expect(container.textContent).toBe('0'); // Dispatch a few more actions. None of these will start until the previous // one finishes. await act(() => dispatch('increment')); await act(() => dispatch('decrement')); await act(() => dispatch('increment')); assertLog([]); // Each action starts as soon as the previous one finishes. // NOTE: React does not render in between these actions because they all // update the same queue, which means they get entangled together. This is // intentional behavior. await act(() => resolveText('Wait [1]')); assertLog(['Async action started [2]']); await act(() => resolveText('Wait [2]')); assertLog(['Async action started [3]']); await act(() => resolveText('Wait [3]')); assertLog(['Async action started [4]']); await act(() => resolveText('Wait [4]')); // Finally the last action finishes and we can render the result. assertLog([2]); expect(container.textContent).toBe('2'); }); // @gate enableFormActions // @gate enableAsyncActions test('useFormState supports inline actions', async () => { let increment; function App({stepSize}) { const [state, dispatch] = useFormState(async prevState => { return prevState + stepSize; }, 0); increment = dispatch; return <Text text={state} />; } // Initial render const root = ReactDOMClient.createRoot(container); await act(() => root.render(<App stepSize={1} />)); assertLog([0]); // Perform an action. This will increase the state by 1, as defined by the // stepSize prop. await act(() => increment()); assertLog([1]); // Now increase the stepSize prop to 10. Subsequent steps will increase // by this amount. await act(() => root.render(<App stepSize={10} />)); assertLog([1]); // Increment again. The state should increase by 10. await act(() => increment()); assertLog([11]); }); // @gate enableFormActions // @gate enableAsyncActions test('useFormState: dispatch throws if called during render', async () => { function App() { const [state, dispatch] = useFormState(async () => {}, 0); dispatch(); return <Text text={state} />; } const root = ReactDOMClient.createRoot(container); await act(async () => { root.render(<App />); await waitForThrow('Cannot update form state while rendering.'); }); }); // @gate enableFormActions // @gate enableAsyncActions test('queues multiple actions and runs them in order', async () => { let action; function App() { const [state, dispatch] = useFormState( async (s, a) => await getText(a), 'A', ); action = dispatch; return <Text text={state} />; } const root = ReactDOMClient.createRoot(container); await act(() => root.render(<App />)); assertLog(['A']); await act(() => action('B')); await act(() => action('C')); await act(() => action('D')); await act(() => resolveText('B')); await act(() => resolveText('C')); await act(() => resolveText('D')); assertLog(['D']); expect(container.textContent).toBe('D'); }); // @gate enableFormActions // @gate enableAsyncActions test('useFormState: works if action is sync', async () => { let increment; function App({stepSize}) { const [state, dispatch] = useFormState(prevState => { return prevState + stepSize; }, 0); increment = dispatch; return <Text text={state} />; } // Initial render const root = ReactDOMClient.createRoot(container); await act(() => root.render(<App stepSize={1} />)); assertLog([0]); // Perform an action. This will increase the state by 1, as defined by the // stepSize prop. await act(() => increment()); assertLog([1]); // Now increase the stepSize prop to 10. Subsequent steps will increase // by this amount. await act(() => root.render(<App stepSize={10} />)); assertLog([1]); // Increment again. The state should increase by 10. await act(() => increment()); assertLog([11]); }); // @gate enableFormActions // @gate enableAsyncActions test('useFormState: can mix sync and async actions', async () => { let action; function App() { const [state, dispatch] = useFormState((s, a) => a, 'A'); action = dispatch; return <Text text={state} />; } const root = ReactDOMClient.createRoot(container); await act(() => root.render(<App />)); assertLog(['A']); await act(() => action(getText('B'))); await act(() => action('C')); await act(() => action(getText('D'))); await act(() => action('E')); await act(() => resolveText('B')); await act(() => resolveText('D')); assertLog(['E']); expect(container.textContent).toBe('E'); }); // @gate enableFormActions // @gate enableAsyncActions test('useFormState: error handling (sync action)', async () => { let resetErrorBoundary; class ErrorBoundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { resetErrorBoundary = () => this.setState({error: null}); if (this.state.error !== null) { return <Text text={'Caught an error: ' + this.state.error.message} />; } return this.props.children; } } let action; function App() { const [state, dispatch] = useFormState((s, a) => { if (a.endsWith('!')) { throw new Error(a); } return a; }, 'A'); action = dispatch; return <Text text={state} />; } const root = ReactDOMClient.createRoot(container); await act(() => root.render( <ErrorBoundary> <App /> </ErrorBoundary>, ), ); assertLog(['A']); await act(() => action('Oops!')); assertLog(['Caught an error: Oops!', 'Caught an error: Oops!']); expect(container.textContent).toBe('Caught an error: Oops!'); // Reset the error boundary await act(() => resetErrorBoundary()); assertLog(['A']); // Trigger an error again, but this time, perform another action that // overrides the first one and fixes the error await act(() => { action('Oops!'); action('B'); }); assertLog(['B']); expect(container.textContent).toBe('B'); }); // @gate enableFormActions // @gate enableAsyncActions test('useFormState: error handling (async action)', async () => { let resetErrorBoundary; class ErrorBoundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { resetErrorBoundary = () => this.setState({error: null}); if (this.state.error !== null) { return <Text text={'Caught an error: ' + this.state.error.message} />; } return this.props.children; } } let action; function App() { const [state, dispatch] = useFormState(async (s, a) => { const text = await getText(a); if (text.endsWith('!')) { throw new Error(text); } return text; }, 'A'); action = dispatch; return <Text text={state} />; } const root = ReactDOMClient.createRoot(container); await act(() => root.render( <ErrorBoundary> <App /> </ErrorBoundary>, ), ); assertLog(['A']); await act(() => action('Oops!')); assertLog([]); await act(() => resolveText('Oops!')); assertLog(['Caught an error: Oops!', 'Caught an error: Oops!']); expect(container.textContent).toBe('Caught an error: Oops!'); // Reset the error boundary await act(() => resetErrorBoundary()); assertLog(['A']); // Trigger an error again, but this time, perform another action that // overrides the first one and fixes the error await act(() => { action('Oops!'); action('B'); }); assertLog([]); await act(() => resolveText('B')); assertLog(['B']); expect(container.textContent).toBe('B'); }); });
26.78483
93
0.576037
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=useTheme.js.map?foo=bar&param=some_value
23.851852
70
0.701493
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 */ // Ids are base 32 strings whose binary representation corresponds to the // position of a node in a tree. // Every time the tree forks into multiple children, we add additional bits to // the left of the sequence that represent the position of the child within the // current level of children. // // 00101 00010001011010101 // ╰─┬─╯ ╰───────┬───────╯ // Fork 5 of 20 Parent id // // The leading 0s are important. In the above example, you only need 3 bits to // represent slot 5. However, you need 5 bits to represent all the forks at // the current level, so we must account for the empty bits at the end. // // For this same reason, slots are 1-indexed instead of 0-indexed. Otherwise, // the zeroth id at a level would be indistinguishable from its parent. // // If a node has only one child, and does not materialize an id (i.e. does not // contain a useId hook), then we don't need to allocate any space in the // sequence. It's treated as a transparent indirection. For example, these two // trees produce the same ids: // // <> <> // <Indirection> <A /> // <A /> <B /> // </Indirection> </> // <B /> // </> // // However, we cannot skip any node that materializes an id. Otherwise, a parent // id that does not fork would be indistinguishable from its child id. For // example, this tree does not fork, but the parent and child must have // different ids. // // <Parent> // <Child /> // </Parent> // // To handle this scenario, every time we materialize an id, we allocate a // new level with a single slot. You can think of this as a fork with only one // prong, or an array of children with length 1. // // It's possible for the size of the sequence to exceed 32 bits, the max // size for bitwise operations. When this happens, we make more room by // converting the right part of the id to a string and storing it in an overflow // variable. We use a base 32 string representation, because 32 is the largest // power of 2 that is supported by toString(). We want the base to be large so // that the resulting ids are compact, and we want the base to be a power of 2 // because every log2(base) bits corresponds to a single character, i.e. every // log2(32) = 5 bits. That means we can lop bits off the end 5 at a time without // affecting the final result. export type TreeContext = { +id: number, +overflow: string, }; export const emptyTreeContext = { id: 1, overflow: '', }; export function getTreeId(context: TreeContext): string { const overflow = context.overflow; const idWithLeadingBit = context.id; const id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit); return id.toString(32) + overflow; } export function pushTreeContext( baseContext: TreeContext, totalChildren: number, index: number, ): TreeContext { const baseIdWithLeadingBit = baseContext.id; const baseOverflow = baseContext.overflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part // of the id; we use it to account for leading 0s. const baseLength = getBitLength(baseIdWithLeadingBit) - 1; const baseId = baseIdWithLeadingBit & ~(1 << baseLength); const slot = index + 1; const length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into // consideration the leading 1 we use to mark the end of the sequence. if (length > 30) { // We overflowed the bitwise-safe range. Fall back to slower algorithm. // This branch assumes the length of the base id is greater than 5; it won't // work for smaller ids, because you need 5 bits per character. // // We encode the id in multiple steps: first the base id, then the // remaining digits. // // Each 5 bit sequence corresponds to a single base 32 character. So for // example, if the current id is 23 bits long, we can convert 20 of those // bits into a string of 4 characters, with 3 bits left over. // // First calculate how many bits in the base id represent a complete // sequence of characters. const numberOfOverflowBits = baseLength - (baseLength % 5); // Then create a bitmask that selects only those bits. const newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string. const newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id. const restOfBaseId = baseId >> numberOfOverflowBits; const restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because // we made more room, this time it won't overflow. const restOfLength = getBitLength(totalChildren) + restOfBaseLength; const restOfNewBits = slot << restOfBaseLength; const id = restOfNewBits | restOfBaseId; const overflow = newOverflow + baseOverflow; return { id: (1 << restOfLength) | id, overflow, }; } else { // Normal path const newBits = slot << baseLength; const id = newBits | baseId; const overflow = baseOverflow; return { id: (1 << length) | id, overflow, }; } } function getBitLength(number: number): number { return 32 - clz32(number); } function getLeadingBit(id: number) { return 1 << (getBitLength(id) - 1); } // TODO: Math.clz32 is supported in Node 12+. Maybe we can drop the fallback. const clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros. // Based on: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32 const log = Math.log; const LN2 = Math.LN2; function clz32Fallback(x: number): number { const asUint = x >>> 0; if (asUint === 0) { return 32; } return (31 - ((log(asUint) / LN2) | 0)) | 0; }
35.100592
94
0.683115
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 ReactTestUtils; let TestComponent; describe('refs-destruction', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactTestUtils = require('react-dom/test-utils'); class ClassComponent extends React.Component { render() { return null; } } TestComponent = class extends React.Component { theInnerDivRef = React.createRef(); theInnerClassComponentRef = React.createRef(); render() { if (this.props.destroy) { return <div />; } else if (this.props.removeRef) { return ( <div> <div /> <ClassComponent /> </div> ); } else { return ( <div> <div ref={this.theInnerDivRef} /> <ClassComponent ref={this.theInnerClassComponentRef} /> </div> ); } } }; }); it('should remove refs when destroying the parent', () => { const container = document.createElement('div'); const testInstance = ReactDOM.render(<TestComponent />, container); expect( ReactTestUtils.isDOMComponent(testInstance.theInnerDivRef.current), ).toBe(true); expect(testInstance.theInnerClassComponentRef.current).toBeTruthy(); ReactDOM.unmountComponentAtNode(container); expect(testInstance.theInnerDivRef.current).toBe(null); expect(testInstance.theInnerClassComponentRef.current).toBe(null); }); it('should remove refs when destroying the child', () => { const container = document.createElement('div'); const testInstance = ReactDOM.render(<TestComponent />, container); expect( ReactTestUtils.isDOMComponent(testInstance.theInnerDivRef.current), ).toBe(true); expect(testInstance.theInnerClassComponentRef.current).toBeTruthy(); ReactDOM.render(<TestComponent destroy={true} />, container); expect(testInstance.theInnerDivRef.current).toBe(null); expect(testInstance.theInnerClassComponentRef.current).toBe(null); }); it('should remove refs when removing the child ref attribute', () => { const container = document.createElement('div'); const testInstance = ReactDOM.render(<TestComponent />, container); expect( ReactTestUtils.isDOMComponent(testInstance.theInnerDivRef.current), ).toBe(true); expect(testInstance.theInnerClassComponentRef.current).toBeTruthy(); ReactDOM.render(<TestComponent removeRef={true} />, container); expect(testInstance.theInnerDivRef.current).toBe(null); expect(testInstance.theInnerClassComponentRef.current).toBe(null); }); it('should not error when destroying child with ref asynchronously', () => { class Modal extends React.Component { componentDidMount() { this.div = document.createElement('div'); document.body.appendChild(this.div); this.componentDidUpdate(); } componentDidUpdate() { ReactDOM.render(<div>{this.props.children}</div>, this.div); } componentWillUnmount() { const self = this; // some async animation setTimeout(function () { expect(function () { ReactDOM.unmountComponentAtNode(self.div); }).not.toThrow(); document.body.removeChild(self.div); }, 0); } render() { return null; } } class AppModal extends React.Component { render() { return ( <Modal> <a ref={React.createRef()} /> </Modal> ); } } class App extends React.Component { render() { return this.props.hidden ? null : <AppModal onClose={this.close} />; } } const container = document.createElement('div'); ReactDOM.render(<App />, container); ReactDOM.render(<App hidden={true} />, container); jest.runAllTimers(); }); });
26.736842
78
0.624437
owtf
import * as React from 'react'; import Container from './Container.js'; import {Counter} from './Counter.js'; import {Counter as Counter2} from './Counter2.js'; import AsyncModule from './cjs/Counter3.js'; const Counter3 = await(AsyncModule); import ShowMore from './ShowMore.js'; import Button from './Button.js'; import Form from './Form.js'; import {Dynamic} from './Dynamic.js'; import {Client} from './Client.js'; import {Note} from './cjs/Note.js'; import {like, greet, increment} from './actions.js'; import {getServerState} from './ServerState.js'; export default async function App() { const res = await fetch('http://localhost:3001/todos'); const todos = await res.json(); return ( <html lang="en"> <head> <meta charSet="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Flight</title> </head> <body> <Container> <h1>{getServerState()}</h1> <Counter incrementAction={increment} /> <Counter2 incrementAction={increment} /> <Counter3 incrementAction={increment} /> <ul> {todos.map(todo => ( <li key={todo.id}>{todo.text}</li> ))} </ul> <ShowMore> <p>Lorem ipsum</p> </ShowMore> <Form action={greet} /> <div> <Button action={like}>Like</Button> </div> <div> loaded statically: <Dynamic /> </div> <Client /> <Note /> </Container> </body> </html> ); }
25.783333
78
0.553549
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 * as React from 'react'; import styles from './Profiler.css'; export default function ProcessingData(): React.Node { return ( <div className={styles.Column}> <div className={styles.Header}>Processing data...</div> <div className={styles.Row}>This should only take a minute.</div> </div> ); }
23.090909
71
0.672968
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 { Fragment, Suspense, useCallback, useContext, useEffect, useMemo, useRef, useState, } from 'react'; import AutoSizer from 'react-virtualized-auto-sizer'; import {FixedSizeList} from 'react-window'; import {TreeDispatcherContext, TreeStateContext} from './TreeContext'; import Icon from '../Icon'; import {SettingsContext} from '../Settings/SettingsContext'; import {BridgeContext, StoreContext, OptionsContext} from '../context'; import Element from './Element'; import InspectHostNodesToggle from './InspectHostNodesToggle'; import OwnersStack from './OwnersStack'; import ComponentSearchInput from './ComponentSearchInput'; import SettingsModalContextToggle from 'react-devtools-shared/src/devtools/views/Settings/SettingsModalContextToggle'; import SelectedTreeHighlight from './SelectedTreeHighlight'; import TreeFocusedContext from './TreeFocusedContext'; import {useHighlightNativeElement, useSubscription} from '../hooks'; import {clearErrorsAndWarnings as clearErrorsAndWarningsAPI} from 'react-devtools-shared/src/backendAPI'; import styles from './Tree.css'; import ButtonIcon from '../ButtonIcon'; import Button from '../Button'; import {logEvent} from 'react-devtools-shared/src/Logger'; // Never indent more than this number of pixels (even if we have the room). const DEFAULT_INDENTATION_SIZE = 12; export type ItemData = { numElements: number, isNavigatingWithKeyboard: boolean, lastScrolledIDRef: {current: number | null, ...}, onElementMouseEnter: (id: number) => void, treeFocused: boolean, }; type Props = {}; export default function Tree(props: Props): React.Node { const dispatch = useContext(TreeDispatcherContext); const { numElements, ownerID, searchIndex, searchResults, selectedElementID, selectedElementIndex, } = useContext(TreeStateContext); const bridge = useContext(BridgeContext); const store = useContext(StoreContext); const {hideSettings} = useContext(OptionsContext); const [isNavigatingWithKeyboard, setIsNavigatingWithKeyboard] = useState(false); const {highlightNativeElement, clearHighlightNativeElement} = useHighlightNativeElement(); const treeRef = useRef<HTMLDivElement | null>(null); const focusTargetRef = useRef<HTMLDivElement | null>(null); const [treeFocused, setTreeFocused] = useState<boolean>(false); const {lineHeight, showInlineWarningsAndErrors} = useContext(SettingsContext); // Make sure a newly selected element is visible in the list. // This is helpful for things like the owners list and search. // // TRICKY: // It's important to use a callback ref for this, rather than a ref object and an effect. // As an optimization, the AutoSizer component does not render children when their size would be 0. // This means that in some cases (if the browser panel size is initially really small), // the Tree component might render without rendering an inner List. // In this case, the list ref would be null on mount (when the scroll effect runs), // meaning the scroll action would be skipped (since ref updates don't re-run effects). // Using a callback ref accounts for this case... const listCallbackRef = useCallback( (list: $FlowFixMe) => { if (list != null && selectedElementIndex !== null) { list.scrollToItem(selectedElementIndex, 'smart'); } }, [selectedElementIndex], ); // Picking an element in the inspector should put focus into the tree. // This ensures that keyboard navigation works right after picking a node. useEffect(() => { function handleStopInspectingNative(didSelectNode: boolean) { if (didSelectNode && focusTargetRef.current !== null) { focusTargetRef.current.focus(); logEvent({ event_name: 'select-element', metadata: {source: 'inspector'}, }); } } bridge.addListener('stopInspectingNative', handleStopInspectingNative); return () => bridge.removeListener('stopInspectingNative', handleStopInspectingNative); }, [bridge]); // This ref is passed down the context to elements. // It lets them avoid autoscrolling to the same item many times // when a selected virtual row goes in and out of the viewport. const lastScrolledIDRef = useRef<number | null>(null); // Navigate the tree with up/down arrow keys. useEffect(() => { if (treeRef.current === null) { return () => {}; } const handleKeyDown = (event: KeyboardEvent) => { if ((event: any).target.tagName === 'INPUT' || event.defaultPrevented) { return; } let element; switch (event.key) { case 'ArrowDown': event.preventDefault(); if (event.altKey) { dispatch({type: 'SELECT_NEXT_SIBLING_IN_TREE'}); } else { dispatch({type: 'SELECT_NEXT_ELEMENT_IN_TREE'}); } break; case 'ArrowLeft': event.preventDefault(); element = selectedElementID !== null ? store.getElementByID(selectedElementID) : null; if (element !== null) { if (event.altKey) { if (element.ownerID !== null) { dispatch({type: 'SELECT_OWNER_LIST_PREVIOUS_ELEMENT_IN_TREE'}); } } else { if (element.children.length > 0 && !element.isCollapsed) { store.toggleIsCollapsed(element.id, true); } else { dispatch({type: 'SELECT_PARENT_ELEMENT_IN_TREE'}); } } } break; case 'ArrowRight': event.preventDefault(); element = selectedElementID !== null ? store.getElementByID(selectedElementID) : null; if (element !== null) { if (event.altKey) { dispatch({type: 'SELECT_OWNER_LIST_NEXT_ELEMENT_IN_TREE'}); } else { if (element.children.length > 0 && element.isCollapsed) { store.toggleIsCollapsed(element.id, false); } else { dispatch({type: 'SELECT_CHILD_ELEMENT_IN_TREE'}); } } } break; case 'ArrowUp': event.preventDefault(); if (event.altKey) { dispatch({type: 'SELECT_PREVIOUS_SIBLING_IN_TREE'}); } else { dispatch({type: 'SELECT_PREVIOUS_ELEMENT_IN_TREE'}); } break; default: return; } setIsNavigatingWithKeyboard(true); }; // We used to listen to at the document level for this event. // That allowed us to listen to up/down arrow key events while another section // of DevTools (like the search input) was focused. // This was a minor UX positive. // // (We had to use ownerDocument rather than document for this, because the // DevTools extension renders the Components and Profiler tabs into portals.) // // This approach caused a problem though: it meant that a react-devtools-inline // instance could steal (and prevent/block) keyboard events from other JavaScript // on the page– which could even include other react-devtools-inline instances. // This is a potential major UX negative. // // Given the above trade offs, we now listen on the root of the Tree itself. const container = treeRef.current; container.addEventListener('keydown', handleKeyDown); return () => { container.removeEventListener('keydown', handleKeyDown); }; }, [dispatch, selectedElementID, store]); // Focus management. const handleBlur = useCallback(() => setTreeFocused(false), []); const handleFocus = useCallback(() => { setTreeFocused(true); if (selectedElementIndex === null && numElements > 0) { dispatch({ type: 'SELECT_ELEMENT_AT_INDEX', payload: 0, }); } }, [dispatch, numElements, selectedElementIndex]); const handleKeyPress = useCallback( (event: $FlowFixMe) => { switch (event.key) { case 'Enter': case ' ': if (selectedElementID !== null) { dispatch({type: 'SELECT_OWNER', payload: selectedElementID}); } break; default: break; } }, [dispatch, selectedElementID], ); // If we switch the selected element while using the keyboard, // start highlighting it in the DOM instead of the last hovered node. const searchRef = useRef({searchIndex, searchResults}); useEffect(() => { let didSelectNewSearchResult = false; if ( searchRef.current.searchIndex !== searchIndex || searchRef.current.searchResults !== searchResults ) { searchRef.current.searchIndex = searchIndex; searchRef.current.searchResults = searchResults; didSelectNewSearchResult = true; } if (isNavigatingWithKeyboard || didSelectNewSearchResult) { if (selectedElementID !== null) { highlightNativeElement(selectedElementID); } else { clearHighlightNativeElement(); } } }, [ bridge, isNavigatingWithKeyboard, highlightNativeElement, searchIndex, searchResults, selectedElementID, ]); // Highlight last hovered element. const handleElementMouseEnter = useCallback( (id: $FlowFixMe) => { // Ignore hover while we're navigating with keyboard. // This avoids flicker from the hovered nodes under the mouse. if (!isNavigatingWithKeyboard) { highlightNativeElement(id); } }, [isNavigatingWithKeyboard, highlightNativeElement], ); const handleMouseMove = useCallback(() => { // We started using the mouse again. // This will enable hover styles in individual rows. setIsNavigatingWithKeyboard(false); }, []); const handleMouseLeave = clearHighlightNativeElement; // Let react-window know to re-render any time the underlying tree data changes. // This includes the owner context, since it controls a filtered view of the tree. const itemData = useMemo<ItemData>( () => ({ numElements, isNavigatingWithKeyboard, onElementMouseEnter: handleElementMouseEnter, lastScrolledIDRef, treeFocused, }), [ numElements, isNavigatingWithKeyboard, handleElementMouseEnter, lastScrolledIDRef, treeFocused, ], ); const itemKey = useCallback( (index: number) => store.getElementIDAtIndex(index), [store], ); const handlePreviousErrorOrWarningClick = React.useCallback(() => { dispatch({type: 'SELECT_PREVIOUS_ELEMENT_WITH_ERROR_OR_WARNING_IN_TREE'}); }, []); const handleNextErrorOrWarningClick = React.useCallback(() => { dispatch({type: 'SELECT_NEXT_ELEMENT_WITH_ERROR_OR_WARNING_IN_TREE'}); }, []); const errorsOrWarningsSubscription = useMemo( () => ({ getCurrentValue: () => ({ errors: store.errorCount, warnings: store.warningCount, }), subscribe: (callback: Function) => { store.addListener('mutated', callback); return () => store.removeListener('mutated', callback); }, }), [store], ); const {errors, warnings} = useSubscription(errorsOrWarningsSubscription); const clearErrorsAndWarnings = () => { clearErrorsAndWarningsAPI({bridge, store}); }; const zeroElementsNotice = ( <div className={styles.ZeroElementsNotice}> <p>Loading React Element Tree...</p> <p> If this seems stuck, please follow the{' '} <a className={styles.Link} href="https://github.com/facebook/react/blob/main/packages/react-devtools/README.md#the-react-tab-shows-no-components" target="_blank"> troubleshooting instructions </a> . </p> </div> ); return ( <TreeFocusedContext.Provider value={treeFocused}> <div className={styles.Tree} ref={treeRef}> <div className={styles.SearchInput}> {store.supportsNativeInspection && ( <Fragment> <InspectHostNodesToggle /> <div className={styles.VRule} /> </Fragment> )} <Suspense fallback={<Loading />}> {ownerID !== null ? <OwnersStack /> : <ComponentSearchInput />} </Suspense> {showInlineWarningsAndErrors && ownerID === null && (errors > 0 || warnings > 0) && ( <React.Fragment> <div className={styles.VRule} /> {errors > 0 && ( <div className={styles.IconAndCount}> <Icon className={styles.ErrorIcon} type="error" /> {errors} </div> )} {warnings > 0 && ( <div className={styles.IconAndCount}> <Icon className={styles.WarningIcon} type="warning" /> {warnings} </div> )} <Button onClick={handlePreviousErrorOrWarningClick} title="Scroll to previous error or warning"> <ButtonIcon type="up" /> </Button> <Button onClick={handleNextErrorOrWarningClick} title="Scroll to next error or warning"> <ButtonIcon type="down" /> </Button> <Button onClick={clearErrorsAndWarnings} title="Clear all errors and warnings"> <ButtonIcon type="clear" /> </Button> </React.Fragment> )} {!hideSettings && ( <Fragment> <div className={styles.VRule} /> <SettingsModalContextToggle /> </Fragment> )} </div> {numElements === 0 ? ( zeroElementsNotice ) : ( <div className={styles.AutoSizerWrapper} onBlur={handleBlur} onFocus={handleFocus} onKeyPress={handleKeyPress} onMouseMove={handleMouseMove} onMouseLeave={handleMouseLeave} ref={focusTargetRef} tabIndex={0}> <AutoSizer> {({height, width}) => ( <FixedSizeList className={styles.List} height={height} innerElementType={InnerElementType} itemCount={numElements} itemData={itemData} itemKey={itemKey} itemSize={lineHeight} ref={listCallbackRef} width={width}> {Element} </FixedSizeList> )} </AutoSizer> </div> )} </div> </TreeFocusedContext.Provider> ); } // Indentation size can be adjusted but child width is fixed. // We need to adjust indentations so the widest child can fit without overflowing. // Sometimes the widest child is also the deepest in the tree: // ┏----------------------┓ // ┆ <Foo> ┆ // ┆ ••••<Foobar> ┆ // ┆ ••••••••<Baz> ┆ // ┗----------------------┛ // // But this is not always the case. // Even with the above example, a change in indentation may change the overall widest child: // ┏----------------------┓ // ┆ <Foo> ┆ // ┆ ••<Foobar> ┆ // ┆ ••••<Baz> ┆ // ┗----------------------┛ // // In extreme cases this difference can be important: // ┏----------------------┓ // ┆ <ReallyLongName> ┆ // ┆ ••<Foo> ┆ // ┆ ••••<Bar> ┆ // ┆ ••••••<Baz> ┆ // ┆ ••••••••<Qux> ┆ // ┗----------------------┛ // // In the above example, the current indentation is fine, // but if we naively assumed that the widest element is also the deepest element, // we would end up compressing the indentation unnecessarily: // ┏----------------------┓ // ┆ <ReallyLongName> ┆ // ┆ •<Foo> ┆ // ┆ ••<Bar> ┆ // ┆ •••<Baz> ┆ // ┆ ••••<Qux> ┆ // ┗----------------------┛ // // The way we deal with this is to compute the max indentation size that can fit each child, // given the child's fixed width and depth within the tree. // Then we take the smallest of these indentation sizes... function updateIndentationSizeVar( innerDiv: HTMLDivElement, cachedChildWidths: WeakMap<HTMLElement, number>, indentationSizeRef: {current: number}, prevListWidthRef: {current: number}, ): void { const list = ((innerDiv.parentElement: any): HTMLDivElement); const listWidth = list.clientWidth; // Skip measurements when the Components panel is hidden. if (listWidth === 0) { return; } // Reset the max indentation size if the width of the tree has increased. if (listWidth > prevListWidthRef.current) { indentationSizeRef.current = DEFAULT_INDENTATION_SIZE; } prevListWidthRef.current = listWidth; let maxIndentationSize: number = indentationSizeRef.current; // eslint-disable-next-line no-for-of-loops/no-for-of-loops for (const child of innerDiv.children) { const depth = parseInt(child.getAttribute('data-depth'), 10) || 0; let childWidth: number = 0; const cachedChildWidth = cachedChildWidths.get(child); if (cachedChildWidth != null) { childWidth = cachedChildWidth; } else { const {firstElementChild} = child; // Skip over e.g. the guideline element if (firstElementChild != null) { childWidth = firstElementChild.clientWidth; cachedChildWidths.set(child, childWidth); } } const remainingWidth = Math.max(0, listWidth - childWidth); maxIndentationSize = Math.min(maxIndentationSize, remainingWidth / depth); } indentationSizeRef.current = maxIndentationSize; list.style.setProperty('--indentation-size', `${maxIndentationSize}px`); } // $FlowFixMe[missing-local-annot] function InnerElementType({children, style, ...rest}) { const {ownerID} = useContext(TreeStateContext); const cachedChildWidths = useMemo<WeakMap<HTMLElement, number>>( () => new WeakMap(), [], ); // This ref tracks the current indentation size. // We decrease indentation to fit wider/deeper trees. // We intentionally do not increase it again afterward, to avoid the perception of content "jumping" // e.g. clicking to toggle/collapse a row might otherwise jump horizontally beneath your cursor, // e.g. scrolling a wide row off screen could cause narrower rows to jump to the right some. // // There are two exceptions for this: // 1. The first is when the width of the tree increases. // The user may have resized the window specifically to make more room for DevTools. // In either case, this should reset our max indentation size logic. // 2. The second is when the user enters or exits an owner tree. const indentationSizeRef = useRef<number>(DEFAULT_INDENTATION_SIZE); const prevListWidthRef = useRef<number>(0); const prevOwnerIDRef = useRef<number | null>(ownerID); const divRef = useRef<HTMLDivElement | null>(null); // We shouldn't retain this width across different conceptual trees though, // so when the user opens the "owners tree" view, we should discard the previous width. if (ownerID !== prevOwnerIDRef.current) { prevOwnerIDRef.current = ownerID; indentationSizeRef.current = DEFAULT_INDENTATION_SIZE; } // When we render new content, measure to see if we need to shrink indentation to fit it. useEffect(() => { if (divRef.current !== null) { updateIndentationSizeVar( divRef.current, cachedChildWidths, indentationSizeRef, prevListWidthRef, ); } }); // This style override enables the background color to fill the full visible width, // when combined with the CSS tweaks in Element. // A lot of options were considered; this seemed the one that requires the least code. // See https://github.com/bvaughn/react-devtools-experimental/issues/9 return ( <div className={styles.InnerElementType} ref={divRef} style={style} {...rest}> <SelectedTreeHighlight /> {children} </div> ); } function Loading() { return <div className={styles.Loading}>Loading...</div>; }
33.308458
128
0.61425
Python-Penetration-Testing-Cookbook
/* * 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 {getHookNamesMappingFromAST} from './astUtils'; import {encode, decode} from 'sourcemap-codec'; // Missing types in @babel/types type File = any; export type HookMap = { names: $ReadOnlyArray<string>, mappings: HookMapMappings, }; export type EncodedHookMap = { names: $ReadOnlyArray<string>, mappings: string, }; // See generateHookMap below for more details on formatting export type HookMapEntry = [ number, // 1-indexed line number number, // 0-indexed column number number, // 0-indexed index into names array number, // TODO: filler number to support reusing encoding from `sourcemap-codec` (see TODO below) ]; export type HookMapLine = HookMapEntry[]; export type HookMapMappings = HookMapLine[]; /** * Given a parsed source code AST, returns a "Hook Map", which is a * mapping which maps locations in the source code to their to their * corresponding Hook name, if there is a relevant Hook name for that * location (see getHookNamesMappingFromAST for details on the * representation of the mapping). * * The format of the Hook Map follows a similar format as the `name` * and `mappings` fields in the Source Map spec, where `names` is an * array of strings, and `mappings` contains segments lines, columns, * and indices into the `names` array. * * E.g.: * { * names: ["<no-hook>", "state"], * mappings: [ * [ -> line 1 * [1, 0, 0], -> line, col, name index * ], * [ -> line 2 * [2, 5, 1], -> line, col, name index * [2, 15, 0], -> line, col, name index * ], * ], * } */ export function generateHookMap(sourceAST: File): HookMap { const hookNamesMapping = getHookNamesMappingFromAST(sourceAST); const namesMap: Map<string, number> = new Map(); const names = []; const mappings: Array<HookMapLine> = []; let currentLine: $FlowFixMe | null = null; hookNamesMapping.forEach(({name, start}) => { let nameIndex = namesMap.get(name); if (nameIndex == null) { names.push(name); nameIndex = names.length - 1; namesMap.set(name, nameIndex); } // TODO: We add a -1 at the end of the entry so we can later // encode/decode the mappings by reusing the encode/decode functions // from the `sourcemap-codec` library. This library expects segments // of specific sizes (i.e. of size 4) in order to encode them correctly. // In the future, when we implement our own encoding, we will not // need this restriction and can remove the -1 at the end. const entry = [start.line, start.column, nameIndex, -1]; if (currentLine !== start.line) { currentLine = start.line; mappings.push([entry]); } else { const current = mappings[mappings.length - 1]; current.push(entry); } }); return {names, mappings}; } /** * Returns encoded version of a Hook Map that is returned * by generateHookMap. * * **NOTE:** * TODO: To encode the `mappings` in the Hook Map, we * reuse the encode function from the `sourcemap-codec` * library, which means that we are restricted to only * encoding segments of specific sizes. * Inside generateHookMap we make sure to build segments * of size 4. * In the future, when we implement our own encoding, we will not * need this restriction and can remove the -1 at the end. */ export function generateEncodedHookMap(sourceAST: File): EncodedHookMap { const hookMap = generateHookMap(sourceAST); const encoded = encode(hookMap.mappings); return { names: hookMap.names, mappings: encoded, }; } export function decodeHookMap(encodedHookMap: EncodedHookMap): HookMap { return { names: encodedHookMap.names, mappings: decode(encodedHookMap.mappings), }; }
30.261905
100
0.675216
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 nullthrows from 'nullthrows'; import InvalidProfileError from './InvalidProfileError'; export const readInputData = (file: File): Promise<string> => { if (!file.name.endsWith('.json')) { throw new InvalidProfileError( 'Invalid file type. Only JSON performance profiles are supported', ); } const fileReader = new FileReader(); return new Promise((resolve, reject) => { fileReader.onload = () => { const result = nullthrows(fileReader.result); if (typeof result === 'string') { resolve(result); } reject(new InvalidProfileError('Input file was not read as a string')); }; fileReader.onerror = () => reject(fileReader.error); fileReader.readAsText(file); }); };
25.361111
77
0.661392
hackipy
/** * 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} from './src/ReactFlightWebpackPlugin';
22.727273
66
0.707692
hackipy
/** * 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/ReactFlightDOMServerBrowser';
22.272727
66
0.705882
diff-droid
"use strict"; /** * 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 { useMemo, useState } = require('react'); function Component(props) { const InnerComponent = useMemo(() => () => { const [state] = useState(0); return state; }); props.callback(InnerComponent); return null; } module.exports = { Component }; //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhOZXN0ZWRIb29rcy5qcyJdLCJuYW1lcyI6WyJ1c2VNZW1vIiwidXNlU3RhdGUiLCJyZXF1aXJlIiwiQ29tcG9uZW50IiwicHJvcHMiLCJJbm5lckNvbXBvbmVudCIsInN0YXRlIiwiY2FsbGJhY2siLCJtb2R1bGUiLCJleHBvcnRzIl0sIm1hcHBpbmdzIjoiOztBQUFBOzs7Ozs7OztBQVFBLE1BQU07QUFBQ0EsRUFBQUEsT0FBRDtBQUFVQyxFQUFBQTtBQUFWLElBQXNCQyxPQUFPLENBQUMsT0FBRCxDQUFuQzs7QUFFQSxTQUFTQyxTQUFULENBQW1CQyxLQUFuQixFQUEwQjtBQUN4QixRQUFNQyxjQUFjLEdBQUdMLE9BQU8sQ0FBQyxNQUFNLE1BQU07QUFDekMsVUFBTSxDQUFDTSxLQUFELElBQVVMLFFBQVEsQ0FBQyxDQUFELENBQXhCO0FBRUEsV0FBT0ssS0FBUDtBQUNELEdBSjZCLENBQTlCO0FBS0FGLEVBQUFBLEtBQUssQ0FBQ0csUUFBTixDQUFlRixjQUFmO0FBRUEsU0FBTyxJQUFQO0FBQ0Q7O0FBRURHLE1BQU0sQ0FBQ0MsT0FBUCxHQUFpQjtBQUFDTixFQUFBQTtBQUFELENBQWpCIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBDb3B5cmlnaHQgKGMpIEZhY2Vib29rLCBJbmMuIGFuZCBpdHMgYWZmaWxpYXRlcy5cbiAqXG4gKiBUaGlzIHNvdXJjZSBjb2RlIGlzIGxpY2Vuc2VkIHVuZGVyIHRoZSBNSVQgbGljZW5zZSBmb3VuZCBpbiB0aGVcbiAqIExJQ0VOU0UgZmlsZSBpbiB0aGUgcm9vdCBkaXJlY3Rvcnkgb2YgdGhpcyBzb3VyY2UgdHJlZS5cbiAqXG4gKiBAZmxvd1xuICovXG5jb25zdCB7dXNlTWVtbywgdXNlU3RhdGV9ID0gcmVxdWlyZSgncmVhY3QnKTtcblxuZnVuY3Rpb24gQ29tcG9uZW50KHByb3BzKSB7XG4gIGNvbnN0IElubmVyQ29tcG9uZW50ID0gdXNlTWVtbygoKSA9PiAoKSA9PiB7XG4gICAgY29uc3QgW3N0YXRlXSA9IHVzZVN0YXRlKDApO1xuXG4gICAgcmV0dXJuIHN0YXRlO1xuICB9KTtcbiAgcHJvcHMuY2FsbGJhY2soSW5uZXJDb21wb25lbnQpO1xuXG4gIHJldHVybiBudWxsO1xufVxuXG5tb2R1bGUuZXhwb3J0cyA9IHtDb21wb25lbnR9O1xuIl0sInhfcmVhY3Rfc291cmNlcyI6W1t7Im5hbWVzIjpbIjxuby1ob29rPiIsIklubmVyQ29tcG9uZW50Iiwic3RhdGUiXSwibWFwcGluZ3MiOiJDQUFEO1l5QkNBO2FMQ0EsQVdEQTtnQjNCREEifV1dfQ==
74.035714
1,616
0.912381
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 strict */ 'use strict'; // Noop // TODO #10932517: Move all initialization callers back into react-native
19.666667
73
0.705502
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 * as React from 'react'; import {Fragment, memo, useCallback, useContext} from 'react'; import {areEqual} from 'react-window'; import {barWidthThreshold} from './constants'; import {getGradientColor} from './utils'; import ChartNode from './ChartNode'; import {SettingsContext} from '../Settings/SettingsContext'; import type {ChartNode as ChartNodeType} from './FlamegraphChartBuilder'; import type {ItemData} from './CommitFlamegraph'; type Props = { data: ItemData, index: number, style: Object, ... }; function CommitFlamegraphListItem({data, index, style}: Props): React.Node { const { chartData, onElementMouseEnter, onElementMouseLeave, scaleX, selectedChartNode, selectedChartNodeIndex, selectFiber, width, } = data; const {renderPathNodes, maxSelfDuration, rows} = chartData; const {lineHeight} = useContext(SettingsContext); const handleClick = useCallback( (event: SyntheticMouseEvent<EventTarget>, id: number, name: string) => { event.stopPropagation(); selectFiber(id, name); }, [selectFiber], ); const handleMouseEnter = (nodeData: ChartNodeType) => { const {id, name} = nodeData; onElementMouseEnter({id, name}); }; const handleMouseLeave = () => { onElementMouseLeave(); }; // List items are absolutely positioned using the CSS "top" attribute. // The "left" value will always be 0. // Since height is fixed, and width is based on the node's duration, // We can ignore those values as well. const top = parseInt(style.top, 10); const row = rows[index]; const selectedNodeOffset = scaleX( selectedChartNode !== null ? selectedChartNode.offset : 0, width, ); return ( <Fragment> {row.map(chartNode => { const { didRender, id, label, name, offset, selfDuration, treeBaseDuration, } = chartNode; const nodeOffset = scaleX(offset, width); const nodeWidth = scaleX(treeBaseDuration, width); // Filter out nodes that are too small to see or click. // This also helps render large trees faster. if (nodeWidth < barWidthThreshold) { return null; } // Filter out nodes that are outside of the horizontal window. if ( nodeOffset + nodeWidth < selectedNodeOffset || nodeOffset > selectedNodeOffset + width ) { return null; } let color = 'url(#didNotRenderPattern)'; let textColor = 'var(--color-commit-did-not-render-pattern-text)'; if (didRender) { color = getGradientColor(selfDuration / maxSelfDuration); textColor = 'var(--color-commit-gradient-text)'; } else if (renderPathNodes.has(id)) { color = 'var(--color-commit-did-not-render-fill)'; textColor = 'var(--color-commit-did-not-render-fill-text)'; } return ( <ChartNode color={color} height={lineHeight} isDimmed={index < selectedChartNodeIndex} key={id} label={label} onClick={event => handleClick(event, id, name)} onMouseEnter={() => handleMouseEnter(chartNode)} onMouseLeave={handleMouseLeave} textStyle={{color: textColor}} width={nodeWidth} x={nodeOffset - selectedNodeOffset} y={top} /> ); })} </Fragment> ); } export default (memo( CommitFlamegraphListItem, areEqual, ): React.ComponentType<Props>);
26.630435
76
0.617786
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('ReactDOMInvalidARIAHook', () => { let React; let ReactTestUtils; let mountComponent; beforeEach(() => { jest.resetModules(); React = require('react'); ReactTestUtils = require('react-dom/test-utils'); mountComponent = function (props) { ReactTestUtils.renderIntoDocument(<div {...props} />); }; }); describe('aria-* props', () => { it('should allow valid aria-* props', () => { mountComponent({'aria-label': 'Bumble bees'}); }); it('should warn for one invalid aria-* prop', () => { expect(() => mountComponent({'aria-badprop': 'maybe'})).toErrorDev( 'Warning: Invalid aria prop `aria-badprop` on <div> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', ); }); it('should warn for many invalid aria-* props', () => { expect(() => mountComponent({ 'aria-badprop': 'Very tall trees', 'aria-malprop': 'Turbulent seas', }), ).toErrorDev( 'Warning: Invalid aria props `aria-badprop`, `aria-malprop` on <div> ' + 'tag. For details, see https://reactjs.org/link/invalid-aria-props', ); }); it('should warn for an improperly cased aria-* prop', () => { // The valid attribute name is aria-haspopup. expect(() => mountComponent({'aria-hasPopup': 'true'})).toErrorDev( 'Warning: Unknown ARIA attribute `aria-hasPopup`. ' + 'Did you mean `aria-haspopup`?', ); }); it('should warn for use of recognized camel case aria attributes', () => { // The valid attribute name is aria-haspopup. expect(() => mountComponent({ariaHasPopup: 'true'})).toErrorDev( 'Warning: Invalid ARIA attribute `ariaHasPopup`. ' + 'Did you mean `aria-haspopup`?', ); }); it('should warn for use of unrecognized camel case aria attributes', () => { // The valid attribute name is aria-haspopup. expect(() => mountComponent({ariaSomethingInvalid: 'true'})).toErrorDev( 'Warning: Invalid ARIA attribute `ariaSomethingInvalid`. ARIA ' + 'attributes follow the pattern aria-* and must be lowercase.', ); }); }); });
32.506849
80
0.597137
Python-Penetration-Testing-Cookbook
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e=e||self).ReactWindow={},e.React)}(this,function(e,t){"use strict";function r(){return(r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function n(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}function o(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}var i=function(e,t){return e.length===t.length&&e.every(function(e,r){return n=e,o=t[r],n===o;var n,o})};function a(e,t){var r;void 0===t&&(t=i);var n,o=[],a=!1;return function(){for(var i=arguments.length,l=new Array(i),s=0;s<i;s++)l[s]=arguments[s];return a&&r===this&&t(l,o)?n:(n=e.apply(this,l),a=!0,r=this,o=l,n)}}var l="object"==typeof performance&&"function"==typeof performance.now?function(){return performance.now()}:function(){return Date.now()};function s(e){cancelAnimationFrame(e.id)}function c(e,t){var r=l();var n={id:requestAnimationFrame(function o(){l()-r>=t?e.call(null):n.id=requestAnimationFrame(o)})};return n}var u=-1;var d=null;function f(e){if(void 0===e&&(e=!1),null===d||e){var t=document.createElement("div"),r=t.style;r.width="50px",r.height="50px",r.overflow="scroll",r.direction="rtl";var n=document.createElement("div"),o=n.style;return o.width="100px",o.height="100px",t.appendChild(n),document.body.appendChild(t),t.scrollLeft>0?d="positive-descending":(t.scrollLeft=1,d=0===t.scrollLeft?"negative":"positive-ascending"),document.body.removeChild(t),d}return d}var h=150,p=function(e){var t=e.columnIndex;e.data;return e.rowIndex+":"+t},m=null,v=null,g=null;function w(e){var i,l,d=e.getColumnOffset,m=e.getColumnStartIndexForOffset,v=e.getColumnStopIndexForStartIndex,g=e.getColumnWidth,w=e.getEstimatedTotalHeight,I=e.getEstimatedTotalWidth,M=e.getOffsetForColumnAndAlignment,y=e.getOffsetForRowAndAlignment,x=e.getRowHeight,C=e.getRowOffset,_=e.getRowStartIndexForOffset,b=e.getRowStopIndexForStartIndex,R=e.initInstanceProps,T=e.shouldResetStyleCacheOnItemSizeChange,z=e.validateProps;return l=i=function(e){function i(t){var r;return(r=e.call(this,t)||this)._instanceProps=R(r.props,o(o(r))),r._resetIsScrollingTimeoutId=null,r._outerRef=void 0,r.state={instance:o(o(r)),isScrolling:!1,horizontalScrollDirection:"forward",scrollLeft:"number"==typeof r.props.initialScrollLeft?r.props.initialScrollLeft:0,scrollTop:"number"==typeof r.props.initialScrollTop?r.props.initialScrollTop:0,scrollUpdateWasRequested:!1,verticalScrollDirection:"forward"},r._callOnItemsRendered=void 0,r._callOnItemsRendered=a(function(e,t,n,o,i,a,l,s){return r.props.onItemsRendered({overscanColumnStartIndex:e,overscanColumnStopIndex:t,overscanRowStartIndex:n,overscanRowStopIndex:o,visibleColumnStartIndex:i,visibleColumnStopIndex:a,visibleRowStartIndex:l,visibleRowStopIndex:s})}),r._callOnScroll=void 0,r._callOnScroll=a(function(e,t,n,o,i){return r.props.onScroll({horizontalScrollDirection:n,scrollLeft:e,scrollTop:t,verticalScrollDirection:o,scrollUpdateWasRequested:i})}),r._getItemStyle=void 0,r._getItemStyle=function(e,t){var n,o,i=r.props,a=i.columnWidth,l=i.direction,s=i.rowHeight,c=r._getItemStyleCache(T&&a,T&&l,T&&s),u=e+":"+t;c.hasOwnProperty(u)?n=c[u]:c[u]=((o={position:"absolute"})["rtl"===l?"right":"left"]=d(r.props,t,r._instanceProps),o.top=C(r.props,e,r._instanceProps),o.height=x(r.props,e,r._instanceProps),o.width=g(r.props,t,r._instanceProps),n=o);return n},r._getItemStyleCache=void 0,r._getItemStyleCache=a(function(e,t,r){return{}}),r._onScroll=function(e){var t=e.currentTarget,n=t.clientHeight,o=t.clientWidth,i=t.scrollLeft,a=t.scrollTop,l=t.scrollHeight,s=t.scrollWidth;r.setState(function(e){if(e.scrollLeft===i&&e.scrollTop===a)return null;var t=r.props.direction,c=i;if("rtl"===t)switch(f()){case"negative":c=-i;break;case"positive-descending":c=s-o-i}c=Math.max(0,Math.min(c,s-o));var u=Math.max(0,Math.min(a,l-n));return{isScrolling:!0,horizontalScrollDirection:e.scrollLeft<i?"forward":"backward",scrollLeft:c,scrollTop:u,verticalScrollDirection:e.scrollTop<a?"forward":"backward",scrollUpdateWasRequested:!1}},r._resetIsScrollingDebounced)},r._outerRefSetter=function(e){var t=r.props.outerRef;r._outerRef=e,"function"==typeof t?t(e):null!=t&&"object"==typeof t&&t.hasOwnProperty("current")&&(t.current=e)},r._resetIsScrollingDebounced=function(){null!==r._resetIsScrollingTimeoutId&&s(r._resetIsScrollingTimeoutId),r._resetIsScrollingTimeoutId=c(r._resetIsScrolling,h)},r._resetIsScrolling=function(){r._resetIsScrollingTimeoutId=null,r.setState({isScrolling:!1},function(){r._getItemStyleCache(-1)})},r}n(i,e),i.getDerivedStateFromProps=function(e,t){return S(e,t),z(e),null};var l=i.prototype;return l.scrollTo=function(e){var t=e.scrollLeft,r=e.scrollTop;void 0!==t&&(t=Math.max(0,t)),void 0!==r&&(r=Math.max(0,r)),this.setState(function(e){return void 0===t&&(t=e.scrollLeft),void 0===r&&(r=e.scrollTop),e.scrollLeft===t&&e.scrollTop===r?null:{horizontalScrollDirection:e.scrollLeft<t?"forward":"backward",scrollLeft:t,scrollTop:r,scrollUpdateWasRequested:!0,verticalScrollDirection:e.scrollTop<r?"forward":"backward"}},this._resetIsScrollingDebounced)},l.scrollToItem=function(e){var t=e.align,r=void 0===t?"auto":t,n=e.columnIndex,o=e.rowIndex,i=this.props,a=i.columnCount,l=i.height,s=i.rowCount,c=i.width,d=this.state,f=d.scrollLeft,h=d.scrollTop,p=function(e){if(void 0===e&&(e=!1),-1===u||e){var t=document.createElement("div"),r=t.style;r.width="50px",r.height="50px",r.overflow="scroll",document.body.appendChild(t),u=t.offsetWidth-t.clientWidth,document.body.removeChild(t)}return u}();void 0!==n&&(n=Math.max(0,Math.min(n,a-1))),void 0!==o&&(o=Math.max(0,Math.min(o,s-1)));var m=w(this.props,this._instanceProps),v=I(this.props,this._instanceProps)>c?p:0,g=m>l?p:0;this.scrollTo({scrollLeft:void 0!==n?M(this.props,n,r,f,this._instanceProps,g):f,scrollTop:void 0!==o?y(this.props,o,r,h,this._instanceProps,v):h})},l.componentDidMount=function(){var e=this.props,t=e.initialScrollLeft,r=e.initialScrollTop;if(null!=this._outerRef){var n=this._outerRef;"number"==typeof t&&(n.scrollLeft=t),"number"==typeof r&&(n.scrollTop=r)}this._callPropsCallbacks()},l.componentDidUpdate=function(){var e=this.props.direction,t=this.state,r=t.scrollLeft,n=t.scrollTop;if(t.scrollUpdateWasRequested&&null!=this._outerRef){var o=this._outerRef;if("rtl"===e)switch(f()){case"negative":o.scrollLeft=-r;break;case"positive-ascending":o.scrollLeft=r;break;default:var i=o.clientWidth,a=o.scrollWidth;o.scrollLeft=a-i-r}else o.scrollLeft=Math.max(0,r);o.scrollTop=Math.max(0,n)}this._callPropsCallbacks()},l.componentWillUnmount=function(){null!==this._resetIsScrollingTimeoutId&&s(this._resetIsScrollingTimeoutId)},l.render=function(){var e=this.props,n=e.children,o=e.className,i=e.columnCount,a=e.direction,l=e.height,s=e.innerRef,c=e.innerElementType,u=e.innerTagName,d=e.itemData,f=e.itemKey,h=void 0===f?p:f,m=e.outerElementType,v=e.outerTagName,g=e.rowCount,S=e.style,M=e.useIsScrolling,y=e.width,x=this.state.isScrolling,C=this._getHorizontalRangeToRender(),_=C[0],b=C[1],R=this._getVerticalRangeToRender(),T=R[0],z=R[1],O=[];if(i>0&&g)for(var P=T;P<=z;P++)for(var W=_;W<=b;W++)O.push(t.createElement(n,{columnIndex:W,data:d,isScrolling:M?x:void 0,key:h({columnIndex:W,data:d,rowIndex:P}),rowIndex:P,style:this._getItemStyle(P,W)}));var E=w(this.props,this._instanceProps),A=I(this.props,this._instanceProps);return t.createElement(m||v||"div",{className:o,onScroll:this._onScroll,ref:this._outerRefSetter,style:r({position:"relative",height:l,width:y,overflow:"auto",WebkitOverflowScrolling:"touch",willChange:"transform",direction:a},S)},t.createElement(c||u||"div",{children:O,ref:s,style:{height:E,pointerEvents:x?"none":void 0,width:A}}))},l._callPropsCallbacks=function(){var e=this.props,t=e.columnCount,r=e.onItemsRendered,n=e.onScroll,o=e.rowCount;if("function"==typeof r&&t>0&&o>0){var i=this._getHorizontalRangeToRender(),a=i[0],l=i[1],s=i[2],c=i[3],u=this._getVerticalRangeToRender(),d=u[0],f=u[1],h=u[2],p=u[3];this._callOnItemsRendered(a,l,d,f,s,c,h,p)}if("function"==typeof n){var m=this.state,v=m.horizontalScrollDirection,g=m.scrollLeft,w=m.scrollTop,S=m.scrollUpdateWasRequested,I=m.verticalScrollDirection;this._callOnScroll(g,w,v,I,S)}},l._getHorizontalRangeToRender=function(){var e=this.props,t=e.columnCount,r=e.overscanColumnCount,n=e.overscanColumnsCount,o=e.overscanCount,i=e.rowCount,a=this.state,l=a.horizontalScrollDirection,s=a.isScrolling,c=a.scrollLeft,u=r||n||o||1;if(0===t||0===i)return[0,0,0,0];var d=m(this.props,c,this._instanceProps),f=v(this.props,d,c,this._instanceProps),h=s&&"backward"!==l?1:Math.max(1,u),p=s&&"forward"!==l?1:Math.max(1,u);return[Math.max(0,d-h),Math.max(0,Math.min(t-1,f+p)),d,f]},l._getVerticalRangeToRender=function(){var e=this.props,t=e.columnCount,r=e.overscanCount,n=e.overscanRowCount,o=e.overscanRowsCount,i=e.rowCount,a=this.state,l=a.isScrolling,s=a.verticalScrollDirection,c=a.scrollTop,u=n||o||r||1;if(0===t||0===i)return[0,0,0,0];var d=_(this.props,c,this._instanceProps),f=b(this.props,d,c,this._instanceProps),h=l&&"backward"!==s?1:Math.max(1,u),p=l&&"forward"!==s?1:Math.max(1,u);return[Math.max(0,d-h),Math.max(0,Math.min(i-1,f+p)),d,f]},i}(t.PureComponent),i.defaultProps={direction:"ltr",itemData:void 0,useIsScrolling:!1},l}"undefined"!=typeof window&&void 0!==window.WeakSet&&(m=new WeakSet,v=new WeakSet,g=new WeakSet);var S=function(e,t){var r=e.children,n=e.direction,o=e.height,i=e.innerTagName,a=e.outerTagName,l=e.overscanColumnsCount,s=e.overscanCount,c=e.overscanRowsCount,u=e.width,d=t.instance;if("number"==typeof s&&m&&!m.has(d)&&(m.add(d),console.warn("The overscanCount prop has been deprecated. Please use the overscanColumnCount and overscanRowCount props instead.")),"number"!=typeof l&&"number"!=typeof c||v&&!v.has(d)&&(v.add(d),console.warn("The overscanColumnsCount and overscanRowsCount props have been deprecated. Please use the overscanColumnCount and overscanRowCount props instead.")),null==i&&null==a||g&&!g.has(d)&&(g.add(d),console.warn("The innerTagName and outerTagName props have been deprecated. Please use the innerElementType and outerElementType props instead.")),null==r)throw Error('An invalid "children" prop has been specified. Value should be a React component. "'+(null===r?"null":typeof r)+'" was specified.');switch(n){case"ltr":case"rtl":break;default:throw Error('An invalid "direction" prop has been specified. Value should be either "ltr" or "rtl". "'+n+'" was specified.')}if("number"!=typeof u)throw Error('An invalid "width" prop has been specified. Grids must specify a number for width. "'+(null===u?"null":typeof u)+'" was specified.');if("number"!=typeof o)throw Error('An invalid "height" prop has been specified. Grids must specify a number for height. "'+(null===o?"null":typeof o)+'" was specified.')},I=function(e,t){var r=e.rowCount,n=t.rowMetadataMap,o=t.estimatedRowHeight,i=t.lastMeasuredRowIndex,a=0;if(i>=r&&(i=r-1),i>=0){var l=n[i];a=l.offset+l.size}return a+(r-i-1)*o},M=function(e,t){var r=e.columnCount,n=t.columnMetadataMap,o=t.estimatedColumnWidth,i=t.lastMeasuredColumnIndex,a=0;if(i>=r&&(i=r-1),i>=0){var l=n[i];a=l.offset+l.size}return a+(r-i-1)*o},y=function(e,t,r,n){var o,i,a;if("column"===e?(o=n.columnMetadataMap,i=t.columnWidth,a=n.lastMeasuredColumnIndex):(o=n.rowMetadataMap,i=t.rowHeight,a=n.lastMeasuredRowIndex),r>a){var l=0;if(a>=0){var s=o[a];l=s.offset+s.size}for(var c=a+1;c<=r;c++){var u=i(c);o[c]={offset:l,size:u},l+=u}"column"===e?n.lastMeasuredColumnIndex=r:n.lastMeasuredRowIndex=r}return o[r]},x=function(e,t,r,n){var o,i;return"column"===e?(o=r.columnMetadataMap,i=r.lastMeasuredColumnIndex):(o=r.rowMetadataMap,i=r.lastMeasuredRowIndex),(i>0?o[i].offset:0)>=n?C(e,t,r,i,0,n):_(e,t,r,Math.max(0,i),n)},C=function(e,t,r,n,o,i){for(;o<=n;){var a=o+Math.floor((n-o)/2),l=y(e,t,a,r).offset;if(l===i)return a;l<i?o=a+1:l>i&&(n=a-1)}return o>0?o-1:0},_=function(e,t,r,n,o){for(var i="column"===e?t.columnCount:t.rowCount,a=1;n<i&&y(e,t,n,r).offset<o;)n+=a,a*=2;return C(e,t,r,Math.min(n,i-1),Math.floor(n/2),o)},b=function(e,t,r,n,o,i,a){var l="column"===e?t.width:t.height,s=y(e,t,r,i),c="column"===e?M(t,i):I(t,i),u=Math.max(0,Math.min(c-l,s.offset)),d=Math.max(0,s.offset-l+a+s.size);switch("smart"===n&&(n=o>=d-l&&o<=u+l?"auto":"center"),n){case"start":return u;case"end":return d;case"center":return Math.round(d+(u-d)/2);case"auto":default:return o>=d&&o<=u?o:d>u?d:o<d?d:u}},R=w({getColumnOffset:function(e,t,r){return y("column",e,t,r).offset},getColumnStartIndexForOffset:function(e,t,r){return x("column",e,r,t)},getColumnStopIndexForStartIndex:function(e,t,r,n){for(var o=e.columnCount,i=e.width,a=y("column",e,t,n),l=r+i,s=a.offset+a.size,c=t;c<o-1&&s<l;)s+=y("column",e,++c,n).size;return c},getColumnWidth:function(e,t,r){return r.columnMetadataMap[t].size},getEstimatedTotalHeight:I,getEstimatedTotalWidth:M,getOffsetForColumnAndAlignment:function(e,t,r,n,o,i){return b("column",e,t,r,n,o,i)},getOffsetForRowAndAlignment:function(e,t,r,n,o,i){return b("row",e,t,r,n,o,i)},getRowOffset:function(e,t,r){return y("row",e,t,r).offset},getRowHeight:function(e,t,r){return r.rowMetadataMap[t].size},getRowStartIndexForOffset:function(e,t,r){return x("row",e,r,t)},getRowStopIndexForStartIndex:function(e,t,r,n){for(var o=e.rowCount,i=e.height,a=y("row",e,t,n),l=r+i,s=a.offset+a.size,c=t;c<o-1&&s<l;)s+=y("row",e,++c,n).size;return c},initInstanceProps:function(e,t){var r=e,n={columnMetadataMap:{},estimatedColumnWidth:r.estimatedColumnWidth||50,estimatedRowHeight:r.estimatedRowHeight||50,lastMeasuredColumnIndex:-1,lastMeasuredRowIndex:-1,rowMetadataMap:{}};return t.resetAfterColumnIndex=function(e,r){void 0===r&&(r=!0),t.resetAfterIndices({columnIndex:e,shouldForceUpdate:r})},t.resetAfterRowIndex=function(e,r){void 0===r&&(r=!0),t.resetAfterIndices({rowIndex:e,shouldForceUpdate:r})},t.resetAfterIndices=function(e){var r=e.columnIndex,o=e.rowIndex,i=e.shouldForceUpdate,a=void 0===i||i;"number"==typeof r&&(n.lastMeasuredColumnIndex=Math.min(n.lastMeasuredColumnIndex,r-1)),"number"==typeof o&&(n.lastMeasuredRowIndex=Math.min(n.lastMeasuredRowIndex,o-1)),t._getItemStyleCache(-1),a&&t.forceUpdate()},n},shouldResetStyleCacheOnItemSizeChange:!1,validateProps:function(e){var t=e.columnWidth,r=e.rowHeight;if("function"!=typeof t)throw Error('An invalid "columnWidth" prop has been specified. Value should be a function. "'+(null===t?"null":typeof t)+'" was specified.');if("function"!=typeof r)throw Error('An invalid "rowHeight" prop has been specified. Value should be a function. "'+(null===r?"null":typeof r)+'" was specified.')}}),T=150,z=function(e,t){return e},O=null,P=null;function W(e){var i,l,u=e.getItemOffset,d=e.getEstimatedTotalSize,h=e.getItemSize,p=e.getOffsetForIndexAndAlignment,m=e.getStartIndexForOffset,v=e.getStopIndexForStartIndex,g=e.initInstanceProps,w=e.shouldResetStyleCacheOnItemSizeChange,S=e.validateProps;return l=i=function(e){function i(t){var r;return(r=e.call(this,t)||this)._instanceProps=g(r.props,o(o(r))),r._outerRef=void 0,r._resetIsScrollingTimeoutId=null,r.state={instance:o(o(r)),isScrolling:!1,scrollDirection:"forward",scrollOffset:"number"==typeof r.props.initialScrollOffset?r.props.initialScrollOffset:0,scrollUpdateWasRequested:!1},r._callOnItemsRendered=void 0,r._callOnItemsRendered=a(function(e,t,n,o){return r.props.onItemsRendered({overscanStartIndex:e,overscanStopIndex:t,visibleStartIndex:n,visibleStopIndex:o})}),r._callOnScroll=void 0,r._callOnScroll=a(function(e,t,n){return r.props.onScroll({scrollDirection:e,scrollOffset:t,scrollUpdateWasRequested:n})}),r._getItemStyle=void 0,r._getItemStyle=function(e){var t,n=r.props,o=n.direction,i=n.itemSize,a=n.layout,l=r._getItemStyleCache(w&&i,w&&a,w&&o);if(l.hasOwnProperty(e))t=l[e];else{var s,c=u(r.props,e,r._instanceProps),d=h(r.props,e,r._instanceProps),f="horizontal"===o||"horizontal"===a;l[e]=((s={position:"absolute"})["rtl"===o?"right":"left"]=f?c:0,s.top=f?0:c,s.height=f?"100%":d,s.width=f?d:"100%",t=s)}return t},r._getItemStyleCache=void 0,r._getItemStyleCache=a(function(e,t,r){return{}}),r._onScrollHorizontal=function(e){var t=e.currentTarget,n=t.clientWidth,o=t.scrollLeft,i=t.scrollWidth;r.setState(function(e){if(e.scrollOffset===o)return null;var t=r.props.direction,a=o;if("rtl"===t)switch(f()){case"negative":a=-o;break;case"positive-descending":a=i-n-o}return a=Math.max(0,Math.min(a,i-n)),{isScrolling:!0,scrollDirection:e.scrollOffset<o?"forward":"backward",scrollOffset:a,scrollUpdateWasRequested:!1}},r._resetIsScrollingDebounced)},r._onScrollVertical=function(e){var t=e.currentTarget,n=t.clientHeight,o=t.scrollHeight,i=t.scrollTop;r.setState(function(e){if(e.scrollOffset===i)return null;var t=Math.max(0,Math.min(i,o-n));return{isScrolling:!0,scrollDirection:e.scrollOffset<t?"forward":"backward",scrollOffset:t,scrollUpdateWasRequested:!1}},r._resetIsScrollingDebounced)},r._outerRefSetter=function(e){var t=r.props.outerRef;r._outerRef=e,"function"==typeof t?t(e):null!=t&&"object"==typeof t&&t.hasOwnProperty("current")&&(t.current=e)},r._resetIsScrollingDebounced=function(){null!==r._resetIsScrollingTimeoutId&&s(r._resetIsScrollingTimeoutId),r._resetIsScrollingTimeoutId=c(r._resetIsScrolling,T)},r._resetIsScrolling=function(){r._resetIsScrollingTimeoutId=null,r.setState({isScrolling:!1},function(){r._getItemStyleCache(-1,null)})},r}n(i,e),i.getDerivedStateFromProps=function(e,t){return E(e,t),S(e),null};var l=i.prototype;return l.scrollTo=function(e){e=Math.max(0,e),this.setState(function(t){return t.scrollOffset===e?null:{scrollDirection:t.scrollOffset<e?"forward":"backward",scrollOffset:e,scrollUpdateWasRequested:!0}},this._resetIsScrollingDebounced)},l.scrollToItem=function(e,t){void 0===t&&(t="auto");var r=this.props.itemCount,n=this.state.scrollOffset;e=Math.max(0,Math.min(e,r-1)),this.scrollTo(p(this.props,e,t,n,this._instanceProps))},l.componentDidMount=function(){var e=this.props,t=e.direction,r=e.initialScrollOffset,n=e.layout;if("number"==typeof r&&null!=this._outerRef){var o=this._outerRef;"horizontal"===t||"horizontal"===n?o.scrollLeft=r:o.scrollTop=r}this._callPropsCallbacks()},l.componentDidUpdate=function(){var e=this.props,t=e.direction,r=e.layout,n=this.state,o=n.scrollOffset;if(n.scrollUpdateWasRequested&&null!=this._outerRef){var i=this._outerRef;if("horizontal"===t||"horizontal"===r)if("rtl"===t)switch(f()){case"negative":i.scrollLeft=-o;break;case"positive-ascending":i.scrollLeft=o;break;default:var a=i.clientWidth,l=i.scrollWidth;i.scrollLeft=l-a-o}else i.scrollLeft=o;else i.scrollTop=o}this._callPropsCallbacks()},l.componentWillUnmount=function(){null!==this._resetIsScrollingTimeoutId&&s(this._resetIsScrollingTimeoutId)},l.render=function(){var e=this.props,n=e.children,o=e.className,i=e.direction,a=e.height,l=e.innerRef,s=e.innerElementType,c=e.innerTagName,u=e.itemCount,f=e.itemData,h=e.itemKey,p=void 0===h?z:h,m=e.layout,v=e.outerElementType,g=e.outerTagName,w=e.style,S=e.useIsScrolling,I=e.width,M=this.state.isScrolling,y="horizontal"===i||"horizontal"===m,x=y?this._onScrollHorizontal:this._onScrollVertical,C=this._getRangeToRender(),_=C[0],b=C[1],R=[];if(u>0)for(var T=_;T<=b;T++)R.push(t.createElement(n,{data:f,key:p(T,f),index:T,isScrolling:S?M:void 0,style:this._getItemStyle(T)}));var O=d(this.props,this._instanceProps);return t.createElement(v||g||"div",{className:o,onScroll:x,ref:this._outerRefSetter,style:r({position:"relative",height:a,width:I,overflow:"auto",WebkitOverflowScrolling:"touch",willChange:"transform",direction:i},w)},t.createElement(s||c||"div",{children:R,ref:l,style:{height:y?"100%":O,pointerEvents:M?"none":void 0,width:y?O:"100%"}}))},l._callPropsCallbacks=function(){if("function"==typeof this.props.onItemsRendered&&this.props.itemCount>0){var e=this._getRangeToRender(),t=e[0],r=e[1],n=e[2],o=e[3];this._callOnItemsRendered(t,r,n,o)}if("function"==typeof this.props.onScroll){var i=this.state,a=i.scrollDirection,l=i.scrollOffset,s=i.scrollUpdateWasRequested;this._callOnScroll(a,l,s)}},l._getRangeToRender=function(){var e=this.props,t=e.itemCount,r=e.overscanCount,n=this.state,o=n.isScrolling,i=n.scrollDirection,a=n.scrollOffset;if(0===t)return[0,0,0,0];var l=m(this.props,a,this._instanceProps),s=v(this.props,l,a,this._instanceProps),c=o&&"backward"!==i?1:Math.max(1,r),u=o&&"forward"!==i?1:Math.max(1,r);return[Math.max(0,l-c),Math.max(0,Math.min(t-1,s+u)),l,s]},i}(t.PureComponent),i.defaultProps={direction:"ltr",itemData:void 0,layout:"vertical",overscanCount:2,useIsScrolling:!1},l}"undefined"!=typeof window&&void 0!==window.WeakSet&&(O=new WeakSet,P=new WeakSet);var E=function(e,t){var r=e.children,n=e.direction,o=e.height,i=e.layout,a=e.innerTagName,l=e.outerTagName,s=e.width,c=t.instance;null==a&&null==l||P&&!P.has(c)&&(P.add(c),console.warn("The innerTagName and outerTagName props have been deprecated. Please use the innerElementType and outerElementType props instead."));var u="horizontal"===n||"horizontal"===i;switch(n){case"horizontal":case"vertical":O&&!O.has(c)&&(O.add(c),console.warn('The direction prop should be either "ltr" (default) or "rtl". Please use the layout prop to specify "vertical" (default) or "horizontal" orientation.'));break;case"ltr":case"rtl":break;default:throw Error('An invalid "direction" prop has been specified. Value should be either "ltr" or "rtl". "'+n+'" was specified.')}switch(i){case"horizontal":case"vertical":break;default:throw Error('An invalid "layout" prop has been specified. Value should be either "horizontal" or "vertical". "'+i+'" was specified.')}if(null==r)throw Error('An invalid "children" prop has been specified. Value should be a React component. "'+(null===r?"null":typeof r)+'" was specified.');if(u&&"number"!=typeof s)throw Error('An invalid "width" prop has been specified. Horizontal lists must specify a number for width. "'+(null===s?"null":typeof s)+'" was specified.');if(!u&&"number"!=typeof o)throw Error('An invalid "height" prop has been specified. Vertical lists must specify a number for height. "'+(null===o?"null":typeof o)+'" was specified.')},A=function(e,t,r){var n=e.itemSize,o=r.itemMetadataMap,i=r.lastMeasuredIndex;if(t>i){var a=0;if(i>=0){var l=o[i];a=l.offset+l.size}for(var s=i+1;s<=t;s++){var c=n(s);o[s]={offset:a,size:c},a+=c}r.lastMeasuredIndex=t}return o[t]},k=function(e,t,r,n,o){for(;n<=r;){var i=n+Math.floor((r-n)/2),a=A(e,i,t).offset;if(a===o)return i;a<o?n=i+1:a>o&&(r=i-1)}return n>0?n-1:0},D=function(e,t,r,n){for(var o=e.itemCount,i=1;r<o&&A(e,r,t).offset<n;)r+=i,i*=2;return k(e,t,Math.min(r,o-1),Math.floor(r/2),n)},F=function(e,t){var r=e.itemCount,n=t.itemMetadataMap,o=t.estimatedItemSize,i=t.lastMeasuredIndex,a=0;if(i>=r&&(i=r-1),i>=0){var l=n[i];a=l.offset+l.size}return a+(r-i-1)*o},L=W({getItemOffset:function(e,t,r){return A(e,t,r).offset},getItemSize:function(e,t,r){return r.itemMetadataMap[t].size},getEstimatedTotalSize:F,getOffsetForIndexAndAlignment:function(e,t,r,n,o){var i=e.direction,a=e.height,l=e.layout,s=e.width,c="horizontal"===i||"horizontal"===l?s:a,u=A(e,t,o),d=F(e,o),f=Math.max(0,Math.min(d-c,u.offset)),h=Math.max(0,u.offset-c+u.size);switch("smart"===r&&(r=n>=h-c&&n<=f+c?"auto":"center"),r){case"start":return f;case"end":return h;case"center":return Math.round(h+(f-h)/2);case"auto":default:return n>=h&&n<=f?n:n<h?h:f}},getStartIndexForOffset:function(e,t,r){return function(e,t,r){var n=t.itemMetadataMap,o=t.lastMeasuredIndex;return(o>0?n[o].offset:0)>=r?k(e,t,o,0,r):D(e,t,Math.max(0,o),r)}(e,r,t)},getStopIndexForStartIndex:function(e,t,r,n){for(var o=e.direction,i=e.height,a=e.itemCount,l=e.layout,s=e.width,c="horizontal"===o||"horizontal"===l?s:i,u=A(e,t,n),d=r+c,f=u.offset+u.size,h=t;h<a-1&&f<d;)f+=A(e,++h,n).size;return h},initInstanceProps:function(e,t){var r={itemMetadataMap:{},estimatedItemSize:e.estimatedItemSize||50,lastMeasuredIndex:-1};return t.resetAfterIndex=function(e,n){void 0===n&&(n=!0),r.lastMeasuredIndex=Math.min(r.lastMeasuredIndex,e-1),t._getItemStyleCache(-1),n&&t.forceUpdate()},r},shouldResetStyleCacheOnItemSizeChange:!1,validateProps:function(e){var t=e.itemSize;if("function"!=typeof t)throw Error('An invalid "itemSize" prop has been specified. Value should be a function. "'+(null===t?"null":typeof t)+'" was specified.')}}),H=w({getColumnOffset:function(e,t){return t*e.columnWidth},getColumnWidth:function(e,t){return e.columnWidth},getRowOffset:function(e,t){return t*e.rowHeight},getRowHeight:function(e,t){return e.rowHeight},getEstimatedTotalHeight:function(e){var t=e.rowCount;return e.rowHeight*t},getEstimatedTotalWidth:function(e){var t=e.columnCount;return e.columnWidth*t},getOffsetForColumnAndAlignment:function(e,t,r,n,o,i){var a=e.columnCount,l=e.columnWidth,s=e.width,c=Math.max(0,a*l-s),u=Math.min(c,t*l),d=Math.max(0,t*l-s+i+l);switch("smart"===r&&(r=n>=d-s&&n<=u+s?"auto":"center"),r){case"start":return u;case"end":return d;case"center":var f=Math.round(d+(u-d)/2);return f<Math.ceil(s/2)?0:f>c+Math.floor(s/2)?c:f;case"auto":default:return n>=d&&n<=u?n:d>u?d:n<d?d:u}},getOffsetForRowAndAlignment:function(e,t,r,n,o,i){var a=e.rowHeight,l=e.height,s=e.rowCount,c=Math.max(0,s*a-l),u=Math.min(c,t*a),d=Math.max(0,t*a-l+i+a);switch("smart"===r&&(r=n>=d-l&&n<=u+l?"auto":"center"),r){case"start":return u;case"end":return d;case"center":var f=Math.round(d+(u-d)/2);return f<Math.ceil(l/2)?0:f>c+Math.floor(l/2)?c:f;case"auto":default:return n>=d&&n<=u?n:d>u?d:n<d?d:u}},getColumnStartIndexForOffset:function(e,t){var r=e.columnWidth,n=e.columnCount;return Math.max(0,Math.min(n-1,Math.floor(t/r)))},getColumnStopIndexForStartIndex:function(e,t,r){var n=e.columnWidth,o=e.columnCount,i=e.width,a=t*n,l=Math.ceil((i+r-a)/n);return Math.max(0,Math.min(o-1,t+l-1))},getRowStartIndexForOffset:function(e,t){var r=e.rowHeight,n=e.rowCount;return Math.max(0,Math.min(n-1,Math.floor(t/r)))},getRowStopIndexForStartIndex:function(e,t,r){var n=e.rowHeight,o=e.rowCount,i=e.height,a=t*n,l=Math.ceil((i+r-a)/n);return Math.max(0,Math.min(o-1,t+l-1))},initInstanceProps:function(e){},shouldResetStyleCacheOnItemSizeChange:!0,validateProps:function(e){var t=e.columnWidth,r=e.rowHeight;if("number"!=typeof t)throw Error('An invalid "columnWidth" prop has been specified. Value should be a number. "'+(null===t?"null":typeof t)+'" was specified.');if("number"!=typeof r)throw Error('An invalid "rowHeight" prop has been specified. Value should be a number. "'+(null===r?"null":typeof r)+'" was specified.')}}),U=W({getItemOffset:function(e,t){return t*e.itemSize},getItemSize:function(e,t){return e.itemSize},getEstimatedTotalSize:function(e){var t=e.itemCount;return e.itemSize*t},getOffsetForIndexAndAlignment:function(e,t,r,n){var o=e.direction,i=e.height,a=e.itemCount,l=e.itemSize,s=e.layout,c=e.width,u="horizontal"===o||"horizontal"===s?c:i,d=Math.max(0,a*l-u),f=Math.min(d,t*l),h=Math.max(0,t*l-u+l);switch("smart"===r&&(r=n>=h-u&&n<=f+u?"auto":"center"),r){case"start":return f;case"end":return h;case"center":var p=Math.round(h+(f-h)/2);return p<Math.ceil(u/2)?0:p>d+Math.floor(u/2)?d:p;case"auto":default:return n>=h&&n<=f?n:n<h?h:f}},getStartIndexForOffset:function(e,t){var r=e.itemCount,n=e.itemSize;return Math.max(0,Math.min(r-1,Math.floor(t/n)))},getStopIndexForStartIndex:function(e,t,r){var n=e.direction,o=e.height,i=e.itemCount,a=e.itemSize,l=e.layout,s=e.width,c=t*a,u="horizontal"===n||"horizontal"===l?s:o,d=Math.ceil((u+r-c)/a);return Math.max(0,Math.min(i-1,t+d-1))},initInstanceProps:function(e){},shouldResetStyleCacheOnItemSizeChange:!0,validateProps:function(e){var t=e.itemSize;if("number"!=typeof t)throw Error('An invalid "itemSize" prop has been specified. Value should be a number. "'+(null===t?"null":typeof t)+'" was specified.')}});function V(e,t){if(null==e)return{};var r,n,o={},i=Object.keys(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)>=0||(o[r]=e[r]);return o}function q(e,t){for(var r in e)if(!(r in t))return!0;for(var n in t)if(e[n]!==t[n])return!0;return!1}function N(e,t){var r=e.style,n=V(e,["style"]),o=t.style,i=V(t,["style"]);return!q(r,o)&&!q(n,i)}e.VariableSizeGrid=R,e.VariableSizeList=L,e.FixedSizeGrid=H,e.FixedSizeList=U,e.areEqual=N,e.shouldComponentUpdate=function(e,t){return!N(this.props,e)||q(this.state,t)},Object.defineProperty(e,"__esModule",{value:!0})}); //# sourceMappingURL=index-dev.umd.js.map
9,508.333333
28,484
0.737897
owtf
import Fixture from '../../Fixture'; const React = window.React; class EmailDisabledAttributesTestCase extends React.Component { state = {value: '[email protected]'}; 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 EmailDisabledAttributesTestCase;
22.675
63
0.520085
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'); const TEXT_NODE_TYPE = 3; let React; let ReactDOM; let ReactDOMServer; let ReactTestUtils; function initModules() { 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, itThrowsWhenRendering, serverRender, streamRender, clientCleanRender, clientRenderOnServerString, } = ReactDOMServerIntegrationUtils(initModules); describe('ReactDOMServerIntegration', () => { beforeEach(() => { resetModules(); }); describe('elements and children', function () { function expectNode(node, type, value) { expect(node).not.toBe(null); expect(node.nodeType).toBe(type); expect(node.nodeValue).toMatch(value); } function expectTextNode(node, text) { expectNode(node, TEXT_NODE_TYPE, text); } describe('text children', function () { itRenders('a div with text', async render => { const e = await render(<div>Text</div>); expect(e.tagName).toBe('DIV'); expect(e.childNodes.length).toBe(1); expectNode(e.firstChild, TEXT_NODE_TYPE, 'Text'); }); itRenders('a div with text with flanking whitespace', async render => { // prettier-ignore const e = await render(<div> Text </div>); expect(e.childNodes.length).toBe(1); expectNode(e.childNodes[0], TEXT_NODE_TYPE, ' Text '); }); itRenders('a div with an empty text child', async render => { const e = await render(<div>{''}</div>); expect(e.childNodes.length).toBe(0); }); itRenders('a div with multiple empty text children', async render => { const e = await render( <div> {''} {''} {''} </div>, ); expect(e.childNodes.length).toBe(0); expect(e.textContent).toBe(''); }); itRenders('a div with multiple whitespace children', async render => { // prettier-ignore const e = await render(<div>{' '}{' '}{' '}</div>); if ( render === serverRender || render === clientRenderOnServerString || render === streamRender ) { // For plain server markup result we have comments between. // If we're able to hydrate, they remain. expect(e.childNodes.length).toBe(5); expectTextNode(e.childNodes[0], ' '); expectTextNode(e.childNodes[2], ' '); expectTextNode(e.childNodes[4], ' '); } else { expect(e.childNodes.length).toBe(3); expectTextNode(e.childNodes[0], ' '); expectTextNode(e.childNodes[1], ' '); expectTextNode(e.childNodes[2], ' '); } }); itRenders('a div with text sibling to a node', async render => { const e = await render( <div> Text<span>More Text</span> </div>, ); expect(e.childNodes.length).toBe(2); const spanNode = e.childNodes[1]; expectTextNode(e.childNodes[0], 'Text'); expect(spanNode.tagName).toBe('SPAN'); expect(spanNode.childNodes.length).toBe(1); expectNode(spanNode.firstChild, TEXT_NODE_TYPE, 'More Text'); }); itRenders('a non-standard element with text', async render => { // This test suite generally assumes that we get exactly // the same warnings (or none) for all scenarios including // SSR + innerHTML, hydration, and client-side rendering. // However this particular warning fires only when creating // DOM nodes on the client side. We force it to fire early // so that it gets deduplicated later, and doesn't fail the test. expect(() => { ReactDOM.render(<nonstandard />, document.createElement('div')); }).toErrorDev('The tag <nonstandard> is unrecognized in this browser.'); const e = await render(<nonstandard>Text</nonstandard>); expect(e.tagName).toBe('NONSTANDARD'); expect(e.childNodes.length).toBe(1); expectNode(e.firstChild, TEXT_NODE_TYPE, 'Text'); }); itRenders('a custom element with text', async render => { const e = await render(<custom-element>Text</custom-element>); expect(e.tagName).toBe('CUSTOM-ELEMENT'); expect(e.childNodes.length).toBe(1); expectNode(e.firstChild, TEXT_NODE_TYPE, 'Text'); }); itRenders('a leading blank child with a text sibling', async render => { const e = await render(<div>{''}foo</div>); expect(e.childNodes.length).toBe(1); expectTextNode(e.childNodes[0], 'foo'); }); itRenders('a trailing blank child with a text sibling', async render => { const e = await render(<div>foo{''}</div>); expect(e.childNodes.length).toBe(1); expectTextNode(e.childNodes[0], 'foo'); }); itRenders('an element with two text children', async render => { const e = await render( <div> {'foo'} {'bar'} </div>, ); if ( render === serverRender || render === clientRenderOnServerString || render === streamRender ) { // In the server render output there's a comment between them. expect(e.childNodes.length).toBe(3); expectTextNode(e.childNodes[0], 'foo'); expectTextNode(e.childNodes[2], 'bar'); } else { expect(e.childNodes.length).toBe(2); expectTextNode(e.childNodes[0], 'foo'); expectTextNode(e.childNodes[1], 'bar'); } }); itRenders( 'a component returning text node between two text nodes', async render => { const B = () => 'b'; const e = await render( <div> {'a'} <B /> {'c'} </div>, ); if ( render === serverRender || render === clientRenderOnServerString || render === streamRender ) { // In the server render output there's a comment between them. expect(e.childNodes.length).toBe(5); expectTextNode(e.childNodes[0], 'a'); expectTextNode(e.childNodes[2], 'b'); expectTextNode(e.childNodes[4], 'c'); } else { expect(e.childNodes.length).toBe(3); expectTextNode(e.childNodes[0], 'a'); expectTextNode(e.childNodes[1], 'b'); expectTextNode(e.childNodes[2], 'c'); } }, ); itRenders('a tree with sibling host and text nodes', async render => { class X extends React.Component { render() { return [null, [<Y key="1" />], false]; } } function Y() { return [<Z key="1" />, ['c']]; } function Z() { return null; } const e = await render( <div> {[['a'], 'b']} <div> <X key="1" />d </div> e </div>, ); if ( render === serverRender || render === streamRender || render === clientRenderOnServerString ) { // In the server render output there's comments between text nodes. expect(e.childNodes.length).toBe(5); expectTextNode(e.childNodes[0], 'a'); expectTextNode(e.childNodes[2], 'b'); expect(e.childNodes[3].childNodes.length).toBe(3); expectTextNode(e.childNodes[3].childNodes[0], 'c'); expectTextNode(e.childNodes[3].childNodes[2], 'd'); expectTextNode(e.childNodes[4], 'e'); } else { expect(e.childNodes.length).toBe(4); expectTextNode(e.childNodes[0], 'a'); expectTextNode(e.childNodes[1], 'b'); expect(e.childNodes[2].childNodes.length).toBe(2); expectTextNode(e.childNodes[2].childNodes[0], 'c'); expectTextNode(e.childNodes[2].childNodes[1], 'd'); expectTextNode(e.childNodes[3], 'e'); } }); }); describe('number children', function () { itRenders('a number as single child', async render => { const e = await render(<div>{3}</div>); expect(e.textContent).toBe('3'); }); // zero is falsey, so it could look like no children if the code isn't careful. itRenders('zero as single child', async render => { const e = await render(<div>{0}</div>); expect(e.textContent).toBe('0'); }); itRenders('an element with number and text children', async render => { const e = await render( <div> {'foo'} {40} </div>, ); // with Fiber, there are just two text nodes. if ( render === serverRender || render === clientRenderOnServerString || render === streamRender ) { // In the server markup there's a comment between. expect(e.childNodes.length).toBe(3); expectTextNode(e.childNodes[0], 'foo'); expectTextNode(e.childNodes[2], '40'); } else { expect(e.childNodes.length).toBe(2); expectTextNode(e.childNodes[0], 'foo'); expectTextNode(e.childNodes[1], '40'); } }); }); describe('null, false, and undefined children', function () { itRenders('null single child as blank', async render => { const e = await render(<div>{null}</div>); expect(e.childNodes.length).toBe(0); }); itRenders('false single child as blank', async render => { const e = await render(<div>{false}</div>); expect(e.childNodes.length).toBe(0); }); itRenders('undefined single child as blank', async render => { const e = await render(<div>{undefined}</div>); expect(e.childNodes.length).toBe(0); }); itRenders('a null component children as empty', async render => { const NullComponent = () => null; const e = await render( <div> <NullComponent /> </div>, ); expect(e.childNodes.length).toBe(0); }); itRenders('null children as blank', async render => { const e = await render(<div>{null}foo</div>); expect(e.childNodes.length).toBe(1); expectTextNode(e.childNodes[0], 'foo'); }); itRenders('false children as blank', async render => { const e = await render(<div>{false}foo</div>); expect(e.childNodes.length).toBe(1); expectTextNode(e.childNodes[0], 'foo'); }); itRenders('null and false children together as blank', async render => { const e = await render( <div> {false} {null}foo{null} {false} </div>, ); expect(e.childNodes.length).toBe(1); expectTextNode(e.childNodes[0], 'foo'); }); itRenders('only null and false children as blank', async render => { const e = await render( <div> {false} {null} {null} {false} </div>, ); expect(e.childNodes.length).toBe(0); }); }); describe('elements with implicit namespaces', function () { itRenders('an svg element', async render => { const e = await render(<svg />); expect(e.childNodes.length).toBe(0); expect(e.tagName).toBe('svg'); expect(e.namespaceURI).toBe('http://www.w3.org/2000/svg'); }); itRenders('svg child element with an attribute', async render => { const e = await render(<svg viewBox="0 0 0 0" />); expect(e.childNodes.length).toBe(0); expect(e.tagName).toBe('svg'); expect(e.namespaceURI).toBe('http://www.w3.org/2000/svg'); expect(e.getAttribute('viewBox')).toBe('0 0 0 0'); }); itRenders( 'svg child element with a namespace attribute', async render => { let e = await render( <svg> <image xlinkHref="http://i.imgur.com/w7GCRPb.png" /> </svg>, ); e = e.firstChild; expect(e.childNodes.length).toBe(0); expect(e.tagName).toBe('image'); expect(e.namespaceURI).toBe('http://www.w3.org/2000/svg'); expect(e.getAttributeNS('http://www.w3.org/1999/xlink', 'href')).toBe( 'http://i.imgur.com/w7GCRPb.png', ); }, ); itRenders('svg child element with a badly cased alias', async render => { let e = await render( <svg> <image xlinkhref="http://i.imgur.com/w7GCRPb.png" /> </svg>, 1, ); e = e.firstChild; expect(e.hasAttributeNS('http://www.w3.org/1999/xlink', 'href')).toBe( false, ); expect(e.getAttribute('xlinkhref')).toBe( 'http://i.imgur.com/w7GCRPb.png', ); }); itRenders('svg element with a tabIndex attribute', async render => { const e = await render(<svg tabIndex="1" />); expect(e.tabIndex).toBe(1); }); itRenders( 'svg element with a badly cased tabIndex attribute', async render => { const e = await render(<svg tabindex="1" />, 1); expect(e.tabIndex).toBe(1); }, ); itRenders('svg element with a mixed case name', async render => { let e = await render( <svg> <filter> <feMorphology /> </filter> </svg>, ); e = e.firstChild.firstChild; expect(e.childNodes.length).toBe(0); expect(e.tagName).toBe('feMorphology'); expect(e.namespaceURI).toBe('http://www.w3.org/2000/svg'); }); itRenders('a math element', async render => { const e = await render(<math />); expect(e.childNodes.length).toBe(0); expect(e.tagName).toBe('math'); expect(e.namespaceURI).toBe('http://www.w3.org/1998/Math/MathML'); }); }); // specially wrapped components // (see the big switch near the beginning ofReactDOMComponent.mountComponent) itRenders('an img', async render => { const e = await render(<img />); expect(e.childNodes.length).toBe(0); expect(e.nextSibling).toBe(null); expect(e.tagName).toBe('IMG'); }); itRenders('a button', async render => { const e = await render(<button />); expect(e.childNodes.length).toBe(0); expect(e.nextSibling).toBe(null); expect(e.tagName).toBe('BUTTON'); }); itRenders('a div with dangerouslySetInnerHTML number', async render => { // Put dangerouslySetInnerHTML one level deeper because otherwise // hydrating from a bad markup would cause a mismatch (since we don't // patch dangerouslySetInnerHTML as text content). const e = ( await render( <div> <span dangerouslySetInnerHTML={{__html: 0}} /> </div>, ) ).firstChild; expect(e.childNodes.length).toBe(1); expect(e.firstChild.nodeType).toBe(TEXT_NODE_TYPE); expect(e.textContent).toBe('0'); }); itRenders('a div with dangerouslySetInnerHTML boolean', async render => { // Put dangerouslySetInnerHTML one level deeper because otherwise // hydrating from a bad markup would cause a mismatch (since we don't // patch dangerouslySetInnerHTML as text content). const e = ( await render( <div> <span dangerouslySetInnerHTML={{__html: false}} /> </div>, ) ).firstChild; expect(e.childNodes.length).toBe(1); expect(e.firstChild.nodeType).toBe(TEXT_NODE_TYPE); expect(e.firstChild.data).toBe('false'); }); itRenders( 'a div with dangerouslySetInnerHTML text string', async render => { // Put dangerouslySetInnerHTML one level deeper because otherwise // hydrating from a bad markup would cause a mismatch (since we don't // patch dangerouslySetInnerHTML as text content). const e = ( await render( <div> <span dangerouslySetInnerHTML={{__html: 'hello'}} /> </div>, ) ).firstChild; expect(e.childNodes.length).toBe(1); expect(e.firstChild.nodeType).toBe(TEXT_NODE_TYPE); expect(e.textContent).toBe('hello'); }, ); itRenders( 'a div with dangerouslySetInnerHTML element string', async render => { const e = await render( <div dangerouslySetInnerHTML={{__html: "<span id='child'/>"}} />, ); expect(e.childNodes.length).toBe(1); expect(e.firstChild.tagName).toBe('SPAN'); expect(e.firstChild.getAttribute('id')).toBe('child'); expect(e.firstChild.childNodes.length).toBe(0); }, ); itRenders('a div with dangerouslySetInnerHTML object', async render => { const obj = { toString() { return "<span id='child'/>"; }, }; const e = await render(<div dangerouslySetInnerHTML={{__html: obj}} />); expect(e.childNodes.length).toBe(1); expect(e.firstChild.tagName).toBe('SPAN'); expect(e.firstChild.getAttribute('id')).toBe('child'); expect(e.firstChild.childNodes.length).toBe(0); }); itRenders( 'a div with dangerouslySetInnerHTML set to null', async render => { const e = await render( <div dangerouslySetInnerHTML={{__html: null}} />, ); expect(e.childNodes.length).toBe(0); }, ); itRenders( 'a div with dangerouslySetInnerHTML set to undefined', async render => { const e = await render( <div dangerouslySetInnerHTML={{__html: undefined}} />, ); expect(e.childNodes.length).toBe(0); }, ); itRenders('a noscript with children', async render => { const e = await render( <noscript> <div>Enable JavaScript to run this app.</div> </noscript>, ); if (render === clientCleanRender) { // On the client we ignore the contents of a noscript expect(e.childNodes.length).toBe(0); } else { // On the server or when hydrating the content should be correct expect(e.childNodes.length).toBe(1); expect(e.firstChild.textContent).toBe( '<div>Enable JavaScript to run this app.</div>', ); } }); describe('newline-eating elements', function () { itRenders( 'a newline-eating tag with content not starting with \\n', async render => { const e = await render(<pre>Hello</pre>); expect(e.textContent).toBe('Hello'); }, ); itRenders( 'a newline-eating tag with content starting with \\n', async render => { const e = await render(<pre>{'\nHello'}</pre>); expect(e.textContent).toBe('\nHello'); }, ); itRenders('a normal tag with content starting with \\n', async render => { const e = await render(<div>{'\nHello'}</div>); expect(e.textContent).toBe('\nHello'); }); }); describe('different component implementations', function () { function checkFooDiv(e) { expect(e.childNodes.length).toBe(1); expectNode(e.firstChild, TEXT_NODE_TYPE, 'foo'); } itRenders('stateless components', async render => { const FunctionComponent = () => <div>foo</div>; checkFooDiv(await render(<FunctionComponent />)); }); itRenders('ES6 class components', async render => { class ClassComponent extends React.Component { render() { return <div>foo</div>; } } checkFooDiv(await render(<ClassComponent />)); }); if (require('shared/ReactFeatureFlags').disableModulePatternComponents) { itThrowsWhenRendering( 'factory components', async render => { const FactoryComponent = () => { return { render: function () { return <div>foo</div>; }, }; }; await render(<FactoryComponent />, 1); }, 'Objects are not valid as a React child (found: object with keys {render})', ); } else { itRenders('factory components', async render => { const FactoryComponent = () => { return { render: function () { return <div>foo</div>; }, }; }; checkFooDiv(await render(<FactoryComponent />, 1)); }); } }); describe('component hierarchies', function () { itRenders('single child hierarchies of components', async render => { const Component = props => <div>{props.children}</div>; let e = await render( <Component> <Component> <Component> <Component /> </Component> </Component> </Component>, ); for (let i = 0; i < 3; i++) { expect(e.tagName).toBe('DIV'); expect(e.childNodes.length).toBe(1); e = e.firstChild; } expect(e.tagName).toBe('DIV'); expect(e.childNodes.length).toBe(0); }); itRenders('multi-child hierarchies of components', async render => { const Component = props => <div>{props.children}</div>; const e = await render( <Component> <Component> <Component /> <Component /> </Component> <Component> <Component /> <Component /> </Component> </Component>, ); expect(e.tagName).toBe('DIV'); expect(e.childNodes.length).toBe(2); for (let i = 0; i < 2; i++) { const child = e.childNodes[i]; expect(child.tagName).toBe('DIV'); expect(child.childNodes.length).toBe(2); for (let j = 0; j < 2; j++) { const grandchild = child.childNodes[j]; expect(grandchild.tagName).toBe('DIV'); expect(grandchild.childNodes.length).toBe(0); } } }); itRenders('a div with a child', async render => { const e = await render( <div id="parent"> <div id="child" /> </div>, ); expect(e.id).toBe('parent'); expect(e.childNodes.length).toBe(1); expect(e.childNodes[0].id).toBe('child'); expect(e.childNodes[0].childNodes.length).toBe(0); }); itRenders('a div with multiple children', async render => { const e = await render( <div id="parent"> <div id="child1" /> <div id="child2" /> </div>, ); expect(e.id).toBe('parent'); expect(e.childNodes.length).toBe(2); expect(e.childNodes[0].id).toBe('child1'); expect(e.childNodes[0].childNodes.length).toBe(0); expect(e.childNodes[1].id).toBe('child2'); expect(e.childNodes[1].childNodes.length).toBe(0); }); itRenders( 'a div with multiple children separated by whitespace', async render => { const e = await render( <div id="parent"> <div id="child1" /> <div id="child2" /> </div>, ); expect(e.id).toBe('parent'); expect(e.childNodes.length).toBe(3); const child1 = e.childNodes[0]; const textNode = e.childNodes[1]; const child2 = e.childNodes[2]; expect(child1.id).toBe('child1'); expect(child1.childNodes.length).toBe(0); expectTextNode(textNode, ' '); expect(child2.id).toBe('child2'); expect(child2.childNodes.length).toBe(0); }, ); itRenders( 'a div with a single child surrounded by whitespace', async render => { // prettier-ignore const e = await render(<div id="parent"> <div id="child" /> </div>); // eslint-disable-line no-multi-spaces expect(e.childNodes.length).toBe(3); const textNode1 = e.childNodes[0]; const child = e.childNodes[1]; const textNode2 = e.childNodes[2]; expect(e.id).toBe('parent'); expectTextNode(textNode1, ' '); expect(child.id).toBe('child'); expect(child.childNodes.length).toBe(0); expectTextNode(textNode2, ' '); }, ); itRenders('a composite with multiple children', async render => { const Component = props => props.children; const e = await render( <Component>{['a', 'b', [undefined], [[false, 'c']]]}</Component>, ); const parent = e.parentNode; if ( render === serverRender || render === clientRenderOnServerString || render === streamRender ) { // For plain server markup result we have comments between. // If we're able to hydrate, they remain. expect(parent.childNodes.length).toBe(5); expectTextNode(parent.childNodes[0], 'a'); expectTextNode(parent.childNodes[2], 'b'); expectTextNode(parent.childNodes[4], 'c'); } else { expect(parent.childNodes.length).toBe(3); expectTextNode(parent.childNodes[0], 'a'); expectTextNode(parent.childNodes[1], 'b'); expectTextNode(parent.childNodes[2], 'c'); } }); }); describe('escaping >, <, and &', function () { itRenders('>,<, and & as single child', async render => { const e = await render(<div>{'<span>Text&quot;</span>'}</div>); expect(e.childNodes.length).toBe(1); expectNode(e.firstChild, TEXT_NODE_TYPE, '<span>Text&quot;</span>'); }); itRenders('>,<, and & as multiple children', async render => { const e = await render( <div> {'<span>Text1&quot;</span>'} {'<span>Text2&quot;</span>'} </div>, ); if ( render === serverRender || render === clientRenderOnServerString || render === streamRender ) { expect(e.childNodes.length).toBe(3); expectTextNode(e.childNodes[0], '<span>Text1&quot;</span>'); expectTextNode(e.childNodes[2], '<span>Text2&quot;</span>'); } else { expect(e.childNodes.length).toBe(2); expectTextNode(e.childNodes[0], '<span>Text1&quot;</span>'); expectTextNode(e.childNodes[1], '<span>Text2&quot;</span>'); } }); }); describe('carriage return and null character', () => { // HTML parsing normalizes CR and CRLF to LF. // It also ignores null character. // https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream // If we have a mismatch, it might be caused by that (and should not be reported). // We won't be patching up in this case as that matches our past behavior. itRenders( 'an element with one text child with special characters', async render => { const e = await render(<div>{'foo\rbar\r\nbaz\nqux\u0000'}</div>); if (render === serverRender || render === streamRender) { expect(e.childNodes.length).toBe(1); // Everything becomes LF when parsed from server HTML. // Null character is ignored. expectNode(e.childNodes[0], TEXT_NODE_TYPE, 'foo\nbar\nbaz\nqux'); } else { expect(e.childNodes.length).toBe(1); // Client rendering (or hydration) uses JS value with CR. // Null character stays. expectNode( e.childNodes[0], TEXT_NODE_TYPE, 'foo\rbar\r\nbaz\nqux\u0000', ); } }, ); itRenders( 'an element with two text children with special characters', async render => { const e = await render( <div> {'foo\rbar'} {'\r\nbaz\nqux\u0000'} </div>, ); if (render === serverRender || render === streamRender) { // We have three nodes because there is a comment between them. expect(e.childNodes.length).toBe(3); // Everything becomes LF when parsed from server HTML. // Null character is ignored. expectNode(e.childNodes[0], TEXT_NODE_TYPE, 'foo\nbar'); expectNode(e.childNodes[2], TEXT_NODE_TYPE, '\nbaz\nqux'); } else if (render === clientRenderOnServerString) { // We have three nodes because there is a comment between them. expect(e.childNodes.length).toBe(3); // Hydration uses JS value with CR and null character. expectNode(e.childNodes[0], TEXT_NODE_TYPE, 'foo\rbar'); expectNode(e.childNodes[2], TEXT_NODE_TYPE, '\r\nbaz\nqux\u0000'); } else { expect(e.childNodes.length).toBe(2); // Client rendering uses JS value with CR and null character. expectNode(e.childNodes[0], TEXT_NODE_TYPE, 'foo\rbar'); expectNode(e.childNodes[1], TEXT_NODE_TYPE, '\r\nbaz\nqux\u0000'); } }, ); itRenders( 'an element with an attribute value with special characters', async render => { const e = await render(<a title={'foo\rbar\r\nbaz\nqux\u0000'} />); if ( render === serverRender || render === streamRender || render === clientRenderOnServerString ) { // Everything becomes LF when parsed from server HTML. // Null character in an attribute becomes the replacement character. // Hydration also ends up with LF because we don't patch up attributes. expect(e.title).toBe('foo\nbar\nbaz\nqux\uFFFD'); } else { // Client rendering uses JS value with CR and null character. expect(e.title).toBe('foo\rbar\r\nbaz\nqux\u0000'); } }, ); }); describe('components that render nullish', function () { itRenders('a function returning null', async render => { const NullComponent = () => null; await render(<NullComponent />); }); itRenders('a class returning null', async render => { class NullComponent extends React.Component { render() { return null; } } await render(<NullComponent />); }); itRenders('a function returning undefined', async render => { const UndefinedComponent = () => undefined; await render(<UndefinedComponent />); }); itRenders('a class returning undefined', async render => { class UndefinedComponent extends React.Component { render() { return undefined; } } await render(<UndefinedComponent />); }); }); describe('components that throw errors', function () { itThrowsWhenRendering( 'a function returning an object', async render => { const ObjectComponent = () => ({x: 123}); await render(<ObjectComponent />, 1); }, 'Objects are not valid as a React child (found: object with keys {x}).' + (__DEV__ ? ' If you meant to render a collection of children, use ' + 'an array instead.' : ''), ); itThrowsWhenRendering( 'a class returning an object', async render => { class ObjectComponent extends React.Component { render() { return {x: 123}; } } await render(<ObjectComponent />, 1); }, 'Objects are not valid as a React child (found: object with keys {x}).' + (__DEV__ ? ' If you meant to render a collection of children, use ' + 'an array instead.' : ''), ); itThrowsWhenRendering( 'top-level object', async render => { await render({x: 123}); }, 'Objects are not valid as a React child (found: object with keys {x}).' + (__DEV__ ? ' If you meant to render a collection of children, use ' + 'an array instead.' : ''), ); }); describe('badly-typed elements', function () { itThrowsWhenRendering( 'object', async render => { let EmptyComponent = {}; expect(() => { EmptyComponent = <EmptyComponent />; }).toErrorDev( 'Warning: React.createElement: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: object. You likely forgot to export your ' + "component from the file it's defined in, or you might have mixed up " + 'default and named imports.', {withoutStack: true}, ); await render(EmptyComponent); }, 'Element type is invalid: expected a string (for built-in components) or a class/function ' + '(for composite components) but got: object.' + (__DEV__ ? " You likely forgot to export your component from the file it's defined in, " + 'or you might have mixed up default and named imports.' : ''), ); itThrowsWhenRendering( 'null', async render => { let NullComponent = null; expect(() => { NullComponent = <NullComponent />; }).toErrorDev( 'Warning: React.createElement: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: null.', {withoutStack: true}, ); await render(NullComponent); }, 'Element type is invalid: expected a string (for built-in components) or a class/function ' + '(for composite components) but got: null', ); itThrowsWhenRendering( 'undefined', async render => { let UndefinedComponent = undefined; expect(() => { UndefinedComponent = <UndefinedComponent />; }).toErrorDev( 'Warning: React.createElement: 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.', {withoutStack: true}, ); await render(UndefinedComponent); }, 'Element type is invalid: expected a string (for built-in components) or a class/function ' + '(for composite components) but got: undefined.' + (__DEV__ ? " You likely forgot to export your component from the file it's defined in, " + 'or you might have mixed up default and named imports.' : ''), ); }); }); });
33.498095
120
0.543841
Python-Penetration-Testing-Cookbook
/** * 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 */ const {useEffect} = require('react'); function useCustom() { useEffect(() => { // ... }, []); } module.exports = {useCustom};
17.888889
66
0.631268
owtf
require(['react', 'react-dom'], function (React, ReactDOM) { ReactDOM.render( React.createElement('h1', null, 'Hello World!'), document.getElementById('container') ); });
25.285714
60
0.655738
null
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/use-sync-external-store.production.min.js'); } else { module.exports = require('./cjs/use-sync-external-store.development.js'); }
27.375
78
0.690265
owtf
import Fixture from '../../Fixture'; const React = window.React; class RadioGroupFixture extends React.Component { constructor(props, context) { super(props, context); this.state = { changeCount: 0, }; } handleChange = () => { this.setState(({changeCount}) => { return { changeCount: changeCount + 1, }; }); }; handleReset = () => { this.setState({ changeCount: 0, }); }; render() { const {changeCount} = this.state; const color = changeCount >= 3 ? 'green' : 'red'; return ( <Fixture> <label> <input defaultChecked name="foo" type="radio" onChange={this.handleChange} /> Radio 1 </label> <label> <input name="foo" type="radio" onChange={this.handleChange} /> Radio 2 </label>{' '} <p style={{color}}> <code>onChange</code> {' calls: '} <strong>{changeCount}</strong> </p> <button onClick={this.handleReset}>Reset count</button> </Fixture> ); } } export default RadioGroupFixture;
19.293103
72
0.505952
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. * */ // Tweak these to play with different kinds of latency. // How long the data fetches on the server. exports.API_DELAY = 2000; // How long the server waits for data before giving up. exports.ABORT_DELAY = 10000; // How long serving the JS bundles is delayed. exports.JS_BUNDLE_DELAY = 4000;
24.736842
66
0.723361
Tricks-Web-Penetration-Tester
// @flow import shallowDiffers from './shallowDiffers'; // Custom comparison function for React.memo(). // It knows to compare individual style props and ignore the wrapper object. // See https://reactjs.org/docs/react-api.html#reactmemo export default function areEqual( prevProps: Object, nextProps: Object ): boolean { const { style: prevStyle, ...prevRest } = prevProps; const { style: nextStyle, ...nextRest } = nextProps; return ( !shallowDiffers(prevStyle, nextStyle) && !shallowDiffers(prevRest, nextRest) ); }
27.368421
80
0.72119
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 { __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, act as unstable_act, Children, Component, Fragment, Profiler, PureComponent, StrictMode, Suspense, cloneElement, createContext, createElement, createRef, use, forwardRef, isValidElement, lazy, memo, cache, startTransition, unstable_Cache, unstable_DebugTracingMode, unstable_LegacyHidden, unstable_Activity, unstable_Scope, unstable_SuspenseList, unstable_getCacheSignal, unstable_getCacheForType, unstable_useCacheRefresh, unstable_useMemoCache, useId, useCallback, useContext, useDebugValue, useDeferredValue, useEffect, experimental_useEffectEvent, useImperativeHandle, useInsertionEffect, useLayoutEffect, useMemo, useOptimistic, useReducer, useRef, useState, useSyncExternalStore, useTransition, version, } from './src/React'; export {jsx, jsxs, jsxDEV} from './src/jsx/ReactJSX';
17.819672
66
0.728858
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. */ // This is only used by bundle tests so they can *read* the default feature flags. // It lets us determine whether we're running in Fire mode without making tests internal. const ReactFeatureFlags = require('../ReactFeatureFlags'); // Forbid writes because this wouldn't work with bundle tests. module.exports = Object.freeze({...ReactFeatureFlags});
40.846154
89
0.747698
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'; 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, expectMarkupMismatch, expectMarkupMatch} = ReactDOMServerIntegrationUtils(initModules); describe('ReactDOMServerIntegration', () => { beforeEach(() => { resetModules(); }); describe('reconnecting to server markup', function () { let EmptyComponent; beforeEach(() => { EmptyComponent = class extends React.Component { render() { return null; } }; }); describe('elements', function () { describe('reconnecting different component implementations', function () { let ES6ClassComponent, PureComponent, bareElement; beforeEach(() => { // try each type of component on client and server. ES6ClassComponent = class extends React.Component { render() { return <div id={this.props.id} />; } }; PureComponent = props => <div id={props.id} />; bareElement = <div id="foobarbaz" />; }); it('should reconnect ES6 Class to ES6 Class', () => expectMarkupMatch( <ES6ClassComponent id="foobarbaz" />, <ES6ClassComponent id="foobarbaz" />, )); it('should reconnect Pure Component to ES6 Class', () => expectMarkupMatch( <ES6ClassComponent id="foobarbaz" />, <PureComponent id="foobarbaz" />, )); it('should reconnect Bare Element to ES6 Class', () => expectMarkupMatch(<ES6ClassComponent id="foobarbaz" />, bareElement)); it('should reconnect ES6 Class to Pure Component', () => expectMarkupMatch( <PureComponent id="foobarbaz" />, <ES6ClassComponent id="foobarbaz" />, )); it('should reconnect Pure Component to Pure Component', () => expectMarkupMatch( <PureComponent id="foobarbaz" />, <PureComponent id="foobarbaz" />, )); it('should reconnect Bare Element to Pure Component', () => expectMarkupMatch(<PureComponent id="foobarbaz" />, bareElement)); it('should reconnect ES6 Class to Bare Element', () => expectMarkupMatch(bareElement, <ES6ClassComponent id="foobarbaz" />)); it('should reconnect Pure Component to Bare Element', () => expectMarkupMatch(bareElement, <PureComponent id="foobarbaz" />)); it('should reconnect Bare Element to Bare Element', () => expectMarkupMatch(bareElement, bareElement)); }); it('should error reconnecting different element types', () => expectMarkupMismatch(<div />, <span />)); it('should error reconnecting fewer root children', () => expectMarkupMismatch(<span key="a" />, [ <span key="a" />, <span key="b" />, ])); it('should error reconnecting missing attributes', () => expectMarkupMismatch(<div id="foo" />, <div />)); it('should error reconnecting added attributes', () => expectMarkupMismatch(<div />, <div id="foo" />)); it('should error reconnecting different attribute values', () => expectMarkupMismatch(<div id="foo" />, <div id="bar" />)); it('can explicitly ignore errors reconnecting different element types of children', () => expectMarkupMatch( <div> <div /> </div>, <div suppressHydrationWarning={true}> <span /> </div>, )); it('can explicitly ignore errors reconnecting missing attributes', () => expectMarkupMatch( <div id="foo" />, <div suppressHydrationWarning={true} />, )); it('can explicitly ignore errors reconnecting added attributes', () => expectMarkupMatch( <div />, <div id="foo" suppressHydrationWarning={true} />, )); it('can explicitly ignore errors reconnecting different attribute values', () => expectMarkupMatch( <div id="foo" />, <div id="bar" suppressHydrationWarning={true} />, )); it('can not deeply ignore errors reconnecting different attribute values', () => expectMarkupMismatch( <div> <div id="foo" /> </div>, <div suppressHydrationWarning={true}> <div id="bar" /> </div>, )); }); describe('inline styles', function () { it('should error reconnecting missing style attribute', () => expectMarkupMismatch(<div style={{width: '1px'}} />, <div />)); it('should error reconnecting added style attribute', () => expectMarkupMismatch(<div />, <div style={{width: '1px'}} />)); it('should error reconnecting empty style attribute', () => expectMarkupMismatch( <div style={{width: '1px'}} />, <div style={{}} />, )); it('should error reconnecting added style values', () => expectMarkupMismatch( <div style={{}} />, <div style={{width: '1px'}} />, )); it('should error reconnecting different style values', () => expectMarkupMismatch( <div style={{width: '1px'}} />, <div style={{width: '2px'}} />, )); it('should reconnect number and string versions of a number', () => expectMarkupMatch( <div style={{width: '1px', height: 2}} />, <div style={{width: 1, height: '2px'}} />, )); it('should error reconnecting reordered style values', () => expectMarkupMismatch( <div style={{width: '1px', fontSize: '2px'}} />, <div style={{fontSize: '2px', width: '1px'}} />, )); it('can explicitly ignore errors reconnecting added style values', () => expectMarkupMatch( <div style={{}} />, <div style={{width: '1px'}} suppressHydrationWarning={true} />, )); it('can explicitly ignore reconnecting different style values', () => expectMarkupMatch( <div style={{width: '1px'}} />, <div style={{width: '2px'}} suppressHydrationWarning={true} />, )); }); describe('text nodes', function () { it('should error reconnecting different text', () => expectMarkupMismatch(<div>Text</div>, <div>Other Text</div>)); it('should reconnect a div with a number and string version of number', () => expectMarkupMatch(<div>{2}</div>, <div>2</div>)); it('should error reconnecting different numbers', () => expectMarkupMismatch(<div>{2}</div>, <div>{3}</div>)); it('should error reconnecting different number from text', () => expectMarkupMismatch(<div>{2}</div>, <div>3</div>)); it('should error reconnecting different text in two code blocks', () => expectMarkupMismatch( <div> {'Text1'} {'Text2'} </div>, <div> {'Text1'} {'Text3'} </div>, )); it('can explicitly ignore reconnecting different text', () => expectMarkupMatch( <div>Text</div>, <div suppressHydrationWarning={true}>Other Text</div>, )); it('can explicitly ignore reconnecting different text in two code blocks', () => expectMarkupMatch( <div suppressHydrationWarning={true}> {'Text1'} {'Text2'} </div>, <div suppressHydrationWarning={true}> {'Text1'} {'Text3'} </div>, )); }); describe('element trees and children', function () { it('should error reconnecting missing children', () => expectMarkupMismatch( <div> <div /> </div>, <div />, )); it('should error reconnecting added children', () => expectMarkupMismatch( <div />, <div> <div /> </div>, )); it('should error reconnecting more children', () => expectMarkupMismatch( <div> <div /> </div>, <div> <div /> <div /> </div>, )); it('should error reconnecting fewer children', () => expectMarkupMismatch( <div> <div /> <div /> </div>, <div> <div /> </div>, )); it('should error reconnecting reordered children', () => expectMarkupMismatch( <div> <div /> <span /> </div>, <div> <span /> <div /> </div>, )); it('should error reconnecting a div with children separated by whitespace on the client', () => expectMarkupMismatch( <div id="parent"> <div id="child1" /> <div id="child2" /> </div>, // prettier-ignore <div id="parent"><div id="child1" /> <div id="child2" /></div>, // eslint-disable-line no-multi-spaces )); it('should error reconnecting a div with children separated by different whitespace on the server', () => expectMarkupMismatch( // prettier-ignore <div id="parent"><div id="child1" /> <div id="child2" /></div>, // eslint-disable-line no-multi-spaces <div id="parent"> <div id="child1" /> <div id="child2" /> </div>, )); it('should error reconnecting a div with children separated by different whitespace', () => expectMarkupMismatch( <div id="parent"> <div id="child1" /> <div id="child2" /> </div>, // prettier-ignore <div id="parent"><div id="child1" /> <div id="child2" /></div>, // eslint-disable-line no-multi-spaces )); it('can distinguish an empty component from a dom node', () => expectMarkupMismatch( <div> <span /> </div>, <div> <EmptyComponent /> </div>, )); it('can distinguish an empty component from an empty text component', () => expectMarkupMatch( <div> <EmptyComponent /> </div>, <div>{''}</div>, )); it('can explicitly ignore reconnecting more children', () => expectMarkupMatch( <div> <div /> </div>, <div suppressHydrationWarning={true}> <div /> <div /> </div>, )); it('can explicitly ignore reconnecting fewer children', () => expectMarkupMatch( <div> <div /> <div /> </div>, <div suppressHydrationWarning={true}> <div /> </div>, )); it('can explicitly ignore reconnecting reordered children', () => expectMarkupMatch( <div suppressHydrationWarning={true}> <div /> <span /> </div>, <div suppressHydrationWarning={true}> <span /> <div /> </div>, )); it('can not deeply ignore reconnecting reordered children', () => expectMarkupMismatch( <div suppressHydrationWarning={true}> <div> <div /> <span /> </div> </div>, <div suppressHydrationWarning={true}> <div> <span /> <div /> </div> </div>, )); }); // Markup Mismatches: misc it('should error reconnecting a div with different dangerouslySetInnerHTML', () => expectMarkupMismatch( <div dangerouslySetInnerHTML={{__html: "<span id='child1'/>"}} />, <div dangerouslySetInnerHTML={{__html: "<span id='child2'/>"}} />, )); it('should error reconnecting a div with different text dangerouslySetInnerHTML', () => expectMarkupMismatch( <div dangerouslySetInnerHTML={{__html: 'foo'}} />, <div dangerouslySetInnerHTML={{__html: 'bar'}} />, )); it('should error reconnecting a div with different number dangerouslySetInnerHTML', () => expectMarkupMismatch( <div dangerouslySetInnerHTML={{__html: 10}} />, <div dangerouslySetInnerHTML={{__html: 20}} />, )); it('should error reconnecting a div with different object dangerouslySetInnerHTML', () => expectMarkupMismatch( <div dangerouslySetInnerHTML={{ __html: { toString() { return 'hi'; }, }, }} />, <div dangerouslySetInnerHTML={{ __html: { toString() { return 'bye'; }, }, }} />, )); it('can explicitly ignore reconnecting a div with different dangerouslySetInnerHTML', () => expectMarkupMatch( <div dangerouslySetInnerHTML={{__html: "<span id='child1'/>"}} />, <div dangerouslySetInnerHTML={{__html: "<span id='child2'/>"}} suppressHydrationWarning={true} />, )); }); });
29.568627
117
0.525445
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 useSyncExternalStore; let React; let ReactDOM; let ReactDOMServer; let Scheduler; let assertLog; // This tests the userspace shim of `useSyncExternalStore` in a server-rendering // (Node) environment describe('useSyncExternalStore (userspace shim, server rendering)', () => { beforeEach(() => { jest.resetModules(); // Remove useSyncExternalStore from the React imports so that we use the // shim instead. Also removing startTransition, since we use that to detect // outdated 18 alphas that don't yet include useSyncExternalStore. // // Longer term, we'll probably test this branch using an actual build of // React 17. jest.mock('react', () => { const { // eslint-disable-next-line no-unused-vars startTransition: _, // eslint-disable-next-line no-unused-vars useSyncExternalStore: __, ...otherExports } = jest.requireActual('react'); return otherExports; }); React = require('react'); ReactDOM = require('react-dom'); ReactDOMServer = require('react-dom/server'); Scheduler = require('scheduler'); const InternalTestUtils = require('internal-test-utils'); assertLog = InternalTestUtils.assertLog; useSyncExternalStore = require('use-sync-external-store/shim').useSyncExternalStore; }); function Text({text}) { Scheduler.log(text); return text; } function createExternalStore(initialState) { const listeners = new Set(); let currentState = initialState; return { set(text) { currentState = text; ReactDOM.unstable_batchedUpdates(() => { listeners.forEach(listener => listener()); }); }, subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); }, getState() { return currentState; }, getSubscriberCount() { return listeners.size; }, }; } test('basic server render', async () => { const store = createExternalStore('client'); function App() { const text = useSyncExternalStore( store.subscribe, store.getState, () => 'server', ); return <Text text={text} />; } const html = ReactDOMServer.renderToString(<App />); // We don't call getServerSnapshot in the shim assertLog(['client']); expect(html).toEqual('client'); }); });
25.067961
80
0.632265
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 {compareVersions} from 'compare-versions'; import {dehydrate} from '../hydration'; import isArray from 'shared/isArray'; import type {DehydratedData} from 'react-devtools-shared/src/frontend/types'; // TODO: update this to the first React version that has a corresponding DevTools backend const FIRST_DEVTOOLS_BACKEND_LOCKSTEP_VER = '999.9.9'; export function hasAssignedBackend(version?: string): boolean { if (version == null || version === '') { return false; } return gte(version, FIRST_DEVTOOLS_BACKEND_LOCKSTEP_VER); } export function cleanForBridge( data: Object | null, isPathAllowed: (path: Array<string | number>) => boolean, path: Array<string | number> = [], ): DehydratedData | null { if (data !== null) { const cleanedPaths: Array<Array<string | number>> = []; const unserializablePaths: Array<Array<string | number>> = []; const cleanedData = dehydrate( data, cleanedPaths, unserializablePaths, path, isPathAllowed, ); return { data: cleanedData, cleaned: cleanedPaths, unserializable: unserializablePaths, }; } else { return null; } } export function copyWithDelete( obj: Object | Array<any>, path: Array<string | number>, index: number = 0, ): Object | Array<any> { const key = path[index]; const updated = isArray(obj) ? obj.slice() : {...obj}; if (index + 1 === path.length) { if (isArray(updated)) { updated.splice(((key: any): number), 1); } else { delete updated[key]; } } else { // $FlowFixMe[incompatible-use] number or string is fine here updated[key] = copyWithDelete(obj[key], path, index + 1); } return updated; } // This function expects paths to be the same except for the final value. // e.g. ['path', 'to', 'foo'] and ['path', 'to', 'bar'] export function copyWithRename( obj: Object | Array<any>, oldPath: Array<string | number>, newPath: Array<string | number>, index: number = 0, ): Object | Array<any> { const oldKey = oldPath[index]; const updated = isArray(obj) ? obj.slice() : {...obj}; if (index + 1 === oldPath.length) { const newKey = newPath[index]; // $FlowFixMe[incompatible-use] number or string is fine here updated[newKey] = updated[oldKey]; if (isArray(updated)) { updated.splice(((oldKey: any): number), 1); } else { delete updated[oldKey]; } } else { // $FlowFixMe[incompatible-use] number or string is fine here updated[oldKey] = copyWithRename(obj[oldKey], oldPath, newPath, index + 1); } return updated; } export function copyWithSet( obj: Object | Array<any>, path: Array<string | number>, value: any, index: number = 0, ): Object | Array<any> { if (index >= path.length) { return value; } const key = path[index]; const updated = isArray(obj) ? obj.slice() : {...obj}; // $FlowFixMe[incompatible-use] number or string is fine here updated[key] = copyWithSet(obj[key], path, value, index + 1); return updated; } export function getEffectDurations(root: Object): { effectDuration: any | null, passiveEffectDuration: any | null, } { // Profiling durations are only available for certain builds. // If available, they'll be stored on the HostRoot. let effectDuration = null; let passiveEffectDuration = null; const hostRoot = root.current; if (hostRoot != null) { const stateNode = hostRoot.stateNode; if (stateNode != null) { effectDuration = stateNode.effectDuration != null ? stateNode.effectDuration : null; passiveEffectDuration = stateNode.passiveEffectDuration != null ? stateNode.passiveEffectDuration : null; } } return {effectDuration, passiveEffectDuration}; } export function serializeToString(data: any): string { if (data === undefined) { return 'undefined'; } const cache = new Set<mixed>(); // Use a custom replacer function to protect against circular references. return JSON.stringify( data, (key, value) => { if (typeof value === 'object' && value !== null) { if (cache.has(value)) { return; } cache.add(value); } if (typeof value === 'bigint') { return value.toString() + 'n'; } return value; }, 2, ); } // Formats an array of args with a style for console methods, using // the following algorithm: // 1. The first param is a string that contains %c // - Bail out and return the args without modifying the styles. // We don't want to affect styles that the developer deliberately set. // 2. The first param is a string that doesn't contain %c but contains // string formatting // - [`%c${args[0]}`, style, ...args.slice(1)] // - Note: we assume that the string formatting that the developer uses // is correct. // 3. The first param is a string that doesn't contain string formatting // OR is not a string // - Create a formatting string where: // boolean, string, symbol -> %s // number -> %f OR %i depending on if it's an int or float // default -> %o export 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]; } } // based on https://github.com/tmpfs/format-util/blob/0e62d430efb0a1c51448709abd3e2406c14d8401/format.js#L1 // based on https://developer.mozilla.org/en-US/docs/Web/API/console#Using_string_substitutions // Implements s, d, i and f placeholders // NOTE: KEEP IN SYNC with src/hook.js export function format( maybeMessage: any, ...inputArgs: $ReadOnlyArray<any> ): string { const args = inputArgs.slice(); let formatted: string = String(maybeMessage); // If the first argument is a string, check for substitutions. if (typeof maybeMessage === 'string') { if (args.length) { const REGEXP = /(%?)(%([jds]))/g; formatted = formatted.replace(REGEXP, (match, escaped, ptn, flag) => { let arg = args.shift(); switch (flag) { case 's': arg += ''; break; case 'd': case 'i': arg = parseInt(arg, 10).toString(); break; case 'f': arg = parseFloat(arg).toString(); break; } if (!escaped) { return arg; } args.unshift(arg); return match; }); } } // Arguments that remain after formatting. if (args.length) { for (let i = 0; i < args.length; i++) { formatted += ' ' + String(args[i]); } } // Update escaped %% values. formatted = formatted.replace(/%{2,2}/g, '%'); return String(formatted); } export function isSynchronousXHRSupported(): boolean { return !!( window.document && window.document.featurePolicy && window.document.featurePolicy.allowsFeature('sync-xhr') ); } export function gt(a: string = '', b: string = ''): boolean { return compareVersions(a, b) === 1; } export function gte(a: string = '', b: string = ''): boolean { return compareVersions(a, b) > -1; } export const isReactNativeEnvironment = (): boolean => { // We've been relying on this for such a long time // We should probably define the client for DevTools on the backend side and share it with the frontend return window.document == null; };
28.609589
107
0.610642
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 */ /*jslint evil: true */ 'use strict'; import * as React from 'react'; import * as ReactART from 'react-art'; import ARTSVGMode from 'art/modes/svg'; import ARTCurrentMode from 'art/modes/current'; // Since these are default exports, we need to import them using ESM. // Since they must be on top, we need to import this before ReactDOM. import Circle from 'react-art/Circle'; import Rectangle from 'react-art/Rectangle'; import Wedge from 'react-art/Wedge'; // Isolate DOM renderer. jest.resetModules(); const ReactDOM = require('react-dom'); const ReactTestUtils = require('react-dom/test-utils'); // Isolate test renderer. jest.resetModules(); const ReactTestRenderer = require('react-test-renderer'); // Isolate the noop renderer jest.resetModules(); const ReactNoop = require('react-noop-renderer'); const Scheduler = require('scheduler'); let Group; let Shape; let Surface; let TestComponent; let waitFor; const Missing = {}; function testDOMNodeStructure(domNode, expectedStructure) { expect(domNode).toBeDefined(); expect(domNode.nodeName).toBe(expectedStructure.nodeName); for (const prop in expectedStructure) { if (!expectedStructure.hasOwnProperty(prop)) { continue; } if (prop !== 'nodeName' && prop !== 'children') { if (expectedStructure[prop] === Missing) { expect(domNode.hasAttribute(prop)).toBe(false); } else { expect(domNode.getAttribute(prop)).toBe(expectedStructure[prop]); } } } if (expectedStructure.children) { expectedStructure.children.forEach(function (subTree, index) { testDOMNodeStructure(domNode.childNodes[index], subTree); }); } } describe('ReactART', () => { let container; beforeEach(() => { container = document.createElement('div'); document.body.appendChild(container); ARTCurrentMode.setCurrent(ARTSVGMode); Group = ReactART.Group; Shape = ReactART.Shape; Surface = ReactART.Surface; ({waitFor} = require('internal-test-utils')); TestComponent = class extends React.Component { group = React.createRef(); render() { const a = ( <Shape d="M0,0l50,0l0,50l-50,0z" fill={new ReactART.LinearGradient(['black', 'white'])} key="a" width={50} height={50} x={50} y={50} opacity={0.1} /> ); const b = ( <Shape fill="#3C5A99" key="b" scale={0.5} x={50} y={50} title="This is an F" cursor="pointer"> M64.564,38.583H54l0.008-5.834c0-3.035,0.293-4.666,4.657-4.666 h5.833V16.429h-9.33c-11.213,0-15.159,5.654-15.159,15.16v6.994 h-6.99v11.652h6.99v33.815H54V50.235h9.331L64.564,38.583z </Shape> ); const c = <Group key="c" />; return ( <Surface width={150} height={200}> <Group ref={this.group}> {this.props.flipped ? [b, a, c] : [a, b, c]} </Group> </Surface> ); } }; }); afterEach(() => { document.body.removeChild(container); container = null; }); it('should have the correct lifecycle state', () => { let instance = <TestComponent />; instance = ReactTestUtils.renderIntoDocument(instance); const group = instance.group.current; // Duck type test for an ART group expect(typeof group.indicate).toBe('function'); }); it('should render a reasonable SVG structure in SVG mode', () => { let instance = <TestComponent />; instance = ReactTestUtils.renderIntoDocument(instance); const expectedStructure = { nodeName: 'svg', width: '150', height: '200', children: [ {nodeName: 'defs'}, { nodeName: 'g', children: [ { nodeName: 'defs', children: [{nodeName: 'linearGradient'}], }, {nodeName: 'path'}, {nodeName: 'path'}, {nodeName: 'g'}, ], }, ], }; const realNode = ReactDOM.findDOMNode(instance); testDOMNodeStructure(realNode, expectedStructure); }); it('should be able to reorder components', () => { const instance = ReactDOM.render( <TestComponent flipped={false} />, container, ); const expectedStructure = { nodeName: 'svg', children: [ {nodeName: 'defs'}, { nodeName: 'g', children: [ {nodeName: 'defs'}, {nodeName: 'path', opacity: '0.1'}, {nodeName: 'path', opacity: Missing}, {nodeName: 'g'}, ], }, ], }; const realNode = ReactDOM.findDOMNode(instance); testDOMNodeStructure(realNode, expectedStructure); ReactDOM.render(<TestComponent flipped={true} />, container); const expectedNewStructure = { nodeName: 'svg', children: [ {nodeName: 'defs'}, { nodeName: 'g', children: [ {nodeName: 'defs'}, {nodeName: 'path', opacity: Missing}, {nodeName: 'path', opacity: '0.1'}, {nodeName: 'g'}, ], }, ], }; testDOMNodeStructure(realNode, expectedNewStructure); }); it('should be able to reorder many components', () => { class Component extends React.Component { render() { const chars = this.props.chars.split(''); return ( <Surface> {chars.map(text => ( <Shape key={text} title={text} /> ))} </Surface> ); } } // Mini multi-child stress test: lots of reorders, some adds, some removes. const before = 'abcdefghijklmnopqrst'; const after = 'mxhpgwfralkeoivcstzy'; let instance = ReactDOM.render(<Component chars={before} />, container); const realNode = ReactDOM.findDOMNode(instance); expect(realNode.textContent).toBe(before); instance = ReactDOM.render(<Component chars={after} />, container); expect(realNode.textContent).toBe(after); ReactDOM.unmountComponentAtNode(container); }); it('renders composite with lifecycle inside group', () => { let mounted = false; class CustomShape extends React.Component { render() { return <Shape />; } componentDidMount() { mounted = true; } } ReactTestUtils.renderIntoDocument( <Surface> <Group> <CustomShape /> </Group> </Surface>, ); expect(mounted).toBe(true); }); it('resolves refs before componentDidMount', () => { class CustomShape extends React.Component { render() { return <Shape />; } } let ref = null; class Outer extends React.Component { test = React.createRef(); componentDidMount() { ref = this.test.current; } render() { return ( <Surface> <Group> <CustomShape ref={this.test} /> </Group> </Surface> ); } } ReactTestUtils.renderIntoDocument(<Outer />); expect(ref.constructor).toBe(CustomShape); }); it('resolves refs before componentDidUpdate', () => { class CustomShape extends React.Component { render() { return <Shape />; } } let ref = {}; class Outer extends React.Component { test = React.createRef(); componentDidMount() { ref = this.test.current; } componentDidUpdate() { ref = this.test.current; } render() { return ( <Surface> <Group> {this.props.mountCustomShape && <CustomShape ref={this.test} />} </Group> </Surface> ); } } ReactDOM.render(<Outer />, container); expect(ref).toBe(null); ReactDOM.render(<Outer mountCustomShape={true} />, container); expect(ref.constructor).toBe(CustomShape); }); it('adds and updates event handlers', () => { function render(onClick) { return ReactDOM.render( <Surface> <Shape onClick={onClick} /> </Surface>, container, ); } function doClick(instance) { const path = ReactDOM.findDOMNode(instance).querySelector('path'); path.dispatchEvent( new MouseEvent('click', { bubbles: true, }), ); } const onClick1 = jest.fn(); let instance = render(onClick1); doClick(instance); expect(onClick1).toBeCalled(); const onClick2 = jest.fn(); instance = render(onClick2); doClick(instance); expect(onClick2).toBeCalled(); }); // @gate forceConcurrentByDefaultForTesting it('can concurrently render with a "primary" renderer while sharing context', async () => { const CurrentRendererContext = React.createContext(null); function Yield(props) { Scheduler.log(props.value); return null; } let ops = []; function LogCurrentRenderer() { return ( <CurrentRendererContext.Consumer> {currentRenderer => { ops.push(currentRenderer); return null; }} </CurrentRendererContext.Consumer> ); } // Using test renderer instead of the DOM renderer here because async // testing APIs for the DOM renderer don't exist. ReactNoop.render( <CurrentRendererContext.Provider value="Test"> <Yield value="A" /> <Yield value="B" /> <LogCurrentRenderer /> <Yield value="C" /> </CurrentRendererContext.Provider>, ); await waitFor(['A']); ReactDOM.render( <Surface> <LogCurrentRenderer /> <CurrentRendererContext.Provider value="ART"> <LogCurrentRenderer /> </CurrentRendererContext.Provider> </Surface>, container, ); expect(ops).toEqual([null, 'ART']); ops = []; await waitFor(['B', 'C']); expect(ops).toEqual(['Test']); }); }); describe('ReactARTComponents', () => { it('should generate a <Shape> with props for drawing the Circle', () => { const circle = ReactTestRenderer.create( <Circle radius={10} stroke="green" strokeWidth={3} fill="blue" />, ); expect(circle.toJSON()).toMatchSnapshot(); }); it('should warn if radius is missing on a Circle component', () => { expect(() => ReactTestRenderer.create( <Circle stroke="green" strokeWidth={3} fill="blue" />, ), ).toErrorDev( 'Warning: Failed prop type: The prop `radius` is marked as required in `Circle`, ' + 'but its value is `undefined`.' + '\n in Circle (at **)', ); }); it('should generate a <Shape> with props for drawing the Rectangle', () => { const rectangle = ReactTestRenderer.create( <Rectangle width={50} height={50} stroke="green" fill="blue" />, ); expect(rectangle.toJSON()).toMatchSnapshot(); }); it('should generate a <Shape> with positive width when width prop is negative', () => { const rectangle = ReactTestRenderer.create( <Rectangle width={-50} height={50} />, ); expect(rectangle.toJSON()).toMatchSnapshot(); }); it('should generate a <Shape> with positive height when height prop is negative', () => { const rectangle = ReactTestRenderer.create( <Rectangle height={-50} width={50} />, ); expect(rectangle.toJSON()).toMatchSnapshot(); }); it('should generate a <Shape> with a radius property of 0 when top left radius prop is negative', () => { const rectangle = ReactTestRenderer.create( <Rectangle radiusTopLeft={-25} width={50} height={50} />, ); expect(rectangle.toJSON()).toMatchSnapshot(); }); it('should generate a <Shape> with a radius property of 0 when top right radius prop is negative', () => { const rectangle = ReactTestRenderer.create( <Rectangle radiusTopRight={-25} width={50} height={50} />, ); expect(rectangle.toJSON()).toMatchSnapshot(); }); it('should generate a <Shape> with a radius property of 0 when bottom right radius prop is negative', () => { const rectangle = ReactTestRenderer.create( <Rectangle radiusBottomRight={-30} width={50} height={50} />, ); expect(rectangle.toJSON()).toMatchSnapshot(); }); it('should generate a <Shape> with a radius property of 0 when bottom left radius prop is negative', () => { const rectangle = ReactTestRenderer.create( <Rectangle radiusBottomLeft={-25} width={50} height={50} />, ); expect(rectangle.toJSON()).toMatchSnapshot(); }); it('should generate a <Shape> where top radius is 0 if the sum of the top radius is greater than width', () => { const rectangle = ReactTestRenderer.create( <Rectangle radiusTopRight={25} radiusTopLeft={26} width={50} height={40} />, ); expect(rectangle.toJSON()).toMatchSnapshot(); }); it('should warn if width/height is missing on a Rectangle component', () => { expect(() => ReactTestRenderer.create(<Rectangle stroke="green" fill="blue" />), ).toErrorDev([ 'Warning: Failed prop type: The prop `width` is marked as required in `Rectangle`, ' + 'but its value is `undefined`.' + '\n in Rectangle (at **)', 'Warning: Failed prop type: The prop `height` is marked as required in `Rectangle`, ' + 'but its value is `undefined`.' + '\n in Rectangle (at **)', ]); }); it('should generate a <Shape> with props for drawing the Wedge', () => { const wedge = ReactTestRenderer.create( <Wedge outerRadius={50} startAngle={0} endAngle={360} fill="blue" />, ); expect(wedge.toJSON()).toMatchSnapshot(); }); it('should return null if startAngle equals to endAngle on Wedge', () => { const wedge = ReactTestRenderer.create( <Wedge outerRadius={50} startAngle={0} endAngle={0} fill="blue" />, ); expect(wedge.toJSON()).toBeNull(); }); it('should warn if outerRadius/startAngle/endAngle is missing on a Wedge component', () => { expect(() => ReactTestRenderer.create(<Wedge fill="blue" />)).toErrorDev([ 'Warning: Failed prop type: The prop `outerRadius` is marked as required in `Wedge`, ' + 'but its value is `undefined`.' + '\n in Wedge (at **)', 'Warning: Failed prop type: The prop `startAngle` is marked as required in `Wedge`, ' + 'but its value is `undefined`.' + '\n in Wedge (at **)', 'Warning: Failed prop type: The prop `endAngle` is marked as required in `Wedge`, ' + 'but its value is `undefined`.' + '\n in Wedge (at **)', ]); }); });
26.765683
114
0.584264
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 */ // This is a host config that's used for the `react-server` package on npm. // It is only used by third-party renderers. // // Its API lets you pass the host config as an argument. // However, inside the `react-server` we treat host config as a module. // This file is a shim between two worlds. // // It works because the `react-server` bundle is wrapped in something like: // // module.exports = function ($$$config) { // /* renderer code */ // } // // So `$$$config` looks like a global variable, but it's // really an argument to a top-level wrapping function. import type {Request} from 'react-server/src/ReactFizzServer'; import type {TransitionStatus} from 'react-reconciler/src/ReactFiberConfig'; declare var $$$config: any; export opaque type Destination = mixed; // eslint-disable-line no-undef export opaque type RenderState = mixed; export opaque type ResumableState = mixed; export opaque type BoundaryResources = mixed; export opaque type FormatContext = mixed; export opaque type HeadersDescriptor = mixed; export type {TransitionStatus}; export const isPrimaryRenderer = false; export const supportsRequestStorage = false; export const requestStorage: AsyncLocalStorage<Request> = (null: any); export const resetResumableState = $$$config.resetResumableState; export const completeResumableState = $$$config.completeResumableState; export const getChildFormatContext = $$$config.getChildFormatContext; export const makeId = $$$config.makeId; export const pushTextInstance = $$$config.pushTextInstance; export const pushStartInstance = $$$config.pushStartInstance; export const pushEndInstance = $$$config.pushEndInstance; export const pushStartCompletedSuspenseBoundary = $$$config.pushStartCompletedSuspenseBoundary; export const pushEndCompletedSuspenseBoundary = $$$config.pushEndCompletedSuspenseBoundary; export const pushSegmentFinale = $$$config.pushSegmentFinale; export const pushFormStateMarkerIsMatching = $$$config.pushFormStateMarkerIsMatching; export const pushFormStateMarkerIsNotMatching = $$$config.pushFormStateMarkerIsNotMatching; export const writeCompletedRoot = $$$config.writeCompletedRoot; export const writePlaceholder = $$$config.writePlaceholder; export const writeStartCompletedSuspenseBoundary = $$$config.writeStartCompletedSuspenseBoundary; export const writeStartPendingSuspenseBoundary = $$$config.writeStartPendingSuspenseBoundary; export const writeStartClientRenderedSuspenseBoundary = $$$config.writeStartClientRenderedSuspenseBoundary; export const writeEndCompletedSuspenseBoundary = $$$config.writeEndCompletedSuspenseBoundary; export const writeEndPendingSuspenseBoundary = $$$config.writeEndPendingSuspenseBoundary; export const writeEndClientRenderedSuspenseBoundary = $$$config.writeEndClientRenderedSuspenseBoundary; export const writeStartSegment = $$$config.writeStartSegment; export const writeEndSegment = $$$config.writeEndSegment; export const writeCompletedSegmentInstruction = $$$config.writeCompletedSegmentInstruction; export const writeCompletedBoundaryInstruction = $$$config.writeCompletedBoundaryInstruction; export const writeClientRenderBoundaryInstruction = $$$config.writeClientRenderBoundaryInstruction; export const prepareHostDispatcher = $$$config.prepareHostDispatcher; export const NotPendingTransition = $$$config.NotPendingTransition; // ------------------------- // Resources // ------------------------- export const writePreamble = $$$config.writePreamble; export const writeHoistables = $$$config.writeHoistables; export const writePostamble = $$$config.writePostamble; export const hoistResources = $$$config.hoistResources; export const createResources = $$$config.createResources; export const createBoundaryResources = $$$config.createBoundaryResources; export const setCurrentlyRenderingBoundaryResourcesTarget = $$$config.setCurrentlyRenderingBoundaryResourcesTarget; export const writeResourcesForBoundary = $$$config.writeResourcesForBoundary; export const emitEarlyPreloads = $$$config.emitEarlyPreloads;
42.814433
77
0.797364
Python-Penetration-Testing-for-Developers
let React; let ReactNoop; let Scheduler; let act; let Suspense; let useEffect; let getCacheForType; let caches; let seededCache; let assertLog; describe('ReactSuspenseWithNoopRenderer', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); act = require('internal-test-utils').act; Suspense = React.Suspense; useEffect = React.useEffect; getCacheForType = React.unstable_getCacheForType; const InternalTestUtils = require('internal-test-utils'); assertLog = InternalTestUtils.assertLog; caches = []; seededCache = null; }); function createTextCache() { if (seededCache !== null) { // Trick to seed a cache before it exists. // TODO: Need a built-in API to seed data before the initial render (i.e. // not a refresh because nothing has mounted yet). const cache = seededCache; seededCache = null; return cache; } const data = new Map(); const version = caches.length + 1; const cache = { version, data, resolve(text) { const record = data.get(text); if (record === undefined) { const newRecord = { status: 'resolved', value: text, }; data.set(text, newRecord); } else if (record.status === 'pending') { const thenable = record.value; record.status = 'resolved'; record.value = text; thenable.pings.forEach(t => t()); } }, reject(text, error) { const record = data.get(text); if (record === undefined) { const newRecord = { status: 'rejected', value: error, }; data.set(text, newRecord); } else if (record.status === 'pending') { const thenable = record.value; record.status = 'rejected'; record.value = error; thenable.pings.forEach(t => t()); } }, }; caches.push(cache); return cache; } function readText(text) { const textCache = getCacheForType(createTextCache); const record = textCache.data.get(text); if (record !== undefined) { switch (record.status) { case 'pending': Scheduler.log(`Suspend! [${text}]`); throw record.value; case 'rejected': Scheduler.log(`Error! [${text}]`); throw record.value; case 'resolved': return textCache.version; } } 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.data.set(text, newRecord); throw thenable; } } function resolveMostRecentTextCache(text) { if (caches.length === 0) { throw Error('Cache does not exist.'); } else { // Resolve the most recently created cache. An older cache can by // resolved with `caches[index].resolve(text)`. caches[caches.length - 1].resolve(text); } } const resolveText = resolveMostRecentTextCache; // @gate experimental || www it('regression: false positive for legacy suspense', async () => { // Wrapping in memo because regular function components go through the // mountIndeterminateComponent path, which acts like there's no `current` // fiber even though there is. `memo` is not indeterminate, so it goes // through the update path. const Child = React.memo(({text}) => { // If text hasn't resolved, this will throw and exit before the passive // static effect flag is added by the useEffect call below. readText(text); useEffect(() => { Scheduler.log('Effect'); }, []); Scheduler.log(text); return text; }); function App() { return ( <Suspense fallback="Loading..."> <Child text="Async" /> </Suspense> ); } const root = ReactNoop.createLegacyRoot(null); // On initial mount, the suspended component is committed in an incomplete // state, without a passive static effect flag. await act(() => { root.render(<App />); }); assertLog(['Suspend! [Async]']); expect(root).toMatchRenderedOutput('Loading...'); // When the promise resolves, a passive static effect flag is added. In the // regression, the "missing expected static flag" would fire, because the // previous fiber did not have one. await act(() => { resolveText('Async'); }); assertLog(['Async', 'Effect']); expect(root).toMatchRenderedOutput('Async'); }); });
26.577778
79
0.578884
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = _interopRequireDefault(require("react")); var _useTheme = _interopRequireDefault(require("./useTheme")); var _jsxFileName = ""; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function Component() { const theme = (0, _useTheme.default)(); return /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 16, columnNumber: 10 } }, "theme: ", theme); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhFeHRlcm5hbEN1c3RvbUhvb2tzLmpzIl0sIm5hbWVzIjpbIkNvbXBvbmVudCIsInRoZW1lIl0sIm1hcHBpbmdzIjoiOzs7Ozs7O0FBU0E7O0FBQ0E7Ozs7OztBQUVPLFNBQVNBLFNBQVQsR0FBcUI7QUFDMUIsUUFBTUMsS0FBSyxHQUFHLHdCQUFkO0FBRUEsc0JBQU87QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsZ0JBQWFBLEtBQWIsQ0FBUDtBQUNEIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBDb3B5cmlnaHQgKGMpIEZhY2Vib29rLCBJbmMuIGFuZCBpdHMgYWZmaWxpYXRlcy5cbiAqXG4gKiBUaGlzIHNvdXJjZSBjb2RlIGlzIGxpY2Vuc2VkIHVuZGVyIHRoZSBNSVQgbGljZW5zZSBmb3VuZCBpbiB0aGVcbiAqIExJQ0VOU0UgZmlsZSBpbiB0aGUgcm9vdCBkaXJlY3Rvcnkgb2YgdGhpcyBzb3VyY2UgdHJlZS5cbiAqXG4gKiBAZmxvd1xuICovXG5cbmltcG9ydCBSZWFjdCBmcm9tICdyZWFjdCc7XG5pbXBvcnQgdXNlVGhlbWUgZnJvbSAnLi91c2VUaGVtZSc7XG5cbmV4cG9ydCBmdW5jdGlvbiBDb21wb25lbnQoKSB7XG4gIGNvbnN0IHRoZW1lID0gdXNlVGhlbWUoKTtcblxuICByZXR1cm4gPGRpdj50aGVtZToge3RoZW1lfTwvZGl2Pjtcbn1cbiJdLCJ4X2ZhY2Vib29rX3NvdXJjZXMiOltbbnVsbCxbeyJuYW1lcyI6WyI8bm8taG9vaz4iLCJ0aGVtZSJdLCJtYXBwaW5ncyI6IkNBQUQ7Y2dCQ0EsQVVEQSJ9XV1dfX1dfQ==
65.846154
1,136
0.868739
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'; let Scheduler; let runWithPriority; let ImmediatePriority; let UserBlockingPriority; let NormalPriority; let LowPriority; let IdlePriority; let scheduleCallback; let cancelCallback; let wrapCallback; let getCurrentPriorityLevel; let shouldYield; let waitForAll; let assertLog; let waitFor; let waitForPaint; describe('Scheduler', () => { beforeEach(() => { jest.resetModules(); jest.mock('scheduler', () => require('scheduler/unstable_mock')); Scheduler = require('scheduler'); runWithPriority = Scheduler.unstable_runWithPriority; ImmediatePriority = Scheduler.unstable_ImmediatePriority; UserBlockingPriority = Scheduler.unstable_UserBlockingPriority; NormalPriority = Scheduler.unstable_NormalPriority; LowPriority = Scheduler.unstable_LowPriority; IdlePriority = Scheduler.unstable_IdlePriority; scheduleCallback = Scheduler.unstable_scheduleCallback; cancelCallback = Scheduler.unstable_cancelCallback; wrapCallback = Scheduler.unstable_wrapCallback; getCurrentPriorityLevel = Scheduler.unstable_getCurrentPriorityLevel; shouldYield = Scheduler.unstable_shouldYield; const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; assertLog = InternalTestUtils.assertLog; waitFor = InternalTestUtils.waitFor; waitForPaint = InternalTestUtils.waitForPaint; }); it('flushes work incrementally', async () => { scheduleCallback(NormalPriority, () => Scheduler.log('A')); scheduleCallback(NormalPriority, () => Scheduler.log('B')); scheduleCallback(NormalPriority, () => Scheduler.log('C')); scheduleCallback(NormalPriority, () => Scheduler.log('D')); await waitFor(['A', 'B']); await waitFor(['C']); await waitForAll(['D']); }); it('cancels work', async () => { scheduleCallback(NormalPriority, () => Scheduler.log('A')); const callbackHandleB = scheduleCallback(NormalPriority, () => Scheduler.log('B'), ); scheduleCallback(NormalPriority, () => Scheduler.log('C')); cancelCallback(callbackHandleB); await waitForAll([ 'A', // B should have been cancelled 'C', ]); }); it('executes the highest priority callbacks first', async () => { scheduleCallback(NormalPriority, () => Scheduler.log('A')); scheduleCallback(NormalPriority, () => Scheduler.log('B')); // Yield before B is flushed await waitFor(['A']); scheduleCallback(UserBlockingPriority, () => Scheduler.log('C')); scheduleCallback(UserBlockingPriority, () => Scheduler.log('D')); // C and D should come first, because they are higher priority await waitForAll(['C', 'D', 'B']); }); it('expires work', async () => { scheduleCallback(NormalPriority, didTimeout => { Scheduler.unstable_advanceTime(100); Scheduler.log(`A (did timeout: ${didTimeout})`); }); scheduleCallback(UserBlockingPriority, didTimeout => { Scheduler.unstable_advanceTime(100); Scheduler.log(`B (did timeout: ${didTimeout})`); }); scheduleCallback(UserBlockingPriority, didTimeout => { Scheduler.unstable_advanceTime(100); Scheduler.log(`C (did timeout: ${didTimeout})`); }); // Advance time, but not by enough to expire any work Scheduler.unstable_advanceTime(249); assertLog([]); // Schedule a few more callbacks scheduleCallback(NormalPriority, didTimeout => { Scheduler.unstable_advanceTime(100); Scheduler.log(`D (did timeout: ${didTimeout})`); }); scheduleCallback(NormalPriority, didTimeout => { Scheduler.unstable_advanceTime(100); Scheduler.log(`E (did timeout: ${didTimeout})`); }); // Advance by just a bit more to expire the user blocking callbacks Scheduler.unstable_advanceTime(1); await waitFor(['B (did timeout: true)', 'C (did timeout: true)']); // Expire A Scheduler.unstable_advanceTime(4600); await waitFor(['A (did timeout: true)']); // Flush the rest without expiring await waitForAll(['D (did timeout: false)', 'E (did timeout: true)']); }); it('has a default expiration of ~5 seconds', () => { scheduleCallback(NormalPriority, () => Scheduler.log('A')); Scheduler.unstable_advanceTime(4999); assertLog([]); Scheduler.unstable_advanceTime(1); Scheduler.unstable_flushExpired(); assertLog(['A']); }); it('continues working on same task after yielding', async () => { scheduleCallback(NormalPriority, () => { Scheduler.unstable_advanceTime(100); Scheduler.log('A'); }); scheduleCallback(NormalPriority, () => { Scheduler.unstable_advanceTime(100); Scheduler.log('B'); }); let didYield = false; const tasks = [ ['C1', 100], ['C2', 100], ['C3', 100], ]; const C = () => { while (tasks.length > 0) { const [label, ms] = tasks.shift(); Scheduler.unstable_advanceTime(ms); Scheduler.log(label); if (shouldYield()) { didYield = true; return C; } } }; scheduleCallback(NormalPriority, C); scheduleCallback(NormalPriority, () => { Scheduler.unstable_advanceTime(100); Scheduler.log('D'); }); scheduleCallback(NormalPriority, () => { Scheduler.unstable_advanceTime(100); Scheduler.log('E'); }); // Flush, then yield while in the middle of C. expect(didYield).toBe(false); await waitFor(['A', 'B', 'C1']); expect(didYield).toBe(true); // When we resume, we should continue working on C. await waitForAll(['C2', 'C3', 'D', 'E']); }); it('continuation callbacks inherit the expiration of the previous callback', async () => { const tasks = [ ['A', 125], ['B', 124], ['C', 100], ['D', 100], ]; const work = () => { while (tasks.length > 0) { const [label, ms] = tasks.shift(); Scheduler.unstable_advanceTime(ms); Scheduler.log(label); if (shouldYield()) { return work; } } }; // Schedule a high priority callback scheduleCallback(UserBlockingPriority, work); // Flush until just before the expiration time await waitFor(['A', 'B']); // Advance time by just a bit more. This should expire all the remaining work. Scheduler.unstable_advanceTime(1); Scheduler.unstable_flushExpired(); assertLog(['C', 'D']); }); it('continuations are interrupted by higher priority work', async () => { const tasks = [ ['A', 100], ['B', 100], ['C', 100], ['D', 100], ]; const work = () => { while (tasks.length > 0) { const [label, ms] = tasks.shift(); Scheduler.unstable_advanceTime(ms); Scheduler.log(label); if (tasks.length > 0 && shouldYield()) { return work; } } }; scheduleCallback(NormalPriority, work); await waitFor(['A']); scheduleCallback(UserBlockingPriority, () => { Scheduler.unstable_advanceTime(100); Scheduler.log('High pri'); }); await waitForAll(['High pri', 'B', 'C', 'D']); }); it( 'continuations do not block higher priority work scheduled ' + 'inside an executing callback', async () => { const tasks = [ ['A', 100], ['B', 100], ['C', 100], ['D', 100], ]; const work = () => { while (tasks.length > 0) { const task = tasks.shift(); const [label, ms] = task; Scheduler.unstable_advanceTime(ms); Scheduler.log(label); if (label === 'B') { // Schedule high pri work from inside another callback Scheduler.log('Schedule high pri'); scheduleCallback(UserBlockingPriority, () => { Scheduler.unstable_advanceTime(100); Scheduler.log('High pri'); }); } if (tasks.length > 0) { // Return a continuation return work; } } }; scheduleCallback(NormalPriority, work); await waitForAll([ 'A', 'B', 'Schedule high pri', // The high pri callback should fire before the continuation of the // lower pri work 'High pri', // Continue low pri work 'C', 'D', ]); }, ); it('cancelling a continuation', async () => { const task = scheduleCallback(NormalPriority, () => { Scheduler.log('Yield'); return () => { Scheduler.log('Continuation'); }; }); await waitFor(['Yield']); cancelCallback(task); await waitForAll([]); }); it('top-level immediate callbacks fire in a subsequent task', () => { scheduleCallback(ImmediatePriority, () => Scheduler.log('A')); scheduleCallback(ImmediatePriority, () => Scheduler.log('B')); scheduleCallback(ImmediatePriority, () => Scheduler.log('C')); scheduleCallback(ImmediatePriority, () => Scheduler.log('D')); // Immediate callback hasn't fired, yet. assertLog([]); // They all flush immediately within the subsequent task. Scheduler.unstable_flushExpired(); assertLog(['A', 'B', 'C', 'D']); }); it('nested immediate callbacks are added to the queue of immediate callbacks', () => { scheduleCallback(ImmediatePriority, () => Scheduler.log('A')); scheduleCallback(ImmediatePriority, () => { Scheduler.log('B'); // This callback should go to the end of the queue scheduleCallback(ImmediatePriority, () => Scheduler.log('C')); }); scheduleCallback(ImmediatePriority, () => Scheduler.log('D')); assertLog([]); // C should flush at the end Scheduler.unstable_flushExpired(); assertLog(['A', 'B', 'D', 'C']); }); it('wrapped callbacks have same signature as original callback', () => { const wrappedCallback = wrapCallback((...args) => ({args})); expect(wrappedCallback('a', 'b')).toEqual({args: ['a', 'b']}); }); it('wrapped callbacks inherit the current priority', () => { const wrappedCallback = runWithPriority(NormalPriority, () => wrapCallback(() => { Scheduler.log(getCurrentPriorityLevel()); }), ); const wrappedUserBlockingCallback = runWithPriority( UserBlockingPriority, () => wrapCallback(() => { Scheduler.log(getCurrentPriorityLevel()); }), ); wrappedCallback(); assertLog([NormalPriority]); wrappedUserBlockingCallback(); assertLog([UserBlockingPriority]); }); it('wrapped callbacks inherit the current priority even when nested', () => { let wrappedCallback; let wrappedUserBlockingCallback; runWithPriority(NormalPriority, () => { wrappedCallback = wrapCallback(() => { Scheduler.log(getCurrentPriorityLevel()); }); wrappedUserBlockingCallback = runWithPriority(UserBlockingPriority, () => wrapCallback(() => { Scheduler.log(getCurrentPriorityLevel()); }), ); }); wrappedCallback(); assertLog([NormalPriority]); wrappedUserBlockingCallback(); assertLog([UserBlockingPriority]); }); it("immediate callbacks fire even if there's an error", () => { scheduleCallback(ImmediatePriority, () => { Scheduler.log('A'); throw new Error('Oops A'); }); scheduleCallback(ImmediatePriority, () => { Scheduler.log('B'); }); scheduleCallback(ImmediatePriority, () => { Scheduler.log('C'); throw new Error('Oops C'); }); expect(() => Scheduler.unstable_flushExpired()).toThrow('Oops A'); assertLog(['A']); // B and C flush in a subsequent event. That way, the second error is not // swallowed. expect(() => Scheduler.unstable_flushExpired()).toThrow('Oops C'); assertLog(['B', 'C']); }); it('multiple immediate callbacks can throw and there will be an error for each one', () => { scheduleCallback(ImmediatePriority, () => { throw new Error('First error'); }); scheduleCallback(ImmediatePriority, () => { throw new Error('Second error'); }); expect(() => Scheduler.unstable_flushAll()).toThrow('First error'); // The next error is thrown in the subsequent event expect(() => Scheduler.unstable_flushAll()).toThrow('Second error'); }); it('exposes the current priority level', () => { Scheduler.log(getCurrentPriorityLevel()); runWithPriority(ImmediatePriority, () => { Scheduler.log(getCurrentPriorityLevel()); runWithPriority(NormalPriority, () => { Scheduler.log(getCurrentPriorityLevel()); runWithPriority(UserBlockingPriority, () => { Scheduler.log(getCurrentPriorityLevel()); }); }); Scheduler.log(getCurrentPriorityLevel()); }); assertLog([ NormalPriority, ImmediatePriority, NormalPriority, UserBlockingPriority, ImmediatePriority, ]); }); if (__DEV__) { // Function names are minified in prod, though you could still infer the // priority if you have sourcemaps. // TODO: Feature temporarily disabled while we investigate a bug in one of // our minifiers. it.skip('adds extra function to the JS stack whose name includes the priority level', async () => { function inferPriorityFromCallstack() { try { throw Error(); } catch (e) { const stack = e.stack; const lines = stack.split('\n'); for (let i = lines.length - 1; i >= 0; i--) { const line = lines[i]; const found = line.match( /scheduler_flushTaskAtPriority_([A-Za-z]+)/, ); if (found !== null) { const priorityStr = found[1]; switch (priorityStr) { case 'Immediate': return ImmediatePriority; case 'UserBlocking': return UserBlockingPriority; case 'Normal': return NormalPriority; case 'Low': return LowPriority; case 'Idle': return IdlePriority; } } } return null; } } scheduleCallback(ImmediatePriority, () => Scheduler.log('Immediate: ' + inferPriorityFromCallstack()), ); scheduleCallback(UserBlockingPriority, () => Scheduler.log('UserBlocking: ' + inferPriorityFromCallstack()), ); scheduleCallback(NormalPriority, () => Scheduler.log('Normal: ' + inferPriorityFromCallstack()), ); scheduleCallback(LowPriority, () => Scheduler.log('Low: ' + inferPriorityFromCallstack()), ); scheduleCallback(IdlePriority, () => Scheduler.log('Idle: ' + inferPriorityFromCallstack()), ); await waitForAll([ 'Immediate: ' + ImmediatePriority, 'UserBlocking: ' + UserBlockingPriority, 'Normal: ' + NormalPriority, 'Low: ' + LowPriority, 'Idle: ' + IdlePriority, ]); }); } describe('delayed tasks', () => { it('schedules a delayed task', async () => { scheduleCallback(NormalPriority, () => Scheduler.log('A'), { delay: 1000, }); // Should flush nothing, because delay hasn't elapsed await waitForAll([]); // Advance time until right before the threshold Scheduler.unstable_advanceTime(999); // Still nothing await waitForAll([]); // Advance time past the threshold Scheduler.unstable_advanceTime(1); // Now it should flush like normal await waitForAll(['A']); }); it('schedules multiple delayed tasks', async () => { scheduleCallback(NormalPriority, () => Scheduler.log('C'), { delay: 300, }); scheduleCallback(NormalPriority, () => Scheduler.log('B'), { delay: 200, }); scheduleCallback(NormalPriority, () => Scheduler.log('D'), { delay: 400, }); scheduleCallback(NormalPriority, () => Scheduler.log('A'), { delay: 100, }); // Should flush nothing, because delay hasn't elapsed await waitForAll([]); // Advance some time. Scheduler.unstable_advanceTime(200); // Both A and B are no longer delayed. They can now flush incrementally. await waitFor(['A']); await waitForAll(['B']); // Advance the rest Scheduler.unstable_advanceTime(200); await waitForAll(['C', 'D']); }); it('interleaves normal tasks and delayed tasks', async () => { // Schedule some high priority callbacks with a delay. When their delay // elapses, they will be the most important callback in the queue. scheduleCallback(UserBlockingPriority, () => Scheduler.log('Timer 2'), { delay: 300, }); scheduleCallback(UserBlockingPriority, () => Scheduler.log('Timer 1'), { delay: 100, }); // Schedule some tasks at default priority. scheduleCallback(NormalPriority, () => { Scheduler.log('A'); Scheduler.unstable_advanceTime(100); }); scheduleCallback(NormalPriority, () => { Scheduler.log('B'); Scheduler.unstable_advanceTime(100); }); scheduleCallback(NormalPriority, () => { Scheduler.log('C'); Scheduler.unstable_advanceTime(100); }); scheduleCallback(NormalPriority, () => { Scheduler.log('D'); Scheduler.unstable_advanceTime(100); }); // Flush all the work. The timers should be interleaved with the // other tasks. await waitForAll(['A', 'Timer 1', 'B', 'C', 'Timer 2', 'D']); }); it('interleaves delayed tasks with time-sliced tasks', async () => { // Schedule some high priority callbacks with a delay. When their delay // elapses, they will be the most important callback in the queue. scheduleCallback(UserBlockingPriority, () => Scheduler.log('Timer 2'), { delay: 300, }); scheduleCallback(UserBlockingPriority, () => Scheduler.log('Timer 1'), { delay: 100, }); // Schedule a time-sliced task at default priority. const tasks = [ ['A', 100], ['B', 100], ['C', 100], ['D', 100], ]; const work = () => { while (tasks.length > 0) { const task = tasks.shift(); const [label, ms] = task; Scheduler.unstable_advanceTime(ms); Scheduler.log(label); if (tasks.length > 0) { return work; } } }; scheduleCallback(NormalPriority, work); // Flush all the work. The timers should be interleaved with the // other tasks. await waitForAll(['A', 'Timer 1', 'B', 'C', 'Timer 2', 'D']); }); it('cancels a delayed task', async () => { // Schedule several tasks with the same delay const options = {delay: 100}; scheduleCallback(NormalPriority, () => Scheduler.log('A'), options); const taskB = scheduleCallback( NormalPriority, () => Scheduler.log('B'), options, ); const taskC = scheduleCallback( NormalPriority, () => Scheduler.log('C'), options, ); // Cancel B before its delay has elapsed await waitForAll([]); cancelCallback(taskB); // Cancel C after its delay has elapsed Scheduler.unstable_advanceTime(500); cancelCallback(taskC); // Only A should flush await waitForAll(['A']); }); it('gracefully handles scheduled tasks that are not a function', async () => { scheduleCallback(ImmediatePriority, null); await waitForAll([]); scheduleCallback(ImmediatePriority, undefined); await waitForAll([]); scheduleCallback(ImmediatePriority, {}); await waitForAll([]); scheduleCallback(ImmediatePriority, 42); await waitForAll([]); }); it('toFlushUntilNextPaint stops if a continuation is returned', async () => { scheduleCallback(NormalPriority, () => { Scheduler.log('Original Task'); Scheduler.log('shouldYield: ' + shouldYield()); Scheduler.log('Return a continuation'); return () => { Scheduler.log('Continuation Task'); }; }); await waitForPaint([ 'Original Task', // Immediately before returning a continuation, `shouldYield` returns // false, which means there must be time remaining in the frame. 'shouldYield: false', 'Return a continuation', // The continuation should not flush yet. ]); // No time has elapsed expect(Scheduler.unstable_now()).toBe(0); // Continue the task await waitForAll(['Continuation Task']); }); it("toFlushAndYield keeps flushing even if there's a continuation", async () => { scheduleCallback(NormalPriority, () => { Scheduler.log('Original Task'); Scheduler.log('shouldYield: ' + shouldYield()); Scheduler.log('Return a continuation'); return () => { Scheduler.log('Continuation Task'); }; }); await waitForAll([ 'Original Task', // Immediately before returning a continuation, `shouldYield` returns // false, which means there must be time remaining in the frame. 'shouldYield: false', 'Return a continuation', // The continuation should flush immediately, even though the task // yielded a continuation. 'Continuation Task', ]); }); }); });
29.575209
103
0.595253
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 ReactCurrentDispatcher from './ReactCurrentDispatcher'; import ReactCurrentCache from './ReactCurrentCache'; import ReactCurrentBatchConfig from './ReactCurrentBatchConfig'; import ReactCurrentActQueue from './ReactCurrentActQueue'; import ReactCurrentOwner from './ReactCurrentOwner'; import ReactDebugCurrentFrame from './ReactDebugCurrentFrame'; import {enableServerContext} from 'shared/ReactFeatureFlags'; import {ContextRegistry} from './ReactServerContextRegistry'; const ReactSharedInternals = { ReactCurrentDispatcher, ReactCurrentCache, ReactCurrentBatchConfig, ReactCurrentOwner, }; if (__DEV__) { ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue; } if (enableServerContext) { ReactSharedInternals.ContextRegistry = ContextRegistry; } export default ReactSharedInternals;
30.970588
71
0.808471
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 {existsSync} from 'fs'; import {basename, join, isAbsolute} from 'path'; import {execSync, spawn} from 'child_process'; import {parse} from 'shell-quote'; function isTerminalEditor(editor: string): boolean { switch (editor) { case 'vim': case 'emacs': case 'nano': return true; default: return false; } } // Map from full process name to binary that starts the process // We can't just re-use full process name, because it will spawn a new instance // of the app every time const COMMON_EDITORS = { '/Applications/Atom.app/Contents/MacOS/Atom': 'atom', '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta': '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta', '/Applications/Sublime Text.app/Contents/MacOS/Sublime Text': '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl', '/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2': '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl', '/Applications/Visual Studio Code.app/Contents/MacOS/Electron': 'code', }; function getArgumentsForLineNumber( editor: string, filePath: string, lineNumber: number, ): Array<string> { switch (basename(editor)) { case 'vim': case 'mvim': return [filePath, '+' + lineNumber]; case 'atom': case 'Atom': case 'Atom Beta': case 'subl': case 'sublime': case 'wstorm': case 'appcode': case 'charm': case 'idea': return [filePath + ':' + lineNumber]; case 'joe': case 'emacs': case 'emacsclient': return ['+' + lineNumber, filePath]; case 'rmate': case 'mate': case 'mine': return ['--line', lineNumber + '', filePath]; case 'code': return ['-g', filePath + ':' + lineNumber]; default: // For all others, drop the lineNumber until we have // a mapping above, since providing the lineNumber incorrectly // can result in errors or confusing behavior. return [filePath]; } } function guessEditor(): Array<string> { // Explicit config always wins if (process.env.REACT_EDITOR) { return parse(process.env.REACT_EDITOR); } // Using `ps x` on OSX we can find out which editor is currently running. // Potentially we could use similar technique for Windows and Linux if (process.platform === 'darwin') { try { const output = execSync('ps x').toString(); const processNames = Object.keys(COMMON_EDITORS); for (let i = 0; i < processNames.length; i++) { const processName = processNames[i]; if (output.indexOf(processName) !== -1) { return [COMMON_EDITORS[processName]]; } } } catch (error) { // Ignore... } } // Last resort, use old-school env vars if (process.env.VISUAL) { return [process.env.VISUAL]; } else if (process.env.EDITOR) { return [process.env.EDITOR]; } return []; } let childProcess = null; export function getValidFilePath( maybeRelativePath: string, absoluteProjectRoots: Array<string>, ): string | null { // We use relative paths at Facebook with deterministic builds. // This is why our internal tooling calls React DevTools with absoluteProjectRoots. // If the filename is absolute then we don't need to care about this. if (isAbsolute(maybeRelativePath)) { if (existsSync(maybeRelativePath)) { return maybeRelativePath; } } else { for (let i = 0; i < absoluteProjectRoots.length; i++) { const projectRoot = absoluteProjectRoots[i]; const joinedPath = join(projectRoot, maybeRelativePath); if (existsSync(joinedPath)) { return joinedPath; } } } return null; } export function doesFilePathExist( maybeRelativePath: string, absoluteProjectRoots: Array<string>, ): boolean { return getValidFilePath(maybeRelativePath, absoluteProjectRoots) !== null; } export function launchEditor( maybeRelativePath: string, lineNumber: number, absoluteProjectRoots: Array<string>, ) { const filePath = getValidFilePath(maybeRelativePath, absoluteProjectRoots); if (filePath === null) { return; } // Sanitize lineNumber to prevent malicious use on win32 // via: https://github.com/nodejs/node/blob/c3bb4b1aa5e907d489619fb43d233c3336bfc03d/lib/child_process.js#L333 if (lineNumber && isNaN(lineNumber)) { return; } const [editor, ...destructuredArgs] = guessEditor(); if (!editor) { return; } let args = destructuredArgs; if (lineNumber) { args = args.concat(getArgumentsForLineNumber(editor, filePath, lineNumber)); } else { args.push(filePath); } if (childProcess && isTerminalEditor(editor)) { // There's an existing editor process already and it's attached // to the terminal, so go kill it. Otherwise two separate editor // instances attach to the stdin/stdout which gets confusing. // $FlowFixMe[incompatible-use] found when upgrading Flow childProcess.kill('SIGKILL'); } if (process.platform === 'win32') { // On Windows, launch the editor in a shell because spawn can only // launch .exe files. childProcess = spawn('cmd.exe', ['/C', editor].concat(args), { stdio: 'inherit', }); } else { childProcess = spawn(editor, args, {stdio: 'inherit'}); } childProcess.on('error', function () {}); // $FlowFixMe[incompatible-use] found when upgrading Flow childProcess.on('exit', function () { childProcess = null; }); }
28.05641
112
0.666726
cybersecurity-penetration-testing
'use strict'; var s; if (process.env.NODE_ENV === 'production') { s = require('./cjs/react-dom-server.browser.production.min.js'); } else { s = require('./cjs/react-dom-server.browser.development.js'); } exports.version = s.version; exports.prerender = s.prerender;
21.75
66
0.683824
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 {AsyncLocalStorage} from 'async_hooks'; import type {Request} from 'react-server/src/ReactFizzServer'; export * from 'react-dom-bindings/src/server/ReactFizzConfigDOM'; export const supportsRequestStorage = true; export const requestStorage: AsyncLocalStorage<Request> = new AsyncLocalStorage();
26
66
0.753906
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 strict */ // In www, these flags are controlled by GKs. Because most GKs have some // population running in either mode, we should run our tests that way, too, // // Use __VARIANT__ to simulate a GK. The tests will be run twice: once // with the __VARIANT__ set to `true`, and once set to `false`. export const disableInputAttributeSyncing = __VARIANT__; export const disableIEWorkarounds = __VARIANT__; export const enableLegacyFBSupport = __VARIANT__; export const enableUseRefAccessWarning = __VARIANT__; export const enableProfilerNestedUpdateScheduledHook = __VARIANT__; export const disableSchedulerTimeoutInWorkLoop = __VARIANT__; export const enableLazyContextPropagation = __VARIANT__; export const forceConcurrentByDefaultForTesting = __VARIANT__; export const enableUnifiedSyncLane = __VARIANT__; export const enableTransitionTracing = __VARIANT__; export const enableCustomElementPropertySupport = __VARIANT__; export const enableDeferRootSchedulingToMicrotask = __VARIANT__; export const enableAsyncActions = __VARIANT__; export const alwaysThrottleRetries = __VARIANT__; export const enableDO_NOT_USE_disableStrictPassiveEffect = __VARIANT__; export const enableUseDeferredValueInitialArg = __VARIANT__; export const enableRetryLaneExpiration = __VARIANT__; export const retryLaneExpirationMs = 5000; export const syncLaneExpirationMs = 250; export const transitionLaneExpirationMs = 5000; // Enable this flag to help with concurrent mode debugging. // It logs information to the console about React scheduling, rendering, and commit phases. // // NOTE: This feature will only work in DEV mode; all callsites are wrapped with __DEV__. export const enableDebugTracing = __EXPERIMENTAL__; export const enableSchedulingProfiler = __VARIANT__; // These are already tested in both modes using the build type dimension, // so we don't need to use __VARIANT__ to get extra coverage. export const replayFailedUnitOfWorkWithInvokeGuardedCallback = __DEV__; // TODO: These flags are hard-coded to the default values used in open source. // Update the tests so that they pass in either mode, then set these // to __VARIANT__. export const enableTrustedTypesIntegration = false; // You probably *don't* want to add more hardcoded ones. // Instead, try to add them above with the __VARIANT__ value.
43.785714
91
0.766653
Ethical-Hacking-Scripts
/** * 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 {createContext, Component, useContext, useState} from 'react'; import PropTypes from 'prop-types'; import type {ReactContext} from 'shared/ReactTypes'; function someNamedFunction() {} function formatContextForDisplay(name: string, value: any | string) { return ( <li> {name}: <pre>{JSON.stringify(value, null, 2)}</pre> </li> ); } const contextData = { array: ['first', 'second', 'third'], bool: true, func: someNamedFunction, number: 123, object: {outer: {inner: {}}}, string: 'abc', symbol: Symbol.for('symbol'), null: null, undefined: undefined, }; class LegacyContextProvider extends Component<any> { static childContextTypes: { array: any, bool: any, func: any, null: any, number: any, object: any, string: any, symbol: any, undefined: any, } = { array: PropTypes.array, bool: PropTypes.bool, func: PropTypes.func, number: PropTypes.number, object: PropTypes.object, string: PropTypes.string, symbol: PropTypes.symbol, null: PropTypes.any, undefined: PropTypes.any, }; getChildContext(): { array: Array<string>, bool: boolean, func: () => void, null: null, number: number, object: {outer: {inner: {...}}}, string: string, symbol: symbol, undefined: void, } { return contextData; } render(): any { return this.props.children; } } class LegacyContextConsumer extends Component<any> { static contextTypes: { array: any, bool: any, func: any, null: any, number: any, object: any, string: any, symbol: any, undefined: any, } = { array: PropTypes.array, bool: PropTypes.bool, func: PropTypes.func, number: PropTypes.number, object: PropTypes.object, string: PropTypes.string, symbol: PropTypes.symbol, null: PropTypes.any, undefined: PropTypes.any, }; render(): any { return formatContextForDisplay('LegacyContextConsumer', this.context); } } class LegacyContextProviderWithUpdates extends Component<any> { constructor(props: any) { super(props); this.state = {type: 'desktop'}; } getChildContext(): {type: any} { return {type: this.state.type}; } // $FlowFixMe[missing-local-annot] handleChange = event => { this.setState({type: event.target.value}); }; render(): any { return ( <> <LegacyFunctionalContextConsumer /> <div> <input value={this.state.type} onChange={this.handleChange} /> </div> </> ); } } LegacyContextProviderWithUpdates.childContextTypes = { type: PropTypes.string, }; // $FlowFixMe[missing-local-annot] function LegacyFunctionalContextConsumer(props: any, context) { return formatContextForDisplay('LegacyFunctionContextConsumer', context.type); } LegacyFunctionalContextConsumer.contextTypes = { type: PropTypes.string, }; const ModernContext = createContext(); ModernContext.displayName = 'ModernContext'; const ArrayContext = createContext(contextData.array); ArrayContext.displayName = 'ArrayContext'; const BoolContext = createContext(contextData.bool); BoolContext.displayName = 'BoolContext'; const FuncContext = createContext(contextData.func); FuncContext.displayName = 'FuncContext'; const NumberContext = createContext(contextData.number); NumberContext.displayName = 'NumberContext'; const StringContext = createContext(contextData.string); StringContext.displayName = 'StringContext'; const SymbolContext = createContext(contextData.symbol); SymbolContext.displayName = 'SymbolContext'; const NullContext = createContext(null); NullContext.displayName = 'NullContext'; const UndefinedContext = createContext(undefined); UndefinedContext.displayName = 'UndefinedContext'; class ModernContextType extends Component<any> { static contextType: ReactContext<void> = ModernContext; render(): any { return formatContextForDisplay('ModernContextType', this.context); } } function FunctionalContextConsumer() { const value = useContext(StringContext); return formatContextForDisplay('FunctionalContextConsumer', value); } const StringContextWithUpdates = createContext({ string: contextData.string, setString: (string: string) => {}, }); const StringContextWithUpdates2 = createContext({ string2: contextData.string, setString2: (string: string) => {}, }); function FunctionalContextProviderWithContextUpdates() { const [string, setString] = useState(contextData.string); const [string2, setString2] = useState(contextData.string); const value = {string, setString}; const value2 = {string2, setString2}; return ( <StringContextWithUpdates.Provider value={value}> <StringContextWithUpdates2.Provider value={value2}> <FunctionalContextConsumerWithContextUpdates /> </StringContextWithUpdates2.Provider> </StringContextWithUpdates.Provider> ); } function FunctionalContextConsumerWithContextUpdates() { const {string, setString} = useContext(StringContextWithUpdates); const {string2, setString2} = useContext(StringContextWithUpdates2); const [state, setState] = useState('state'); // $FlowFixMe[missing-local-annot] const handleChange = e => setString(e.target.value); // $FlowFixMe[missing-local-annot] const handleChange2 = e => setString2(e.target.value); return ( <> {formatContextForDisplay( 'FunctionalContextConsumerWithUpdates', `context: ${string}, context 2: ${string2}`, )} <div> context: <input value={string} onChange={handleChange} /> </div> <div> context 2: <input value={string2} onChange={handleChange2} /> </div> <div> {state} <div> test state:{' '} <input value={state} onChange={e => setState(e.target.value)} /> </div> </div> </> ); } class ModernClassContextProviderWithUpdates extends Component<any> { constructor(props: any) { super(props); this.setString = string => { this.setState({string}); }; this.state = { string: contextData.string, setString: this.setString, }; } render(): any { return ( <StringContextWithUpdates.Provider value={this.state}> <ModernClassContextConsumerWithUpdates /> </StringContextWithUpdates.Provider> ); } } class ModernClassContextConsumerWithUpdates extends Component<any> { render(): any { return ( <StringContextWithUpdates.Consumer> {({string, setString}: {string: string, setString: string => void}) => ( <> {formatContextForDisplay( 'ModernClassContextConsumerWithUpdates', string, )} <input value={string} onChange={e => setString(e.target.value)} /> </> )} </StringContextWithUpdates.Consumer> ); } } export default function Contexts(): React.Node { return ( <div> <h1>Contexts</h1> <ul> <LegacyContextProvider> <LegacyContextConsumer /> </LegacyContextProvider> <LegacyContextProviderWithUpdates /> <ModernContext.Provider value={contextData}> <ModernContext.Consumer> {(value: $FlowFixMe) => formatContextForDisplay('ModernContext.Consumer', value) } </ModernContext.Consumer> <ModernContextType /> </ModernContext.Provider> <FunctionalContextConsumer /> <FunctionalContextProviderWithContextUpdates /> <ModernClassContextProviderWithUpdates /> <ArrayContext.Consumer> {(value: $FlowFixMe) => formatContextForDisplay('ArrayContext.Consumer', value) } </ArrayContext.Consumer> <BoolContext.Consumer> {(value: $FlowFixMe) => formatContextForDisplay('BoolContext.Consumer', value) } </BoolContext.Consumer> <FuncContext.Consumer> {(value: $FlowFixMe) => formatContextForDisplay('FuncContext.Consumer', value) } </FuncContext.Consumer> <NumberContext.Consumer> {(value: $FlowFixMe) => formatContextForDisplay('NumberContext.Consumer', value) } </NumberContext.Consumer> <StringContext.Consumer> {(value: $FlowFixMe) => formatContextForDisplay('StringContext.Consumer', value) } </StringContext.Consumer> <SymbolContext.Consumer> {(value: $FlowFixMe) => formatContextForDisplay('SymbolContext.Consumer', value) } </SymbolContext.Consumer> <NullContext.Consumer> {(value: $FlowFixMe) => formatContextForDisplay('NullContext.Consumer', value) } </NullContext.Consumer> <UndefinedContext.Consumer> {(value: $FlowFixMe) => formatContextForDisplay('UndefinedContext.Consumer', value) } </UndefinedContext.Consumer> </ul> </div> ); }
26.352941
80
0.652328
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 {copy} from 'clipboard-js'; import * as React from 'react'; import {useCallback, useContext, useRef, useState} from 'react'; import {BridgeContext, StoreContext} from '../context'; import Button from '../Button'; import ButtonIcon from '../ButtonIcon'; import Toggle from '../Toggle'; import ExpandCollapseToggle from './ExpandCollapseToggle'; import KeyValue from './KeyValue'; import {getMetaValueLabel, serializeHooksForCopy} from '../utils'; import Store from '../../store'; import styles from './InspectedElementHooksTree.css'; import useContextMenu from '../../ContextMenu/useContextMenu'; import {meta} from '../../../hydration'; import {getHookSourceLocationKey} from 'react-devtools-shared/src/hookNamesCache'; import HookNamesModuleLoaderContext from 'react-devtools-shared/src/devtools/views/Components/HookNamesModuleLoaderContext'; import isArray from 'react-devtools-shared/src/isArray'; import type {InspectedElement} from 'react-devtools-shared/src/frontend/types'; import type {HooksNode, HooksTree} from 'react-debug-tools/src/ReactDebugHooks'; import type {FrontendBridge} from 'react-devtools-shared/src/bridge'; import type {HookNames} from 'react-devtools-shared/src/frontend/types'; import type {Element} from 'react-devtools-shared/src/frontend/types'; import type {ToggleParseHookNames} from './InspectedElementContext'; type HooksTreeViewProps = { bridge: FrontendBridge, element: Element, hookNames: HookNames | null, inspectedElement: InspectedElement, parseHookNames: boolean, store: Store, toggleParseHookNames: ToggleParseHookNames, }; export function InspectedElementHooksTree({ bridge, element, hookNames, inspectedElement, parseHookNames, store, toggleParseHookNames, }: HooksTreeViewProps): React.Node { const {hooks, id} = inspectedElement; // Changing parseHookNames is done in a transition, because it suspends. // This value is done outside of the transition, so the UI toggle feels responsive. const [parseHookNamesOptimistic, setParseHookNamesOptimistic] = useState(parseHookNames); const handleChange = () => { setParseHookNamesOptimistic(!parseHookNames); toggleParseHookNames(); }; const hookNamesModuleLoader = useContext(HookNamesModuleLoaderContext); const hookParsingFailed = parseHookNames && hookNames === null; let toggleTitle; if (hookParsingFailed) { toggleTitle = 'Hook parsing failed'; } else if (parseHookNames) { toggleTitle = 'Parsing hook names ...'; } else { toggleTitle = 'Parse hook names (may be slow)'; } const handleCopy = () => copy(serializeHooksForCopy(hooks)); if (hooks === null) { return null; } else { return ( <div className={styles.HooksTreeView} data-testname="InspectedElementHooksTree"> <div className={styles.HeaderRow}> <div className={styles.Header}>hooks</div> {typeof hookNamesModuleLoader === 'function' && (!parseHookNames || hookParsingFailed) && ( <Toggle className={hookParsingFailed ? styles.ToggleError : null} isChecked={parseHookNamesOptimistic} isDisabled={parseHookNamesOptimistic || hookParsingFailed} onChange={handleChange} testName="LoadHookNamesButton" title={toggleTitle}> <ButtonIcon type="parse-hook-names" /> </Toggle> )} <Button onClick={handleCopy} title="Copy to clipboard"> <ButtonIcon type="copy" /> </Button> </div> <InnerHooksTreeView hookNames={hookNames} hooks={hooks} id={id} element={element} inspectedElement={inspectedElement} path={[]} /> </div> ); } } type InnerHooksTreeViewProps = { element: Element, hookNames: HookNames | null, hooks: HooksTree, id: number, inspectedElement: InspectedElement, path: Array<string | number>, }; export function InnerHooksTreeView({ element, hookNames, hooks, id, inspectedElement, path, }: InnerHooksTreeViewProps): React.Node { return hooks.map((hook, index) => ( <HookView key={index} element={element} hook={hooks[index]} hookNames={hookNames} id={id} inspectedElement={inspectedElement} path={path.concat([index])} /> )); } type HookViewProps = { element: Element, hook: HooksNode, hookNames: HookNames | null, id: number, inspectedElement: InspectedElement, path: Array<string | number>, }; function HookView({ element, hook, hookNames, id, inspectedElement, path, }: HookViewProps) { const {canEditHooks, canEditHooksAndDeletePaths, canEditHooksAndRenamePaths} = inspectedElement; const {id: hookID, isStateEditable, subHooks, value} = hook; const isReadOnly = hookID == null || !isStateEditable; const canDeletePaths = !isReadOnly && canEditHooksAndDeletePaths; const canEditValues = !isReadOnly && canEditHooks; const canRenamePaths = !isReadOnly && canEditHooksAndRenamePaths; const bridge = useContext(BridgeContext); const store = useContext(StoreContext); const [isOpen, setIsOpen] = useState<boolean>(false); const toggleIsOpen = useCallback( () => setIsOpen(prevIsOpen => !prevIsOpen), [], ); const contextMenuTriggerRef = useRef(null); useContextMenu({ data: { path: ['hooks', ...path], type: hook !== null && typeof hook === 'object' && hook.hasOwnProperty(meta.type) ? hook[(meta.type: any)] : typeof value, }, id: 'InspectedElement', ref: contextMenuTriggerRef, }); if (hook.hasOwnProperty(meta.inspected)) { // This Hook is too deep and hasn't been hydrated. if (__DEV__) { console.warn('Unexpected dehydrated hook; this is a DevTools error.'); } return ( <div className={styles.Hook}> <div className={styles.NameValueRow}> <span className={styles.TruncationIndicator}>...</span> </div> </div> ); } // Certain hooks are not editable at all (as identified by react-debug-tools). // Primitive hook names (e.g. the "State" name for useState) are also never editable. // $FlowFixMe[missing-local-annot] const canRenamePathsAtDepth = depth => isStateEditable && depth > 1; const isCustomHook = subHooks.length > 0; let name = hook.name; if (hookID !== null) { name = ( <> <span className={styles.PrimitiveHookNumber}>{hookID + 1}</span> {name} </> ); } const type = typeof value; let displayValue; let isComplexDisplayValue = false; const hookSource = hook.hookSource; const hookName = hookNames != null && hookSource != null ? hookNames.get(getHookSourceLocationKey(hookSource)) : null; const hookDisplayName = hookName ? ( <> {name} {!!hookName && <span className={styles.HookName}>({hookName})</span>} </> ) : ( name ); // Format data for display to mimic the props/state/context for now. if (type === 'string') { displayValue = `"${((value: any): string)}"`; } else if (type === 'boolean') { displayValue = value ? 'true' : 'false'; } else if (type === 'number') { displayValue = value; } else if (value === null) { displayValue = 'null'; } else if (value === undefined) { displayValue = null; } else if (isArray(value)) { isComplexDisplayValue = true; displayValue = 'Array'; } else if (type === 'object') { isComplexDisplayValue = true; displayValue = 'Object'; } if (isCustomHook) { const subHooksView = isArray(subHooks) ? ( <InnerHooksTreeView element={element} hooks={subHooks} hookNames={hookNames} id={id} inspectedElement={inspectedElement} path={path.concat(['subHooks'])} /> ) : ( <KeyValue alphaSort={false} bridge={bridge} canDeletePaths={canDeletePaths} canEditValues={canEditValues} canRenamePaths={canRenamePaths} canRenamePathsAtDepth={canRenamePathsAtDepth} depth={1} element={element} hookID={hookID} hookName={hookName} inspectedElement={inspectedElement} name="subHooks" path={path.concat(['subHooks'])} store={store} type="hooks" value={subHooks} /> ); if (isComplexDisplayValue) { return ( <div className={styles.Hook}> <div ref={contextMenuTriggerRef} className={styles.NameValueRow}> <ExpandCollapseToggle isOpen={isOpen} setIsOpen={setIsOpen} /> <span onClick={toggleIsOpen} className={name !== '' ? styles.Name : styles.NameAnonymous}> {hookDisplayName || 'Anonymous'} </span> <span className={styles.Value} onClick={toggleIsOpen}> {isOpen || getMetaValueLabel(value)} </span> </div> <div className={styles.Children} hidden={!isOpen}> <KeyValue alphaSort={false} bridge={bridge} canDeletePaths={canDeletePaths} canEditValues={canEditValues} canRenamePaths={canRenamePaths} canRenamePathsAtDepth={canRenamePathsAtDepth} depth={1} element={element} hookID={hookID} hookName={hookName} inspectedElement={inspectedElement} name="DebugValue" path={path.concat(['value'])} pathRoot="hooks" store={store} value={value} /> {subHooksView} </div> </div> ); } else { return ( <div className={styles.Hook}> <div ref={contextMenuTriggerRef} className={styles.NameValueRow}> <ExpandCollapseToggle isOpen={isOpen} setIsOpen={setIsOpen} /> <span onClick={toggleIsOpen} className={name !== '' ? styles.Name : styles.NameAnonymous}> {hookDisplayName || 'Anonymous'} </span>{' '} <span className={styles.Value} onClick={toggleIsOpen}> {displayValue} </span> </div> <div className={styles.Children} hidden={!isOpen}> {subHooksView} </div> </div> ); } } else { if (isComplexDisplayValue) { return ( <div className={styles.Hook}> <KeyValue alphaSort={false} bridge={bridge} canDeletePaths={canDeletePaths} canEditValues={canEditValues} canRenamePaths={canRenamePaths} canRenamePathsAtDepth={canRenamePathsAtDepth} depth={1} element={element} hookID={hookID} hookName={hookName} inspectedElement={inspectedElement} name={name} path={path.concat(['value'])} pathRoot="hooks" store={store} value={value} /> </div> ); } else { return ( <div className={styles.Hook}> <KeyValue alphaSort={false} bridge={bridge} canDeletePaths={false} canEditValues={canEditValues} canRenamePaths={false} depth={1} element={element} hookID={hookID} hookName={hookName} inspectedElement={inspectedElement} name={name} path={[]} pathRoot="hooks" store={store} value={value} /> </div> ); } } } export default (React.memo( InspectedElementHooksTree, ): React.ComponentType<HookViewProps>);
28.469586
124
0.610272
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 strict */ import typeof * as ExportsType from './ReactFeatureFlags.native-fb-dynamic'; import typeof * as DynamicFlagsType from 'ReactNativeInternalFeatureFlags'; // In xplat, these flags are controlled by GKs. Because most GKs have some // population running in either mode, we should run our tests that way, too, // // Use __VARIANT__ to simulate a GK. The tests will be run twice: once // with the __VARIANT__ set to `true`, and once set to `false`. // // TODO: __VARIANT__ isn't supported for React Native flags yet. You can set the // flag here but it won't be set to `true` in any of our test runs. Need to // update the test configuration. export const alwaysThrottleRetries = __VARIANT__; export const enableDeferRootSchedulingToMicrotask = __VARIANT__; export const enableUnifiedSyncLane = __VARIANT__; export const enableUseRefAccessWarning = __VARIANT__; export const passChildrenWhenCloningPersistedNodes = __VARIANT__; export const useMicrotasksForSchedulingInFabric = __VARIANT__; // Flow magic to verify the exports of this file match the original version. ((((null: any): ExportsType): DynamicFlagsType): ExportsType);
40.875
80
0.746079
PenetrationTestingScripts
/** @flow */ import * as React from 'react'; import {forwardRef} from 'react'; import Bridge from 'react-devtools-shared/src/bridge'; import Store from 'react-devtools-shared/src/devtools/store'; import DevTools from 'react-devtools-shared/src/devtools/views/DevTools'; import { getAppendComponentStack, getBreakOnConsoleErrors, getSavedComponentFilters, getShowInlineWarningsAndErrors, getHideConsoleLogsInStrictMode, } from 'react-devtools-shared/src/utils'; import type {Wall} from 'react-devtools-shared/src/frontend/types'; import type {FrontendBridge} from 'react-devtools-shared/src/bridge'; import type {Props} from 'react-devtools-shared/src/devtools/views/DevTools'; type Config = { checkBridgeProtocolCompatibility?: boolean, supportsNativeInspection?: boolean, supportsProfiling?: boolean, }; export function createStore(bridge: FrontendBridge, config?: Config): Store { return new Store(bridge, { checkBridgeProtocolCompatibility: true, supportsTraceUpdates: true, supportsTimeline: true, supportsNativeInspection: true, ...config, }); } export function createBridge(contentWindow: any, wall?: Wall): FrontendBridge { if (wall == null) { wall = { listen(fn) { // $FlowFixMe[missing-local-annot] const onMessage = ({data}) => { fn(data); }; window.addEventListener('message', onMessage); return () => { window.removeEventListener('message', onMessage); }; }, send(event: string, payload: any, transferable?: Array<any>) { contentWindow.postMessage({event, payload}, '*', transferable); }, }; } return (new Bridge(wall): FrontendBridge); } export function initialize( contentWindow: any, { bridge, store, }: { bridge?: FrontendBridge, store?: Store, } = {}, ): React.AbstractComponent<Props, mixed> { if (bridge == null) { bridge = createBridge(contentWindow); } // Type refinement. const frontendBridge = ((bridge: any): FrontendBridge); if (store == null) { store = createStore(frontendBridge); } const onGetSavedPreferences = () => { // This is the only message we're listening for, // so it's safe to cleanup after we've received it. frontendBridge.removeListener('getSavedPreferences', onGetSavedPreferences); const data = { appendComponentStack: getAppendComponentStack(), breakOnConsoleErrors: getBreakOnConsoleErrors(), componentFilters: getSavedComponentFilters(), showInlineWarningsAndErrors: getShowInlineWarningsAndErrors(), hideConsoleLogsInStrictMode: getHideConsoleLogsInStrictMode(), }; // The renderer interface can't read saved preferences directly, // because they are stored in localStorage within the context of the extension. // Instead it relies on the extension to pass them through. frontendBridge.send('savedPreferences', data); }; frontendBridge.addListener('getSavedPreferences', onGetSavedPreferences); const ForwardRef = forwardRef<Props, mixed>((props, ref) => ( <DevTools ref={ref} bridge={frontendBridge} store={store} {...props} /> )); ForwardRef.displayName = 'DevTools'; return ForwardRef; }
29.252336
83
0.699011
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 { REACT_ELEMENT_TYPE, REACT_FORWARD_REF_TYPE, REACT_LAZY_TYPE, REACT_MEMO_TYPE, REACT_SUSPENSE_TYPE, REACT_SUSPENSE_LIST_TYPE, } from 'shared/ReactSymbols'; import type {LazyComponent} from 'react/src/ReactLazy'; import isArray from 'shared/isArray'; import getPrototypeOf from 'shared/getPrototypeOf'; // Used for DEV messages to keep track of which parent rendered some props, // in case they error. export const jsxPropsParents: WeakMap<any, any> = new WeakMap(); export const jsxChildrenParents: WeakMap<any, any> = new WeakMap(); function isObjectPrototype(object: any): boolean { if (!object) { return false; } const ObjectPrototype = Object.prototype; if (object === ObjectPrototype) { return true; } // It might be an object from a different Realm which is // still just a plain simple object. if (getPrototypeOf(object)) { return false; } const names = Object.getOwnPropertyNames(object); for (let i = 0; i < names.length; i++) { if (!(names[i] in ObjectPrototype)) { return false; } } return true; } export function isSimpleObject(object: any): boolean { if (!isObjectPrototype(getPrototypeOf(object))) { return false; } const names = Object.getOwnPropertyNames(object); for (let i = 0; i < names.length; i++) { const descriptor = Object.getOwnPropertyDescriptor(object, names[i]); if (!descriptor) { return false; } if (!descriptor.enumerable) { if ( (names[i] === 'key' || names[i] === 'ref') && typeof descriptor.get === 'function' ) { // React adds key and ref getters to props objects to issue warnings. // Those getters will not be transferred to the client, but that's ok, // so we'll special case them. continue; } return false; } } return true; } export function objectName(object: mixed): string { // $FlowFixMe[method-unbinding] const name = Object.prototype.toString.call(object); return name.replace(/^\[object (.*)\]$/, function (m, p0) { return p0; }); } function describeKeyForErrorMessage(key: string): string { const encodedKey = JSON.stringify(key); return '"' + key + '"' === encodedKey ? key : encodedKey; } export function describeValueForErrorMessage(value: mixed): string { switch (typeof value) { case 'string': { return JSON.stringify( value.length <= 10 ? value : value.slice(0, 10) + '...', ); } case 'object': { if (isArray(value)) { return '[...]'; } const name = objectName(value); if (name === 'Object') { return '{...}'; } return name; } case 'function': return 'function'; default: // eslint-disable-next-line react-internal/safe-string-coercion return String(value); } } function describeElementType(type: any): string { if (typeof type === 'string') { return type; } switch (type) { case REACT_SUSPENSE_TYPE: return 'Suspense'; case REACT_SUSPENSE_LIST_TYPE: return 'SuspenseList'; } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_FORWARD_REF_TYPE: return describeElementType(type.render); case REACT_MEMO_TYPE: return describeElementType(type.type); case REACT_LAZY_TYPE: { const lazyComponent: LazyComponent<any, any> = (type: any); const payload = lazyComponent._payload; const init = lazyComponent._init; try { // Lazy may contain any component type so we recursively resolve it. return describeElementType(init(payload)); } catch (x) {} } } } return ''; } export function describeObjectForErrorMessage( objectOrArray: {+[key: string | number]: mixed, ...} | $ReadOnlyArray<mixed>, expandedName?: string, ): string { const objKind = objectName(objectOrArray); if (objKind !== 'Object' && objKind !== 'Array') { return objKind; } let str = ''; let start = -1; let length = 0; if (isArray(objectOrArray)) { if (__DEV__ && jsxChildrenParents.has(objectOrArray)) { // Print JSX Children const type = jsxChildrenParents.get(objectOrArray); str = '<' + describeElementType(type) + '>'; const array: $ReadOnlyArray<mixed> = objectOrArray; for (let i = 0; i < array.length; i++) { const value = array[i]; let substr; if (typeof value === 'string') { substr = value; } else if (typeof value === 'object' && value !== null) { substr = '{' + describeObjectForErrorMessage(value) + '}'; } else { substr = '{' + describeValueForErrorMessage(value) + '}'; } if ('' + i === expandedName) { start = str.length; length = substr.length; str += substr; } else if (substr.length < 15 && str.length + substr.length < 40) { str += substr; } else { str += '{...}'; } } str += '</' + describeElementType(type) + '>'; } else { // Print Array str = '['; const array: $ReadOnlyArray<mixed> = objectOrArray; for (let i = 0; i < array.length; i++) { if (i > 0) { str += ', '; } const value = array[i]; let substr; if (typeof value === 'object' && value !== null) { substr = describeObjectForErrorMessage(value); } else { substr = describeValueForErrorMessage(value); } if ('' + i === expandedName) { start = str.length; length = substr.length; str += substr; } else if (substr.length < 10 && str.length + substr.length < 40) { str += substr; } else { str += '...'; } } str += ']'; } } else { if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE) { str = '<' + describeElementType(objectOrArray.type) + '/>'; } else if (__DEV__ && jsxPropsParents.has(objectOrArray)) { // Print JSX const type = jsxPropsParents.get(objectOrArray); str = '<' + (describeElementType(type) || '...'); const object: {+[key: string | number]: mixed, ...} = objectOrArray; const names = Object.keys(object); for (let i = 0; i < names.length; i++) { str += ' '; const name = names[i]; str += describeKeyForErrorMessage(name) + '='; const value = object[name]; let substr; if ( name === expandedName && typeof value === 'object' && value !== null ) { substr = describeObjectForErrorMessage(value); } else { substr = describeValueForErrorMessage(value); } if (typeof value !== 'string') { substr = '{' + substr + '}'; } if (name === expandedName) { start = str.length; length = substr.length; str += substr; } else if (substr.length < 10 && str.length + substr.length < 40) { str += substr; } else { str += '...'; } } str += '>'; } else { // Print Object str = '{'; const object: {+[key: string | number]: mixed, ...} = objectOrArray; const names = Object.keys(object); for (let i = 0; i < names.length; i++) { if (i > 0) { str += ', '; } const name = names[i]; str += describeKeyForErrorMessage(name) + ': '; const value = object[name]; let substr; if (typeof value === 'object' && value !== null) { substr = describeObjectForErrorMessage(value); } else { substr = describeValueForErrorMessage(value); } if (name === expandedName) { start = str.length; length = substr.length; str += substr; } else if (substr.length < 10 && str.length + substr.length < 40) { str += substr; } else { str += '...'; } } str += '}'; } } if (expandedName === undefined) { return str; } if (start > -1 && length > 0) { const highlight = ' '.repeat(start) + '^'.repeat(length); return '\n ' + str + '\n ' + highlight; } return '\n ' + str; }
28.541667
79
0.55519
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 ReactNoop; let JSXDEVRuntime; let waitForAll; describe('ReactDeprecationWarnings', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; if (__DEV__) { JSXDEVRuntime = require('react/jsx-dev-runtime'); } }); it('should warn when given defaultProps', async () => { function FunctionalComponent(props) { return null; } FunctionalComponent.defaultProps = { testProp: true, }; ReactNoop.render(<FunctionalComponent />); await expect(async () => await waitForAll([])).toErrorDev( 'Warning: FunctionalComponent: Support for defaultProps ' + 'will be removed from function components in a future major ' + 'release. Use JavaScript default parameters instead.', ); }); it('should warn when given defaultProps on a memoized function', async () => { const MemoComponent = React.memo(function FunctionalComponent(props) { return null; }); MemoComponent.defaultProps = { testProp: true, }; ReactNoop.render( <div> <MemoComponent /> </div>, ); await expect(async () => await waitForAll([])).toErrorDev( 'Warning: FunctionalComponent: Support for defaultProps ' + 'will be removed from memo components in a future major ' + 'release. Use JavaScript default parameters instead.', ); }); it('should warn when given string refs', async () => { class RefComponent extends React.Component { render() { return null; } } class Component extends React.Component { render() { return <RefComponent ref="refComponent" />; } } ReactNoop.render(<Component />); await expect(async () => await waitForAll([])).toErrorDev( 'Warning: Component "Component" contains the string ref "refComponent". ' + 'Support for string refs will be removed in a future major release. ' + 'We recommend using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref' + '\n in Component (at **)', ); }); it('should warn when owner and self are the same for string refs', async () => { class RefComponent extends React.Component { render() { return null; } } class Component extends React.Component { render() { return <RefComponent ref="refComponent" __self={this} />; } } expect(() => { ReactNoop.renderLegacySyncRoot(<Component />); }).toErrorDev([ 'Component "Component" contains the string ref "refComponent". Support for string refs will be removed in a future major release.', ]); await waitForAll([]); }); it('should warn when owner and self are different for string refs', async () => { class RefComponent extends React.Component { render() { return null; } } class Component extends React.Component { render() { return <RefComponent ref="refComponent" __self={{}} />; } } ReactNoop.render(<Component />); await expect(async () => await waitForAll([])).toErrorDev([ 'Warning: Component "Component" contains the string ref "refComponent". ' + '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', ]); }); if (__DEV__) { it('should warn when owner and self are different for string refs', async () => { class RefComponent extends React.Component { render() { return null; } } class Component extends React.Component { render() { return JSXDEVRuntime.jsxDEV( RefComponent, {ref: 'refComponent'}, null, false, {}, {}, ); } } ReactNoop.render(<Component />); await expect(async () => await waitForAll([])).toErrorDev( 'Warning: Component "Component" contains the string ref "refComponent". ' + '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', ); }); } });
30.243902
137
0.609018
null
'use strict'; const {join} = require('path'); async function build(reactPath, asyncCopyTo) { // copy the UMD bundles await asyncCopyTo( join(reactPath, 'build', 'dist', 'react.production.min.js'), join(__dirname, 'react.production.min.js') ); await asyncCopyTo( join(reactPath, 'build', 'dist', 'react-dom.production.min.js'), join(__dirname, 'react-dom.production.min.js') ); } module.exports = build;
23.055556
68
0.662037
owtf
'use strict'; const {esNextPaths} = require('./scripts/shared/pathsByLanguageVersion'); module.exports = { bracketSpacing: false, singleQuote: true, bracketSameLine: true, trailingComma: 'es5', printWidth: 80, parser: 'flow', arrowParens: 'avoid', overrides: [ { files: esNextPaths, options: { trailingComma: 'all', }, }, ], };
16.409091
73
0.615183
hackipy
'use strict'; throw new Error( 'The React Server Writer cannot be used outside a react-server environment. ' + 'You must configure Node.js using the `--conditions react-server` flag.' );
26.857143
81
0.716495
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. * * @flow */ 'use strict'; export * from './src/ReactCacheOld';
18.769231
66
0.683594
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 */ /** * This is a renderer of React that doesn't have a render target output. * It is useful to demonstrate the internals of the reconciler in isolation * and for testing semantics of reconciliation separate from the host * environment. */ import ReactFiberReconciler from 'react-reconciler'; import createReactNoop from './createReactNoop'; export const { _Scheduler, getChildren, dangerouslyGetChildren, getPendingChildren, dangerouslyGetPendingChildren, getOrCreateRootContainer, createRoot, createLegacyRoot, getChildrenAsJSX, getPendingChildrenAsJSX, getSuspenseyThingStatus, resolveSuspenseyThing, resetSuspenseyThingCache, createPortal, render, renderLegacySyncRoot, renderToRootWithID, unmountRootWithID, findInstance, flushNextYield, startTrackingHostCounters, stopTrackingHostCounters, expire, flushExpired, batchedUpdates, deferredUpdates, discreteUpdates, idleUpdates, flushDiscreteUpdates, flushSync, flushPassiveEffects, act, dumpTree, getRoot, // TODO: Remove this once callers migrate to alternatives. // This should only be used by React internals. unstable_runWithPriority, } = createReactNoop( ReactFiberReconciler, // reconciler false, // useMutation );
22.580645
75
0.765914
ShonyDanza
/** * 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} from 'react'; import {ProfilerContext} from './ProfilerContext'; import Button from '../Button'; import ButtonIcon from '../ButtonIcon'; import {StoreContext} from '../context'; import {TimelineContext} from 'react-devtools-timeline/src/TimelineContext'; export default function ClearProfilingDataButton(): React.Node { const store = useContext(StoreContext); const {didRecordCommits, isProfiling} = useContext(ProfilerContext); const {file, setFile} = useContext(TimelineContext); const {profilerStore} = store; const doesHaveInMemoryData = didRecordCommits; const doesHaveUserTimingData = file !== null; const clear = () => { if (doesHaveInMemoryData) { profilerStore.clear(); } if (doesHaveUserTimingData) { setFile(null); } }; return ( <Button disabled={ isProfiling || !(doesHaveInMemoryData || doesHaveUserTimingData) } onClick={clear} title="Clear profiling data"> <ButtonIcon type="clear" /> </Button> ); }
26.021277
76
0.687943
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 * as React from 'react'; import {useCallback, useContext, useMemo, useState} from 'react'; import AutoSizer from 'react-virtualized-auto-sizer'; import {FixedSizeList} from 'react-window'; import {ProfilerContext} from './ProfilerContext'; import NoCommitData from './NoCommitData'; import CommitRankedListItem from './CommitRankedListItem'; import HoveredFiberInfo from './HoveredFiberInfo'; import {scale} from './utils'; import {StoreContext} from '../context'; import {SettingsContext} from '../Settings/SettingsContext'; import {useHighlightNativeElement} from '../hooks'; import Tooltip from './Tooltip'; import styles from './CommitRanked.css'; import type {TooltipFiberData} from './HoveredFiberInfo'; import type {ChartData} from './RankedChartBuilder'; import type {CommitTree} from './types'; export type ItemData = { chartData: ChartData, onElementMouseEnter: (fiberData: TooltipFiberData) => void, onElementMouseLeave: () => void, scaleX: (value: number, fallbackValue: number) => number, selectedFiberID: number | null, selectedFiberIndex: number, selectFiber: (id: number | null, name: string | null) => void, width: number, }; export default function CommitRankedAutoSizer(_: {}): React.Node { const {profilerStore} = useContext(StoreContext); const {rootID, selectedCommitIndex, selectFiber} = useContext(ProfilerContext); const {profilingCache} = profilerStore; const deselectCurrentFiber = useCallback( (event: $FlowFixMe) => { event.stopPropagation(); selectFiber(null, null); }, [selectFiber], ); let commitTree: CommitTree | null = null; let chartData: ChartData | null = null; if (selectedCommitIndex !== null) { commitTree = profilingCache.getCommitTree({ commitIndex: selectedCommitIndex, rootID: ((rootID: any): number), }); chartData = profilingCache.getRankedChartData({ commitIndex: selectedCommitIndex, commitTree, rootID: ((rootID: any): number), }); } if (commitTree != null && chartData != null && chartData.nodes.length > 0) { return ( <div className={styles.Container} onClick={deselectCurrentFiber}> <AutoSizer> {({height, width}) => ( <CommitRanked chartData={((chartData: any): ChartData)} commitTree={((commitTree: any): CommitTree)} height={height} width={width} /> )} </AutoSizer> </div> ); } else { return <NoCommitData />; } } type Props = { chartData: ChartData, commitTree: CommitTree, height: number, width: number, }; function CommitRanked({chartData, commitTree, height, width}: Props) { const [hoveredFiberData, setHoveredFiberData] = useState<TooltipFiberData | null>(null); const {lineHeight} = useContext(SettingsContext); const {selectedFiberID, selectFiber} = useContext(ProfilerContext); const {highlightNativeElement, clearHighlightNativeElement} = useHighlightNativeElement(); const selectedFiberIndex = useMemo( () => getNodeIndex(chartData, selectedFiberID), [chartData, selectedFiberID], ); const handleElementMouseEnter = useCallback( ({id, name}: $FlowFixMe) => { highlightNativeElement(id); // Highlight last hovered element. setHoveredFiberData({id, name}); // Set hovered fiber data for tooltip }, [highlightNativeElement], ); const handleElementMouseLeave = useCallback(() => { clearHighlightNativeElement(); // clear highlighting of element on mouse leave setHoveredFiberData(null); // clear hovered fiber data for tooltip }, [clearHighlightNativeElement]); const itemData = useMemo<ItemData>( () => ({ chartData, onElementMouseEnter: handleElementMouseEnter, onElementMouseLeave: handleElementMouseLeave, scaleX: scale(0, chartData.nodes[selectedFiberIndex].value, 0, width), selectedFiberID, selectedFiberIndex, selectFiber, width, }), [ chartData, handleElementMouseEnter, handleElementMouseLeave, selectedFiberID, selectedFiberIndex, selectFiber, width, ], ); // Tooltip used to show summary of fiber info on hover const tooltipLabel = useMemo( () => hoveredFiberData !== null ? ( <HoveredFiberInfo fiberData={hoveredFiberData} /> ) : null, [hoveredFiberData], ); return ( <Tooltip label={tooltipLabel}> <FixedSizeList height={height} innerElementType="svg" itemCount={chartData.nodes.length} itemData={itemData} itemSize={lineHeight} width={width}> {CommitRankedListItem} </FixedSizeList> </Tooltip> ); } const getNodeIndex = (chartData: ChartData, id: number | null): number => { if (id === null) { return 0; } const {nodes} = chartData; for (let index = 0; index < nodes.length; index++) { if (nodes[index].id === id) { return index; } } return 0; };
27.939227
82
0.665457
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. */ import Transform from 'art/core/transform'; import Mode from 'art/modes/current'; import {TYPES, EVENT_TYPES, childrenAsString} from './ReactARTInternals'; import {DefaultEventPriority} from 'react-reconciler/src/ReactEventPriorities'; const pooledTransform = new Transform(); const NO_CONTEXT = {}; if (__DEV__) { Object.freeze(NO_CONTEXT); } /** Helper Methods */ function addEventListeners(instance, type, listener) { // We need to explicitly unregister before unmount. // For this reason we need to track subscriptions. if (!instance._listeners) { instance._listeners = {}; instance._subscriptions = {}; } instance._listeners[type] = listener; if (listener) { if (!instance._subscriptions[type]) { instance._subscriptions[type] = instance.subscribe( type, createEventHandler(instance), instance, ); } } else { if (instance._subscriptions[type]) { instance._subscriptions[type](); delete instance._subscriptions[type]; } } } function createEventHandler(instance) { return function handleEvent(event) { const listener = instance._listeners[event.type]; if (!listener) { // Noop } else if (typeof listener === 'function') { listener.call(instance, event); } else if (listener.handleEvent) { listener.handleEvent(event); } }; } function destroyEventListeners(instance) { if (instance._subscriptions) { for (const type in instance._subscriptions) { instance._subscriptions[type](); } } instance._subscriptions = null; instance._listeners = null; } function getScaleX(props) { if (props.scaleX != null) { return props.scaleX; } else if (props.scale != null) { return props.scale; } else { return 1; } } function getScaleY(props) { if (props.scaleY != null) { return props.scaleY; } else if (props.scale != null) { return props.scale; } else { return 1; } } function isSameFont(oldFont, newFont) { if (oldFont === newFont) { return true; } else if (typeof newFont === 'string' || typeof oldFont === 'string') { return false; } else { return ( newFont.fontSize === oldFont.fontSize && newFont.fontStyle === oldFont.fontStyle && newFont.fontVariant === oldFont.fontVariant && newFont.fontWeight === oldFont.fontWeight && newFont.fontFamily === oldFont.fontFamily ); } } /** Render Methods */ function applyClippingRectangleProps(instance, props, prevProps = {}) { applyNodeProps(instance, props, prevProps); instance.width = props.width; instance.height = props.height; } function applyGroupProps(instance, props, prevProps = {}) { applyNodeProps(instance, props, prevProps); instance.width = props.width; instance.height = props.height; } function applyNodeProps(instance, props, prevProps = {}) { const scaleX = getScaleX(props); const scaleY = getScaleY(props); pooledTransform .transformTo(1, 0, 0, 1, 0, 0) .move(props.x || 0, props.y || 0) .rotate(props.rotation || 0, props.originX, props.originY) .scale(scaleX, scaleY, props.originX, props.originY); if (props.transform != null) { pooledTransform.transform(props.transform); } if ( instance.xx !== pooledTransform.xx || instance.yx !== pooledTransform.yx || instance.xy !== pooledTransform.xy || instance.yy !== pooledTransform.yy || instance.x !== pooledTransform.x || instance.y !== pooledTransform.y ) { instance.transformTo(pooledTransform); } if (props.cursor !== prevProps.cursor || props.title !== prevProps.title) { instance.indicate(props.cursor, props.title); } if (instance.blend && props.opacity !== prevProps.opacity) { instance.blend(props.opacity == null ? 1 : props.opacity); } if (props.visible !== prevProps.visible) { if (props.visible == null || props.visible) { instance.show(); } else { instance.hide(); } } for (const type in EVENT_TYPES) { addEventListeners(instance, EVENT_TYPES[type], props[type]); } } function applyRenderableNodeProps(instance, props, prevProps = {}) { applyNodeProps(instance, props, prevProps); if (prevProps.fill !== props.fill) { if (props.fill && props.fill.applyFill) { props.fill.applyFill(instance); } else { instance.fill(props.fill); } } if ( prevProps.stroke !== props.stroke || prevProps.strokeWidth !== props.strokeWidth || prevProps.strokeCap !== props.strokeCap || prevProps.strokeJoin !== props.strokeJoin || // TODO: Consider deep check of stokeDash; may benefit VML in IE. prevProps.strokeDash !== props.strokeDash ) { instance.stroke( props.stroke, props.strokeWidth, props.strokeCap, props.strokeJoin, props.strokeDash, ); } } function applyShapeProps(instance, props, prevProps = {}) { applyRenderableNodeProps(instance, props, prevProps); const path = props.d || childrenAsString(props.children); const prevDelta = instance._prevDelta; const prevPath = instance._prevPath; if ( path !== prevPath || path.delta !== prevDelta || prevProps.height !== props.height || prevProps.width !== props.width ) { instance.draw(path, props.width, props.height); instance._prevDelta = path.delta; instance._prevPath = path; } } function applyTextProps(instance, props, prevProps = {}) { applyRenderableNodeProps(instance, props, prevProps); const string = props.children; if ( instance._currentString !== string || !isSameFont(props.font, prevProps.font) || props.alignment !== prevProps.alignment || props.path !== prevProps.path ) { instance.draw(string, props.font, props.alignment, props.path); instance._currentString = string; } } export * from 'react-reconciler/src/ReactFiberConfigWithNoPersistence'; export * from 'react-reconciler/src/ReactFiberConfigWithNoHydration'; export * from 'react-reconciler/src/ReactFiberConfigWithNoScopes'; export * from 'react-reconciler/src/ReactFiberConfigWithNoTestSelectors'; export * from 'react-reconciler/src/ReactFiberConfigWithNoMicrotasks'; export * from 'react-reconciler/src/ReactFiberConfigWithNoResources'; export * from 'react-reconciler/src/ReactFiberConfigWithNoSingletons'; export function appendInitialChild(parentInstance, child) { if (typeof child === 'string') { // Noop for string children of Text (eg <Text>{'foo'}{'bar'}</Text>) throw new Error('Text children should already be flattened.'); } child.inject(parentInstance); } export function createInstance(type, props, internalInstanceHandle) { let instance; switch (type) { case TYPES.CLIPPING_RECTANGLE: instance = Mode.ClippingRectangle(); instance._applyProps = applyClippingRectangleProps; break; case TYPES.GROUP: instance = Mode.Group(); instance._applyProps = applyGroupProps; break; case TYPES.SHAPE: instance = Mode.Shape(); instance._applyProps = applyShapeProps; break; case TYPES.TEXT: instance = Mode.Text( props.children, props.font, props.alignment, props.path, ); instance._applyProps = applyTextProps; break; } if (!instance) { throw new Error(`ReactART does not support the type "${type}"`); } instance._applyProps(instance, props); return instance; } export function createTextInstance( text, rootContainerInstance, internalInstanceHandle, ) { return text; } export function finalizeInitialChildren(domElement, type, props) { return false; } export function getPublicInstance(instance) { return instance; } export function prepareForCommit() { // Noop return null; } export function resetAfterCommit() { // Noop } export function resetTextContent(domElement) { // Noop } export function getRootHostContext() { return NO_CONTEXT; } export function getChildHostContext() { return NO_CONTEXT; } export const scheduleTimeout = setTimeout; export const cancelTimeout = clearTimeout; export const noTimeout = -1; export function shouldSetTextContent(type, props) { return ( typeof props.children === 'string' || typeof props.children === 'number' ); } export function getCurrentEventPriority() { return DefaultEventPriority; } export function shouldAttemptEagerTransition() { return false; } // The ART renderer is secondary to the React DOM renderer. export const isPrimaryRenderer = false; // The ART renderer shouldn't trigger missing act() warnings export const warnsIfNotActing = false; export const supportsMutation = true; export function appendChild(parentInstance, child) { if (child.parentNode === parentInstance) { child.eject(); } child.inject(parentInstance); } export function appendChildToContainer(parentInstance, child) { if (child.parentNode === parentInstance) { child.eject(); } child.inject(parentInstance); } export function insertBefore(parentInstance, child, beforeChild) { if (child === beforeChild) { throw new Error('ReactART: Can not insert node before itself'); } child.injectBefore(beforeChild); } export function insertInContainerBefore(parentInstance, child, beforeChild) { if (child === beforeChild) { throw new Error('ReactART: Can not insert node before itself'); } child.injectBefore(beforeChild); } export function removeChild(parentInstance, child) { destroyEventListeners(child); child.eject(); } export function removeChildFromContainer(parentInstance, child) { destroyEventListeners(child); child.eject(); } export function commitTextUpdate(textInstance, oldText, newText) { // Noop } export function commitMount(instance, type, newProps) { // Noop } export function commitUpdate( instance, updatePayload, type, oldProps, newProps, ) { instance._applyProps(instance, newProps, oldProps); } export function hideInstance(instance) { instance.hide(); } export function hideTextInstance(textInstance) { // Noop } export function unhideInstance(instance, props) { if (props.visible == null || props.visible) { instance.show(); } } export function unhideTextInstance(textInstance, text): void { // Noop } export function clearContainer(container) { // TODO Implement this } export function getInstanceFromNode(node) { throw new Error('Not implemented.'); } export function beforeActiveInstanceBlur(internalInstanceHandle: Object) { // noop } export function afterActiveInstanceBlur() { // noop } export function preparePortalMount(portalInstance: any): void { // noop } // eslint-disable-next-line no-undef export function detachDeletedInstance(node: Instance): void { // noop } export function requestPostPaintCallback(callback: (time: number) => void) { // noop } export function maySuspendCommit(type, props) { return false; } export function preloadInstance(type, props) { // Return true to indicate it's already loaded return true; } export function startSuspendingCommit() {} export function suspendInstance(type, props) {} export function waitForCommitToBeReady() { return null; } export const NotPendingTransition = null;
22.90795
79
0.692395
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ListItem = ListItem; exports.List = List; var React = _interopRequireWildcard(require("react")); var _jsxFileName = ""; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function ListItem({ item, removeItem, toggleItem }) { const handleDelete = (0, React.useCallback)(() => { removeItem(item); }, [item, removeItem]); const handleToggle = (0, React.useCallback)(() => { toggleItem(item); }, [item, toggleItem]); return /*#__PURE__*/React.createElement("li", { __source: { fileName: _jsxFileName, lineNumber: 23, columnNumber: 5 } }, /*#__PURE__*/React.createElement("button", { onClick: handleDelete, __source: { fileName: _jsxFileName, lineNumber: 24, columnNumber: 7 } }, "Delete"), /*#__PURE__*/React.createElement("label", { __source: { fileName: _jsxFileName, lineNumber: 25, columnNumber: 7 } }, /*#__PURE__*/React.createElement("input", { checked: item.isComplete, onChange: handleToggle, type: "checkbox", __source: { fileName: _jsxFileName, lineNumber: 26, columnNumber: 9 } }), ' ', item.text)); } function List(props) { const [newItemText, setNewItemText] = (0, React.useState)(''); const [items, setItems] = (0, React.useState)([{ id: 1, isComplete: true, text: 'First' }, { id: 2, isComplete: true, text: 'Second' }, { id: 3, isComplete: false, text: 'Third' }]); const [uid, setUID] = (0, React.useState)(4); const handleClick = (0, React.useCallback)(() => { if (newItemText !== '') { setItems([...items, { id: uid, isComplete: false, text: newItemText }]); setUID(uid + 1); setNewItemText(''); } }, [newItemText, items, uid]); const handleKeyPress = (0, React.useCallback)(event => { if (event.key === 'Enter') { handleClick(); } }, [handleClick]); const handleChange = (0, React.useCallback)(event => { setNewItemText(event.currentTarget.value); }, [setNewItemText]); const removeItem = (0, React.useCallback)(itemToRemove => setItems(items.filter(item => item !== itemToRemove)), [items]); const toggleItem = (0, React.useCallback)(itemToToggle => { // Dont use indexOf() // because editing props in DevTools creates a new Object. const index = items.findIndex(item => item.id === itemToToggle.id); setItems(items.slice(0, index).concat({ ...itemToToggle, isComplete: !itemToToggle.isComplete }).concat(items.slice(index + 1))); }, [items]); return /*#__PURE__*/React.createElement(React.Fragment, { __source: { fileName: _jsxFileName, lineNumber: 102, columnNumber: 5 } }, /*#__PURE__*/React.createElement("h1", { __source: { fileName: _jsxFileName, lineNumber: 103, columnNumber: 7 } }, "List"), /*#__PURE__*/React.createElement("input", { type: "text", placeholder: "New list item...", value: newItemText, onChange: handleChange, onKeyPress: handleKeyPress, __source: { fileName: _jsxFileName, lineNumber: 104, columnNumber: 7 } }), /*#__PURE__*/React.createElement("button", { disabled: newItemText === '', onClick: handleClick, __source: { fileName: _jsxFileName, lineNumber: 111, columnNumber: 7 } }, /*#__PURE__*/React.createElement("span", { role: "img", "aria-label": "Add item", __source: { fileName: _jsxFileName, lineNumber: 112, columnNumber: 9 } }, "Add")), /*#__PURE__*/React.createElement("ul", { __source: { fileName: _jsxFileName, lineNumber: 116, columnNumber: 7 } }, items.map(item => /*#__PURE__*/React.createElement(ListItem, { key: item.id, item: item, removeItem: removeItem, toggleItem: toggleItem, __source: { fileName: _jsxFileName, lineNumber: 118, columnNumber: 11 } })))); } //# sourceMappingURL=ToDoList.js.map?foo=bar&param=some_value
30.425
743
0.603939
owtf
import FixtureSet from '../../FixtureSet'; import TestCase from '../../TestCase'; import RangeKeyboardFixture from './RangeKeyboardFixture'; import RadioClickFixture from './RadioClickFixture'; import RadioGroupFixture from './RadioGroupFixture'; import RadioNameChangeFixture from './RadioNameChangeFixture'; import InputPlaceholderFixture from './InputPlaceholderFixture'; const React = window.React; class InputChangeEvents extends React.Component { render() { return ( <FixtureSet title="Input change events" description="Tests proper behavior of the onChange event for inputs"> <TestCase title="Range keyboard changes" description={` Range inputs should fire onChange events for keyboard events `}> <TestCase.Steps> <li>Focus range input</li> <li>change value via the keyboard arrow keys</li> </TestCase.Steps> <TestCase.ExpectedResult> The <code>onKeyDown</code> call count should be equal to the{' '} <code>onChange</code> call count. </TestCase.ExpectedResult> <RangeKeyboardFixture /> </TestCase> <TestCase title="Radio input clicks" description={` Radio inputs should only fire change events when the checked state changes. `} resolvedIn="16.0.0"> <TestCase.Steps> <li>Click on the Radio input (or label text)</li> </TestCase.Steps> <TestCase.ExpectedResult> The <code>onChange</code> call count should remain at 0 </TestCase.ExpectedResult> <RadioClickFixture /> </TestCase> <TestCase title="Uncontrolled radio groups" description={` Radio inputs should fire change events when the value moved to another named input `} introducedIn="15.6.0"> <TestCase.Steps> <li>Click on the "Radio 2"</li> <li>Click back to "Radio 1"</li> <li>Click back to "Radio 2"</li> </TestCase.Steps> <TestCase.ExpectedResult> The <code>onChange</code> call count increment on each value change (at least 3+) </TestCase.ExpectedResult> <RadioGroupFixture /> </TestCase> <TestCase title="Inputs with placeholders" description={` Text inputs with placeholders should not trigger changes when the placeholder is altered `} resolvedIn="15.0.0" resolvedBy="#5004" affectedBrowsers="IE9+"> <TestCase.Steps> <li>Click on the Text input</li> <li>Click on the "Change placeholder" button</li> </TestCase.Steps> <TestCase.ExpectedResult> The <code>onChange</code> call count should remain at 0 </TestCase.ExpectedResult> <InputPlaceholderFixture /> </TestCase> <TestCase title="Radio button groups with name changes" description={` A radio button group should have correct checked value when the names changes `} resolvedBy="#11227" affectedBrowsers="IE9+"> <TestCase.Steps> <li>Click the toggle button</li> </TestCase.Steps> <TestCase.ExpectedResult> The checked radio button should switch between the first and second radio button </TestCase.ExpectedResult> <RadioNameChangeFixture /> </TestCase> </FixtureSet> ); } } export default InputChangeEvents;
31.025641
79
0.585424
owtf
import semver from 'semver'; /** * Take a version from the window query string and load a specific * version of React. * * @example * http://localhost:3000?version=15.4.1 * (Loads React 15.4.1) */ function parseQuery(qstr) { var query = {}; var a = qstr.slice(1).split('&'); for (var i = 0; i < a.length; i++) { var b = a[i].split('='); query[decodeURIComponent(b[0])] = decodeURIComponent(b[1] || ''); } return query; } function loadScript(src) { let firstScript = document.getElementsByTagName('script')[0]; let scriptNode; return new Promise((resolve, reject) => { scriptNode = document.createElement('script'); scriptNode.async = 1; scriptNode.src = src; scriptNode.onload = () => resolve(); scriptNode.onerror = () => reject(new Error(`failed to load: ${src}`)); firstScript.parentNode.insertBefore(scriptNode, firstScript); }); } function getVersion() { let query = parseQuery(window.location.search); return query.version || 'local'; } export function reactPaths(version = getVersion()) { let query = parseQuery(window.location.search); let isProduction = query.production === 'true'; let environment = isProduction ? 'production.min' : 'development'; let reactPath = `react.${environment}.js`; let reactDOMPath = `react-dom.${environment}.js`; let reactDOMServerPath = `react-dom-server.browser.${environment}.js`; let needsCreateElement = true; let needsReactDOM = true; if (version !== 'local') { const {major, minor, prerelease} = semver(version); if (major === 0) { needsCreateElement = minor >= 12; needsReactDOM = minor >= 14; } const [preReleaseStage] = prerelease; // The file structure was updated in 16. This wasn't the case for alphas. // Load the old module location for anything less than 16 RC if (major >= 16 && !(minor === 0 && preReleaseStage === 'alpha')) { reactPath = 'https://unpkg.com/react@' + version + '/umd/react.' + environment + '.js'; reactDOMPath = 'https://unpkg.com/react-dom@' + version + '/umd/react-dom.' + environment + '.js'; reactDOMServerPath = 'https://unpkg.com/react-dom@' + version + '/umd/react-dom-server.browser' + environment; } else if (major > 0 || minor > 11) { reactPath = 'https://unpkg.com/react@' + version + '/dist/react.js'; reactDOMPath = 'https://unpkg.com/react-dom@' + version + '/dist/react-dom.js'; reactDOMServerPath = 'https://unpkg.com/react-dom@' + version + '/dist/react-dom-server.js'; } else { reactPath = 'https://cdnjs.cloudflare.com/ajax/libs/react/' + version + '/react.js'; } } return { reactPath, reactDOMPath, reactDOMServerPath, needsCreateElement, needsReactDOM, }; } export default function loadReact() { const {reactPath, reactDOMPath, needsReactDOM} = reactPaths(); let request = loadScript(reactPath); if (needsReactDOM) { request = request.then(() => loadScript(reactDOMPath)); } else { // Aliasing React to ReactDOM for compatibility. request = request.then(() => { window.ReactDOM = window.React; }); } return request; }
26.508333
80
0.617879
hackipy
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-server-dom-webpack-server.node.production.min.js'); } else { module.exports = require('./cjs/react-server-dom-webpack-server.node.development.js'); }
30.625
91
0.706349
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 type for SyntheticEvent class that includes private properties * @flow */ import type {Fiber} from 'react-reconciler/src/ReactInternalTypes'; import type {TopLevelType} from './TopLevelEventTypes'; export type DispatchConfig = { dependencies?: Array<TopLevelType>, phasedRegistrationNames: { bubbled: null | string, captured: null | string, skipBubbling?: ?boolean, }, registrationName?: string, }; export type CustomDispatchConfig = { phasedRegistrationNames: { bubbled: null, captured: null, skipBubbling?: ?boolean, }, registrationName?: string, customEvent: true, }; export type ReactSyntheticEvent = { dispatchConfig: DispatchConfig | CustomDispatchConfig, getPooled: ( dispatchConfig: DispatchConfig | CustomDispatchConfig, targetInst: Fiber, nativeTarget: Event, nativeEventTarget: EventTarget, ) => ReactSyntheticEvent, isPersistent: () => boolean, isPropagationStopped: () => boolean, _dispatchInstances?: null | Array<Fiber | null> | Fiber, _dispatchListeners?: null | Array<Function> | Function, _targetInst: Fiber, type: string, currentTarget: null | EventTarget, };
26.2
70
0.718175
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 = require('react'); let ReactDOM = require('react-dom'); let ReactDOMClient = require('react-dom/client'); let ReactDOMServer = require('react-dom/server'); let Scheduler = require('scheduler'); let act; let useEffect; let assertLog; let waitFor; let waitForAll; describe('ReactDOMRoot', () => { let container; beforeEach(() => { jest.resetModules(); container = document.createElement('div'); React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); ReactDOMServer = require('react-dom/server'); Scheduler = require('scheduler'); act = require('internal-test-utils').act; useEffect = React.useEffect; const InternalTestUtils = require('internal-test-utils'); assertLog = InternalTestUtils.assertLog; waitFor = InternalTestUtils.waitFor; waitForAll = InternalTestUtils.waitForAll; }); it('renders children', async () => { const root = ReactDOMClient.createRoot(container); root.render(<div>Hi</div>); await waitForAll([]); expect(container.textContent).toEqual('Hi'); }); it('warns if you import createRoot from react-dom', async () => { expect(() => ReactDOM.createRoot(container)).toErrorDev( 'You are importing createRoot from "react-dom" which is not supported. ' + 'You should instead import it from "react-dom/client".', { withoutStack: true, }, ); }); it('warns if you import hydrateRoot from react-dom', async () => { expect(() => ReactDOM.hydrateRoot(container, null)).toErrorDev( 'You are importing hydrateRoot from "react-dom" which is not supported. ' + 'You should instead import it from "react-dom/client".', { withoutStack: true, }, ); }); it('warns if a callback parameter is provided to render', async () => { const callback = jest.fn(); const root = ReactDOMClient.createRoot(container); expect(() => root.render(<div>Hi</div>, callback)).toErrorDev( 'render(...): does not support the second callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().', {withoutStack: true}, ); await waitForAll([]); expect(callback).not.toHaveBeenCalled(); }); it('warn if a container is passed to root.render(...)', async () => { function App() { return 'Child'; } const root = ReactDOMClient.createRoot(container); expect(() => root.render(<App />, {})).toErrorDev( 'You passed a second argument to root.render(...) but it only accepts ' + 'one argument.', { withoutStack: true, }, ); }); it('warn if a container is passed to root.render(...)', async () => { function App() { return 'Child'; } const root = ReactDOMClient.createRoot(container); expect(() => root.render(<App />, container)).toErrorDev( 'You passed a container to the second argument of root.render(...). ' + "You don't need to pass it again since you already passed it to create " + 'the root.', { withoutStack: true, }, ); }); it('warns if a callback parameter is provided to unmount', async () => { const callback = jest.fn(); const root = ReactDOMClient.createRoot(container); root.render(<div>Hi</div>); expect(() => root.unmount(callback)).toErrorDev( 'unmount(...): does not support a callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().', {withoutStack: true}, ); await waitForAll([]); expect(callback).not.toHaveBeenCalled(); }); it('unmounts children', async () => { const root = ReactDOMClient.createRoot(container); root.render(<div>Hi</div>); await waitForAll([]); expect(container.textContent).toEqual('Hi'); root.unmount(); await waitForAll([]); expect(container.textContent).toEqual(''); }); it('supports hydration', async () => { const markup = await new Promise(resolve => resolve( ReactDOMServer.renderToString( <div> <span className="extra" /> </div>, ), ), ); // Does not hydrate by default const container1 = document.createElement('div'); container1.innerHTML = markup; const root1 = ReactDOMClient.createRoot(container1); root1.render( <div> <span /> </div>, ); await waitForAll([]); const container2 = document.createElement('div'); container2.innerHTML = markup; ReactDOMClient.hydrateRoot( container2, <div> <span /> </div>, ); await expect(async () => await waitForAll([])).toErrorDev( 'Extra attributes', ); }); it('clears existing children with legacy API', async () => { container.innerHTML = '<div>a</div><div>b</div>'; ReactDOM.render( <div> <span>c</span> <span>d</span> </div>, container, ); expect(container.textContent).toEqual('cd'); ReactDOM.render( <div> <span>d</span> <span>c</span> </div>, container, ); await waitForAll([]); expect(container.textContent).toEqual('dc'); }); it('clears existing children', async () => { container.innerHTML = '<div>a</div><div>b</div>'; const root = ReactDOMClient.createRoot(container); root.render( <div> <span>c</span> <span>d</span> </div>, ); await waitForAll([]); expect(container.textContent).toEqual('cd'); root.render( <div> <span>d</span> <span>c</span> </div>, ); await waitForAll([]); expect(container.textContent).toEqual('dc'); }); it('throws a good message on invalid containers', () => { expect(() => { ReactDOMClient.createRoot(<div>Hi</div>); }).toThrow('createRoot(...): Target container is not a DOM element.'); }); it('warns when rendering with legacy API into createRoot() container', async () => { const root = ReactDOMClient.createRoot(container); root.render(<div>Hi</div>); await waitForAll([]); expect(container.textContent).toEqual('Hi'); expect(() => { ReactDOM.render(<div>Bye</div>, container); }).toErrorDev( [ // We care about this warning: 'You are calling ReactDOM.render() on a container that was previously ' + 'passed to ReactDOMClient.createRoot(). This is not supported. ' + 'Did you mean to call root.render(element)?', // This is more of a symptom but restructuring the code to avoid it isn't worth it: 'Replacing React-rendered children with a new root component.', ], {withoutStack: true}, ); await waitForAll([]); // This works now but we could disallow it: expect(container.textContent).toEqual('Bye'); }); it('warns when hydrating with legacy API into createRoot() container', async () => { const root = ReactDOMClient.createRoot(container); root.render(<div>Hi</div>); await waitForAll([]); expect(container.textContent).toEqual('Hi'); expect(() => { ReactDOM.hydrate(<div>Hi</div>, container); }).toErrorDev( [ // We care about this warning: 'You are calling ReactDOM.hydrate() on a container that was previously ' + 'passed to ReactDOMClient.createRoot(). This is not supported. ' + 'Did you mean to call hydrateRoot(container, element)?', // This is more of a symptom but restructuring the code to avoid it isn't worth it: 'Replacing React-rendered children with a new root component.', ], {withoutStack: true}, ); }); it('callback passed to legacy hydrate() API', () => { container.innerHTML = '<div>Hi</div>'; ReactDOM.hydrate(<div>Hi</div>, container, () => { Scheduler.log('callback'); }); expect(container.textContent).toEqual('Hi'); assertLog(['callback']); }); it('warns when unmounting with legacy API (no previous content)', async () => { const root = ReactDOMClient.createRoot(container); root.render(<div>Hi</div>); await waitForAll([]); expect(container.textContent).toEqual('Hi'); let unmounted = false; expect(() => { unmounted = ReactDOM.unmountComponentAtNode(container); }).toErrorDev( [ // We care about this warning: 'You are calling ReactDOM.unmountComponentAtNode() on a container that was previously ' + 'passed to ReactDOMClient.createRoot(). This is not supported. Did you mean to call root.unmount()?', // This is more of a symptom but restructuring the code to avoid it isn't worth it: "The node you're attempting to unmount was rendered by React and is not a top-level container.", ], {withoutStack: true}, ); expect(unmounted).toBe(false); await waitForAll([]); expect(container.textContent).toEqual('Hi'); root.unmount(); await waitForAll([]); expect(container.textContent).toEqual(''); }); it('warns when unmounting with legacy API (has previous content)', async () => { // Currently createRoot().render() doesn't clear this. container.appendChild(document.createElement('div')); // The rest is the same as test above. const root = ReactDOMClient.createRoot(container); root.render(<div>Hi</div>); await waitForAll([]); expect(container.textContent).toEqual('Hi'); let unmounted = false; expect(() => { unmounted = ReactDOM.unmountComponentAtNode(container); }).toErrorDev( [ 'Did you mean to call root.unmount()?', // This is more of a symptom but restructuring the code to avoid it isn't worth it: "The node you're attempting to unmount was rendered by React and is not a top-level container.", ], {withoutStack: true}, ); expect(unmounted).toBe(false); await waitForAll([]); expect(container.textContent).toEqual('Hi'); root.unmount(); await waitForAll([]); expect(container.textContent).toEqual(''); }); it('warns when passing legacy container to createRoot()', () => { ReactDOM.render(<div>Hi</div>, container); expect(() => { ReactDOMClient.createRoot(container); }).toErrorDev( 'You are calling ReactDOMClient.createRoot() on a container that was previously ' + 'passed to ReactDOM.render(). This is not supported.', {withoutStack: true}, ); }); it('warns when creating two roots managing the same container', () => { ReactDOMClient.createRoot(container); expect(() => { ReactDOMClient.createRoot(container); }).toErrorDev( 'You are calling ReactDOMClient.createRoot() on a container that ' + 'has already been passed to createRoot() before. Instead, call ' + 'root.render() on the existing root instead if you want to update it.', {withoutStack: true}, ); }); it('does not warn when creating second root after first one is unmounted', async () => { const root = ReactDOMClient.createRoot(container); root.unmount(); await waitForAll([]); ReactDOMClient.createRoot(container); // No warning }); it('warns if creating a root on the document.body', async () => { if (gate(flags => flags.enableFloat)) { // we no longer expect an error for this if float is enabled ReactDOMClient.createRoot(document.body); } else { expect(() => { ReactDOMClient.createRoot(document.body); }).toErrorDev( 'createRoot(): Creating roots directly with document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try using a container element created ' + 'for your app.', {withoutStack: true}, ); } }); it('warns if updating a root that has had its contents removed', async () => { const root = ReactDOMClient.createRoot(container); root.render(<div>Hi</div>); await waitForAll([]); container.innerHTML = ''; if (gate(flags => flags.enableFloat)) { // When either of these flags are on this validation is turned off so we // expect there to be no warnings root.render(<div>Hi</div>); } else { expect(() => { root.render(<div>Hi</div>); }).toErrorDev( 'render(...): It looks like the React-rendered content of the ' + 'root container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + "root.unmount() to empty a root's container.", {withoutStack: true}, ); } }); it('opts-in to concurrent default updates', async () => { const root = ReactDOMClient.createRoot(container, { unstable_concurrentUpdatesByDefault: true, }); function Foo({value}) { Scheduler.log(value); return <div>{value}</div>; } await act(() => { root.render(<Foo value="a" />); }); expect(container.textContent).toEqual('a'); await act(async () => { root.render(<Foo value="b" />); assertLog(['a']); expect(container.textContent).toEqual('a'); await waitFor(['b']); if (gate(flags => flags.allowConcurrentByDefault)) { expect(container.textContent).toEqual('a'); } else { expect(container.textContent).toEqual('b'); } }); expect(container.textContent).toEqual('b'); }); it('unmount is synchronous', async () => { const root = ReactDOMClient.createRoot(container); await act(() => { root.render('Hi'); }); expect(container.textContent).toEqual('Hi'); await act(() => { root.unmount(); // Should have already unmounted expect(container.textContent).toEqual(''); }); }); it('throws if an unmounted root is updated', async () => { const root = ReactDOMClient.createRoot(container); await act(() => { root.render('Hi'); }); expect(container.textContent).toEqual('Hi'); root.unmount(); expect(() => root.render("I'm back")).toThrow( 'Cannot update an unmounted root.', ); }); it('warns if root is unmounted inside an effect', async () => { const container1 = document.createElement('div'); const root1 = ReactDOMClient.createRoot(container1); const container2 = document.createElement('div'); const root2 = ReactDOMClient.createRoot(container2); function App({step}) { useEffect(() => { if (step === 2) { root2.unmount(); } }, [step]); return 'Hi'; } await act(() => { root1.render(<App step={1} />); }); expect(container1.textContent).toEqual('Hi'); expect(() => { ReactDOM.flushSync(() => { root1.render(<App step={2} />); }); }).toErrorDev( 'Attempted to synchronously unmount a root while React was ' + 'already rendering.', ); }); // @gate disableCommentsAsDOMContainers it('errors if container is a comment node', () => { // This is an old feature used by www. Disabled in the open source build. const div = document.createElement('div'); div.innerHTML = '<!-- react-mount-point-unstable -->'; const commentNode = div.childNodes[0]; expect(() => ReactDOMClient.createRoot(commentNode)).toThrow( 'createRoot(...): Target container is not a DOM element.', ); expect(() => ReactDOMClient.hydrateRoot(commentNode)).toThrow( 'hydrateRoot(...): Target container is not a DOM element.', ); // Still works in the legacy API ReactDOM.render(<div />, commentNode); }); it('warn if no children passed to hydrateRoot', async () => { expect(() => ReactDOMClient.hydrateRoot(container)).toErrorDev( 'Must provide initial children as second argument to hydrateRoot.', {withoutStack: true}, ); }); it('warn if JSX passed to createRoot', async () => { function App() { return 'Child'; } expect(() => ReactDOMClient.createRoot(container, <App />)).toErrorDev( 'You passed a JSX element to createRoot. You probably meant to call ' + 'root.render instead', { withoutStack: true, }, ); }); });
30.818702
111
0.613064
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 {REACT_FRAGMENT_TYPE} from 'shared/ReactSymbols'; import { jsxWithValidationStatic, jsxWithValidationDynamic, jsxWithValidation, } from './ReactJSXElementValidator'; import {jsx as jsxProd} from './ReactJSXElement'; const jsx: any = __DEV__ ? jsxWithValidationDynamic : jsxProd; // we may want to special case jsxs internally to take advantage of static children. // for now we can ship identical prod functions const jsxs: any = __DEV__ ? jsxWithValidationStatic : jsxProd; const jsxDEV: any = __DEV__ ? jsxWithValidation : undefined; export {REACT_FRAGMENT_TYPE as Fragment, jsx, jsxs, jsxDEV};
34.434783
84
0.740786
cybersecurity-penetration-testing
#!/usr/bin/env node /** * 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 */ const electron = require('electron'); const spawn = require('cross-spawn'); const argv = process.argv.slice(2); const pkg = require('./package.json'); const updateNotifier = require('update-notifier'); // Notify if there's an update in 7 days' interval const notifier = updateNotifier({ pkg, updateCheckInterval: 1000 * 60 * 60 * 24 * 7, }); if (notifier.update) { const updateMsg = `Update available ${notifier.update.current} -> ${notifier.update.latest}` + '\nTo update:' + '\n"npm i [-g] react-devtools" or "yarn add react-devtools"'; notifier.notify({defer: false, message: updateMsg}); } const result = spawn.sync(electron, [require.resolve('./app')].concat(argv), { stdio: 'ignore', }); process.exit(result.status);
25.351351
80
0.679671
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 Scheduler; let waitFor; let waitForAll; describe('ReactIncrementalReflection', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); const InternalTestUtils = require('internal-test-utils'); waitFor = InternalTestUtils.waitFor; waitForAll = InternalTestUtils.waitForAll; }); function div(...children) { children = children.map(c => typeof c === 'string' ? {text: c, hidden: false} : c, ); return {type: 'div', children, prop: undefined, hidden: false}; } function span(prop) { return {type: 'span', children: [], prop, hidden: false}; } it('handles isMounted even when the initial render is deferred', async () => { const instances = []; class Component extends React.Component { _isMounted() { // No longer a public API, but we can test that it works internally by // reaching into the updater. return this.updater.isMounted(this); } UNSAFE_componentWillMount() { instances.push(this); Scheduler.log('componentWillMount: ' + this._isMounted()); } componentDidMount() { Scheduler.log('componentDidMount: ' + this._isMounted()); } render() { return <span />; } } function Foo() { return <Component />; } React.startTransition(() => { ReactNoop.render(<Foo />); }); // Render part way through but don't yet commit the updates. await waitFor(['componentWillMount: false']); expect(instances[0]._isMounted()).toBe(false); // Render the rest and commit the updates. await waitForAll(['componentDidMount: true']); expect(instances[0]._isMounted()).toBe(true); }); it('handles isMounted when an unmount is deferred', async () => { const instances = []; class Component extends React.Component { _isMounted() { return this.updater.isMounted(this); } UNSAFE_componentWillMount() { instances.push(this); } componentWillUnmount() { Scheduler.log('componentWillUnmount: ' + this._isMounted()); } render() { Scheduler.log('Component'); return <span />; } } function Other() { Scheduler.log('Other'); return <span />; } function Foo(props) { return props.mount ? <Component /> : <Other />; } ReactNoop.render(<Foo mount={true} />); await waitForAll(['Component']); expect(instances[0]._isMounted()).toBe(true); React.startTransition(() => { ReactNoop.render(<Foo mount={false} />); }); // Render part way through but don't yet commit the updates so it is not // fully unmounted yet. await waitFor(['Other']); expect(instances[0]._isMounted()).toBe(true); // Finish flushing the unmount. await waitForAll(['componentWillUnmount: true']); expect(instances[0]._isMounted()).toBe(false); }); it('finds no node before insertion and correct node before deletion', async () => { let classInstance = null; function findInstance(inst) { // We ignore warnings fired by findInstance because we are testing // that the actual behavior still works as expected even though it // is deprecated. const oldConsoleError = console.error; console.error = jest.fn(); try { return ReactNoop.findInstance(inst); } finally { console.error = oldConsoleError; } } class Component extends React.Component { UNSAFE_componentWillMount() { classInstance = this; Scheduler.log(['componentWillMount', findInstance(this)]); } componentDidMount() { Scheduler.log(['componentDidMount', findInstance(this)]); } UNSAFE_componentWillUpdate() { Scheduler.log(['componentWillUpdate', findInstance(this)]); } componentDidUpdate() { Scheduler.log(['componentDidUpdate', findInstance(this)]); } componentWillUnmount() { Scheduler.log(['componentWillUnmount', findInstance(this)]); } render() { Scheduler.log('render'); return this.props.step < 2 ? ( <span ref={ref => (this.span = ref)} /> ) : this.props.step === 2 ? ( <div ref={ref => (this.div = ref)} /> ) : this.props.step === 3 ? null : this.props.step === 4 ? ( <div ref={ref => (this.span = ref)} /> ) : null; } } function Sibling() { // Sibling is used to assert that we've rendered past the first component. Scheduler.log('render sibling'); return <span />; } function Foo(props) { return [<Component key="a" step={props.step} />, <Sibling key="b" />]; } React.startTransition(() => { ReactNoop.render(<Foo step={0} />); }); // Flush past Component but don't complete rendering everything yet. await waitFor([['componentWillMount', null], 'render', 'render sibling']); expect(classInstance).toBeDefined(); // The instance has been complete but is still not committed so it should // not find any host nodes in it. expect(findInstance(classInstance)).toBe(null); await waitForAll([['componentDidMount', span()]]); const hostSpan = classInstance.span; expect(hostSpan).toBeDefined(); expect(findInstance(classInstance)).toBe(hostSpan); // Flush next step which will cause an update but not yet render a new host // node. ReactNoop.render(<Foo step={1} />); await waitForAll([ ['componentWillUpdate', hostSpan], 'render', 'render sibling', ['componentDidUpdate', hostSpan], ]); expect(ReactNoop.findInstance(classInstance)).toBe(hostSpan); // The next step will render a new host node but won't get committed yet. // We expect this to mutate the original Fiber. React.startTransition(() => { ReactNoop.render(<Foo step={2} />); }); await waitFor([ ['componentWillUpdate', hostSpan], 'render', 'render sibling', ]); // This should still be the host span. expect(ReactNoop.findInstance(classInstance)).toBe(hostSpan); // When we finally flush the tree it will get committed. await waitForAll([['componentDidUpdate', div()]]); const hostDiv = classInstance.div; expect(hostDiv).toBeDefined(); expect(hostSpan).not.toBe(hostDiv); // We should now find the new host node. expect(ReactNoop.findInstance(classInstance)).toBe(hostDiv); // Render to null but don't commit it yet. React.startTransition(() => { ReactNoop.render(<Foo step={3} />); }); await waitFor([ ['componentWillUpdate', hostDiv], 'render', 'render sibling', ]); // This should still be the host div since the deletion is not committed. expect(ReactNoop.findInstance(classInstance)).toBe(hostDiv); await waitForAll([['componentDidUpdate', null]]); // This should still be the host div since the deletion is not committed. expect(ReactNoop.findInstance(classInstance)).toBe(null); // Render a div again ReactNoop.render(<Foo step={4} />); await waitForAll([ ['componentWillUpdate', null], 'render', 'render sibling', ['componentDidUpdate', div()], ]); // Unmount the component. ReactNoop.render([]); await waitForAll([['componentWillUnmount', hostDiv]]); }); });
27.680147
85
0.617436
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 {ReactClientValue} from 'react-server/src/ReactFlightServer'; import type { ClientReference, ServerReference, } from './ReactFlightESMReferences'; export type {ClientReference, ServerReference}; export type ClientManifest = string; // base URL on the file system export type ServerReferenceId = string; export type ClientReferenceMetadata = [ string, // module path string, // export name ]; export type ClientReferenceKey = string; export {isClientReference, isServerReference} from './ReactFlightESMReferences'; export function getClientReferenceKey( reference: ClientReference<any>, ): ClientReferenceKey { return reference.$$id; } export function resolveClientReferenceMetadata<T>( config: ClientManifest, clientReference: ClientReference<T>, ): ClientReferenceMetadata { const baseURL: string = config; const id = clientReference.$$id; const idx = id.lastIndexOf('#'); const exportName = id.slice(idx + 1); const fullURL = id.slice(0, idx); if (!fullURL.startsWith(baseURL)) { throw new Error( 'Attempted to load a Client Module outside the hosted root.', ); } // Relative URL const modulePath = fullURL.slice(baseURL.length); return [modulePath, exportName]; } export function getServerReferenceId<T>( config: ClientManifest, serverReference: ServerReference<T>, ): ServerReferenceId { return serverReference.$$id; } export function getServerReferenceBoundArguments<T>( config: ClientManifest, serverReference: ServerReference<T>, ): null | Array<ReactClientValue> { return serverReference.$$bound; }
24.671429
80
0.742762
PenTestScripts
/** * 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 {TextDecoder} from 'util'; export type StringDecoder = TextDecoder; export function createStringDecoder(): StringDecoder { return new TextDecoder(); } const decoderOptions = {stream: true}; export function readPartialStringChunk( decoder: StringDecoder, buffer: Uint8Array, ): string { return decoder.decode(buffer, decoderOptions); } export function readFinalStringChunk( decoder: StringDecoder, buffer: Uint8Array, ): string { return decoder.decode(buffer); }
20
66
0.739884
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 {getElementDimensions, getNestedBoundingClientRect} from '../utils'; import type {Rect} from '../utils'; import type Agent from 'react-devtools-shared/src/backend/agent'; type Box = {top: number, left: number, width: number, height: number}; const assign = Object.assign; // Note that the Overlay components are not affected by the active Theme, // because they highlight elements in the main Chrome window (outside of devtools). // The colors below were chosen to roughly match those used by Chrome devtools. class OverlayRect { node: HTMLElement; border: HTMLElement; padding: HTMLElement; content: HTMLElement; constructor(doc: Document, container: HTMLElement) { this.node = doc.createElement('div'); this.border = doc.createElement('div'); this.padding = doc.createElement('div'); this.content = doc.createElement('div'); this.border.style.borderColor = overlayStyles.border; this.padding.style.borderColor = overlayStyles.padding; this.content.style.backgroundColor = overlayStyles.background; assign(this.node.style, { borderColor: overlayStyles.margin, pointerEvents: 'none', position: 'fixed', }); this.node.style.zIndex = '10000000'; this.node.appendChild(this.border); this.border.appendChild(this.padding); this.padding.appendChild(this.content); container.appendChild(this.node); } remove() { if (this.node.parentNode) { this.node.parentNode.removeChild(this.node); } } update(box: Rect, dims: any) { boxWrap(dims, 'margin', this.node); boxWrap(dims, 'border', this.border); boxWrap(dims, 'padding', this.padding); assign(this.content.style, { height: box.height - dims.borderTop - dims.borderBottom - dims.paddingTop - dims.paddingBottom + 'px', width: box.width - dims.borderLeft - dims.borderRight - dims.paddingLeft - dims.paddingRight + 'px', }); assign(this.node.style, { top: box.top - dims.marginTop + 'px', left: box.left - dims.marginLeft + 'px', }); } } class OverlayTip { tip: HTMLElement; nameSpan: HTMLElement; dimSpan: HTMLElement; constructor(doc: Document, container: HTMLElement) { this.tip = doc.createElement('div'); assign(this.tip.style, { display: 'flex', flexFlow: 'row nowrap', backgroundColor: '#333740', borderRadius: '2px', fontFamily: '"SFMono-Regular", Consolas, "Liberation Mono", Menlo, Courier, monospace', fontWeight: 'bold', padding: '3px 5px', pointerEvents: 'none', position: 'fixed', fontSize: '12px', whiteSpace: 'nowrap', }); this.nameSpan = doc.createElement('span'); this.tip.appendChild(this.nameSpan); assign(this.nameSpan.style, { color: '#ee78e6', borderRight: '1px solid #aaaaaa', paddingRight: '0.5rem', marginRight: '0.5rem', }); this.dimSpan = doc.createElement('span'); this.tip.appendChild(this.dimSpan); assign(this.dimSpan.style, { color: '#d7d7d7', }); this.tip.style.zIndex = '10000000'; container.appendChild(this.tip); } remove() { if (this.tip.parentNode) { this.tip.parentNode.removeChild(this.tip); } } updateText(name: string, width: number, height: number) { this.nameSpan.textContent = name; this.dimSpan.textContent = Math.round(width) + 'px × ' + Math.round(height) + 'px'; } updatePosition(dims: Box, bounds: Box) { const tipRect = this.tip.getBoundingClientRect(); const tipPos = findTipPos(dims, bounds, { width: tipRect.width, height: tipRect.height, }); assign(this.tip.style, tipPos.style); } } export default class Overlay { window: any; tipBoundsWindow: any; container: HTMLElement; tip: OverlayTip; rects: Array<OverlayRect>; agent: Agent; constructor(agent: Agent) { // Find the root window, because overlays are positioned relative to it. const currentWindow = window.__REACT_DEVTOOLS_TARGET_WINDOW__ || window; this.window = currentWindow; // When opened in shells/dev, the tooltip should be bound by the app iframe, not by the topmost window. const tipBoundsWindow = window.__REACT_DEVTOOLS_TARGET_WINDOW__ || window; this.tipBoundsWindow = tipBoundsWindow; const doc = currentWindow.document; this.container = doc.createElement('div'); this.container.style.zIndex = '10000000'; this.tip = new OverlayTip(doc, this.container); this.rects = []; this.agent = agent; doc.body.appendChild(this.container); } remove() { this.tip.remove(); this.rects.forEach(rect => { rect.remove(); }); this.rects.length = 0; if (this.container.parentNode) { this.container.parentNode.removeChild(this.container); } } inspect(nodes: Array<HTMLElement>, name?: ?string) { // We can't get the size of text nodes or comment nodes. React as of v15 // heavily uses comment nodes to delimit text. const elements = nodes.filter(node => node.nodeType === Node.ELEMENT_NODE); while (this.rects.length > elements.length) { const rect = this.rects.pop(); rect.remove(); } if (elements.length === 0) { return; } while (this.rects.length < elements.length) { this.rects.push(new OverlayRect(this.window.document, this.container)); } const outerBox = { top: Number.POSITIVE_INFINITY, right: Number.NEGATIVE_INFINITY, bottom: Number.NEGATIVE_INFINITY, left: Number.POSITIVE_INFINITY, }; elements.forEach((element, index) => { const box = getNestedBoundingClientRect(element, this.window); const dims = getElementDimensions(element); outerBox.top = Math.min(outerBox.top, box.top - dims.marginTop); outerBox.right = Math.max( outerBox.right, box.left + box.width + dims.marginRight, ); outerBox.bottom = Math.max( outerBox.bottom, box.top + box.height + dims.marginBottom, ); outerBox.left = Math.min(outerBox.left, box.left - dims.marginLeft); const rect = this.rects[index]; rect.update(box, dims); }); if (!name) { name = elements[0].nodeName.toLowerCase(); const node = elements[0]; const rendererInterface = this.agent.getBestMatchingRendererInterface(node); if (rendererInterface) { const id = rendererInterface.getFiberIDForNative(node, true); if (id) { const ownerName = rendererInterface.getDisplayNameForFiberID( id, true, ); if (ownerName) { name += ' (in ' + ownerName + ')'; } } } } this.tip.updateText( name, outerBox.right - outerBox.left, outerBox.bottom - outerBox.top, ); const tipBounds = getNestedBoundingClientRect( this.tipBoundsWindow.document.documentElement, this.window, ); this.tip.updatePosition( { top: outerBox.top, left: outerBox.left, height: outerBox.bottom - outerBox.top, width: outerBox.right - outerBox.left, }, { top: tipBounds.top + this.tipBoundsWindow.scrollY, left: tipBounds.left + this.tipBoundsWindow.scrollX, height: this.tipBoundsWindow.innerHeight, width: this.tipBoundsWindow.innerWidth, }, ); } } function findTipPos( dims: Box, bounds: Box, tipSize: {height: number, width: number}, ) { const tipHeight = Math.max(tipSize.height, 20); const tipWidth = Math.max(tipSize.width, 60); const margin = 5; let top: number | string; if (dims.top + dims.height + tipHeight <= bounds.top + bounds.height) { if (dims.top + dims.height < bounds.top + 0) { top = bounds.top + margin; } else { top = dims.top + dims.height + margin; } } else if (dims.top - tipHeight <= bounds.top + bounds.height) { if (dims.top - tipHeight - margin < bounds.top + margin) { top = bounds.top + margin; } else { top = dims.top - tipHeight - margin; } } else { top = bounds.top + bounds.height - tipHeight - margin; } let left: number | string = dims.left + margin; if (dims.left < bounds.left) { left = bounds.left + margin; } if (dims.left + tipWidth > bounds.left + bounds.width) { left = bounds.left + bounds.width - tipWidth - margin; } top += 'px'; left += 'px'; return { style: {top, left}, }; } function boxWrap(dims: any, what: string, node: HTMLElement) { assign(node.style, { borderTopWidth: dims[what + 'Top'] + 'px', borderLeftWidth: dims[what + 'Left'] + 'px', borderRightWidth: dims[what + 'Right'] + 'px', borderBottomWidth: dims[what + 'Bottom'] + 'px', borderStyle: 'solid', }); } const overlayStyles = { background: 'rgba(120, 170, 210, 0.7)', padding: 'rgba(77, 200, 0, 0.3)', margin: 'rgba(255, 155, 0, 0.3)', border: 'rgba(255, 200, 50, 0.3)', };
26.732143
107
0.629065
Tricks-Web-Penetration-Tester
// @flow import type {ComponentType} from "react"; import createListComponent from './createListComponent'; import type { Props, ScrollToAlign } from './createListComponent'; const FixedSizeList: ComponentType<Props<$FlowFixMe>> = createListComponent({ getItemOffset: ({ itemSize }: Props<any>, index: number): number => index * ((itemSize: any): number), getItemSize: ({ itemSize }: Props<any>, index: number): number => ((itemSize: any): number), getEstimatedTotalSize: ({ itemCount, itemSize }: Props<any>) => ((itemSize: any): number) * itemCount, getOffsetForIndexAndAlignment: ( { direction, height, itemCount, itemSize, layout, width }: Props<any>, index: number, align: ScrollToAlign, scrollOffset: number ): number => { // TODO Deprecate direction "horizontal" const isHorizontal = direction === 'horizontal' || layout === 'horizontal'; const size = (((isHorizontal ? width : height): any): number); const lastItemOffset = Math.max( 0, itemCount * ((itemSize: any): number) - size ); const maxOffset = Math.min( lastItemOffset, index * ((itemSize: any): number) ); const minOffset = Math.max( 0, index * ((itemSize: any): number) - size + ((itemSize: any): number) ); if (align === 'smart') { if ( scrollOffset >= minOffset - size && scrollOffset <= maxOffset + size ) { align = 'auto'; } else { align = 'center'; } } switch (align) { case 'start': return maxOffset; case 'end': return minOffset; case 'center': { // "Centered" offset is usually the average of the min and max. // But near the edges of the list, this doesn't hold true. const middleOffset = Math.round( minOffset + (maxOffset - minOffset) / 2 ); if (middleOffset < Math.ceil(size / 2)) { return 0; // near the beginning } else if (middleOffset > lastItemOffset + Math.floor(size / 2)) { return lastItemOffset; // near the end } else { return middleOffset; } } case 'auto': default: if (scrollOffset >= minOffset && scrollOffset <= maxOffset) { return scrollOffset; } else if (scrollOffset < minOffset) { return minOffset; } else { return maxOffset; } } }, getStartIndexForOffset: ( { itemCount, itemSize }: Props<any>, offset: number ): number => Math.max( 0, Math.min(itemCount - 1, Math.floor(offset / ((itemSize: any): number))) ), getStopIndexForStartIndex: ( { direction, height, itemCount, itemSize, layout, width }: Props<any>, startIndex: number, scrollOffset: number ): number => { // TODO Deprecate direction "horizontal" const isHorizontal = direction === 'horizontal' || layout === 'horizontal'; const offset = startIndex * ((itemSize: any): number); const size = (((isHorizontal ? width : height): any): number); const numVisibleItems = Math.ceil( (size + scrollOffset - offset) / ((itemSize: any): number) ); return Math.max( 0, Math.min( itemCount - 1, startIndex + numVisibleItems - 1 // -1 is because stop index is inclusive ) ); }, initInstanceProps(props: Props<any>): any { // Noop }, shouldResetStyleCacheOnItemSizeChange: true, validateProps: ({ itemSize }: Props<any>): void => { if (process.env.NODE_ENV !== 'production') { if (typeof itemSize !== 'number') { throw Error( 'An invalid "itemSize" prop has been specified. ' + 'Value should be a number. ' + `"${itemSize === null ? 'null' : typeof itemSize}" was specified.` ); } } }, }); export default FixedSizeList;
28.255639
81
0.584319
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 */ // This client file is in the shared folder because it applies to both SSR and browser contexts. // It is the configuration of the FlightClient behavior which can run in either environment. import type {HintCode, HintModel} from '../server/ReactFlightServerConfigDOM'; import ReactDOMSharedInternals from 'shared/ReactDOMSharedInternals'; const ReactDOMCurrentDispatcher = ReactDOMSharedInternals.Dispatcher; import {getCrossOriginString} from './crossOriginStrings'; export function dispatchHint<Code: HintCode>( code: Code, model: HintModel<Code>, ): void { const dispatcher = ReactDOMCurrentDispatcher.current; if (dispatcher) { switch (code) { case 'D': { const refined = refineModel(code, model); const href = refined; dispatcher.prefetchDNS(href); return; } case 'C': { const refined = refineModel(code, model); if (typeof refined === 'string') { const href = refined; dispatcher.preconnect(href); } else { const href = refined[0]; const crossOrigin = refined[1]; dispatcher.preconnect(href, crossOrigin); } return; } case 'L': { const refined = refineModel(code, model); const href = refined[0]; const as = refined[1]; if (refined.length === 3) { const options = refined[2]; dispatcher.preload(href, as, options); } else { dispatcher.preload(href, as); } return; } case 'm': { const refined = refineModel(code, model); if (typeof refined === 'string') { const href = refined; dispatcher.preloadModule(href); } else { const href = refined[0]; const options = refined[1]; dispatcher.preloadModule(href, options); } return; } case 'S': { const refined = refineModel(code, model); if (typeof refined === 'string') { const href = refined; dispatcher.preinitStyle(href); } else { const href = refined[0]; const precedence = refined[1] === 0 ? undefined : refined[1]; const options = refined.length === 3 ? refined[2] : undefined; dispatcher.preinitStyle(href, precedence, options); } return; } case 'X': { const refined = refineModel(code, model); if (typeof refined === 'string') { const href = refined; dispatcher.preinitScript(href); } else { const href = refined[0]; const options = refined[1]; dispatcher.preinitScript(href, options); } return; } case 'M': { const refined = refineModel(code, model); if (typeof refined === 'string') { const href = refined; dispatcher.preinitModuleScript(href); } else { const href = refined[0]; const options = refined[1]; dispatcher.preinitModuleScript(href, options); } return; } } } } // Flow is having trouble refining the HintModels so we help it a bit. // This should be compiled out in the production build. function refineModel<T>(code: T, model: HintModel<any>): HintModel<T> { return model; } export function preinitModuleForSSR( href: string, nonce: ?string, crossOrigin: ?string, ) { const dispatcher = ReactDOMCurrentDispatcher.current; if (dispatcher) { dispatcher.preinitModuleScript(href, { crossOrigin: getCrossOriginString(crossOrigin), nonce, }); } } export function preinitScriptForSSR( href: string, nonce: ?string, crossOrigin: ?string, ) { const dispatcher = ReactDOMCurrentDispatcher.current; if (dispatcher) { dispatcher.preinitScript(href, { crossOrigin: getCrossOriginString(crossOrigin), nonce, }); } }
27.881119
96
0.602083
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. */ export {default} from './src/ReactFreshBabelPlugin';
26.333333
66
0.722449
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ListItem = ListItem; exports.List = List; var React = _interopRequireWildcard(require("react")); var _jsxFileName = ""; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function ListItem({ item, removeItem, toggleItem }) { const handleDelete = (0, React.useCallback)(() => { removeItem(item); }, [item, removeItem]); const handleToggle = (0, React.useCallback)(() => { toggleItem(item); }, [item, toggleItem]); return /*#__PURE__*/React.createElement("li", { __source: { fileName: _jsxFileName, lineNumber: 23, columnNumber: 5 } }, /*#__PURE__*/React.createElement("button", { onClick: handleDelete, __source: { fileName: _jsxFileName, lineNumber: 24, columnNumber: 7 } }, "Delete"), /*#__PURE__*/React.createElement("label", { __source: { fileName: _jsxFileName, lineNumber: 25, columnNumber: 7 } }, /*#__PURE__*/React.createElement("input", { checked: item.isComplete, onChange: handleToggle, type: "checkbox", __source: { fileName: _jsxFileName, lineNumber: 26, columnNumber: 9 } }), ' ', item.text)); } function List(props) { const [newItemText, setNewItemText] = (0, React.useState)(''); const [items, setItems] = (0, React.useState)([{ id: 1, isComplete: true, text: 'First' }, { id: 2, isComplete: true, text: 'Second' }, { id: 3, isComplete: false, text: 'Third' }]); const [uid, setUID] = (0, React.useState)(4); const handleClick = (0, React.useCallback)(() => { if (newItemText !== '') { setItems([...items, { id: uid, isComplete: false, text: newItemText }]); setUID(uid + 1); setNewItemText(''); } }, [newItemText, items, uid]); const handleKeyPress = (0, React.useCallback)(event => { if (event.key === 'Enter') { handleClick(); } }, [handleClick]); const handleChange = (0, React.useCallback)(event => { setNewItemText(event.currentTarget.value); }, [setNewItemText]); const removeItem = (0, React.useCallback)(itemToRemove => setItems(items.filter(item => item !== itemToRemove)), [items]); const toggleItem = (0, React.useCallback)(itemToToggle => { // Dont use indexOf() // because editing props in DevTools creates a new Object. const index = items.findIndex(item => item.id === itemToToggle.id); setItems(items.slice(0, index).concat({ ...itemToToggle, isComplete: !itemToToggle.isComplete }).concat(items.slice(index + 1))); }, [items]); return /*#__PURE__*/React.createElement(React.Fragment, { __source: { fileName: _jsxFileName, lineNumber: 102, columnNumber: 5 } }, /*#__PURE__*/React.createElement("h1", { __source: { fileName: _jsxFileName, lineNumber: 103, columnNumber: 7 } }, "List"), /*#__PURE__*/React.createElement("input", { type: "text", placeholder: "New list item...", value: newItemText, onChange: handleChange, onKeyPress: handleKeyPress, __source: { fileName: _jsxFileName, lineNumber: 104, columnNumber: 7 } }), /*#__PURE__*/React.createElement("button", { disabled: newItemText === '', onClick: handleClick, __source: { fileName: _jsxFileName, lineNumber: 111, columnNumber: 7 } }, /*#__PURE__*/React.createElement("span", { role: "img", "aria-label": "Add item", __source: { fileName: _jsxFileName, lineNumber: 112, columnNumber: 9 } }, "Add")), /*#__PURE__*/React.createElement("ul", { __source: { fileName: _jsxFileName, lineNumber: 116, columnNumber: 7 } }, items.map(item => /*#__PURE__*/React.createElement(ListItem, { key: item.id, item: item, removeItem: removeItem, toggleItem: toggleItem, __source: { fileName: _jsxFileName, lineNumber: 118, columnNumber: 11 } })))); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIlRvRG9MaXN0LmpzIl0sIm5hbWVzIjpbIkxpc3RJdGVtIiwiaXRlbSIsInJlbW92ZUl0ZW0iLCJ0b2dnbGVJdGVtIiwiaGFuZGxlRGVsZXRlIiwiaGFuZGxlVG9nZ2xlIiwiaXNDb21wbGV0ZSIsInRleHQiLCJMaXN0IiwicHJvcHMiLCJuZXdJdGVtVGV4dCIsInNldE5ld0l0ZW1UZXh0IiwiaXRlbXMiLCJzZXRJdGVtcyIsImlkIiwidWlkIiwic2V0VUlEIiwiaGFuZGxlQ2xpY2siLCJoYW5kbGVLZXlQcmVzcyIsImV2ZW50Iiwia2V5IiwiaGFuZGxlQ2hhbmdlIiwiY3VycmVudFRhcmdldCIsInZhbHVlIiwiaXRlbVRvUmVtb3ZlIiwiZmlsdGVyIiwiaXRlbVRvVG9nZ2xlIiwiaW5kZXgiLCJmaW5kSW5kZXgiLCJzbGljZSIsImNvbmNhdCIsIm1hcCJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7QUFTQTs7Ozs7Ozs7QUFHTyxTQUFTQSxRQUFULENBQWtCO0FBQUNDLEVBQUFBLElBQUQ7QUFBT0MsRUFBQUEsVUFBUDtBQUFtQkMsRUFBQUE7QUFBbkIsQ0FBbEIsRUFBa0Q7QUFDdkQsUUFBTUMsWUFBWSxHQUFHLHVCQUFZLE1BQU07QUFDckNGLElBQUFBLFVBQVUsQ0FBQ0QsSUFBRCxDQUFWO0FBQ0QsR0FGb0IsRUFFbEIsQ0FBQ0EsSUFBRCxFQUFPQyxVQUFQLENBRmtCLENBQXJCO0FBSUEsUUFBTUcsWUFBWSxHQUFHLHVCQUFZLE1BQU07QUFDckNGLElBQUFBLFVBQVUsQ0FBQ0YsSUFBRCxDQUFWO0FBQ0QsR0FGb0IsRUFFbEIsQ0FBQ0EsSUFBRCxFQUFPRSxVQUFQLENBRmtCLENBQXJCO0FBSUEsc0JBQ0U7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsa0JBQ0U7QUFBUSxJQUFBLE9BQU8sRUFBRUMsWUFBakI7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsY0FERixlQUVFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGtCQUNFO0FBQ0UsSUFBQSxPQUFPLEVBQUVILElBQUksQ0FBQ0ssVUFEaEI7QUFFRSxJQUFBLFFBQVEsRUFBRUQsWUFGWjtBQUdFLElBQUEsSUFBSSxFQUFDLFVBSFA7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsSUFERixFQUtLLEdBTEwsRUFNR0osSUFBSSxDQUFDTSxJQU5SLENBRkYsQ0FERjtBQWFEOztBQUVNLFNBQVNDLElBQVQsQ0FBY0MsS0FBZCxFQUFxQjtBQUMxQixRQUFNLENBQUNDLFdBQUQsRUFBY0MsY0FBZCxJQUFnQyxvQkFBUyxFQUFULENBQXRDO0FBQ0EsUUFBTSxDQUFDQyxLQUFELEVBQVFDLFFBQVIsSUFBb0Isb0JBQVMsQ0FDakM7QUFBQ0MsSUFBQUEsRUFBRSxFQUFFLENBQUw7QUFBUVIsSUFBQUEsVUFBVSxFQUFFLElBQXBCO0FBQTBCQyxJQUFBQSxJQUFJLEVBQUU7QUFBaEMsR0FEaUMsRUFFakM7QUFBQ08sSUFBQUEsRUFBRSxFQUFFLENBQUw7QUFBUVIsSUFBQUEsVUFBVSxFQUFFLElBQXBCO0FBQTBCQyxJQUFBQSxJQUFJLEVBQUU7QUFBaEMsR0FGaUMsRUFHakM7QUFBQ08sSUFBQUEsRUFBRSxFQUFFLENBQUw7QUFBUVIsSUFBQUEsVUFBVSxFQUFFLEtBQXBCO0FBQTJCQyxJQUFBQSxJQUFJLEVBQUU7QUFBakMsR0FIaUMsQ0FBVCxDQUExQjtBQUtBLFFBQU0sQ0FBQ1EsR0FBRCxFQUFNQyxNQUFOLElBQWdCLG9CQUFTLENBQVQsQ0FBdEI7QUFFQSxRQUFNQyxXQUFXLEdBQUcsdUJBQVksTUFBTTtBQUNwQyxRQUFJUCxXQUFXLEtBQUssRUFBcEIsRUFBd0I7QUFDdEJHLE1BQUFBLFFBQVEsQ0FBQyxDQUNQLEdBQUdELEtBREksRUFFUDtBQUNFRSxRQUFBQSxFQUFFLEVBQUVDLEdBRE47QUFFRVQsUUFBQUEsVUFBVSxFQUFFLEtBRmQ7QUFHRUMsUUFBQUEsSUFBSSxFQUFFRztBQUhSLE9BRk8sQ0FBRCxDQUFSO0FBUUFNLE1BQUFBLE1BQU0sQ0FBQ0QsR0FBRyxHQUFHLENBQVAsQ0FBTjtBQUNBSixNQUFBQSxjQUFjLENBQUMsRUFBRCxDQUFkO0FBQ0Q7QUFDRixHQWJtQixFQWFqQixDQUFDRCxXQUFELEVBQWNFLEtBQWQsRUFBcUJHLEdBQXJCLENBYmlCLENBQXBCO0FBZUEsUUFBTUcsY0FBYyxHQUFHLHVCQUNyQkMsS0FBSyxJQUFJO0FBQ1AsUUFBSUEsS0FBSyxDQUFDQyxHQUFOLEtBQWMsT0FBbEIsRUFBMkI7QUFDekJILE1BQUFBLFdBQVc7QUFDWjtBQUNGLEdBTG9CLEVBTXJCLENBQUNBLFdBQUQsQ0FOcUIsQ0FBdkI7QUFTQSxRQUFNSSxZQUFZLEdBQUcsdUJBQ25CRixLQUFLLElBQUk7QUFDUFIsSUFBQUEsY0FBYyxDQUFDUSxLQUFLLENBQUNHLGFBQU4sQ0FBb0JDLEtBQXJCLENBQWQ7QUFDRCxHQUhrQixFQUluQixDQUFDWixjQUFELENBSm1CLENBQXJCO0FBT0EsUUFBTVQsVUFBVSxHQUFHLHVCQUNqQnNCLFlBQVksSUFBSVgsUUFBUSxDQUFDRCxLQUFLLENBQUNhLE1BQU4sQ0FBYXhCLElBQUksSUFBSUEsSUFBSSxLQUFLdUIsWUFBOUIsQ0FBRCxDQURQLEVBRWpCLENBQUNaLEtBQUQsQ0FGaUIsQ0FBbkI7QUFLQSxRQUFNVCxVQUFVLEdBQUcsdUJBQ2pCdUIsWUFBWSxJQUFJO0FBQ2Q7QUFDQTtBQUNBLFVBQU1DLEtBQUssR0FBR2YsS0FBSyxDQUFDZ0IsU0FBTixDQUFnQjNCLElBQUksSUFBSUEsSUFBSSxDQUFDYSxFQUFMLEtBQVlZLFlBQVksQ0FBQ1osRUFBakQsQ0FBZDtBQUVBRCxJQUFBQSxRQUFRLENBQ05ELEtBQUssQ0FDRmlCLEtBREgsQ0FDUyxDQURULEVBQ1lGLEtBRFosRUFFR0csTUFGSCxDQUVVLEVBQ04sR0FBR0osWUFERztBQUVOcEIsTUFBQUEsVUFBVSxFQUFFLENBQUNvQixZQUFZLENBQUNwQjtBQUZwQixLQUZWLEVBTUd3QixNQU5ILENBTVVsQixLQUFLLENBQUNpQixLQUFOLENBQVlGLEtBQUssR0FBRyxDQUFwQixDQU5WLENBRE0sQ0FBUjtBQVNELEdBZmdCLEVBZ0JqQixDQUFDZixLQUFELENBaEJpQixDQUFuQjtBQW1CQSxzQkFDRSxvQkFBQyxjQUFEO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGtCQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLFlBREYsZUFFRTtBQUNFLElBQUEsSUFBSSxFQUFDLE1BRFA7QUFFRSxJQUFBLFdBQVcsRUFBQyxrQkFGZDtBQUdFLElBQUEsS0FBSyxFQUFFRixXQUhUO0FBSUUsSUFBQSxRQUFRLEVBQUVXLFlBSlo7QUFLRSxJQUFBLFVBQVUsRUFBRUgsY0FMZDtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxJQUZGLGVBU0U7QUFBUSxJQUFBLFFBQVEsRUFBRVIsV0FBVyxLQUFLLEVBQWxDO0FBQXNDLElBQUEsT0FBTyxFQUFFTyxXQUEvQztBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxrQkFDRTtBQUFNLElBQUEsSUFBSSxFQUFDLEtBQVg7QUFBaUIsa0JBQVcsVUFBNUI7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsV0FERixDQVRGLGVBY0U7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsS0FDR0wsS0FBSyxDQUFDbUIsR0FBTixDQUFVOUIsSUFBSSxpQkFDYixvQkFBQyxRQUFEO0FBQ0UsSUFBQSxHQUFHLEVBQUVBLElBQUksQ0FBQ2EsRUFEWjtBQUVFLElBQUEsSUFBSSxFQUFFYixJQUZSO0FBR0UsSUFBQSxVQUFVLEVBQUVDLFVBSGQ7QUFJRSxJQUFBLFVBQVUsRUFBRUMsVUFKZDtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxJQURELENBREgsQ0FkRixDQURGO0FBMkJEIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBDb3B5cmlnaHQgKGMpIEZhY2Vib29rLCBJbmMuIGFuZCBpdHMgYWZmaWxpYXRlcy5cbiAqXG4gKiBUaGlzIHNvdXJjZSBjb2RlIGlzIGxpY2Vuc2VkIHVuZGVyIHRoZSBNSVQgbGljZW5zZSBmb3VuZCBpbiB0aGVcbiAqIExJQ0VOU0UgZmlsZSBpbiB0aGUgcm9vdCBkaXJlY3Rvcnkgb2YgdGhpcyBzb3VyY2UgdHJlZS5cbiAqXG4gKiBAZmxvd1xuICovXG5cbmltcG9ydCAqIGFzIFJlYWN0IGZyb20gJ3JlYWN0JztcbmltcG9ydCB7RnJhZ21lbnQsIHVzZUNhbGxiYWNrLCB1c2VTdGF0ZX0gZnJvbSAncmVhY3QnO1xuXG5leHBvcnQgZnVuY3Rpb24gTGlzdEl0ZW0oe2l0ZW0sIHJlbW92ZUl0ZW0sIHRvZ2dsZUl0ZW19KSB7XG4gIGNvbnN0IGhhbmRsZURlbGV0ZSA9IHVzZUNhbGxiYWNrKCgpID0+IHtcbiAgICByZW1vdmVJdGVtKGl0ZW0pO1xuICB9LCBbaXRlbSwgcmVtb3ZlSXRlbV0pO1xuXG4gIGNvbnN0IGhhbmRsZVRvZ2dsZSA9IHVzZUNhbGxiYWNrKCgpID0+IHtcbiAgICB0b2dnbGVJdGVtKGl0ZW0pO1xuICB9LCBbaXRlbSwgdG9nZ2xlSXRlbV0pO1xuXG4gIHJldHVybiAoXG4gICAgPGxpPlxuICAgICAgPGJ1dHRvbiBvbkNsaWNrPXtoYW5kbGVEZWxldGV9PkRlbGV0ZTwvYnV0dG9uPlxuICAgICAgPGxhYmVsPlxuICAgICAgICA8aW5wdXRcbiAgICAgICAgICBjaGVja2VkPXtpdGVtLmlzQ29tcGxldGV9XG4gICAgICAgICAgb25DaGFuZ2U9e2hhbmRsZVRvZ2dsZX1cbiAgICAgICAgICB0eXBlPVwiY2hlY2tib3hcIlxuICAgICAgICAvPnsnICd9XG4gICAgICAgIHtpdGVtLnRleHR9XG4gICAgICA8L2xhYmVsPlxuICAgIDwvbGk+XG4gICk7XG59XG5cbmV4cG9ydCBmdW5jdGlvbiBMaXN0KHByb3BzKSB7XG4gIGNvbnN0IFtuZXdJdGVtVGV4dCwgc2V0TmV3SXRlbVRleHRdID0gdXNlU3RhdGUoJycpO1xuICBjb25zdCBbaXRlbXMsIHNldEl0ZW1zXSA9IHVzZVN0YXRlKFtcbiAgICB7aWQ6IDEsIGlzQ29tcGxldGU6IHRydWUsIHRleHQ6ICdGaXJzdCd9LFxuICAgIHtpZDogMiwgaXNDb21wbGV0ZTogdHJ1ZSwgdGV4dDogJ1NlY29uZCd9LFxuICAgIHtpZDogMywgaXNDb21wbGV0ZTogZmFsc2UsIHRleHQ6ICdUaGlyZCd9LFxuICBdKTtcbiAgY29uc3QgW3VpZCwgc2V0VUlEXSA9IHVzZVN0YXRlKDQpO1xuXG4gIGNvbnN0IGhhbmRsZUNsaWNrID0gdXNlQ2FsbGJhY2soKCkgPT4ge1xuICAgIGlmIChuZXdJdGVtVGV4dCAhPT0gJycpIHtcbiAgICAgIHNldEl0ZW1zKFtcbiAgICAgICAgLi4uaXRlbXMsXG4gICAgICAgIHtcbiAgICAgICAgICBpZDogdWlkLFxuICAgICAgICAgIGlzQ29tcGxldGU6IGZhbHNlLFxuICAgICAgICAgIHRleHQ6IG5ld0l0ZW1UZXh0LFxuICAgICAgICB9LFxuICAgICAgXSk7XG4gICAgICBzZXRVSUQodWlkICsgMSk7XG4gICAgICBzZXROZXdJdGVtVGV4dCgnJyk7XG4gICAgfVxuICB9LCBbbmV3SXRlbVRleHQsIGl0ZW1zLCB1aWRdKTtcblxuICBjb25zdCBoYW5kbGVLZXlQcmVzcyA9IHVzZUNhbGxiYWNrKFxuICAgIGV2ZW50ID0+IHtcbiAgICAgIGlmIChldmVudC5rZXkgPT09ICdFbnRlcicpIHtcbiAgICAgICAgaGFuZGxlQ2xpY2soKTtcbiAgICAgIH1cbiAgICB9LFxuICAgIFtoYW5kbGVDbGlja10sXG4gICk7XG5cbiAgY29uc3QgaGFuZGxlQ2hhbmdlID0gdXNlQ2FsbGJhY2soXG4gICAgZXZlbnQgPT4ge1xuICAgICAgc2V0TmV3SXRlbVRleHQoZXZlbnQuY3VycmVudFRhcmdldC52YWx1ZSk7XG4gICAgfSxcbiAgICBbc2V0TmV3SXRlbVRleHRdLFxuICApO1xuXG4gIGNvbnN0IHJlbW92ZUl0ZW0gPSB1c2VDYWxsYmFjayhcbiAgICBpdGVtVG9SZW1vdmUgPT4gc2V0SXRlbXMoaXRlbXMuZmlsdGVyKGl0ZW0gPT4gaXRlbSAhPT0gaXRlbVRvUmVtb3ZlKSksXG4gICAgW2l0ZW1zXSxcbiAgKTtcblxuICBjb25zdCB0b2dnbGVJdGVtID0gdXNlQ2FsbGJhY2soXG4gICAgaXRlbVRvVG9nZ2xlID0+IHtcbiAgICAgIC8vIERvbnQgdXNlIGluZGV4T2YoKVxuICAgICAgLy8gYmVjYXVzZSBlZGl0aW5nIHByb3BzIGluIERldlRvb2xzIGNyZWF0ZXMgYSBuZXcgT2JqZWN0LlxuICAgICAgY29uc3QgaW5kZXggPSBpdGVtcy5maW5kSW5kZXgoaXRlbSA9PiBpdGVtLmlkID09PSBpdGVtVG9Ub2dnbGUuaWQpO1xuXG4gICAgICBzZXRJdGVtcyhcbiAgICAgICAgaXRlbXNcbiAgICAgICAgICAuc2xpY2UoMCwgaW5kZXgpXG4gICAgICAgICAgLmNvbmNhdCh7XG4gICAgICAgICAgICAuLi5pdGVtVG9Ub2dnbGUsXG4gICAgICAgICAgICBpc0NvbXBsZXRlOiAhaXRlbVRvVG9nZ2xlLmlzQ29tcGxldGUsXG4gICAgICAgICAgfSlcbiAgICAgICAgICAuY29uY2F0KGl0ZW1zLnNsaWNlKGluZGV4ICsgMSkpLFxuICAgICAgKTtcbiAgICB9LFxuICAgIFtpdGVtc10sXG4gICk7XG5cbiAgcmV0dXJuIChcbiAgICA8RnJhZ21lbnQ+XG4gICAgICA8aDE+TGlzdDwvaDE+XG4gICAgICA8aW5wdXRcbiAgICAgICAgdHlwZT1cInRleHRcIlxuICAgICAgICBwbGFjZWhvbGRlcj1cIk5ldyBsaXN0IGl0ZW0uLi5cIlxuICAgICAgICB2YWx1ZT17bmV3SXRlbVRleHR9XG4gICAgICAgIG9uQ2hhbmdlPXtoYW5kbGVDaGFuZ2V9XG4gICAgICAgIG9uS2V5UHJlc3M9e2hhbmRsZUtleVByZXNzfVxuICAgICAgLz5cbiAgICAgIDxidXR0b24gZGlzYWJsZWQ9e25ld0l0ZW1UZXh0ID09PSAnJ30gb25DbGljaz17aGFuZGxlQ2xpY2t9PlxuICAgICAgICA8c3BhbiByb2xlPVwiaW1nXCIgYXJpYS1sYWJlbD1cIkFkZCBpdGVtXCI+XG4gICAgICAgICAgQWRkXG4gICAgICAgIDwvc3Bhbj5cbiAgICAgIDwvYnV0dG9uPlxuICAgICAgPHVsPlxuICAgICAgICB7aXRlbXMubWFwKGl0ZW0gPT4gKFxuICAgICAgICAgIDxMaXN0SXRlbVxuICAgICAgICAgICAga2V5PXtpdGVtLmlkfVxuICAgICAgICAgICAgaXRlbT17aXRlbX1cbiAgICAgICAgICAgIHJlbW92ZUl0ZW09e3JlbW92ZUl0ZW19XG4gICAgICAgICAgICB0b2dnbGVJdGVtPXt0b2dnbGVJdGVtfVxuICAgICAgICAgIC8+XG4gICAgICAgICkpfVxuICAgICAgPC91bD5cbiAgICA8L0ZyYWdtZW50PlxuICApO1xufVxuIl0sInhfZmFjZWJvb2tfc291cmNlcyI6W1tudWxsLFt7Im5hbWVzIjpbIjxuby1ob29rPiIsImhhbmRsZURlbGV0ZSIsImhhbmRsZVRvZ2dsZSIsIm5ld0l0ZW1UZXh0IiwiaXRlbXMiLCJ1aWQiLCJoYW5kbGVDbGljayIsImhhbmRsZUtleVByZXNzIiwiaGFuZGxlQ2hhbmdlIiwicmVtb3ZlSXRlbSIsInRvZ2dsZUl0ZW0iXSwibWFwcGluZ3MiOiJDQUFEO2N1QkNBO2dCQ0RBO2tCREVBO29CQ0ZBO3NDZ0JHQSxBWUhBO3VDeEJJQTsyQ3hCSkE7NENvQktBLEFXTEE7OENiTUE7MkRTTkE7NkROT0E7b0V0QlBBO3NFb0JRQTsyRXBCUkE7NkVrQlNBO2dGbEJUQTtrRmtCVUE7bUdsQlZBIn1dXV19fV19
88.26875
9,316
0.859894
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 strict */ type Heap<T: Node> = Array<T>; type Node = { id: number, sortIndex: number, ... }; export function push<T: Node>(heap: Heap<T>, node: T): void { const index = heap.length; heap.push(node); siftUp(heap, node, index); } export function peek<T: Node>(heap: Heap<T>): T | null { return heap.length === 0 ? null : heap[0]; } export function pop<T: Node>(heap: Heap<T>): T | null { if (heap.length === 0) { return null; } const first = heap[0]; const last = heap.pop(); if (last !== first) { heap[0] = last; siftDown(heap, last, 0); } return first; } function siftUp<T: Node>(heap: Heap<T>, node: T, i: number): void { let index = i; while (index > 0) { const parentIndex = (index - 1) >>> 1; const parent = heap[parentIndex]; if (compare(parent, node) > 0) { // The parent is larger. Swap positions. heap[parentIndex] = node; heap[index] = parent; index = parentIndex; } else { // The parent is smaller. Exit. return; } } } function siftDown<T: Node>(heap: Heap<T>, node: T, i: number): void { let index = i; const length = heap.length; const halfLength = length >>> 1; while (index < halfLength) { const leftIndex = (index + 1) * 2 - 1; const left = heap[leftIndex]; const rightIndex = leftIndex + 1; const right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those. if (compare(left, node) < 0) { if (rightIndex < length && compare(right, left) < 0) { heap[index] = right; heap[rightIndex] = node; index = rightIndex; } else { heap[index] = left; heap[leftIndex] = node; index = leftIndex; } } else if (rightIndex < length && compare(right, node) < 0) { heap[index] = right; heap[rightIndex] = node; index = rightIndex; } else { // Neither child is smaller. Exit. return; } } } function compare(a: Node, b: Node) { // Compare sort index first, then task id. const diff = a.sortIndex - b.sortIndex; return diff !== 0 ? diff : a.id - b.id; }
23.946809
76
0.586177
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 */ declare function isArray(a: mixed): boolean %checks(Array.isArray(a)); const isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare function isArray(a: mixed): boolean { return isArrayImpl(a); } export default isArray;
21.2
70
0.722348
PenetrationTestingScripts
#!/usr/bin/env node 'use strict'; const {exec, execSync} = require('child_process'); const {readFileSync, writeFileSync} = require('fs'); const {join} = require('path'); const shell = require('shelljs'); const main = async buildId => { const root = join(__dirname, buildId); const buildPath = join(root, 'build'); execSync(`node ${join(root, './build')}`, { cwd: __dirname, env: { ...process.env, NODE_ENV: 'production', }, stdio: 'inherit', }); shell.cp(join(root, 'now.json'), join(buildPath, 'now.json')); const file = readFileSync(join(root, 'now.json')); const json = JSON.parse(file); const alias = json.alias[0]; const commit = execSync('git rev-parse HEAD').toString().trim().slice(0, 7); let date = new Date(); date = `${date.toLocaleDateString()} – ${date.toLocaleTimeString()}`; const installationInstructions = buildId === 'chrome' ? readFileSync(join(__dirname, 'deploy.chrome.html')) : readFileSync(join(__dirname, 'deploy.firefox.html')); let html = readFileSync(join(__dirname, 'deploy.html')).toString(); html = html.replace(/%commit%/g, commit); html = html.replace(/%date%/g, date); html = html.replace(/%installation%/, installationInstructions); writeFileSync(join(buildPath, 'index.html'), html); await exec(`now deploy && now alias ${alias}`, { cwd: buildPath, stdio: 'inherit', }); console.log(`Deployed to https://${alias}.now.sh`); }; module.exports = main;
27.615385
78
0.63618
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 */ // Renderers that don't support hydration // can re-export everything from this module. function shim(...args: any): empty { throw new Error( 'The current renderer does not support hydration. ' + 'This error is likely caused by a bug in React. ' + 'Please file an issue.', ); } // Hydration (when unsupported) export type SuspenseInstance = mixed; export const supportsHydration = false; export const isHydratableText = shim; export const isSuspenseInstancePending = shim; export const isSuspenseInstanceFallback = shim; export const getSuspenseInstanceFallbackErrorDetails = shim; export const registerSuspenseInstanceRetry = shim; export const canHydrateFormStateMarker = shim; export const isFormStateMarkerMatching = shim; export const getNextHydratableSibling = shim; export const getFirstHydratableChild = shim; export const getFirstHydratableChildWithinContainer = shim; export const getFirstHydratableChildWithinSuspenseInstance = shim; export const canHydrateInstance = shim; export const canHydrateTextInstance = shim; export const canHydrateSuspenseInstance = shim; export const hydrateInstance = shim; export const hydrateTextInstance = shim; export const hydrateSuspenseInstance = shim; export const getNextHydratableInstanceAfterSuspenseInstance = shim; export const commitHydratedContainer = shim; export const commitHydratedSuspenseInstance = shim; export const clearSuspenseBoundary = shim; export const clearSuspenseBoundaryFromContainer = shim; export const shouldDeleteUnhydratedTailInstances = shim; export const didNotMatchHydratedContainerTextInstance = shim; export const didNotMatchHydratedTextInstance = shim; export const didNotHydrateInstanceWithinContainer = shim; export const didNotHydrateInstanceWithinSuspenseInstance = shim; export const didNotHydrateInstance = shim; export const didNotFindHydratableInstanceWithinContainer = shim; export const didNotFindHydratableTextInstanceWithinContainer = shim; export const didNotFindHydratableSuspenseInstanceWithinContainer = shim; export const didNotFindHydratableInstanceWithinSuspenseInstance = shim; export const didNotFindHydratableTextInstanceWithinSuspenseInstance = shim; export const didNotFindHydratableSuspenseInstanceWithinSuspenseInstance = shim; export const didNotFindHydratableInstance = shim; export const didNotFindHydratableTextInstance = shim; export const didNotFindHydratableSuspenseInstance = shim; export const errorHydratingContainer = shim;
42.080645
79
0.830337
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'; const React = require('react'); const ReactDOM = require('react-dom'); function expectWarnings(tags, warnings = [], withoutStack = 0) { tags = [...tags]; warnings = [...warnings]; let element = null; const containerTag = tags.shift(); const container = containerTag === 'svg' ? document.createElementNS('http://www.w3.org/2000/svg', containerTag) : document.createElement(containerTag); while (tags.length) { const Tag = tags.pop(); element = <Tag>{element}</Tag>; } if (warnings.length) { expect(() => ReactDOM.render(element, container)).toErrorDev(warnings, { withoutStack, }); } } describe('validateDOMNesting', () => { it('allows valid nestings', () => { expectWarnings(['table', 'tbody', 'tr', 'td', 'b']); expectWarnings(['body', 'datalist', 'option']); expectWarnings(['div', 'a', 'object', 'a']); expectWarnings(['div', 'p', 'button', 'p']); expectWarnings(['p', 'svg', 'foreignObject', 'p']); expectWarnings(['html', 'body', 'div']); // Invalid, but not changed by browser parsing so we allow them expectWarnings(['div', 'ul', 'ul', 'li']); expectWarnings(['div', 'label', 'div']); expectWarnings(['div', 'ul', 'li', 'section', 'li']); expectWarnings(['div', 'ul', 'li', 'dd', 'li']); }); it('prevents problematic nestings', () => { expectWarnings( ['a', 'a'], [ 'validateDOMNesting(...): <a> cannot appear as a descendant of <a>.\n' + ' in a (at **)', ], ); expectWarnings( ['form', 'form'], [ 'validateDOMNesting(...): <form> cannot appear as a descendant of <form>.\n' + ' in form (at **)', ], ); expectWarnings( ['p', 'p'], [ 'validateDOMNesting(...): <p> cannot appear as a descendant of <p>.\n' + ' in p (at **)', ], ); expectWarnings( ['table', 'tr'], [ 'validateDOMNesting(...): <tr> cannot appear as a child of <table>. ' + 'Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by the browser.\n' + ' in tr (at **)', ], ); expectWarnings( ['div', 'ul', 'li', 'div', 'li'], [ 'validateDOMNesting(...): <li> cannot appear as a descendant of <li>.\n' + ' in li (at **)\n' + ' in div (at **)\n' + ' in li (at **)\n' + ' in ul (at **)', ], ); expectWarnings( ['div', 'html'], [ 'validateDOMNesting(...): <html> cannot appear as a child of <div>.\n' + ' in html (at **)', ], ); expectWarnings( ['body', 'body'], [ 'validateDOMNesting(...): <body> cannot appear as a child of <body>.\n' + ' in body (at **)', ], ); expectWarnings( ['svg', 'foreignObject', 'body', 'p'], [ 'validateDOMNesting(...): <body> cannot appear as a child of <foreignObject>.\n' + ' in body (at **)\n' + ' in foreignObject (at **)', 'Warning: You are mounting a new body component when a previous one has not first unmounted. It is an error to render more than one body component at a time and attributes and children of these components will likely fail in unpredictable ways. Please only render a single instance of <body> and if you need to mount a new one, ensure any previous ones have unmounted first.\n' + ' in body (at **)', ], ); }); });
30.383333
387
0.536255
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 */ /* eslint-disable react-internal/prod-error-codes */ import type {ReactElement} from 'shared/ReactElementType'; import type {Fiber, FiberRoot} from './ReactInternalTypes'; import type {Instance} from './ReactFiberConfig'; import type {ReactNodeList} from 'shared/ReactTypes'; import {enableFloat} from 'shared/ReactFeatureFlags'; import { flushSync, scheduleUpdateOnFiber, flushPassiveEffects, } from './ReactFiberWorkLoop'; import {enqueueConcurrentRenderForLane} from './ReactFiberConcurrentUpdates'; import {updateContainer} from './ReactFiberReconciler'; import {emptyContextObject} from './ReactFiberContext'; import {SyncLane} from './ReactFiberLane'; import { ClassComponent, FunctionComponent, ForwardRef, HostComponent, HostHoistable, HostSingleton, HostPortal, HostRoot, MemoComponent, SimpleMemoComponent, } from './ReactWorkTags'; import { REACT_FORWARD_REF_TYPE, REACT_MEMO_TYPE, REACT_LAZY_TYPE, } from 'shared/ReactSymbols'; import {supportsSingletons} from './ReactFiberConfig'; export type Family = { current: any, }; export type RefreshUpdate = { staleFamilies: Set<Family>, updatedFamilies: Set<Family>, }; // Resolves type to a family. type RefreshHandler = any => Family | void; // Used by React Refresh runtime through DevTools Global Hook. export type SetRefreshHandler = (handler: RefreshHandler | null) => void; export type ScheduleRefresh = (root: FiberRoot, update: RefreshUpdate) => void; export type ScheduleRoot = (root: FiberRoot, element: ReactNodeList) => void; export type FindHostInstancesForRefresh = ( root: FiberRoot, families: Array<Family>, ) => Set<Instance>; let resolveFamily: RefreshHandler | null = null; let failedBoundaries: WeakSet<Fiber> | null = null; export const setRefreshHandler = (handler: RefreshHandler | null): void => { if (__DEV__) { resolveFamily = handler; } }; export function resolveFunctionForHotReloading(type: any): any { if (__DEV__) { if (resolveFamily === null) { // Hot reloading is disabled. return type; } const family = resolveFamily(type); if (family === undefined) { return type; } // Use the latest known implementation. return family.current; } else { return type; } } export function resolveClassForHotReloading(type: any): any { // No implementation differences. return resolveFunctionForHotReloading(type); } export function resolveForwardRefForHotReloading(type: any): any { if (__DEV__) { if (resolveFamily === null) { // Hot reloading is disabled. return type; } const family = resolveFamily(type); if (family === undefined) { // Check if we're dealing with a real forwardRef. Don't want to crash early. if ( type !== null && type !== undefined && typeof type.render === 'function' ) { // ForwardRef is special because its resolved .type is an object, // but it's possible that we only have its inner render function in the map. // If that inner render function is different, we'll build a new forwardRef type. const currentRender = resolveFunctionForHotReloading(type.render); if (type.render !== currentRender) { const syntheticType = { $$typeof: REACT_FORWARD_REF_TYPE, render: currentRender, }; if (type.displayName !== undefined) { (syntheticType: any).displayName = type.displayName; } return syntheticType; } } return type; } // Use the latest known implementation. return family.current; } else { return type; } } export function isCompatibleFamilyForHotReloading( fiber: Fiber, element: ReactElement, ): boolean { if (__DEV__) { if (resolveFamily === null) { // Hot reloading is disabled. return false; } const prevType = fiber.elementType; const nextType = element.type; // If we got here, we know types aren't === equal. let needsCompareFamilies = false; const $$typeofNextType = typeof nextType === 'object' && nextType !== null ? nextType.$$typeof : null; switch (fiber.tag) { case ClassComponent: { if (typeof nextType === 'function') { needsCompareFamilies = true; } break; } case FunctionComponent: { if (typeof nextType === 'function') { needsCompareFamilies = true; } else if ($$typeofNextType === REACT_LAZY_TYPE) { // We don't know the inner type yet. // We're going to assume that the lazy inner type is stable, // and so it is sufficient to avoid reconciling it away. // We're not going to unwrap or actually use the new lazy type. needsCompareFamilies = true; } break; } case ForwardRef: { if ($$typeofNextType === REACT_FORWARD_REF_TYPE) { needsCompareFamilies = true; } else if ($$typeofNextType === REACT_LAZY_TYPE) { needsCompareFamilies = true; } break; } case MemoComponent: case SimpleMemoComponent: { if ($$typeofNextType === REACT_MEMO_TYPE) { // TODO: if it was but can no longer be simple, // we shouldn't set this. needsCompareFamilies = true; } else if ($$typeofNextType === REACT_LAZY_TYPE) { needsCompareFamilies = true; } break; } default: return false; } // Check if both types have a family and it's the same one. if (needsCompareFamilies) { // Note: memo() and forwardRef() we'll compare outer rather than inner type. // This means both of them need to be registered to preserve state. // If we unwrapped and compared the inner types for wrappers instead, // then we would risk falsely saying two separate memo(Foo) // calls are equivalent because they wrap the same Foo function. const prevFamily = resolveFamily(prevType); // $FlowFixMe[not-a-function] found when upgrading Flow if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) { return true; } } return false; } else { return false; } } export function markFailedErrorBoundaryForHotReloading(fiber: Fiber) { if (__DEV__) { if (resolveFamily === null) { // Hot reloading is disabled. return; } if (typeof WeakSet !== 'function') { return; } if (failedBoundaries === null) { failedBoundaries = new WeakSet(); } failedBoundaries.add(fiber); } } export const scheduleRefresh: ScheduleRefresh = ( root: FiberRoot, update: RefreshUpdate, ): void => { if (__DEV__) { if (resolveFamily === null) { // Hot reloading is disabled. return; } const {staleFamilies, updatedFamilies} = update; flushPassiveEffects(); flushSync(() => { scheduleFibersWithFamiliesRecursively( root.current, updatedFamilies, staleFamilies, ); }); } }; export const scheduleRoot: ScheduleRoot = ( root: FiberRoot, element: ReactNodeList, ): void => { if (__DEV__) { if (root.context !== emptyContextObject) { // Super edge case: root has a legacy _renderSubtree context // but we don't know the parentComponent so we can't pass it. // Just ignore. We'll delete this with _renderSubtree code path later. return; } flushPassiveEffects(); flushSync(() => { updateContainer(element, root, null, null); }); } }; function scheduleFibersWithFamiliesRecursively( fiber: Fiber, updatedFamilies: Set<Family>, staleFamilies: Set<Family>, ): void { if (__DEV__) { const {alternate, child, sibling, tag, type} = fiber; let candidateType = null; switch (tag) { case FunctionComponent: case SimpleMemoComponent: case ClassComponent: candidateType = type; break; case ForwardRef: candidateType = type.render; break; default: break; } if (resolveFamily === null) { throw new Error('Expected resolveFamily to be set during hot reload.'); } let needsRender = false; let needsRemount = false; if (candidateType !== null) { const family = resolveFamily(candidateType); if (family !== undefined) { if (staleFamilies.has(family)) { needsRemount = true; } else if (updatedFamilies.has(family)) { if (tag === ClassComponent) { needsRemount = true; } else { needsRender = true; } } } } if (failedBoundaries !== null) { if ( failedBoundaries.has(fiber) || // $FlowFixMe[incompatible-use] found when upgrading Flow (alternate !== null && failedBoundaries.has(alternate)) ) { needsRemount = true; } } if (needsRemount) { fiber._debugNeedsRemount = true; } if (needsRemount || needsRender) { const root = enqueueConcurrentRenderForLane(fiber, SyncLane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, SyncLane); } } if (child !== null && !needsRemount) { scheduleFibersWithFamiliesRecursively( child, updatedFamilies, staleFamilies, ); } if (sibling !== null) { scheduleFibersWithFamiliesRecursively( sibling, updatedFamilies, staleFamilies, ); } } } export const findHostInstancesForRefresh: FindHostInstancesForRefresh = ( root: FiberRoot, families: Array<Family>, ): Set<Instance> => { if (__DEV__) { const hostInstances = new Set<Instance>(); const types = new Set(families.map(family => family.current)); findHostInstancesForMatchingFibersRecursively( root.current, types, hostInstances, ); return hostInstances; } else { throw new Error( 'Did not expect findHostInstancesForRefresh to be called in production.', ); } }; function findHostInstancesForMatchingFibersRecursively( fiber: Fiber, types: Set<any>, hostInstances: Set<Instance>, ) { if (__DEV__) { const {child, sibling, tag, type} = fiber; let candidateType = null; switch (tag) { case FunctionComponent: case SimpleMemoComponent: case ClassComponent: candidateType = type; break; case ForwardRef: candidateType = type.render; break; default: break; } let didMatch = false; if (candidateType !== null) { if (types.has(candidateType)) { didMatch = true; } } if (didMatch) { // We have a match. This only drills down to the closest host components. // There's no need to search deeper because for the purpose of giving // visual feedback, "flashing" outermost parent rectangles is sufficient. findHostInstancesForFiberShallowly(fiber, hostInstances); } else { // If there's no match, maybe there will be one further down in the child tree. if (child !== null) { findHostInstancesForMatchingFibersRecursively( child, types, hostInstances, ); } } if (sibling !== null) { findHostInstancesForMatchingFibersRecursively( sibling, types, hostInstances, ); } } } function findHostInstancesForFiberShallowly( fiber: Fiber, hostInstances: Set<Instance>, ): void { if (__DEV__) { const foundHostInstances = findChildHostInstancesForFiberShallowly( fiber, hostInstances, ); if (foundHostInstances) { return; } // If we didn't find any host children, fallback to closest host parent. let node = fiber; while (true) { switch (node.tag) { case HostSingleton: case HostComponent: hostInstances.add(node.stateNode); return; case HostPortal: hostInstances.add(node.stateNode.containerInfo); return; case HostRoot: hostInstances.add(node.stateNode.containerInfo); return; } if (node.return === null) { throw new Error('Expected to reach root first.'); } node = node.return; } } } function findChildHostInstancesForFiberShallowly( fiber: Fiber, hostInstances: Set<Instance>, ): boolean { if (__DEV__) { let node: Fiber = fiber; let foundHostInstances = false; while (true) { if ( node.tag === HostComponent || (enableFloat ? node.tag === HostHoistable : false) || (supportsSingletons ? node.tag === HostSingleton : false) ) { // We got a match. foundHostInstances = true; hostInstances.add(node.stateNode); // There may still be more, so keep searching. } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } if (node === fiber) { return foundHostInstances; } while (node.sibling === null) { if (node.return === null || node.return === fiber) { return foundHostInstances; } node = node.return; } node.sibling.return = node.return; node = node.sibling; } } return false; }
26.335341
89
0.618058
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 ReactTestUtils; let act; let Scheduler; let waitForAll; let waitFor; let assertLog; describe('ReactUpdates', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); ReactTestUtils = require('react-dom/test-utils'); act = require('internal-test-utils').act; Scheduler = require('scheduler'); const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; waitFor = InternalTestUtils.waitFor; assertLog = InternalTestUtils.assertLog; }); // Note: This is based on a similar component we use in www. We can delete // once the extra div wrapper is no longer necessary. function LegacyHiddenDiv({children, mode}) { return ( <div hidden={mode === 'hidden'}> <React.unstable_LegacyHidden mode={mode === 'hidden' ? 'unstable-defer-without-hiding' : mode}> {children} </React.unstable_LegacyHidden> </div> ); } it('should batch state when updating state twice', () => { let updateCount = 0; class Component extends React.Component { state = {x: 0}; componentDidUpdate() { updateCount++; } render() { return <div>{this.state.x}</div>; } } const instance = ReactTestUtils.renderIntoDocument(<Component />); expect(instance.state.x).toBe(0); ReactDOM.unstable_batchedUpdates(function () { instance.setState({x: 1}); instance.setState({x: 2}); expect(instance.state.x).toBe(0); expect(updateCount).toBe(0); }); expect(instance.state.x).toBe(2); expect(updateCount).toBe(1); }); it('should batch state when updating two different state keys', () => { let updateCount = 0; class Component extends React.Component { state = {x: 0, y: 0}; componentDidUpdate() { updateCount++; } render() { return ( <div> ({this.state.x}, {this.state.y}) </div> ); } } const instance = ReactTestUtils.renderIntoDocument(<Component />); expect(instance.state.x).toBe(0); expect(instance.state.y).toBe(0); ReactDOM.unstable_batchedUpdates(function () { instance.setState({x: 1}); instance.setState({y: 2}); expect(instance.state.x).toBe(0); expect(instance.state.y).toBe(0); expect(updateCount).toBe(0); }); expect(instance.state.x).toBe(1); expect(instance.state.y).toBe(2); expect(updateCount).toBe(1); }); it('should batch state and props together', () => { let updateCount = 0; class Component extends React.Component { state = {y: 0}; componentDidUpdate() { updateCount++; } render() { return ( <div> ({this.props.x}, {this.state.y}) </div> ); } } const container = document.createElement('div'); const instance = ReactDOM.render(<Component x={0} />, container); expect(instance.props.x).toBe(0); expect(instance.state.y).toBe(0); ReactDOM.unstable_batchedUpdates(function () { ReactDOM.render(<Component x={1} />, container); instance.setState({y: 2}); expect(instance.props.x).toBe(0); expect(instance.state.y).toBe(0); expect(updateCount).toBe(0); }); expect(instance.props.x).toBe(1); expect(instance.state.y).toBe(2); expect(updateCount).toBe(1); }); it('should batch parent/child state updates together', () => { let parentUpdateCount = 0; class Parent extends React.Component { state = {x: 0}; childRef = React.createRef(); componentDidUpdate() { parentUpdateCount++; } render() { return ( <div> <Child ref={this.childRef} x={this.state.x} /> </div> ); } } let childUpdateCount = 0; class Child extends React.Component { state = {y: 0}; componentDidUpdate() { childUpdateCount++; } render() { return <div>{this.props.x + this.state.y}</div>; } } const instance = ReactTestUtils.renderIntoDocument(<Parent />); const child = instance.childRef.current; expect(instance.state.x).toBe(0); expect(child.state.y).toBe(0); ReactDOM.unstable_batchedUpdates(function () { instance.setState({x: 1}); child.setState({y: 2}); expect(instance.state.x).toBe(0); expect(child.state.y).toBe(0); expect(parentUpdateCount).toBe(0); expect(childUpdateCount).toBe(0); }); expect(instance.state.x).toBe(1); expect(child.state.y).toBe(2); expect(parentUpdateCount).toBe(1); expect(childUpdateCount).toBe(1); }); it('should batch child/parent state updates together', () => { let parentUpdateCount = 0; class Parent extends React.Component { state = {x: 0}; childRef = React.createRef(); componentDidUpdate() { parentUpdateCount++; } render() { return ( <div> <Child ref={this.childRef} x={this.state.x} /> </div> ); } } let childUpdateCount = 0; class Child extends React.Component { state = {y: 0}; componentDidUpdate() { childUpdateCount++; } render() { return <div>{this.props.x + this.state.y}</div>; } } const instance = ReactTestUtils.renderIntoDocument(<Parent />); const child = instance.childRef.current; expect(instance.state.x).toBe(0); expect(child.state.y).toBe(0); ReactDOM.unstable_batchedUpdates(function () { child.setState({y: 2}); instance.setState({x: 1}); expect(instance.state.x).toBe(0); expect(child.state.y).toBe(0); expect(parentUpdateCount).toBe(0); expect(childUpdateCount).toBe(0); }); expect(instance.state.x).toBe(1); expect(child.state.y).toBe(2); expect(parentUpdateCount).toBe(1); // Batching reduces the number of updates here to 1. expect(childUpdateCount).toBe(1); }); it('should support chained state updates', () => { let updateCount = 0; class Component extends React.Component { state = {x: 0}; componentDidUpdate() { updateCount++; } render() { return <div>{this.state.x}</div>; } } const instance = ReactTestUtils.renderIntoDocument(<Component />); expect(instance.state.x).toBe(0); let innerCallbackRun = false; ReactDOM.unstable_batchedUpdates(function () { instance.setState({x: 1}, function () { instance.setState({x: 2}, function () { expect(this).toBe(instance); innerCallbackRun = true; expect(instance.state.x).toBe(2); expect(updateCount).toBe(2); }); expect(instance.state.x).toBe(1); expect(updateCount).toBe(1); }); expect(instance.state.x).toBe(0); expect(updateCount).toBe(0); }); expect(innerCallbackRun).toBeTruthy(); expect(instance.state.x).toBe(2); expect(updateCount).toBe(2); }); it('should batch forceUpdate together', () => { let shouldUpdateCount = 0; let updateCount = 0; class Component extends React.Component { state = {x: 0}; shouldComponentUpdate() { shouldUpdateCount++; } componentDidUpdate() { updateCount++; } render() { return <div>{this.state.x}</div>; } } const instance = ReactTestUtils.renderIntoDocument(<Component />); expect(instance.state.x).toBe(0); let callbacksRun = 0; ReactDOM.unstable_batchedUpdates(function () { instance.setState({x: 1}, function () { callbacksRun++; }); instance.forceUpdate(function () { callbacksRun++; }); expect(instance.state.x).toBe(0); expect(updateCount).toBe(0); }); expect(callbacksRun).toBe(2); // shouldComponentUpdate shouldn't be called since we're forcing expect(shouldUpdateCount).toBe(0); expect(instance.state.x).toBe(1); expect(updateCount).toBe(1); }); it('should update children even if parent blocks updates', () => { let parentRenderCount = 0; let childRenderCount = 0; class Parent extends React.Component { childRef = React.createRef(); shouldComponentUpdate() { return false; } render() { parentRenderCount++; return <Child ref={this.childRef} />; } } class Child extends React.Component { render() { childRenderCount++; return <div />; } } expect(parentRenderCount).toBe(0); expect(childRenderCount).toBe(0); let instance = <Parent />; instance = ReactTestUtils.renderIntoDocument(instance); expect(parentRenderCount).toBe(1); expect(childRenderCount).toBe(1); ReactDOM.unstable_batchedUpdates(function () { instance.setState({x: 1}); }); expect(parentRenderCount).toBe(1); expect(childRenderCount).toBe(1); ReactDOM.unstable_batchedUpdates(function () { instance.childRef.current.setState({x: 1}); }); expect(parentRenderCount).toBe(1); expect(childRenderCount).toBe(2); }); it('should not reconcile children passed via props', () => { let numMiddleRenders = 0; let numBottomRenders = 0; class Top extends React.Component { render() { return ( <Middle> <Bottom /> </Middle> ); } } class Middle extends React.Component { componentDidMount() { this.forceUpdate(); } render() { numMiddleRenders++; return React.Children.only(this.props.children); } } class Bottom extends React.Component { render() { numBottomRenders++; return null; } } ReactTestUtils.renderIntoDocument(<Top />); expect(numMiddleRenders).toBe(2); expect(numBottomRenders).toBe(1); }); it('should flow updates correctly', () => { let willUpdates = []; let didUpdates = []; const UpdateLoggingMixin = { UNSAFE_componentWillUpdate: function () { willUpdates.push(this.constructor.displayName); }, componentDidUpdate: function () { didUpdates.push(this.constructor.displayName); }, }; class Box extends React.Component { boxDivRef = React.createRef(); render() { return <div ref={this.boxDivRef}>{this.props.children}</div>; } } Object.assign(Box.prototype, UpdateLoggingMixin); class Child extends React.Component { spanRef = React.createRef(); render() { return <span ref={this.spanRef}>child</span>; } } Object.assign(Child.prototype, UpdateLoggingMixin); class Switcher extends React.Component { state = {tabKey: 'hello'}; boxRef = React.createRef(); switcherDivRef = React.createRef(); render() { const child = this.props.children; return ( <Box ref={this.boxRef}> <div ref={this.switcherDivRef} style={{ display: this.state.tabKey === child.key ? '' : 'none', }}> {child} </div> </Box> ); } } Object.assign(Switcher.prototype, UpdateLoggingMixin); class App extends React.Component { switcherRef = React.createRef(); childRef = React.createRef(); render() { return ( <Switcher ref={this.switcherRef}> <Child key="hello" ref={this.childRef} /> </Switcher> ); } } Object.assign(App.prototype, UpdateLoggingMixin); let root = <App />; root = ReactTestUtils.renderIntoDocument(root); function expectUpdates(desiredWillUpdates, desiredDidUpdates) { let i; for (i = 0; i < desiredWillUpdates; i++) { expect(willUpdates).toContain(desiredWillUpdates[i]); } for (i = 0; i < desiredDidUpdates; i++) { expect(didUpdates).toContain(desiredDidUpdates[i]); } willUpdates = []; didUpdates = []; } function triggerUpdate(c) { c.setState({x: 1}); } function testUpdates(components, desiredWillUpdates, desiredDidUpdates) { let i; ReactDOM.unstable_batchedUpdates(function () { for (i = 0; i < components.length; i++) { triggerUpdate(components[i]); } }); expectUpdates(desiredWillUpdates, desiredDidUpdates); // Try them in reverse order ReactDOM.unstable_batchedUpdates(function () { for (i = components.length - 1; i >= 0; i--) { triggerUpdate(components[i]); } }); expectUpdates(desiredWillUpdates, desiredDidUpdates); } testUpdates( [root.switcherRef.current.boxRef.current, root.switcherRef.current], // Owner-child relationships have inverse will and did ['Switcher', 'Box'], ['Box', 'Switcher'], ); testUpdates( [root.childRef.current, root.switcherRef.current.boxRef.current], // Not owner-child so reconcile independently ['Box', 'Child'], ['Box', 'Child'], ); testUpdates( [root.childRef.current, root.switcherRef.current], // Switcher owns Box and Child, Box does not own Child ['Switcher', 'Box', 'Child'], ['Box', 'Switcher', 'Child'], ); }); it('should queue mount-ready handlers across different roots', () => { // We'll define two components A and B, then update both of them. When A's // componentDidUpdate handlers is called, B's DOM should already have been // updated. const bContainer = document.createElement('div'); let b; let aUpdated = false; class A extends React.Component { state = {x: 0}; componentDidUpdate() { expect(ReactDOM.findDOMNode(b).textContent).toBe('B1'); aUpdated = true; } render() { let portal = null; // If we're using Fiber, we use Portals instead to achieve this. portal = ReactDOM.createPortal(<B ref={n => (b = n)} />, bContainer); return ( <div> A{this.state.x} {portal} </div> ); } } class B extends React.Component { state = {x: 0}; render() { return <div>B{this.state.x}</div>; } } const a = ReactTestUtils.renderIntoDocument(<A />); ReactDOM.unstable_batchedUpdates(function () { a.setState({x: 1}); b.setState({x: 1}); }); expect(aUpdated).toBe(true); }); it('should flush updates in the correct order', () => { const updates = []; class Outer extends React.Component { state = {x: 0}; innerRef = React.createRef(); render() { updates.push('Outer-render-' + this.state.x); return ( <div> <Inner x={this.state.x} ref={this.innerRef} /> </div> ); } componentDidUpdate() { const x = this.state.x; updates.push('Outer-didUpdate-' + x); updates.push('Inner-setState-' + x); this.innerRef.current.setState({x: x}, function () { updates.push('Inner-callback-' + x); }); } } class Inner extends React.Component { state = {x: 0}; render() { updates.push('Inner-render-' + this.props.x + '-' + this.state.x); return <div />; } componentDidUpdate() { updates.push('Inner-didUpdate-' + this.props.x + '-' + this.state.x); } } const instance = ReactTestUtils.renderIntoDocument(<Outer />); updates.push('Outer-setState-1'); instance.setState({x: 1}, function () { updates.push('Outer-callback-1'); updates.push('Outer-setState-2'); instance.setState({x: 2}, function () { updates.push('Outer-callback-2'); }); }); /* eslint-disable indent */ expect(updates).toEqual([ 'Outer-render-0', 'Inner-render-0-0', 'Outer-setState-1', 'Outer-render-1', 'Inner-render-1-0', 'Inner-didUpdate-1-0', 'Outer-didUpdate-1', // Happens in a batch, so don't re-render yet 'Inner-setState-1', 'Outer-callback-1', // Happens in a batch 'Outer-setState-2', // Flush batched updates all at once 'Outer-render-2', 'Inner-render-2-1', 'Inner-didUpdate-2-1', 'Inner-callback-1', 'Outer-didUpdate-2', 'Inner-setState-2', 'Outer-callback-2', 'Inner-render-2-2', 'Inner-didUpdate-2-2', 'Inner-callback-2', ]); /* eslint-enable indent */ }); it('should flush updates in the correct order across roots', () => { const instances = []; const updates = []; class MockComponent extends React.Component { render() { updates.push(this.props.depth); return <div />; } componentDidMount() { instances.push(this); if (this.props.depth < this.props.count) { ReactDOM.render( <MockComponent depth={this.props.depth + 1} count={this.props.count} />, ReactDOM.findDOMNode(this), ); } } } ReactTestUtils.renderIntoDocument(<MockComponent depth={0} count={2} />); expect(updates).toEqual([0, 1, 2]); ReactDOM.unstable_batchedUpdates(function () { // Simulate update on each component from top to bottom. instances.forEach(function (instance) { instance.forceUpdate(); }); }); expect(updates).toEqual([0, 1, 2, 0, 1, 2]); }); it('should queue nested updates', () => { // See https://github.com/facebook/react/issues/1147 class X extends React.Component { state = {s: 0}; render() { if (this.state.s === 0) { return ( <div> <span>0</span> </div> ); } else { return <div>1</div>; } } go = () => { this.setState({s: 1}); this.setState({s: 0}); this.setState({s: 1}); }; } class Y extends React.Component { render() { return ( <div> <Z /> </div> ); } } class Z extends React.Component { render() { return <div />; } UNSAFE_componentWillUpdate() { x.go(); } } const x = ReactTestUtils.renderIntoDocument(<X />); const y = ReactTestUtils.renderIntoDocument(<Y />); expect(ReactDOM.findDOMNode(x).textContent).toBe('0'); y.forceUpdate(); expect(ReactDOM.findDOMNode(x).textContent).toBe('1'); }); it('should queue updates from during mount', () => { // See https://github.com/facebook/react/issues/1353 let a; class A extends React.Component { state = {x: 0}; UNSAFE_componentWillMount() { a = this; } render() { return <div>A{this.state.x}</div>; } } class B extends React.Component { UNSAFE_componentWillMount() { a.setState({x: 1}); } render() { return <div />; } } ReactDOM.unstable_batchedUpdates(function () { ReactTestUtils.renderIntoDocument( <div> <A /> <B /> </div>, ); }); expect(a.state.x).toBe(1); expect(ReactDOM.findDOMNode(a).textContent).toBe('A1'); }); it('calls componentWillReceiveProps setState callback properly', () => { let callbackCount = 0; class A extends React.Component { state = {x: this.props.x}; UNSAFE_componentWillReceiveProps(nextProps) { const newX = nextProps.x; this.setState({x: newX}, function () { // State should have updated by the time this callback gets called expect(this.state.x).toBe(newX); callbackCount++; }); } render() { return <div>{this.state.x}</div>; } } const container = document.createElement('div'); ReactDOM.render(<A x={1} />, container); ReactDOM.render(<A x={2} />, container); expect(callbackCount).toBe(1); }); it('does not call render after a component as been deleted', () => { let renderCount = 0; let componentB = null; class B extends React.Component { state = {updates: 0}; componentDidMount() { componentB = this; } render() { renderCount++; return <div />; } } class A extends React.Component { state = {showB: true}; render() { return this.state.showB ? <B /> : <div />; } } const component = ReactTestUtils.renderIntoDocument(<A />); ReactDOM.unstable_batchedUpdates(function () { // B will have scheduled an update but the batching should ensure that its // update never fires. componentB.setState({updates: 1}); component.setState({showB: false}); }); expect(renderCount).toBe(1); }); it('throws in setState if the update callback is not a function', () => { function Foo() { this.a = 1; this.b = 2; } class A extends React.Component { state = {}; render() { return <div />; } } let component = ReactTestUtils.renderIntoDocument(<A />); expect(() => { expect(() => component.setState({}, 'no')).toErrorDev( 'setState(...): Expected the last optional `callback` argument to be ' + 'a function. Instead received: no.', ); }).toThrowError( 'Invalid argument passed as callback. Expected a function. Instead ' + 'received: no', ); component = ReactTestUtils.renderIntoDocument(<A />); expect(() => { expect(() => component.setState({}, {foo: 'bar'})).toErrorDev( 'setState(...): Expected the last optional `callback` argument to be ' + 'a function. Instead received: [object Object].', ); }).toThrowError( 'Invalid argument passed as callback. Expected a function. Instead ' + 'received: [object Object]', ); // Make sure the warning is deduplicated and doesn't fire again component = ReactTestUtils.renderIntoDocument(<A />); expect(() => component.setState({}, new Foo())).toThrowError( 'Invalid argument passed as callback. Expected a function. Instead ' + 'received: [object Object]', ); }); it('throws in forceUpdate if the update callback is not a function', () => { function Foo() { this.a = 1; this.b = 2; } class A extends React.Component { state = {}; render() { return <div />; } } let component = ReactTestUtils.renderIntoDocument(<A />); expect(() => { expect(() => component.forceUpdate('no')).toErrorDev( 'forceUpdate(...): Expected the last optional `callback` argument to be ' + 'a function. Instead received: no.', ); }).toThrowError( 'Invalid argument passed as callback. Expected a function. Instead ' + 'received: no', ); component = ReactTestUtils.renderIntoDocument(<A />); expect(() => { expect(() => component.forceUpdate({foo: 'bar'})).toErrorDev( 'forceUpdate(...): Expected the last optional `callback` argument to be ' + 'a function. Instead received: [object Object].', ); }).toThrowError( 'Invalid argument passed as callback. Expected a function. Instead ' + 'received: [object Object]', ); // Make sure the warning is deduplicated and doesn't fire again component = ReactTestUtils.renderIntoDocument(<A />); expect(() => component.forceUpdate(new Foo())).toThrowError( 'Invalid argument passed as callback. Expected a function. Instead ' + 'received: [object Object]', ); }); it('does not update one component twice in a batch (#2410)', () => { class Parent extends React.Component { childRef = React.createRef(); getChild = () => { return this.childRef.current; }; render() { return <Child ref={this.childRef} />; } } let renderCount = 0; let postRenderCount = 0; let once = false; class Child extends React.Component { state = {updated: false}; UNSAFE_componentWillUpdate() { if (!once) { once = true; this.setState({updated: true}); } } componentDidMount() { expect(renderCount).toBe(postRenderCount + 1); postRenderCount++; } componentDidUpdate() { expect(renderCount).toBe(postRenderCount + 1); postRenderCount++; } render() { expect(renderCount).toBe(postRenderCount); renderCount++; return <div />; } } const parent = ReactTestUtils.renderIntoDocument(<Parent />); const child = parent.getChild(); ReactDOM.unstable_batchedUpdates(function () { parent.forceUpdate(); child.forceUpdate(); }); }); it('does not update one component twice in a batch (#6371)', () => { let callbacks = []; function emitChange() { callbacks.forEach(c => c()); } class App extends React.Component { constructor(props) { super(props); this.state = {showChild: true}; } componentDidMount() { this.setState({showChild: false}); } render() { return ( <div> <ForceUpdatesOnChange /> {this.state.showChild && <EmitsChangeOnUnmount />} </div> ); } } class EmitsChangeOnUnmount extends React.Component { componentWillUnmount() { emitChange(); } render() { return null; } } class ForceUpdatesOnChange extends React.Component { componentDidMount() { this.onChange = () => this.forceUpdate(); this.onChange(); callbacks.push(this.onChange); } componentWillUnmount() { callbacks = callbacks.filter(c => c !== this.onChange); } render() { return <div key={Math.random()} onClick={function () {}} />; } } ReactDOM.render(<App />, document.createElement('div')); }); it('unstable_batchedUpdates should return value from a callback', () => { const result = ReactDOM.unstable_batchedUpdates(function () { return 42; }); expect(result).toEqual(42); }); it('unmounts and remounts a root in the same batch', () => { const container = document.createElement('div'); ReactDOM.render(<span>a</span>, container); ReactDOM.unstable_batchedUpdates(function () { ReactDOM.unmountComponentAtNode(container); ReactDOM.render(<span>b</span>, container); }); expect(container.textContent).toBe('b'); }); it('handles reentrant mounting in synchronous mode', () => { let mounts = 0; class Editor extends React.Component { render() { return <div>{this.props.text}</div>; } componentDidMount() { mounts++; // This should be called only once but we guard just in case. if (!this.props.rendered) { this.props.onChange({rendered: true}); } } } const container = document.createElement('div'); function render() { ReactDOM.render( <Editor onChange={newProps => { props = {...props, ...newProps}; render(); }} {...props} />, container, ); } let props = {text: 'hello', rendered: false}; render(); props = {...props, text: 'goodbye'}; render(); expect(container.textContent).toBe('goodbye'); expect(mounts).toBe(1); }); it('mounts and unmounts are sync even in a batch', () => { const ops = []; const container = document.createElement('div'); ReactDOM.unstable_batchedUpdates(() => { ReactDOM.render(<div>Hello</div>, container); ops.push(container.textContent); ReactDOM.unmountComponentAtNode(container); ops.push(container.textContent); }); expect(ops).toEqual(['Hello', '']); }); it( 'in legacy mode, updates in componentWillUpdate and componentDidUpdate ' + 'should both flush in the immediately subsequent commit', () => { const ops = []; class Foo extends React.Component { state = {a: false, b: false}; UNSAFE_componentWillUpdate(_, nextState) { if (!nextState.a) { this.setState({a: true}); } } componentDidUpdate() { ops.push('Foo updated'); if (!this.state.b) { this.setState({b: true}); } } render() { ops.push(`a: ${this.state.a}, b: ${this.state.b}`); return null; } } const container = document.createElement('div'); // Mount ReactDOM.render(<Foo />, container); // Root update ReactDOM.render(<Foo />, container); expect(ops).toEqual([ // Mount 'a: false, b: false', // Root update 'a: false, b: false', 'Foo updated', // Subsequent update (both a and b should have flushed) 'a: true, b: true', 'Foo updated', // There should not be any additional updates ]); }, ); it( 'in legacy mode, updates in componentWillUpdate and componentDidUpdate ' + '(on a sibling) should both flush in the immediately subsequent commit', () => { const ops = []; class Foo extends React.Component { state = {a: false}; UNSAFE_componentWillUpdate(_, nextState) { if (!nextState.a) { this.setState({a: true}); } } componentDidUpdate() { ops.push('Foo updated'); } render() { ops.push(`a: ${this.state.a}`); return null; } } class Bar extends React.Component { state = {b: false}; componentDidUpdate() { ops.push('Bar updated'); if (!this.state.b) { this.setState({b: true}); } } render() { ops.push(`b: ${this.state.b}`); return null; } } const container = document.createElement('div'); // Mount ReactDOM.render( <div> <Foo /> <Bar /> </div>, container, ); // Root update ReactDOM.render( <div> <Foo /> <Bar /> </div>, container, ); expect(ops).toEqual([ // Mount 'a: false', 'b: false', // Root update 'a: false', 'b: false', 'Foo updated', 'Bar updated', // Subsequent update (both a and b should have flushed) 'a: true', 'b: true', 'Foo updated', 'Bar updated', // There should not be any additional updates ]); }, ); it('uses correct base state for setState inside render phase', () => { const ops = []; class Foo extends React.Component { state = {step: 0}; render() { const memoizedStep = this.state.step; this.setState(baseState => { const baseStep = baseState.step; ops.push(`base: ${baseStep}, memoized: ${memoizedStep}`); return baseStep === 0 ? {step: 1} : null; }); return null; } } const container = document.createElement('div'); expect(() => ReactDOM.render(<Foo />, container)).toErrorDev( 'Cannot update during an existing state transition', ); expect(ops).toEqual(['base: 0, memoized: 0', 'base: 1, memoized: 1']); }); it('does not re-render if state update is null', () => { const container = document.createElement('div'); let instance; let ops = []; class Foo extends React.Component { render() { instance = this; ops.push('render'); return <div />; } } ReactDOM.render(<Foo />, container); ops = []; instance.setState(() => null); expect(ops).toEqual([]); }); // Will change once we switch to async by default it('synchronously renders hidden subtrees', () => { const container = document.createElement('div'); let ops = []; function Baz() { ops.push('Baz'); return null; } function Bar() { ops.push('Bar'); return null; } function Foo() { ops.push('Foo'); return ( <div> <div hidden={true}> <Bar /> </div> <Baz /> </div> ); } // Mount ReactDOM.render(<Foo />, container); expect(ops).toEqual(['Foo', 'Bar', 'Baz']); ops = []; // Update ReactDOM.render(<Foo />, container); expect(ops).toEqual(['Foo', 'Bar', 'Baz']); }); // @gate www it('delays sync updates inside hidden subtrees in Concurrent Mode', async () => { const container = document.createElement('div'); function Baz() { Scheduler.log('Baz'); return <p>baz</p>; } let setCounter; function Bar() { const [counter, _setCounter] = React.useState(0); setCounter = _setCounter; Scheduler.log('Bar'); return <p>bar {counter}</p>; } function Foo() { Scheduler.log('Foo'); React.useEffect(() => { Scheduler.log('Foo#effect'); }); return ( <div> <LegacyHiddenDiv mode="hidden"> <Bar /> </LegacyHiddenDiv> <Baz /> </div> ); } const root = ReactDOMClient.createRoot(container); let hiddenDiv; await act(async () => { root.render(<Foo />); await waitFor(['Foo', 'Baz', 'Foo#effect']); hiddenDiv = container.firstChild.firstChild; expect(hiddenDiv.hidden).toBe(true); expect(hiddenDiv.innerHTML).toBe(''); // Run offscreen update await waitForAll(['Bar']); expect(hiddenDiv.hidden).toBe(true); expect(hiddenDiv.innerHTML).toBe('<p>bar 0</p>'); }); ReactDOM.flushSync(() => { setCounter(1); }); // Should not flush yet expect(hiddenDiv.innerHTML).toBe('<p>bar 0</p>'); // Run offscreen update await waitForAll(['Bar']); expect(hiddenDiv.innerHTML).toBe('<p>bar 1</p>'); }); it('can render ridiculously large number of roots without triggering infinite update loop error', () => { class Foo extends React.Component { componentDidMount() { const limit = 1200; for (let i = 0; i < limit; i++) { if (i < limit - 1) { ReactDOM.render(<div />, document.createElement('div')); } else { ReactDOM.render(<div />, document.createElement('div'), () => { // The "nested update limit" error isn't thrown until setState this.setState({}); }); } } } render() { return null; } } const container = document.createElement('div'); ReactDOM.render(<Foo />, container); }); it('resets the update counter for unrelated updates', () => { const container = document.createElement('div'); const ref = React.createRef(); class EventuallyTerminating extends React.Component { state = {step: 0}; componentDidMount() { this.setState({step: 1}); } componentDidUpdate() { if (this.state.step < limit) { this.setState({step: this.state.step + 1}); } } render() { return this.state.step; } } let limit = 55; expect(() => { ReactDOM.render(<EventuallyTerminating ref={ref} />, container); }).toThrow('Maximum'); // Verify that we don't go over the limit if these updates are unrelated. limit -= 10; ReactDOM.render(<EventuallyTerminating ref={ref} />, container); expect(container.textContent).toBe(limit.toString()); ref.current.setState({step: 0}); expect(container.textContent).toBe(limit.toString()); ref.current.setState({step: 0}); expect(container.textContent).toBe(limit.toString()); limit += 10; expect(() => { ref.current.setState({step: 0}); }).toThrow('Maximum'); expect(ref.current).toBe(null); }); it('does not fall into an infinite update loop', () => { class NonTerminating extends React.Component { state = {step: 0}; componentDidMount() { this.setState({step: 1}); } UNSAFE_componentWillUpdate() { this.setState({step: 2}); } render() { return ( <div> Hello {this.props.name} {this.state.step} </div> ); } } const container = document.createElement('div'); expect(() => { ReactDOM.render(<NonTerminating />, container); }).toThrow('Maximum'); }); it('does not fall into an infinite update loop with useLayoutEffect', () => { function NonTerminating() { const [step, setStep] = React.useState(0); React.useLayoutEffect(() => { setStep(x => x + 1); }); return step; } const container = document.createElement('div'); expect(() => { ReactDOM.render(<NonTerminating />, container); }).toThrow('Maximum'); }); it('can recover after falling into an infinite update loop', () => { class NonTerminating extends React.Component { state = {step: 0}; componentDidMount() { this.setState({step: 1}); } componentDidUpdate() { this.setState({step: 2}); } render() { return this.state.step; } } class Terminating extends React.Component { state = {step: 0}; componentDidMount() { this.setState({step: 1}); } render() { return this.state.step; } } const container = document.createElement('div'); expect(() => { ReactDOM.render(<NonTerminating />, container); }).toThrow('Maximum'); ReactDOM.render(<Terminating />, container); expect(container.textContent).toBe('1'); expect(() => { ReactDOM.render(<NonTerminating />, container); }).toThrow('Maximum'); ReactDOM.render(<Terminating />, container); expect(container.textContent).toBe('1'); }); it('does not fall into mutually recursive infinite update loop with same container', () => { // Note: this test would fail if there were two or more different roots. class A extends React.Component { componentDidMount() { ReactDOM.render(<B />, container); } render() { return null; } } class B extends React.Component { componentDidMount() { ReactDOM.render(<A />, container); } render() { return null; } } const container = document.createElement('div'); expect(() => { ReactDOM.render(<A />, container); }).toThrow('Maximum'); }); it('does not fall into an infinite error loop', () => { function BadRender() { throw new Error('error'); } class ErrorBoundary extends React.Component { componentDidCatch() { // Schedule a no-op state update to avoid triggering a DEV warning in the test. this.setState({}); this.props.parent.remount(); } render() { return <BadRender />; } } class NonTerminating extends React.Component { state = {step: 0}; remount() { this.setState(state => ({step: state.step + 1})); } render() { return <ErrorBoundary key={this.state.step} parent={this} />; } } const container = document.createElement('div'); expect(() => { ReactDOM.render(<NonTerminating />, container); }).toThrow('Maximum'); }); it('can schedule ridiculously many updates within the same batch without triggering a maximum update error', () => { const subscribers = []; class Child extends React.Component { state = {value: 'initial'}; componentDidMount() { subscribers.push(this); } render() { return null; } } class App extends React.Component { render() { const children = []; for (let i = 0; i < 1200; i++) { children.push(<Child key={i} />); } return children; } } const container = document.createElement('div'); ReactDOM.render(<App />, container); ReactDOM.unstable_batchedUpdates(() => { subscribers.forEach(s => { s.setState({value: 'update'}); }); }); }); // TODO: Replace this branch with @gate pragmas if (__DEV__) { it('warns about a deferred infinite update loop with useEffect', async () => { function NonTerminating() { const [step, setStep] = React.useState(0); React.useEffect(() => { setStep(x => x + 1); }); return step; } function App() { return <NonTerminating />; } let error = null; let stack = null; const originalConsoleError = console.error; console.error = (e, s) => { error = e; stack = s; Scheduler.log('stop'); }; try { const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); root.render(<App />); await waitFor(['stop']); } finally { console.error = originalConsoleError; } expect(error).toContain('Maximum update depth exceeded'); expect(stack).toContain('at NonTerminating'); }); it('can have nested updates if they do not cross the limit', async () => { let _setStep; const LIMIT = 50; function Terminating() { const [step, setStep] = React.useState(0); _setStep = setStep; React.useEffect(() => { if (step < LIMIT) { setStep(x => x + 1); } }); Scheduler.log(step); return step; } const container = document.createElement('div'); await act(() => { ReactDOM.render(<Terminating />, container); }); expect(container.textContent).toBe('50'); await act(() => { _setStep(0); }); expect(container.textContent).toBe('50'); }); it('can have many updates inside useEffect without triggering a warning', async () => { function Terminating() { const [step, setStep] = React.useState(0); React.useEffect(() => { for (let i = 0; i < 1000; i++) { setStep(x => x + 1); } Scheduler.log('Done'); }, []); return step; } const container = document.createElement('div'); await act(() => { ReactDOM.render(<Terminating />, container); }); assertLog(['Done']); expect(container.textContent).toBe('1000'); }); } it('prevents infinite update loop triggered by synchronous updates in useEffect', () => { // Ignore flushSync warning spyOnDev(console, 'error').mockImplementation(() => {}); function NonTerminating() { const [step, setStep] = React.useState(0); React.useEffect(() => { // Other examples of synchronous updates in useEffect are imperative // event dispatches like `el.focus`, or `useSyncExternalStore`, which // may schedule a synchronous update upon subscribing if it detects // that the store has been mutated since the initial render. // // (Originally I wrote this test using `el.focus` but those errors // get dispatched in a JSDOM event and I don't know how to "catch" those // so that they don't fail the test.) ReactDOM.flushSync(() => { setStep(step + 1); }); }, [step]); return step; } const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); expect(() => { ReactDOM.flushSync(() => { root.render(<NonTerminating />); }); }).toThrow('Maximum update depth exceeded'); }); });
24.765382
118
0.559112
null
'use strict'; const forks = require('./forks'); const {UMD_DEV, UMD_PROD, UMD_PROFILING} = require('./bundles').bundleTypes; // For any external that is used in a DEV-only condition, explicitly // specify whether it has side effects during import or not. This lets // us know whether we can safely omit them when they are unused. const HAS_NO_SIDE_EFFECTS_ON_IMPORT = false; // const HAS_SIDE_EFFECTS_ON_IMPORT = true; const importSideEffects = Object.freeze({ fs: HAS_NO_SIDE_EFFECTS_ON_IMPORT, 'fs/promises': HAS_NO_SIDE_EFFECTS_ON_IMPORT, path: HAS_NO_SIDE_EFFECTS_ON_IMPORT, stream: HAS_NO_SIDE_EFFECTS_ON_IMPORT, 'prop-types/checkPropTypes': HAS_NO_SIDE_EFFECTS_ON_IMPORT, 'react-native/Libraries/ReactPrivate/ReactNativePrivateInterface': HAS_NO_SIDE_EFFECTS_ON_IMPORT, scheduler: HAS_NO_SIDE_EFFECTS_ON_IMPORT, react: HAS_NO_SIDE_EFFECTS_ON_IMPORT, 'react-dom/server': HAS_NO_SIDE_EFFECTS_ON_IMPORT, 'react/jsx-dev-runtime': HAS_NO_SIDE_EFFECTS_ON_IMPORT, 'react-dom': HAS_NO_SIDE_EFFECTS_ON_IMPORT, url: HAS_NO_SIDE_EFFECTS_ON_IMPORT, ReactNativeInternalFeatureFlags: HAS_NO_SIDE_EFFECTS_ON_IMPORT, }); // Bundles exporting globals that other modules rely on. const knownGlobals = Object.freeze({ react: 'React', 'react-dom': 'ReactDOM', 'react-dom/server': 'ReactDOMServer', 'react-interactions/events/tap': 'ReactEventsTap', scheduler: 'Scheduler', 'scheduler/unstable_mock': 'SchedulerMock', ReactNativeInternalFeatureFlags: 'ReactNativeInternalFeatureFlags', }); // Given ['react'] in bundle externals, returns { 'react': 'React' }. function getPeerGlobals(externals, bundleType) { const peerGlobals = {}; externals.forEach(name => { if ( !knownGlobals[name] && (bundleType === UMD_DEV || bundleType === UMD_PROD || bundleType === UMD_PROFILING) ) { throw new Error('Cannot build UMD without a global name for: ' + name); } peerGlobals[name] = knownGlobals[name]; }); return peerGlobals; } // Determines node_modules packages that are safe to assume will exist. function getDependencies(bundleType, entry) { // Replaces any part of the entry that follow the package name (like // "/server" in "react-dom/server") by the path to the package settings const packageJson = require(entry.replace(/(\/.*)?$/, '/package.json')); // Both deps and peerDeps are assumed as accessible. return Array.from( new Set([ ...Object.keys(packageJson.dependencies || {}), ...Object.keys(packageJson.peerDependencies || {}), ]) ); } // Hijacks some modules for optimization and integration reasons. function getForks(bundleType, entry, moduleType, bundle) { const forksForBundle = {}; Object.keys(forks).forEach(srcModule => { const dependencies = getDependencies(bundleType, entry); const targetModule = forks[srcModule]( bundleType, entry, dependencies, moduleType, bundle ); if (targetModule === null) { return; } forksForBundle[srcModule] = targetModule; }); return forksForBundle; } function getImportSideEffects() { return importSideEffects; } module.exports = { getImportSideEffects, getPeerGlobals, getDependencies, getForks, };
31.49
77
0.6992
owtf
'use strict'; // Do this as the first thing so that any code reading it knows the right env. process.env.BABEL_ENV = 'test'; process.env.NODE_ENV = 'test'; process.env.PUBLIC_URL = ''; // Makes the script crash on unhandled rejections instead of silently // ignoring them. In the future, promise rejections that are not handled will // terminate the Node.js process with a non-zero exit code. process.on('unhandledRejection', err => { throw err; }); // Ensure environment variables are read. require('../config/env'); const jest = require('jest'); const execSync = require('child_process').execSync; let argv = process.argv.slice(2); function isInGitRepository() { try { execSync('git rev-parse --is-inside-work-tree', {stdio: 'ignore'}); return true; } catch (e) { return false; } } function isInMercurialRepository() { try { execSync('hg --cwd . root', {stdio: 'ignore'}); return true; } catch (e) { return false; } } // Watch unless on CI or explicitly running all tests if ( !process.env.CI && argv.indexOf('--watchAll') === -1 && argv.indexOf('--watchAll=false') === -1 ) { // https://github.com/facebook/create-react-app/issues/5210 const hasSourceControl = isInGitRepository() || isInMercurialRepository(); argv.push(hasSourceControl ? '--watch' : '--watchAll'); } jest.run(argv);
24.903846
78
0.676077
Python-Penetration-Testing-for-Developers
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-server-dom-turbopack-server.node.production.min.js'); } else { module.exports = require('./cjs/react-server-dom-turbopack-server.node.development.js'); }
31.125
93
0.710938
Python-Penetration-Testing-Cookbook
/** * 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 { getDataType, getDisplayNameForReactElement, getAllEnumerableKeys, getInObject, formatDataForPreview, setInObject, } from 'react-devtools-shared/src/utils'; import type { DehydratedData, InspectedElementPath, } from 'react-devtools-shared/src/frontend/types'; export const meta = { inspectable: (Symbol('inspectable'): symbol), inspected: (Symbol('inspected'): symbol), name: (Symbol('name'): symbol), preview_long: (Symbol('preview_long'): symbol), preview_short: (Symbol('preview_short'): symbol), readonly: (Symbol('readonly'): symbol), size: (Symbol('size'): symbol), type: (Symbol('type'): symbol), unserializable: (Symbol('unserializable'): symbol), }; export type Dehydrated = { inspectable: boolean, name: string | null, preview_long: string | null, preview_short: string | null, readonly?: boolean, size?: number, type: string, }; // Typed arrays and other complex iteratable objects (e.g. Map, Set, ImmutableJS) need special handling. // These objects can't be serialized without losing type information, // so a "Unserializable" type wrapper is used (with meta-data keys) to send nested values- // while preserving the original type and name. export type Unserializable = { name: string | null, preview_long: string | null, preview_short: string | null, readonly?: boolean, size?: number, type: string, unserializable: boolean, [string | number]: any, }; // This threshold determines the depth at which the bridge "dehydrates" nested data. // Dehydration means that we don't serialize the data for e.g. postMessage or stringify, // unless the frontend explicitly requests it (e.g. a user clicks to expand a props object). // // Reducing this threshold will improve the speed of initial component inspection, // but may decrease the responsiveness of expanding objects/arrays to inspect further. const LEVEL_THRESHOLD = 2; /** * Generate the dehydrated metadata for complex object instances */ function createDehydrated( type: string, inspectable: boolean, data: Object, cleaned: Array<Array<string | number>>, path: Array<string | number>, ): Dehydrated { cleaned.push(path); const dehydrated: Dehydrated = { inspectable, type, preview_long: formatDataForPreview(data, true), preview_short: formatDataForPreview(data, false), name: !data.constructor || data.constructor.name === 'Object' ? '' : data.constructor.name, }; if (type === 'array' || type === 'typed_array') { dehydrated.size = data.length; } else if (type === 'object') { dehydrated.size = Object.keys(data).length; } if (type === 'iterator' || type === 'typed_array') { dehydrated.readonly = true; } return dehydrated; } /** * Strip out complex data (instances, functions, and data nested > LEVEL_THRESHOLD levels deep). * The paths of the stripped out objects are appended to the `cleaned` list. * On the other side of the barrier, the cleaned list is used to "re-hydrate" the cleaned representation into * an object with symbols as attributes, so that a sanitized object can be distinguished from a normal object. * * Input: {"some": {"attr": fn()}, "other": AnInstance} * Output: { * "some": { * "attr": {"name": the fn.name, type: "function"} * }, * "other": { * "name": "AnInstance", * "type": "object", * }, * } * and cleaned = [["some", "attr"], ["other"]] */ export function dehydrate( data: Object, cleaned: Array<Array<string | number>>, unserializable: Array<Array<string | number>>, path: Array<string | number>, isPathAllowed: (path: Array<string | number>) => boolean, level: number = 0, ): $PropertyType<DehydratedData, 'data'> { const type = getDataType(data); let isPathAllowedCheck; switch (type) { case 'html_element': cleaned.push(path); return { inspectable: false, preview_short: formatDataForPreview(data, false), preview_long: formatDataForPreview(data, true), name: data.tagName, type, }; case 'function': cleaned.push(path); return { inspectable: false, preview_short: formatDataForPreview(data, false), preview_long: formatDataForPreview(data, true), name: typeof data.name === 'function' || !data.name ? 'function' : data.name, type, }; case 'string': isPathAllowedCheck = isPathAllowed(path); if (isPathAllowedCheck) { return data; } else { return data.length <= 500 ? data : data.slice(0, 500) + '...'; } case 'bigint': cleaned.push(path); return { inspectable: false, preview_short: formatDataForPreview(data, false), preview_long: formatDataForPreview(data, true), name: data.toString(), type, }; case 'symbol': cleaned.push(path); return { inspectable: false, preview_short: formatDataForPreview(data, false), preview_long: formatDataForPreview(data, true), name: data.toString(), type, }; // React Elements aren't very inspector-friendly, // and often contain private fields or circular references. case 'react_element': cleaned.push(path); return { inspectable: false, preview_short: formatDataForPreview(data, false), preview_long: formatDataForPreview(data, true), name: getDisplayNameForReactElement(data) || 'Unknown', type, }; // ArrayBuffers error if you try to inspect them. case 'array_buffer': case 'data_view': cleaned.push(path); return { inspectable: false, preview_short: formatDataForPreview(data, false), preview_long: formatDataForPreview(data, true), name: type === 'data_view' ? 'DataView' : 'ArrayBuffer', size: data.byteLength, type, }; case 'array': isPathAllowedCheck = isPathAllowed(path); if (level >= LEVEL_THRESHOLD && !isPathAllowedCheck) { return createDehydrated(type, true, data, cleaned, path); } return data.map((item, i) => dehydrate( item, cleaned, unserializable, path.concat([i]), isPathAllowed, isPathAllowedCheck ? 1 : level + 1, ), ); case 'html_all_collection': case 'typed_array': case 'iterator': isPathAllowedCheck = isPathAllowed(path); if (level >= LEVEL_THRESHOLD && !isPathAllowedCheck) { return createDehydrated(type, true, data, cleaned, path); } else { const unserializableValue: Unserializable = { unserializable: true, type: type, readonly: true, size: type === 'typed_array' ? data.length : undefined, preview_short: formatDataForPreview(data, false), preview_long: formatDataForPreview(data, true), name: !data.constructor || data.constructor.name === 'Object' ? '' : data.constructor.name, }; // TRICKY // Don't use [...spread] syntax for this purpose. // This project uses @babel/plugin-transform-spread in "loose" mode which only works with Array values. // Other types (e.g. typed arrays, Sets) will not spread correctly. Array.from(data).forEach( (item, i) => (unserializableValue[i] = dehydrate( item, cleaned, unserializable, path.concat([i]), isPathAllowed, isPathAllowedCheck ? 1 : level + 1, )), ); unserializable.push(path); return unserializableValue; } case 'opaque_iterator': cleaned.push(path); return { inspectable: false, preview_short: formatDataForPreview(data, false), preview_long: formatDataForPreview(data, true), name: data[Symbol.toStringTag], type, }; case 'date': cleaned.push(path); return { inspectable: false, preview_short: formatDataForPreview(data, false), preview_long: formatDataForPreview(data, true), name: data.toString(), type, }; case 'regexp': cleaned.push(path); return { inspectable: false, preview_short: formatDataForPreview(data, false), preview_long: formatDataForPreview(data, true), name: data.toString(), type, }; case 'object': isPathAllowedCheck = isPathAllowed(path); if (level >= LEVEL_THRESHOLD && !isPathAllowedCheck) { return createDehydrated(type, true, data, cleaned, path); } else { const object: { [string]: $PropertyType<DehydratedData, 'data'>, } = {}; getAllEnumerableKeys(data).forEach(key => { const name = key.toString(); object[name] = dehydrate( data[key], cleaned, unserializable, path.concat([name]), isPathAllowed, isPathAllowedCheck ? 1 : level + 1, ); }); return object; } case 'class_instance': isPathAllowedCheck = isPathAllowed(path); if (level >= LEVEL_THRESHOLD && !isPathAllowedCheck) { return createDehydrated(type, true, data, cleaned, path); } const value: Unserializable = { unserializable: true, type, readonly: true, preview_short: formatDataForPreview(data, false), preview_long: formatDataForPreview(data, true), name: data.constructor.name, }; getAllEnumerableKeys(data).forEach(key => { const keyAsString = key.toString(); value[keyAsString] = dehydrate( data[key], cleaned, unserializable, path.concat([keyAsString]), isPathAllowed, isPathAllowedCheck ? 1 : level + 1, ); }); unserializable.push(path); return value; case 'infinity': case 'nan': case 'undefined': // Some values are lossy when sent through a WebSocket. // We dehydrate+rehydrate them to preserve their type. cleaned.push(path); return {type}; default: return data; } } export function fillInPath( object: Object, data: DehydratedData, path: InspectedElementPath, value: any, ) { const target = getInObject(object, path); if (target != null) { if (!target[meta.unserializable]) { delete target[meta.inspectable]; delete target[meta.inspected]; delete target[meta.name]; delete target[meta.preview_long]; delete target[meta.preview_short]; delete target[meta.readonly]; delete target[meta.size]; delete target[meta.type]; } } if (value !== null && data.unserializable.length > 0) { const unserializablePath = data.unserializable[0]; let isMatch = unserializablePath.length === path.length; for (let i = 0; i < path.length; i++) { if (path[i] !== unserializablePath[i]) { isMatch = false; break; } } if (isMatch) { upgradeUnserializable(value, value); } } setInObject(object, path, value); } export function hydrate( object: any, cleaned: Array<Array<string | number>>, unserializable: Array<Array<string | number>>, ): Object { cleaned.forEach((path: Array<string | number>) => { const length = path.length; const last = path[length - 1]; const parent = getInObject(object, path.slice(0, length - 1)); if (!parent || !parent.hasOwnProperty(last)) { return; } const value = parent[last]; if (!value) { return; } else if (value.type === 'infinity') { parent[last] = Infinity; } else if (value.type === 'nan') { parent[last] = NaN; } else if (value.type === 'undefined') { parent[last] = undefined; } else { // Replace the string keys with Symbols so they're non-enumerable. const replaced: {[key: symbol]: boolean | string} = {}; replaced[meta.inspectable] = !!value.inspectable; replaced[meta.inspected] = false; replaced[meta.name] = value.name; replaced[meta.preview_long] = value.preview_long; replaced[meta.preview_short] = value.preview_short; replaced[meta.size] = value.size; replaced[meta.readonly] = !!value.readonly; replaced[meta.type] = value.type; parent[last] = replaced; } }); unserializable.forEach((path: Array<string | number>) => { const length = path.length; const last = path[length - 1]; const parent = getInObject(object, path.slice(0, length - 1)); if (!parent || !parent.hasOwnProperty(last)) { return; } const node = parent[last]; const replacement = { ...node, }; upgradeUnserializable(replacement, node); parent[last] = replacement; }); return object; } function upgradeUnserializable(destination: Object, source: Object) { Object.defineProperties(destination, { // $FlowFixMe[invalid-computed-prop] [meta.inspected]: { configurable: true, enumerable: false, value: !!source.inspected, }, // $FlowFixMe[invalid-computed-prop] [meta.name]: { configurable: true, enumerable: false, value: source.name, }, // $FlowFixMe[invalid-computed-prop] [meta.preview_long]: { configurable: true, enumerable: false, value: source.preview_long, }, // $FlowFixMe[invalid-computed-prop] [meta.preview_short]: { configurable: true, enumerable: false, value: source.preview_short, }, // $FlowFixMe[invalid-computed-prop] [meta.size]: { configurable: true, enumerable: false, value: source.size, }, // $FlowFixMe[invalid-computed-prop] [meta.readonly]: { configurable: true, enumerable: false, value: !!source.readonly, }, // $FlowFixMe[invalid-computed-prop] [meta.type]: { configurable: true, enumerable: false, value: source.type, }, // $FlowFixMe[invalid-computed-prop] [meta.unserializable]: { configurable: true, enumerable: false, value: !!source.unserializable, }, }); delete destination.inspected; delete destination.name; delete destination.preview_long; delete destination.preview_short; delete destination.size; delete destination.readonly; delete destination.type; delete destination.unserializable; }
27.339048
111
0.613161
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 type {ReactContext} from 'shared/ReactTypes'; import * as React from 'react'; import {createContext, useCallback, useContext, useEffect} from 'react'; import {createResource} from '../../cache'; import {BridgeContext, StoreContext} from '../context'; import {TreeStateContext} from './TreeContext'; import {backendToFrontendSerializedElementMapper} from 'react-devtools-shared/src/utils'; import type {OwnersList} from 'react-devtools-shared/src/backend/types'; import type { Element, SerializedElement, } from 'react-devtools-shared/src/frontend/types'; import type {Resource, Thenable} from '../../cache'; type Context = (id: number) => Array<SerializedElement> | null; const OwnersListContext: ReactContext<Context> = createContext<Context>( ((null: any): Context), ); OwnersListContext.displayName = 'OwnersListContext'; type ResolveFn = (ownersList: Array<SerializedElement> | null) => void; type InProgressRequest = { promise: Thenable<Array<SerializedElement>>, resolveFn: ResolveFn, }; const inProgressRequests: WeakMap<Element, InProgressRequest> = new WeakMap(); const resource: Resource< Element, Element, Array<SerializedElement>, > = createResource( (element: Element) => { const request = inProgressRequests.get(element); if (request != null) { return request.promise; } let resolveFn: | ResolveFn | (( result: Promise<Array<SerializedElement>> | Array<SerializedElement>, ) => void) = ((null: any): ResolveFn); const promise = new Promise(resolve => { resolveFn = resolve; }); // $FlowFixMe[incompatible-call] found when upgrading Flow inProgressRequests.set(element, {promise, resolveFn}); return (promise: $FlowFixMe); }, (element: Element) => element, {useWeakMap: true}, ); type Props = { children: React$Node, }; function OwnersListContextController({children}: Props): React.Node { const bridge = useContext(BridgeContext); const store = useContext(StoreContext); const {ownerID} = useContext(TreeStateContext); const read = useCallback( (id: number) => { const element = store.getElementByID(id); if (element !== null) { return resource.read(element); } else { return null; } }, [store], ); useEffect(() => { const onOwnersList = (ownersList: OwnersList) => { const id = ownersList.id; const element = store.getElementByID(id); if (element !== null) { const request = inProgressRequests.get(element); if (request != null) { inProgressRequests.delete(element); request.resolveFn( ownersList.owners === null ? null : ownersList.owners.map(backendToFrontendSerializedElementMapper), ); } } }; bridge.addListener('ownersList', onOwnersList); return () => bridge.removeListener('ownersList', onOwnersList); }, [bridge, store]); // This effect requests an updated owners list any time the selected owner changes useEffect(() => { if (ownerID !== null) { const rendererID = store.getRendererIDForElement(ownerID); if (rendererID !== null) { bridge.send('getOwnersList', {id: ownerID, rendererID}); } } return () => {}; }, [bridge, ownerID, store]); return ( <OwnersListContext.Provider value={read}> {children} </OwnersListContext.Provider> ); } export {OwnersListContext, OwnersListContextController};
26.93985
89
0.66245
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 ReactFeatureFlags; let ReactNoop; let Scheduler; let ReactTestRenderer; let act; let AdvanceTime; let assertLog; let waitFor; let waitForAll; let waitForThrow; function loadModules({ enableProfilerTimer = true, enableProfilerCommitHooks = true, enableProfilerNestedUpdatePhase = true, enableProfilerNestedUpdateScheduledHook = false, replayFailedUnitOfWorkWithInvokeGuardedCallback = false, useNoopRenderer = false, } = {}) { ReactFeatureFlags = require('shared/ReactFeatureFlags'); ReactFeatureFlags.enableProfilerTimer = enableProfilerTimer; ReactFeatureFlags.enableProfilerCommitHooks = enableProfilerCommitHooks; ReactFeatureFlags.enableProfilerNestedUpdatePhase = enableProfilerNestedUpdatePhase; ReactFeatureFlags.enableProfilerNestedUpdateScheduledHook = enableProfilerNestedUpdateScheduledHook; ReactFeatureFlags.replayFailedUnitOfWorkWithInvokeGuardedCallback = replayFailedUnitOfWorkWithInvokeGuardedCallback; React = require('react'); Scheduler = require('scheduler'); act = require('internal-test-utils').act; if (useNoopRenderer) { ReactNoop = require('react-noop-renderer'); ReactTestRenderer = null; } else { ReactNoop = null; ReactTestRenderer = require('react-test-renderer'); } const InternalTestUtils = require('internal-test-utils'); assertLog = InternalTestUtils.assertLog; waitFor = InternalTestUtils.waitFor; waitForAll = InternalTestUtils.waitForAll; waitForThrow = InternalTestUtils.waitForThrow; AdvanceTime = class extends React.Component { static defaultProps = { byAmount: 10, shouldComponentUpdate: true, }; shouldComponentUpdate(nextProps) { return nextProps.shouldComponentUpdate; } render() { // Simulate time passing when this component is rendered Scheduler.unstable_advanceTime(this.props.byAmount); return this.props.children || null; } }; } describe('Profiler', () => { describe('works in profiling and non-profiling bundles', () => { [true, false].forEach(enableProfilerTimer => { describe(`enableProfilerTimer:${ enableProfilerTimer ? 'enabled' : 'disabled' }`, () => { beforeEach(() => { jest.resetModules(); loadModules({enableProfilerTimer}); }); // This will throw in production too, // But the test is only interested in verifying the DEV error message. if (__DEV__ && enableProfilerTimer) { it('should warn if required params are missing', () => { expect(() => { ReactTestRenderer.create(<React.Profiler />); }).toErrorDev( 'Profiler must specify an "id" of type `string` as a prop. Received the type `undefined` instead.', { withoutStack: true, }, ); }); } it('should support an empty Profiler (with no children)', () => { // As root expect( ReactTestRenderer.create( <React.Profiler id="label" onRender={jest.fn()} />, ).toJSON(), ).toMatchSnapshot(); // As non-root expect( ReactTestRenderer.create( <div> <React.Profiler id="label" onRender={jest.fn()} /> </div>, ).toJSON(), ).toMatchSnapshot(); }); it('should render children', () => { const FunctionComponent = ({label}) => <span>{label}</span>; const renderer = ReactTestRenderer.create( <div> <span>outside span</span> <React.Profiler id="label" onRender={jest.fn()}> <span>inside span</span> <FunctionComponent label="function component" /> </React.Profiler> </div>, ); expect(renderer.toJSON()).toMatchSnapshot(); }); it('should support nested Profilers', () => { const FunctionComponent = ({label}) => <div>{label}</div>; class ClassComponent extends React.Component { render() { return <block>{this.props.label}</block>; } } const renderer = ReactTestRenderer.create( <React.Profiler id="outer" onRender={jest.fn()}> <FunctionComponent label="outer function component" /> <React.Profiler id="inner" onRender={jest.fn()}> <ClassComponent label="inner class component" /> <span>inner span</span> </React.Profiler> </React.Profiler>, ); expect(renderer.toJSON()).toMatchSnapshot(); }); }); }); }); }); describe(`onRender`, () => { beforeEach(() => { jest.resetModules(); loadModules(); }); it('should handle errors thrown', () => { const callback = jest.fn(id => { if (id === 'throw') { throw Error('expected'); } }); let didMount = false; class ClassComponent extends React.Component { componentDidMount() { didMount = true; } render() { return this.props.children; } } // Errors thrown from onRender should not break the commit phase, // Or prevent other lifecycles from being called. expect(() => ReactTestRenderer.create( <ClassComponent> <React.Profiler id="do-not-throw" onRender={callback}> <React.Profiler id="throw" onRender={callback}> <div /> </React.Profiler> </React.Profiler> </ClassComponent>, ), ).toThrow('expected'); expect(didMount).toBe(true); expect(callback).toHaveBeenCalledTimes(2); }); it('is not invoked until the commit phase', async () => { const callback = jest.fn(); const Yield = ({value}) => { Scheduler.log(value); return null; }; React.startTransition(() => { ReactTestRenderer.create( <React.Profiler id="test" onRender={callback}> <Yield value="first" /> <Yield value="last" /> </React.Profiler>, { isConcurrent: true, }, ); }); // Times are logged until a render is committed. await waitFor(['first']); expect(callback).toHaveBeenCalledTimes(0); await waitForAll(['last']); expect(callback).toHaveBeenCalledTimes(1); }); it('does not record times for components outside of Profiler tree', () => { // Mock the Scheduler module so we can track how many times the current // time is read jest.mock('scheduler', obj => { const ActualScheduler = jest.requireActual('scheduler/unstable_mock'); return { ...ActualScheduler, unstable_now: function mockUnstableNow() { ActualScheduler.log('read current time'); return ActualScheduler.unstable_now(); }, }; }); jest.resetModules(); loadModules(); // Clear yields in case the current time is read during initialization. Scheduler.unstable_clearLog(); ReactTestRenderer.create( <div> <AdvanceTime /> <AdvanceTime /> <AdvanceTime /> <AdvanceTime /> <AdvanceTime /> </div>, ); // Restore original mock jest.mock('scheduler', () => jest.requireActual('scheduler/unstable_mock')); // TODO: unstable_now is called by more places than just the profiler. // Rewrite this test so it's less fragile. if (gate(flags => flags.enableDeferRootSchedulingToMicrotask)) { assertLog(['read current time', 'read current time']); } else { assertLog([ 'read current time', 'read current time', 'read current time', 'read current time', 'read current time', ]); } }); it('does not report work done on a sibling', async () => { const callback = jest.fn(); const DoesNotUpdate = React.memo( function DoesNotUpdateInner() { Scheduler.unstable_advanceTime(10); return null; }, () => true, ); let updateProfilerSibling; function ProfilerSibling() { const [count, setCount] = React.useState(0); updateProfilerSibling = () => setCount(count + 1); return null; } function App() { return ( <React.Fragment> <React.Profiler id="test" onRender={callback}> <DoesNotUpdate /> </React.Profiler> <ProfilerSibling /> </React.Fragment> ); } const renderer = ReactTestRenderer.create(<App />); expect(callback).toHaveBeenCalledTimes(1); let call = callback.mock.calls[0]; expect(call).toHaveLength(6); expect(call[0]).toBe('test'); expect(call[1]).toBe('mount'); expect(call[2]).toBe(10); // actual time expect(call[3]).toBe(10); // base time expect(call[4]).toBe(0); // start time expect(call[5]).toBe(10); // commit time callback.mockReset(); Scheduler.unstable_advanceTime(20); // 10 -> 30 renderer.update(<App />); if (gate(flags => flags.enableUseJSStackToTrackPassiveDurations)) { // None of the Profiler's subtree was rendered because App bailed out before the Profiler. // So we expect onRender not to be called. expect(callback).not.toHaveBeenCalled(); } else { // Updating a parent reports a re-render, // since React technically did a little bit of work between the Profiler and the bailed out subtree. // This is not optimal but it's how the old reconciler fork works. expect(callback).toHaveBeenCalledTimes(1); call = callback.mock.calls[0]; expect(call).toHaveLength(6); expect(call[0]).toBe('test'); expect(call[1]).toBe('update'); expect(call[2]).toBe(0); // actual time expect(call[3]).toBe(10); // base time expect(call[4]).toBe(30); // start time expect(call[5]).toBe(30); // commit time callback.mockReset(); } Scheduler.unstable_advanceTime(20); // 30 -> 50 // Updating a sibling should not report a re-render. await act(() => updateProfilerSibling()); expect(callback).not.toHaveBeenCalled(); }); it('logs render times for both mount and update', () => { const callback = jest.fn(); Scheduler.unstable_advanceTime(5); // 0 -> 5 const renderer = ReactTestRenderer.create( <React.Profiler id="test" onRender={callback}> <AdvanceTime /> </React.Profiler>, ); expect(callback).toHaveBeenCalledTimes(1); let [call] = callback.mock.calls; expect(call).toHaveLength(6); expect(call[0]).toBe('test'); expect(call[1]).toBe('mount'); expect(call[2]).toBe(10); // actual time expect(call[3]).toBe(10); // base time expect(call[4]).toBe(5); // start time expect(call[5]).toBe(15); // commit time callback.mockReset(); Scheduler.unstable_advanceTime(20); // 15 -> 35 renderer.update( <React.Profiler id="test" onRender={callback}> <AdvanceTime /> </React.Profiler>, ); expect(callback).toHaveBeenCalledTimes(1); [call] = callback.mock.calls; expect(call).toHaveLength(6); expect(call[0]).toBe('test'); expect(call[1]).toBe('update'); expect(call[2]).toBe(10); // actual time expect(call[3]).toBe(10); // base time expect(call[4]).toBe(35); // start time expect(call[5]).toBe(45); // commit time callback.mockReset(); Scheduler.unstable_advanceTime(20); // 45 -> 65 renderer.update( <React.Profiler id="test" onRender={callback}> <AdvanceTime byAmount={4} /> </React.Profiler>, ); expect(callback).toHaveBeenCalledTimes(1); [call] = callback.mock.calls; expect(call).toHaveLength(6); expect(call[0]).toBe('test'); expect(call[1]).toBe('update'); expect(call[2]).toBe(4); // actual time expect(call[3]).toBe(4); // base time expect(call[4]).toBe(65); // start time expect(call[5]).toBe(69); // commit time }); it('includes render times of nested Profilers in their parent times', () => { const callback = jest.fn(); Scheduler.unstable_advanceTime(5); // 0 -> 5 ReactTestRenderer.create( <React.Fragment> <React.Profiler id="parent" onRender={callback}> <AdvanceTime byAmount={10}> <React.Profiler id="child" onRender={callback}> <AdvanceTime byAmount={20} /> </React.Profiler> </AdvanceTime> </React.Profiler> </React.Fragment>, ); expect(callback).toHaveBeenCalledTimes(2); // Callbacks bubble (reverse order). const [childCall, parentCall] = callback.mock.calls; expect(childCall[0]).toBe('child'); expect(parentCall[0]).toBe('parent'); // Parent times should include child times expect(childCall[2]).toBe(20); // actual time expect(childCall[3]).toBe(20); // base time expect(childCall[4]).toBe(15); // start time expect(childCall[5]).toBe(35); // commit time expect(parentCall[2]).toBe(30); // actual time expect(parentCall[3]).toBe(30); // base time expect(parentCall[4]).toBe(5); // start time expect(parentCall[5]).toBe(35); // commit time }); it('traces sibling Profilers separately', () => { const callback = jest.fn(); Scheduler.unstable_advanceTime(5); // 0 -> 5 ReactTestRenderer.create( <React.Fragment> <React.Profiler id="first" onRender={callback}> <AdvanceTime byAmount={20} /> </React.Profiler> <React.Profiler id="second" onRender={callback}> <AdvanceTime byAmount={5} /> </React.Profiler> </React.Fragment>, ); expect(callback).toHaveBeenCalledTimes(2); const [firstCall, secondCall] = callback.mock.calls; expect(firstCall[0]).toBe('first'); expect(secondCall[0]).toBe('second'); // Parent times should include child times expect(firstCall[2]).toBe(20); // actual time expect(firstCall[3]).toBe(20); // base time expect(firstCall[4]).toBe(5); // start time expect(firstCall[5]).toBe(30); // commit time expect(secondCall[2]).toBe(5); // actual time expect(secondCall[3]).toBe(5); // base time expect(secondCall[4]).toBe(25); // start time expect(secondCall[5]).toBe(30); // commit time }); it('does not include time spent outside of profile root', () => { const callback = jest.fn(); Scheduler.unstable_advanceTime(5); // 0 -> 5 ReactTestRenderer.create( <React.Fragment> <AdvanceTime byAmount={20} /> <React.Profiler id="test" onRender={callback}> <AdvanceTime byAmount={5} /> </React.Profiler> <AdvanceTime byAmount={20} /> </React.Fragment>, ); expect(callback).toHaveBeenCalledTimes(1); const [call] = callback.mock.calls; expect(call[0]).toBe('test'); expect(call[2]).toBe(5); // actual time expect(call[3]).toBe(5); // base time expect(call[4]).toBe(25); // start time expect(call[5]).toBe(50); // commit time }); it('is not called when blocked by sCU false', () => { const callback = jest.fn(); let instance; class Updater extends React.Component { state = {}; render() { instance = this; return this.props.children; } } const renderer = ReactTestRenderer.create( <React.Profiler id="outer" onRender={callback}> <Updater> <React.Profiler id="inner" onRender={callback}> <div /> </React.Profiler> </Updater> </React.Profiler>, ); // All profile callbacks are called for initial render expect(callback).toHaveBeenCalledTimes(2); callback.mockReset(); renderer.unstable_flushSync(() => { instance.setState({ count: 1, }); }); // Only call onRender for paths that have re-rendered. // Since the Updater's props didn't change, // React does not re-render its children. expect(callback).toHaveBeenCalledTimes(1); expect(callback.mock.calls[0][0]).toBe('outer'); }); it('decreases actual time but not base time when sCU prevents an update', () => { const callback = jest.fn(); Scheduler.unstable_advanceTime(5); // 0 -> 5 const renderer = ReactTestRenderer.create( <React.Profiler id="test" onRender={callback}> <AdvanceTime byAmount={10}> <AdvanceTime byAmount={13} shouldComponentUpdate={false} /> </AdvanceTime> </React.Profiler>, ); expect(callback).toHaveBeenCalledTimes(1); Scheduler.unstable_advanceTime(30); // 28 -> 58 renderer.update( <React.Profiler id="test" onRender={callback}> <AdvanceTime byAmount={4}> <AdvanceTime byAmount={7} shouldComponentUpdate={false} /> </AdvanceTime> </React.Profiler>, ); expect(callback).toHaveBeenCalledTimes(2); const [mountCall, updateCall] = callback.mock.calls; expect(mountCall[1]).toBe('mount'); expect(mountCall[2]).toBe(23); // actual time expect(mountCall[3]).toBe(23); // base time expect(mountCall[4]).toBe(5); // start time expect(mountCall[5]).toBe(28); // commit time expect(updateCall[1]).toBe('update'); expect(updateCall[2]).toBe(4); // actual time expect(updateCall[3]).toBe(17); // base time expect(updateCall[4]).toBe(58); // start time expect(updateCall[5]).toBe(62); // commit time }); it('includes time spent in render phase lifecycles', () => { class WithLifecycles extends React.Component { state = {}; static getDerivedStateFromProps() { Scheduler.unstable_advanceTime(3); return null; } shouldComponentUpdate() { Scheduler.unstable_advanceTime(7); return true; } render() { Scheduler.unstable_advanceTime(5); return null; } } const callback = jest.fn(); Scheduler.unstable_advanceTime(5); // 0 -> 5 const renderer = ReactTestRenderer.create( <React.Profiler id="test" onRender={callback}> <WithLifecycles /> </React.Profiler>, ); Scheduler.unstable_advanceTime(15); // 13 -> 28 renderer.update( <React.Profiler id="test" onRender={callback}> <WithLifecycles /> </React.Profiler>, ); expect(callback).toHaveBeenCalledTimes(2); const [mountCall, updateCall] = callback.mock.calls; expect(mountCall[1]).toBe('mount'); expect(mountCall[2]).toBe(8); // actual time expect(mountCall[3]).toBe(8); // base time expect(mountCall[4]).toBe(5); // start time expect(mountCall[5]).toBe(13); // commit time expect(updateCall[1]).toBe('update'); expect(updateCall[2]).toBe(15); // actual time expect(updateCall[3]).toBe(15); // base time expect(updateCall[4]).toBe(28); // start time expect(updateCall[5]).toBe(43); // commit time }); it('should clear nested-update flag when multiple cascading renders are scheduled', async () => { loadModules({ useNoopRenderer: true, }); function Component() { const [didMount, setDidMount] = React.useState(false); const [didMountAndUpdate, setDidMountAndUpdate] = React.useState(false); React.useLayoutEffect(() => { setDidMount(true); }, []); React.useEffect(() => { if (didMount && !didMountAndUpdate) { setDidMountAndUpdate(true); } }, [didMount, didMountAndUpdate]); Scheduler.log(`${didMount}:${didMountAndUpdate}`); return null; } const onRender = jest.fn(); await act(() => { ReactNoop.render( <React.Profiler id="root" onRender={onRender}> <Component /> </React.Profiler>, ); }); assertLog(['false:false', 'true:false', 'true:true']); expect(onRender).toHaveBeenCalledTimes(3); expect(onRender.mock.calls[0][1]).toBe('mount'); expect(onRender.mock.calls[1][1]).toBe('nested-update'); expect(onRender.mock.calls[2][1]).toBe('update'); }); it('is properly distinguish updates and nested-updates when there is more than sync remaining work', () => { loadModules({ useNoopRenderer: true, }); function Component() { const [didMount, setDidMount] = React.useState(false); React.useLayoutEffect(() => { setDidMount(true); }, []); Scheduler.log(didMount); return didMount; } const onRender = jest.fn(); // Schedule low-priority work. React.startTransition(() => ReactNoop.render( <React.Profiler id="root" onRender={onRender}> <Component /> </React.Profiler>, ), ); // Flush sync work with a nested update ReactNoop.flushSync(() => { ReactNoop.render( <React.Profiler id="root" onRender={onRender}> <Component /> </React.Profiler>, ); }); assertLog([false, true]); // Verify that the nested update inside of the sync work is appropriately tagged. expect(onRender).toHaveBeenCalledTimes(2); expect(onRender.mock.calls[0][1]).toBe('mount'); expect(onRender.mock.calls[1][1]).toBe('nested-update'); }); describe('with regard to interruptions', () => { it('should accumulate actual time after a scheduling interruptions', async () => { const callback = jest.fn(); const Yield = ({renderTime}) => { Scheduler.unstable_advanceTime(renderTime); Scheduler.log('Yield:' + renderTime); return null; }; Scheduler.unstable_advanceTime(5); // 0 -> 5 // Render partially, but run out of time before completing. React.startTransition(() => { ReactTestRenderer.create( <React.Profiler id="test" onRender={callback}> <Yield renderTime={2} /> <Yield renderTime={3} /> </React.Profiler>, {isConcurrent: true}, ); }); await waitFor(['Yield:2']); expect(callback).toHaveBeenCalledTimes(0); // Resume render for remaining children. await waitForAll(['Yield:3']); // Verify that logged times include both durations above. expect(callback).toHaveBeenCalledTimes(1); const [call] = callback.mock.calls; expect(call[2]).toBe(5); // actual time expect(call[3]).toBe(5); // base time expect(call[4]).toBe(5); // start time expect(call[5]).toBe(10); // commit time }); it('should not include time between frames', async () => { const callback = jest.fn(); const Yield = ({renderTime}) => { Scheduler.unstable_advanceTime(renderTime); Scheduler.log('Yield:' + renderTime); return null; }; Scheduler.unstable_advanceTime(5); // 0 -> 5 // Render partially, but don't finish. // This partial render should take 5ms of simulated time. React.startTransition(() => { ReactTestRenderer.create( <React.Profiler id="outer" onRender={callback}> <Yield renderTime={5} /> <Yield renderTime={10} /> <React.Profiler id="inner" onRender={callback}> <Yield renderTime={17} /> </React.Profiler> </React.Profiler>, {isConcurrent: true}, ); }); await waitFor(['Yield:5']); expect(callback).toHaveBeenCalledTimes(0); // Simulate time moving forward while frame is paused. Scheduler.unstable_advanceTime(50); // 10 -> 60 // Flush the remaining work, // Which should take an additional 10ms of simulated time. await waitForAll(['Yield:10', 'Yield:17']); expect(callback).toHaveBeenCalledTimes(2); const [innerCall, outerCall] = callback.mock.calls; // Verify that the actual time includes all work times, // But not the time that elapsed between frames. expect(innerCall[0]).toBe('inner'); expect(innerCall[2]).toBe(17); // actual time expect(innerCall[3]).toBe(17); // base time expect(innerCall[4]).toBe(70); // start time expect(innerCall[5]).toBe(87); // commit time expect(outerCall[0]).toBe('outer'); expect(outerCall[2]).toBe(32); // actual time expect(outerCall[3]).toBe(32); // base time expect(outerCall[4]).toBe(5); // start time expect(outerCall[5]).toBe(87); // commit time }); it('should report the expected times when a high-pri update replaces a mount in-progress', async () => { const callback = jest.fn(); const Yield = ({renderTime}) => { Scheduler.unstable_advanceTime(renderTime); Scheduler.log('Yield:' + renderTime); return null; }; Scheduler.unstable_advanceTime(5); // 0 -> 5 // Render a partially update, but don't finish. // This partial render should take 10ms of simulated time. let renderer; React.startTransition(() => { renderer = ReactTestRenderer.create( <React.Profiler id="test" onRender={callback}> <Yield renderTime={10} /> <Yield renderTime={20} /> </React.Profiler>, {isConcurrent: true}, ); }); await waitFor(['Yield:10']); expect(callback).toHaveBeenCalledTimes(0); // Simulate time moving forward while frame is paused. Scheduler.unstable_advanceTime(100); // 15 -> 115 // Interrupt with higher priority work. // The interrupted work simulates an additional 5ms of time. renderer.unstable_flushSync(() => { renderer.update( <React.Profiler id="test" onRender={callback}> <Yield renderTime={5} /> </React.Profiler>, ); }); assertLog(['Yield:5']); // The initial work was thrown away in this case, // So the actual and base times should only include the final rendered tree times. expect(callback).toHaveBeenCalledTimes(1); const call = callback.mock.calls[0]; expect(call[2]).toBe(5); // actual time expect(call[3]).toBe(5); // base time expect(call[4]).toBe(115); // start time expect(call[5]).toBe(120); // commit time callback.mockReset(); // Verify no more unexpected callbacks from low priority work await waitForAll([]); expect(callback).toHaveBeenCalledTimes(0); }); it('should report the expected times when a high-priority update replaces a low-priority update', async () => { const callback = jest.fn(); const Yield = ({renderTime}) => { Scheduler.unstable_advanceTime(renderTime); Scheduler.log('Yield:' + renderTime); return null; }; Scheduler.unstable_advanceTime(5); // 0 -> 5 const renderer = ReactTestRenderer.create( <React.Profiler id="test" onRender={callback}> <Yield renderTime={6} /> <Yield renderTime={15} /> </React.Profiler>, {isConcurrent: true}, ); // Render everything initially. // This should take 21 seconds of actual and base time. await waitForAll(['Yield:6', 'Yield:15']); expect(callback).toHaveBeenCalledTimes(1); let call = callback.mock.calls[0]; expect(call[2]).toBe(21); // actual time expect(call[3]).toBe(21); // base time expect(call[4]).toBe(5); // start time expect(call[5]).toBe(26); // commit time callback.mockReset(); Scheduler.unstable_advanceTime(30); // 26 -> 56 // Render a partially update, but don't finish. // This partial render should take 3ms of simulated time. React.startTransition(() => { renderer.update( <React.Profiler id="test" onRender={callback}> <Yield renderTime={3} /> <Yield renderTime={5} /> <Yield renderTime={9} /> </React.Profiler>, ); }); await waitFor(['Yield:3']); expect(callback).toHaveBeenCalledTimes(0); // Simulate time moving forward while frame is paused. Scheduler.unstable_advanceTime(100); // 59 -> 159 // Render another 5ms of simulated time. await waitFor(['Yield:5']); expect(callback).toHaveBeenCalledTimes(0); // Simulate time moving forward while frame is paused. Scheduler.unstable_advanceTime(100); // 164 -> 264 // Interrupt with higher priority work. // The interrupted work simulates an additional 11ms of time. renderer.unstable_flushSync(() => { renderer.update( <React.Profiler id="test" onRender={callback}> <Yield renderTime={11} /> </React.Profiler>, ); }); assertLog(['Yield:11']); // The actual time should include only the most recent render, // Because this lets us avoid a lot of commit phase reset complexity. // The base time includes only the final rendered tree times. expect(callback).toHaveBeenCalledTimes(1); call = callback.mock.calls[0]; expect(call[2]).toBe(11); // actual time expect(call[3]).toBe(11); // base time expect(call[4]).toBe(264); // start time expect(call[5]).toBe(275); // commit time // Verify no more unexpected callbacks from low priority work await waitForAll([]); expect(callback).toHaveBeenCalledTimes(1); }); it('should report the expected times when a high-priority update interrupts a low-priority update', async () => { const callback = jest.fn(); const Yield = ({renderTime}) => { Scheduler.unstable_advanceTime(renderTime); Scheduler.log('Yield:' + renderTime); return null; }; let first; class FirstComponent extends React.Component { state = {renderTime: 1}; render() { first = this; Scheduler.unstable_advanceTime(this.state.renderTime); Scheduler.log('FirstComponent:' + this.state.renderTime); return <Yield renderTime={4} />; } } let second; class SecondComponent extends React.Component { state = {renderTime: 2}; render() { second = this; Scheduler.unstable_advanceTime(this.state.renderTime); Scheduler.log('SecondComponent:' + this.state.renderTime); return <Yield renderTime={7} />; } } Scheduler.unstable_advanceTime(5); // 0 -> 5 const renderer = ReactTestRenderer.create( <React.Profiler id="test" onRender={callback}> <FirstComponent /> <SecondComponent /> </React.Profiler>, {isConcurrent: true}, ); // Render everything initially. // This simulates a total of 14ms of actual render time. // The base render time is also 14ms for the initial render. await waitForAll([ 'FirstComponent:1', 'Yield:4', 'SecondComponent:2', 'Yield:7', ]); expect(callback).toHaveBeenCalledTimes(1); let call = callback.mock.calls[0]; expect(call[2]).toBe(14); // actual time expect(call[3]).toBe(14); // base time expect(call[4]).toBe(5); // start time expect(call[5]).toBe(19); // commit time callback.mockClear(); Scheduler.unstable_advanceTime(100); // 19 -> 119 // Render a partially update, but don't finish. // This partial render will take 10ms of actual render time. React.startTransition(() => { first.setState({renderTime: 10}); }); await waitFor(['FirstComponent:10']); expect(callback).toHaveBeenCalledTimes(0); // Simulate time moving forward while frame is paused. Scheduler.unstable_advanceTime(100); // 129 -> 229 // Interrupt with higher priority work. // This simulates a total of 37ms of actual render time. renderer.unstable_flushSync(() => second.setState({renderTime: 30})); assertLog(['SecondComponent:30', 'Yield:7']); // The actual time should include only the most recent render (37ms), // Because this greatly simplifies the commit phase logic. // The base time should include the more recent times for the SecondComponent subtree, // As well as the original times for the FirstComponent subtree. expect(callback).toHaveBeenCalledTimes(1); call = callback.mock.calls[0]; expect(call[2]).toBe(37); // actual time expect(call[3]).toBe(42); // base time expect(call[4]).toBe(229); // start time expect(call[5]).toBe(266); // commit time callback.mockClear(); // Simulate time moving forward while frame is paused. Scheduler.unstable_advanceTime(100); // 266 -> 366 // Resume the original low priority update, with rebased state. // This simulates a total of 14ms of actual render time, // And does not include the original (interrupted) 10ms. // The tree contains 42ms of base render time at this point, // Reflecting the most recent (longer) render durations. // TODO: This actual time should decrease by 10ms once the scheduler supports resuming. await waitForAll(['FirstComponent:10', 'Yield:4']); expect(callback).toHaveBeenCalledTimes(1); call = callback.mock.calls[0]; expect(call[2]).toBe(14); // actual time expect(call[3]).toBe(51); // base time expect(call[4]).toBe(366); // start time expect(call[5]).toBe(380); // commit time }); [true, false].forEach(replayFailedUnitOfWorkWithInvokeGuardedCallback => { describe(`replayFailedUnitOfWorkWithInvokeGuardedCallback ${ replayFailedUnitOfWorkWithInvokeGuardedCallback ? 'enabled' : 'disabled' }`, () => { beforeEach(() => { jest.resetModules(); loadModules({ replayFailedUnitOfWorkWithInvokeGuardedCallback, }); }); it('should accumulate actual time after an error handled by componentDidCatch()', () => { const callback = jest.fn(); const ThrowsError = ({unused}) => { Scheduler.unstable_advanceTime(3); throw Error('expected error'); }; class ErrorBoundary extends React.Component { state = {error: null}; componentDidCatch(error) { this.setState({error}); } render() { Scheduler.unstable_advanceTime(2); return this.state.error === null ? ( this.props.children ) : ( <AdvanceTime byAmount={20} /> ); } } Scheduler.unstable_advanceTime(5); // 0 -> 5 ReactTestRenderer.create( <React.Profiler id="test" onRender={callback}> <ErrorBoundary> <AdvanceTime byAmount={9} /> <ThrowsError /> </ErrorBoundary> </React.Profiler>, ); expect(callback).toHaveBeenCalledTimes(2); // Callbacks bubble (reverse order). const [mountCall, updateCall] = callback.mock.calls; // The initial mount only includes the ErrorBoundary (which takes 2) // But it spends time rendering all of the failed subtree also. expect(mountCall[1]).toBe('mount'); // actual time includes: 2 (ErrorBoundary) + 9 (AdvanceTime) + 3 (ThrowsError) // We don't count the time spent in replaying the failed unit of work (ThrowsError) expect(mountCall[2]).toBe(14); // base time includes: 2 (ErrorBoundary) // Since the tree is empty for the initial commit expect(mountCall[3]).toBe(2); // start time expect(mountCall[4]).toBe(5); // commit time: 5 initially + 14 of work // Add an additional 3 (ThrowsError) if we replayed the failed work expect(mountCall[5]).toBe( __DEV__ && replayFailedUnitOfWorkWithInvokeGuardedCallback ? 22 : 19, ); // The update includes the ErrorBoundary and its fallback child expect(updateCall[1]).toBe('nested-update'); // actual time includes: 2 (ErrorBoundary) + 20 (AdvanceTime) expect(updateCall[2]).toBe(22); // base time includes: 2 (ErrorBoundary) + 20 (AdvanceTime) expect(updateCall[3]).toBe(22); // start time expect(updateCall[4]).toBe( __DEV__ && replayFailedUnitOfWorkWithInvokeGuardedCallback ? 22 : 19, ); // commit time: 19 (startTime) + 2 (ErrorBoundary) + 20 (AdvanceTime) // Add an additional 3 (ThrowsError) if we replayed the failed work expect(updateCall[5]).toBe( __DEV__ && replayFailedUnitOfWorkWithInvokeGuardedCallback ? 44 : 41, ); }); it('should accumulate actual time after an error handled by getDerivedStateFromError()', () => { const callback = jest.fn(); const ThrowsError = ({unused}) => { Scheduler.unstable_advanceTime(10); throw Error('expected error'); }; class ErrorBoundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { Scheduler.unstable_advanceTime(2); return this.state.error === null ? ( this.props.children ) : ( <AdvanceTime byAmount={20} /> ); } } Scheduler.unstable_advanceTime(5); // 0 -> 5 ReactTestRenderer.create( <React.Profiler id="test" onRender={callback}> <ErrorBoundary> <AdvanceTime byAmount={5} /> <ThrowsError /> </ErrorBoundary> </React.Profiler>, ); expect(callback).toHaveBeenCalledTimes(1); // Callbacks bubble (reverse order). const [mountCall] = callback.mock.calls; // The initial mount includes the ErrorBoundary's error state, // But it also spends actual time rendering UI that fails and isn't included. expect(mountCall[1]).toBe('mount'); // actual time includes: 2 (ErrorBoundary) + 5 (AdvanceTime) + 10 (ThrowsError) // Then the re-render: 2 (ErrorBoundary) + 20 (AdvanceTime) // We don't count the time spent in replaying the failed unit of work (ThrowsError) expect(mountCall[2]).toBe(39); // base time includes: 2 (ErrorBoundary) + 20 (AdvanceTime) expect(mountCall[3]).toBe(22); // start time expect(mountCall[4]).toBe(5); // commit time expect(mountCall[5]).toBe( __DEV__ && replayFailedUnitOfWorkWithInvokeGuardedCallback ? 54 : 44, ); }); it('should reset the fiber stack correct after a "complete" phase error', async () => { jest.resetModules(); loadModules({ useNoopRenderer: true, replayFailedUnitOfWorkWithInvokeGuardedCallback, }); // Simulate a renderer error during the "complete" phase. // This mimics behavior like React Native's View/Text nesting validation. ReactNoop.render( <React.Profiler id="profiler" onRender={jest.fn()}> <errorInCompletePhase>hi</errorInCompletePhase> </React.Profiler>, ); await waitForThrow('Error in host config.'); // A similar case we've seen caused by an invariant in ReactDOM. // It didn't reproduce without a host component inside. ReactNoop.render( <React.Profiler id="profiler" onRender={jest.fn()}> <errorInCompletePhase> <span>hi</span> </errorInCompletePhase> </React.Profiler>, ); await waitForThrow('Error in host config.'); // So long as the profiler timer's fiber stack is reset correctly, // Subsequent renders should not error. ReactNoop.render( <React.Profiler id="profiler" onRender={jest.fn()}> <span>hi</span> </React.Profiler>, ); await waitForAll([]); }); }); }); }); it('reflects the most recently rendered id value', () => { const callback = jest.fn(); Scheduler.unstable_advanceTime(5); // 0 -> 5 const renderer = ReactTestRenderer.create( <React.Profiler id="one" onRender={callback}> <AdvanceTime byAmount={2} /> </React.Profiler>, ); expect(callback).toHaveBeenCalledTimes(1); Scheduler.unstable_advanceTime(20); // 7 -> 27 renderer.update( <React.Profiler id="two" onRender={callback}> <AdvanceTime byAmount={1} /> </React.Profiler>, ); expect(callback).toHaveBeenCalledTimes(2); const [mountCall, updateCall] = callback.mock.calls; expect(mountCall[0]).toBe('one'); expect(mountCall[1]).toBe('mount'); expect(mountCall[2]).toBe(2); // actual time expect(mountCall[3]).toBe(2); // base time expect(mountCall[4]).toBe(5); // start time expect(updateCall[0]).toBe('two'); expect(updateCall[1]).toBe('update'); expect(updateCall[2]).toBe(1); // actual time expect(updateCall[3]).toBe(1); // base time expect(updateCall[4]).toBe(27); // start time }); it('should not be called until after mutations', () => { let classComponentMounted = false; const callback = jest.fn( (id, phase, actualDuration, baseDuration, startTime, commitTime) => { // Don't call this hook until after mutations expect(classComponentMounted).toBe(true); // But the commit time should reflect pre-mutation expect(commitTime).toBe(2); }, ); class ClassComponent extends React.Component { componentDidMount() { Scheduler.unstable_advanceTime(5); classComponentMounted = true; } render() { Scheduler.unstable_advanceTime(2); return null; } } ReactTestRenderer.create( <React.Profiler id="test" onRender={callback}> <ClassComponent /> </React.Profiler>, ); expect(callback).toHaveBeenCalledTimes(1); }); }); describe(`onCommit`, () => { beforeEach(() => { jest.resetModules(); loadModules(); }); it('should report time spent in layout effects and commit lifecycles', () => { const callback = jest.fn(); const ComponentWithEffects = () => { React.useLayoutEffect(() => { Scheduler.unstable_advanceTime(10); return () => { Scheduler.unstable_advanceTime(100); }; }, []); React.useLayoutEffect(() => { Scheduler.unstable_advanceTime(1000); return () => { Scheduler.unstable_advanceTime(10000); }; }); React.useEffect(() => { // This passive effect is here to verify that its time isn't reported. Scheduler.unstable_advanceTime(5); return () => { Scheduler.unstable_advanceTime(7); }; }); return null; }; class ComponentWithCommitHooks extends React.Component { componentDidMount() { Scheduler.unstable_advanceTime(100000); } componentDidUpdate() { Scheduler.unstable_advanceTime(1000000); } render() { return null; } } Scheduler.unstable_advanceTime(1); const renderer = ReactTestRenderer.create( <React.Profiler id="mount-test" onCommit={callback}> <ComponentWithEffects /> <ComponentWithCommitHooks /> </React.Profiler>, ); expect(callback).toHaveBeenCalledTimes(1); let call = callback.mock.calls[0]; expect(call).toHaveLength(4); expect(call[0]).toBe('mount-test'); expect(call[1]).toBe('mount'); expect(call[2]).toBe(101010); // durations expect(call[3]).toBe(1); // commit start time (before mutations or effects) Scheduler.unstable_advanceTime(1); renderer.update( <React.Profiler id="update-test" onCommit={callback}> <ComponentWithEffects /> <ComponentWithCommitHooks /> </React.Profiler>, ); expect(callback).toHaveBeenCalledTimes(2); call = callback.mock.calls[1]; expect(call).toHaveLength(4); expect(call[0]).toBe('update-test'); expect(call[1]).toBe('update'); expect(call[2]).toBe(1011000); // durations expect(call[3]).toBe(101017); // commit start time (before mutations or effects) Scheduler.unstable_advanceTime(1); renderer.update(<React.Profiler id="unmount-test" onCommit={callback} />); expect(callback).toHaveBeenCalledTimes(3); call = callback.mock.calls[2]; expect(call).toHaveLength(4); expect(call[0]).toBe('unmount-test'); expect(call[1]).toBe('update'); expect(call[2]).toBe(10100); // durations expect(call[3]).toBe(1112030); // commit start time (before mutations or effects) }); it('should report time spent in layout effects and commit lifecycles with cascading renders', () => { const callback = jest.fn(); const ComponentWithEffects = ({shouldCascade}) => { const [didCascade, setDidCascade] = React.useState(false); Scheduler.unstable_advanceTime(100000000); React.useLayoutEffect(() => { if (shouldCascade && !didCascade) { setDidCascade(true); } Scheduler.unstable_advanceTime(didCascade ? 30 : 10); return () => { Scheduler.unstable_advanceTime(100); }; }, [didCascade, shouldCascade]); return null; }; class ComponentWithCommitHooks extends React.Component { state = { didCascade: false, }; componentDidMount() { Scheduler.unstable_advanceTime(1000); } componentDidUpdate() { Scheduler.unstable_advanceTime(10000); if (this.props.shouldCascade && !this.state.didCascade) { this.setState({didCascade: true}); } } render() { Scheduler.unstable_advanceTime(1000000000); return null; } } Scheduler.unstable_advanceTime(1); const renderer = ReactTestRenderer.create( <React.Profiler id="mount-test" onCommit={callback}> <ComponentWithEffects shouldCascade={true} /> <ComponentWithCommitHooks /> </React.Profiler>, ); expect(callback).toHaveBeenCalledTimes(2); let call = callback.mock.calls[0]; expect(call).toHaveLength(4); expect(call[0]).toBe('mount-test'); expect(call[1]).toBe('mount'); expect(call[2]).toBe(1010); // durations expect(call[3]).toBe(1100000001); // commit start time (before mutations or effects) call = callback.mock.calls[1]; expect(call).toHaveLength(4); expect(call[0]).toBe('mount-test'); expect(call[1]).toBe('nested-update'); expect(call[2]).toBe(130); // durations expect(call[3]).toBe(1200001011); // commit start time (before mutations or effects) Scheduler.unstable_advanceTime(1); renderer.update( <React.Profiler id="update-test" onCommit={callback}> <ComponentWithEffects /> <ComponentWithCommitHooks shouldCascade={true} /> </React.Profiler>, ); expect(callback).toHaveBeenCalledTimes(4); call = callback.mock.calls[2]; expect(call).toHaveLength(4); expect(call[0]).toBe('update-test'); expect(call[1]).toBe('update'); expect(call[2]).toBe(10130); // durations expect(call[3]).toBe(2300001142); // commit start time (before mutations or effects) call = callback.mock.calls[3]; expect(call).toHaveLength(4); expect(call[0]).toBe('update-test'); expect(call[1]).toBe('nested-update'); expect(call[2]).toBe(10000); // durations expect(call[3]).toBe(3300011272); // commit start time (before mutations or effects) }); it('should include time spent in ref callbacks', () => { const callback = jest.fn(); const refSetter = ref => { if (ref !== null) { Scheduler.unstable_advanceTime(10); } else { Scheduler.unstable_advanceTime(100); } }; class ClassComponent extends React.Component { render() { return null; } } const Component = () => { Scheduler.unstable_advanceTime(1000); return <ClassComponent ref={refSetter} />; }; Scheduler.unstable_advanceTime(1); const renderer = ReactTestRenderer.create( <React.Profiler id="root" onCommit={callback}> <Component /> </React.Profiler>, ); expect(callback).toHaveBeenCalledTimes(1); let call = callback.mock.calls[0]; expect(call).toHaveLength(4); expect(call[0]).toBe('root'); expect(call[1]).toBe('mount'); expect(call[2]).toBe(10); // durations expect(call[3]).toBe(1001); // commit start time (before mutations or effects) callback.mockClear(); renderer.update(<React.Profiler id="root" onCommit={callback} />); expect(callback).toHaveBeenCalledTimes(1); call = callback.mock.calls[0]; expect(call).toHaveLength(4); expect(call[0]).toBe('root'); expect(call[1]).toBe('update'); expect(call[2]).toBe(100); // durations expect(call[3]).toBe(1011); // commit start time (before mutations or effects) }); it('should bubble time spent in layout effects to higher profilers', async () => { const callback = jest.fn(); const ComponentWithEffects = ({cleanupDuration, duration, setCountRef}) => { const setCount = React.useState(0)[1]; if (setCountRef != null) { setCountRef.current = setCount; } React.useLayoutEffect(() => { Scheduler.unstable_advanceTime(duration); return () => { Scheduler.unstable_advanceTime(cleanupDuration); }; }); Scheduler.unstable_advanceTime(1); return null; }; const setCountRef = React.createRef(null); let renderer = null; await act(() => { renderer = ReactTestRenderer.create( <React.Profiler id="root-mount" onCommit={callback}> <React.Profiler id="a"> <ComponentWithEffects duration={10} cleanupDuration={100} setCountRef={setCountRef} /> </React.Profiler> <React.Profiler id="b"> <ComponentWithEffects duration={1000} cleanupDuration={10000} /> </React.Profiler> </React.Profiler>, ); }); expect(callback).toHaveBeenCalledTimes(1); let call = callback.mock.calls[0]; expect(call).toHaveLength(4); expect(call[0]).toBe('root-mount'); expect(call[1]).toBe('mount'); expect(call[2]).toBe(1010); // durations expect(call[3]).toBe(2); // commit start time (before mutations or effects) await act(() => setCountRef.current(count => count + 1)); expect(callback).toHaveBeenCalledTimes(2); call = callback.mock.calls[1]; expect(call).toHaveLength(4); expect(call[0]).toBe('root-mount'); expect(call[1]).toBe('update'); expect(call[2]).toBe(110); // durations expect(call[3]).toBe(1013); // commit start time (before mutations or effects) await act(() => { renderer.update( <React.Profiler id="root-update" onCommit={callback}> <React.Profiler id="b"> <ComponentWithEffects duration={1000} cleanupDuration={10000} /> </React.Profiler> </React.Profiler>, ); }); expect(callback).toHaveBeenCalledTimes(3); call = callback.mock.calls[2]; expect(call).toHaveLength(4); expect(call[0]).toBe('root-update'); expect(call[1]).toBe('update'); expect(call[2]).toBe(1100); // durations expect(call[3]).toBe(1124); // commit start time (before mutations or effects) }); it('should properly report time in layout effects even when there are errors', async () => { const callback = jest.fn(); class ErrorBoundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { return this.state.error === null ? this.props.children : this.props.fallback; } } const ComponentWithEffects = ({ cleanupDuration, duration, effectDuration, shouldThrow, }) => { React.useLayoutEffect(() => { Scheduler.unstable_advanceTime(effectDuration); if (shouldThrow) { throw Error('expected'); } return () => { Scheduler.unstable_advanceTime(cleanupDuration); }; }); Scheduler.unstable_advanceTime(duration); return null; }; Scheduler.unstable_advanceTime(1); // Test an error that happens during an effect await act(() => { ReactTestRenderer.create( <React.Profiler id="root" onCommit={callback}> <ErrorBoundary fallback={ <ComponentWithEffects duration={10000000} effectDuration={100000000} cleanupDuration={1000000000} /> }> <ComponentWithEffects duration={10} effectDuration={100} cleanupDuration={1000} shouldThrow={true} /> </ErrorBoundary> <ComponentWithEffects duration={10000} effectDuration={100000} cleanupDuration={1000000} /> </React.Profiler>, ); }); expect(callback).toHaveBeenCalledTimes(2); let call = callback.mock.calls[0]; // Initial render (with error) expect(call).toHaveLength(4); expect(call[0]).toBe('root'); expect(call[1]).toBe('mount'); expect(call[2]).toBe(100100); // durations expect(call[3]).toBe(10011); // commit start time (before mutations or effects) call = callback.mock.calls[1]; // Cleanup render from error boundary expect(call).toHaveLength(4); expect(call[0]).toBe('root'); expect(call[1]).toBe('nested-update'); expect(call[2]).toBe(100000000); // durations expect(call[3]).toBe(10110111); // commit start time (before mutations or effects) }); it('should properly report time in layout effect cleanup functions even when there are errors', async () => { const callback = jest.fn(); class ErrorBoundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { return this.state.error === null ? this.props.children : this.props.fallback; } } const ComponentWithEffects = ({ cleanupDuration, duration, effectDuration, shouldThrow = false, }) => { React.useLayoutEffect(() => { Scheduler.unstable_advanceTime(effectDuration); return () => { Scheduler.unstable_advanceTime(cleanupDuration); if (shouldThrow) { throw Error('expected'); } }; }); Scheduler.unstable_advanceTime(duration); return null; }; Scheduler.unstable_advanceTime(1); let renderer = null; await act(() => { renderer = ReactTestRenderer.create( <React.Profiler id="root" onCommit={callback}> <ErrorBoundary fallback={ <ComponentWithEffects duration={10000000} effectDuration={100000000} cleanupDuration={1000000000} /> }> <ComponentWithEffects duration={10} effectDuration={100} cleanupDuration={1000} shouldThrow={true} /> </ErrorBoundary> <ComponentWithEffects duration={10000} effectDuration={100000} cleanupDuration={1000000} /> </React.Profiler>, ); }); expect(callback).toHaveBeenCalledTimes(1); let call = callback.mock.calls[0]; // Initial render expect(call).toHaveLength(4); expect(call[0]).toBe('root'); expect(call[1]).toBe('mount'); expect(call[2]).toBe(100100); // durations expect(call[3]).toBe(10011); // commit start time (before mutations or effects) callback.mockClear(); // Test an error that happens during an cleanup function await act(() => { renderer.update( <React.Profiler id="root" onCommit={callback}> <ErrorBoundary fallback={ <ComponentWithEffects duration={10000000} effectDuration={100000000} cleanupDuration={1000000000} /> }> <ComponentWithEffects duration={10} effectDuration={100} cleanupDuration={1000} shouldThrow={false} /> </ErrorBoundary> <ComponentWithEffects duration={10000} effectDuration={100000} cleanupDuration={1000000} /> </React.Profiler>, ); }); expect(callback).toHaveBeenCalledTimes(2); call = callback.mock.calls[0]; // Update (that throws) expect(call).toHaveLength(4); expect(call[0]).toBe('root'); expect(call[1]).toBe('update'); expect(call[2]).toBe(1101100); // durations expect(call[3]).toBe(120121); // commit start time (before mutations or effects) call = callback.mock.calls[1]; // Cleanup render from error boundary expect(call).toHaveLength(4); expect(call[0]).toBe('root'); expect(call[1]).toBe('nested-update'); expect(call[2]).toBe(100001000); // durations expect(call[3]).toBe(11221221); // commit start time (before mutations or effects) }); }); describe(`onPostCommit`, () => { beforeEach(() => { jest.resetModules(); loadModules(); }); it('should report time spent in passive effects', async () => { const callback = jest.fn(); const ComponentWithEffects = () => { React.useLayoutEffect(() => { // This layout effect is here to verify that its time isn't reported. Scheduler.unstable_advanceTime(5); return () => { Scheduler.unstable_advanceTime(7); }; }); React.useEffect(() => { Scheduler.unstable_advanceTime(10); return () => { Scheduler.unstable_advanceTime(100); }; }, []); React.useEffect(() => { Scheduler.unstable_advanceTime(1000); return () => { Scheduler.unstable_advanceTime(10000); }; }); return null; }; Scheduler.unstable_advanceTime(1); let renderer; await act(() => { renderer = ReactTestRenderer.create( <React.Profiler id="mount-test" onPostCommit={callback}> <ComponentWithEffects /> </React.Profiler>, ); }); await waitForAll([]); expect(callback).toHaveBeenCalledTimes(1); let call = callback.mock.calls[0]; expect(call).toHaveLength(4); expect(call[0]).toBe('mount-test'); expect(call[1]).toBe('mount'); expect(call[2]).toBe(1010); // durations expect(call[3]).toBe(1); // commit start time (before mutations or effects) Scheduler.unstable_advanceTime(1); await act(() => { renderer.update( <React.Profiler id="update-test" onPostCommit={callback}> <ComponentWithEffects /> </React.Profiler>, ); }); await waitForAll([]); expect(callback).toHaveBeenCalledTimes(2); call = callback.mock.calls[1]; expect(call).toHaveLength(4); expect(call[0]).toBe('update-test'); expect(call[1]).toBe('update'); expect(call[2]).toBe(11000); // durations expect(call[3]).toBe(1017); // commit start time (before mutations or effects) Scheduler.unstable_advanceTime(1); await act(() => { renderer.update( <React.Profiler id="unmount-test" onPostCommit={callback} />, ); }); await waitForAll([]); expect(callback).toHaveBeenCalledTimes(3); call = callback.mock.calls[2]; expect(call).toHaveLength(4); expect(call[0]).toBe('unmount-test'); expect(call[1]).toBe('update'); // TODO (bvaughn) The duration reported below should be 10100, but is 0 // by the time the passive effect is flushed its parent Fiber pointer is gone. // If we refactor to preserve the unmounted Fiber tree we could fix this. // The current implementation would require too much extra overhead to track this. expect(call[2]).toBe(0); // durations expect(call[3]).toBe(12030); // commit start time (before mutations or effects) }); it('should report time spent in passive effects with cascading renders', async () => { const callback = jest.fn(); const ComponentWithEffects = () => { const [didMount, setDidMount] = React.useState(false); Scheduler.unstable_advanceTime(1000); React.useEffect(() => { if (!didMount) { setDidMount(true); } Scheduler.unstable_advanceTime(didMount ? 30 : 10); return () => { Scheduler.unstable_advanceTime(100); }; }, [didMount]); return null; }; Scheduler.unstable_advanceTime(1); await act(() => { ReactTestRenderer.create( <React.Profiler id="mount-test" onPostCommit={callback}> <ComponentWithEffects /> </React.Profiler>, ); }); expect(callback).toHaveBeenCalledTimes(2); let call = callback.mock.calls[0]; expect(call).toHaveLength(4); expect(call[0]).toBe('mount-test'); expect(call[1]).toBe('mount'); expect(call[2]).toBe(10); // durations expect(call[3]).toBe(1001); // commit start time (before mutations or effects) call = callback.mock.calls[1]; expect(call).toHaveLength(4); expect(call[0]).toBe('mount-test'); expect(call[1]).toBe('update'); expect(call[2]).toBe(130); // durations expect(call[3]).toBe(2011); // commit start time (before mutations or effects) }); it('should bubble time spent in effects to higher profilers', async () => { const callback = jest.fn(); const ComponentWithEffects = ({cleanupDuration, duration, setCountRef}) => { const setCount = React.useState(0)[1]; if (setCountRef != null) { setCountRef.current = setCount; } React.useEffect(() => { Scheduler.unstable_advanceTime(duration); return () => { Scheduler.unstable_advanceTime(cleanupDuration); }; }); Scheduler.unstable_advanceTime(1); return null; }; const setCountRef = React.createRef(null); let renderer = null; await act(() => { renderer = ReactTestRenderer.create( <React.Profiler id="root-mount" onPostCommit={callback}> <React.Profiler id="a"> <ComponentWithEffects duration={10} cleanupDuration={100} setCountRef={setCountRef} /> </React.Profiler> <React.Profiler id="b"> <ComponentWithEffects duration={1000} cleanupDuration={10000} /> </React.Profiler> </React.Profiler>, ); }); expect(callback).toHaveBeenCalledTimes(1); let call = callback.mock.calls[0]; expect(call).toHaveLength(4); expect(call[0]).toBe('root-mount'); expect(call[1]).toBe('mount'); expect(call[2]).toBe(1010); // durations expect(call[3]).toBe(2); // commit start time (before mutations or effects) await act(() => setCountRef.current(count => count + 1)); expect(callback).toHaveBeenCalledTimes(2); call = callback.mock.calls[1]; expect(call).toHaveLength(4); expect(call[0]).toBe('root-mount'); expect(call[1]).toBe('update'); expect(call[2]).toBe(110); // durations expect(call[3]).toBe(1013); // commit start time (before mutations or effects) await act(() => { renderer.update( <React.Profiler id="root-update" onPostCommit={callback}> <React.Profiler id="b"> <ComponentWithEffects duration={1000} cleanupDuration={10000} /> </React.Profiler> </React.Profiler>, ); }); expect(callback).toHaveBeenCalledTimes(3); call = callback.mock.calls[2]; expect(call).toHaveLength(4); expect(call[0]).toBe('root-update'); expect(call[1]).toBe('update'); expect(call[2]).toBe(1100); // durations expect(call[3]).toBe(1124); // commit start time (before mutations or effects) }); it('should properly report time in passive effects even when there are errors', async () => { const callback = jest.fn(); class ErrorBoundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { return this.state.error === null ? this.props.children : this.props.fallback; } } const ComponentWithEffects = ({ cleanupDuration, duration, effectDuration, shouldThrow, }) => { React.useEffect(() => { Scheduler.unstable_advanceTime(effectDuration); if (shouldThrow) { throw Error('expected'); } return () => { Scheduler.unstable_advanceTime(cleanupDuration); }; }); Scheduler.unstable_advanceTime(duration); return null; }; Scheduler.unstable_advanceTime(1); // Test an error that happens during an effect await act(() => { ReactTestRenderer.create( <React.Profiler id="root" onPostCommit={callback}> <ErrorBoundary fallback={ <ComponentWithEffects duration={10000000} effectDuration={100000000} cleanupDuration={1000000000} /> }> <ComponentWithEffects duration={10} effectDuration={100} cleanupDuration={1000} shouldThrow={true} /> </ErrorBoundary> <ComponentWithEffects duration={10000} effectDuration={100000} cleanupDuration={1000000} /> </React.Profiler>, ); }); expect(callback).toHaveBeenCalledTimes(2); let call = callback.mock.calls[0]; // Initial render (with error) expect(call).toHaveLength(4); expect(call[0]).toBe('root'); expect(call[1]).toBe('mount'); expect(call[2]).toBe(100100); // durations expect(call[3]).toBe(10011); // commit start time (before mutations or effects) call = callback.mock.calls[1]; // Cleanup render from error boundary expect(call).toHaveLength(4); expect(call[0]).toBe('root'); expect(call[1]).toBe('update'); expect(call[2]).toBe(100000000); // durations expect(call[3]).toBe(10110111); // commit start time (before mutations or effects) }); it('should properly report time in passive effect cleanup functions even when there are errors', async () => { const callback = jest.fn(); class ErrorBoundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { return this.state.error === null ? this.props.children : this.props.fallback; } } const ComponentWithEffects = ({ cleanupDuration, duration, effectDuration, shouldThrow = false, id, }) => { React.useEffect(() => { Scheduler.unstable_advanceTime(effectDuration); return () => { Scheduler.unstable_advanceTime(cleanupDuration); if (shouldThrow) { throw Error('expected'); } }; }); Scheduler.unstable_advanceTime(duration); return null; }; Scheduler.unstable_advanceTime(1); let renderer = null; await act(() => { renderer = ReactTestRenderer.create( <React.Profiler id="root" onPostCommit={callback}> <ErrorBoundary fallback={ <ComponentWithEffects duration={10000000} effectDuration={100000000} cleanupDuration={1000000000} /> }> <ComponentWithEffects duration={10} effectDuration={100} cleanupDuration={1000} shouldThrow={true} /> </ErrorBoundary> <ComponentWithEffects duration={10000} effectDuration={100000} cleanupDuration={1000000} /> </React.Profiler>, ); }); expect(callback).toHaveBeenCalledTimes(1); let call = callback.mock.calls[0]; // Initial render expect(call).toHaveLength(4); expect(call[0]).toBe('root'); expect(call[1]).toBe('mount'); expect(call[2]).toBe(100100); // durations expect(call[3]).toBe(10011); // commit start time (before mutations or effects) callback.mockClear(); // Test an error that happens during an cleanup function await act(() => { renderer.update( <React.Profiler id="root" onPostCommit={callback}> <ErrorBoundary fallback={ <ComponentWithEffects duration={10000000} effectDuration={100000000} cleanupDuration={1000000000} /> }> <ComponentWithEffects duration={10} effectDuration={100} cleanupDuration={1000} shouldThrow={false} /> </ErrorBoundary> <ComponentWithEffects duration={10000} effectDuration={100000} cleanupDuration={1000000} /> </React.Profiler>, ); }); expect(callback).toHaveBeenCalledTimes(2); call = callback.mock.calls[0]; // Update (that throws) expect(call).toHaveLength(4); expect(call[0]).toBe('root'); expect(call[1]).toBe('update'); // We continue flushing pending effects even if one throws. expect(call[2]).toBe(1101100); // durations expect(call[3]).toBe(120121); // commit start time (before mutations or effects) call = callback.mock.calls[1]; // Cleanup render from error boundary expect(call).toHaveLength(4); expect(call[0]).toBe('root'); expect(call[1]).toBe('update'); expect(call[2]).toBe(100000000); // durations // The commit time varies because the above duration time varies expect(call[3]).toBe(11221221); // commit start time (before mutations or effects) }); }); describe(`onNestedUpdateScheduled`, () => { beforeEach(() => { jest.resetModules(); loadModules({ enableProfilerNestedUpdateScheduledHook: true, useNoopRenderer: true, }); }); it('is not called when the legacy render API is used to schedule an update', () => { const onNestedUpdateScheduled = jest.fn(); ReactNoop.renderLegacySyncRoot( <React.Profiler id="test" onNestedUpdateScheduled={onNestedUpdateScheduled}> <div>initial</div> </React.Profiler>, ); ReactNoop.renderLegacySyncRoot( <React.Profiler id="test" onNestedUpdateScheduled={onNestedUpdateScheduled}> <div>update</div> </React.Profiler>, ); expect(onNestedUpdateScheduled).not.toHaveBeenCalled(); }); it('is not called when the root API is used to schedule an update', () => { const onNestedUpdateScheduled = jest.fn(); ReactNoop.render( <React.Profiler id="test" onNestedUpdateScheduled={onNestedUpdateScheduled}> <div>initial</div> </React.Profiler>, ); ReactNoop.render( <React.Profiler id="test" onNestedUpdateScheduled={onNestedUpdateScheduled}> <div>update</div> </React.Profiler>, ); expect(onNestedUpdateScheduled).not.toHaveBeenCalled(); }); it('is called when a function component schedules an update during a layout effect', async () => { function Component() { const [didMount, setDidMount] = React.useState(false); React.useLayoutEffect(() => { setDidMount(true); }, []); Scheduler.log(`Component:${didMount}`); return didMount; } const onNestedUpdateScheduled = jest.fn(); await act(() => { ReactNoop.render( <React.Profiler id="test" onNestedUpdateScheduled={onNestedUpdateScheduled}> <Component /> </React.Profiler>, ); }); assertLog(['Component:false', 'Component:true']); expect(onNestedUpdateScheduled).toHaveBeenCalledTimes(1); expect(onNestedUpdateScheduled.mock.calls[0][0]).toBe('test'); }); it('is called when a function component schedules a batched update during a layout effect', async () => { function Component() { const [didMount, setDidMount] = React.useState(false); React.useLayoutEffect(() => { ReactNoop.batchedUpdates(() => { setDidMount(true); }); }, []); Scheduler.log(`Component:${didMount}`); return didMount; } const onNestedUpdateScheduled = jest.fn(); const onRender = jest.fn(); ReactNoop.render( <React.Profiler id="root" onNestedUpdateScheduled={onNestedUpdateScheduled} onRender={onRender}> <Component /> </React.Profiler>, ); await waitForAll(['Component:false', 'Component:true']); expect(onRender).toHaveBeenCalledTimes(2); expect(onRender.mock.calls[0][1]).toBe('mount'); expect(onRender.mock.calls[1][1]).toBe('nested-update'); expect(onNestedUpdateScheduled).toHaveBeenCalledTimes(1); expect(onNestedUpdateScheduled.mock.calls[0][0]).toBe('root'); }); it('bubbles up and calls all ancestor Profilers', async () => { function Component() { const [didMount, setDidMount] = React.useState(false); React.useLayoutEffect(() => { setDidMount(true); }, []); Scheduler.log(`Component:${didMount}`); return didMount; } const onNestedUpdateScheduledOne = jest.fn(); const onNestedUpdateScheduledTwo = jest.fn(); const onNestedUpdateScheduledThree = jest.fn(); await act(() => { ReactNoop.render( <React.Profiler id="one" onNestedUpdateScheduled={onNestedUpdateScheduledOne}> <React.Profiler id="two" onNestedUpdateScheduled={onNestedUpdateScheduledTwo}> <> <Component /> <React.Profiler id="three" onNestedUpdateScheduled={onNestedUpdateScheduledThree} /> </> </React.Profiler> </React.Profiler>, ); }); assertLog(['Component:false', 'Component:true']); expect(onNestedUpdateScheduledOne).toHaveBeenCalledTimes(1); expect(onNestedUpdateScheduledOne.mock.calls[0][0]).toBe('one'); expect(onNestedUpdateScheduledTwo).toHaveBeenCalledTimes(1); expect(onNestedUpdateScheduledTwo.mock.calls[0][0]).toBe('two'); expect(onNestedUpdateScheduledThree).not.toHaveBeenCalled(); }); it('is not called when an update is scheduled for another doort during a layout effect', async () => { const setStateRef = React.createRef(null); function ComponentRootOne() { const [state, setState] = React.useState(false); setStateRef.current = setState; Scheduler.log(`ComponentRootOne:${state}`); return state; } function ComponentRootTwo() { React.useLayoutEffect(() => { setStateRef.current(true); }, []); Scheduler.log('ComponentRootTwo'); return null; } const onNestedUpdateScheduled = jest.fn(); await act(() => { ReactNoop.renderToRootWithID( <React.Profiler id="test" onNestedUpdateScheduled={onNestedUpdateScheduled}> <ComponentRootOne /> </React.Profiler>, 1, ); ReactNoop.renderToRootWithID( <React.Profiler id="test" onNestedUpdateScheduled={onNestedUpdateScheduled}> <ComponentRootTwo /> </React.Profiler>, 2, ); }); assertLog([ 'ComponentRootOne:false', 'ComponentRootTwo', 'ComponentRootOne:true', ]); expect(onNestedUpdateScheduled).not.toHaveBeenCalled(); }); it('is not called when a function component schedules an update during a passive effect', async () => { function Component() { const [didMount, setDidMount] = React.useState(false); React.useEffect(() => { setDidMount(true); }, []); Scheduler.log(`Component:${didMount}`); return didMount; } const onNestedUpdateScheduled = jest.fn(); await act(() => { ReactNoop.render( <React.Profiler id="test" onNestedUpdateScheduled={onNestedUpdateScheduled}> <Component /> </React.Profiler>, ); }); assertLog(['Component:false', 'Component:true']); expect(onNestedUpdateScheduled).not.toHaveBeenCalled(); }); it('is not called when a function component schedules an update outside of render', async () => { const updateFnRef = React.createRef(null); function Component() { const [state, setState] = React.useState(false); updateFnRef.current = () => setState(true); Scheduler.log(`Component:${state}`); return state; } const onNestedUpdateScheduled = jest.fn(); await act(() => { ReactNoop.render( <React.Profiler id="test" onNestedUpdateScheduled={onNestedUpdateScheduled}> <Component /> </React.Profiler>, ); }); assertLog(['Component:false']); await act(() => { updateFnRef.current(); }); assertLog(['Component:true']); expect(onNestedUpdateScheduled).not.toHaveBeenCalled(); }); it('it is not called when a component schedules an update during render', async () => { function Component() { const [state, setState] = React.useState(false); if (state === false) { setState(true); } Scheduler.log(`Component:${state}`); return state; } const onNestedUpdateScheduled = jest.fn(); await act(() => { ReactNoop.render( <React.Profiler id="test" onNestedUpdateScheduled={onNestedUpdateScheduled}> <Component /> </React.Profiler>, ); }); assertLog(['Component:false', 'Component:true']); expect(onNestedUpdateScheduled).not.toHaveBeenCalled(); }); it('it is called when a component schedules an update from a ref callback', async () => { function Component({mountChild}) { const [refAttached, setRefAttached] = React.useState(false); const [refDetached, setRefDetached] = React.useState(false); const refSetter = React.useCallback(ref => { if (ref !== null) { setRefAttached(true); } else { setRefDetached(true); } }, []); Scheduler.log(`Component:${refAttached}:${refDetached}`); return mountChild ? <div ref={refSetter} /> : null; } const onNestedUpdateScheduled = jest.fn(); await act(() => { ReactNoop.render( <React.Profiler id="test" onNestedUpdateScheduled={onNestedUpdateScheduled}> <Component mountChild={true} /> </React.Profiler>, ); }); assertLog(['Component:false:false', 'Component:true:false']); expect(onNestedUpdateScheduled).toHaveBeenCalledTimes(1); expect(onNestedUpdateScheduled.mock.calls[0][0]).toBe('test'); await act(() => { ReactNoop.render( <React.Profiler id="test" onNestedUpdateScheduled={onNestedUpdateScheduled}> <Component mountChild={false} /> </React.Profiler>, ); }); assertLog(['Component:true:false', 'Component:true:true']); expect(onNestedUpdateScheduled).toHaveBeenCalledTimes(2); expect(onNestedUpdateScheduled.mock.calls[1][0]).toBe('test'); }); it('is called when a class component schedules an update from the componentDidMount lifecycles', async () => { class Component extends React.Component { state = { value: false, }; componentDidMount() { this.setState({value: true}); } render() { const {value} = this.state; Scheduler.log(`Component:${value}`); return value; } } const onNestedUpdateScheduled = jest.fn(); await act(() => { ReactNoop.render( <React.Profiler id="test" onNestedUpdateScheduled={onNestedUpdateScheduled}> <Component /> </React.Profiler>, ); }); assertLog(['Component:false', 'Component:true']); expect(onNestedUpdateScheduled).toHaveBeenCalledTimes(1); expect(onNestedUpdateScheduled.mock.calls[0][0]).toBe('test'); }); it('is called when a class component schedules an update from the componentDidUpdate lifecycles', async () => { class Component extends React.Component { state = { nestedUpdateSheduled: false, }; componentDidUpdate(prevProps, prevState) { if ( this.props.scheduleNestedUpdate && !this.state.nestedUpdateSheduled ) { this.setState({nestedUpdateSheduled: true}); } } render() { const {scheduleNestedUpdate} = this.props; const {nestedUpdateSheduled} = this.state; Scheduler.log( `Component:${scheduleNestedUpdate}:${nestedUpdateSheduled}`, ); return nestedUpdateSheduled; } } const onNestedUpdateScheduled = jest.fn(); await act(() => { ReactNoop.render( <React.Profiler id="test" onNestedUpdateScheduled={onNestedUpdateScheduled}> <Component scheduleNestedUpdate={false} /> </React.Profiler>, ); }); assertLog(['Component:false:false']); expect(onNestedUpdateScheduled).not.toHaveBeenCalled(); await act(() => { ReactNoop.render( <React.Profiler id="test" onNestedUpdateScheduled={onNestedUpdateScheduled}> <Component scheduleNestedUpdate={true} /> </React.Profiler>, ); }); assertLog(['Component:true:false', 'Component:true:true']); expect(onNestedUpdateScheduled).toHaveBeenCalledTimes(1); expect(onNestedUpdateScheduled.mock.calls[0][0]).toBe('test'); }); it('is not called when a class component schedules an update outside of render', async () => { const updateFnRef = React.createRef(null); class Component extends React.Component { state = { value: false, }; render() { const {value} = this.state; updateFnRef.current = () => this.setState({value: true}); Scheduler.log(`Component:${value}`); return value; } } const onNestedUpdateScheduled = jest.fn(); await act(() => { ReactNoop.render( <React.Profiler id="test" onNestedUpdateScheduled={onNestedUpdateScheduled}> <Component /> </React.Profiler>, ); }); assertLog(['Component:false']); await act(() => { updateFnRef.current(); }); assertLog(['Component:true']); expect(onNestedUpdateScheduled).not.toHaveBeenCalled(); }); // TODO Add hydration tests to ensure we don't have false positives called. });
29.425946
117
0.596144
null
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/scheduler.native.production.min.js'); } else { module.exports = require('./cjs/scheduler.native.development.js'); }
25.625
71
0.688679