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
owtf
import 'core-js/es6/symbol'; import 'core-js/es6/promise'; import 'core-js/es6/set'; import 'core-js/es6/map'; // http://paulirish.com/2011/requestanimationframe-for-smart-animating/ // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating // requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel // MIT license (function () { var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) window.requestAnimationFrame = function (callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function () { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function (id) { clearTimeout(id); }; })();
33.567568
91
0.678404
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export function validateLinkPropsForStyleResource(props: any): boolean { if (__DEV__) { // This should only be called when we know we are opting into Resource semantics (i.e. precedence is not null) const {href, onLoad, onError, disabled} = props; const includedProps = []; if (onLoad) includedProps.push('`onLoad`'); if (onError) includedProps.push('`onError`'); if (disabled != null) includedProps.push('`disabled`'); let includedPropsPhrase = propNamesListJoin(includedProps, 'and'); includedPropsPhrase += includedProps.length === 1 ? ' prop' : ' props'; const withArticlePhrase = includedProps.length === 1 ? 'an ' + includedPropsPhrase : 'the ' + includedPropsPhrase; if (includedProps.length) { console.error( 'React encountered a <link rel="stylesheet" href="%s" ... /> with a `precedence` prop that' + ' also included %s. The presence of loading and error handlers indicates an intent to manage' + ' the stylesheet loading state from your from your Component code and React will not hoist or' + ' deduplicate this stylesheet. If your intent was to have React hoist and deduplciate this stylesheet' + ' using the `precedence` prop remove the %s, otherwise remove the `precedence` prop.', href, withArticlePhrase, includedPropsPhrase, ); return true; } } return false; } function propNamesListJoin( list: Array<string>, combinator: 'and' | 'or', ): string { switch (list.length) { case 0: return ''; case 1: return list[0]; case 2: return list[0] + ' ' + combinator + ' ' + list[1]; default: return ( list.slice(0, -1).join(', ') + ', ' + combinator + ' ' + list[list.length - 1] ); } } export function getValueDescriptorExpectingObjectForWarning( thing: any, ): string { return thing === null ? '`null`' : thing === undefined ? '`undefined`' : thing === '' ? 'an empty string' : `something with type "${typeof thing}"`; } export function getValueDescriptorExpectingEnumForWarning(thing: any): string { return thing === null ? '`null`' : thing === undefined ? '`undefined`' : thing === '' ? 'an empty string' : typeof thing === 'string' ? JSON.stringify(thing) : `something with type "${typeof thing}"`; }
29.011364
114
0.617045
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 {memo, useCallback} from 'react'; import styles from './ListItem.css'; import type {Item} from './List'; type Props = { item: Item, removeItem: (item: Item) => void, toggleItem: (item: Item) => void, }; function ListItem({item, removeItem, toggleItem}: Props) { const handleDelete = useCallback(() => { removeItem(item); }, [item, removeItem]); const handleToggle = useCallback(() => { toggleItem(item); }, [item, toggleItem]); return ( <li className={styles.ListItem}> <button className={styles.IconButton} onClick={handleDelete}> 🗑 </button> <label className={styles.Label}> <input className={styles.Input} checked={item.isComplete} onChange={handleToggle} type="checkbox" />{' '} {item.text} </label> </li> ); } export default (memo(ListItem): React.ComponentType<Props>);
22.12
67
0.61645
cybersecurity-penetration-testing
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-reconciler-reflection.production.min.js'); } else { module.exports = require('./cjs/react-reconciler-reflection.development.js'); }
28.375
82
0.709402
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/ReactFlightServer'; export * from 'react-server-dom-esm/src/ReactFlightServerConfigESMBundler'; export * from 'react-dom-bindings/src/server/ReactFlightServerConfigDOM'; export const supportsRequestStorage = true; export const requestStorage: AsyncLocalStorage<Request> = new AsyncLocalStorage(); export {createHook as createAsyncHook, executionAsyncId} from 'async_hooks'; export * from '../ReactFlightServerConfigDebugNode';
32.136364
76
0.774725
Penetration-Testing-with-Shellcode
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ const acorn = require('acorn-loose'); const url = require('url'); const Module = require('module'); module.exports = function register() { const Server: any = require('react-server-dom-turbopack/server'); const registerServerReference = Server.registerServerReference; const createClientModuleProxy = Server.createClientModuleProxy; // $FlowFixMe[prop-missing] found when upgrading Flow const originalCompile = Module.prototype._compile; // $FlowFixMe[prop-missing] found when upgrading Flow Module.prototype._compile = function ( this: any, content: string, filename: string, ): void { // Do a quick check for the exact string. If it doesn't exist, don't // bother parsing. if ( content.indexOf('use client') === -1 && content.indexOf('use server') === -1 ) { return originalCompile.apply(this, arguments); } let body; try { body = acorn.parse(content, { ecmaVersion: '2024', sourceType: 'source', }).body; } catch (x) { // eslint-disable-next-line react-internal/no-production-logging console.error('Error parsing %s %s', url, x.message); return originalCompile.apply(this, arguments); } let useClient = false; let useServer = false; for (let i = 0; i < body.length; i++) { const node = body[i]; if (node.type !== 'ExpressionStatement' || !node.directive) { break; } if (node.directive === 'use client') { useClient = true; } if (node.directive === 'use server') { useServer = true; } } if (!useClient && !useServer) { return originalCompile.apply(this, arguments); } if (useClient && useServer) { throw new Error( 'Cannot have both "use client" and "use server" directives in the same file.', ); } if (useClient) { const moduleId: string = (url.pathToFileURL(filename).href: any); this.exports = createClientModuleProxy(moduleId); } if (useServer) { originalCompile.apply(this, arguments); const moduleId: string = (url.pathToFileURL(filename).href: any); const exports = this.exports; // This module is imported server to server, but opts in to exposing functions by // reference. If there are any functions in the export. if (typeof exports === 'function') { // The module exports a function directly, registerServerReference( (exports: any), moduleId, // Represents the whole Module object instead of a particular import. null, ); } else { const keys = Object.keys(exports); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const value = exports[keys[i]]; if (typeof value === 'function') { registerServerReference((value: any), moduleId, key); } } } } }; };
27.522523
87
0.606003
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 */ /* eslint-disable no-for-of-loops/no-for-of-loops */ 'use strict'; let React; let ReactDOM; let ReactDOMClient; let ReactFreshRuntime; let Scheduler; let act; let internalAct; let createReactClass; let waitFor; let assertLog; describe('ReactFresh', () => { let container; beforeEach(() => { if (__DEV__) { jest.resetModules(); React = require('react'); ReactFreshRuntime = require('react-refresh/runtime'); ReactFreshRuntime.injectIntoGlobalHook(global); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); Scheduler = require('scheduler'); act = React.unstable_act; internalAct = require('internal-test-utils').act; const InternalTestUtils = require('internal-test-utils'); waitFor = InternalTestUtils.waitFor; assertLog = InternalTestUtils.assertLog; createReactClass = require('create-react-class/factory')( React.Component, React.isValidElement, new React.Component().updater, ); container = document.createElement('div'); document.body.appendChild(container); } }); afterEach(() => { if (__DEV__) { delete global.__REACT_DEVTOOLS_GLOBAL_HOOK__; document.body.removeChild(container); } }); function prepare(version) { const Component = version(); return Component; } function render(version, props) { const Component = version(); act(() => { ReactDOM.render(<Component {...props} />, container); }); return Component; } function patch(version) { const Component = version(); ReactFreshRuntime.performReactRefresh(); return Component; } function $RefreshReg$(type, id) { ReactFreshRuntime.register(type, id); } function $RefreshSig$(type, key, forceReset, getCustomHooks) { ReactFreshRuntime.setSignature(type, key, forceReset, getCustomHooks); return type; } // 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('can preserve state for compatible types', () => { if (__DEV__) { const HelloV1 = render(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); return Hello; }); // Bump the state before patching. const el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('blue'); act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(el.textContent).toBe('1'); // Perform a hot update. const HelloV2 = patch(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'red'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); return Hello; }); // Assert the state was preserved but color changed. expect(container.firstChild).toBe(el); expect(el.textContent).toBe('1'); expect(el.style.color).toBe('red'); // Bump the state again. act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(container.firstChild).toBe(el); expect(el.textContent).toBe('2'); expect(el.style.color).toBe('red'); // Perform top-down renders with both fresh and stale types. // Neither should change the state or color. // They should always resolve to the latest version. render(() => HelloV1); render(() => HelloV2); render(() => HelloV1); expect(container.firstChild).toBe(el); expect(el.textContent).toBe('2'); expect(el.style.color).toBe('red'); // Bump the state again. act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(container.firstChild).toBe(el); expect(el.textContent).toBe('3'); expect(el.style.color).toBe('red'); // Finally, a render with incompatible type should reset it. render(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } // No register call. // This is considered a new type. return Hello; }); expect(container.firstChild).not.toBe(el); const newEl = container.firstChild; expect(newEl.textContent).toBe('0'); expect(newEl.style.color).toBe('blue'); } }); it('can preserve state for forwardRef', () => { if (__DEV__) { const OuterV1 = render(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); const Outer = React.forwardRef(() => <Hello />); $RefreshReg$(Outer, 'Outer'); return Outer; }); // Bump the state before patching. const el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('blue'); act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(el.textContent).toBe('1'); // Perform a hot update. const OuterV2 = patch(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'red'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); const Outer = React.forwardRef(() => <Hello />); $RefreshReg$(Outer, 'Outer'); return Outer; }); // Assert the state was preserved but color changed. expect(container.firstChild).toBe(el); expect(el.textContent).toBe('1'); expect(el.style.color).toBe('red'); // Bump the state again. act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(container.firstChild).toBe(el); expect(el.textContent).toBe('2'); expect(el.style.color).toBe('red'); // Perform top-down renders with both fresh and stale types. // Neither should change the state or color. // They should always resolve to the latest version. render(() => OuterV1); render(() => OuterV2); render(() => OuterV1); expect(container.firstChild).toBe(el); expect(el.textContent).toBe('2'); expect(el.style.color).toBe('red'); // Finally, a render with incompatible type should reset it. render(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); // Note: no forwardRef wrapper this time. return Hello; }); expect(container.firstChild).not.toBe(el); const newEl = container.firstChild; expect(newEl.textContent).toBe('0'); expect(newEl.style.color).toBe('blue'); } }); it('should not consider two forwardRefs around the same type to be equivalent', () => { if (__DEV__) { const ParentV1 = render( () => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); function renderInner() { return <Hello />; } // Both of these are wrappers around the same inner function. // They should be treated as distinct types across reloads. const ForwardRefA = React.forwardRef(renderInner); $RefreshReg$(ForwardRefA, 'ForwardRefA'); const ForwardRefB = React.forwardRef(renderInner); $RefreshReg$(ForwardRefB, 'ForwardRefB'); function Parent({cond}) { return cond ? <ForwardRefA /> : <ForwardRefB />; } $RefreshReg$(Parent, 'Parent'); return Parent; }, {cond: true}, ); // Bump the state before switching up types. let el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('blue'); act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(el.textContent).toBe('1'); // Switching up the inner types should reset the state. render(() => ParentV1, {cond: false}); expect(el).not.toBe(container.firstChild); el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('blue'); act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(el.textContent).toBe('1'); // Switch them up back again. render(() => ParentV1, {cond: true}); expect(el).not.toBe(container.firstChild); el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('blue'); // Now bump up the state to prepare for patching. act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(el.textContent).toBe('1'); // Patch to change the color. const ParentV2 = patch(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'red'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); function renderInner() { return <Hello />; } // Both of these are wrappers around the same inner function. // They should be treated as distinct types across reloads. const ForwardRefA = React.forwardRef(renderInner); $RefreshReg$(ForwardRefA, 'ForwardRefA'); const ForwardRefB = React.forwardRef(renderInner); $RefreshReg$(ForwardRefB, 'ForwardRefB'); function Parent({cond}) { return cond ? <ForwardRefA /> : <ForwardRefB />; } $RefreshReg$(Parent, 'Parent'); return Parent; }); // The state should be intact; the color should change. expect(el).toBe(container.firstChild); expect(el.textContent).toBe('1'); expect(el.style.color).toBe('red'); // Switching up the condition should still reset the state. render(() => ParentV2, {cond: false}); expect(el).not.toBe(container.firstChild); el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('red'); // Now bump up the state to prepare for top-level renders. act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(el).toBe(container.firstChild); expect(el.textContent).toBe('1'); expect(el.style.color).toBe('red'); // Finally, verify using top-level render with stale type keeps state. render(() => ParentV1); render(() => ParentV2); render(() => ParentV1); expect(container.firstChild).toBe(el); expect(el.textContent).toBe('1'); expect(el.style.color).toBe('red'); } }); it('can update forwardRef render function with its wrapper', () => { if (__DEV__) { render(() => { function Hello({color}) { const [val, setVal] = React.useState(0); return ( <p style={{color}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); const Outer = React.forwardRef(() => <Hello color="blue" />); $RefreshReg$(Outer, 'Outer'); return Outer; }); // Bump the state before patching. const el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('blue'); act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(el.textContent).toBe('1'); // Perform a hot update. patch(() => { function Hello({color}) { const [val, setVal] = React.useState(0); return ( <p style={{color}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); const Outer = React.forwardRef(() => <Hello color="red" />); $RefreshReg$(Outer, 'Outer'); return Outer; }); // Assert the state was preserved but color changed. expect(container.firstChild).toBe(el); expect(el.textContent).toBe('1'); expect(el.style.color).toBe('red'); } }); it('can update forwardRef render function in isolation', () => { if (__DEV__) { render(() => { function Hello({color}) { const [val, setVal] = React.useState(0); return ( <p style={{color}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); function renderHello() { return <Hello color="blue" />; } $RefreshReg$(renderHello, 'renderHello'); return React.forwardRef(renderHello); }); // Bump the state before patching. const el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('blue'); act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(el.textContent).toBe('1'); // Perform a hot update of just the rendering function. patch(() => { function Hello({color}) { const [val, setVal] = React.useState(0); return ( <p style={{color}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); function renderHello() { return <Hello color="red" />; } $RefreshReg$(renderHello, 'renderHello'); // Not updating the wrapper. }); // Assert the state was preserved but color changed. expect(container.firstChild).toBe(el); expect(el.textContent).toBe('1'); expect(el.style.color).toBe('red'); } }); it('can preserve state for simple memo', () => { if (__DEV__) { const OuterV1 = render(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); const Outer = React.memo(Hello); $RefreshReg$(Outer, 'Outer'); return Outer; }); // Bump the state before patching. const el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('blue'); act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(el.textContent).toBe('1'); // Perform a hot update. const OuterV2 = patch(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'red'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); const Outer = React.memo(Hello); $RefreshReg$(Outer, 'Outer'); return Outer; }); // Assert the state was preserved but color changed. expect(container.firstChild).toBe(el); expect(el.textContent).toBe('1'); expect(el.style.color).toBe('red'); // Bump the state again. act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(container.firstChild).toBe(el); expect(el.textContent).toBe('2'); expect(el.style.color).toBe('red'); // Perform top-down renders with both fresh and stale types. // Neither should change the state or color. // They should always resolve to the latest version. render(() => OuterV1); render(() => OuterV2); render(() => OuterV1); expect(container.firstChild).toBe(el); expect(el.textContent).toBe('2'); expect(el.style.color).toBe('red'); // Finally, a render with incompatible type should reset it. render(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); // Note: no wrapper this time. return Hello; }); expect(container.firstChild).not.toBe(el); const newEl = container.firstChild; expect(newEl.textContent).toBe('0'); expect(newEl.style.color).toBe('blue'); } }); it('can preserve state for memo with custom comparison', () => { if (__DEV__) { const OuterV1 = render(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } const Outer = React.memo(Hello, () => true); $RefreshReg$(Outer, 'Outer'); return Outer; }); // Bump the state before patching. const el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('blue'); act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(el.textContent).toBe('1'); // Perform a hot update. const OuterV2 = patch(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'red'}} onClick={() => setVal(val + 1)}> {val} </p> ); } const Outer = React.memo(Hello, () => true); $RefreshReg$(Outer, 'Outer'); return Outer; }); // Assert the state was preserved but color changed. expect(container.firstChild).toBe(el); expect(el.textContent).toBe('1'); expect(el.style.color).toBe('red'); // Bump the state again. act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(container.firstChild).toBe(el); expect(el.textContent).toBe('2'); expect(el.style.color).toBe('red'); // Perform top-down renders with both fresh and stale types. // Neither should change the state or color. // They should always resolve to the latest version. render(() => OuterV1); render(() => OuterV2); render(() => OuterV1); expect(container.firstChild).toBe(el); expect(el.textContent).toBe('2'); expect(el.style.color).toBe('red'); // Finally, a render with incompatible type should reset it. render(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); // Note: no wrapper this time. return Hello; }); expect(container.firstChild).not.toBe(el); const newEl = container.firstChild; expect(newEl.textContent).toBe('0'); expect(newEl.style.color).toBe('blue'); } }); it('can update simple memo function in isolation', () => { if (__DEV__) { render(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); return React.memo(Hello); }); // Bump the state before patching. const el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('blue'); act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(el.textContent).toBe('1'); // Perform a hot update of just the rendering function. patch(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'red'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); // Not updating the wrapper. }); // Assert the state was preserved but color changed. expect(container.firstChild).toBe(el); expect(el.textContent).toBe('1'); expect(el.style.color).toBe('red'); } }); it('can preserve state for memo(forwardRef)', () => { if (__DEV__) { const OuterV1 = render(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); const Outer = React.memo(React.forwardRef(() => <Hello />)); $RefreshReg$(Outer, 'Outer'); return Outer; }); // Bump the state before patching. const el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('blue'); act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(el.textContent).toBe('1'); // Perform a hot update. const OuterV2 = patch(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'red'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); const Outer = React.memo(React.forwardRef(() => <Hello />)); $RefreshReg$(Outer, 'Outer'); return Outer; }); // Assert the state was preserved but color changed. expect(container.firstChild).toBe(el); expect(el.textContent).toBe('1'); expect(el.style.color).toBe('red'); // Bump the state again. act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(container.firstChild).toBe(el); expect(el.textContent).toBe('2'); expect(el.style.color).toBe('red'); // Perform top-down renders with both fresh and stale types. // Neither should change the state or color. // They should always resolve to the latest version. render(() => OuterV1); render(() => OuterV2); render(() => OuterV1); expect(container.firstChild).toBe(el); expect(el.textContent).toBe('2'); expect(el.style.color).toBe('red'); // Finally, a render with incompatible type should reset it. render(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); // Note: no wrapper this time. return Hello; }); expect(container.firstChild).not.toBe(el); const newEl = container.firstChild; expect(newEl.textContent).toBe('0'); expect(newEl.style.color).toBe('blue'); } }); it('can preserve state for lazy after resolution', async () => { if (__DEV__) { const AppV1 = render(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); const Outer = React.lazy( () => new Promise(resolve => { setTimeout(() => resolve({default: Hello}), 100); }), ); $RefreshReg$(Outer, 'Outer'); function App() { return ( <React.Suspense fallback={<p>Loading</p>}> <Outer /> </React.Suspense> ); } $RefreshReg$(App, 'App'); return App; }); expect(container.textContent).toBe('Loading'); await act(() => { jest.runAllTimers(); }); expect(container.textContent).toBe('0'); // Bump the state before patching. const el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('blue'); act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(el.textContent).toBe('1'); // Perform a hot update. const AppV2 = patch(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'red'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); const Outer = React.lazy( () => new Promise(resolve => { setTimeout(() => resolve({default: Hello}), 100); }), ); $RefreshReg$(Outer, 'Outer'); function App() { return ( <React.Suspense fallback={<p>Loading</p>}> <Outer /> </React.Suspense> ); } $RefreshReg$(App, 'App'); return App; }); // Assert the state was preserved but color changed. expect(container.firstChild).toBe(el); expect(el.textContent).toBe('1'); expect(el.style.color).toBe('red'); // Bump the state again. act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(container.firstChild).toBe(el); expect(el.textContent).toBe('2'); expect(el.style.color).toBe('red'); // Perform top-down renders with both fresh and stale types. // Neither should change the state or color. // They should always resolve to the latest version. render(() => AppV1); render(() => AppV2); render(() => AppV1); expect(container.firstChild).toBe(el); expect(el.textContent).toBe('2'); expect(el.style.color).toBe('red'); // Finally, a render with incompatible type should reset it. render(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); // Note: no lazy wrapper this time. function App() { return ( <React.Suspense fallback={<p>Loading</p>}> <Hello /> </React.Suspense> ); } $RefreshReg$(App, 'App'); return App; }); expect(container.firstChild).not.toBe(el); const newEl = container.firstChild; expect(newEl.textContent).toBe('0'); expect(newEl.style.color).toBe('blue'); } }); it('can patch lazy before resolution', async () => { if (__DEV__) { render(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); const Outer = React.lazy( () => new Promise(resolve => { setTimeout(() => resolve({default: Hello}), 100); }), ); $RefreshReg$(Outer, 'Outer'); function App() { return ( <React.Suspense fallback={<p>Loading</p>}> <Outer /> </React.Suspense> ); } return App; }); expect(container.textContent).toBe('Loading'); // Perform a hot update. patch(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'red'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); }); await act(() => { jest.runAllTimers(); }); // Expect different color on initial mount. const el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('red'); // Bump state. act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(container.firstChild).toBe(el); expect(el.textContent).toBe('1'); expect(el.style.color).toBe('red'); // Test another reload. patch(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'orange'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); }); expect(container.firstChild).toBe(el); expect(el.textContent).toBe('1'); expect(el.style.color).toBe('orange'); } }); it('can patch lazy(forwardRef) before resolution', async () => { if (__DEV__) { render(() => { function renderHello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } const Hello = React.forwardRef(renderHello); $RefreshReg$(Hello, 'Hello'); const Outer = React.lazy( () => new Promise(resolve => { setTimeout(() => resolve({default: Hello}), 100); }), ); $RefreshReg$(Outer, 'Outer'); function App() { return ( <React.Suspense fallback={<p>Loading</p>}> <Outer /> </React.Suspense> ); } return App; }); expect(container.textContent).toBe('Loading'); // Perform a hot update. patch(() => { function renderHello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'red'}} onClick={() => setVal(val + 1)}> {val} </p> ); } const Hello = React.forwardRef(renderHello); $RefreshReg$(Hello, 'Hello'); }); await act(() => { jest.runAllTimers(); }); // Expect different color on initial mount. const el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('red'); // Bump state. act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(container.firstChild).toBe(el); expect(el.textContent).toBe('1'); expect(el.style.color).toBe('red'); // Test another reload. patch(() => { function renderHello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'orange'}} onClick={() => setVal(val + 1)}> {val} </p> ); } const Hello = React.forwardRef(renderHello); $RefreshReg$(Hello, 'Hello'); }); expect(container.firstChild).toBe(el); expect(el.textContent).toBe('1'); expect(el.style.color).toBe('orange'); } }); it('can patch lazy(memo) before resolution', async () => { if (__DEV__) { render(() => { function renderHello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } const Hello = React.memo(renderHello); $RefreshReg$(Hello, 'Hello'); const Outer = React.lazy( () => new Promise(resolve => { setTimeout(() => resolve({default: Hello}), 100); }), ); $RefreshReg$(Outer, 'Outer'); function App() { return ( <React.Suspense fallback={<p>Loading</p>}> <Outer /> </React.Suspense> ); } return App; }); expect(container.textContent).toBe('Loading'); // Perform a hot update. patch(() => { function renderHello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'red'}} onClick={() => setVal(val + 1)}> {val} </p> ); } const Hello = React.memo(renderHello); $RefreshReg$(Hello, 'Hello'); }); await act(() => { jest.runAllTimers(); }); // Expect different color on initial mount. const el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('red'); // Bump state. act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(container.firstChild).toBe(el); expect(el.textContent).toBe('1'); expect(el.style.color).toBe('red'); // Test another reload. patch(() => { function renderHello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'orange'}} onClick={() => setVal(val + 1)}> {val} </p> ); } const Hello = React.memo(renderHello); $RefreshReg$(Hello, 'Hello'); }); expect(container.firstChild).toBe(el); expect(el.textContent).toBe('1'); expect(el.style.color).toBe('orange'); } }); it('can patch lazy(memo(forwardRef)) before resolution', async () => { if (__DEV__) { render(() => { function renderHello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } const Hello = React.memo(React.forwardRef(renderHello)); $RefreshReg$(Hello, 'Hello'); const Outer = React.lazy( () => new Promise(resolve => { setTimeout(() => resolve({default: Hello}), 100); }), ); $RefreshReg$(Outer, 'Outer'); function App() { return ( <React.Suspense fallback={<p>Loading</p>}> <Outer /> </React.Suspense> ); } return App; }); expect(container.textContent).toBe('Loading'); // Perform a hot update. patch(() => { function renderHello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'red'}} onClick={() => setVal(val + 1)}> {val} </p> ); } const Hello = React.memo(React.forwardRef(renderHello)); $RefreshReg$(Hello, 'Hello'); }); await act(() => { jest.runAllTimers(); }); // Expect different color on initial mount. const el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('red'); // Bump state. act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(container.firstChild).toBe(el); expect(el.textContent).toBe('1'); expect(el.style.color).toBe('red'); // Test another reload. patch(() => { function renderHello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'orange'}} onClick={() => setVal(val + 1)}> {val} </p> ); } const Hello = React.memo(React.forwardRef(renderHello)); $RefreshReg$(Hello, 'Hello'); }); expect(container.firstChild).toBe(el); expect(el.textContent).toBe('1'); expect(el.style.color).toBe('orange'); } }); it('can patch both trees while suspense is displaying the fallback', async () => { if (__DEV__) { const AppV1 = render( () => { function Hello({children}) { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {children} {val} </p> ); } $RefreshReg$(Hello, 'Hello'); function Never() { throw new Promise(resolve => {}); } function App({shouldSuspend}) { return ( <React.Suspense fallback={<Hello>Fallback</Hello>}> <Hello>Content</Hello> {shouldSuspend && <Never />} </React.Suspense> ); } return App; }, {shouldSuspend: false}, ); // We start with just the primary tree. expect(container.childNodes.length).toBe(1); const primaryChild = container.firstChild; expect(primaryChild.textContent).toBe('Content 0'); expect(primaryChild.style.color).toBe('blue'); expect(primaryChild.style.display).toBe(''); // Bump primary content state. act(() => { primaryChild.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(container.childNodes.length).toBe(1); expect(container.childNodes[0]).toBe(primaryChild); expect(primaryChild.textContent).toBe('Content 1'); expect(primaryChild.style.color).toBe('blue'); expect(primaryChild.style.display).toBe(''); // Perform a hot update. patch(() => { function Hello({children}) { const [val, setVal] = React.useState(0); return ( <p style={{color: 'green'}} onClick={() => setVal(val + 1)}> {children} {val} </p> ); } $RefreshReg$(Hello, 'Hello'); }); expect(container.childNodes.length).toBe(1); expect(container.childNodes[0]).toBe(primaryChild); expect(primaryChild.textContent).toBe('Content 1'); expect(primaryChild.style.color).toBe('green'); expect(primaryChild.style.display).toBe(''); // Now force the tree to suspend. render(() => AppV1, {shouldSuspend: true}); // Expect to see two trees, one of them is hidden. expect(container.childNodes.length).toBe(2); expect(container.childNodes[0]).toBe(primaryChild); const fallbackChild = container.childNodes[1]; expect(primaryChild.textContent).toBe('Content 1'); expect(primaryChild.style.color).toBe('green'); expect(primaryChild.style.display).toBe('none'); expect(fallbackChild.textContent).toBe('Fallback 0'); expect(fallbackChild.style.color).toBe('green'); expect(fallbackChild.style.display).toBe(''); // Bump fallback state. act(() => { fallbackChild.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(container.childNodes.length).toBe(2); expect(container.childNodes[0]).toBe(primaryChild); expect(container.childNodes[1]).toBe(fallbackChild); expect(primaryChild.textContent).toBe('Content 1'); expect(primaryChild.style.color).toBe('green'); expect(primaryChild.style.display).toBe('none'); expect(fallbackChild.textContent).toBe('Fallback 1'); expect(fallbackChild.style.color).toBe('green'); expect(fallbackChild.style.display).toBe(''); // Perform a hot update. patch(() => { function Hello({children}) { const [val, setVal] = React.useState(0); return ( <p style={{color: 'red'}} onClick={() => setVal(val + 1)}> {children} {val} </p> ); } $RefreshReg$(Hello, 'Hello'); }); // Colors inside both trees should change: expect(container.childNodes.length).toBe(2); expect(container.childNodes[0]).toBe(primaryChild); expect(container.childNodes[1]).toBe(fallbackChild); expect(primaryChild.textContent).toBe('Content 1'); expect(primaryChild.style.color).toBe('red'); expect(primaryChild.style.display).toBe('none'); expect(fallbackChild.textContent).toBe('Fallback 1'); expect(fallbackChild.style.color).toBe('red'); expect(fallbackChild.style.display).toBe(''); // Only primary tree should exist now: render(() => AppV1, {shouldSuspend: false}); expect(container.childNodes.length).toBe(1); expect(container.childNodes[0]).toBe(primaryChild); expect(primaryChild.textContent).toBe('Content 1'); expect(primaryChild.style.color).toBe('red'); expect(primaryChild.style.display).toBe(''); // Perform a hot update. patch(() => { function Hello({children}) { const [val, setVal] = React.useState(0); return ( <p style={{color: 'orange'}} onClick={() => setVal(val + 1)}> {children} {val} </p> ); } $RefreshReg$(Hello, 'Hello'); }); expect(container.childNodes.length).toBe(1); expect(container.childNodes[0]).toBe(primaryChild); expect(primaryChild.textContent).toBe('Content 1'); expect(primaryChild.style.color).toBe('orange'); expect(primaryChild.style.display).toBe(''); } }); it('does not re-render ancestor components unnecessarily during a hot update', () => { if (__DEV__) { let appRenders = 0; render(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); function App() { appRenders++; return <Hello />; } $RefreshReg$(App, 'App'); return App; }); expect(appRenders).toBe(1); // Bump the state before patching. const el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('blue'); act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(el.textContent).toBe('1'); // No re-renders from the top. expect(appRenders).toBe(1); // Perform a hot update for Hello only. patch(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'red'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); }); // Assert the state was preserved but color changed. expect(container.firstChild).toBe(el); expect(el.textContent).toBe('1'); expect(el.style.color).toBe('red'); // Still no re-renders from the top. expect(appRenders).toBe(1); // Bump the state. act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(el.textContent).toBe('2'); // Still no re-renders from the top. expect(appRenders).toBe(1); } }); it('batches re-renders during a hot update', () => { if (__DEV__) { let helloRenders = 0; render(() => { function Hello({children}) { helloRenders++; return <div>X{children}X</div>; } $RefreshReg$(Hello, 'Hello'); function App() { return ( <Hello> <Hello> <Hello /> </Hello> <Hello> <Hello /> </Hello> </Hello> ); } return App; }); expect(helloRenders).toBe(5); expect(container.textContent).toBe('XXXXXXXXXX'); helloRenders = 0; patch(() => { function Hello({children}) { helloRenders++; return <div>O{children}O</div>; } $RefreshReg$(Hello, 'Hello'); }); expect(helloRenders).toBe(5); expect(container.textContent).toBe('OOOOOOOOOO'); } }); it('does not leak state between components', () => { if (__DEV__) { const AppV1 = render( () => { function Hello1() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello1, 'Hello1'); function Hello2() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello2, 'Hello2'); function App({cond}) { return cond ? <Hello1 /> : <Hello2 />; } $RefreshReg$(App, 'App'); return App; }, {cond: false}, ); // Bump the state before patching. const el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('blue'); act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(el.textContent).toBe('1'); // Switch the condition, flipping inner content. // This should reset the state. render(() => AppV1, {cond: true}); const el2 = container.firstChild; expect(el2).not.toBe(el); expect(el2.textContent).toBe('0'); expect(el2.style.color).toBe('blue'); // Bump it again. act(() => { el2.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(el2.textContent).toBe('1'); // Perform a hot update for both inner components. patch(() => { function Hello1() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'red'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello1, 'Hello1'); function Hello2() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'red'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello2, 'Hello2'); }); // Assert the state was preserved but color changed. expect(container.firstChild).toBe(el2); expect(el2.textContent).toBe('1'); expect(el2.style.color).toBe('red'); // Flip the condition again. render(() => AppV1, {cond: false}); const el3 = container.firstChild; expect(el3).not.toBe(el2); expect(el3.textContent).toBe('0'); expect(el3.style.color).toBe('red'); } }); it('can force remount by changing signature', () => { if (__DEV__) { const HelloV1 = render(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); // When this changes, we'll expect a remount: $RefreshSig$(Hello, '1'); return Hello; }); // Bump the state before patching. const el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('blue'); act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(el.textContent).toBe('1'); // Perform a hot update. const HelloV2 = patch(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'red'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); // The signature hasn't changed since the last time: $RefreshSig$(Hello, '1'); return Hello; }); // Assert the state was preserved but color changed. expect(container.firstChild).toBe(el); expect(el.textContent).toBe('1'); expect(el.style.color).toBe('red'); // Perform a hot update. const HelloV3 = patch(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'yellow'}} onClick={() => setVal(val + 1)}> {val} </p> ); } // We're changing the signature now so it will remount: $RefreshReg$(Hello, 'Hello'); $RefreshSig$(Hello, '2'); return Hello; }); // Expect a remount. expect(container.firstChild).not.toBe(el); const newEl = container.firstChild; expect(newEl.textContent).toBe('0'); expect(newEl.style.color).toBe('yellow'); // Bump state again. act(() => { newEl.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(newEl.textContent).toBe('1'); expect(newEl.style.color).toBe('yellow'); // Perform top-down renders with both fresh and stale types. // Neither should change the state or color. // They should always resolve to the latest version. render(() => HelloV1); render(() => HelloV2); render(() => HelloV3); render(() => HelloV2); render(() => HelloV1); expect(container.firstChild).toBe(newEl); expect(newEl.textContent).toBe('1'); expect(newEl.style.color).toBe('yellow'); // Verify we can patch again while preserving the signature. patch(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'purple'}} onClick={() => setVal(val + 1)}> {val} </p> ); } // Same signature as last time. $RefreshReg$(Hello, 'Hello'); $RefreshSig$(Hello, '2'); return Hello; }); expect(container.firstChild).toBe(newEl); expect(newEl.textContent).toBe('1'); expect(newEl.style.color).toBe('purple'); // Check removing the signature also causes a remount. patch(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'orange'}} onClick={() => setVal(val + 1)}> {val} </p> ); } // No signature this time. $RefreshReg$(Hello, 'Hello'); return Hello; }); // Expect a remount. expect(container.firstChild).not.toBe(newEl); const finalEl = container.firstChild; expect(finalEl.textContent).toBe('0'); expect(finalEl.style.color).toBe('orange'); } }); it('keeps a valid tree when forcing remount', () => { if (__DEV__) { const HelloV1 = prepare(() => { function Hello() { return null; } $RefreshReg$(Hello, 'Hello'); $RefreshSig$(Hello, '1'); return Hello; }); const Bailout = React.memo(({children}) => { return children; }); // Each of those renders three instances of HelloV1, // but in different ways. const trees = [ <div> <HelloV1 /> <div> <HelloV1 /> <Bailout> <HelloV1 /> </Bailout> </div> </div>, <div> <div> <HelloV1> <HelloV1 /> </HelloV1> <HelloV1 /> </div> </div>, <div> <span /> <HelloV1 /> <HelloV1 /> <HelloV1 /> </div>, <div> <HelloV1 /> <span /> <HelloV1 /> <HelloV1 /> </div>, <div> <div>foo</div> <HelloV1 /> <div> <HelloV1 /> </div> <HelloV1 /> <span /> </div>, <div> <HelloV1> <span /> Hello <span /> </HelloV1> , <HelloV1> <> <HelloV1 /> </> </HelloV1> , </div>, <HelloV1> <HelloV1> <Bailout> <span /> <HelloV1> <span /> </HelloV1> <span /> </Bailout> </HelloV1> </HelloV1>, <div> <span /> <HelloV1 key="0" /> <HelloV1 key="1" /> <HelloV1 key="2" /> <span /> </div>, <div> <span /> {null} <HelloV1 key="1" /> {null} <HelloV1 /> <HelloV1 /> <span /> </div>, <div> <HelloV1 key="2" /> <span /> <HelloV1 key="0" /> <span /> <HelloV1 key="1" /> </div>, <div> {[[<HelloV1 key="2" />]]} <span> <HelloV1 key="0" /> {[null]} <HelloV1 key="1" /> </span> </div>, <div> {['foo', <HelloV1 key="hi" />, null, <HelloV1 key="2" />]} <span> {[null]} <HelloV1 key="x" /> </span> </div>, <HelloV1> <HelloV1> <span /> <Bailout> <HelloV1>hi</HelloV1> <span /> </Bailout> </HelloV1> </HelloV1>, ]; // First, check that each tree handles remounts in isolation. ReactDOM.render(null, container); for (let i = 0; i < trees.length; i++) { runRemountingStressTest(trees[i]); } // Then check that each tree is resilient to updates from another tree. for (let i = 0; i < trees.length; i++) { for (let j = 0; j < trees.length; j++) { ReactDOM.render(null, container); // Intentionally don't clean up between the tests: runRemountingStressTest(trees[i]); runRemountingStressTest(trees[j]); runRemountingStressTest(trees[i]); } } } }); function runRemountingStressTest(tree) { patch(() => { function Hello({children}) { return <section data-color="blue">{children}</section>; } $RefreshReg$(Hello, 'Hello'); $RefreshSig$(Hello, '1'); return Hello; }); ReactDOM.render(tree, container); const elements = container.querySelectorAll('section'); // Each tree above produces exactly three <section> elements: expect(elements.length).toBe(3); elements.forEach(el => { expect(el.dataset.color).toBe('blue'); }); // Patch color without changing the signature. patch(() => { function Hello({children}) { return <section data-color="red">{children}</section>; } $RefreshReg$(Hello, 'Hello'); $RefreshSig$(Hello, '1'); return Hello; }); const elementsAfterPatch = container.querySelectorAll('section'); expect(elementsAfterPatch.length).toBe(3); elementsAfterPatch.forEach((el, index) => { // The signature hasn't changed so we expect DOM nodes to stay the same. expect(el).toBe(elements[index]); // However, the color should have changed: expect(el.dataset.color).toBe('red'); }); // Patch color *and* change the signature. patch(() => { function Hello({children}) { return <section data-color="orange">{children}</section>; } $RefreshReg$(Hello, 'Hello'); $RefreshSig$(Hello, '2'); // Remount return Hello; }); const elementsAfterRemount = container.querySelectorAll('section'); expect(elementsAfterRemount.length).toBe(3); elementsAfterRemount.forEach((el, index) => { // The signature changed so we expect DOM nodes to be different. expect(el).not.toBe(elements[index]); // They should all be using the new color: expect(el.dataset.color).toBe('orange'); }); // Now patch color but *don't* change the signature. patch(() => { function Hello({children}) { return <section data-color="black">{children}</section>; } $RefreshReg$(Hello, 'Hello'); $RefreshSig$(Hello, '2'); // Same signature as before return Hello; }); expect(container.querySelectorAll('section').length).toBe(3); container.querySelectorAll('section').forEach((el, index) => { // The signature didn't change so DOM nodes should stay the same. expect(el).toBe(elementsAfterRemount[index]); // They should all be using the new color: expect(el.dataset.color).toBe('black'); }); // Do another render just in case. ReactDOM.render(tree, container); expect(container.querySelectorAll('section').length).toBe(3); container.querySelectorAll('section').forEach((el, index) => { expect(el).toBe(elementsAfterRemount[index]); expect(el.dataset.color).toBe('black'); }); } it('can remount on signature change within a <root> wrapper', () => { if (__DEV__) { testRemountingWithWrapper(Hello => Hello); } }); it('can remount on signature change within a simple memo wrapper', () => { if (__DEV__) { testRemountingWithWrapper(Hello => React.memo(Hello)); } }); it('can remount on signature change within a lazy simple memo wrapper', () => { if (__DEV__) { testRemountingWithWrapper(Hello => React.lazy(() => ({ then(cb) { cb({default: React.memo(Hello)}); }, })), ); } }); it('can remount on signature change within forwardRef', () => { if (__DEV__) { testRemountingWithWrapper(Hello => React.forwardRef(Hello)); } }); it('can remount on signature change within forwardRef render function', () => { if (__DEV__) { testRemountingWithWrapper(Hello => React.forwardRef(() => <Hello />)); } }); it('can remount on signature change within nested memo', () => { if (__DEV__) { testRemountingWithWrapper(Hello => React.memo(React.memo(React.memo(Hello))), ); } }); it('can remount on signature change within a memo wrapper and custom comparison', () => { if (__DEV__) { testRemountingWithWrapper(Hello => React.memo(Hello, () => true)); } }); it('can remount on signature change within a class', () => { if (__DEV__) { testRemountingWithWrapper(Hello => { const child = <Hello />; return class Wrapper extends React.PureComponent { render() { return child; } }; }); } }); it('can remount on signature change within a context provider', () => { if (__DEV__) { testRemountingWithWrapper(Hello => { const Context = React.createContext(); const child = ( <Context.Provider value="constant"> <Hello /> </Context.Provider> ); return function Wrapper() { return child; }; }); } }); it('can remount on signature change within a context consumer', () => { if (__DEV__) { testRemountingWithWrapper(Hello => { const Context = React.createContext(); const child = <Context.Consumer>{() => <Hello />}</Context.Consumer>; return function Wrapper() { return child; }; }); } }); it('can remount on signature change within a suspense node', () => { if (__DEV__) { testRemountingWithWrapper(Hello => { // TODO: we'll probably want to test fallback trees too. const child = ( <React.Suspense> <Hello /> </React.Suspense> ); return function Wrapper() { return child; }; }); } }); it('can remount on signature change within a mode node', () => { if (__DEV__) { testRemountingWithWrapper(Hello => { const child = ( <React.StrictMode> <Hello /> </React.StrictMode> ); return function Wrapper() { return child; }; }); } }); it('can remount on signature change within a fragment node', () => { if (__DEV__) { testRemountingWithWrapper(Hello => { const child = ( <> <Hello /> </> ); return function Wrapper() { return child; }; }); } }); it('can remount on signature change within multiple siblings', () => { if (__DEV__) { testRemountingWithWrapper(Hello => { const child = ( <> <> <React.Fragment /> </> <Hello /> <React.Fragment /> </> ); return function Wrapper() { return child; }; }); } }); it('can remount on signature change within a profiler node', () => { if (__DEV__) { testRemountingWithWrapper(Hello => { const child = <Hello />; return function Wrapper() { return ( <React.Profiler onRender={() => {}} id="foo"> {child} </React.Profiler> ); }; }); } }); function testRemountingWithWrapper(wrap) { render(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); // When this changes, we'll expect a remount: $RefreshSig$(Hello, '1'); // Use the passed wrapper. // This will be different in every test. return wrap(Hello); }); // Bump the state before patching. const el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('blue'); act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(el.textContent).toBe('1'); // Perform a hot update that doesn't remount. patch(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'red'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); // The signature hasn't changed since the last time: $RefreshSig$(Hello, '1'); return Hello; }); // Assert the state was preserved but color changed. expect(container.firstChild).toBe(el); expect(el.textContent).toBe('1'); expect(el.style.color).toBe('red'); // Perform a hot update that remounts. patch(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'yellow'}} onClick={() => setVal(val + 1)}> {val} </p> ); } // We're changing the signature now so it will remount: $RefreshReg$(Hello, 'Hello'); $RefreshSig$(Hello, '2'); return Hello; }); // Expect a remount. expect(container.firstChild).not.toBe(el); const newEl = container.firstChild; expect(newEl.textContent).toBe('0'); expect(newEl.style.color).toBe('yellow'); // Bump state again. act(() => { newEl.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(newEl.textContent).toBe('1'); expect(newEl.style.color).toBe('yellow'); // Verify we can patch again while preserving the signature. patch(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'purple'}} onClick={() => setVal(val + 1)}> {val} </p> ); } // Same signature as last time. $RefreshReg$(Hello, 'Hello'); $RefreshSig$(Hello, '2'); return Hello; }); expect(container.firstChild).toBe(newEl); expect(newEl.textContent).toBe('1'); expect(newEl.style.color).toBe('purple'); // Check removing the signature also causes a remount. patch(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'orange'}} onClick={() => setVal(val + 1)}> {val} </p> ); } // No signature this time. $RefreshReg$(Hello, 'Hello'); return Hello; }); // Expect a remount. expect(container.firstChild).not.toBe(newEl); const finalEl = container.firstChild; expect(finalEl.textContent).toBe('0'); expect(finalEl.style.color).toBe('orange'); } it('resets hooks with dependencies on hot reload', () => { if (__DEV__) { let useEffectWithEmptyArrayCalls = 0; render(() => { function Hello() { const [val, setVal] = React.useState(0); const tranformed = React.useMemo(() => val * 2, [val]); const handleClick = React.useCallback(() => setVal(v => v + 1), []); React.useEffect(() => { useEffectWithEmptyArrayCalls++; }, []); return ( <p style={{color: 'blue'}} onClick={handleClick}> {tranformed} </p> ); } $RefreshReg$(Hello, 'Hello'); return Hello; }); // Bump the state before patching. const el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('blue'); expect(useEffectWithEmptyArrayCalls).toBe(1); // useEffect ran act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(el.textContent).toBe('2'); // val * 2 expect(useEffectWithEmptyArrayCalls).toBe(1); // useEffect didn't re-run // Perform a hot update. act(() => { patch(() => { function Hello() { const [val, setVal] = React.useState(0); const tranformed = React.useMemo(() => val * 10, [val]); const handleClick = React.useCallback(() => setVal(v => v - 1), []); React.useEffect(() => { useEffectWithEmptyArrayCalls++; }, []); return ( <p style={{color: 'red'}} onClick={handleClick}> {tranformed} </p> ); } $RefreshReg$(Hello, 'Hello'); return Hello; }); }); // Assert the state was preserved but memo was evicted. expect(container.firstChild).toBe(el); expect(el.textContent).toBe('10'); // val * 10 expect(el.style.color).toBe('red'); expect(useEffectWithEmptyArrayCalls).toBe(2); // useEffect re-ran // This should fire the new callback which decreases the counter. act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(el.textContent).toBe('0'); expect(el.style.color).toBe('red'); expect(useEffectWithEmptyArrayCalls).toBe(2); // useEffect didn't re-run } }); // This pattern is inspired by useSubscription and similar mechanisms. it('does not get into infinite loops during render phase updates', () => { if (__DEV__) { render(() => { function Hello() { const source = React.useMemo(() => ({value: 10}), []); const [state, setState] = React.useState({value: null}); if (state !== source) { setState(source); } return <p style={{color: 'blue'}}>{state.value}</p>; } $RefreshReg$(Hello, 'Hello'); return Hello; }); const el = container.firstChild; expect(el.textContent).toBe('10'); expect(el.style.color).toBe('blue'); // Perform a hot update. act(() => { patch(() => { function Hello() { const source = React.useMemo(() => ({value: 20}), []); const [state, setState] = React.useState({value: null}); if (state !== source) { // This should perform a single render-phase update. setState(source); } return <p style={{color: 'red'}}>{state.value}</p>; } $RefreshReg$(Hello, 'Hello'); return Hello; }); }); expect(container.firstChild).toBe(el); expect(el.textContent).toBe('20'); expect(el.style.color).toBe('red'); } }); // @gate www && __DEV__ it('can hot reload offscreen components', async () => { const AppV1 = prepare(() => { function Hello() { React.useLayoutEffect(() => { Scheduler.log('Hello#layout'); }); const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); return function App({offscreen}) { React.useLayoutEffect(() => { Scheduler.log('App#layout'); }); return ( <LegacyHiddenDiv mode={offscreen ? 'hidden' : 'visible'}> <Hello /> </LegacyHiddenDiv> ); }; }); const root = ReactDOMClient.createRoot(container); root.render(<AppV1 offscreen={true} />); await waitFor(['App#layout']); const el = container.firstChild; expect(el.hidden).toBe(true); expect(el.firstChild).toBe(null); // Offscreen content not flushed yet. // Perform a hot update. patch(() => { function Hello() { React.useLayoutEffect(() => { Scheduler.log('Hello#layout'); }); const [val, setVal] = React.useState(0); return ( <p style={{color: 'red'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); }); // It's still offscreen so we don't see anything. expect(container.firstChild).toBe(el); expect(el.hidden).toBe(true); expect(el.firstChild).toBe(null); // Process the offscreen updates. await waitFor(['Hello#layout']); expect(container.firstChild).toBe(el); expect(el.firstChild.textContent).toBe('0'); expect(el.firstChild.style.color).toBe('red'); await internalAct(() => { el.firstChild.dispatchEvent( new MouseEvent('click', { bubbles: true, }), ); }); assertLog(['Hello#layout']); expect(el.firstChild.textContent).toBe('1'); expect(el.firstChild.style.color).toBe('red'); // Hot reload while we're offscreen. patch(() => { function Hello() { React.useLayoutEffect(() => { Scheduler.log('Hello#layout'); }); const [val, setVal] = React.useState(0); return ( <p style={{color: 'orange'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); }); // It's still offscreen so we don't see the updates. expect(container.firstChild).toBe(el); expect(el.firstChild.textContent).toBe('1'); expect(el.firstChild.style.color).toBe('red'); // Process the offscreen updates. await waitFor(['Hello#layout']); expect(container.firstChild).toBe(el); expect(el.firstChild.textContent).toBe('1'); expect(el.firstChild.style.color).toBe('orange'); }); it('remounts failed error boundaries (componentDidCatch)', () => { if (__DEV__) { render(() => { function Hello() { return <h1>Hi</h1>; } $RefreshReg$(Hello, 'Hello'); class Boundary extends React.Component { state = {error: null}; componentDidCatch(error) { this.setState({error}); } render() { if (this.state.error) { return <h1>Oops: {this.state.error.message}</h1>; } return this.props.children; } } function App() { return ( <> <p>A</p> <Boundary> <Hello /> </Boundary> <p>B</p> </> ); } return App; }); expect(container.innerHTML).toBe('<p>A</p><h1>Hi</h1><p>B</p>'); const firstP = container.firstChild; const secondP = firstP.nextSibling.nextSibling; // Perform a hot update that fails. patch(() => { function Hello() { throw new Error('No'); } $RefreshReg$(Hello, 'Hello'); }); expect(container.innerHTML).toBe('<p>A</p><h1>Oops: No</h1><p>B</p>'); expect(container.firstChild).toBe(firstP); expect(container.firstChild.nextSibling.nextSibling).toBe(secondP); // Perform a hot update that fixes the error. patch(() => { function Hello() { return <h1>Fixed!</h1>; } $RefreshReg$(Hello, 'Hello'); }); // This should remount the error boundary (but not anything above it). expect(container.innerHTML).toBe('<p>A</p><h1>Fixed!</h1><p>B</p>'); expect(container.firstChild).toBe(firstP); expect(container.firstChild.nextSibling.nextSibling).toBe(secondP); // Verify next hot reload doesn't remount anything. const helloNode = container.firstChild.nextSibling; patch(() => { function Hello() { return <h1>Nice.</h1>; } $RefreshReg$(Hello, 'Hello'); }); expect(container.firstChild.nextSibling).toBe(helloNode); expect(helloNode.textContent).toBe('Nice.'); } }); it('remounts failed error boundaries (getDerivedStateFromError)', () => { if (__DEV__) { render(() => { function Hello() { return <h1>Hi</h1>; } $RefreshReg$(Hello, 'Hello'); class Boundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { if (this.state.error) { return <h1>Oops: {this.state.error.message}</h1>; } return this.props.children; } } function App() { return ( <> <p>A</p> <Boundary> <Hello /> </Boundary> <p>B</p> </> ); } return App; }); expect(container.innerHTML).toBe('<p>A</p><h1>Hi</h1><p>B</p>'); const firstP = container.firstChild; const secondP = firstP.nextSibling.nextSibling; // Perform a hot update that fails. patch(() => { function Hello() { throw new Error('No'); } $RefreshReg$(Hello, 'Hello'); }); expect(container.innerHTML).toBe('<p>A</p><h1>Oops: No</h1><p>B</p>'); expect(container.firstChild).toBe(firstP); expect(container.firstChild.nextSibling.nextSibling).toBe(secondP); // Perform a hot update that fixes the error. patch(() => { function Hello() { return <h1>Fixed!</h1>; } $RefreshReg$(Hello, 'Hello'); }); // This should remount the error boundary (but not anything above it). expect(container.innerHTML).toBe('<p>A</p><h1>Fixed!</h1><p>B</p>'); expect(container.firstChild).toBe(firstP); expect(container.firstChild.nextSibling.nextSibling).toBe(secondP); // Verify next hot reload doesn't remount anything. const helloNode = container.firstChild.nextSibling; patch(() => { function Hello() { return <h1>Nice.</h1>; } $RefreshReg$(Hello, 'Hello'); }); expect(container.firstChild.nextSibling).toBe(helloNode); expect(helloNode.textContent).toBe('Nice.'); } }); it('remounts error boundaries that failed asynchronously after hot update', () => { if (__DEV__) { render(() => { function Hello() { const [x] = React.useState(''); React.useEffect(() => {}, []); x.slice(); // Doesn't throw initially. return <h1>Hi</h1>; } $RefreshReg$(Hello, 'Hello'); class Boundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { if (this.state.error) { return <h1>Oops: {this.state.error.message}</h1>; } return this.props.children; } } function App() { return ( <> <p>A</p> <Boundary> <Hello /> </Boundary> <p>B</p> </> ); } return App; }); expect(container.innerHTML).toBe('<p>A</p><h1>Hi</h1><p>B</p>'); const firstP = container.firstChild; const secondP = firstP.nextSibling.nextSibling; // Perform a hot update that fails. act(() => { patch(() => { function Hello() { const [x, setX] = React.useState(''); React.useEffect(() => { setTimeout(() => { setX(42); // This will crash next render. }, 1); }, []); x.slice(); return <h1>Hi</h1>; } $RefreshReg$(Hello, 'Hello'); }); }); expect(container.innerHTML).toBe('<p>A</p><h1>Hi</h1><p>B</p>'); // Run timeout inside effect: act(() => { jest.runAllTimers(); }); expect(container.innerHTML).toBe( '<p>A</p><h1>Oops: x.slice is not a function</h1><p>B</p>', ); expect(container.firstChild).toBe(firstP); expect(container.firstChild.nextSibling.nextSibling).toBe(secondP); // Perform a hot update that fixes the error. act(() => { patch(() => { function Hello() { const [x] = React.useState(''); React.useEffect(() => {}, []); // Removes the bad effect code. x.slice(); // Doesn't throw initially. return <h1>Fixed!</h1>; } $RefreshReg$(Hello, 'Hello'); }); }); // This should remount the error boundary (but not anything above it). expect(container.innerHTML).toBe('<p>A</p><h1>Fixed!</h1><p>B</p>'); expect(container.firstChild).toBe(firstP); expect(container.firstChild.nextSibling.nextSibling).toBe(secondP); // Verify next hot reload doesn't remount anything. const helloNode = container.firstChild.nextSibling; act(() => { patch(() => { function Hello() { const [x] = React.useState(''); React.useEffect(() => {}, []); x.slice(); return <h1>Nice.</h1>; } $RefreshReg$(Hello, 'Hello'); }); }); expect(container.firstChild.nextSibling).toBe(helloNode); expect(helloNode.textContent).toBe('Nice.'); } }); it('remounts a failed root on mount', () => { if (__DEV__) { expect(() => { render(() => { function Hello() { throw new Error('No'); } $RefreshReg$(Hello, 'Hello'); return Hello; }); }).toThrow('No'); expect(container.innerHTML).toBe(''); // A bad retry expect(() => { patch(() => { function Hello() { throw new Error('Not yet'); } $RefreshReg$(Hello, 'Hello'); }); }).toThrow('Not yet'); expect(container.innerHTML).toBe(''); // Perform a hot update that fixes the error. patch(() => { function Hello() { return <h1>Fixed!</h1>; } $RefreshReg$(Hello, 'Hello'); }); // This should mount the root. expect(container.innerHTML).toBe('<h1>Fixed!</h1>'); // Ensure we can keep failing and recovering later. expect(() => { patch(() => { function Hello() { throw new Error('No 2'); } $RefreshReg$(Hello, 'Hello'); }); }).toThrow('No 2'); expect(container.innerHTML).toBe(''); expect(() => { patch(() => { function Hello() { throw new Error('Not yet 2'); } $RefreshReg$(Hello, 'Hello'); }); }).toThrow('Not yet 2'); expect(container.innerHTML).toBe(''); patch(() => { function Hello() { return <h1>Fixed 2!</h1>; } $RefreshReg$(Hello, 'Hello'); }); expect(container.innerHTML).toBe('<h1>Fixed 2!</h1>'); // Updates after intentional unmount are ignored. ReactDOM.unmountComponentAtNode(container); patch(() => { function Hello() { throw new Error('Ignored'); } $RefreshReg$(Hello, 'Hello'); }); expect(container.innerHTML).toBe(''); patch(() => { function Hello() { return <h1>Ignored</h1>; } $RefreshReg$(Hello, 'Hello'); }); expect(container.innerHTML).toBe(''); } }); it('does not retry an intentionally unmounted failed root', () => { if (__DEV__) { expect(() => { render(() => { function Hello() { throw new Error('No'); } $RefreshReg$(Hello, 'Hello'); return Hello; }); }).toThrow('No'); expect(container.innerHTML).toBe(''); // Intentional unmount. ReactDOM.unmountComponentAtNode(container); // Perform a hot update that fixes the error. patch(() => { function Hello() { return <h1>Fixed!</h1>; } $RefreshReg$(Hello, 'Hello'); }); // This should stay unmounted. expect(container.innerHTML).toBe(''); } }); it('remounts a failed root on update', () => { if (__DEV__) { render(() => { function Hello() { return <h1>Hi</h1>; } $RefreshReg$(Hello, 'Hello'); return Hello; }); expect(container.innerHTML).toBe('<h1>Hi</h1>'); // Perform a hot update that fails. // This removes the root. expect(() => { patch(() => { function Hello() { throw new Error('No'); } $RefreshReg$(Hello, 'Hello'); }); }).toThrow('No'); expect(container.innerHTML).toBe(''); // A bad retry expect(() => { patch(() => { function Hello() { throw new Error('Not yet'); } $RefreshReg$(Hello, 'Hello'); }); }).toThrow('Not yet'); expect(container.innerHTML).toBe(''); // Perform a hot update that fixes the error. patch(() => { function Hello() { return <h1>Fixed!</h1>; } $RefreshReg$(Hello, 'Hello'); }); // This should remount the root. expect(container.innerHTML).toBe('<h1>Fixed!</h1>'); // Verify next hot reload doesn't remount anything. const helloNode = container.firstChild; patch(() => { function Hello() { return <h1>Nice.</h1>; } $RefreshReg$(Hello, 'Hello'); }); expect(container.firstChild).toBe(helloNode); expect(helloNode.textContent).toBe('Nice.'); // Break again. expect(() => { patch(() => { function Hello() { throw new Error('Oops'); } $RefreshReg$(Hello, 'Hello'); }); }).toThrow('Oops'); expect(container.innerHTML).toBe(''); // Perform a hot update that fixes the error. patch(() => { function Hello() { return <h1>At last.</h1>; } $RefreshReg$(Hello, 'Hello'); }); // This should remount the root. expect(container.innerHTML).toBe('<h1>At last.</h1>'); // Check we don't attempt to reverse an intentional unmount. ReactDOM.unmountComponentAtNode(container); expect(container.innerHTML).toBe(''); patch(() => { function Hello() { return <h1>Never mind me!</h1>; } $RefreshReg$(Hello, 'Hello'); }); expect(container.innerHTML).toBe(''); // Mount a new container. render(() => { function Hello() { return <h1>Hi</h1>; } $RefreshReg$(Hello, 'Hello'); return Hello; }); expect(container.innerHTML).toBe('<h1>Hi</h1>'); // Break again. expect(() => { patch(() => { function Hello() { throw new Error('Oops'); } $RefreshReg$(Hello, 'Hello'); }); }).toThrow('Oops'); expect(container.innerHTML).toBe(''); // Check we don't attempt to reverse an intentional unmount, even after an error. ReactDOM.unmountComponentAtNode(container); expect(container.innerHTML).toBe(''); patch(() => { function Hello() { return <h1>Never mind me!</h1>; } $RefreshReg$(Hello, 'Hello'); }); expect(container.innerHTML).toBe(''); } }); it('regression test: does not get into an infinite loop', () => { if (__DEV__) { const containerA = document.createElement('div'); const containerB = document.createElement('div'); // Initially, nothing interesting. const RootAV1 = () => { return 'A1'; }; $RefreshReg$(RootAV1, 'RootA'); const RootBV1 = () => { return 'B1'; }; $RefreshReg$(RootBV1, 'RootB'); act(() => { ReactDOM.render(<RootAV1 />, containerA); ReactDOM.render(<RootBV1 />, containerB); }); expect(containerA.innerHTML).toBe('A1'); expect(containerB.innerHTML).toBe('B1'); // Then make the first root fail. const RootAV2 = () => { throw new Error('A2!'); }; $RefreshReg$(RootAV2, 'RootA'); expect(() => ReactFreshRuntime.performReactRefresh()).toThrow('A2!'); expect(containerA.innerHTML).toBe(''); expect(containerB.innerHTML).toBe('B1'); // Then patch the first root, but make it fail in the commit phase. // This used to trigger an infinite loop due to a list of failed roots // being mutated while it was being iterated on. const RootAV3 = () => { React.useLayoutEffect(() => { throw new Error('A3!'); }, []); return 'A3'; }; $RefreshReg$(RootAV3, 'RootA'); expect(() => ReactFreshRuntime.performReactRefresh()).toThrow('A3!'); expect(containerA.innerHTML).toBe(''); expect(containerB.innerHTML).toBe('B1'); const RootAV4 = () => { return 'A4'; }; $RefreshReg$(RootAV4, 'RootA'); ReactFreshRuntime.performReactRefresh(); expect(containerA.innerHTML).toBe('A4'); expect(containerB.innerHTML).toBe('B1'); } }); it('remounts classes on every edit', () => { if (__DEV__) { const HelloV1 = render(() => { class Hello extends React.Component { state = {count: 0}; handleClick = () => { this.setState(prev => ({ count: prev.count + 1, })); }; render() { return ( <p style={{color: 'blue'}} onClick={this.handleClick}> {this.state.count} </p> ); } } // For classes, we wouldn't do this call via Babel plugin. // Instead, we'd do it at module boundaries. // Normally classes would get a different type and remount anyway, // but at module boundaries we may want to prevent propagation. // However we still want to force a remount and use latest version. $RefreshReg$(Hello, 'Hello'); return Hello; }); // Bump the state before patching. const el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('blue'); act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(el.textContent).toBe('1'); // Perform a hot update. const HelloV2 = patch(() => { class Hello extends React.Component { state = {count: 0}; handleClick = () => { this.setState(prev => ({ count: prev.count + 1, })); }; render() { return ( <p style={{color: 'red'}} onClick={this.handleClick}> {this.state.count} </p> ); } } $RefreshReg$(Hello, 'Hello'); return Hello; }); // It should have remounted the class. expect(container.firstChild).not.toBe(el); const newEl = container.firstChild; expect(newEl.textContent).toBe('0'); expect(newEl.style.color).toBe('red'); act(() => { newEl.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(newEl.textContent).toBe('1'); // Now top-level renders of both types resolve to latest. render(() => HelloV1); render(() => HelloV2); expect(container.firstChild).toBe(newEl); expect(newEl.style.color).toBe('red'); expect(newEl.textContent).toBe('1'); const HelloV3 = patch(() => { class Hello extends React.Component { state = {count: 0}; handleClick = () => { this.setState(prev => ({ count: prev.count + 1, })); }; render() { return ( <p style={{color: 'orange'}} onClick={this.handleClick}> {this.state.count} </p> ); } } $RefreshReg$(Hello, 'Hello'); return Hello; }); // It should have remounted the class again. expect(container.firstChild).not.toBe(el); const finalEl = container.firstChild; expect(finalEl.textContent).toBe('0'); expect(finalEl.style.color).toBe('orange'); act(() => { finalEl.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(finalEl.textContent).toBe('1'); render(() => HelloV3); render(() => HelloV2); render(() => HelloV1); expect(container.firstChild).toBe(finalEl); expect(finalEl.style.color).toBe('orange'); expect(finalEl.textContent).toBe('1'); } }); it('updates refs when remounting', () => { if (__DEV__) { const testRef = React.createRef(); render( () => { class Hello extends React.Component { getColor() { return 'green'; } render() { return <p />; } } $RefreshReg$(Hello, 'Hello'); return Hello; }, {ref: testRef}, ); expect(testRef.current.getColor()).toBe('green'); patch(() => { class Hello extends React.Component { getColor() { return 'orange'; } render() { return <p />; } } $RefreshReg$(Hello, 'Hello'); }); expect(testRef.current.getColor()).toBe('orange'); patch(() => { const Hello = React.forwardRef((props, ref) => { React.useImperativeHandle(ref, () => ({ getColor() { return 'pink'; }, })); return <p />; }); $RefreshReg$(Hello, 'Hello'); }); expect(testRef.current.getColor()).toBe('pink'); patch(() => { const Hello = React.forwardRef((props, ref) => { React.useImperativeHandle(ref, () => ({ getColor() { return 'yellow'; }, })); return <p />; }); $RefreshReg$(Hello, 'Hello'); }); expect(testRef.current.getColor()).toBe('yellow'); patch(() => { const Hello = React.forwardRef((props, ref) => { React.useImperativeHandle(ref, () => ({ getColor() { return 'yellow'; }, })); return <p />; }); $RefreshReg$(Hello, 'Hello'); }); expect(testRef.current.getColor()).toBe('yellow'); } }); it('remounts on conversion from class to function and back', () => { if (__DEV__) { const HelloV1 = render(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); return Hello; }); // Bump the state before patching. const el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('blue'); act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(el.textContent).toBe('1'); // Perform a hot update that turns it into a class. const HelloV2 = patch(() => { class Hello extends React.Component { state = {count: 0}; handleClick = () => { this.setState(prev => ({ count: prev.count + 1, })); }; render() { return ( <p style={{color: 'red'}} onClick={this.handleClick}> {this.state.count} </p> ); } } $RefreshReg$(Hello, 'Hello'); return Hello; }); // It should have remounted. expect(container.firstChild).not.toBe(el); const newEl = container.firstChild; expect(newEl.textContent).toBe('0'); expect(newEl.style.color).toBe('red'); act(() => { newEl.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(newEl.textContent).toBe('1'); // Now top-level renders of both types resolve to latest. render(() => HelloV1); render(() => HelloV2); expect(container.firstChild).toBe(newEl); expect(newEl.style.color).toBe('red'); expect(newEl.textContent).toBe('1'); // Now convert it back to a function. const HelloV3 = patch(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'orange'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); return Hello; }); // It should have remounted again. expect(container.firstChild).not.toBe(el); const finalEl = container.firstChild; expect(finalEl.textContent).toBe('0'); expect(finalEl.style.color).toBe('orange'); act(() => { finalEl.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(finalEl.textContent).toBe('1'); render(() => HelloV3); render(() => HelloV2); render(() => HelloV1); expect(container.firstChild).toBe(finalEl); expect(finalEl.style.color).toBe('orange'); expect(finalEl.textContent).toBe('1'); // Now that it's a function, verify edits keep state. patch(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'purple'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); return Hello; }); expect(container.firstChild).toBe(finalEl); expect(finalEl.style.color).toBe('purple'); expect(finalEl.textContent).toBe('1'); } }); it('can find host instances for a family', () => { if (__DEV__) { render(() => { function Child({children}) { return <div className="Child">{children}</div>; } $RefreshReg$(Child, 'Child'); function Parent({children}) { return ( <div className="Parent"> <div> <Child /> </div> <div> <Child /> </div> </div> ); } $RefreshReg$(Parent, 'Parent'); function App() { return ( <div className="App"> <Parent /> <Cls> <Parent /> </Cls> <Indirection> <Empty /> </Indirection> </div> ); } $RefreshReg$(App, 'App'); class Cls extends React.Component { render() { return this.props.children; } } function Indirection({children}) { return children; } function Empty() { return null; } $RefreshReg$(Empty, 'Empty'); function Frag() { return ( <> <div className="Frag"> <div /> </div> <div className="Frag"> <div /> </div> </> ); } $RefreshReg$(Frag, 'Frag'); return App; }); const parentFamily = ReactFreshRuntime.getFamilyByID('Parent'); const childFamily = ReactFreshRuntime.getFamilyByID('Child'); const emptyFamily = ReactFreshRuntime.getFamilyByID('Empty'); testFindHostInstancesForFamilies( [parentFamily], container.querySelectorAll('.Parent'), ); testFindHostInstancesForFamilies( [childFamily], container.querySelectorAll('.Child'), ); // When searching for both Parent and Child, // we'll stop visual highlighting at the Parent. testFindHostInstancesForFamilies( [parentFamily, childFamily], container.querySelectorAll('.Parent'), ); // When we can't find host nodes, use the closest parent. testFindHostInstancesForFamilies( [emptyFamily], container.querySelectorAll('.App'), ); } }); function testFindHostInstancesForFamilies(families, expectedNodes) { const foundInstances = Array.from( ReactFreshRuntime.findAffectedHostInstances(families), ); expect(foundInstances.length).toEqual(expectedNodes.length); foundInstances.forEach((node, i) => { expect(node).toBe(expectedNodes[i]); }); } it('can update multiple roots independently', () => { if (__DEV__) { // Declare the first version. const HelloV1 = () => { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); }; $RefreshReg$(HelloV1, 'Hello'); // Perform a hot update before any roots exist. const HelloV2 = () => { const [val, setVal] = React.useState(0); return ( <p style={{color: 'red'}} onClick={() => setVal(val + 1)}> {val} </p> ); }; $RefreshReg$(HelloV2, 'Hello'); ReactFreshRuntime.performReactRefresh(); // Mount three roots. const cont1 = document.createElement('div'); const cont2 = document.createElement('div'); const cont3 = document.createElement('div'); document.body.appendChild(cont1); document.body.appendChild(cont2); document.body.appendChild(cont3); try { ReactDOM.render(<HelloV1 id={1} />, cont1); ReactDOM.render(<HelloV2 id={2} />, cont2); ReactDOM.render(<HelloV1 id={3} />, cont3); // Expect we see the V2 color. expect(cont1.firstChild.style.color).toBe('red'); expect(cont2.firstChild.style.color).toBe('red'); expect(cont3.firstChild.style.color).toBe('red'); expect(cont1.firstChild.textContent).toBe('0'); expect(cont2.firstChild.textContent).toBe('0'); expect(cont3.firstChild.textContent).toBe('0'); // Bump the state for each of them. act(() => { cont1.firstChild.dispatchEvent( new MouseEvent('click', {bubbles: true}), ); cont2.firstChild.dispatchEvent( new MouseEvent('click', {bubbles: true}), ); cont3.firstChild.dispatchEvent( new MouseEvent('click', {bubbles: true}), ); }); expect(cont1.firstChild.style.color).toBe('red'); expect(cont2.firstChild.style.color).toBe('red'); expect(cont3.firstChild.style.color).toBe('red'); expect(cont1.firstChild.textContent).toBe('1'); expect(cont2.firstChild.textContent).toBe('1'); expect(cont3.firstChild.textContent).toBe('1'); // Perform another hot update. const HelloV3 = () => { const [val, setVal] = React.useState(0); return ( <p style={{color: 'green'}} onClick={() => setVal(val + 1)}> {val} </p> ); }; $RefreshReg$(HelloV3, 'Hello'); ReactFreshRuntime.performReactRefresh(); // It should affect all roots. expect(cont1.firstChild.style.color).toBe('green'); expect(cont2.firstChild.style.color).toBe('green'); expect(cont3.firstChild.style.color).toBe('green'); expect(cont1.firstChild.textContent).toBe('1'); expect(cont2.firstChild.textContent).toBe('1'); expect(cont3.firstChild.textContent).toBe('1'); // Unmount the second root. ReactDOM.unmountComponentAtNode(cont2); // Make the first root throw and unmount on hot update. const HelloV4 = ({id}) => { if (id === 1) { throw new Error('Oops.'); } const [val, setVal] = React.useState(0); return ( <p style={{color: 'orange'}} onClick={() => setVal(val + 1)}> {val} </p> ); }; $RefreshReg$(HelloV4, 'Hello'); expect(() => { ReactFreshRuntime.performReactRefresh(); }).toThrow('Oops.'); // Still, we expect the last root to be updated. expect(cont1.innerHTML).toBe(''); expect(cont2.innerHTML).toBe(''); expect(cont3.firstChild.style.color).toBe('orange'); expect(cont3.firstChild.textContent).toBe('1'); } finally { document.body.removeChild(cont1); document.body.removeChild(cont2); document.body.removeChild(cont3); } } }); // Module runtimes can use this to decide whether // to propagate an update up to the modules that imported it, // or to stop at the current module because it's a component. // This can't and doesn't need to be 100% precise. it('can detect likely component types', () => { function useTheme() {} function Widget() {} if (__DEV__) { expect(ReactFreshRuntime.isLikelyComponentType(false)).toBe(false); expect(ReactFreshRuntime.isLikelyComponentType(null)).toBe(false); expect(ReactFreshRuntime.isLikelyComponentType('foo')).toBe(false); // We need to hit a balance here. // If we lean towards assuming everything is a component, // editing modules that export plain functions won't trigger // a proper reload because we will bottle up the update. // So we're being somewhat conservative. expect(ReactFreshRuntime.isLikelyComponentType(() => {})).toBe(false); expect(ReactFreshRuntime.isLikelyComponentType(function () {})).toBe( false, ); expect( ReactFreshRuntime.isLikelyComponentType(function lightenColor() {}), ).toBe(false); const loadUser = () => {}; expect(ReactFreshRuntime.isLikelyComponentType(loadUser)).toBe(false); const useStore = () => {}; expect(ReactFreshRuntime.isLikelyComponentType(useStore)).toBe(false); expect(ReactFreshRuntime.isLikelyComponentType(useTheme)).toBe(false); const rogueProxy = new Proxy( {}, { get(target, property) { throw new Error(); }, }, ); expect(ReactFreshRuntime.isLikelyComponentType(rogueProxy)).toBe(false); // These seem like function components. const Button = () => {}; expect(ReactFreshRuntime.isLikelyComponentType(Button)).toBe(true); expect(ReactFreshRuntime.isLikelyComponentType(Widget)).toBe(true); const ProxyButton = new Proxy(Button, { get(target, property) { return target[property]; }, }); expect(ReactFreshRuntime.isLikelyComponentType(ProxyButton)).toBe(true); const anon = (() => () => {})(); anon.displayName = 'Foo'; expect(ReactFreshRuntime.isLikelyComponentType(anon)).toBe(true); // These seem like class components. class Btn extends React.Component {} class PureBtn extends React.PureComponent {} const ProxyBtn = new Proxy(Btn, { get(target, property) { return target[property]; }, }); expect(ReactFreshRuntime.isLikelyComponentType(Btn)).toBe(true); expect(ReactFreshRuntime.isLikelyComponentType(PureBtn)).toBe(true); expect(ReactFreshRuntime.isLikelyComponentType(ProxyBtn)).toBe(true); expect( ReactFreshRuntime.isLikelyComponentType( createReactClass({render() {}}), ), ).toBe(true); // These don't. class Figure { move() {} } expect(ReactFreshRuntime.isLikelyComponentType(Figure)).toBe(false); class Point extends Figure {} expect(ReactFreshRuntime.isLikelyComponentType(Point)).toBe(false); // Run the same tests without Babel. // This tests real arrow functions and classes, as implemented in Node. // eslint-disable-next-line no-new-func new Function( 'global', 'React', 'ReactFreshRuntime', 'expect', 'createReactClass', ` expect(ReactFreshRuntime.isLikelyComponentType(() => {})).toBe(false); expect(ReactFreshRuntime.isLikelyComponentType(function() {})).toBe(false); expect( ReactFreshRuntime.isLikelyComponentType(function lightenColor() {}), ).toBe(false); const loadUser = () => {}; expect(ReactFreshRuntime.isLikelyComponentType(loadUser)).toBe(false); const useStore = () => {}; expect(ReactFreshRuntime.isLikelyComponentType(useStore)).toBe(false); function useTheme() {} expect(ReactFreshRuntime.isLikelyComponentType(useTheme)).toBe(false); // These seem like function components. let Button = () => {}; expect(ReactFreshRuntime.isLikelyComponentType(Button)).toBe(true); function Widget() {} expect(ReactFreshRuntime.isLikelyComponentType(Widget)).toBe(true); let anon = (() => () => {})(); anon.displayName = 'Foo'; expect(ReactFreshRuntime.isLikelyComponentType(anon)).toBe(true); // These seem like class components. class Btn extends React.Component {} class PureBtn extends React.PureComponent {} expect(ReactFreshRuntime.isLikelyComponentType(Btn)).toBe(true); expect(ReactFreshRuntime.isLikelyComponentType(PureBtn)).toBe(true); expect( ReactFreshRuntime.isLikelyComponentType(createReactClass({render() {}})), ).toBe(true); // These don't. class Figure { move() {} } expect(ReactFreshRuntime.isLikelyComponentType(Figure)).toBe(false); class Point extends Figure {} expect(ReactFreshRuntime.isLikelyComponentType(Point)).toBe(false); `, )(global, React, ReactFreshRuntime, expect, createReactClass); } }); it('reports updated and remounted families to the caller', () => { if (__DEV__) { const HelloV1 = () => { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); }; $RefreshReg$(HelloV1, 'Hello'); const HelloV2 = () => { const [val, setVal] = React.useState(0); return ( <p style={{color: 'red'}} onClick={() => setVal(val + 1)}> {val} </p> ); }; $RefreshReg$(HelloV2, 'Hello'); const update = ReactFreshRuntime.performReactRefresh(); expect(update.updatedFamilies.size).toBe(1); expect(update.staleFamilies.size).toBe(0); const family = update.updatedFamilies.values().next().value; expect(family.current.name).toBe('HelloV2'); // For example, we can use this to print a log of what was updated. } }); function initFauxDevToolsHook() { const onCommitFiberRoot = jest.fn(); const onCommitFiberUnmount = jest.fn(); let idCounter = 0; const renderers = new Map(); // This is a minimal shim for the global hook installed by DevTools. // The real one is in packages/react-devtools-shared/src/hook.js. global.__REACT_DEVTOOLS_GLOBAL_HOOK__ = { renderers, supportsFiber: true, inject(renderer) { const id = ++idCounter; renderers.set(id, renderer); return id; }, onCommitFiberRoot, onCommitFiberUnmount, }; } // This simulates the scenario in https://github.com/facebook/react/issues/17626 it('can inject the runtime after the renderer executes', async () => { if (__DEV__) { initFauxDevToolsHook(); // Load these first, as if they're coming from a CDN. jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); Scheduler = require('scheduler'); act = React.unstable_act; internalAct = require('internal-test-utils').act; // Important! Inject into the global hook *after* ReactDOM runs: ReactFreshRuntime = require('react-refresh/runtime'); ReactFreshRuntime.injectIntoGlobalHook(global); // We're verifying that we're able to track roots mounted after this point. // The rest of this test is taken from the simplest first test case. render(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'blue'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); return Hello; }); // Bump the state before patching. const el = container.firstChild; expect(el.textContent).toBe('0'); expect(el.style.color).toBe('blue'); act(() => { el.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(el.textContent).toBe('1'); // Perform a hot update. patch(() => { function Hello() { const [val, setVal] = React.useState(0); return ( <p style={{color: 'red'}} onClick={() => setVal(val + 1)}> {val} </p> ); } $RefreshReg$(Hello, 'Hello'); return Hello; }); // Assert the state was preserved but color changed. expect(container.firstChild).toBe(el); expect(el.textContent).toBe('1'); expect(el.style.color).toBe('red'); } }); // This simulates the scenario in https://github.com/facebook/react/issues/20100 it('does not block DevTools when an unsupported renderer is injected', () => { if (__DEV__) { initFauxDevToolsHook(); const onCommitFiberRoot = global.__REACT_DEVTOOLS_GLOBAL_HOOK__.onCommitFiberRoot; // Redirect all React/ReactDOM requires to v16.8.0 // This version predates Fast Refresh support. jest.mock('scheduler', () => jest.requireActual('scheduler-0-13')); jest.mock('scheduler/tracing', () => jest.requireActual('scheduler-0-13/tracing'), ); jest.mock('react', () => jest.requireActual('react-16-8')); jest.mock('react-dom', () => jest.requireActual('react-dom-16-8')); // Load React and company. jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); Scheduler = require('scheduler'); // Important! Inject into the global hook *after* ReactDOM runs: ReactFreshRuntime = require('react-refresh/runtime'); ReactFreshRuntime.injectIntoGlobalHook(global); render(() => { function Hello() { return <div>Hi!</div>; } $RefreshReg$(Hello, 'Hello'); return Hello; }); expect(onCommitFiberRoot).toHaveBeenCalled(); } }); });
28.589915
91
0.519132
Hands-On-Penetration-Testing-with-Python
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; import {useCallback} from 'react'; import styles from './Toggle.css'; import Tooltip from './Components/reach-ui/tooltip'; type Props = { children: React$Node, className?: string, isChecked: boolean, isDisabled?: boolean, onChange: (isChecked: boolean) => void, testName?: ?string, title?: string, ... }; export default function Toggle({ children, className = '', isDisabled = false, isChecked, onChange, testName, title, }: Props): React.Node { let defaultClassName; if (isDisabled) { defaultClassName = styles.ToggleDisabled; } else if (isChecked) { defaultClassName = styles.ToggleOn; } else { defaultClassName = styles.ToggleOff; } const handleClick = useCallback( () => onChange(!isChecked), [isChecked, onChange], ); let toggle = ( <button className={`${defaultClassName} ${className}`} data-testname={testName} disabled={isDisabled} onClick={handleClick}> <span className={styles.ToggleContent} tabIndex={-1}> {children} </span> </button> ); if (title) { toggle = <Tooltip label={title}>{toggle}</Tooltip>; } return toggle; }
19.691176
66
0.647937
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 {DOMEventName} from './DOMEventNames'; export type DispatchConfig = { dependencies?: Array<DOMEventName>, phasedRegistrationNames: { bubbled: null | string, captured: null | string, }, registrationName?: string, }; type BaseSyntheticEvent = { isPersistent: () => boolean, isPropagationStopped: () => boolean, _dispatchInstances?: null | Array<Fiber | null> | Fiber, _dispatchListeners?: null | Array<Function> | Function, _targetInst: Fiber, nativeEvent: Event, target?: mixed, relatedTarget?: mixed, type: string, currentTarget: null | EventTarget, }; export type KnownReactSyntheticEvent = BaseSyntheticEvent & { _reactName: string, }; export type UnknownReactSyntheticEvent = BaseSyntheticEvent & { _reactName: null, }; export type ReactSyntheticEvent = | KnownReactSyntheticEvent | UnknownReactSyntheticEvent;
25.478261
70
0.728841
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 */ let Profiler; let React; let ReactNoop; let Scheduler; let ReactFeatureFlags; let ReactCache; let Suspense; let TextResource; let textResourceShouldFail; let waitForAll; let assertLog; let act; describe('ReactSuspensePlaceholder', () => { beforeEach(() => { jest.resetModules(); ReactFeatureFlags = require('shared/ReactFeatureFlags'); ReactFeatureFlags.enableProfilerTimer = true; ReactFeatureFlags.replayFailedUnitOfWorkWithInvokeGuardedCallback = false; React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); ReactCache = require('react-cache'); Profiler = React.Profiler; Suspense = React.Suspense; const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; assertLog = InternalTestUtils.assertLog; act = InternalTestUtils.act; TextResource = ReactCache.unstable_createResource( ([text, ms = 0]) => { let listeners = null; let status = 'pending'; let value = null; return { then(resolve, reject) { switch (status) { case 'pending': { if (listeners === null) { listeners = [{resolve, reject}]; setTimeout(() => { if (textResourceShouldFail) { Scheduler.log(`Promise rejected [${text}]`); status = 'rejected'; value = new Error('Failed to load: ' + text); listeners.forEach(listener => listener.reject(value)); } else { Scheduler.log(`Promise resolved [${text}]`); status = 'resolved'; value = text; listeners.forEach(listener => listener.resolve(value)); } }, ms); } else { listeners.push({resolve, reject}); } break; } case 'resolved': { resolve(value); break; } case 'rejected': { reject(value); break; } } }, }; }, ([text, ms]) => text, ); textResourceShouldFail = false; }); function Text({fakeRenderDuration = 0, text = 'Text'}) { Scheduler.unstable_advanceTime(fakeRenderDuration); Scheduler.log(text); return text; } function AsyncText({fakeRenderDuration = 0, ms, text}) { Scheduler.unstable_advanceTime(fakeRenderDuration); try { TextResource.read([text, ms]); Scheduler.log(text); return text; } catch (promise) { if (typeof promise.then === 'function') { Scheduler.log(`Suspend! [${text}]`); } else { Scheduler.log(`Error! [${text}]`); } throw promise; } } it('times out children that are already hidden', async () => { class HiddenText extends React.PureComponent { render() { const text = this.props.text; Scheduler.log(text); return <span hidden={true}>{text}</span>; } } function App(props) { return ( <Suspense fallback={<Text text="Loading..." />}> <HiddenText text="A" /> <span> <AsyncText ms={1000} text={props.middleText} /> </span> <span> <Text text="C" /> </span> </Suspense> ); } // Initial mount ReactNoop.render(<App middleText="B" />); await waitForAll(['A', 'Suspend! [B]', 'Loading...']); expect(ReactNoop).toMatchRenderedOutput('Loading...'); await act(() => jest.advanceTimersByTime(1000)); assertLog(['Promise resolved [B]', 'A', 'B', 'C']); expect(ReactNoop).toMatchRenderedOutput( <> <span hidden={true}>A</span> <span>B</span> <span>C</span> </>, ); // Update ReactNoop.render(<App middleText="B2" />); await waitForAll(['Suspend! [B2]', 'Loading...']); // Time out the update jest.advanceTimersByTime(750); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput( <> <span hidden={true}>A</span> <span hidden={true}>B</span> <span hidden={true}>C</span> Loading... </>, ); // Resolve the promise await act(() => jest.advanceTimersByTime(1000)); assertLog(['Promise resolved [B2]', 'B2', 'C']); // Render the final update. A should still be hidden, because it was // given a `hidden` prop. expect(ReactNoop).toMatchRenderedOutput( <> <span hidden={true}>A</span> <span>B2</span> <span>C</span> </>, ); }); it('times out text nodes', async () => { function App(props) { return ( <Suspense fallback={<Text text="Loading..." />}> <Text text="A" /> <AsyncText ms={1000} text={props.middleText} /> <Text text="C" /> </Suspense> ); } // Initial mount ReactNoop.render(<App middleText="B" />); await waitForAll(['A', 'Suspend! [B]', 'Loading...']); expect(ReactNoop).not.toMatchRenderedOutput('ABC'); await act(() => jest.advanceTimersByTime(1000)); assertLog(['Promise resolved [B]', 'A', 'B', 'C']); expect(ReactNoop).toMatchRenderedOutput('ABC'); // Update ReactNoop.render(<App middleText="B2" />); await waitForAll(['A', 'Suspend! [B2]', 'Loading...']); // Time out the update jest.advanceTimersByTime(750); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput('Loading...'); // Resolve the promise await act(() => jest.advanceTimersByTime(1000)); assertLog(['Promise resolved [B2]', 'A', 'B2', 'C']); // Render the final update. A should still be hidden, because it was // given a `hidden` prop. expect(ReactNoop).toMatchRenderedOutput('AB2C'); }); it('preserves host context for text nodes', async () => { function App(props) { return ( // uppercase is a special type that causes React Noop to render child // text nodes as uppercase. <uppercase> <Suspense fallback={<Text text="Loading..." />}> <Text text="a" /> <AsyncText ms={1000} text={props.middleText} /> <Text text="c" /> </Suspense> </uppercase> ); } // Initial mount ReactNoop.render(<App middleText="b" />); await waitForAll(['a', 'Suspend! [b]', 'Loading...']); expect(ReactNoop).toMatchRenderedOutput(<uppercase>LOADING...</uppercase>); await act(() => jest.advanceTimersByTime(1000)); assertLog(['Promise resolved [b]', 'a', 'b', 'c']); expect(ReactNoop).toMatchRenderedOutput(<uppercase>ABC</uppercase>); // Update ReactNoop.render(<App middleText="b2" />); await waitForAll(['a', 'Suspend! [b2]', 'Loading...']); // Time out the update jest.advanceTimersByTime(750); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<uppercase>LOADING...</uppercase>); // Resolve the promise await act(() => jest.advanceTimersByTime(1000)); assertLog(['Promise resolved [b2]', 'a', 'b2', 'c']); // Render the final update. A should still be hidden, because it was // given a `hidden` prop. expect(ReactNoop).toMatchRenderedOutput(<uppercase>AB2C</uppercase>); }); describe('profiler durations', () => { let App; let onRender; beforeEach(() => { // Order of parameters: id, phase, actualDuration, treeBaseDuration onRender = jest.fn(); const Fallback = () => { Scheduler.log('Fallback'); Scheduler.unstable_advanceTime(10); return 'Loading...'; }; const Suspending = () => { Scheduler.log('Suspending'); Scheduler.unstable_advanceTime(2); return <AsyncText ms={1000} text="Loaded" fakeRenderDuration={1} />; }; App = ({shouldSuspend, text = 'Text', textRenderDuration = 5}) => { Scheduler.log('App'); return ( <Profiler id="root" onRender={onRender}> <Suspense fallback={<Fallback />}> {shouldSuspend && <Suspending />} <Text fakeRenderDuration={textRenderDuration} text={text} /> </Suspense> </Profiler> ); }; }); describe('when suspending during mount', () => { it('properly accounts for base durations when a suspended times out in a legacy tree', async () => { ReactNoop.renderLegacySyncRoot(<App shouldSuspend={true} />); assertLog([ 'App', 'Suspending', 'Suspend! [Loaded]', 'Text', 'Fallback', ]); expect(ReactNoop).toMatchRenderedOutput('Loading...'); expect(onRender).toHaveBeenCalledTimes(1); // Initial mount only shows the "Loading..." Fallback. // The treeBaseDuration then should be 10ms spent rendering Fallback, // but the actualDuration should also include the 8ms spent rendering the hidden tree. expect(onRender.mock.calls[0][2]).toBe(18); expect(onRender.mock.calls[0][3]).toBe(10); jest.advanceTimersByTime(1000); assertLog(['Promise resolved [Loaded]']); ReactNoop.flushSync(); assertLog(['Loaded']); expect(ReactNoop).toMatchRenderedOutput('LoadedText'); expect(onRender).toHaveBeenCalledTimes(2); // When the suspending data is resolved and our final UI is rendered, // the baseDuration should only include the 1ms re-rendering AsyncText, // but the treeBaseDuration should include the full 8ms spent in the tree. expect(onRender.mock.calls[1][2]).toBe(1); expect(onRender.mock.calls[1][3]).toBe(8); }); it('properly accounts for base durations when a suspended times out in a concurrent tree', async () => { ReactNoop.render(<App shouldSuspend={true} />); await waitForAll([ 'App', 'Suspending', 'Suspend! [Loaded]', 'Fallback', ]); // Since this is initial render we immediately commit the fallback. Another test below // deals with the update case where this suspends. expect(ReactNoop).toMatchRenderedOutput('Loading...'); expect(onRender).toHaveBeenCalledTimes(1); // Initial mount only shows the "Loading..." Fallback. // The treeBaseDuration then should be 10ms spent rendering Fallback, // but the actualDuration should also include the 3ms spent rendering the hidden tree. expect(onRender.mock.calls[0][2]).toBe(13); expect(onRender.mock.calls[0][3]).toBe(10); // Resolve the pending promise. await act(() => jest.advanceTimersByTime(1000)); assertLog([ 'Promise resolved [Loaded]', 'Suspending', 'Loaded', 'Text', ]); expect(ReactNoop).toMatchRenderedOutput('LoadedText'); expect(onRender).toHaveBeenCalledTimes(2); // When the suspending data is resolved and our final UI is rendered, // both times should include the 8ms re-rendering Suspending and AsyncText. expect(onRender.mock.calls[1][2]).toBe(8); expect(onRender.mock.calls[1][3]).toBe(8); }); }); describe('when suspending during update', () => { it('properly accounts for base durations when a suspended times out in a legacy tree', async () => { ReactNoop.renderLegacySyncRoot( <App shouldSuspend={false} textRenderDuration={5} />, ); assertLog(['App', 'Text']); expect(ReactNoop).toMatchRenderedOutput('Text'); expect(onRender).toHaveBeenCalledTimes(1); // Initial mount only shows the "Text" text. // It should take 5ms to render. expect(onRender.mock.calls[0][2]).toBe(5); expect(onRender.mock.calls[0][3]).toBe(5); ReactNoop.render(<App shouldSuspend={true} textRenderDuration={5} />); assertLog([ 'App', 'Suspending', 'Suspend! [Loaded]', 'Text', 'Fallback', ]); expect(ReactNoop).toMatchRenderedOutput('Loading...'); expect(onRender).toHaveBeenCalledTimes(2); // The suspense update should only show the "Loading..." Fallback. // The actual duration should include 10ms spent rendering Fallback, // plus the 8ms render all of the hidden, suspended subtree. // But the tree base duration should only include 10ms spent rendering Fallback, expect(onRender.mock.calls[1][2]).toBe(18); expect(onRender.mock.calls[1][3]).toBe(10); ReactNoop.renderLegacySyncRoot( <App shouldSuspend={true} text="New" textRenderDuration={6} />, ); assertLog([ 'App', 'Suspending', 'Suspend! [Loaded]', 'New', 'Fallback', ]); expect(ReactNoop).toMatchRenderedOutput('Loading...'); expect(onRender).toHaveBeenCalledTimes(3); expect(onRender.mock.calls[1][2]).toBe(18); expect(onRender.mock.calls[1][3]).toBe(10); jest.advanceTimersByTime(1000); assertLog(['Promise resolved [Loaded]']); ReactNoop.flushSync(); assertLog(['Loaded']); expect(ReactNoop).toMatchRenderedOutput('LoadedNew'); expect(onRender).toHaveBeenCalledTimes(4); // When the suspending data is resolved and our final UI is rendered, // the baseDuration should only include the 1ms re-rendering AsyncText, // but the treeBaseDuration should include the full 9ms spent in the tree. expect(onRender.mock.calls[3][2]).toBe(1); expect(onRender.mock.calls[3][3]).toBe(9); }); it('properly accounts for base durations when a suspended times out in a concurrent tree', async () => { const Fallback = () => { Scheduler.log('Fallback'); Scheduler.unstable_advanceTime(10); return 'Loading...'; }; const Suspending = () => { Scheduler.log('Suspending'); Scheduler.unstable_advanceTime(2); return <AsyncText ms={1000} text="Loaded" fakeRenderDuration={1} />; }; App = ({shouldSuspend, text = 'Text', textRenderDuration = 5}) => { Scheduler.log('App'); return ( <Profiler id="root" onRender={onRender}> <Suspense fallback={<Fallback />}> {shouldSuspend && <Suspending />} <Text fakeRenderDuration={textRenderDuration} text={text} /> </Suspense> </Profiler> ); }; ReactNoop.render( <> <App shouldSuspend={false} textRenderDuration={5} /> <Suspense fallback={null} /> </>, ); await waitForAll(['App', 'Text']); expect(ReactNoop).toMatchRenderedOutput('Text'); expect(onRender).toHaveBeenCalledTimes(1); // Initial mount only shows the "Text" text. // It should take 5ms to render. expect(onRender.mock.calls[0][2]).toBe(5); expect(onRender.mock.calls[0][3]).toBe(5); ReactNoop.render( <> <App shouldSuspend={true} textRenderDuration={5} /> <Suspense fallback={null} /> </>, ); await waitForAll([ 'App', 'Suspending', 'Suspend! [Loaded]', 'Fallback', ]); // Show the fallback UI. expect(ReactNoop).toMatchRenderedOutput('Loading...'); expect(onRender).toHaveBeenCalledTimes(2); jest.advanceTimersByTime(900); // The suspense update should only show the "Loading..." Fallback. // The actual duration should include 10ms spent rendering Fallback, // plus the 3ms render all of the partially rendered suspended subtree. // But the tree base duration should only include 10ms spent rendering Fallback. expect(onRender.mock.calls[1][2]).toBe(13); expect(onRender.mock.calls[1][3]).toBe(10); // Update again while timed out. // Since this test was originally written we added an optimization to avoid // suspending in the case that we already timed out. To simulate the old // behavior, we add a different suspending boundary as a sibling. ReactNoop.render( <> <App shouldSuspend={true} text="New" textRenderDuration={6} /> <Suspense fallback={null}> <AsyncText ms={100} text="Sibling" fakeRenderDuration={1} /> </Suspense> </>, ); // TODO: This is here only to shift us into the next JND bucket. A // consequence of AsyncText relying on the same timer queue as React's // internal Suspense timer. We should decouple our AsyncText helpers // from timers. Scheduler.unstable_advanceTime(200); await waitForAll([ 'App', 'Suspending', 'Suspend! [Loaded]', 'Fallback', 'Suspend! [Sibling]', ]); expect(ReactNoop).toMatchRenderedOutput('Loading...'); expect(onRender).toHaveBeenCalledTimes(3); // Resolve the pending promise. await act(async () => { jest.advanceTimersByTime(100); assertLog([ 'Promise resolved [Loaded]', 'Promise resolved [Sibling]', ]); await waitForAll(['Suspending', 'Loaded', 'New', 'Sibling']); }); expect(onRender).toHaveBeenCalledTimes(4); // When the suspending data is resolved and our final UI is rendered, // both times should include the 6ms rendering Text, // the 2ms rendering Suspending, and the 1ms rendering AsyncText. expect(onRender.mock.calls[3][2]).toBe(9); expect(onRender.mock.calls[3][3]).toBe(9); }); }); }); });
32.302536
110
0.575182
owtf
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; import { buttonType, buttonsType, defaultPointerSize, defaultBrowserChromeSize, } from './constants'; /** * Native event object mocks for higher-level events. * * 1. Each event type defines the exact object that it accepts. This ensures * that no arbitrary properties can be assigned to events, and the properties * that don't exist on specific event types (e.g., 'pointerType') are not added * to the respective native event. * * 2. Properties that cannot be relied on due to inconsistent browser support (e.g., 'x' and 'y') are not * added to the native event. Others that shouldn't be arbitrarily customized (e.g., 'screenX') * are automatically inferred from associated values. * * 3. PointerEvent and TouchEvent fields are normalized (e.g., 'rotationAngle' -> 'twist') */ function emptyFunction() {} function createEvent(type, data = {}) { const event = document.createEvent('CustomEvent'); event.initCustomEvent(type, true, true); if (data != null) { Object.keys(data).forEach(key => { const value = data[key]; if (key === 'timeStamp' && !value) { return; } Object.defineProperty(event, key, {value}); }); } return event; } function createGetModifierState(keyArg, data) { if (keyArg === 'Alt') { return data.altKey || false; } if (keyArg === 'Control') { return data.ctrlKey || false; } if (keyArg === 'Meta') { return data.metaKey || false; } if (keyArg === 'Shift') { return data.shiftKey || false; } } function createPointerEvent( type, { altKey = false, button = buttonType.none, buttons = buttonsType.none, ctrlKey = false, detail = 1, height, metaKey = false, movementX = 0, movementY = 0, offsetX = 0, offsetY = 0, pageX, pageY, pointerId, pressure = 0, preventDefault = emptyFunction, pointerType = 'mouse', screenX, screenY, shiftKey = false, tangentialPressure = 0, tiltX = 0, tiltY = 0, timeStamp, twist = 0, width, x = 0, y = 0, } = {}, ) { const modifierState = {altKey, ctrlKey, metaKey, shiftKey}; const isMouse = pointerType === 'mouse'; return createEvent(type, { altKey, button, buttons, clientX: x, clientY: y, ctrlKey, detail, getModifierState(keyArg) { return createGetModifierState(keyArg, modifierState); }, height: isMouse ? 1 : height != null ? height : defaultPointerSize, metaKey, movementX, movementY, offsetX, offsetY, pageX: pageX || x, pageY: pageY || y, pointerId, pointerType, pressure, preventDefault, releasePointerCapture: emptyFunction, screenX: screenX === 0 ? screenX : x, screenY: screenY === 0 ? screenY : y + defaultBrowserChromeSize, setPointerCapture: emptyFunction, shiftKey, tangentialPressure, tiltX, tiltY, timeStamp, twist, width: isMouse ? 1 : width != null ? width : defaultPointerSize, }); } function createKeyboardEvent( type, { altKey = false, ctrlKey = false, isComposing = false, key = '', metaKey = false, preventDefault = emptyFunction, shiftKey = false, } = {}, ) { const modifierState = {altKey, ctrlKey, metaKey, shiftKey}; return createEvent(type, { altKey, ctrlKey, getModifierState(keyArg) { return createGetModifierState(keyArg, modifierState); }, isComposing, key, metaKey, preventDefault, shiftKey, }); } function createMouseEvent( type, { altKey = false, button = buttonType.none, buttons = buttonsType.none, ctrlKey = false, detail = 1, metaKey = false, movementX = 0, movementY = 0, offsetX = 0, offsetY = 0, pageX, pageY, preventDefault = emptyFunction, screenX, screenY, shiftKey = false, timeStamp, x = 0, y = 0, } = {}, ) { const modifierState = {altKey, ctrlKey, metaKey, shiftKey}; return createEvent(type, { altKey, button, buttons, clientX: x, clientY: y, ctrlKey, detail, getModifierState(keyArg) { return createGetModifierState(keyArg, modifierState); }, metaKey, movementX, movementY, offsetX, offsetY, pageX: pageX || x, pageY: pageY || y, preventDefault, screenX: screenX === 0 ? screenX : x, screenY: screenY === 0 ? screenY : y + defaultBrowserChromeSize, shiftKey, timeStamp, }); } function createTouchEvent(type, payload) { return createEvent(type, { ...payload, detail: 0, sourceCapabilities: { firesTouchEvents: true, }, }); } /** * Mock event objects */ export function blur({relatedTarget} = {}) { return new FocusEvent('blur', {relatedTarget}); } export function focusOut({relatedTarget} = {}) { return new FocusEvent('focusout', {relatedTarget, bubbles: true}); } export function click(payload) { return createMouseEvent('click', { button: buttonType.primary, ...payload, }); } export function contextmenu(payload) { return createMouseEvent('contextmenu', { ...payload, detail: 0, }); } export function dragstart(payload) { return createMouseEvent('dragstart', { ...payload, detail: 0, }); } export function focus({relatedTarget} = {}) { return new FocusEvent('focus', {relatedTarget}); } export function focusIn({relatedTarget} = {}) { return new FocusEvent('focusin', {relatedTarget, bubbles: true}); } export function scroll() { return createEvent('scroll'); } export function virtualclick(payload) { return createMouseEvent('click', { button: 0, ...payload, buttons: 0, detail: 0, height: 1, pageX: 0, pageY: 0, pressure: 0, screenX: 0, screenY: 0, width: 1, x: 0, y: 0, }); } /** * Key events */ export function keydown(payload) { return createKeyboardEvent('keydown', payload); } export function keyup(payload) { return createKeyboardEvent('keyup', payload); } /** * Pointer events */ export function gotpointercapture(payload) { return createPointerEvent('gotpointercapture', payload); } export function lostpointercapture(payload) { return createPointerEvent('lostpointercapture', payload); } export function pointercancel(payload) { return createPointerEvent('pointercancel', { ...payload, buttons: 0, detail: 0, height: 1, pageX: 0, pageY: 0, pressure: 0, screenX: 0, screenY: 0, width: 1, x: 0, y: 0, }); } export function pointerdown(payload) { const isTouch = payload != null && payload.pointerType === 'touch'; return createPointerEvent('pointerdown', { button: buttonType.primary, buttons: buttonsType.primary, pressure: isTouch ? 1 : 0.5, ...payload, }); } export function pointerenter(payload) { return createPointerEvent('pointerenter', payload); } export function pointerleave(payload) { return createPointerEvent('pointerleave', payload); } export function pointermove(payload) { return createPointerEvent('pointermove', { ...payload, button: buttonType.none, }); } export function pointerout(payload) { return createPointerEvent('pointerout', payload); } export function pointerover(payload) { return createPointerEvent('pointerover', payload); } export function pointerup(payload) { return createPointerEvent('pointerup', { button: buttonType.primary, ...payload, buttons: buttonsType.none, pressure: 0, }); } /** * Mouse events */ export function mousedown(payload) { // The value of 'button' and 'buttons' for 'mousedown' must not be none. const button = payload == null || payload.button === buttonType.none ? buttonType.primary : payload.button; const buttons = payload == null || payload.buttons === buttonsType.none ? buttonsType.primary : payload.buttons; return createMouseEvent('mousedown', { ...payload, button, buttons, }); } export function mouseenter(payload) { return createMouseEvent('mouseenter', payload); } export function mouseleave(payload) { return createMouseEvent('mouseleave', payload); } export function mousemove(payload) { return createMouseEvent('mousemove', payload); } export function mouseout(payload) { return createMouseEvent('mouseout', payload); } export function mouseover(payload) { return createMouseEvent('mouseover', payload); } export function mouseup(payload) { return createMouseEvent('mouseup', { button: buttonType.primary, ...payload, buttons: buttonsType.none, }); } /** * Touch events */ export function touchcancel(payload) { return createTouchEvent('touchcancel', payload); } export function touchend(payload) { return createTouchEvent('touchend', payload); } export function touchmove(payload) { return createTouchEvent('touchmove', payload); } export function touchstart(payload) { return createTouchEvent('touchstart', payload); }
19.896163
105
0.650713
null
'use strict'; const baseConfig = require('./config.base'); module.exports = Object.assign({}, baseConfig, { modulePathIgnorePatterns: [ ...baseConfig.modulePathIgnorePatterns, 'packages/react-devtools-extensions', 'packages/react-devtools-shared', ], setupFiles: [ ...baseConfig.setupFiles, require.resolve('./setupTests.www.js'), require.resolve('./setupHostConfigs.js'), ], });
23.411765
48
0.683575
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'; // Polyfills for test environment global.ReadableStream = require('web-streams-polyfill/ponyfill/es6').ReadableStream; global.TextEncoder = require('util').TextEncoder; let React; let ReactDOMFizzServer; let Suspense; describe('ReactDOMFizzServerBrowser', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOMFizzServer = require('react-dom/server.browser'); Suspense = React.Suspense; }); const theError = new Error('This is an error'); function Throw() { throw theError; } const theInfinitePromise = new Promise(() => {}); function InfiniteSuspend() { throw theInfinitePromise; } async function readResult(stream) { const reader = stream.getReader(); let result = ''; while (true) { const {done, value} = await reader.read(); if (done) { return result; } result += Buffer.from(value).toString('utf8'); } } it('should call renderToReadableStream', async () => { const stream = await ReactDOMFizzServer.renderToReadableStream( <div>hello world</div>, ); const result = await readResult(stream); expect(result).toMatchInlineSnapshot(`"<div>hello world</div>"`); }); it('should emit DOCTYPE at the root of the document', async () => { const stream = await ReactDOMFizzServer.renderToReadableStream( <html> <body>hello world</body> </html>, ); const result = await readResult(stream); if (gate(flags => flags.enableFloat)) { expect(result).toMatchInlineSnapshot( `"<!DOCTYPE html><html><head></head><body>hello world</body></html>"`, ); } else { expect(result).toMatchInlineSnapshot( `"<!DOCTYPE html><html><body>hello world</body></html>"`, ); } }); it('should emit bootstrap script src at the end', async () => { const stream = await ReactDOMFizzServer.renderToReadableStream( <div>hello world</div>, { bootstrapScriptContent: 'INIT();', bootstrapScripts: ['init.js'], bootstrapModules: ['init.mjs'], }, ); const result = await readResult(stream); expect(result).toMatchInlineSnapshot( `"<link rel="preload" as="script" fetchPriority="low" href="init.js"/><link rel="modulepreload" fetchPriority="low" href="init.mjs"/><div>hello world</div><script>INIT();</script><script src="init.js" async=""></script><script type="module" src="init.mjs" async=""></script>"`, ); }); it('emits all HTML as one unit if we wait until the end to start', async () => { let hasLoaded = false; let resolve; const promise = new Promise(r => (resolve = r)); function Wait() { if (!hasLoaded) { throw promise; } return 'Done'; } let isComplete = false; const stream = await ReactDOMFizzServer.renderToReadableStream( <div> <Suspense fallback="Loading"> <Wait /> </Suspense> </div>, ); stream.allReady.then(() => (isComplete = true)); await jest.runAllTimers(); expect(isComplete).toBe(false); // Resolve the loading. hasLoaded = true; await resolve(); await jest.runAllTimers(); expect(isComplete).toBe(true); const result = await readResult(stream); expect(result).toMatchInlineSnapshot( `"<div><!--$-->Done<!-- --><!--/$--></div>"`, ); }); it('should reject the promise when an error is thrown at the root', async () => { const reportedErrors = []; let caughtError = null; try { await ReactDOMFizzServer.renderToReadableStream( <div> <Throw /> </div>, { onError(x) { reportedErrors.push(x); }, }, ); } catch (error) { caughtError = error; } expect(caughtError).toBe(theError); expect(reportedErrors).toEqual([theError]); }); it('should reject the promise when an error is thrown inside a fallback', async () => { const reportedErrors = []; let caughtError = null; try { await ReactDOMFizzServer.renderToReadableStream( <div> <Suspense fallback={<Throw />}> <InfiniteSuspend /> </Suspense> </div>, { onError(x) { reportedErrors.push(x); }, }, ); } catch (error) { caughtError = error; } expect(caughtError).toBe(theError); expect(reportedErrors).toEqual([theError]); }); it('should not error the stream when an error is thrown inside suspense boundary', async () => { const reportedErrors = []; const stream = await ReactDOMFizzServer.renderToReadableStream( <div> <Suspense fallback={<div>Loading</div>}> <Throw /> </Suspense> </div>, { onError(x) { reportedErrors.push(x); }, }, ); const result = await readResult(stream); expect(result).toContain('Loading'); expect(reportedErrors).toEqual([theError]); }); it('should be able to complete by aborting even if the promise never resolves', async () => { const errors = []; const controller = new AbortController(); const stream = await ReactDOMFizzServer.renderToReadableStream( <div> <Suspense fallback={<div>Loading</div>}> <InfiniteSuspend /> </Suspense> </div>, { signal: controller.signal, onError(x) { errors.push(x.message); }, }, ); controller.abort(); const result = await readResult(stream); expect(result).toContain('Loading'); expect(errors).toEqual(['The operation was aborted.']); }); it('should reject if aborting before the shell is complete', async () => { const errors = []; const controller = new AbortController(); const promise = ReactDOMFizzServer.renderToReadableStream( <div> <InfiniteSuspend /> </div>, { signal: controller.signal, onError(x) { errors.push(x.message); }, }, ); await jest.runAllTimers(); const theReason = new Error('aborted for reasons'); controller.abort(theReason); let caughtError = null; try { await promise; } catch (error) { caughtError = error; } expect(caughtError).toBe(theReason); expect(errors).toEqual(['aborted for reasons']); }); it('should be able to abort before something suspends', async () => { const errors = []; const controller = new AbortController(); function App() { controller.abort(); return ( <Suspense fallback={<div>Loading</div>}> <InfiniteSuspend /> </Suspense> ); } const streamPromise = ReactDOMFizzServer.renderToReadableStream( <div> <App /> </div>, { signal: controller.signal, onError(x) { errors.push(x.message); }, }, ); let caughtError = null; try { await streamPromise; } catch (error) { caughtError = error; } expect(caughtError.message).toBe('The operation was aborted.'); expect(errors).toEqual(['The operation was aborted.']); }); it('should reject if passing an already aborted signal', async () => { const errors = []; const controller = new AbortController(); const theReason = new Error('aborted for reasons'); controller.abort(theReason); const promise = ReactDOMFizzServer.renderToReadableStream( <div> <Suspense fallback={<div>Loading</div>}> <InfiniteSuspend /> </Suspense> </div>, { signal: controller.signal, onError(x) { errors.push(x.message); }, }, ); // Technically we could still continue rendering the shell but currently the // semantics mean that we also abort any pending CPU work. let caughtError = null; try { await promise; } catch (error) { caughtError = error; } expect(caughtError).toBe(theReason); expect(errors).toEqual(['aborted for reasons']); }); it('should not continue rendering after the reader cancels', async () => { let hasLoaded = false; let resolve; let isComplete = false; let rendered = false; const promise = new Promise(r => (resolve = r)); function Wait() { if (!hasLoaded) { throw promise; } rendered = true; return 'Done'; } const errors = []; const stream = await ReactDOMFizzServer.renderToReadableStream( <div> <Suspense fallback={<div>Loading</div>}> <Wait /> </Suspense> </div>, { onError(x) { errors.push(x.message); }, }, ); stream.allReady.then(() => (isComplete = true)); expect(rendered).toBe(false); expect(isComplete).toBe(false); const reader = stream.getReader(); await reader.read(); await reader.cancel(); expect(errors).toEqual([ 'The render was aborted by the server without a reason.', ]); hasLoaded = true; resolve(); await jest.runAllTimers(); expect(rendered).toBe(false); expect(isComplete).toBe(true); expect(errors).toEqual([ 'The render was aborted by the server without a reason.', ]); }); it('should stream large contents that might overlow individual buffers', async () => { const str492 = `(492) This string is intentionally 492 bytes long because we want to make sure we process chunks that will overflow buffer boundaries. It will repeat to fill out the bytes required (inclusive of this prompt):: foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux q :: total count (492)`; const str2049 = `(2049) This string is intentionally 2049 bytes long because we want to make sure we process chunks that will overflow buffer boundaries. It will repeat to fill out the bytes required (inclusive of this prompt):: foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy thud foo bar qux quux corge grault garply waldo fred plugh xyzzy :: total count (2049)`; // this specific layout is somewhat contrived to exercise the landing on // an exact view boundary. it's not critical to test this edge case but // since we are setting up a test in general for larger chunks I contrived it // as such for now. I don't think it needs to be maintained if in the future // the view sizes change or become dynamic becasue of the use of byobRequest let stream; stream = await ReactDOMFizzServer.renderToReadableStream( <> <div> <span>{''}</span> </div> <div>{str492}</div> <div>{str492}</div> </>, ); let result; result = await readResult(stream); expect(result).toMatchInlineSnapshot( `"<div><span></span></div><div>${str492}</div><div>${str492}</div>"`, ); // this size 2049 was chosen to be a couple base 2 orders larger than the current view // size. if the size changes in the future hopefully this will still exercise // a chunk that is too large for the view size. stream = await ReactDOMFizzServer.renderToReadableStream( <> <div>{str2049}</div> </>, ); result = await readResult(stream); expect(result).toMatchInlineSnapshot(`"<div>${str2049}</div>"`); }); it('supports custom abort reasons with a string', async () => { const promise = new Promise(r => {}); function Wait() { throw promise; } function App() { return ( <div> <p> <Suspense fallback={'p'}> <Wait /> </Suspense> </p> <span> <Suspense fallback={'span'}> <Wait /> </Suspense> </span> </div> ); } const errors = []; const controller = new AbortController(); await ReactDOMFizzServer.renderToReadableStream(<App />, { signal: controller.signal, onError(x) { errors.push(x); return 'a digest'; }, }); controller.abort('foobar'); expect(errors).toEqual(['foobar', 'foobar']); }); it('supports custom abort reasons with an Error', async () => { const promise = new Promise(r => {}); function Wait() { throw promise; } function App() { return ( <div> <p> <Suspense fallback={'p'}> <Wait /> </Suspense> </p> <span> <Suspense fallback={'span'}> <Wait /> </Suspense> </span> </div> ); } const errors = []; const controller = new AbortController(); await ReactDOMFizzServer.renderToReadableStream(<App />, { signal: controller.signal, onError(x) { errors.push(x.message); return 'a digest'; }, }); controller.abort(new Error('uh oh')); expect(errors).toEqual(['uh oh', 'uh oh']); }); // https://github.com/facebook/react/pull/25534/files - fix transposed escape functions it('should encode title properly', async () => { const stream = await ReactDOMFizzServer.renderToReadableStream( <html> <head> <title>foo</title> </head> <body>bar</body> </html>, ); const result = await readResult(stream); expect(result).toEqual( '<!DOCTYPE html><html><head><title>foo</title></head><body>bar</body></html>', ); }); it('should support nonce attribute for bootstrap scripts', async () => { const nonce = 'R4nd0m'; const stream = await ReactDOMFizzServer.renderToReadableStream( <div>hello world</div>, { nonce, bootstrapScriptContent: 'INIT();', bootstrapScripts: ['init.js'], bootstrapModules: ['init.mjs'], }, ); const result = await readResult(stream); expect(result).toMatchInlineSnapshot( `"<link rel="preload" as="script" fetchPriority="low" nonce="R4nd0m" href="init.js"/><link rel="modulepreload" fetchPriority="low" nonce="R4nd0m" href="init.mjs"/><div>hello world</div><script nonce="${nonce}">INIT();</script><script src="init.js" nonce="${nonce}" async=""></script><script type="module" src="init.mjs" nonce="${nonce}" async=""></script>"`, ); }); // @gate enablePostpone it('errors if trying to postpone outside a Suspense boundary', async () => { function Postponed() { React.unstable_postpone('testing postpone'); return 'client only'; } function App() { return ( <div> <Postponed /> </div> ); } const errors = []; const postponed = []; let caughtError = null; try { await ReactDOMFizzServer.renderToReadableStream(<App />, { onError(error) { errors.push(error.message); }, onPostpone(reason) { postponed.push(reason); }, }); } catch (error) { caughtError = error; } // Postponing is not logged as an error but as a postponed reason. expect(errors).toEqual([]); expect(postponed).toEqual(['testing postpone']); // However, it does error the shell. expect(caughtError.message).toEqual('testing postpone'); }); });
30.722323
2,072
0.615231
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {HostDispatcher} from './shared/ReactDOMTypes'; type InternalsType = { usingClientEntryPoint: boolean, Events: [any, any, any, any, any, any], Dispatcher: { current: null | HostDispatcher, }, }; const Internals: InternalsType = ({ usingClientEntryPoint: false, Events: null, Dispatcher: { current: null, }, }: any); export default Internals;
19.206897
66
0.683761
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 */ function isCustomElement(tagName: string, props: Object): boolean { if (tagName.indexOf('-') === -1) { return false; } switch (tagName) { // These are reserved SVG and MathML elements. // We don't mind this list too much because we expect it to never grow. // The alternative is to track the namespace in a few places which is convoluted. // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts case 'annotation-xml': case 'color-profile': case 'font-face': case 'font-face-src': case 'font-face-uri': case 'font-face-format': case 'font-face-name': case 'missing-glyph': return false; default: return true; } } export default isCustomElement;
27
85
0.666667
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=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhNdWx0aXBsZUhvb2tzUGVyTGluZS5qcyJdLCJuYW1lcyI6WyJBIiwiQiIsIkNvbXBvbmVudCIsImEiLCJiIiwiYyIsImQiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7QUFTQTs7QUFUQTs7Ozs7Ozs7QUFXQSxNQUFNQSxDQUFDLGdCQUFHLDBCQUFjLENBQWQsQ0FBVjtBQUNBLE1BQU1DLENBQUMsZ0JBQUcsMEJBQWMsQ0FBZCxDQUFWOztBQUVPLFNBQVNDLFNBQVQsR0FBcUI7QUFDMUIsUUFBTUMsQ0FBQyxHQUFHLHVCQUFXSCxDQUFYLENBQVY7QUFDQSxRQUFNSSxDQUFDLEdBQUcsdUJBQVdILENBQVgsQ0FBVixDQUYwQixDQUkxQjs7QUFDQSxRQUFNSSxDQUFDLEdBQUcsdUJBQVdMLENBQVgsQ0FBVjtBQUFBLFFBQXlCTSxDQUFDLEdBQUcsdUJBQVdMLENBQVgsQ0FBN0IsQ0FMMEIsQ0FLa0I7O0FBRTVDLFNBQU9FLENBQUMsR0FBR0MsQ0FBSixHQUFRQyxDQUFSLEdBQVlDLENBQW5CO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IHtjcmVhdGVDb250ZXh0LCB1c2VDb250ZXh0fSBmcm9tICdyZWFjdCc7XG5cbmNvbnN0IEEgPSBjcmVhdGVDb250ZXh0KDEpO1xuY29uc3QgQiA9IGNyZWF0ZUNvbnRleHQoMik7XG5cbmV4cG9ydCBmdW5jdGlvbiBDb21wb25lbnQoKSB7XG4gIGNvbnN0IGEgPSB1c2VDb250ZXh0KEEpO1xuICBjb25zdCBiID0gdXNlQ29udGV4dChCKTtcblxuICAvLyBwcmV0dGllci1pZ25vcmVcbiAgY29uc3QgYyA9IHVzZUNvbnRleHQoQSksIGQgPSB1c2VDb250ZXh0KEIpOyAvLyBlc2xpbnQtZGlzYWJsZS1saW5lIG9uZS12YXJcblxuICByZXR1cm4gYSArIGIgKyBjICsgZDtcbn1cbiJdfX1dfQ==
74.3
1,552
0.878211
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 type {DevToolsHook} from 'react-devtools-shared/src/backend/types'; import Agent from 'react-devtools-shared/src/backend/agent'; import Bridge from 'react-devtools-shared/src/bridge'; import {initBackend} from 'react-devtools-shared/src/backend'; import setupNativeStyleEditor from 'react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor'; import {COMPACT_VERSION_NAME} from './utils'; setup(window.__REACT_DEVTOOLS_GLOBAL_HOOK__); function setup(hook: ?DevToolsHook) { if (hook == null) { return; } hook.backends.set(COMPACT_VERSION_NAME, { Agent, Bridge, initBackend, setupNativeStyleEditor, }); hook.emit('devtools-backend-installed', COMPACT_VERSION_NAME); }
25.6
112
0.733333
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 countState = (0, _react.useState)(0); const count = countState[0]; const setCount = countState[1]; const darkMode = useIsDarkMode(); const [isDarkMode] = darkMode; (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: 28, columnNumber: 7 } }, "Dark mode? ", isDarkMode), /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 29, columnNumber: 7 } }, "Count: ", count), /*#__PURE__*/_react.default.createElement("button", { onClick: handleClick, __source: { fileName: _jsxFileName, lineNumber: 30, columnNumber: 7 } }, "Update count")); } function useIsDarkMode() { const darkModeState = (0, _react.useState)(false); const [isDarkMode] = darkModeState; (0, _react.useEffect)(function useEffectCreate() {// Here is where we may listen to a "theme" event... }, []); return [isDarkMode, () => {}]; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFVzaW5nSG9va3NJbmRpcmVjdGx5LmpzIl0sIm5hbWVzIjpbIkNvbXBvbmVudCIsImNvdW50U3RhdGUiLCJjb3VudCIsInNldENvdW50IiwiZGFya01vZGUiLCJ1c2VJc0RhcmtNb2RlIiwiaXNEYXJrTW9kZSIsImhhbmRsZUNsaWNrIiwiZGFya01vZGVTdGF0ZSIsInVzZUVmZmVjdENyZWF0ZSJdLCJtYXBwaW5ncyI6Ijs7Ozs7OztBQVNBOzs7Ozs7OztBQUVPLFNBQVNBLFNBQVQsR0FBcUI7QUFDMUIsUUFBTUMsVUFBVSxHQUFHLHFCQUFTLENBQVQsQ0FBbkI7QUFDQSxRQUFNQyxLQUFLLEdBQUdELFVBQVUsQ0FBQyxDQUFELENBQXhCO0FBQ0EsUUFBTUUsUUFBUSxHQUFHRixVQUFVLENBQUMsQ0FBRCxDQUEzQjtBQUVBLFFBQU1HLFFBQVEsR0FBR0MsYUFBYSxFQUE5QjtBQUNBLFFBQU0sQ0FBQ0MsVUFBRCxJQUFlRixRQUFyQjtBQUVBLHdCQUFVLE1BQU0sQ0FDZDtBQUNELEdBRkQsRUFFRyxFQUZIOztBQUlBLFFBQU1HLFdBQVcsR0FBRyxNQUFNSixRQUFRLENBQUNELEtBQUssR0FBRyxDQUFULENBQWxDOztBQUVBLHNCQUNFLHlFQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLG9CQUFpQkksVUFBakIsQ0FERixlQUVFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGdCQUFhSixLQUFiLENBRkYsZUFHRTtBQUFRLElBQUEsT0FBTyxFQUFFSyxXQUFqQjtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxvQkFIRixDQURGO0FBT0Q7O0FBRUQsU0FBU0YsYUFBVCxHQUF5QjtBQUN2QixRQUFNRyxhQUFhLEdBQUcscUJBQVMsS0FBVCxDQUF0QjtBQUNBLFFBQU0sQ0FBQ0YsVUFBRCxJQUFlRSxhQUFyQjtBQUVBLHdCQUFVLFNBQVNDLGVBQVQsR0FBMkIsQ0FDbkM7QUFDRCxHQUZELEVBRUcsRUFGSDtBQUlBLFNBQU8sQ0FBQ0gsVUFBRCxFQUFhLE1BQU0sQ0FBRSxDQUFyQixDQUFQO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IFJlYWN0LCB7dXNlRWZmZWN0LCB1c2VTdGF0ZX0gZnJvbSAncmVhY3QnO1xuXG5leHBvcnQgZnVuY3Rpb24gQ29tcG9uZW50KCkge1xuICBjb25zdCBjb3VudFN0YXRlID0gdXNlU3RhdGUoMCk7XG4gIGNvbnN0IGNvdW50ID0gY291bnRTdGF0ZVswXTtcbiAgY29uc3Qgc2V0Q291bnQgPSBjb3VudFN0YXRlWzFdO1xuXG4gIGNvbnN0IGRhcmtNb2RlID0gdXNlSXNEYXJrTW9kZSgpO1xuICBjb25zdCBbaXNEYXJrTW9kZV0gPSBkYXJrTW9kZTtcblxuICB1c2VFZmZlY3QoKCkgPT4ge1xuICAgIC8vIC4uLlxuICB9LCBbXSk7XG5cbiAgY29uc3QgaGFuZGxlQ2xpY2sgPSAoKSA9PiBzZXRDb3VudChjb3VudCArIDEpO1xuXG4gIHJldHVybiAoXG4gICAgPD5cbiAgICAgIDxkaXY+RGFyayBtb2RlPyB7aXNEYXJrTW9kZX08L2Rpdj5cbiAgICAgIDxkaXY+Q291bnQ6IHtjb3VudH08L2Rpdj5cbiAgICAgIDxidXR0b24gb25DbGljaz17aGFuZGxlQ2xpY2t9PlVwZGF0ZSBjb3VudDwvYnV0dG9uPlxuICAgIDwvPlxuICApO1xufVxuXG5mdW5jdGlvbiB1c2VJc0RhcmtNb2RlKCkge1xuICBjb25zdCBkYXJrTW9kZVN0YXRlID0gdXNlU3RhdGUoZmFsc2UpO1xuICBjb25zdCBbaXNEYXJrTW9kZV0gPSBkYXJrTW9kZVN0YXRlO1xuXG4gIHVzZUVmZmVjdChmdW5jdGlvbiB1c2VFZmZlY3RDcmVhdGUoKSB7XG4gICAgLy8gSGVyZSBpcyB3aGVyZSB3ZSBtYXkgbGlzdGVuIHRvIGEgXCJ0aGVtZVwiIGV2ZW50Li4uXG4gIH0sIFtdKTtcblxuICByZXR1cm4gW2lzRGFya01vZGUsICgpID0+IHt9XTtcbn1cbiJdLCJ4X3JlYWN0X3NvdXJjZXMiOltbeyJuYW1lcyI6WyI8bm8taG9vaz4iLCJjb3VudCIsImRhcmtNb2RlIiwiaXNEYXJrTW9kZSJdLCJtYXBwaW5ncyI6IkNBQUQ7YXFCQ0EsQVdEQTtpQmJFQSxBZUZBO29DVkdBLEFlSEEifV1dfQ==
91.928571
2,872
0.83817
owtf
export const SAMPLE_CODE = ` class Fixture extends React.Component { state = { value: 'asdf' } onChange(event) { this.setState({ value: event.target.value }); } render() { const { value } = this.state; return ( <form> <input value={value} onChange={this.onChange.bind(this)} /> <p>Value: {value}</p> </form> ); } } `.trim();
15.913043
67
0.546392
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 */ import type {PublicInstance} from './ReactNativePrivateInterface'; export default function createPublicTextInstance( internalInstanceHandle: mixed, ): PublicInstance { return { __internalInstanceHandle: internalInstanceHandle, }; }
22.947368
66
0.742291
Python-Penetration-Testing-Cookbook
const {transformSync} = require('@babel/core'); const {btoa} = require('base64'); const { lstatSync, mkdirSync, readdirSync, readFileSync, writeFileSync, } = require('fs'); const {emptyDirSync} = require('fs-extra'); const {resolve} = require('path'); const rollup = require('rollup'); const babel = require('@rollup/plugin-babel').babel; const commonjs = require('@rollup/plugin-commonjs'); const jsx = require('acorn-jsx'); const rollupResolve = require('@rollup/plugin-node-resolve').nodeResolve; const {encode, decode} = require('sourcemap-codec'); const {generateEncodedHookMap} = require('../generateHookMap'); const {parse} = require('@babel/parser'); const sourceDir = resolve(__dirname, '__source__'); const buildRoot = resolve(sourceDir, '__compiled__'); const externalDir = resolve(buildRoot, 'external'); const inlineDir = resolve(buildRoot, 'inline'); const bundleDir = resolve(buildRoot, 'bundle'); const noColumnsDir = resolve(buildRoot, 'no-columns'); const inlineIndexMapDir = resolve(inlineDir, 'index-map'); const externalIndexMapDir = resolve(externalDir, 'index-map'); const inlineFbSourcesExtendedDir = resolve(inlineDir, 'fb-sources-extended'); const externalFbSourcesExtendedDir = resolve( externalDir, 'fb-sources-extended', ); const inlineFbSourcesIndexMapExtendedDir = resolve( inlineFbSourcesExtendedDir, 'index-map', ); const externalFbSourcesIndexMapExtendedDir = resolve( externalFbSourcesExtendedDir, 'index-map', ); const inlineReactSourcesExtendedDir = resolve( inlineDir, 'react-sources-extended', ); const externalReactSourcesExtendedDir = resolve( externalDir, 'react-sources-extended', ); const inlineReactSourcesIndexMapExtendedDir = resolve( inlineReactSourcesExtendedDir, 'index-map', ); const externalReactSourcesIndexMapExtendedDir = resolve( externalReactSourcesExtendedDir, 'index-map', ); // Remove previous builds emptyDirSync(buildRoot); mkdirSync(externalDir); mkdirSync(inlineDir); mkdirSync(bundleDir); mkdirSync(noColumnsDir); mkdirSync(inlineIndexMapDir); mkdirSync(externalIndexMapDir); mkdirSync(inlineFbSourcesExtendedDir); mkdirSync(externalFbSourcesExtendedDir); mkdirSync(inlineReactSourcesExtendedDir); mkdirSync(externalReactSourcesExtendedDir); mkdirSync(inlineFbSourcesIndexMapExtendedDir); mkdirSync(externalFbSourcesIndexMapExtendedDir); mkdirSync(inlineReactSourcesIndexMapExtendedDir); mkdirSync(externalReactSourcesIndexMapExtendedDir); function compile(fileName) { const code = readFileSync(resolve(sourceDir, fileName), 'utf8'); const transformed = transformSync(code, { plugins: ['@babel/plugin-transform-modules-commonjs'], presets: [ // 'minify', [ '@babel/react', // { // runtime: 'automatic', // development: false, // }, ], ], sourceMap: true, }); const sourceMap = transformed.map; sourceMap.sources = [fileName]; // Generate compiled output with external source maps writeFileSync( resolve(externalDir, fileName), transformed.code + `\n//# sourceMappingURL=${fileName}.map?foo=bar&param=some_value`, 'utf8', ); writeFileSync( resolve(externalDir, `${fileName}.map`), JSON.stringify(sourceMap), 'utf8', ); // Generate compiled output with inline base64 source maps writeFileSync( resolve(inlineDir, fileName), transformed.code + '\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,' + btoa(JSON.stringify(sourceMap)), 'utf8', ); // Strip column numbers from source map to mimic Webpack 'cheap-module-source-map' // The mappings field represents a list of integer arrays. // Each array defines a pair of corresponding file locations, one in the generated code and one in the original. // Each array has also been encoded first as VLQs (variable-length quantities) // and then as base64 because this makes them more compact overall. // https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/view# const decodedMappings = decode(sourceMap.mappings).map(entries => entries.map(entry => { if (entry.length === 0) { return entry; } // Each non-empty segment has the following components: // generated code column, source index, source code line, source code column, and (optional) name index return [...entry.slice(0, 3), 0, ...entry.slice(4)]; }), ); const encodedMappings = encode(decodedMappings); // Generate compiled output with inline base64 source maps without column numbers writeFileSync( resolve(noColumnsDir, fileName), transformed.code + '\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,' + btoa( JSON.stringify({ ...sourceMap, mappings: encodedMappings, }), ), 'utf8', ); // Artificially construct a source map that uses the index map format // (https://sourcemaps.info/spec.html#h.535es3xeprgt) const indexMap = { version: sourceMap.version, file: sourceMap.file, sections: [ { offset: { line: 0, column: 0, }, map: {...sourceMap}, }, ], }; // Generate compiled output using external source maps using index map format writeFileSync( resolve(externalIndexMapDir, fileName), transformed.code + `\n//# sourceMappingURL=${fileName}.map?foo=bar&param=some_value`, 'utf8', ); writeFileSync( resolve(externalIndexMapDir, `${fileName}.map`), JSON.stringify(indexMap), 'utf8', ); // Generate compiled output with inline base64 source maps using index map format writeFileSync( resolve(inlineIndexMapDir, fileName), transformed.code + '\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,' + btoa(JSON.stringify(indexMap)), 'utf8', ); // Generate compiled output with an extended sourcemap that includes a map of hook names. const parsed = parse(code, { sourceType: 'module', plugins: ['jsx', 'flow'], }); const encodedHookMap = generateEncodedHookMap(parsed); const fbSourcesExtendedSourceMap = { ...sourceMap, // When using the x_facebook_sources extension field, the first item // for a given source is reserved for the Function Map, and the // React sources metadata (which includes the Hook Map) is added as // the second item. x_facebook_sources: [[null, [encodedHookMap]]], }; const fbSourcesExtendedIndexMap = { version: fbSourcesExtendedSourceMap.version, file: fbSourcesExtendedSourceMap.file, sections: [ { offset: { line: 0, column: 0, }, map: {...fbSourcesExtendedSourceMap}, }, ], }; const reactSourcesExtendedSourceMap = { ...sourceMap, // When using the x_react_sources extension field, the first item // for a given source is reserved for the Hook Map. x_react_sources: [[encodedHookMap]], }; const reactSourcesExtendedIndexMap = { version: reactSourcesExtendedSourceMap.version, file: reactSourcesExtendedSourceMap.file, sections: [ { offset: { line: 0, column: 0, }, map: {...reactSourcesExtendedSourceMap}, }, ], }; // Using the x_facebook_sources field writeFileSync( resolve(inlineFbSourcesExtendedDir, fileName), transformed.code + '\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,' + btoa(JSON.stringify(fbSourcesExtendedSourceMap)), 'utf8', ); writeFileSync( resolve(externalFbSourcesExtendedDir, fileName), transformed.code + `\n//# sourceMappingURL=${fileName}.map?foo=bar&param=some_value`, 'utf8', ); writeFileSync( resolve(externalFbSourcesExtendedDir, `${fileName}.map`), JSON.stringify(fbSourcesExtendedSourceMap), 'utf8', ); // Using the x_facebook_sources field on an index map format writeFileSync( resolve(inlineFbSourcesIndexMapExtendedDir, fileName), transformed.code + '\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,' + btoa(JSON.stringify(fbSourcesExtendedIndexMap)), 'utf8', ); writeFileSync( resolve(externalFbSourcesIndexMapExtendedDir, fileName), transformed.code + `\n//# sourceMappingURL=${fileName}.map?foo=bar&param=some_value`, 'utf8', ); writeFileSync( resolve(externalFbSourcesIndexMapExtendedDir, `${fileName}.map`), JSON.stringify(fbSourcesExtendedIndexMap), 'utf8', ); // Using the x_react_sources field writeFileSync( resolve(inlineReactSourcesExtendedDir, fileName), transformed.code + '\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,' + btoa(JSON.stringify(reactSourcesExtendedSourceMap)), 'utf8', ); writeFileSync( resolve(externalReactSourcesExtendedDir, fileName), transformed.code + `\n//# sourceMappingURL=${fileName}.map?foo=bar&param=some_value`, 'utf8', ); writeFileSync( resolve(externalReactSourcesExtendedDir, `${fileName}.map`), JSON.stringify(reactSourcesExtendedSourceMap), 'utf8', ); // Using the x_react_sources field on an index map format writeFileSync( resolve(inlineReactSourcesIndexMapExtendedDir, fileName), transformed.code + '\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,' + btoa(JSON.stringify(reactSourcesExtendedIndexMap)), 'utf8', ); writeFileSync( resolve(externalReactSourcesIndexMapExtendedDir, fileName), transformed.code + `\n//# sourceMappingURL=${fileName}.map?foo=bar&param=some_value`, 'utf8', ); writeFileSync( resolve(externalReactSourcesIndexMapExtendedDir, `${fileName}.map`), JSON.stringify(reactSourcesExtendedIndexMap), 'utf8', ); } async function bundle() { const entryFileName = resolve(sourceDir, 'index.js'); // Bundle all modules with rollup const result = await rollup.rollup({ input: entryFileName, acornInjectPlugins: [jsx()], plugins: [ rollupResolve(), commonjs(), babel({ babelHelpers: 'bundled', presets: ['@babel/preset-react'], sourceMap: true, }), ], external: ['react'], }); await result.write({ file: resolve(bundleDir, 'index.js'), format: 'cjs', sourcemap: true, }); } // Compile all files in the current directory const entries = readdirSync(sourceDir); entries.forEach(entry => { const stat = lstatSync(resolve(sourceDir, entry)); if (!stat.isDirectory() && entry.endsWith('.js')) { compile(entry); } }); bundle().catch(e => { console.error(e); process.exit(1); });
29.257062
114
0.687488
owtf
/** * Provides a standard way to access a DOM node across all versions of * React. */ import {reactPaths} from './react-loader'; const React = window.React; const ReactDOM = window.ReactDOM; export function findDOMNode(target) { const {needsReactDOM} = reactPaths(); if (needsReactDOM) { return ReactDOM.findDOMNode(target); } else { // eslint-disable-next-line return React.findDOMNode(target); } }
19.380952
70
0.69555
Python-Penetration-Testing-for-Developers
let React; let ReactNoop; let Scheduler; let act; let assertLog; let useTransition; let useState; let useOptimistic; let textCache; describe('ReactAsyncActions', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); act = require('internal-test-utils').act; assertLog = require('internal-test-utils').assertLog; useTransition = React.useTransition; useState = React.useState; useOptimistic = React.useOptimistic; textCache = new Map(); }); function resolveText(text) { const record = textCache.get(text); if (record === undefined) { const newRecord = { status: 'resolved', value: text, }; textCache.set(text, newRecord); } else if (record.status === 'pending') { const thenable = record.value; record.status = 'resolved'; record.value = text; thenable.pings.forEach(t => t()); } } function readText(text) { const record = textCache.get(text); if (record !== undefined) { switch (record.status) { case 'pending': Scheduler.log(`Suspend! [${text}]`); throw record.value; case 'rejected': throw record.value; case 'resolved': return record.value; } } else { Scheduler.log(`Suspend! [${text}]`); const thenable = { pings: [], then(resolve) { if (newRecord.status === 'pending') { thenable.pings.push(resolve); } else { Promise.resolve().then(() => resolve(newRecord.value)); } }, }; const newRecord = { status: 'pending', value: thenable, }; textCache.set(text, newRecord); throw thenable; } } function 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; } // @gate enableAsyncActions test('isPending remains true until async action finishes', async () => { let startTransition; function App() { const [isPending, _start] = useTransition(); startTransition = _start; return <Text text={'Pending: ' + isPending} />; } const root = ReactNoop.createRoot(); await act(() => { root.render(<App />); }); assertLog(['Pending: false']); expect(root).toMatchRenderedOutput('Pending: false'); // At the start of an async action, isPending is set to true. await act(() => { startTransition(async () => { Scheduler.log('Async action started'); await getText('Wait'); Scheduler.log('Async action ended'); }); }); assertLog(['Async action started', 'Pending: true']); expect(root).toMatchRenderedOutput('Pending: true'); // Once the action finishes, isPending is set back to false. await act(() => resolveText('Wait')); assertLog(['Async action ended', 'Pending: false']); expect(root).toMatchRenderedOutput('Pending: false'); }); // @gate enableAsyncActions test('multiple updates in an async action scope are entangled together', async () => { let startTransition; function App({text}) { const [isPending, _start] = useTransition(); startTransition = _start; return ( <> <span> <Text text={'Pending: ' + isPending} /> </span> <span> <Text text={text} /> </span> </> ); } const root = ReactNoop.createRoot(); await act(() => { root.render(<App text="A" />); }); assertLog(['Pending: false', 'A']); expect(root).toMatchRenderedOutput( <> <span>Pending: false</span> <span>A</span> </>, ); await act(() => { startTransition(async () => { Scheduler.log('Async action started'); await getText('Yield before updating'); Scheduler.log('Async action ended'); startTransition(() => root.render(<App text="B" />)); }); }); assertLog(['Async action started', 'Pending: true', 'A']); expect(root).toMatchRenderedOutput( <> <span>Pending: true</span> <span>A</span> </>, ); await act(() => resolveText('Yield before updating')); assertLog(['Async action ended', 'Pending: false', 'B']); expect(root).toMatchRenderedOutput( <> <span>Pending: false</span> <span>B</span> </>, ); }); // @gate enableAsyncActions test('multiple async action updates in the same scope are entangled together', async () => { let setStepA; function A() { const [step, setStep] = useState(0); setStepA = setStep; return <AsyncText text={'A' + step} />; } let setStepB; function B() { const [step, setStep] = useState(0); setStepB = setStep; return <AsyncText text={'B' + step} />; } let setStepC; function C() { const [step, setStep] = useState(0); setStepC = setStep; return <AsyncText text={'C' + step} />; } let startTransition; function App() { const [isPending, _start] = useTransition(); startTransition = _start; return ( <> <span> <Text text={'Pending: ' + isPending} /> </span> <span> <A />, <B />, <C /> </span> </> ); } const root = ReactNoop.createRoot(); resolveText('A0'); resolveText('B0'); resolveText('C0'); await act(() => { root.render(<App text="A" />); }); assertLog(['Pending: false', 'A0', 'B0', 'C0']); expect(root).toMatchRenderedOutput( <> <span>Pending: false</span> <span>A0, B0, C0</span> </>, ); await act(() => { startTransition(async () => { Scheduler.log('Async action started'); setStepA(1); await getText('Wait before updating B'); startTransition(() => setStepB(1)); await getText('Wait before updating C'); startTransition(() => setStepC(1)); Scheduler.log('Async action ended'); }); }); assertLog(['Async action started', 'Pending: true', 'A0', 'B0', 'C0']); expect(root).toMatchRenderedOutput( <> <span>Pending: true</span> <span>A0, B0, C0</span> </>, ); // This will schedule an update on B, but nothing will render yet because // the async action scope hasn't finished. await act(() => resolveText('Wait before updating B')); assertLog([]); expect(root).toMatchRenderedOutput( <> <span>Pending: true</span> <span>A0, B0, C0</span> </>, ); // This will schedule an update on C, and also the async action scope // will end. This will allow React to attempt to render the updates. await act(() => resolveText('Wait before updating C')); assertLog(['Async action ended', 'Pending: false', 'Suspend! [A1]']); expect(root).toMatchRenderedOutput( <> <span>Pending: true</span> <span>A0, B0, C0</span> </>, ); // Progressively load the all the data. Because they are all entangled // together, only when the all of A, B, and C updates are unblocked is the // render allowed to proceed. await act(() => resolveText('A1')); assertLog(['Pending: false', 'A1', 'Suspend! [B1]']); expect(root).toMatchRenderedOutput( <> <span>Pending: true</span> <span>A0, B0, C0</span> </>, ); await act(() => resolveText('B1')); assertLog(['Pending: false', 'A1', 'B1', 'Suspend! [C1]']); expect(root).toMatchRenderedOutput( <> <span>Pending: true</span> <span>A0, B0, C0</span> </>, ); // Finally, all the data has loaded and the transition is complete. await act(() => resolveText('C1')); assertLog(['Pending: false', 'A1', 'B1', 'C1']); expect(root).toMatchRenderedOutput( <> <span>Pending: false</span> <span>A1, B1, C1</span> </>, ); }); // @gate enableAsyncActions test('urgent updates are not blocked during an async action', async () => { let setStepA; function A() { const [step, setStep] = useState(0); setStepA = setStep; return <Text text={'A' + step} />; } let setStepB; function B() { const [step, setStep] = useState(0); setStepB = setStep; return <Text text={'B' + step} />; } let startTransition; function App() { const [isPending, _start] = useTransition(); startTransition = _start; return ( <> <span> <Text text={'Pending: ' + isPending} /> </span> <span> <A />, <B /> </span> </> ); } const root = ReactNoop.createRoot(); await act(() => { root.render(<App text="A" />); }); assertLog(['Pending: false', 'A0', 'B0']); expect(root).toMatchRenderedOutput( <> <span>Pending: false</span> <span>A0, B0</span> </>, ); await act(() => { startTransition(async () => { Scheduler.log('Async action started'); startTransition(() => setStepA(1)); await getText('Wait'); Scheduler.log('Async action ended'); }); }); assertLog(['Async action started', 'Pending: true', 'A0', 'B0']); expect(root).toMatchRenderedOutput( <> <span>Pending: true</span> <span>A0, B0</span> </>, ); // Update B at urgent priority. This should be allowed to finish. await act(() => setStepB(1)); assertLog(['B1']); expect(root).toMatchRenderedOutput( <> <span>Pending: true</span> <span>A0, B1</span> </>, ); // Finish the async action. await act(() => resolveText('Wait')); assertLog(['Async action ended', 'Pending: false', 'A1', 'B1']); expect(root).toMatchRenderedOutput( <> <span>Pending: false</span> <span>A1, B1</span> </>, ); }); // @gate enableAsyncActions test("if a sync action throws, it's rethrown from the `useTransition`", async () => { class ErrorBoundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { if (this.state.error) { return <Text text={this.state.error.message} />; } return this.props.children; } } let startTransition; function App() { const [isPending, _start] = useTransition(); startTransition = _start; return <Text text={'Pending: ' + isPending} />; } const root = ReactNoop.createRoot(); await act(() => { root.render( <ErrorBoundary> <App /> </ErrorBoundary>, ); }); assertLog(['Pending: false']); expect(root).toMatchRenderedOutput('Pending: false'); await act(() => { startTransition(() => { throw new Error('Oops!'); }); }); assertLog(['Pending: true', 'Oops!', 'Oops!']); expect(root).toMatchRenderedOutput('Oops!'); }); // @gate enableAsyncActions test("if an async action throws, it's rethrown from the `useTransition`", async () => { class ErrorBoundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { if (this.state.error) { return <Text text={this.state.error.message} />; } return this.props.children; } } let startTransition; function App() { const [isPending, _start] = useTransition(); startTransition = _start; return <Text text={'Pending: ' + isPending} />; } const root = ReactNoop.createRoot(); await act(() => { root.render( <ErrorBoundary> <App /> </ErrorBoundary>, ); }); assertLog(['Pending: false']); expect(root).toMatchRenderedOutput('Pending: false'); await act(() => { startTransition(async () => { Scheduler.log('Async action started'); await getText('Wait'); throw new Error('Oops!'); }); }); assertLog(['Async action started', 'Pending: true']); expect(root).toMatchRenderedOutput('Pending: true'); await act(() => resolveText('Wait')); assertLog(['Oops!', 'Oops!']); expect(root).toMatchRenderedOutput('Oops!'); }); // @gate !enableAsyncActions test('when enableAsyncActions is disabled, and a sync action throws, `isPending` is turned off', async () => { let startTransition; function App() { const [isPending, _start] = useTransition(); startTransition = _start; return <Text text={'Pending: ' + isPending} />; } const root = ReactNoop.createRoot(); await act(() => { root.render(<App />); }); assertLog(['Pending: false']); expect(root).toMatchRenderedOutput('Pending: false'); await act(() => { expect(() => { startTransition(() => { throw new Error('Oops!'); }); }).toThrow('Oops!'); }); assertLog(['Pending: true', 'Pending: false']); expect(root).toMatchRenderedOutput('Pending: false'); }); // @gate enableAsyncActions test('if there are multiple entangled actions, and one of them errors, it only affects that action', async () => { class ErrorBoundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { if (this.state.error) { return <Text text={this.state.error.message} />; } return this.props.children; } } let startTransitionA; function ActionA() { const [isPendingA, start] = useTransition(); startTransitionA = start; return <Text text={'Pending A: ' + isPendingA} />; } let startTransitionB; function ActionB() { const [isPending, start] = useTransition(); startTransitionB = start; return <Text text={'Pending B: ' + isPending} />; } let startTransitionC; function ActionC() { const [isPending, start] = useTransition(); startTransitionC = start; return <Text text={'Pending C: ' + isPending} />; } const root = ReactNoop.createRoot(); await act(() => { root.render( <> <div> <ErrorBoundary> <ActionA /> </ErrorBoundary> </div> <div> <ErrorBoundary> <ActionB /> </ErrorBoundary> </div> <div> <ErrorBoundary> <ActionC /> </ErrorBoundary> </div> </>, ); }); assertLog(['Pending A: false', 'Pending B: false', 'Pending C: false']); expect(root).toMatchRenderedOutput( <> <div>Pending A: false</div> <div>Pending B: false</div> <div>Pending C: false</div> </>, ); // Start a bunch of entangled transitions. A and C throw errors, but B // doesn't. A and should surface their respective errors, but B should // finish successfully. await act(() => { startTransitionC(async () => { startTransitionB(async () => { startTransitionA(async () => { await getText('Wait for A'); throw new Error('Oops A!'); }); await getText('Wait for B'); }); await getText('Wait for C'); throw new Error('Oops C!'); }); }); assertLog(['Pending A: true', 'Pending B: true', 'Pending C: true']); // Finish action A. We can't commit the result yet because it's entangled // with B and C. await act(() => resolveText('Wait for A')); assertLog([]); // Finish action B. Same as above. await act(() => resolveText('Wait for B')); assertLog([]); // Now finish action C. This is the last action in the entangled set, so // rendering can proceed. await act(() => resolveText('Wait for C')); assertLog([ // A and C result in (separate) errors, but B does not. 'Oops A!', 'Pending B: false', 'Oops C!', // Because there was an error, React will try rendering one more time. 'Oops A!', 'Pending B: false', 'Oops C!', ]); expect(root).toMatchRenderedOutput( <> <div>Oops A!</div> <div>Pending B: false</div> <div>Oops C!</div> </>, ); }); // @gate enableAsyncActions test('useOptimistic can be used to implement a pending state', async () => { const startTransition = React.startTransition; let setIsPending; function App({text}) { const [isPending, _setIsPending] = useOptimistic(false); setIsPending = _setIsPending; return ( <> <Text text={'Pending: ' + isPending} /> <AsyncText text={text} /> </> ); } // Initial render const root = ReactNoop.createRoot(); resolveText('A'); await act(() => root.render(<App text="A" />)); assertLog(['Pending: false', 'A']); expect(root).toMatchRenderedOutput('Pending: falseA'); // Start a transition await act(() => startTransition(() => { setIsPending(true); root.render(<App text="B" />); }), ); assertLog([ // Render the pending state immediately 'Pending: true', 'A', // Then attempt to render the transition. The pending state will be // automatically reverted. 'Pending: false', 'Suspend! [B]', ]); // Resolve the transition await act(() => resolveText('B')); assertLog([ // Render the pending state immediately 'Pending: false', 'B', ]); }); // @gate enableAsyncActions test('useOptimistic rebases pending updates on top of passthrough value', async () => { let serverCart = ['A']; async function submitNewItem(item) { await getText('Adding item ' + item); serverCart = [...serverCart, item]; React.startTransition(() => { root.render(<App cart={serverCart} />); }); } let addItemToCart; function App({cart}) { const [isPending, startTransition] = useTransition(); const savedCartSize = cart.length; const [optimisticCartSize, setOptimisticCartSize] = useOptimistic(savedCartSize); addItemToCart = item => { startTransition(async () => { setOptimisticCartSize(n => n + 1); await submitNewItem(item); }); }; return ( <> <div> <Text text={'Pending: ' + isPending} /> </div> <div> <Text text={'Items in cart: ' + optimisticCartSize} /> </div> <ul> {cart.map(item => ( <li key={item}> <Text text={'Item ' + item} /> </li> ))} </ul> </> ); } // Initial render const root = ReactNoop.createRoot(); await act(() => root.render(<App cart={serverCart} />)); assertLog(['Pending: false', 'Items in cart: 1', 'Item A']); expect(root).toMatchRenderedOutput( <> <div>Pending: false</div> <div>Items in cart: 1</div> <ul> <li>Item A</li> </ul> </>, ); // The cart size is incremented even though B hasn't been added yet. await act(() => addItemToCart('B')); assertLog(['Pending: true', 'Items in cart: 2', 'Item A']); expect(root).toMatchRenderedOutput( <> <div>Pending: true</div> <div>Items in cart: 2</div> <ul> <li>Item A</li> </ul> </>, ); // While B is still pending, another item gets added to the cart // out-of-band. serverCart = [...serverCart, 'C']; // NOTE: This is a synchronous update only because we don't yet support // parallel transitions; all transitions are entangled together. Once we add // support for parallel transitions, we can update this test. ReactNoop.flushSync(() => root.render(<App cart={serverCart} />)); assertLog([ 'Pending: true', // Note that the optimistic cart size is still correct, because the // pending update was rebased on top new value. 'Items in cart: 3', 'Item A', 'Item C', ]); expect(root).toMatchRenderedOutput( <> <div>Pending: true</div> <div>Items in cart: 3</div> <ul> <li>Item A</li> <li>Item C</li> </ul> </>, ); // Finish loading B. The optimistic state is reverted. await act(() => resolveText('Adding item B')); assertLog([ 'Pending: false', 'Items in cart: 3', 'Item A', 'Item C', 'Item B', ]); expect(root).toMatchRenderedOutput( <> <div>Pending: false</div> <div>Items in cart: 3</div> <ul> <li>Item A</li> <li>Item C</li> <li>Item B</li> </ul> </>, ); }); // @gate enableAsyncActions test('regression: useOptimistic during setState-in-render', async () => { // This is a regression test for a very specific case where useOptimistic is // the first hook in the component, it has a pending update, and a later // hook schedules a local (setState-in-render) update. Don't sweat about // deleting this test if the implementation details change. let setOptimisticState; let startTransition; function App() { const [optimisticState, _setOptimisticState] = useOptimistic(0); setOptimisticState = _setOptimisticState; const [, _startTransition] = useTransition(); startTransition = _startTransition; const [derivedState, setDerivedState] = useState(0); if (derivedState !== optimisticState) { setDerivedState(optimisticState); } return <Text text={optimisticState} />; } const root = ReactNoop.createRoot(); await act(() => root.render(<App />)); assertLog([0]); expect(root).toMatchRenderedOutput('0'); await act(() => { startTransition(async () => { setOptimisticState(1); await getText('Wait'); }); }); assertLog([1]); expect(root).toMatchRenderedOutput('1'); }); // @gate enableAsyncActions test('useOptimistic accepts a custom reducer', async () => { let serverCart = ['A']; async function submitNewItem(item) { await getText('Adding item ' + item); serverCart = [...serverCart, item]; React.startTransition(() => { root.render(<App cart={serverCart} />); }); } let addItemToCart; function App({cart}) { const [isPending, startTransition] = useTransition(); const savedCartSize = cart.length; const [optimisticCartSize, addToOptimisticCart] = useOptimistic( savedCartSize, (prevSize, newItem) => { Scheduler.log('Increment optimistic cart size for ' + newItem); return prevSize + 1; }, ); addItemToCart = item => { startTransition(async () => { addToOptimisticCart(item); await submitNewItem(item); }); }; return ( <> <div> <Text text={'Pending: ' + isPending} /> </div> <div> <Text text={'Items in cart: ' + optimisticCartSize} /> </div> <ul> {cart.map(item => ( <li key={item}> <Text text={'Item ' + item} /> </li> ))} </ul> </> ); } // Initial render const root = ReactNoop.createRoot(); await act(() => root.render(<App cart={serverCart} />)); assertLog(['Pending: false', 'Items in cart: 1', 'Item A']); expect(root).toMatchRenderedOutput( <> <div>Pending: false</div> <div>Items in cart: 1</div> <ul> <li>Item A</li> </ul> </>, ); // The cart size is incremented even though B hasn't been added yet. await act(() => addItemToCart('B')); assertLog([ 'Increment optimistic cart size for B', 'Pending: true', 'Items in cart: 2', 'Item A', ]); expect(root).toMatchRenderedOutput( <> <div>Pending: true</div> <div>Items in cart: 2</div> <ul> <li>Item A</li> </ul> </>, ); // While B is still pending, another item gets added to the cart // out-of-band. serverCart = [...serverCart, 'C']; // NOTE: This is a synchronous update only because we don't yet support // parallel transitions; all transitions are entangled together. Once we add // support for parallel transitions, we can update this test. ReactNoop.flushSync(() => root.render(<App cart={serverCart} />)); assertLog([ 'Increment optimistic cart size for B', 'Pending: true', // Note that the optimistic cart size is still correct, because the // pending update was rebased on top new value. 'Items in cart: 3', 'Item A', 'Item C', ]); expect(root).toMatchRenderedOutput( <> <div>Pending: true</div> <div>Items in cart: 3</div> <ul> <li>Item A</li> <li>Item C</li> </ul> </>, ); // Finish loading B. The optimistic state is reverted. await act(() => resolveText('Adding item B')); assertLog([ 'Pending: false', 'Items in cart: 3', 'Item A', 'Item C', 'Item B', ]); expect(root).toMatchRenderedOutput( <> <div>Pending: false</div> <div>Items in cart: 3</div> <ul> <li>Item A</li> <li>Item C</li> <li>Item B</li> </ul> </>, ); }); // @gate enableAsyncActions test('useOptimistic rebases if the passthrough is updated during a render phase update', async () => { // This is kind of an esoteric case where it's hard to come up with a // realistic real-world scenario but it should still work. let increment; let setCount; function App() { const [isPending, startTransition] = useTransition(2); const [count, _setCount] = useState(0); setCount = _setCount; const [optimisticCount, setOptimisticCount] = useOptimistic( count, prev => { Scheduler.log('Increment optimistic count'); return prev + 1; }, ); if (count === 1) { Scheduler.log('Render phase update count from 1 to 2'); setCount(2); } increment = () => startTransition(async () => { setOptimisticCount(n => n + 1); await getText('Wait to increment'); React.startTransition(() => setCount(n => n + 1)); }); return ( <> <div> <Text text={'Count: ' + count} /> </div> {isPending ? ( <div> <Text text={'Optimistic count: ' + optimisticCount} /> </div> ) : null} </> ); } const root = ReactNoop.createRoot(); await act(() => root.render(<App />)); assertLog(['Count: 0']); expect(root).toMatchRenderedOutput(<div>Count: 0</div>); await act(() => increment()); assertLog([ 'Increment optimistic count', 'Count: 0', 'Optimistic count: 1', ]); expect(root).toMatchRenderedOutput( <> <div>Count: 0</div> <div>Optimistic count: 1</div> </>, ); await act(() => setCount(1)); assertLog([ 'Increment optimistic count', 'Render phase update count from 1 to 2', // The optimistic update is rebased on top of the new passthrough value. 'Increment optimistic count', 'Count: 2', 'Optimistic count: 3', ]); expect(root).toMatchRenderedOutput( <> <div>Count: 2</div> <div>Optimistic count: 3</div> </>, ); // Finish the action await act(() => resolveText('Wait to increment')); assertLog(['Count: 3']); expect(root).toMatchRenderedOutput(<div>Count: 3</div>); }); // @gate enableAsyncActions test('useOptimistic rebases if the passthrough is updated during a render phase update (initial mount)', async () => { // This is kind of an esoteric case where it's hard to come up with a // realistic real-world scenario but it should still work. function App() { const [count, setCount] = useState(0); const [optimisticCount] = useOptimistic(count); if (count === 0) { Scheduler.log('Render phase update count from 1 to 2'); setCount(1); } return ( <> <div> <Text text={'Count: ' + count} /> </div> <div> <Text text={'Optimistic count: ' + optimisticCount} /> </div> </> ); } const root = ReactNoop.createRoot(); await act(() => root.render(<App />)); assertLog([ 'Render phase update count from 1 to 2', 'Count: 1', 'Optimistic count: 1', ]); expect(root).toMatchRenderedOutput( <> <div>Count: 1</div> <div>Optimistic count: 1</div> </>, ); }); // @gate enableAsyncActions test('useOptimistic can update repeatedly in the same async action', async () => { let startTransition; let setLoadingProgress; let setText; function App() { const [, _startTransition] = useTransition(); const [text, _setText] = useState('A'); const [loadingProgress, _setLoadingProgress] = useOptimistic(0); startTransition = _startTransition; setText = _setText; setLoadingProgress = _setLoadingProgress; return ( <> {loadingProgress !== 0 ? ( <div key="progress"> <Text text={`Loading... (${loadingProgress})`} /> </div> ) : null} <div key="real"> <Text text={text} /> </div> </> ); } // Initial render const root = ReactNoop.createRoot(); await act(() => root.render(<App />)); assertLog(['A']); expect(root).toMatchRenderedOutput(<div>A</div>); await act(async () => { startTransition(async () => { setLoadingProgress('25%'); await getText('Wait 1'); setLoadingProgress('75%'); await getText('Wait 2'); startTransition(() => setText('B')); }); }); assertLog(['Loading... (25%)', 'A']); expect(root).toMatchRenderedOutput( <> <div>Loading... (25%)</div> <div>A</div> </>, ); await act(() => resolveText('Wait 1')); assertLog(['Loading... (75%)', 'A']); expect(root).toMatchRenderedOutput( <> <div>Loading... (75%)</div> <div>A</div> </>, ); await act(() => resolveText('Wait 2')); assertLog(['B']); expect(root).toMatchRenderedOutput(<div>B</div>); }); // @gate enableAsyncActions test('useOptimistic warns if outside of a transition', async () => { let startTransition; let setLoadingProgress; let setText; function App() { const [, _startTransition] = useTransition(); const [text, _setText] = useState('A'); const [loadingProgress, _setLoadingProgress] = useOptimistic(0); startTransition = _startTransition; setText = _setText; setLoadingProgress = _setLoadingProgress; return ( <> {loadingProgress !== 0 ? ( <div key="progress"> <Text text={`Loading... (${loadingProgress})`} /> </div> ) : null} <div key="real"> <Text text={text} /> </div> </> ); } // Initial render const root = ReactNoop.createRoot(); await act(() => root.render(<App />)); assertLog(['A']); expect(root).toMatchRenderedOutput(<div>A</div>); await expect(async () => { await act(() => { setLoadingProgress('25%'); startTransition(() => setText('B')); }); }).toErrorDev( 'An optimistic state update occurred outside a transition or ' + 'action. To fix, move the update to an action, or wrap ' + 'with startTransition.', {withoutStack: true}, ); assertLog(['Loading... (25%)', 'A', 'B']); expect(root).toMatchRenderedOutput(<div>B</div>); }); });
26.368893
120
0.541329
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Layouter} from '../layouter'; /** * Assumes {@param layout} will only contain 2 views. */ export const withVerticalScrollbarLayout: Layouter = ( layout, containerFrame, ) => { const [contentLayoutInfo, scrollbarLayoutInfo] = layout; const desiredContentSize = contentLayoutInfo.view.desiredSize(); const shouldShowScrollbar = desiredContentSize.height > containerFrame.size.height; const scrollbarWidth = shouldShowScrollbar ? scrollbarLayoutInfo.view.desiredSize().width : 0; const laidOutContentLayoutInfo = { ...contentLayoutInfo, frame: { origin: contentLayoutInfo.view.frame.origin, size: { width: containerFrame.size.width - scrollbarWidth, height: containerFrame.size.height, }, }, }; const laidOutScrollbarLayoutInfo = { ...scrollbarLayoutInfo, frame: { origin: { x: laidOutContentLayoutInfo.frame.origin.x + laidOutContentLayoutInfo.frame.size.width, y: containerFrame.origin.y, }, size: { width: scrollbarWidth, height: containerFrame.size.height, }, }, }; return [laidOutContentLayoutInfo, laidOutScrollbarLayoutInfo]; };
24.446429
66
0.673455
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 {useCallback, useState} from 'react'; import AutoSizeInput from './NativeStyleEditor/AutoSizeInput'; import styles from './EditableName.css'; type Type = 'props' | 'state' | 'context' | 'hooks'; type OverrideNameFn = ( oldName: Array<string | number>, newName: Array<string | number>, ) => void; type EditableNameProps = { allowEmpty?: boolean, allowWhiteSpace?: boolean, autoFocus?: boolean, className?: string, initialValue?: string, overrideName: OverrideNameFn, path: Array<string | number>, type: Type, }; export default function EditableName({ allowEmpty = false, allowWhiteSpace = false, autoFocus = false, className = '', initialValue = '', overrideName, path, type, }: EditableNameProps): React.Node { const [editableName, setEditableName] = useState(initialValue); const [isValid, setIsValid] = useState(false); const handleChange = useCallback( ({target}: $FlowFixMe) => { let value = target.value; if (!allowWhiteSpace) { value = value.trim(); } if (allowEmpty || value !== '') { setIsValid(true); } else { setIsValid(false); } setEditableName(value); }, [overrideName], ); const handleKeyDown = useCallback( (event: $FlowFixMe) => { // Prevent keydown events from e.g. change selected element in the tree event.stopPropagation(); switch (event.key) { case 'Enter': case 'Tab': if (isValid) { const basePath = path.slice(0, path.length - 1); overrideName( [...basePath, initialValue], [...basePath, editableName], ); } break; case 'Escape': setEditableName(initialValue); break; default: break; } }, [editableName, setEditableName, isValid, initialValue, overrideName], ); return ( <AutoSizeInput autoFocus={autoFocus} className={[styles.Input, className].join(' ')} onChange={handleChange} onKeyDown={handleKeyDown} placeholder="new entry" testName="EditableName" type="text" value={editableName} /> ); }
23.009804
77
0.609477
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 strict-local */ import {enableLogger} from 'react-devtools-feature-flags'; export type LoggerEvent = | { +event_name: 'loaded-dev-tools', } | { +event_name: 'error', +error_message: string | null, +error_stack: string | null, +error_component_stack: string | null, } | { +event_name: 'selected-components-tab', } | { +event_name: 'selected-profiler-tab', } | { +event_name: 'load-hook-names', +event_status: 'success' | 'error' | 'timeout' | 'unknown', +duration_ms: number, +inspected_element_display_name: string | null, +inspected_element_number_of_hooks: number | null, } | { +event_name: 'select-element', +metadata: { +source: string, }, } | { +event_name: 'inspect-element-button-clicked', } | { +event_name: 'profiling-start', +metadata: { +current_tab: string, }, } | { +event_name: 'profiler-tab-changed', +metadata: { +tabId: string, }, } | { +event_name: 'settings-changed', +metadata: { +key: string, +value: any, ... }, }; export type LogFunction = LoggerEvent => void | Promise<void>; let logFunctions: Array<LogFunction> = []; export const logEvent: LogFunction = enableLogger === true ? function logEvent(event: LoggerEvent): void { logFunctions.forEach(log => { log(event); }); } : function logEvent() {}; export const registerEventLogger: (logFunction: LogFunction) => () => void = enableLogger === true ? function registerEventLogger(logFunction: LogFunction): () => void { if (enableLogger) { logFunctions.push(logFunction); return function unregisterEventLogger() { logFunctions = logFunctions.filter(log => log !== logFunction); }; } return () => {}; } : function registerEventLogger(logFunction: LogFunction) { return () => {}; };
23.802198
76
0.563387
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from './ResizableView'; export * from './ResizeBarView';
21.583333
66
0.688889
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'; // Don't wait before processing work on the server. // TODO: we can replace this with FlightServer.act(). global.setImmediate = cb => cb(); let clientExports; let webpackMap; let webpackModules; let webpackModuleLoading; let React; let ReactDOMServer; let ReactServerDOMServer; let ReactServerDOMClient; let Stream; let use; describe('ReactFlightDOMNode', () => { beforeEach(() => { jest.resetModules(); // Simulate the condition resolution jest.mock('react', () => require('react/react.shared-subset')); jest.mock('react-server-dom-webpack/server', () => require('react-server-dom-webpack/server.node'), ); ReactServerDOMServer = require('react-server-dom-webpack/server'); const WebpackMock = require('./utils/WebpackMock'); clientExports = WebpackMock.clientExports; webpackMap = WebpackMock.webpackMap; webpackModules = WebpackMock.webpackModules; webpackModuleLoading = WebpackMock.moduleLoading; jest.resetModules(); __unmockReact(); jest.unmock('react-server-dom-webpack/server'); jest.mock('react-server-dom-webpack/client', () => require('react-server-dom-webpack/client.node'), ); React = require('react'); ReactDOMServer = require('react-dom/server.node'); ReactServerDOMClient = require('react-server-dom-webpack/client'); Stream = require('stream'); use = React.use; }); function readResult(stream) { return new Promise((resolve, reject) => { let buffer = ''; const writable = new Stream.PassThrough(); writable.setEncoding('utf8'); writable.on('data', chunk => { buffer += chunk; }); writable.on('error', error => { reject(error); }); writable.on('end', () => { resolve(buffer); }); stream.pipe(writable); }); } it('should allow an alternative module mapping to be used for SSR', async () => { function ClientComponent() { return <span>Client Component</span>; } // The Client build may not have the same IDs as the Server bundles for the same // component. const ClientComponentOnTheClient = clientExports( ClientComponent, 123, 'path/to/chunk.js', ); const ClientComponentOnTheServer = clientExports(ClientComponent); // In the SSR bundle this module won't exist. We simulate this by deleting it. const clientId = webpackMap[ClientComponentOnTheClient.$$id].id; delete webpackModules[clientId]; // Instead, we have to provide a translation from the client meta data to the SSR // meta data. const ssrMetadata = webpackMap[ClientComponentOnTheServer.$$id]; const translationMap = { [clientId]: { '*': ssrMetadata, }, }; const ssrManifest = { moduleMap: translationMap, moduleLoading: webpackModuleLoading, }; function App() { return <ClientComponentOnTheClient />; } const stream = ReactServerDOMServer.renderToPipeableStream( <App />, webpackMap, ); const readable = new Stream.PassThrough(); let response; stream.pipe(readable); function ClientRoot() { if (response) return use(response); response = ReactServerDOMClient.createFromNodeStream( readable, ssrManifest, ); return use(response); } const ssrStream = await ReactDOMServer.renderToPipeableStream( <ClientRoot />, ); const result = await readResult(ssrStream); expect(result).toEqual( '<script src="/path/to/chunk.js" async=""></script><span>Client Component</span>', ); }); it('should encode long string in a compact format', async () => { const testString = '"\n\t'.repeat(500) + '🙃'; const stream = ReactServerDOMServer.renderToPipeableStream({ text: testString, }); const readable = new Stream.PassThrough(); const stringResult = readResult(readable); const parsedResult = ReactServerDOMClient.createFromNodeStream(readable, { moduleMap: {}, moduleLoading: webpackModuleLoading, }); stream.pipe(readable); const serializedContent = await stringResult; // The content should be compact an unescaped expect(serializedContent.length).toBeLessThan(2000); expect(serializedContent).not.toContain('\\n'); expect(serializedContent).not.toContain('\\t'); expect(serializedContent).not.toContain('\\"'); expect(serializedContent).toContain('\t'); const result = await parsedResult; // Should still match the result when parsed expect(result.text).toBe(testString); }); // @gate enableBinaryFlight it('should be able to serialize any kind of typed array', async () => { const buffer = new Uint8Array([ 123, 4, 10, 5, 100, 255, 244, 45, 56, 67, 43, 124, 67, 89, 100, 20, ]).buffer; const buffers = [ buffer, new Int8Array(buffer, 1), new Uint8Array(buffer, 2), new Uint8ClampedArray(buffer, 2), new Int16Array(buffer, 2), new Uint16Array(buffer, 2), new Int32Array(buffer, 4), new Uint32Array(buffer, 4), new Float32Array(buffer, 4), new Float64Array(buffer, 0), new BigInt64Array(buffer, 0), new BigUint64Array(buffer, 0), new DataView(buffer, 3), ]; const stream = ReactServerDOMServer.renderToPipeableStream(buffers); const readable = new Stream.PassThrough(); const promise = ReactServerDOMClient.createFromNodeStream(readable, { moduleMap: {}, moduleLoading: webpackModuleLoading, }); stream.pipe(readable); const result = await promise; expect(result).toEqual(buffers); }); it('should allow accept a nonce option for Flight preinitialized scripts', async () => { function ClientComponent() { return <span>Client Component</span>; } // The Client build may not have the same IDs as the Server bundles for the same // component. const ClientComponentOnTheClient = clientExports( ClientComponent, 123, 'path/to/chunk.js', ); const ClientComponentOnTheServer = clientExports(ClientComponent); // In the SSR bundle this module won't exist. We simulate this by deleting it. const clientId = webpackMap[ClientComponentOnTheClient.$$id].id; delete webpackModules[clientId]; // Instead, we have to provide a translation from the client meta data to the SSR // meta data. const ssrMetadata = webpackMap[ClientComponentOnTheServer.$$id]; const translationMap = { [clientId]: { '*': ssrMetadata, }, }; const ssrManifest = { moduleMap: translationMap, moduleLoading: webpackModuleLoading, }; function App() { return <ClientComponentOnTheClient />; } const stream = ReactServerDOMServer.renderToPipeableStream( <App />, webpackMap, ); const readable = new Stream.PassThrough(); let response; stream.pipe(readable); function ClientRoot() { if (response) return use(response); response = ReactServerDOMClient.createFromNodeStream( readable, ssrManifest, { nonce: 'r4nd0m', }, ); return use(response); } const ssrStream = await ReactDOMServer.renderToPipeableStream( <ClientRoot />, ); const result = await readResult(ssrStream); expect(result).toEqual( '<script src="/path/to/chunk.js" async="" nonce="r4nd0m"></script><span>Client Component</span>', ); }); });
28.59542
103
0.654456
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core * @jest-environment ./scripts/jest/ReactDOMServerIntegrationEnvironment */ 'use strict'; const ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegrationTestUtils'); let React; let ReactDOM; let ReactDOMServer; let ReactTestUtils; function initModules() { // Reset warning cache. jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMServer = require('react-dom/server'); ReactTestUtils = require('react-dom/test-utils'); // Make them available to the helpers. return { ReactDOM, ReactDOMServer, ReactTestUtils, }; } const {resetModules, itRenders} = ReactDOMServerIntegrationUtils(initModules); describe('ReactDOMServerIntegration', () => { beforeEach(() => { resetModules(); }); describe('context', function () { let Context, PurpleContextProvider, RedContextProvider, Consumer; beforeEach(() => { Context = React.createContext('none'); class Parent extends React.Component { render() { return ( <Context.Provider value={this.props.text}> {this.props.children} </Context.Provider> ); } } Consumer = Context.Consumer; PurpleContextProvider = props => ( <Parent text="purple">{props.children}</Parent> ); RedContextProvider = props => ( <Parent text="red">{props.children}</Parent> ); }); itRenders('class child with context', async render => { class ClassChildWithContext extends React.Component { render() { return ( <div> <Consumer>{text => text}</Consumer> </div> ); } } const e = await render( <PurpleContextProvider> <ClassChildWithContext /> </PurpleContextProvider>, ); expect(e.textContent).toBe('purple'); }); itRenders('stateless child with context', async render => { function FunctionChildWithContext(props) { return <Consumer>{text => text}</Consumer>; } const e = await render( <PurpleContextProvider> <FunctionChildWithContext /> </PurpleContextProvider>, ); expect(e.textContent).toBe('purple'); }); itRenders('class child with default context', async render => { class ClassChildWithWrongContext extends React.Component { render() { return ( <div id="classWrongChild"> <Consumer>{text => text}</Consumer> </div> ); } } const e = await render(<ClassChildWithWrongContext />); expect(e.textContent).toBe('none'); }); itRenders('stateless child with wrong context', async render => { function FunctionChildWithWrongContext(props) { return ( <div id="statelessWrongChild"> <Consumer>{text => text}</Consumer> </div> ); } const e = await render(<FunctionChildWithWrongContext />); expect(e.textContent).toBe('none'); }); itRenders('with context passed through to a grandchild', async render => { function Grandchild(props) { return ( <div> <Consumer>{text => text}</Consumer> </div> ); } const Child = props => <Grandchild />; const e = await render( <PurpleContextProvider> <Child /> </PurpleContextProvider>, ); expect(e.textContent).toBe('purple'); }); itRenders('a child context overriding a parent context', async render => { const Grandchild = props => { return ( <div> <Consumer>{text => text}</Consumer> </div> ); }; const e = await render( <PurpleContextProvider> <RedContextProvider> <Grandchild /> </RedContextProvider> </PurpleContextProvider>, ); expect(e.textContent).toBe('red'); }); itRenders('readContext() in different components', async render => { function readContext(Ctx) { const dispatcher = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED .ReactCurrentDispatcher.current; return dispatcher.readContext(Ctx); } class Cls extends React.Component { render() { return readContext(Context); } } function Fn() { return readContext(Context); } const Memo = React.memo(() => { return readContext(Context); }); const FwdRef = React.forwardRef((props, ref) => { return readContext(Context); }); const e = await render( <PurpleContextProvider> <RedContextProvider> <span> <Fn /> <Cls /> <Memo /> <FwdRef /> <Consumer>{() => readContext(Context)}</Consumer> </span> </RedContextProvider> </PurpleContextProvider>, ); expect(e.textContent).toBe('redredredredred'); }); itRenders('multiple contexts', async render => { const Theme = React.createContext('dark'); const Language = React.createContext('french'); class Parent extends React.Component { render() { return ( <Theme.Provider value="light"> <Child /> </Theme.Provider> ); } } function Child() { return ( <Language.Provider value="english"> <Grandchild /> </Language.Provider> ); } const Grandchild = props => { return ( <div> <Theme.Consumer> {theme => <div id="theme">{theme}</div>} </Theme.Consumer> <Language.Consumer> {language => <div id="language">{language}</div>} </Language.Consumer> </div> ); }; const e = await render(<Parent />); expect(e.querySelector('#theme').textContent).toBe('light'); expect(e.querySelector('#language').textContent).toBe('english'); }); itRenders('nested context unwinding', async render => { const Theme = React.createContext('dark'); const Language = React.createContext('french'); const App = () => ( <div> <Theme.Provider value="light"> <Language.Provider value="english"> <Theme.Provider value="dark"> <Theme.Consumer> {theme => <div id="theme1">{theme}</div>} </Theme.Consumer> </Theme.Provider> <Theme.Consumer> {theme => <div id="theme2">{theme}</div>} </Theme.Consumer> <Language.Provider value="sanskrit"> <Theme.Provider value="blue"> <Theme.Provider value="red"> <Language.Consumer> {() => ( <Language.Provider value="chinese"> <Language.Provider value="hungarian" /> <Language.Consumer> {language => <div id="language1">{language}</div>} </Language.Consumer> </Language.Provider> )} </Language.Consumer> </Theme.Provider> <Language.Consumer> {language => ( <> <Theme.Consumer> {theme => <div id="theme3">{theme}</div>} </Theme.Consumer> <div id="language2">{language}</div> </> )} </Language.Consumer> </Theme.Provider> </Language.Provider> </Language.Provider> </Theme.Provider> <Language.Consumer> {language => <div id="language3">{language}</div>} </Language.Consumer> </div> ); const e = await render(<App />); expect(e.querySelector('#theme1').textContent).toBe('dark'); expect(e.querySelector('#theme2').textContent).toBe('light'); expect(e.querySelector('#theme3').textContent).toBe('blue'); expect(e.querySelector('#language1').textContent).toBe('chinese'); expect(e.querySelector('#language2').textContent).toBe('sanskrit'); expect(e.querySelector('#language3').textContent).toBe('french'); }); itRenders( 'should warn with an error message when using Context as consumer in DEV', async render => { const Theme = React.createContext('dark'); const Language = React.createContext('french'); const App = () => ( <div> <Theme.Provider value="light"> <Language.Provider value="english"> <Theme.Provider value="dark"> <Theme>{theme => <div id="theme1">{theme}</div>}</Theme> </Theme.Provider> </Language.Provider> </Theme.Provider> </div> ); // We expect 1 error. await render(<App />, 1); }, ); // False positive regression test. itRenders( 'should not warn when using Consumer from React < 16.6 with newer renderer', async render => { const Theme = React.createContext('dark'); const Language = React.createContext('french'); // React 16.5 and earlier didn't have a separate object. Theme.Consumer = Theme; const App = () => ( <div> <Theme.Provider value="light"> <Language.Provider value="english"> <Theme.Provider value="dark"> <Theme>{theme => <div id="theme1">{theme}</div>}</Theme> </Theme.Provider> </Language.Provider> </Theme.Provider> </div> ); // We expect 0 errors. await render(<App />, 0); }, ); itRenders( 'should warn with an error message when using nested context consumers in DEV', async render => { const App = () => { const Theme = React.createContext('dark'); const Language = React.createContext('french'); return ( <div> <Theme.Provider value="light"> <Language.Provider value="english"> <Theme.Provider value="dark"> <Theme.Consumer.Consumer> {theme => <div id="theme1">{theme}</div>} </Theme.Consumer.Consumer> </Theme.Provider> </Language.Provider> </Theme.Provider> </div> ); }; // We expect 1 error. await render(<App />, 1); }, ); itRenders( 'should warn with an error message when using Context.Consumer.Provider DEV', async render => { const App = () => { const Theme = React.createContext('dark'); const Language = React.createContext('french'); return ( <div> <Theme.Provider value="light"> <Language.Provider value="english"> <Theme.Consumer.Provider value="dark"> <Theme.Consumer> {theme => <div id="theme1">{theme}</div>} </Theme.Consumer> </Theme.Consumer.Provider> </Language.Provider> </Theme.Provider> </div> ); }; // We expect 1 error. await render(<App />, 1); }, ); it('does not pollute parallel node streams', () => { const LoggedInUser = React.createContext(); const AppWithUser = user => ( <LoggedInUser.Provider value={user}> <header> <LoggedInUser.Consumer>{whoAmI => whoAmI}</LoggedInUser.Consumer> </header> <footer> <LoggedInUser.Consumer>{whoAmI => whoAmI}</LoggedInUser.Consumer> </footer> </LoggedInUser.Provider> ); let streamAmy; let streamBob; expect(() => { streamAmy = ReactDOMServer.renderToNodeStream( AppWithUser('Amy'), ).setEncoding('utf8'); }).toErrorDev( 'renderToNodeStream is deprecated. Use renderToPipeableStream instead.', {withoutStack: true}, ); expect(() => { streamBob = ReactDOMServer.renderToNodeStream( AppWithUser('Bob'), ).setEncoding('utf8'); }).toErrorDev( 'renderToNodeStream is deprecated. Use renderToPipeableStream instead.', {withoutStack: true}, ); // Testing by filling the buffer using internal _read() with a small // number of bytes to avoid a test case which needs to align to a // highWaterMark boundary of 2^14 chars. streamAmy._read(20); streamBob._read(20); streamAmy._read(20); streamBob._read(20); expect(streamAmy.read()).toBe('<header>Amy</header><footer>Amy</footer>'); expect(streamBob.read()).toBe('<header>Bob</header><footer>Bob</footer>'); }); it('does not pollute parallel node streams when many are used', () => { const CurrentIndex = React.createContext(); const NthRender = index => ( <CurrentIndex.Provider value={index}> <header> <CurrentIndex.Consumer>{idx => idx}</CurrentIndex.Consumer> </header> <footer> <CurrentIndex.Consumer>{idx => idx}</CurrentIndex.Consumer> </footer> </CurrentIndex.Provider> ); const streams = []; // Test with more than 32 streams to test that growing the thread count // works properly. const streamCount = 34; for (let i = 0; i < streamCount; i++) { expect(() => { streams[i] = ReactDOMServer.renderToNodeStream( NthRender(i % 2 === 0 ? 'Expected to be recreated' : i), ).setEncoding('utf8'); }).toErrorDev( 'renderToNodeStream is deprecated. Use renderToPipeableStream instead.', {withoutStack: true}, ); } // Testing by filling the buffer using internal _read() with a small // number of bytes to avoid a test case which needs to align to a // highWaterMark boundary of 2^14 chars. for (let i = 0; i < streamCount; i++) { streams[i]._read(20); } // Early destroy every other stream for (let i = 0; i < streamCount; i += 2) { streams[i].destroy(); } // Recreate those same streams. for (let i = 0; i < streamCount; i += 2) { expect(() => { streams[i] = ReactDOMServer.renderToNodeStream( NthRender(i), ).setEncoding('utf8'); }).toErrorDev( 'renderToNodeStream is deprecated. Use renderToPipeableStream instead.', {withoutStack: true}, ); } // Read a bit from all streams again. for (let i = 0; i < streamCount; i++) { streams[i]._read(20); } // Assert that all stream rendered the expected output. for (let i = 0; i < streamCount; i++) { expect(streams[i].read()).toBe( '<header>' + i + '</header><footer>' + i + '</footer>', ); } }); it('does not pollute sync renders after an error', () => { const LoggedInUser = React.createContext('default'); const Crash = () => { throw new Error('Boo!'); }; const AppWithUser = user => ( <LoggedInUser.Provider value={user}> <LoggedInUser.Consumer>{whoAmI => whoAmI}</LoggedInUser.Consumer> <Crash /> </LoggedInUser.Provider> ); expect(() => { ReactDOMServer.renderToString(AppWithUser('Casper')); }).toThrow('Boo'); // Should not report a value from failed render expect( ReactDOMServer.renderToString( <LoggedInUser.Consumer>{whoAmI => whoAmI}</LoggedInUser.Consumer>, ), ).toBe('default'); }); }); });
29.739292
93
0.529747
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. */ 'use strict'; export * from './src/forks/SchedulerMock';
21.818182
66
0.704
owtf
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; import { buttonType, buttonsType, defaultPointerId, defaultPointerSize, defaultBrowserChromeSize, } from './constants'; import * as domEvents from './domEvents'; import {hasPointerEvent, platform} from './domEnvironment'; import * as touchStore from './touchStore'; /** * Converts a PointerEvent payload to a Touch */ function createTouch(target, payload) { const { height = defaultPointerSize, pageX, pageY, pointerId, pressure = 1, twist = 0, width = defaultPointerSize, x = 0, y = 0, } = payload; return { clientX: x, clientY: y, force: pressure, identifier: pointerId, pageX: pageX || x, pageY: pageY || y, radiusX: width / 2, radiusY: height / 2, rotationAngle: twist, target, screenX: x, screenY: y + defaultBrowserChromeSize, }; } /** * Converts a PointerEvent to a TouchEvent */ function createTouchEventPayload(target, touch, payload) { const { altKey = false, ctrlKey = false, metaKey = false, preventDefault, shiftKey = false, timeStamp, } = payload; return { altKey, changedTouches: [touch], ctrlKey, metaKey, preventDefault, shiftKey, targetTouches: touchStore.getTargetTouches(target), timeStamp, touches: touchStore.getTouches(), }; } function getPointerType(payload) { let pointerType = 'mouse'; if (payload != null && payload.pointerType != null) { pointerType = payload.pointerType; } return pointerType; } /** * Pointer events sequences. * * Creates representative browser event sequences for high-level gestures based on pointers. * This allows unit tests to be written in terms of simple pointer interactions while testing * that the responses to those interactions account for the complex sequence of events that * browsers produce as a result. * * Every time a new pointer touches the surface a 'touchstart' event should be dispatched. * - 'changedTouches' contains the new touch. * - 'targetTouches' contains all the active pointers for the target. * - 'touches' contains all the active pointers on the surface. * * Every time an existing pointer moves a 'touchmove' event should be dispatched. * - 'changedTouches' contains the updated touch. * * Every time an existing pointer leaves the surface a 'touchend' event should be dispatched. * - 'changedTouches' contains the released touch. * - 'targetTouches' contains any of the remaining active pointers for the target. */ export function contextmenu( target, defaultPayload, {pointerType = 'mouse', modified} = {}, ) { const dispatch = arg => target.dispatchEvent(arg); const payload = { pointerId: defaultPointerId, pointerType, ...defaultPayload, }; const preventDefault = payload.preventDefault; if (pointerType === 'touch') { if (hasPointerEvent()) { dispatch( domEvents.pointerdown({ ...payload, button: buttonType.primary, buttons: buttonsType.primary, }), ); } const touch = createTouch(target, payload); touchStore.addTouch(touch); const touchEventPayload = createTouchEventPayload(target, touch, payload); dispatch(domEvents.touchstart(touchEventPayload)); dispatch( domEvents.contextmenu({ button: buttonType.primary, buttons: buttonsType.none, preventDefault, }), ); touchStore.removeTouch(touch); } else if (pointerType === 'mouse') { if (modified === true) { const button = buttonType.primary; const buttons = buttonsType.primary; const ctrlKey = true; if (hasPointerEvent()) { dispatch( domEvents.pointerdown({button, buttons, ctrlKey, pointerType}), ); } dispatch(domEvents.mousedown({button, buttons, ctrlKey})); if (platform.get() === 'mac') { dispatch( domEvents.contextmenu({button, buttons, ctrlKey, preventDefault}), ); } } else { const button = buttonType.secondary; const buttons = buttonsType.secondary; if (hasPointerEvent()) { dispatch(domEvents.pointerdown({button, buttons, pointerType})); } dispatch(domEvents.mousedown({button, buttons})); dispatch(domEvents.contextmenu({button, buttons, preventDefault})); } } } export function pointercancel(target, defaultPayload) { const dispatchEvent = arg => target.dispatchEvent(arg); const pointerType = getPointerType(defaultPayload); const payload = { pointerId: defaultPointerId, pointerType, ...defaultPayload, }; if (hasPointerEvent()) { dispatchEvent(domEvents.pointercancel(payload)); } else { if (pointerType === 'mouse') { dispatchEvent(domEvents.dragstart(payload)); } else { const touch = createTouch(target, payload); touchStore.removeTouch(touch); const touchEventPayload = createTouchEventPayload(target, touch, payload); dispatchEvent(domEvents.touchcancel(touchEventPayload)); } } } export function pointerdown(target, defaultPayload) { const dispatch = arg => target.dispatchEvent(arg); const pointerType = getPointerType(defaultPayload); const payload = { button: buttonType.primary, buttons: buttonsType.primary, pointerId: defaultPointerId, pointerType, ...defaultPayload, }; if (pointerType === 'mouse') { if (hasPointerEvent()) { dispatch(domEvents.pointerover(payload)); dispatch(domEvents.pointerenter(payload)); } dispatch(domEvents.mouseover(payload)); dispatch(domEvents.mouseenter(payload)); if (hasPointerEvent()) { dispatch(domEvents.pointerdown(payload)); } dispatch(domEvents.mousedown(payload)); if (document.activeElement !== target) { dispatch(domEvents.focus()); } } else { if (hasPointerEvent()) { dispatch(domEvents.pointerover(payload)); dispatch(domEvents.pointerenter(payload)); dispatch(domEvents.pointerdown(payload)); } const touch = createTouch(target, payload); touchStore.addTouch(touch); const touchEventPayload = createTouchEventPayload(target, touch, payload); dispatch(domEvents.touchstart(touchEventPayload)); if (hasPointerEvent()) { dispatch(domEvents.gotpointercapture(payload)); } } } export function pointerenter(target, defaultPayload) { const dispatch = arg => target.dispatchEvent(arg); const payload = { pointerId: defaultPointerId, ...defaultPayload, }; if (hasPointerEvent()) { dispatch(domEvents.pointerover(payload)); dispatch(domEvents.pointerenter(payload)); } dispatch(domEvents.mouseover(payload)); dispatch(domEvents.mouseenter(payload)); } export function pointerexit(target, defaultPayload) { const dispatch = arg => target.dispatchEvent(arg); const payload = { pointerId: defaultPointerId, ...defaultPayload, }; if (hasPointerEvent()) { dispatch(domEvents.pointerout(payload)); dispatch(domEvents.pointerleave(payload)); } dispatch(domEvents.mouseout(payload)); dispatch(domEvents.mouseleave(payload)); } export function pointerhover(target, defaultPayload) { const dispatch = arg => target.dispatchEvent(arg); const payload = { pointerId: defaultPointerId, ...defaultPayload, }; if (hasPointerEvent()) { dispatch(domEvents.pointermove(payload)); } dispatch(domEvents.mousemove(payload)); } export function pointermove(target, defaultPayload) { const dispatch = arg => target.dispatchEvent(arg); const pointerType = getPointerType(defaultPayload); const payload = { pointerId: defaultPointerId, pointerType, ...defaultPayload, }; if (hasPointerEvent()) { dispatch( domEvents.pointermove({ pressure: pointerType === 'touch' ? 1 : 0.5, ...payload, }), ); } else { if (pointerType === 'mouse') { dispatch(domEvents.mousemove(payload)); } else { const touch = createTouch(target, payload); touchStore.updateTouch(touch); const touchEventPayload = createTouchEventPayload(target, touch, payload); dispatch(domEvents.touchmove(touchEventPayload)); } } } export function pointerup(target, defaultPayload) { const dispatch = arg => target.dispatchEvent(arg); const pointerType = getPointerType(defaultPayload); const payload = { pointerId: defaultPointerId, pointerType, ...defaultPayload, }; if (pointerType === 'mouse') { if (hasPointerEvent()) { dispatch(domEvents.pointerup(payload)); } dispatch(domEvents.mouseup(payload)); dispatch(domEvents.click(payload)); } else { if (hasPointerEvent()) { dispatch(domEvents.pointerup(payload)); dispatch(domEvents.lostpointercapture(payload)); dispatch(domEvents.pointerout(payload)); dispatch(domEvents.pointerleave(payload)); } const touch = createTouch(target, payload); touchStore.removeTouch(touch); const touchEventPayload = createTouchEventPayload(target, touch, payload); dispatch(domEvents.touchend(touchEventPayload)); dispatch(domEvents.mouseover(payload)); dispatch(domEvents.mousemove(payload)); dispatch(domEvents.mousedown(payload)); if (document.activeElement !== target) { dispatch(domEvents.focus()); } dispatch(domEvents.mouseup(payload)); dispatch(domEvents.click(payload)); } } /** * This function should be called after each test to ensure the touchStore is cleared * in cases where the mock pointers weren't released before the test completed * (e.g., a test failed or ran a partial gesture). */ export function resetActivePointers() { touchStore.clear(); }
26.546961
93
0.680574
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. */ /* global BigInt */ /* eslint-disable no-for-of-loops/no-for-of-loops */ 'use strict'; /** * Catch all identifiers that begin with "use" followed by an uppercase Latin * character to exclude identifiers like "user". */ function isHookName(s) { return s === 'use' || /^use[A-Z0-9]/.test(s); } /** * We consider hooks to be a hook name identifier or a member expression * containing a hook name. */ function isHook(node) { if (node.type === 'Identifier') { return isHookName(node.name); } else if ( node.type === 'MemberExpression' && !node.computed && isHook(node.property) ) { const obj = node.object; const isPascalCaseNameSpace = /^[A-Z].*/; return obj.type === 'Identifier' && isPascalCaseNameSpace.test(obj.name); } else { return false; } } /** * Checks if the node is a React component name. React component names must * always start with an uppercase letter. */ function isComponentName(node) { return node.type === 'Identifier' && /^[A-Z]/.test(node.name); } function isReactFunction(node, functionName) { return ( node.name === functionName || (node.type === 'MemberExpression' && node.object.name === 'React' && node.property.name === functionName) ); } /** * Checks if the node is a callback argument of forwardRef. This render function * should follow the rules of hooks. */ function isForwardRefCallback(node) { return !!( node.parent && node.parent.callee && isReactFunction(node.parent.callee, 'forwardRef') ); } /** * Checks if the node is a callback argument of React.memo. This anonymous * functional component should follow the rules of hooks. */ function isMemoCallback(node) { return !!( node.parent && node.parent.callee && isReactFunction(node.parent.callee, 'memo') ); } function isInsideComponentOrHook(node) { while (node) { const functionName = getFunctionName(node); if (functionName) { if (isComponentName(functionName) || isHook(functionName)) { return true; } } if (isForwardRefCallback(node) || isMemoCallback(node)) { return true; } node = node.parent; } return false; } function isUseEffectEventIdentifier(node) { if (__EXPERIMENTAL__) { return node.type === 'Identifier' && node.name === 'useEffectEvent'; } return false; } function isUseIdentifier(node) { return isReactFunction(node, 'use'); } export default { meta: { type: 'problem', docs: { description: 'enforces the Rules of Hooks', recommended: true, url: 'https://reactjs.org/docs/hooks-rules.html', }, }, create(context) { let lastEffect = null; const codePathReactHooksMapStack = []; const codePathSegmentStack = []; const useEffectEventFunctions = new WeakSet(); // For a given scope, iterate through the references and add all useEffectEvent definitions. We can // do this in non-Program nodes because we can rely on the assumption that useEffectEvent functions // can only be declared within a component or hook at its top level. function recordAllUseEffectEventFunctions(scope) { for (const reference of scope.references) { const parent = reference.identifier.parent; if ( parent.type === 'VariableDeclarator' && parent.init && parent.init.type === 'CallExpression' && parent.init.callee && isUseEffectEventIdentifier(parent.init.callee) ) { for (const ref of reference.resolved.references) { if (ref !== reference) { useEffectEventFunctions.add(ref.identifier); } } } } } return { // Maintain code segment path stack as we traverse. onCodePathSegmentStart: segment => codePathSegmentStack.push(segment), onCodePathSegmentEnd: () => codePathSegmentStack.pop(), // Maintain code path stack as we traverse. onCodePathStart: () => codePathReactHooksMapStack.push(new Map()), // Process our code path. // // Everything is ok if all React Hooks are both reachable from the initial // segment and reachable from every final segment. onCodePathEnd(codePath, codePathNode) { const reactHooksMap = codePathReactHooksMapStack.pop(); if (reactHooksMap.size === 0) { return; } // All of the segments which are cyclic are recorded in this set. const cyclic = new Set(); /** * Count the number of code paths from the start of the function to this * segment. For example: * * ```js * function MyComponent() { * if (condition) { * // Segment 1 * } else { * // Segment 2 * } * // Segment 3 * } * ``` * * Segments 1 and 2 have one path to the beginning of `MyComponent` and * segment 3 has two paths to the beginning of `MyComponent` since we * could have either taken the path of segment 1 or segment 2. * * Populates `cyclic` with cyclic segments. */ function countPathsFromStart(segment, pathHistory) { const {cache} = countPathsFromStart; let paths = cache.get(segment.id); const pathList = new Set(pathHistory); // If `pathList` includes the current segment then we've found a cycle! // We need to fill `cyclic` with all segments inside cycle if (pathList.has(segment.id)) { const pathArray = [...pathList]; const cyclicSegments = pathArray.slice( pathArray.indexOf(segment.id) + 1, ); for (const cyclicSegment of cyclicSegments) { cyclic.add(cyclicSegment); } return BigInt('0'); } // add the current segment to pathList pathList.add(segment.id); // We have a cached `paths`. Return it. if (paths !== undefined) { return paths; } if (codePath.thrownSegments.includes(segment)) { paths = BigInt('0'); } else if (segment.prevSegments.length === 0) { paths = BigInt('1'); } else { paths = BigInt('0'); for (const prevSegment of segment.prevSegments) { paths += countPathsFromStart(prevSegment, pathList); } } // If our segment is reachable then there should be at least one path // to it from the start of our code path. if (segment.reachable && paths === BigInt('0')) { cache.delete(segment.id); } else { cache.set(segment.id, paths); } return paths; } /** * Count the number of code paths from this segment to the end of the * function. For example: * * ```js * function MyComponent() { * // Segment 1 * if (condition) { * // Segment 2 * } else { * // Segment 3 * } * } * ``` * * Segments 2 and 3 have one path to the end of `MyComponent` and * segment 1 has two paths to the end of `MyComponent` since we could * either take the path of segment 1 or segment 2. * * Populates `cyclic` with cyclic segments. */ function countPathsToEnd(segment, pathHistory) { const {cache} = countPathsToEnd; let paths = cache.get(segment.id); const pathList = new Set(pathHistory); // If `pathList` includes the current segment then we've found a cycle! // We need to fill `cyclic` with all segments inside cycle if (pathList.has(segment.id)) { const pathArray = Array.from(pathList); const cyclicSegments = pathArray.slice( pathArray.indexOf(segment.id) + 1, ); for (const cyclicSegment of cyclicSegments) { cyclic.add(cyclicSegment); } return BigInt('0'); } // add the current segment to pathList pathList.add(segment.id); // We have a cached `paths`. Return it. if (paths !== undefined) { return paths; } if (codePath.thrownSegments.includes(segment)) { paths = BigInt('0'); } else if (segment.nextSegments.length === 0) { paths = BigInt('1'); } else { paths = BigInt('0'); for (const nextSegment of segment.nextSegments) { paths += countPathsToEnd(nextSegment, pathList); } } cache.set(segment.id, paths); return paths; } /** * Gets the shortest path length to the start of a code path. * For example: * * ```js * function MyComponent() { * if (condition) { * // Segment 1 * } * // Segment 2 * } * ``` * * There is only one path from segment 1 to the code path start. Its * length is one so that is the shortest path. * * There are two paths from segment 2 to the code path start. One * through segment 1 with a length of two and another directly to the * start with a length of one. The shortest path has a length of one * so we would return that. */ function shortestPathLengthToStart(segment) { const {cache} = shortestPathLengthToStart; let length = cache.get(segment.id); // If `length` is null then we found a cycle! Return infinity since // the shortest path is definitely not the one where we looped. if (length === null) { return Infinity; } // We have a cached `length`. Return it. if (length !== undefined) { return length; } // Compute `length` and cache it. Guarding against cycles. cache.set(segment.id, null); if (segment.prevSegments.length === 0) { length = 1; } else { length = Infinity; for (const prevSegment of segment.prevSegments) { const prevLength = shortestPathLengthToStart(prevSegment); if (prevLength < length) { length = prevLength; } } length += 1; } cache.set(segment.id, length); return length; } countPathsFromStart.cache = new Map(); countPathsToEnd.cache = new Map(); shortestPathLengthToStart.cache = new Map(); // Count all code paths to the end of our component/hook. Also primes // the `countPathsToEnd` cache. const allPathsFromStartToEnd = countPathsToEnd(codePath.initialSegment); // Gets the function name for our code path. If the function name is // `undefined` then we know either that we have an anonymous function // expression or our code path is not in a function. In both cases we // will want to error since neither are React function components or // hook functions - unless it is an anonymous function argument to // forwardRef or memo. const codePathFunctionName = getFunctionName(codePathNode); // This is a valid code path for React hooks if we are directly in a React // function component or we are in a hook function. const isSomewhereInsideComponentOrHook = isInsideComponentOrHook(codePathNode); const isDirectlyInsideComponentOrHook = codePathFunctionName ? isComponentName(codePathFunctionName) || isHook(codePathFunctionName) : isForwardRefCallback(codePathNode) || isMemoCallback(codePathNode); // Compute the earliest finalizer level using information from the // cache. We expect all reachable final segments to have a cache entry // after calling `visitSegment()`. let shortestFinalPathLength = Infinity; for (const finalSegment of codePath.finalSegments) { if (!finalSegment.reachable) { continue; } const length = shortestPathLengthToStart(finalSegment); if (length < shortestFinalPathLength) { shortestFinalPathLength = length; } } // Make sure all React Hooks pass our lint invariants. Log warnings // if not. for (const [segment, reactHooks] of reactHooksMap) { // NOTE: We could report here that the hook is not reachable, but // that would be redundant with more general "no unreachable" // lint rules. if (!segment.reachable) { continue; } // If there are any final segments with a shorter path to start then // we possibly have an early return. // // If our segment is a final segment itself then siblings could // possibly be early returns. const possiblyHasEarlyReturn = segment.nextSegments.length === 0 ? shortestFinalPathLength <= shortestPathLengthToStart(segment) : shortestFinalPathLength < shortestPathLengthToStart(segment); // Count all the paths from the start of our code path to the end of // our code path that go _through_ this segment. The critical piece // of this is _through_. If we just call `countPathsToEnd(segment)` // then we neglect that we may have gone through multiple paths to get // to this point! Consider: // // ```js // function MyComponent() { // if (a) { // // Segment 1 // } else { // // Segment 2 // } // // Segment 3 // if (b) { // // Segment 4 // } else { // // Segment 5 // } // } // ``` // // In this component we have four code paths: // // 1. `a = true; b = true` // 2. `a = true; b = false` // 3. `a = false; b = true` // 4. `a = false; b = false` // // From segment 3 there are two code paths to the end through segment // 4 and segment 5. However, we took two paths to get here through // segment 1 and segment 2. // // If we multiply the paths from start (two) by the paths to end (two) // for segment 3 we get four. Which is our desired count. const pathsFromStartToEnd = countPathsFromStart(segment) * countPathsToEnd(segment); // Is this hook a part of a cyclic segment? const cycled = cyclic.has(segment.id); for (const hook of reactHooks) { // Report an error if a hook may be called more then once. // `use(...)` can be called in loops. if (cycled && !isUseIdentifier(hook)) { context.report({ node: hook, message: `React Hook "${context.getSource(hook)}" may be executed ` + 'more than once. Possibly because it is called in a loop. ' + 'React Hooks must be called in the exact same order in ' + 'every component render.', }); } // If this is not a valid code path for React hooks then we need to // log a warning for every hook in this code path. // // Pick a special message depending on the scope this hook was // called in. if (isDirectlyInsideComponentOrHook) { // Report an error if the hook is called inside an async function. const isAsyncFunction = codePathNode.async; if (isAsyncFunction) { context.report({ node: hook, message: `React Hook "${context.getSource(hook)}" cannot be ` + 'called in an async function.', }); } // Report an error if a hook does not reach all finalizing code // path segments. // // Special case when we think there might be an early return. if ( !cycled && pathsFromStartToEnd !== allPathsFromStartToEnd && !isUseIdentifier(hook) // `use(...)` can be called conditionally. ) { const message = `React Hook "${context.getSource(hook)}" is called ` + 'conditionally. React Hooks must be called in the exact ' + 'same order in every component render.' + (possiblyHasEarlyReturn ? ' Did you accidentally call a React Hook after an' + ' early return?' : ''); context.report({node: hook, message}); } } else if ( codePathNode.parent && (codePathNode.parent.type === 'MethodDefinition' || codePathNode.parent.type === 'ClassProperty') && codePathNode.parent.value === codePathNode ) { // Custom message for hooks inside a class const message = `React Hook "${context.getSource(hook)}" cannot be called ` + 'in a class component. React Hooks must be called in a ' + 'React function component or a custom React Hook function.'; context.report({node: hook, message}); } else if (codePathFunctionName) { // Custom message if we found an invalid function name. const message = `React Hook "${context.getSource(hook)}" is called in ` + `function "${context.getSource(codePathFunctionName)}" ` + 'that is neither a React function component nor a custom ' + 'React Hook function.' + ' React component names must start with an uppercase letter.' + ' React Hook names must start with the word "use".'; context.report({node: hook, message}); } else if (codePathNode.type === 'Program') { // These are dangerous if you have inline requires enabled. const message = `React Hook "${context.getSource(hook)}" cannot be called ` + 'at the top level. React Hooks must be called in a ' + 'React function component or a custom React Hook function.'; context.report({node: hook, message}); } else { // Assume in all other cases the user called a hook in some // random function callback. This should usually be true for // anonymous function expressions. Hopefully this is clarifying // enough in the common case that the incorrect message in // uncommon cases doesn't matter. // `use(...)` can be called in callbacks. if (isSomewhereInsideComponentOrHook && !isUseIdentifier(hook)) { const message = `React Hook "${context.getSource(hook)}" cannot be called ` + 'inside a callback. React Hooks must be called in a ' + 'React function component or a custom React Hook function.'; context.report({node: hook, message}); } } } } }, // Missed opportunity...We could visit all `Identifier`s instead of all // `CallExpression`s and check that _every use_ of a hook name is valid. // But that gets complicated and enters type-system territory, so we're // only being strict about hook calls for now. CallExpression(node) { if (isHook(node.callee)) { // Add the hook node to a map keyed by the code path segment. We will // do full code path analysis at the end of our code path. const reactHooksMap = last(codePathReactHooksMapStack); const codePathSegment = last(codePathSegmentStack); let reactHooks = reactHooksMap.get(codePathSegment); if (!reactHooks) { reactHooks = []; reactHooksMap.set(codePathSegment, reactHooks); } reactHooks.push(node.callee); } // useEffectEvent: useEffectEvent functions can be passed by reference within useEffect as well as in // another useEffectEvent if ( node.callee.type === 'Identifier' && (node.callee.name === 'useEffect' || isUseEffectEventIdentifier(node.callee)) && node.arguments.length > 0 ) { // Denote that we have traversed into a useEffect call, and stash the CallExpr for // comparison later when we exit lastEffect = node; } }, Identifier(node) { // This identifier resolves to a useEffectEvent function, but isn't being referenced in an // effect or another event function. It isn't being called either. if ( lastEffect == null && useEffectEventFunctions.has(node) && node.parent.type !== 'CallExpression' ) { context.report({ node, message: `\`${context.getSource( node, )}\` is a function created with React Hook "useEffectEvent", and can only be called from ` + 'the same component. They cannot be assigned to variables or passed down.', }); } }, 'CallExpression:exit'(node) { if (node === lastEffect) { lastEffect = null; } }, FunctionDeclaration(node) { // function MyComponent() { const onClick = useEffectEvent(...) } if (isInsideComponentOrHook(node)) { recordAllUseEffectEventFunctions(context.getScope()); } }, ArrowFunctionExpression(node) { // const MyComponent = () => { const onClick = useEffectEvent(...) } if (isInsideComponentOrHook(node)) { recordAllUseEffectEventFunctions(context.getScope()); } }, }; }, }; /** * Gets the static name of a function AST node. For function declarations it is * easy. For anonymous function expressions it is much harder. If you search for * `IsAnonymousFunctionDefinition()` in the ECMAScript spec you'll find places * where JS gives anonymous function expressions names. We roughly detect the * same AST nodes with some exceptions to better fit our use case. */ function getFunctionName(node) { if ( node.type === 'FunctionDeclaration' || (node.type === 'FunctionExpression' && node.id) ) { // function useHook() {} // const whatever = function useHook() {}; // // Function declaration or function expression names win over any // assignment statements or other renames. return node.id; } else if ( node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression' ) { if ( node.parent.type === 'VariableDeclarator' && node.parent.init === node ) { // const useHook = () => {}; return node.parent.id; } else if ( node.parent.type === 'AssignmentExpression' && node.parent.right === node && node.parent.operator === '=' ) { // useHook = () => {}; return node.parent.left; } else if ( node.parent.type === 'Property' && node.parent.value === node && !node.parent.computed ) { // {useHook: () => {}} // {useHook() {}} return node.parent.key; // NOTE: We could also support `ClassProperty` and `MethodDefinition` // here to be pedantic. However, hooks in a class are an anti-pattern. So // we don't allow it to error early. // // class {useHook = () => {}} // class {useHook() {}} } else if ( node.parent.type === 'AssignmentPattern' && node.parent.right === node && !node.parent.computed ) { // const {useHook = () => {}} = {}; // ({useHook = () => {}} = {}); // // Kinda clowny, but we'd said we'd follow spec convention for // `IsAnonymousFunctionDefinition()` usage. return node.parent.left; } else { return undefined; } } else { return undefined; } } /** * Convenience function for peeking the last item in a stack. */ function last(array) { return array[array.length - 1]; }
34.351617
109
0.562783
PenTesting
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from './src/ReactFlightDOMClientNode';
22
66
0.702381
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import 'regenerator-runtime/runtime'; import type {TimelineEvent} from '@elg/speedscope'; import type {ImportWorkerOutputData} from './index'; import preprocessData from './preprocessData'; import {readInputData} from './readInputData'; import InvalidProfileError from './InvalidProfileError'; export async function importFile(file: File): Promise<ImportWorkerOutputData> { try { const readFile = await readInputData(file); const events: TimelineEvent[] = JSON.parse(readFile); if (events.length === 0) { throw new InvalidProfileError('No profiling data found in file.'); } const processedData = await preprocessData(events); return { status: 'SUCCESS', processedData, }; } catch (error) { if (error instanceof InvalidProfileError) { return { status: 'INVALID_PROFILE_ERROR', error, }; } else { return { status: 'UNEXPECTED_ERROR', error, }; } } }
24.06383
79
0.662702
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 {Fragment, useCallback, useState} from 'react'; import ListItem from './ListItem'; import styles from './List.css'; export type Item = { id: number, isComplete: boolean, text: string, }; type Props = {}; export default function List(props: Props): React.Node { const [newItemText, setNewItemText] = useState<string>(''); const [items, setItems] = useState<Array<Item>>([ {id: 1, isComplete: true, text: 'First'}, {id: 2, isComplete: true, text: 'Second'}, {id: 3, isComplete: false, text: 'Third'}, ]); const [uid, setUID] = useState<number>(4); const handleClick = useCallback(() => { if (newItemText !== '') { setItems([ ...items, { id: uid, isComplete: false, text: newItemText, }, ]); setUID(uid + 1); setNewItemText(''); } }, [newItemText, items, uid]); const handleKeyPress = useCallback( (event: $FlowFixMe) => { if (event.key === 'Enter') { handleClick(); } }, [handleClick], ); const handleChange = useCallback( (event: $FlowFixMe) => { setNewItemText(event.currentTarget.value); }, [setNewItemText], ); const removeItem = useCallback( (itemToRemove: $FlowFixMe) => setItems(items.filter(item => item !== itemToRemove)), [items], ); const toggleItem = useCallback( (itemToToggle: $FlowFixMe) => { // 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 ( <Fragment> <h1>List</h1> <input type="text" placeholder="New list item..." className={styles.Input} value={newItemText} onChange={handleChange} onKeyPress={handleKeyPress} /> <button className={styles.IconButton} disabled={newItemText === ''} onClick={handleClick}> <span role="img" aria-label="Add item"> ➕ </span> </button> <ul className={styles.List}> {items.map(item => ( <ListItem key={item.id} item={item} removeItem={removeItem} toggleItem={toggleItem} /> ))} </ul> </Fragment> ); }
22.383333
73
0.550802
owtf
import Fixture from '../../Fixture'; const React = window.React; class InputPlaceholderFixture extends React.Component { constructor(props, context) { super(props, context); this.state = { placeholder: 'A placeholder', changeCount: 0, }; } handleChange = () => { this.setState(({changeCount}) => { return { changeCount: changeCount + 1, }; }); }; handleGeneratePlaceholder = () => { this.setState({ placeholder: `A placeholder: ${Math.random() * 100}`, }); }; handleReset = () => { this.setState({ changeCount: 0, }); }; render() { const {placeholder, changeCount} = this.state; const color = changeCount === 0 ? 'green' : 'red'; return ( <Fixture> <input type="text" placeholder={placeholder} onChange={this.handleChange} />{' '} <button onClick={this.handleGeneratePlaceholder}> Change placeholder </button> <p style={{color}}> <code>onChange</code> {' calls: '} <strong>{changeCount}</strong> </p> <button onClick={this.handleReset}>Reset count</button> </Fixture> ); } } export default InputPlaceholderFixture;
20.644068
63
0.550157
Hands-On-Penetration-Testing-with-Python
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; import {useContext} from 'react'; import {createPortal} from 'react-dom'; import ErrorBoundary from './ErrorBoundary'; import {StoreContext} from './context'; import ThemeProvider from './ThemeProvider'; export type Props = {portalContainer?: Element, ...}; export default function portaledContent( Component: React$AbstractComponent<any>, ): React$AbstractComponent<any> { return function PortaledContent({portalContainer, ...rest}: Props) { const store = useContext(StoreContext); let children = ( <ErrorBoundary store={store}> <Component {...rest} /> </ErrorBoundary> ); if (portalContainer != null) { // The ThemeProvider works by writing DOM style variables to an HTMLDivElement. // Because Portals render in a different DOM subtree, these variables don't propagate. // So in this case, we need to re-wrap portaled content in a second ThemeProvider. children = ( <ThemeProvider> <div data-react-devtools-portal-root={true} style={{width: '100vw', height: '100vh'}}> {children} </div> </ThemeProvider> ); } return portalContainer != null ? createPortal(children, portalContainer) : children; }; }
28.54902
92
0.654714
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 {readModule} from 'react-noop-renderer/flight-modules'; import ReactFlightClient from 'react-client/flight'; type Source = Array<Uint8Array>; const decoderOptions = {stream: true}; const {createResponse, processBinaryChunk, getRoot, close} = ReactFlightClient({ createStringDecoder() { return new TextDecoder(); }, readPartialStringChunk(decoder: TextDecoder, buffer: Uint8Array): string { return decoder.decode(buffer, decoderOptions); }, readFinalStringChunk(decoder: TextDecoder, buffer: Uint8Array): string { return decoder.decode(buffer); }, resolveClientReference(bundlerConfig: null, idx: string) { return idx; }, prepareDestinationForModule(moduleLoading: null, metadata: string) {}, preloadModule(idx: string) {}, requireModule(idx: string) { return readModule(idx); }, parseModel(response: Response, json) { return JSON.parse(json, response._fromJSON); }, }); function read<T>(source: Source): Thenable<T> { const response = createResponse(source, null); for (let i = 0; i < source.length; i++) { processBinaryChunk(response, source[i], 0); } close(response); return getRoot(response); } export {read};
27.293103
80
0.717683
Hands-On-Penetration-Testing-with-Python
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; import useThemeStyles from './useThemeStyles'; export default function ThemeProvider({ children, }: { children: React.Node, }): React.Node { const themeStyle = useThemeStyles(); const style = React.useMemo(() => { return { ...themeStyle, width: '100%', height: '100%', }; }, [themeStyle]); return <div style={style}>{children}</div>; }
19.466667
66
0.639478
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ 'use strict'; export * from './src/forks/SchedulerNative';
19.384615
66
0.689394
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 */ 'use strict'; export * from './src/ReactFiberTreeReflection';
19.615385
66
0.696629
owtf
import React from 'react'; import {useContext} from 'react'; import {Link} from 'react-router-dom'; import ThemeContext from './shared/ThemeContext'; import Clock from './shared/Clock'; export default function HomePage({counter, dispatch}) { const theme = useContext(ThemeContext); return ( <> <h2>src/modern/HomePage.js</h2> <h3 style={{color: theme}}> This component is rendered by the outer React ({React.version}). </h3> <Clock /> <b> <Link to="/about">Go to About</Link> </b> </> ); }
23.304348
72
0.616487
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'; class Custom { _number = 42; get number(): number { return this._number; } } export default function CustomObject(): React.Node { return <ChildComponent customObject={new Custom()} />; } function ChildComponent(props: any) { return null; }
18
66
0.679513
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Thenable} from 'shared/ReactTypes'; import type {RendererTask} from './ReactCurrentActQueue'; import ReactCurrentActQueue from './ReactCurrentActQueue'; import queueMacrotask from 'shared/enqueueTask'; // `act` calls can be nested, so we track the depth. This represents the // number of `act` scopes on the stack. let actScopeDepth = 0; // We only warn the first time you neglect to await an async `act` scope. let didWarnNoAwaitAct = false; export function act<T>(callback: () => T | Thenable<T>): Thenable<T> { if (__DEV__) { // When ReactCurrentActQueue.current is not null, it signals to React that // we're currently inside an `act` scope. React will push all its tasks to // this queue instead of scheduling them with platform APIs. // // We set this to an empty array when we first enter an `act` scope, and // only unset it once we've left the outermost `act` scope — remember that // `act` calls can be nested. // // If we're already inside an `act` scope, reuse the existing queue. const prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy; const prevActQueue = ReactCurrentActQueue.current; const prevActScopeDepth = actScopeDepth; actScopeDepth++; const queue = (ReactCurrentActQueue.current = prevActQueue !== null ? prevActQueue : []); // Used to reproduce behavior of `batchedUpdates` in legacy mode. Only // set to `true` while the given callback is executed, not for updates // triggered during an async event, because this is how the legacy // implementation of `act` behaved. ReactCurrentActQueue.isBatchingLegacy = true; let result; // This tracks whether the `act` call is awaited. In certain cases, not // awaiting it is a mistake, so we will detect that and warn. let didAwaitActCall = false; try { // Reset this to `false` right before entering the React work loop. The // only place we ever read this fields is just below, right after running // the callback. So we don't need to reset after the callback runs. ReactCurrentActQueue.didScheduleLegacyUpdate = false; result = callback(); const didScheduleLegacyUpdate = ReactCurrentActQueue.didScheduleLegacyUpdate; // Replicate behavior of original `act` implementation in legacy mode, // which flushed updates immediately after the scope function exits, even // if it's an async function. if (!prevIsBatchingLegacy && didScheduleLegacyUpdate) { flushActQueue(queue); } // `isBatchingLegacy` gets reset using the regular stack, not the async // one used to track `act` scopes. Why, you may be wondering? Because // that's how it worked before version 18. Yes, it's confusing! We should // delete legacy mode!! ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy; } catch (error) { // `isBatchingLegacy` gets reset using the regular stack, not the async // one used to track `act` scopes. Why, you may be wondering? Because // that's how it worked before version 18. Yes, it's confusing! We should // delete legacy mode!! ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy; popActScope(prevActQueue, prevActScopeDepth); throw error; } if ( result !== null && typeof result === 'object' && // $FlowFixMe[method-unbinding] typeof result.then === 'function' ) { // A promise/thenable was returned from the callback. Wait for it to // resolve before flushing the queue. // // If `act` were implemented as an async function, this whole block could // be a single `await` call. That's really the only difference between // this branch and the next one. const thenable = ((result: any): Thenable<T>); // Warn if the an `act` call with an async scope is not awaited. In a // future release, consider making this an error. queueSeveralMicrotasks(() => { if (!didAwaitActCall && !didWarnNoAwaitAct) { didWarnNoAwaitAct = true; console.error( 'You called act(async () => ...) without await. ' + 'This could lead to unexpected testing behaviour, ' + 'interleaving multiple act calls and mixing their ' + 'scopes. ' + 'You should - await act(async () => ...);', ); } }); return { then(resolve: T => mixed, reject: mixed => mixed) { didAwaitActCall = true; thenable.then( returnValue => { popActScope(prevActQueue, prevActScopeDepth); if (prevActScopeDepth === 0) { // We're exiting the outermost `act` scope. Flush the queue. try { flushActQueue(queue); queueMacrotask(() => // Recursively flush tasks scheduled by a microtask. recursivelyFlushAsyncActWork(returnValue, resolve, reject), ); } catch (error) { // `thenable` might not be a real promise, and `flushActQueue` // might throw, so we need to wrap `flushActQueue` in a // try/catch. reject(error); } } else { resolve(returnValue); } }, error => { popActScope(prevActQueue, prevActScopeDepth); reject(error); }, ); }, }; } else { const returnValue: T = (result: any); // The callback is not an async function. Exit the current // scope immediately. popActScope(prevActQueue, prevActScopeDepth); if (prevActScopeDepth === 0) { // We're exiting the outermost `act` scope. Flush the queue. flushActQueue(queue); // If the queue is not empty, it implies that we intentionally yielded // to the main thread, because something suspended. We will continue // in an asynchronous task. // // Warn if something suspends but the `act` call is not awaited. // In a future release, consider making this an error. if (queue.length !== 0) { queueSeveralMicrotasks(() => { if (!didAwaitActCall && !didWarnNoAwaitAct) { didWarnNoAwaitAct = true; console.error( 'A component suspended inside an `act` scope, but the ' + '`act` call was not awaited. When testing React ' + 'components that depend on asynchronous data, you must ' + 'await the result:\n\n' + 'await act(() => ...)', ); } }); } // Like many things in this module, this is next part is confusing. // // We do not currently require every `act` call that is passed a // callback to be awaited, through arguably we should. Since this // callback was synchronous, we need to exit the current scope before // returning. // // However, if thenable we're about to return *is* awaited, we'll // immediately restore the current scope. So it shouldn't observable. // // This doesn't affect the case where the scope callback is async, // because we always require those calls to be awaited. // // TODO: In a future version, consider always requiring all `act` calls // to be awaited, regardless of whether the callback is sync or async. ReactCurrentActQueue.current = null; } return { then(resolve: T => mixed, reject: mixed => mixed) { didAwaitActCall = true; if (prevActScopeDepth === 0) { // If the `act` call is awaited, restore the queue we were // using before (see long comment above) so we can flush it. ReactCurrentActQueue.current = queue; queueMacrotask(() => // Recursively flush tasks scheduled by a microtask. recursivelyFlushAsyncActWork(returnValue, resolve, reject), ); } else { resolve(returnValue); } }, }; } } else { throw new Error('act(...) is not supported in production builds of React.'); } } function popActScope( prevActQueue: null | Array<RendererTask>, prevActScopeDepth: number, ) { if (__DEV__) { if (prevActScopeDepth !== actScopeDepth - 1) { console.error( 'You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. ', ); } actScopeDepth = prevActScopeDepth; } } function recursivelyFlushAsyncActWork<T>( returnValue: T, resolve: T => mixed, reject: mixed => mixed, ) { if (__DEV__) { // Check if any tasks were scheduled asynchronously. const queue = ReactCurrentActQueue.current; if (queue !== null) { if (queue.length !== 0) { // Async tasks were scheduled, mostly likely in a microtask. // Keep flushing until there are no more. try { flushActQueue(queue); // The work we just performed may have schedule additional async // tasks. Wait a macrotask and check again. queueMacrotask(() => recursivelyFlushAsyncActWork(returnValue, resolve, reject), ); } catch (error) { // Leave remaining tasks on the queue if something throws. reject(error); } } else { // The queue is empty. We can finish. ReactCurrentActQueue.current = null; resolve(returnValue); } } else { resolve(returnValue); } } } let isFlushing = false; function flushActQueue(queue: Array<RendererTask>) { if (__DEV__) { if (!isFlushing) { // Prevent re-entrance. isFlushing = true; let i = 0; try { for (; i < queue.length; i++) { let callback: RendererTask = queue[i]; do { ReactCurrentActQueue.didUsePromise = false; const continuation = callback(false); if (continuation !== null) { if (ReactCurrentActQueue.didUsePromise) { // The component just suspended. Yield to the main thread in // case the promise is already resolved. If so, it will ping in // a microtask and we can resume without unwinding the stack. queue[i] = callback; queue.splice(0, i); return; } callback = continuation; } else { break; } } while (true); } // We flushed the entire queue. queue.length = 0; } catch (error) { // If something throws, leave the remaining callbacks on the queue. queue.splice(0, i + 1); throw error; } finally { isFlushing = false; } } } } // Some of our warnings attempt to detect if the `act` call is awaited by // checking in an asynchronous task. Wait a few microtasks before checking. The // only reason one isn't sufficient is we want to accommodate the case where an // `act` call is returned from an async function without first being awaited, // since that's a somewhat common pattern. If you do this too many times in a // nested sequence, you might get a warning, but you can always fix by awaiting // the call. // // A macrotask would also work (and is the fallback) but depending on the test // environment it may cause the warning to fire too late. const queueSeveralMicrotasks = typeof queueMicrotask === 'function' ? (callback: () => void) => { queueMicrotask(() => queueMicrotask(callback)); } : queueMacrotask;
37.742038
80
0.601776
owtf
/** @license React v0.14.10 * react-jsx-runtime.development.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; if (process.env.NODE_ENV !== "production") { (function() { 'use strict'; var React = require('react'); // ATTENTION // When adding new symbols to this file, // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = 0xeac7; var REACT_PORTAL_TYPE = 0xeaca; exports.Fragment = 0xeacb; var REACT_STRICT_MODE_TYPE = 0xeacc; var REACT_PROFILER_TYPE = 0xead2; var REACT_PROVIDER_TYPE = 0xeacd; var REACT_CONTEXT_TYPE = 0xeace; var REACT_FORWARD_REF_TYPE = 0xead0; var REACT_SUSPENSE_TYPE = 0xead1; var REACT_SUSPENSE_LIST_TYPE = 0xead8; var REACT_MEMO_TYPE = 0xead3; var REACT_LAZY_TYPE = 0xead4; var REACT_BLOCK_TYPE = 0xead9; var REACT_SERVER_BLOCK_TYPE = 0xeada; var REACT_FUNDAMENTAL_TYPE = 0xead5; var REACT_SCOPE_TYPE = 0xead7; var REACT_OPAQUE_ID_TYPE = 0xeae0; var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1; var REACT_OFFSCREEN_TYPE = 0xeae2; var REACT_LEGACY_HIDDEN_TYPE = 0xeae3; if (typeof Symbol === 'function' && Symbol.for) { var symbolFor = Symbol.for; REACT_ELEMENT_TYPE = symbolFor('react.element'); REACT_PORTAL_TYPE = symbolFor('react.portal'); exports.Fragment = symbolFor('react.fragment'); REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode'); REACT_PROFILER_TYPE = symbolFor('react.profiler'); REACT_PROVIDER_TYPE = symbolFor('react.provider'); REACT_CONTEXT_TYPE = symbolFor('react.context'); REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref'); REACT_SUSPENSE_TYPE = symbolFor('react.suspense'); REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list'); REACT_MEMO_TYPE = symbolFor('react.memo'); REACT_LAZY_TYPE = symbolFor('react.lazy'); REACT_BLOCK_TYPE = symbolFor('react.block'); REACT_SERVER_BLOCK_TYPE = symbolFor('react.server.block'); REACT_FUNDAMENTAL_TYPE = symbolFor('react.fundamental'); REACT_SCOPE_TYPE = symbolFor('react.scope'); REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id'); REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode'); REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen'); REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden'); } var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== 'object') { return null; } var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof maybeIterator === 'function') { return maybeIterator; } return null; } function error(format) { { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } printWarning('error', format, args); } } function printWarning(level, format, args) { // When changing this logic, you might want to also // update consoleWithStackDev.www.js as well. { var stack = ''; if (stack !== '') { format += '%s'; args = args.concat([stack]); } var argsWithFormat = args.map(function (item) { return '' + item; }); // Careful: RN currently depends on this prefix argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it // breaks IE9: https://github.com/facebook/react/issues/13610 // eslint-disable-next-line react-internal/no-production-logging Function.prototype.apply.call(console[level], console, argsWithFormat); } } // Filter certain DOM attributes (e.g. src, href) if their values are empty strings. var enableScopeAPI = false; // Experimental Create Event Handle API. function isValidElementType(type) { if (typeof type === 'string' || typeof type === 'function') { return true; } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). if (type === exports.Fragment || type === REACT_PROFILER_TYPE || type === REACT_DEBUG_TRACING_MODE_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || type === REACT_LEGACY_HIDDEN_TYPE || enableScopeAPI ) { return true; } if (typeof type === 'object' && type !== null) { if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_BLOCK_TYPE || type[0] === REACT_SERVER_BLOCK_TYPE) { return true; } } return false; } var BEFORE_SLASH_RE = /^(.*)[\\\/]/; function describeComponentFrame (name, source, ownerName) { var sourceInfo = ''; if (source) { var path = source.fileName; var fileName = path.replace(BEFORE_SLASH_RE, ''); { // In DEV, include code for a common special case: // prefer "folder/index.js" instead of just "index.js". if (/^index\./.test(fileName)) { var match = path.match(BEFORE_SLASH_RE); if (match) { var pathBeforeSlash = match[1]; if (pathBeforeSlash) { var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, ''); fileName = folderName + '/' + fileName; } } } } sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')'; } else if (ownerName) { sourceInfo = ' (created by ' + ownerName + ')'; } return '\n in ' + (name || 'Unknown') + sourceInfo; } var Resolved = 1; function refineResolvedLazyComponent(lazyComponent) { return lazyComponent._status === Resolved ? lazyComponent._result : null; } function getWrappedName(outerType, innerType, wrapperName) { var functionName = innerType.displayName || innerType.name || ''; return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName); } function getComponentName(type) { if (type == null) { // Host root, text node or just invalid type. return null; } { if (typeof type.tag === 'number') { error('Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.'); } } if (typeof type === 'function') { return type.displayName || type.name || null; } if (typeof type === 'string') { return type; } switch (type) { case exports.Fragment: return 'Fragment'; case REACT_PORTAL_TYPE: return 'Portal'; case REACT_PROFILER_TYPE: return "Profiler"; case REACT_STRICT_MODE_TYPE: return 'StrictMode'; case REACT_SUSPENSE_TYPE: return 'Suspense'; case REACT_SUSPENSE_LIST_TYPE: return 'SuspenseList'; } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_CONTEXT_TYPE: return 'Context.Consumer'; case REACT_PROVIDER_TYPE: return 'Context.Provider'; case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, 'ForwardRef'); case REACT_MEMO_TYPE: return getComponentName(type.type); case REACT_BLOCK_TYPE: return getComponentName(type.render); case REACT_LAZY_TYPE: { var thenable = type; var resolvedThenable = refineResolvedLazyComponent(thenable); if (resolvedThenable) { return getComponentName(resolvedThenable); } break; } } } return null; } var loggedTypeFailures = {}; var currentlyValidatingElement = null; function setCurrentlyValidatingElement(element) { { currentlyValidatingElement = element; } } function checkPropTypes(typeSpecs, values, location, componentName, element) { { // $FlowFixMe This is okay but Flow doesn't know it. var has = Function.call.bind(Object.prototype.hasOwnProperty); for (var typeSpecName in typeSpecs) { if (has(typeSpecs, typeSpecName)) { var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if (typeof typeSpecs[typeSpecName] !== 'function') { var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); err.name = 'Invariant Violation'; throw err; } error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); } catch (ex) { error$1 = ex; } if (error$1 && !(error$1 instanceof Error)) { setCurrentlyValidatingElement(element); error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); setCurrentlyValidatingElement(null); } if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error$1.message] = true; setCurrentlyValidatingElement(element); error('Failed %s type: %s', location, error$1.message); setCurrentlyValidatingElement(null); } } } } } var ReactCurrentOwner = require('react/lib/ReactCurrentOwner'); var hasOwnProperty = Object.prototype.hasOwnProperty; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown; var specialPropRefWarningShown; var didWarnAboutStringRefs; { didWarnAboutStringRefs = {}; } function hasValidRef(config) { { if (hasOwnProperty.call(config, 'ref')) { var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== undefined; } function hasValidKey(config) { { if (hasOwnProperty.call(config, 'key')) { var getter = Object.getOwnPropertyDescriptor(config, 'key').get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== undefined; } function defineKeyPropWarningGetter(props, displayName) { { var warnAboutAccessingKey = function () { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, 'key', { get: warnAboutAccessingKey, configurable: true }); } } function defineRefPropWarningGetter(props, displayName) { { var warnAboutAccessingRef = function () { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, 'ref', { get: warnAboutAccessingRef, configurable: true }); } } /** * Factory method to create a new React element. This no longer adheres to * the class pattern, so do not use new to call it. Also, instanceof check * will not work. Instead test $$typeof field against Symbol.for('react.element') to check * if something is a React Element. * * @param {*} type * @param {*} props * @param {*} key * @param {string|object} ref * @param {*} owner * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allows us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; /** * https://github.com/reactjs/rfcs/pull/107 * @param {*} type * @param {object} props * @param {string} key */ function jsxDEV(type, config, maybeKey, source, self) { { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; // Currently, key can be spread in as a prop. This causes a potential // issue if key is also explicitly declared (ie. <div {...props} key="Hi" /> // or <div key="Hi" {...props} /> ). We want to deprecate key spread, // but as an intermediary step, we will use jsxDEV for everything except // <div {...props} key="Hi" />, because we aren't currently able to tell if // key is explicitly declared to be undefined or not. if (maybeKey !== undefined) { key = '' + maybeKey; } if (hasValidKey(config)) { key = '' + config.key; } if (hasValidRef(config)) { ref = config.ref; } // Remaining properties are added to a new props object for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } if (key || ref) { var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); } } var ReactCurrentOwner$1 = require('react/lib/ReactCurrentOwner'); function setCurrentlyValidatingElement$1(element) { currentlyValidatingElement = element; } var propTypesMisspellWarningShown; { propTypesMisspellWarningShown = false; } /** * Verifies the object is a ReactElement. * See https://reactjs.org/docs/react-api.html#isvalidelement * @param {?object} object * @return {boolean} True if `object` is a ReactElement. * @final */ function isValidElement(object) { { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } } function getDeclarationErrorAddendum() { { if (ReactCurrentOwner$1.current) { var name = ReactCurrentOwner$1.current.getName(); if (name) { return '\n\nCheck the render method of `' + name + '`.'; } } return ''; } } function getSourceInfoErrorAddendum(source) { { if (source !== undefined) { var fileName = source.fileName.replace(/^.*[\\\/]/, ''); var lineNumber = source.lineNumber; return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.'; } return ''; } } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { info = "\n\nCheck the top-level render call using <" + parentName + ">."; } } return info; } } /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. Error statuses are cached so a warning * will only be shown once. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { return; } ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. var childOwner = ''; if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) { // Give the component that originally created this child. childOwner = " It was passed a child from " + element._owner.getName() + "."; } setCurrentlyValidatingElement$1(element); error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); setCurrentlyValidatingElement$1(null); } } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ function validateChildKeys(node, parentType) { { if (typeof node !== 'object') { return; } if (Array.isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (isValidElement(node)) { // This element was passed in a valid location. if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); if (typeof iteratorFn === 'function') { // Entry iterators used to provide implicit keys, // but now we print a separate warning for them later. if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { { var type = element.type; if (type === null || type === undefined || typeof type === 'string') { return; } var propTypes; if (typeof type === 'function') { propTypes = type.propTypes; } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. // Inner props are checked in the reconciler. type.$$typeof === REACT_MEMO_TYPE)) { propTypes = type.propTypes; } else { return; } if (propTypes) { // Intentionally inside to avoid triggering lazy initializers: var name = getComponentName(type); checkPropTypes(propTypes, element.props, 'prop', name, element); } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers: var _name = getComponentName(type); error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown'); } if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) { error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.'); } } } /** * Given a fragment, validate that it can only be provided with fragment props * @param {ReactElement} fragment */ function validateFragmentProps(fragment) { { var keys = Object.keys(fragment.props); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (key !== 'children' && key !== 'key') { setCurrentlyValidatingElement$1(fragment); error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key); setCurrentlyValidatingElement$1(null); break; } } if (fragment.ref !== null) { setCurrentlyValidatingElement$1(fragment); error('Invalid attribute `ref` supplied to `React.Fragment`.'); setCurrentlyValidatingElement$1(null); } } } function jsxWithValidation(type, props, key, isStaticChildren, source, self) { { var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. if (!validType) { var info = ''; if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports."; } var sourceInfo = getSourceInfoErrorAddendum(source); if (sourceInfo) { info += sourceInfo; } else { info += getDeclarationErrorAddendum(); } var typeString; if (type === null) { typeString = 'null'; } else if (Array.isArray(type)) { typeString = 'array'; } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { typeString = "<" + (getComponentName(type.type) || 'Unknown') + " />"; info = ' Did you accidentally export a JSX literal instead of a component?'; } else { typeString = typeof type; } error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info); } var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { var children = props.children; if (children !== undefined) { if (isStaticChildren) { if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { validateChildKeys(children[i], type); } if (Object.freeze) { Object.freeze(children); } } else { error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.'); } } else { validateChildKeys(children, type); } } } if (type === exports.Fragment) { validateFragmentProps(element); } else { validatePropTypes(element); } return element; } } // These two functions exist to still get child warnings in dev // even with the prod transform. This means that jsxDEV is purely // opt-in behavior for better messages but that we won't stop // giving you warnings if you use production apis. function jsxWithValidationStatic(type, props, key) { { return jsxWithValidation(type, props, key, true); } } function jsxWithValidationDynamic(type, props, key) { { return jsxWithValidation(type, props, key, false); } } var jsx = jsxWithValidationDynamic ; // we may want to special case jsxs internally to take advantage of static children. // for now we can ship identical prod functions var jsxs = jsxWithValidationStatic ; exports.jsx = jsx; exports.jsxs = jsxs; })(); }
30.368778
397
0.648166
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 */ /* eslint-disable no-func-assign */ 'use strict'; describe('useRef', () => { let React; let ReactNoop; let Scheduler; let act; let useCallback; let useEffect; let useLayoutEffect; let useRef; let useState; let waitForAll; let assertLog; beforeEach(() => { React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); const ReactFeatureFlags = require('shared/ReactFeatureFlags'); ReactFeatureFlags.debugRenderPhaseSideEffectsForStrictMode = false; act = require('internal-test-utils').act; useCallback = React.useCallback; useEffect = React.useEffect; useLayoutEffect = React.useLayoutEffect; useRef = React.useRef; useState = React.useState; const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; assertLog = InternalTestUtils.assertLog; }); function Text(props) { Scheduler.log(props.text); return <span prop={props.text} />; } it('creates a ref object initialized with the provided value', async () => { jest.useFakeTimers(); function useDebouncedCallback(callback, ms, inputs) { const timeoutID = useRef(-1); useEffect(() => { return function unmount() { clearTimeout(timeoutID.current); }; }, []); const debouncedCallback = useCallback( (...args) => { clearTimeout(timeoutID.current); timeoutID.current = setTimeout(callback, ms, ...args); }, [callback, ms], ); return useCallback(debouncedCallback, inputs); } let ping; function App() { ping = useDebouncedCallback( value => { Scheduler.log('ping: ' + value); }, 100, [], ); return null; } await act(() => { ReactNoop.render(<App />); }); assertLog([]); ping(1); ping(2); ping(3); assertLog([]); jest.advanceTimersByTime(100); assertLog(['ping: 3']); ping(4); jest.advanceTimersByTime(20); ping(5); ping(6); jest.advanceTimersByTime(80); assertLog([]); jest.advanceTimersByTime(20); assertLog(['ping: 6']); }); it('should return the same ref during re-renders', async () => { function Counter() { const ref = useRef('val'); const [count, setCount] = useState(0); const [firstRef] = useState(ref); if (firstRef !== ref) { throw new Error('should never change'); } if (count < 3) { setCount(count + 1); } return <Text text={count} />; } ReactNoop.render(<Counter />); await waitForAll([3]); ReactNoop.render(<Counter />); await waitForAll([3]); }); if (__DEV__) { it('should never warn when attaching to children', async () => { class Component extends React.Component { render() { return null; } } function Example({phase}) { const hostRef = useRef(); const classRef = useRef(); return ( <> <div key={`host-${phase}`} ref={hostRef} /> <Component key={`class-${phase}`} ref={classRef} /> </> ); } await act(() => { ReactNoop.render(<Example phase="mount" />); }); await act(() => { ReactNoop.render(<Example phase="update" />); }); }); // @gate enableUseRefAccessWarning it('should warn about reads during render', async () => { function Example() { const ref = useRef(123); let value; expect(() => { value = ref.current; }).toWarnDev([ 'Example: Unsafe read of a mutable value during render.', ]); return value; } await act(() => { ReactNoop.render(<Example />); }); }); it('should not warn about lazy init during render', async () => { function Example() { const ref1 = useRef(null); const ref2 = useRef(undefined); // Read: safe because lazy init: if (ref1.current === null) { ref1.current = 123; } if (ref2.current === undefined) { ref2.current = 123; } return null; } await act(() => { ReactNoop.render(<Example />); }); // Should not warn after an update either. await act(() => { ReactNoop.render(<Example />); }); }); it('should not warn about lazy init outside of render', async () => { function Example() { // eslint-disable-next-line no-unused-vars const [didMount, setDidMount] = useState(false); const ref1 = useRef(null); const ref2 = useRef(undefined); useLayoutEffect(() => { ref1.current = 123; ref2.current = 123; setDidMount(true); }, []); return null; } await act(() => { ReactNoop.render(<Example />); }); }); // @gate enableUseRefAccessWarning it('should warn about unconditional lazy init during render', async () => { function Example() { const ref1 = useRef(null); const ref2 = useRef(undefined); if (shouldExpectWarning) { expect(() => { ref1.current = 123; }).toWarnDev([ 'Example: Unsafe write of a mutable value during render', ]); expect(() => { ref2.current = 123; }).toWarnDev([ 'Example: Unsafe write of a mutable value during render', ]); } else { ref1.current = 123; ref1.current = 123; } // But only warn once ref1.current = 345; ref1.current = 345; return null; } let shouldExpectWarning = true; await act(() => { ReactNoop.render(<Example />); }); // Should not warn again on update. shouldExpectWarning = false; await act(() => { ReactNoop.render(<Example />); }); }); // @gate enableUseRefAccessWarning it('should warn about reads to ref after lazy init pattern', async () => { function Example() { const ref1 = useRef(null); const ref2 = useRef(undefined); // Read 1: safe because lazy init: if (ref1.current === null) { ref1.current = 123; } if (ref2.current === undefined) { ref2.current = 123; } let value; expect(() => { value = ref1.current; }).toWarnDev(['Example: Unsafe read of a mutable value during render']); expect(() => { value = ref2.current; }).toWarnDev(['Example: Unsafe read of a mutable value during render']); // But it should only warn once. value = ref1.current; value = ref2.current; return value; } await act(() => { ReactNoop.render(<Example />); }); }); // @gate enableUseRefAccessWarning it('should warn about writes to ref after lazy init pattern', async () => { function Example() { const ref1 = useRef(null); const ref2 = useRef(undefined); // Read: safe because lazy init: if (ref1.current === null) { ref1.current = 123; } if (ref2.current === undefined) { ref2.current = 123; } expect(() => { ref1.current = 456; }).toWarnDev([ 'Example: Unsafe write of a mutable value during render', ]); expect(() => { ref2.current = 456; }).toWarnDev([ 'Example: Unsafe write of a mutable value during render', ]); return null; } await act(() => { ReactNoop.render(<Example />); }); }); it('should not warn about reads or writes within effect', async () => { function Example() { const ref = useRef(123); useLayoutEffect(() => { expect(ref.current).toBe(123); ref.current = 456; expect(ref.current).toBe(456); }, []); useEffect(() => { expect(ref.current).toBe(456); ref.current = 789; expect(ref.current).toBe(789); }, []); return null; } await act(() => { ReactNoop.render(<Example />); }); ReactNoop.flushPassiveEffects(); }); it('should not warn about reads or writes outside of render phase (e.g. event handler)', async () => { let ref; function Example() { ref = useRef(123); return null; } await act(() => { ReactNoop.render(<Example />); }); expect(ref.current).toBe(123); ref.current = 456; expect(ref.current).toBe(456); }); } });
23.552561
106
0.530413
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Fiber} from 'react-reconciler/src/ReactInternalTypes'; import {getFiberCurrentPropsFromNode} from './legacy-events/EventPluginUtils'; export default function getListener( inst: Fiber, registrationName: string, ): Function | null { const stateNode = inst.stateNode; if (stateNode === null) { // Work in progress (ex: onload events in incremental mode). return null; } const props = getFiberCurrentPropsFromNode(stateNode); if (props === null) { // Work in progress. return null; } const listener = props[registrationName]; if (listener && typeof listener !== 'function') { throw new Error( `Expected \`${registrationName}\` listener to be a function, instead got a value of \`${typeof listener}\` type.`, ); } return listener; }
25.421053
120
0.686939
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 EventEmitter from '../events'; import {prepareProfilingDataFrontendFromBackendAndStore} from './views/Profiler/utils'; import ProfilingCache from './ProfilingCache'; import Store from './store'; import type {FrontendBridge} from 'react-devtools-shared/src/bridge'; import type {ProfilingDataBackend} from 'react-devtools-shared/src/backend/types'; import type { CommitDataFrontend, ProfilingDataForRootFrontend, ProfilingDataFrontend, SnapshotNode, } from './views/Profiler/types'; export default class ProfilerStore extends EventEmitter<{ isProcessingData: [], isProfiling: [], profilingData: [], }> { _bridge: FrontendBridge; // Suspense cache for lazily calculating derived profiling data. _cache: ProfilingCache; // Temporary store of profiling data from the backend renderer(s). // This data will be converted to the ProfilingDataFrontend format after being collected from all renderers. _dataBackends: Array<ProfilingDataBackend> = []; // Data from the most recently completed profiling session, // or data that has been imported from a previously exported session. // This object contains all necessary data to drive the Profiler UI interface, // even though some of it is lazily parsed/derived via the ProfilingCache. _dataFrontend: ProfilingDataFrontend | null = null; // Snapshot of all attached renderer IDs. // Once profiling is finished, this snapshot will be used to query renderers for profiling data. // // This map is initialized when profiling starts and updated when a new root is added while profiling; // Upon completion, it is converted into the exportable ProfilingDataFrontend format. _initialRendererIDs: Set<number> = new Set(); // Snapshot of the state of the main Store (including all roots) when profiling started. // Once profiling is finished, this snapshot can be used along with "operations" messages emitted during profiling, // to reconstruct the state of each root for each commit. // It's okay to use a single root to store this information because node IDs are unique across all roots. // // This map is initialized when profiling starts and updated when a new root is added while profiling; // Upon completion, it is converted into the exportable ProfilingDataFrontend format. _initialSnapshotsByRootID: Map<number, Map<number, SnapshotNode>> = new Map(); // Map of root (id) to a list of tree mutation that occur during profiling. // Once profiling is finished, these mutations can be used, along with the initial tree snapshots, // to reconstruct the state of each root for each commit. // // This map is only updated while profiling is in progress; // Upon completion, it is converted into the exportable ProfilingDataFrontend format. _inProgressOperationsByRootID: Map<number, Array<Array<number>>> = new Map(); // The backend is currently profiling. // When profiling is in progress, operations are stored so that we can later reconstruct past commit trees. _isProfiling: boolean = false; // Tracks whether a specific renderer logged any profiling data during the most recent session. _rendererIDsThatReportedProfilingData: Set<number> = new Set(); // After profiling, data is requested from each attached renderer using this queue. // So long as this queue is not empty, the store is retrieving and processing profiling data from the backend. _rendererQueue: Set<number> = new Set(); _store: Store; constructor( bridge: FrontendBridge, store: Store, defaultIsProfiling: boolean, ) { super(); this._bridge = bridge; this._isProfiling = defaultIsProfiling; this._store = store; bridge.addListener('operations', this.onBridgeOperations); bridge.addListener('profilingData', this.onBridgeProfilingData); bridge.addListener('profilingStatus', this.onProfilingStatus); bridge.addListener('shutdown', this.onBridgeShutdown); // It's possible that profiling has already started (e.g. "reload and start profiling") // so the frontend needs to ask the backend for its status after mounting. bridge.send('getProfilingStatus'); this._cache = new ProfilingCache(this); } getCommitData(rootID: number, commitIndex: number): CommitDataFrontend { if (this._dataFrontend !== null) { const dataForRoot = this._dataFrontend.dataForRoots.get(rootID); if (dataForRoot != null) { const commitDatum = dataForRoot.commitData[commitIndex]; if (commitDatum != null) { return commitDatum; } } } throw Error( `Could not find commit data for root "${rootID}" and commit "${commitIndex}"`, ); } getDataForRoot(rootID: number): ProfilingDataForRootFrontend { if (this._dataFrontend !== null) { const dataForRoot = this._dataFrontend.dataForRoots.get(rootID); if (dataForRoot != null) { return dataForRoot; } } throw Error(`Could not find commit data for root "${rootID}"`); } // Profiling data has been recorded for at least one root. get didRecordCommits(): boolean { return ( this._dataFrontend !== null && this._dataFrontend.dataForRoots.size > 0 ); } get isProcessingData(): boolean { return this._rendererQueue.size > 0 || this._dataBackends.length > 0; } get isProfiling(): boolean { return this._isProfiling; } get profilingCache(): ProfilingCache { return this._cache; } get profilingData(): ProfilingDataFrontend | null { return this._dataFrontend; } set profilingData(value: ProfilingDataFrontend | null): void { if (this._isProfiling) { console.warn( 'Profiling data cannot be updated while profiling is in progress.', ); return; } this._dataBackends.splice(0); this._dataFrontend = value; this._initialRendererIDs.clear(); this._initialSnapshotsByRootID.clear(); this._inProgressOperationsByRootID.clear(); this._cache.invalidate(); this.emit('profilingData'); } clear(): void { this._dataBackends.splice(0); this._dataFrontend = null; this._initialRendererIDs.clear(); this._initialSnapshotsByRootID.clear(); this._inProgressOperationsByRootID.clear(); this._rendererQueue.clear(); // Invalidate suspense cache if profiling data is being (re-)recorded. // Note that we clear now because any existing data is "stale". this._cache.invalidate(); this.emit('profilingData'); } startProfiling(): void { this._bridge.send('startProfiling', this._store.recordChangeDescriptions); // Don't actually update the local profiling boolean yet! // Wait for onProfilingStatus() to confirm the status has changed. // This ensures the frontend and backend are in sync wrt which commits were profiled. // We do this to avoid mismatches on e.g. CommitTreeBuilder that would cause errors. } stopProfiling(): void { this._bridge.send('stopProfiling'); // Don't actually update the local profiling boolean yet! // Wait for onProfilingStatus() to confirm the status has changed. // This ensures the frontend and backend are in sync wrt which commits were profiled. // We do this to avoid mismatches on e.g. CommitTreeBuilder that would cause errors. } _takeProfilingSnapshotRecursive: ( elementID: number, profilingSnapshots: Map<number, SnapshotNode>, ) => void = (elementID, profilingSnapshots) => { const element = this._store.getElementByID(elementID); if (element !== null) { const snapshotNode: SnapshotNode = { id: elementID, children: element.children.slice(0), displayName: element.displayName, hocDisplayNames: element.hocDisplayNames, key: element.key, type: element.type, }; profilingSnapshots.set(elementID, snapshotNode); element.children.forEach(childID => this._takeProfilingSnapshotRecursive(childID, profilingSnapshots), ); } }; onBridgeOperations: (operations: Array<number>) => void = operations => { // The first two values are always rendererID and rootID const rendererID = operations[0]; const rootID = operations[1]; if (this._isProfiling) { let profilingOperations = this._inProgressOperationsByRootID.get(rootID); if (profilingOperations == null) { profilingOperations = [operations]; this._inProgressOperationsByRootID.set(rootID, profilingOperations); } else { profilingOperations.push(operations); } if (!this._initialRendererIDs.has(rendererID)) { this._initialRendererIDs.add(rendererID); } if (!this._initialSnapshotsByRootID.has(rootID)) { this._initialSnapshotsByRootID.set(rootID, new Map()); } this._rendererIDsThatReportedProfilingData.add(rendererID); } }; onBridgeProfilingData: (dataBackend: ProfilingDataBackend) => void = dataBackend => { if (this._isProfiling) { // This should never happen, but if it does- ignore previous profiling data. return; } const {rendererID} = dataBackend; if (!this._rendererQueue.has(rendererID)) { throw Error( `Unexpected profiling data update from renderer "${rendererID}"`, ); } this._dataBackends.push(dataBackend); this._rendererQueue.delete(rendererID); if (this._rendererQueue.size === 0) { this._dataFrontend = prepareProfilingDataFrontendFromBackendAndStore( this._dataBackends, this._inProgressOperationsByRootID, this._initialSnapshotsByRootID, ); this._dataBackends.splice(0); this.emit('isProcessingData'); } }; onBridgeShutdown: () => void = () => { this._bridge.removeListener('operations', this.onBridgeOperations); this._bridge.removeListener('profilingData', this.onBridgeProfilingData); this._bridge.removeListener('profilingStatus', this.onProfilingStatus); this._bridge.removeListener('shutdown', this.onBridgeShutdown); }; onProfilingStatus: (isProfiling: boolean) => void = isProfiling => { if (isProfiling) { this._dataBackends.splice(0); this._dataFrontend = null; this._initialRendererIDs.clear(); this._initialSnapshotsByRootID.clear(); this._inProgressOperationsByRootID.clear(); this._rendererIDsThatReportedProfilingData.clear(); this._rendererQueue.clear(); // Record all renderer IDs initially too (in case of unmount) // eslint-disable-next-line no-for-of-loops/no-for-of-loops for (const rendererID of this._store.rootIDToRendererID.values()) { if (!this._initialRendererIDs.has(rendererID)) { this._initialRendererIDs.add(rendererID); } } // Record snapshot of tree at the time profiling is started. // This info is required to handle cases of e.g. nodes being removed during profiling. this._store.roots.forEach(rootID => { const profilingSnapshots = new Map<number, SnapshotNode>(); this._initialSnapshotsByRootID.set(rootID, profilingSnapshots); this._takeProfilingSnapshotRecursive(rootID, profilingSnapshots); }); } if (this._isProfiling !== isProfiling) { this._isProfiling = isProfiling; // Invalidate suspense cache if profiling data is being (re-)recorded. // Note that we clear again, in case any views read from the cache while profiling. // (That would have resolved a now-stale value without any profiling data.) this._cache.invalidate(); this.emit('isProfiling'); // If we've just finished a profiling session, we need to fetch data stored in each renderer interface // and re-assemble it on the front-end into a format (ProfilingDataFrontend) that can power the Profiler UI. // During this time, DevTools UI should probably not be interactive. if (!isProfiling) { this._dataBackends.splice(0); this._rendererQueue.clear(); // Only request data from renderers that actually logged it. // This avoids unnecessary bridge requests and also avoids edge case mixed renderer bugs. // (e.g. when v15 and v16 are both present) this._rendererIDsThatReportedProfilingData.forEach(rendererID => { if (!this._rendererQueue.has(rendererID)) { this._rendererQueue.add(rendererID); this._bridge.send('getProfilingData', {rendererID}); } }); this.emit('isProcessingData'); } } }; }
35.597143
117
0.693473
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * @flow */ import type {RefObject} from 'shared/ReactTypes'; // an immutable object with a single mutable value export function createRef(): RefObject { const refObject = { current: null, }; if (__DEV__) { Object.seal(refObject); } return refObject; }
21
66
0.683297
owtf
// Example const x = React.createElement; class ErrorBoundary extends React.Component { static getDerivedStateFromError(error) { return { error: error, }; } componentDidCatch(error, errorInfo) { console.log(error.message, errorInfo.componentStack); this.setState({ componentStack: errorInfo.componentStack, }); } render() { if (this.state && this.state.error) { return x( 'div', null, x('h3', null, this.state.error.message), x('pre', null, this.state.componentStack) ); } return this.props.children; } } function Example() { let state = React.useState(false); return x( ErrorBoundary, null, x( DisplayName, null, x( React.unstable_SuspenseList, null, x( NativeClass, null, x( FrozenClass, null, x( BabelClass, null, x( BabelClassWithFields, null, x( React.Suspense, null, x('div', null, x(Component, null, x(Throw))) ) ) ) ) ) ) ) ); }
17.867647
62
0.469579
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 */ // Keep in sync with https://github.com/facebook/flow/blob/main/lib/react.js export type ComponentType<-P> = React$ComponentType<P>; export type AbstractComponent< -Config, +Instance = mixed, > = React$AbstractComponent<Config, Instance>; export type ElementType = React$ElementType; export type Element<+C> = React$Element<C>; export type Key = React$Key; export type Ref<C> = React$Ref<C>; export type Node = React$Node; export type Context<T> = React$Context<T>; export type Portal = React$Portal; export type ElementProps<C> = React$ElementProps<C>; export type ElementConfig<C> = React$ElementConfig<C>; export type ElementRef<C> = React$ElementRef<C>; export type Config<Props, DefaultProps> = React$Config<Props, DefaultProps>; export type ChildrenArray<+T> = $ReadOnlyArray<ChildrenArray<T>> | T; // Export all exports so that they're available in tests. // We can't use export * from in Flow for some reason. 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, createFactory, createRef, createServerContext, use, forwardRef, isValidElement, lazy, memo, cache, startTransition, unstable_Cache, unstable_DebugTracingMode, unstable_LegacyHidden, unstable_Activity, unstable_Scope, unstable_SuspenseList, unstable_TracingMarker, unstable_getCacheSignal, unstable_getCacheForType, unstable_useCacheRefresh, unstable_useMemoCache, useId, useCallback, useContext, useDebugValue, useDeferredValue, useEffect, experimental_useEffectEvent, useImperativeHandle, useInsertionEffect, useLayoutEffect, useMemo, useOptimistic, useSyncExternalStore, useReducer, useRef, useState, useTransition, version, } from './src/React';
23.797619
76
0.741595
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; const rule = require('../no-production-logging'); const {RuleTester} = require('eslint'); const ruleTester = new RuleTester(); ruleTester.run('no-production-logging', rule, { valid: [ { code: ` if (__DEV__) { console.error('Oh no'); } `, }, { code: ` if (__DEV__) { console.error('Hello %s', foo) } `, }, { code: ` if (__DEV__) { console.error('Hello %s %s', foo, bar) } `, }, { code: ` if (__DEV__) { console.warn('Oh no'); } `, }, { code: ` if (__DEV__) { console.warn('Oh no'); } `, }, // This is OK too because it's wrapped outside: { code: ` if (__DEV__) { if (potato) { while (true) { console.error('Oh no'); } } }`, }, { code: ` var f; if (__DEV__) { f = function() { if (potato) { while (true) { console.error('Oh no'); } } }; }`, }, // Don't do anything with these: { code: 'normalFunctionCall(test);', }, { code: 'invariant(test);', }, { code: ` if (__DEV__) { normalFunctionCall(test); } `, }, // This is OK because of the outer if. { code: ` if (__DEV__) { if (foo) { if (__DEV__) { } else { console.error('Oh no'); } } }`, }, { // This is an escape hatch that makes it fire in production. code: ` console['error']('Oh no'); `, }, ], invalid: [ { code: "console.error('Oh no');", output: "if (__DEV__) {console.error('Oh no')};", errors: [ { message: `Wrap console.error() in an "if (__DEV__) {}" check`, }, ], }, { code: "console.warn('Oh no');", output: "if (__DEV__) {console.warn('Oh no')};", errors: [ { message: `Wrap console.warn() in an "if (__DEV__) {}" check`, }, ], }, { code: "console.warn('Oh no')", output: "if (__DEV__) {console.warn('Oh no')}", errors: [ { message: `Wrap console.warn() in an "if (__DEV__) {}" check`, }, ], }, { code: ` if (potato) { console.warn('Oh no'); } `, output: ` if (potato) { if (__DEV__) {console.warn('Oh no')}; } `, errors: [ { message: `Wrap console.warn() in an "if (__DEV__) {}" check`, }, ], }, { code: ` if (__DEV__ || potato && true) { console.error('Oh no'); } `, output: ` if (__DEV__ || potato && true) { if (__DEV__) {console.error('Oh no')}; } `, errors: [ { message: `Wrap console.error() in an "if (__DEV__) {}" check`, }, ], }, { code: ` if (banana && __DEV__ && potato && kitten) { console.error('Oh no'); } `, output: ` if (banana && __DEV__ && potato && kitten) { if (__DEV__) {console.error('Oh no')}; } `, // Technically this code is valid but we prefer // explicit standalone __DEV__ blocks that stand out. errors: [ { message: `Wrap console.error() in an "if (__DEV__) {}" check`, }, ], }, { code: ` if (!__DEV__) { console.error('Oh no'); } `, output: ` if (!__DEV__) { if (__DEV__) {console.error('Oh no')}; } `, errors: [ { message: `Wrap console.error() in an "if (__DEV__) {}" check`, }, ], }, { code: ` if (foo || x && __DEV__) { console.error('Oh no'); } `, output: ` if (foo || x && __DEV__) { if (__DEV__) {console.error('Oh no')}; } `, errors: [ { message: `Wrap console.error() in an "if (__DEV__) {}" check`, }, ], }, { code: ` if (__DEV__) { } else { console.error('Oh no'); } `, output: ` if (__DEV__) { } else { if (__DEV__) {console.error('Oh no')}; } `, errors: [ { message: `Wrap console.error() in an "if (__DEV__) {}" check`, }, ], }, { code: ` if (__DEV__) { } else { if (__DEV__) { } else { console.error('Oh no'); } } `, output: ` if (__DEV__) { } else { if (__DEV__) { } else { if (__DEV__) {console.error('Oh no')}; } } `, errors: [ { message: `Wrap console.error() in an "if (__DEV__) {}" check`, }, ], }, { code: ` if (__DEV__) { console.log('Oh no'); } `, errors: [ { message: 'Unexpected use of console', }, ], }, { code: ` if (__DEV__) { console.log.apply(console, 'Oh no'); } `, errors: [ { message: 'Unexpected use of console', }, ], }, ], });
18.884746
72
0.352259
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 */ let fakeNode: Element = (null: any); if (__DEV__) { if ( typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && // $FlowFixMe[method-unbinding] typeof document.createEvent === 'function' ) { fakeNode = document.createElement('react'); } } export default function invokeGuardedCallbackImpl<Args: Array<mixed>, Context>( this: {onError: (error: mixed) => void}, name: string | null, func: (...Args) => mixed, context: Context, ): void { if (__DEV__) { // In DEV mode, we use a special version // that plays more nicely with the browser's DevTools. The idea is to preserve // "Pause on exceptions" behavior. Because React wraps all user-provided // functions in invokeGuardedCallback, and the production version of // invokeGuardedCallback uses a try-catch, all user exceptions are treated // like caught exceptions, and the DevTools won't pause unless the developer // takes the extra step of enabling pause on caught exceptions. This is // unintuitive, though, because even though React has caught the error, from // the developer's perspective, the error is uncaught. // // To preserve the expected "Pause on exceptions" behavior, we don't use a // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake // DOM node, and call the user-provided callback from inside an event handler // for that fake event. If the callback throws, the error is "captured" using // event loop context, it does not interrupt the normal program flow. // Effectively, this gives us try-catch behavior without actually using // try-catch. Neat! // fakeNode signifies we are in an environment with a document and window object if (fakeNode) { const evt = document.createEvent('Event'); let didCall = false; // Keeps track of whether the user-provided callback threw an error. We // set this to true at the beginning, then set it to false right after // calling the function. If the function errors, `didError` will never be // set to false. This strategy works even if the browser is flaky and // fails to call our global error handler, because it doesn't rely on // the error event at all. let didError = true; // Keeps track of the value of window.event so that we can reset it // during the callback to let user code access window.event in the // browsers that support it. const windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event // dispatching: https://github.com/facebook/react/issues/13688 const windowEventDescriptor = Object.getOwnPropertyDescriptor( window, 'event', ); const restoreAfterDispatch = () => { // We immediately remove the callback from event listeners so that // nested `invokeGuardedCallback` calls do not clash. Otherwise, a // nested call would trigger the fake event handlers of any call higher // in the stack. fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the // window.event assignment in both IE <= 10 as they throw an error // "Member not found" in strict mode, and in Firefox which does not // support window.event. if ( typeof window.event !== 'undefined' && window.hasOwnProperty('event') ) { window.event = windowEvent; } }; // Create an event handler for our fake event. We will synchronously // dispatch our fake event using `dispatchEvent`. Inside the handler, we // call the user-provided callback. // $FlowFixMe[method-unbinding] const funcArgs = Array.prototype.slice.call(arguments, 3); const callCallback = () => { didCall = true; restoreAfterDispatch(); // $FlowFixMe[incompatible-call] Flow doesn't understand the arguments splicing. func.apply(context, funcArgs); didError = false; }; // Create a global error event handler. We use this to capture the value // that was thrown. It's possible that this error handler will fire more // than once; for example, if non-React code also calls `dispatchEvent` // and a handler for that event throws. We should be resilient to most of // those cases. Even if our error event handler fires more than once, the // last error event is always used. If the callback actually does error, // we know that the last error event is the correct one, because it's not // possible for anything else to have happened in between our callback // erroring and the code that follows the `dispatchEvent` call below. If // the callback doesn't error, but the error event was fired, we know to // ignore it because `didError` will be false, as described above. let error; // Use this to track whether the error event is ever called. let didSetError = false; let isCrossOriginError = false; const handleWindowError = (event: ErrorEvent) => { error = event.error; didSetError = true; if (error === null && event.colno === 0 && event.lineno === 0) { isCrossOriginError = true; } if (event.defaultPrevented) { // Some other error handler has prevented default. // Browsers silence the error report if this happens. // We'll remember this to later decide whether to log it or not. if (error != null && typeof error === 'object') { try { error._suppressLogging = true; } catch (inner) { // Ignore. } } } }; // Create a fake event type. const evtType = `react-${name ? name : 'invokeguardedcallback'}`; // Attach our event handlers window.addEventListener('error', handleWindowError); fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function // errors, it will trigger our global error handler. evt.initEvent(evtType, false, false); fakeNode.dispatchEvent(evt); if (windowEventDescriptor) { Object.defineProperty(window, 'event', windowEventDescriptor); } if (didCall && didError) { if (!didSetError) { // The callback errored, but the error event never fired. // eslint-disable-next-line react-internal/prod-error-codes error = new Error( 'An error was thrown inside one of your components, but React ' + "doesn't know what it was. This is likely due to browser " + 'flakiness. React does its best to preserve the "Pause on ' + 'exceptions" behavior of the DevTools, which requires some ' + "DEV-mode only tricks. It's possible that these don't work in " + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.', ); } else if (isCrossOriginError) { // eslint-disable-next-line react-internal/prod-error-codes error = new Error( "A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://reactjs.org/link/crossorigin-error for more information.', ); } this.onError(error); } // Remove our event listeners window.removeEventListener('error', handleWindowError); if (didCall) { return; } else { // Something went really wrong, and our event was not dispatched. // https://github.com/facebook/react/issues/16734 // https://github.com/facebook/react/issues/16585 // Fall back to the production implementation. restoreAfterDispatch(); // we fall through and call the prod version instead } } // We only get here if we are in an environment that either does not support the browser // variant or we had trouble getting the browser to emit the error. // $FlowFixMe[method-unbinding] const funcArgs = Array.prototype.slice.call(arguments, 3); try { // $FlowFixMe[incompatible-call] Flow doesn't understand the arguments splicing. func.apply(context, funcArgs); } catch (error) { this.onError(error); } } else { // $FlowFixMe[method-unbinding] const funcArgs = Array.prototype.slice.call(arguments, 3); try { // $FlowFixMe[incompatible-call] Flow doesn't understand the arguments splicing. func.apply(context, funcArgs); } catch (error) { this.onError(error); } } }
41.736111
92
0.643445
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 */ // 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. import type {Fiber} from 'react-reconciler/src/ReactInternalTypes'; import {getIsHydrating} from './ReactFiberHydrationContext'; import {clz32} from './clz32'; import {Forked, NoFlags} from './ReactFiberFlags'; export type TreeContext = { id: number, overflow: string, }; // TODO: Use the unified fiber stack module instead of this local one? // Intentionally not using it yet to derisk the initial implementation, because // the way we push/pop these values is a bit unusual. If there's a mistake, I'd // rather the ids be wrong than crash the whole reconciler. const forkStack: Array<any> = []; let forkStackIndex: number = 0; let treeForkProvider: Fiber | null = null; let treeForkCount: number = 0; const idStack: Array<any> = []; let idStackIndex: number = 0; let treeContextProvider: Fiber | null = null; let treeContextId: number = 1; let treeContextOverflow: string = ''; export function isForkedChild(workInProgress: Fiber): boolean { warnIfNotHydrating(); return (workInProgress.flags & Forked) !== NoFlags; } export function getForksAtLevel(workInProgress: Fiber): number { warnIfNotHydrating(); return treeForkCount; } export function getTreeId(): string { const overflow = treeContextOverflow; const idWithLeadingBit = treeContextId; const id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit); return id.toString(32) + overflow; } export function pushTreeFork( workInProgress: Fiber, totalChildren: number, ): void { // This is called right after we reconcile an array (or iterator) of child // fibers, because that's the only place where we know how many children in // the whole set without doing extra work later, or storing addtional // information on the fiber. // // That's why this function is separate from pushTreeId — it's called during // the render phase of the fork parent, not the child, which is where we push // the other context values. // // In the Fizz implementation this is much simpler because the child is // rendered in the same callstack as the parent. // // It might be better to just add a `forks` field to the Fiber type. It would // make this module simpler. warnIfNotHydrating(); forkStack[forkStackIndex++] = treeForkCount; forkStack[forkStackIndex++] = treeForkProvider; treeForkProvider = workInProgress; treeForkCount = totalChildren; } export function pushTreeId( workInProgress: Fiber, totalChildren: number, index: number, ) { warnIfNotHydrating(); idStack[idStackIndex++] = treeContextId; idStack[idStackIndex++] = treeContextOverflow; idStack[idStackIndex++] = treeContextProvider; treeContextProvider = workInProgress; const baseIdWithLeadingBit = treeContextId; const baseOverflow = treeContextOverflow; // 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; treeContextId = (1 << restOfLength) | id; treeContextOverflow = overflow; } else { // Normal path const newBits = slot << baseLength; const id = newBits | baseId; const overflow = baseOverflow; treeContextId = (1 << length) | id; treeContextOverflow = overflow; } } export function pushMaterializedTreeId(workInProgress: Fiber) { warnIfNotHydrating(); // This component materialized an id. This will affect any ids that appear // in its children. const returnFiber = workInProgress.return; if (returnFiber !== null) { const numberOfForks = 1; const slotIndex = 0; pushTreeFork(workInProgress, numberOfForks); pushTreeId(workInProgress, numberOfForks, slotIndex); } } function getBitLength(number: number): number { return 32 - clz32(number); } function getLeadingBit(id: number) { return 1 << (getBitLength(id) - 1); } export function popTreeContext(workInProgress: Fiber) { // Restore the previous values. // This is a bit more complicated than other context-like modules in Fiber // because the same Fiber may appear on the stack multiple times and for // different reasons. We have to keep popping until the work-in-progress is // no longer at the top of the stack. while (workInProgress === treeForkProvider) { treeForkProvider = forkStack[--forkStackIndex]; forkStack[forkStackIndex] = null; treeForkCount = forkStack[--forkStackIndex]; forkStack[forkStackIndex] = null; } while (workInProgress === treeContextProvider) { treeContextProvider = idStack[--idStackIndex]; idStack[idStackIndex] = null; treeContextOverflow = idStack[--idStackIndex]; idStack[idStackIndex] = null; treeContextId = idStack[--idStackIndex]; idStack[idStackIndex] = null; } } export function getSuspendedTreeContext(): TreeContext | null { warnIfNotHydrating(); if (treeContextProvider !== null) { return { id: treeContextId, overflow: treeContextOverflow, }; } else { return null; } } export function restoreSuspendedTreeContext( workInProgress: Fiber, suspendedContext: TreeContext, ) { warnIfNotHydrating(); idStack[idStackIndex++] = treeContextId; idStack[idStackIndex++] = treeContextOverflow; idStack[idStackIndex++] = treeContextProvider; treeContextId = suspendedContext.id; treeContextOverflow = suspendedContext.overflow; treeContextProvider = workInProgress; } function warnIfNotHydrating() { if (__DEV__) { if (!getIsHydrating()) { console.error( 'Expected to be hydrating. This is a bug in React. Please file ' + 'an issue.', ); } } }
33.575862
80
0.706463
owtf
/** @license React v15.7.0 * react-jsx-runtime.development.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; if (process.env.NODE_ENV !== "production") { (function() { 'use strict'; var React = require('react'); var ReactComponentTreeHook = require('react/lib/ReactComponentTreeHook'); // ATTENTION // When adding new symbols to this file, // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = 0xeac7; var REACT_PORTAL_TYPE = 0xeaca; exports.Fragment = 0xeacb; var REACT_STRICT_MODE_TYPE = 0xeacc; var REACT_PROFILER_TYPE = 0xead2; var REACT_PROVIDER_TYPE = 0xeacd; var REACT_CONTEXT_TYPE = 0xeace; var REACT_FORWARD_REF_TYPE = 0xead0; var REACT_SUSPENSE_TYPE = 0xead1; var REACT_SUSPENSE_LIST_TYPE = 0xead8; var REACT_MEMO_TYPE = 0xead3; var REACT_LAZY_TYPE = 0xead4; var REACT_BLOCK_TYPE = 0xead9; var REACT_SERVER_BLOCK_TYPE = 0xeada; var REACT_FUNDAMENTAL_TYPE = 0xead5; var REACT_SCOPE_TYPE = 0xead7; var REACT_OPAQUE_ID_TYPE = 0xeae0; var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1; var REACT_OFFSCREEN_TYPE = 0xeae2; var REACT_LEGACY_HIDDEN_TYPE = 0xeae3; if (typeof Symbol === 'function' && Symbol.for) { var symbolFor = Symbol.for; REACT_ELEMENT_TYPE = symbolFor('react.element'); REACT_PORTAL_TYPE = symbolFor('react.portal'); exports.Fragment = symbolFor('react.fragment'); REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode'); REACT_PROFILER_TYPE = symbolFor('react.profiler'); REACT_PROVIDER_TYPE = symbolFor('react.provider'); REACT_CONTEXT_TYPE = symbolFor('react.context'); REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref'); REACT_SUSPENSE_TYPE = symbolFor('react.suspense'); REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list'); REACT_MEMO_TYPE = symbolFor('react.memo'); REACT_LAZY_TYPE = symbolFor('react.lazy'); REACT_BLOCK_TYPE = symbolFor('react.block'); REACT_SERVER_BLOCK_TYPE = symbolFor('react.server.block'); REACT_FUNDAMENTAL_TYPE = symbolFor('react.fundamental'); REACT_SCOPE_TYPE = symbolFor('react.scope'); REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id'); REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode'); REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen'); REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden'); } var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== 'object') { return null; } var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof maybeIterator === 'function') { return maybeIterator; } return null; } function error(format) { { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } printWarning('error', format, args); } } function printWarning(level, format, args) { // When changing this logic, you might want to also // update consoleWithStackDev.www.js as well. { var stack = ''; if (currentlyValidatingElement) { stack += ReactComponentTreeHook.getCurrentStackAddendum(currentlyValidatingElement) } if (stack !== '') { format += '%s'; args = args.concat([stack]); } var argsWithFormat = args.map(function (item) { return '' + item; }); // Careful: RN currently depends on this prefix argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it // breaks IE9: https://github.com/facebook/react/issues/13610 // eslint-disable-next-line react-internal/no-production-logging Function.prototype.apply.call(console[level], console, argsWithFormat); } } // Filter certain DOM attributes (e.g. src, href) if their values are empty strings. var enableScopeAPI = false; // Experimental Create Event Handle API. function isValidElementType(type) { if (typeof type === 'string' || typeof type === 'function') { return true; } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). if (type === exports.Fragment || type === REACT_PROFILER_TYPE || type === REACT_DEBUG_TRACING_MODE_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || type === REACT_LEGACY_HIDDEN_TYPE || enableScopeAPI ) { return true; } if (typeof type === 'object' && type !== null) { if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_BLOCK_TYPE || type[0] === REACT_SERVER_BLOCK_TYPE) { return true; } } return false; } var BEFORE_SLASH_RE = /^(.*)[\\\/]/; function describeComponentFrame (name, source, ownerName) { var sourceInfo = ''; if (source) { var path = source.fileName; var fileName = path.replace(BEFORE_SLASH_RE, ''); { // In DEV, include code for a common special case: // prefer "folder/index.js" instead of just "index.js". if (/^index\./.test(fileName)) { var match = path.match(BEFORE_SLASH_RE); if (match) { var pathBeforeSlash = match[1]; if (pathBeforeSlash) { var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, ''); fileName = folderName + '/' + fileName; } } } } sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')'; } else if (ownerName) { sourceInfo = ' (created by ' + ownerName + ')'; } return '\n in ' + (name || 'Unknown') + sourceInfo; } var Resolved = 1; function refineResolvedLazyComponent(lazyComponent) { return lazyComponent._status === Resolved ? lazyComponent._result : null; } function getWrappedName(outerType, innerType, wrapperName) { var functionName = innerType.displayName || innerType.name || ''; return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName); } function getComponentName(type) { if (type == null) { // Host root, text node or just invalid type. return null; } { if (typeof type.tag === 'number') { error('Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.'); } } if (typeof type === 'function') { return type.displayName || type.name || null; } if (typeof type === 'string') { return type; } switch (type) { case exports.Fragment: return 'Fragment'; case REACT_PORTAL_TYPE: return 'Portal'; case REACT_PROFILER_TYPE: return "Profiler"; case REACT_STRICT_MODE_TYPE: return 'StrictMode'; case REACT_SUSPENSE_TYPE: return 'Suspense'; case REACT_SUSPENSE_LIST_TYPE: return 'SuspenseList'; } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_CONTEXT_TYPE: return 'Context.Consumer'; case REACT_PROVIDER_TYPE: return 'Context.Provider'; case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, 'ForwardRef'); case REACT_MEMO_TYPE: return getComponentName(type.type); case REACT_BLOCK_TYPE: return getComponentName(type.render); case REACT_LAZY_TYPE: { var thenable = type; var resolvedThenable = refineResolvedLazyComponent(thenable); if (resolvedThenable) { return getComponentName(resolvedThenable); } break; } } } return null; } var loggedTypeFailures = {}; var currentlyValidatingElement = null; function setCurrentlyValidatingElement(element) { { currentlyValidatingElement = element; } } function checkPropTypes(typeSpecs, values, location, componentName, element) { { // $FlowFixMe This is okay but Flow doesn't know it. var has = Function.call.bind(Object.prototype.hasOwnProperty); for (var typeSpecName in typeSpecs) { if (has(typeSpecs, typeSpecName)) { var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if (typeof typeSpecs[typeSpecName] !== 'function') { var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); err.name = 'Invariant Violation'; throw err; } error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); } catch (ex) { error$1 = ex; } if (error$1 && !(error$1 instanceof Error)) { setCurrentlyValidatingElement(element); error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); setCurrentlyValidatingElement(null); } if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error$1.message] = true; setCurrentlyValidatingElement(element); error('Failed %s type: %s', location, error$1.message); setCurrentlyValidatingElement(null); } } } } } var ReactCurrentOwner = require('react/lib/ReactCurrentOwner'); var hasOwnProperty = Object.prototype.hasOwnProperty; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown; var specialPropRefWarningShown; var didWarnAboutStringRefs; { didWarnAboutStringRefs = {}; } function hasValidRef(config) { { if (hasOwnProperty.call(config, 'ref')) { var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== undefined; } function hasValidKey(config) { { if (hasOwnProperty.call(config, 'key')) { var getter = Object.getOwnPropertyDescriptor(config, 'key').get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== undefined; } function defineKeyPropWarningGetter(props, displayName) { { var warnAboutAccessingKey = function () { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, 'key', { get: warnAboutAccessingKey, configurable: true }); } } function defineRefPropWarningGetter(props, displayName) { { var warnAboutAccessingRef = function () { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, 'ref', { get: warnAboutAccessingRef, configurable: true }); } } /** * Factory method to create a new React element. This no longer adheres to * the class pattern, so do not use new to call it. Also, instanceof check * will not work. Instead test $$typeof field against Symbol.for('react.element') to check * if something is a React Element. * * @param {*} type * @param {*} props * @param {*} key * @param {string|object} ref * @param {*} owner * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allows us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; /** * https://github.com/reactjs/rfcs/pull/107 * @param {*} type * @param {object} props * @param {string} key */ function jsxDEV(type, config, maybeKey, source, self) { { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; // Currently, key can be spread in as a prop. This causes a potential // issue if key is also explicitly declared (ie. <div {...props} key="Hi" /> // or <div key="Hi" {...props} /> ). We want to deprecate key spread, // but as an intermediary step, we will use jsxDEV for everything except // <div {...props} key="Hi" />, because we aren't currently able to tell if // key is explicitly declared to be undefined or not. if (maybeKey !== undefined) { key = '' + maybeKey; } if (hasValidKey(config)) { key = '' + config.key; } if (hasValidRef(config)) { ref = config.ref; } // Remaining properties are added to a new props object for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } if (key || ref) { var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); } } var ReactCurrentOwner$1 = require('react/lib/ReactCurrentOwner'); function setCurrentlyValidatingElement$1(element) { currentlyValidatingElement = element; } var propTypesMisspellWarningShown; { propTypesMisspellWarningShown = false; } /** * Verifies the object is a ReactElement. * See https://reactjs.org/docs/react-api.html#isvalidelement * @param {?object} object * @return {boolean} True if `object` is a ReactElement. * @final */ function isValidElement(object) { { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } } function getDeclarationErrorAddendum() { { if (ReactCurrentOwner$1.current) { var name = ReactCurrentOwner$1.current.getName(); if (name) { return '\n\nCheck the render method of `' + name + '`.'; } } return ''; } } function getSourceInfoErrorAddendum(source) { { if (source !== undefined) { var fileName = source.fileName.replace(/^.*[\\\/]/, ''); var lineNumber = source.lineNumber; return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.'; } return ''; } } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { info = "\n\nCheck the top-level render call using <" + parentName + ">."; } } return info; } } /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. Error statuses are cached so a warning * will only be shown once. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { return; } ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. var childOwner = ''; if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) { // Give the component that originally created this child. childOwner = " It was passed a child from " + element._owner.getName() + "."; } setCurrentlyValidatingElement$1(element); error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); setCurrentlyValidatingElement$1(null); } } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ function validateChildKeys(node, parentType) { { if (typeof node !== 'object') { return; } if (Array.isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (isValidElement(node)) { // This element was passed in a valid location. if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); if (typeof iteratorFn === 'function') { // Entry iterators used to provide implicit keys, // but now we print a separate warning for them later. if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { { var type = element.type; if (type === null || type === undefined || typeof type === 'string') { return; } var propTypes; if (typeof type === 'function') { propTypes = type.propTypes; } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. // Inner props are checked in the reconciler. type.$$typeof === REACT_MEMO_TYPE)) { propTypes = type.propTypes; } else { return; } if (propTypes) { // Intentionally inside to avoid triggering lazy initializers: var name = getComponentName(type); checkPropTypes(propTypes, element.props, 'prop', name, element); } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers: var _name = getComponentName(type); error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown'); } if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) { error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.'); } } } /** * Given a fragment, validate that it can only be provided with fragment props * @param {ReactElement} fragment */ function validateFragmentProps(fragment) { { var keys = Object.keys(fragment.props); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (key !== 'children' && key !== 'key') { setCurrentlyValidatingElement$1(fragment); error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key); setCurrentlyValidatingElement$1(null); break; } } if (fragment.ref !== null) { setCurrentlyValidatingElement$1(fragment); error('Invalid attribute `ref` supplied to `React.Fragment`.'); setCurrentlyValidatingElement$1(null); } } } function jsxWithValidation(type, props, key, isStaticChildren, source, self) { { var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. if (!validType) { var info = ''; if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports."; } var sourceInfo = getSourceInfoErrorAddendum(source); if (sourceInfo) { info += sourceInfo; } else { info += getDeclarationErrorAddendum(); } var typeString; if (type === null) { typeString = 'null'; } else if (Array.isArray(type)) { typeString = 'array'; } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { typeString = "<" + (getComponentName(type.type) || 'Unknown') + " />"; info = ' Did you accidentally export a JSX literal instead of a component?'; } else { typeString = typeof type; } error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info); } var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { var children = props.children; if (children !== undefined) { if (isStaticChildren) { if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { validateChildKeys(children[i], type); } if (Object.freeze) { Object.freeze(children); } } else { error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.'); } } else { validateChildKeys(children, type); } } } if (type === exports.Fragment) { validateFragmentProps(element); } else { validatePropTypes(element); } return element; } } // These two functions exist to still get child warnings in dev // even with the prod transform. This means that jsxDEV is purely // opt-in behavior for better messages but that we won't stop // giving you warnings if you use production apis. function jsxWithValidationStatic(type, props, key) { { return jsxWithValidation(type, props, key, true); } } function jsxWithValidationDynamic(type, props, key) { { return jsxWithValidation(type, props, key, false); } } var jsx = jsxWithValidationDynamic ; // we may want to special case jsxs internally to take advantage of static children. // for now we can ship identical prod functions var jsxs = jsxWithValidationStatic ; exports.jsx = jsx; exports.jsxs = jsxs; })(); }
30.426322
397
0.649247
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 ProfilingNotSupported(): React.Node { return ( <div className={styles.Column}> <div className={styles.Header}>Profiling not supported.</div> <p className={styles.Paragraph}> Profiling support requires either a development or profiling build of React v16.5+. </p> <p className={styles.Paragraph}> Learn more at{' '} <a className={styles.Link} href="https://fb.me/react-devtools-profiling" rel="noopener noreferrer" target="_blank"> reactjs.org/link/profiling </a> . </p> </div> ); }
24.611111
77
0.612378
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('ReactDOMEventListener', () => { let React; let ReactDOM; let ReactDOMServer; beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMServer = require('react-dom/server'); }); describe('Propagation', () => { it('should propagate events one level down', () => { const mouseOut = jest.fn(); const onMouseOut = event => mouseOut(event.currentTarget); const childContainer = document.createElement('div'); const parentContainer = document.createElement('div'); const childNode = ReactDOM.render( <div onMouseOut={onMouseOut}>Child</div>, childContainer, ); const parentNode = ReactDOM.render( <div onMouseOut={onMouseOut}>div</div>, parentContainer, ); parentNode.appendChild(childContainer); document.body.appendChild(parentContainer); try { const nativeEvent = document.createEvent('Event'); nativeEvent.initEvent('mouseout', true, true); childNode.dispatchEvent(nativeEvent); expect(mouseOut).toBeCalled(); expect(mouseOut).toHaveBeenCalledTimes(2); expect(mouseOut.mock.calls[0][0]).toEqual(childNode); expect(mouseOut.mock.calls[1][0]).toEqual(parentNode); } finally { document.body.removeChild(parentContainer); } }); it('should propagate events two levels down', () => { const mouseOut = jest.fn(); const onMouseOut = event => mouseOut(event.currentTarget); const childContainer = document.createElement('div'); const parentContainer = document.createElement('div'); const grandParentContainer = document.createElement('div'); const childNode = ReactDOM.render( <div onMouseOut={onMouseOut}>Child</div>, childContainer, ); const parentNode = ReactDOM.render( <div onMouseOut={onMouseOut}>Parent</div>, parentContainer, ); const grandParentNode = ReactDOM.render( <div onMouseOut={onMouseOut}>Parent</div>, grandParentContainer, ); parentNode.appendChild(childContainer); grandParentNode.appendChild(parentContainer); document.body.appendChild(grandParentContainer); try { const nativeEvent = document.createEvent('Event'); nativeEvent.initEvent('mouseout', true, true); childNode.dispatchEvent(nativeEvent); expect(mouseOut).toBeCalled(); expect(mouseOut).toHaveBeenCalledTimes(3); expect(mouseOut.mock.calls[0][0]).toEqual(childNode); expect(mouseOut.mock.calls[1][0]).toEqual(parentNode); expect(mouseOut.mock.calls[2][0]).toEqual(grandParentNode); } finally { document.body.removeChild(grandParentContainer); } }); // Regression test for https://github.com/facebook/react/issues/1105 it('should not get confused by disappearing elements', () => { const container = document.createElement('div'); document.body.appendChild(container); try { class MyComponent extends React.Component { state = {clicked: false}; handleClick = () => { this.setState({clicked: true}); }; componentDidMount() { expect(ReactDOM.findDOMNode(this)).toBe(container.firstChild); } componentDidUpdate() { expect(ReactDOM.findDOMNode(this)).toBe(container.firstChild); } render() { if (this.state.clicked) { return <span>clicked!</span>; } else { return ( <button onClick={this.handleClick}>not yet clicked</button> ); } } } ReactDOM.render(<MyComponent />, container); container.firstChild.dispatchEvent( new MouseEvent('click', { bubbles: true, }), ); expect(container.firstChild.textContent).toBe('clicked!'); } finally { document.body.removeChild(container); } }); it('should batch between handlers from different roots', () => { const mock = jest.fn(); const childContainer = document.createElement('div'); const handleChildMouseOut = () => { ReactDOM.render(<div>1</div>, childContainer); mock(childNode.textContent); }; const parentContainer = document.createElement('div'); const handleParentMouseOut = () => { ReactDOM.render(<div>2</div>, childContainer); mock(childNode.textContent); }; const childNode = ReactDOM.render( <div onMouseOut={handleChildMouseOut}>Child</div>, childContainer, ); const parentNode = ReactDOM.render( <div onMouseOut={handleParentMouseOut}>Parent</div>, parentContainer, ); parentNode.appendChild(childContainer); document.body.appendChild(parentContainer); try { const nativeEvent = document.createEvent('Event'); nativeEvent.initEvent('mouseout', true, true); childNode.dispatchEvent(nativeEvent); // Child and parent should both call from event handlers. expect(mock).toHaveBeenCalledTimes(2); // The first call schedules a render of '1' into the 'Child'. // However, we're batching so it isn't flushed yet. expect(mock.mock.calls[0][0]).toBe('Child'); // As we have two roots, it means we have two event listeners. // This also means we enter the event batching phase twice, // flushing the child to be 1. // We don't have any good way of knowing if another event will // occur because another event handler might invoke // stopPropagation() along the way. After discussions internally // with Sebastian, it seems that for now over-flushing should // be fine, especially as the new event system is a breaking // change anyway. We can maybe revisit this later as part of // the work to refine this in the scheduler (maybe by leveraging // isInputPending?). expect(mock.mock.calls[1][0]).toBe('1'); // By the time we leave the handler, the second update is flushed. expect(childNode.textContent).toBe('2'); } finally { document.body.removeChild(parentContainer); } }); }); it('should not fire duplicate events for a React DOM tree', () => { const mouseOut = jest.fn(); const onMouseOut = event => mouseOut(event.target); class Wrapper extends React.Component { innerRef = React.createRef(); getInner = () => { return this.innerRef.current; }; render() { const inner = <div ref={this.innerRef}>Inner</div>; return ( <div> <div onMouseOut={onMouseOut} id="outer"> {inner} </div> </div> ); } } const container = document.createElement('div'); const instance = ReactDOM.render(<Wrapper />, container); document.body.appendChild(container); try { const nativeEvent = document.createEvent('Event'); nativeEvent.initEvent('mouseout', true, true); instance.getInner().dispatchEvent(nativeEvent); expect(mouseOut).toBeCalled(); expect(mouseOut).toHaveBeenCalledTimes(1); expect(mouseOut.mock.calls[0][0]).toEqual(instance.getInner()); } finally { document.body.removeChild(container); } }); // Regression test for https://github.com/facebook/react/pull/12877 it('should not fire form events twice', () => { const container = document.createElement('div'); document.body.appendChild(container); const formRef = React.createRef(); const inputRef = React.createRef(); const handleInvalid = jest.fn(); const handleReset = jest.fn(); const handleSubmit = jest.fn(); ReactDOM.render( <form ref={formRef} onReset={handleReset} onSubmit={handleSubmit}> <input ref={inputRef} onInvalid={handleInvalid} /> </form>, container, ); inputRef.current.dispatchEvent( new Event('invalid', { // https://developer.mozilla.org/en-US/docs/Web/Events/invalid bubbles: false, }), ); expect(handleInvalid).toHaveBeenCalledTimes(1); formRef.current.dispatchEvent( new Event('reset', { // https://developer.mozilla.org/en-US/docs/Web/Events/reset bubbles: true, }), ); expect(handleReset).toHaveBeenCalledTimes(1); formRef.current.dispatchEvent( new Event('submit', { // https://developer.mozilla.org/en-US/docs/Web/Events/submit bubbles: true, }), ); expect(handleSubmit).toHaveBeenCalledTimes(1); formRef.current.dispatchEvent( new Event('submit', { // Might happen on older browsers. bubbles: true, }), ); expect(handleSubmit).toHaveBeenCalledTimes(2); // It already fired in this test. document.body.removeChild(container); }); // This tests an implementation detail that submit/reset events are listened to // at the document level, which is necessary for event replaying to work. // They bubble in all modern browsers. it('should not receive submit events if native, interim DOM handler prevents it', () => { const container = document.createElement('div'); document.body.appendChild(container); try { const formRef = React.createRef(); const interimRef = React.createRef(); const handleSubmit = jest.fn(); const handleReset = jest.fn(); ReactDOM.render( <div ref={interimRef}> <form ref={formRef} onSubmit={handleSubmit} onReset={handleReset} /> </div>, container, ); interimRef.current.onsubmit = nativeEvent => nativeEvent.stopPropagation(); interimRef.current.onreset = nativeEvent => nativeEvent.stopPropagation(); formRef.current.dispatchEvent( new Event('submit', { // https://developer.mozilla.org/en-US/docs/Web/Events/submit bubbles: true, }), ); formRef.current.dispatchEvent( new Event('reset', { // https://developer.mozilla.org/en-US/docs/Web/Events/reset bubbles: true, }), ); expect(handleSubmit).not.toHaveBeenCalled(); expect(handleReset).not.toHaveBeenCalled(); } finally { document.body.removeChild(container); } }); it('should dispatch loadstart only for media elements', () => { const container = document.createElement('div'); document.body.appendChild(container); try { const imgRef = React.createRef(); const videoRef = React.createRef(); const handleImgLoadStart = jest.fn(); const handleVideoLoadStart = jest.fn(); ReactDOM.render( <div> <img ref={imgRef} onLoadStart={handleImgLoadStart} /> <video ref={videoRef} onLoadStart={handleVideoLoadStart} /> </div>, container, ); // Note for debugging: loadstart currently doesn't fire in Chrome. // https://bugs.chromium.org/p/chromium/issues/detail?id=458851 imgRef.current.dispatchEvent( new ProgressEvent('loadstart', { bubbles: false, }), ); expect(handleImgLoadStart).toHaveBeenCalledTimes(0); videoRef.current.dispatchEvent( new ProgressEvent('loadstart', { bubbles: false, }), ); expect(handleVideoLoadStart).toHaveBeenCalledTimes(1); } finally { document.body.removeChild(container); } }); it('should not attempt to listen to unnecessary events on the top level', () => { const container = document.createElement('div'); document.body.appendChild(container); const videoRef = React.createRef(); // We'll test this event alone. const handleVideoPlay = jest.fn(); const handleVideoPlayDelegated = jest.fn(); const mediaEvents = { onAbort() {}, onCanPlay() {}, onCanPlayThrough() {}, onDurationChange() {}, onEmptied() {}, onEncrypted() {}, onEnded() {}, onError() {}, onLoadedData() {}, onLoadedMetadata() {}, onLoadStart() {}, onPause() {}, onPlay() {}, onPlaying() {}, onProgress() {}, onRateChange() {}, onResize() {}, onSeeked() {}, onSeeking() {}, onStalled() {}, onSuspend() {}, onTimeUpdate() {}, onVolumeChange() {}, onWaiting() {}, }; const originalDocAddEventListener = document.addEventListener; const originalRootAddEventListener = container.addEventListener; document.addEventListener = function (type) { switch (type) { case 'selectionchange': break; default: throw new Error( `Did not expect to add a document-level listener for the "${type}" event.`, ); } }; container.addEventListener = function (type, fn, options) { if (options && (options === true || options.capture)) { return; } switch (type) { case 'abort': case 'canplay': case 'canplaythrough': case 'durationchange': case 'emptied': case 'encrypted': case 'ended': case 'error': case 'loadeddata': case 'loadedmetadata': case 'loadstart': case 'pause': case 'play': case 'playing': case 'progress': case 'ratechange': case 'resize': case 'seeked': case 'seeking': case 'stalled': case 'suspend': case 'timeupdate': case 'volumechange': case 'waiting': throw new Error( `Did not expect to add a root-level listener for the "${type}" event.`, ); default: break; } }; try { // We expect that mounting this tree will // *not* attach handlers for any top-level events. ReactDOM.render( <div onPlay={handleVideoPlayDelegated}> <video ref={videoRef} {...mediaEvents} onPlay={handleVideoPlay} /> <audio {...mediaEvents}> <source {...mediaEvents} /> </audio> </div>, container, ); // Also verify dispatching one of them works videoRef.current.dispatchEvent( new Event('play', { bubbles: false, }), ); expect(handleVideoPlay).toHaveBeenCalledTimes(1); // Unlike browsers, we delegate media events. // (This doesn't make a lot of sense but it would be a breaking change not to.) expect(handleVideoPlayDelegated).toHaveBeenCalledTimes(1); } finally { document.addEventListener = originalDocAddEventListener; container.addEventListener = originalRootAddEventListener; document.body.removeChild(container); } }); it('should dispatch load for embed elements', () => { const container = document.createElement('div'); document.body.appendChild(container); try { const ref = React.createRef(); const handleLoad = jest.fn(); ReactDOM.render( <div> <embed ref={ref} onLoad={handleLoad} /> </div>, container, ); ref.current.dispatchEvent( new ProgressEvent('load', { bubbles: false, }), ); expect(handleLoad).toHaveBeenCalledTimes(1); } finally { document.body.removeChild(container); } }); // Unlike browsers, we delegate media events. // (This doesn't make a lot of sense but it would be a breaking change not to.) it('should delegate media events even without a direct listener', () => { const container = document.createElement('div'); const ref = React.createRef(); const handleVideoPlayDelegated = jest.fn(); document.body.appendChild(container); try { ReactDOM.render( <div onPlay={handleVideoPlayDelegated}> {/* Intentionally no handler on the target: */} <video ref={ref} /> </div>, container, ); ref.current.dispatchEvent( new Event('play', { bubbles: false, }), ); // Regression test: ensure React tree delegation still works // even if the actual DOM element did not have a handler. expect(handleVideoPlayDelegated).toHaveBeenCalledTimes(1); } finally { document.body.removeChild(container); } }); it('should delegate dialog events even without a direct listener', () => { const container = document.createElement('div'); const ref = React.createRef(); const onCancel = jest.fn(); const onClose = jest.fn(); document.body.appendChild(container); try { ReactDOM.render( <div onCancel={onCancel} onClose={onClose}> {/* Intentionally no handler on the target: */} <dialog ref={ref} /> </div>, container, ); ref.current.dispatchEvent( new Event('close', { bubbles: false, }), ); ref.current.dispatchEvent( new Event('cancel', { bubbles: false, }), ); // Regression test: ensure React tree delegation still works // even if the actual DOM element did not have a handler. expect(onCancel).toHaveBeenCalledTimes(1); expect(onClose).toHaveBeenCalledTimes(1); } finally { document.body.removeChild(container); } }); it('should bubble non-native bubbling toggle events', () => { const container = document.createElement('div'); const ref = React.createRef(); const onToggle = jest.fn(); document.body.appendChild(container); try { ReactDOM.render( <div onToggle={onToggle}> <details ref={ref} onToggle={onToggle} /> </div>, container, ); ref.current.dispatchEvent( new Event('toggle', { bubbles: false, }), ); expect(onToggle).toHaveBeenCalledTimes(2); } finally { document.body.removeChild(container); } }); it('should bubble non-native bubbling cancel/close events', () => { const container = document.createElement('div'); const ref = React.createRef(); const onCancel = jest.fn(); const onClose = jest.fn(); document.body.appendChild(container); try { ReactDOM.render( <div onCancel={onCancel} onClose={onClose}> <dialog ref={ref} onCancel={onCancel} onClose={onClose} /> </div>, container, ); ref.current.dispatchEvent( new Event('cancel', { bubbles: false, }), ); ref.current.dispatchEvent( new Event('close', { bubbles: false, }), ); expect(onCancel).toHaveBeenCalledTimes(2); expect(onClose).toHaveBeenCalledTimes(2); } finally { document.body.removeChild(container); } }); it('should bubble non-native bubbling media events events', () => { const container = document.createElement('div'); const ref = React.createRef(); const onPlay = jest.fn(); document.body.appendChild(container); try { ReactDOM.render( <div onPlay={onPlay}> <video ref={ref} onPlay={onPlay} /> </div>, container, ); ref.current.dispatchEvent( new Event('play', { bubbles: false, }), ); expect(onPlay).toHaveBeenCalledTimes(2); } finally { document.body.removeChild(container); } }); it('should bubble non-native bubbling invalid events', () => { const container = document.createElement('div'); const ref = React.createRef(); const onInvalid = jest.fn(); document.body.appendChild(container); try { ReactDOM.render( <form onInvalid={onInvalid}> <input ref={ref} onInvalid={onInvalid} /> </form>, container, ); ref.current.dispatchEvent( new Event('invalid', { bubbles: false, }), ); expect(onInvalid).toHaveBeenCalledTimes(2); } finally { document.body.removeChild(container); } }); it('should handle non-bubbling capture events correctly', () => { const container = document.createElement('div'); const innerRef = React.createRef(); const outerRef = React.createRef(); const onPlayCapture = jest.fn(e => log.push(e.currentTarget)); const log = []; document.body.appendChild(container); try { ReactDOM.render( <div ref={outerRef} onPlayCapture={onPlayCapture}> <div onPlayCapture={onPlayCapture}> <div ref={innerRef} onPlayCapture={onPlayCapture} /> </div> </div>, container, ); innerRef.current.dispatchEvent( new Event('play', { bubbles: false, }), ); expect(onPlayCapture).toHaveBeenCalledTimes(3); expect(log).toEqual([ outerRef.current, outerRef.current.firstChild, innerRef.current, ]); outerRef.current.dispatchEvent( new Event('play', { bubbles: false, }), ); expect(onPlayCapture).toHaveBeenCalledTimes(4); expect(log).toEqual([ outerRef.current, outerRef.current.firstChild, innerRef.current, outerRef.current, ]); } finally { document.body.removeChild(container); } }); // We're moving towards aligning more closely with the browser. // Currently we emulate bubbling for all non-bubbling events except scroll. // We may expand this list in the future, removing emulated bubbling altogether. it('should not emulate bubbling of scroll events', () => { const container = document.createElement('div'); const ref = React.createRef(); const log = []; const onScroll = jest.fn(e => log.push(['onScroll', 'bubble', e.currentTarget.className]), ); const onScrollCapture = jest.fn(e => log.push(['onScroll', 'capture', e.currentTarget.className]), ); const onScrollEnd = jest.fn(e => log.push(['onScrollEnd', 'bubble', e.currentTarget.className]), ); const onScrollEndCapture = jest.fn(e => log.push(['onScrollEnd', 'capture', e.currentTarget.className]), ); document.body.appendChild(container); try { ReactDOM.render( <div className="grand" onScroll={onScroll} onScrollCapture={onScrollCapture} onScrollEnd={onScrollEnd} onScrollEndCapture={onScrollEndCapture}> <div className="parent" onScroll={onScroll} onScrollCapture={onScrollCapture} onScrollEnd={onScrollEnd} onScrollEndCapture={onScrollEndCapture}> <div className="child" onScroll={onScroll} onScrollCapture={onScrollCapture} onScrollEnd={onScrollEnd} onScrollEndCapture={onScrollEndCapture} ref={ref} /> </div> </div>, container, ); ref.current.dispatchEvent( new Event('scroll', { bubbles: false, }), ); ref.current.dispatchEvent( new Event('scrollend', { bubbles: false, }), ); expect(log).toEqual([ ['onScroll', 'capture', 'grand'], ['onScroll', 'capture', 'parent'], ['onScroll', 'capture', 'child'], ['onScroll', 'bubble', 'child'], ['onScrollEnd', 'capture', 'grand'], ['onScrollEnd', 'capture', 'parent'], ['onScrollEnd', 'capture', 'child'], ['onScrollEnd', 'bubble', 'child'], ]); } finally { document.body.removeChild(container); } }); // We're moving towards aligning more closely with the browser. // Currently we emulate bubbling for all non-bubbling events except scroll. // We may expand this list in the future, removing emulated bubbling altogether. it('should not emulate bubbling of scroll events (no own handler)', () => { const container = document.createElement('div'); const ref = React.createRef(); const log = []; const onScroll = jest.fn(e => log.push(['onScroll', 'bubble', e.currentTarget.className]), ); const onScrollCapture = jest.fn(e => log.push(['onScroll', 'capture', e.currentTarget.className]), ); const onScrollEnd = jest.fn(e => log.push(['onScrollEnd', 'bubble', e.currentTarget.className]), ); const onScrollEndCapture = jest.fn(e => log.push(['onScrollEnd', 'capture', e.currentTarget.className]), ); document.body.appendChild(container); try { ReactDOM.render( <div className="grand" onScroll={onScroll} onScrollCapture={onScrollCapture} onScrollEnd={onScrollEnd} onScrollEndCapture={onScrollEndCapture}> <div className="parent" onScroll={onScroll} onScrollCapture={onScrollCapture} onScrollEnd={onScrollEnd} onScrollEndCapture={onScrollEndCapture}> {/* Intentionally no handler on the child: */} <div className="child" ref={ref} /> </div> </div>, container, ); ref.current.dispatchEvent( new Event('scroll', { bubbles: false, }), ); ref.current.dispatchEvent( new Event('scrollend', { bubbles: false, }), ); expect(log).toEqual([ ['onScroll', 'capture', 'grand'], ['onScroll', 'capture', 'parent'], ['onScrollEnd', 'capture', 'grand'], ['onScrollEnd', 'capture', 'parent'], ]); } finally { document.body.removeChild(container); } }); it('should subscribe to scroll during updates', () => { const container = document.createElement('div'); const ref = React.createRef(); const log = []; const onScroll = jest.fn(e => log.push(['onScroll', 'bubble', e.currentTarget.className]), ); const onScrollCapture = jest.fn(e => log.push(['onScroll', 'capture', e.currentTarget.className]), ); const onScrollEnd = jest.fn(e => log.push(['onScrollEnd', 'bubble', e.currentTarget.className]), ); const onScrollEndCapture = jest.fn(e => log.push(['onScrollEnd', 'capture', e.currentTarget.className]), ); document.body.appendChild(container); try { ReactDOM.render( <div> <div> <div /> </div> </div>, container, ); // Update to attach. ReactDOM.render( <div className="grand" onScroll={e => onScroll(e)} onScrollCapture={e => onScrollCapture(e)} onScrollEnd={e => onScrollEnd(e)} onScrollEndCapture={e => onScrollEndCapture(e)}> <div className="parent" onScroll={e => onScroll(e)} onScrollCapture={e => onScrollCapture(e)} onScrollEnd={e => onScrollEnd(e)} onScrollEndCapture={e => onScrollEndCapture(e)}> <div className="child" onScroll={e => onScroll(e)} onScrollCapture={e => onScrollCapture(e)} onScrollEnd={e => onScrollEnd(e)} onScrollEndCapture={e => onScrollEndCapture(e)} ref={ref} /> </div> </div>, container, ); ref.current.dispatchEvent( new Event('scroll', { bubbles: false, }), ); ref.current.dispatchEvent( new Event('scrollend', { bubbles: false, }), ); expect(log).toEqual([ ['onScroll', 'capture', 'grand'], ['onScroll', 'capture', 'parent'], ['onScroll', 'capture', 'child'], ['onScroll', 'bubble', 'child'], ['onScrollEnd', 'capture', 'grand'], ['onScrollEnd', 'capture', 'parent'], ['onScrollEnd', 'capture', 'child'], ['onScrollEnd', 'bubble', 'child'], ]); // Update to verify deduplication. log.length = 0; ReactDOM.render( <div className="grand" // Note: these are intentionally inline functions so that // we hit the reattachment codepath instead of bailing out. onScroll={e => onScroll(e)} onScrollCapture={e => onScrollCapture(e)} onScrollEnd={e => onScrollEnd(e)} onScrollEndCapture={e => onScrollEndCapture(e)}> <div className="parent" onScroll={e => onScroll(e)} onScrollCapture={e => onScrollCapture(e)} onScrollEnd={e => onScrollEnd(e)} onScrollEndCapture={e => onScrollEndCapture(e)}> <div className="child" onScroll={e => onScroll(e)} onScrollCapture={e => onScrollCapture(e)} onScrollEnd={e => onScrollEnd(e)} onScrollEndCapture={e => onScrollEndCapture(e)} ref={ref} /> </div> </div>, container, ); ref.current.dispatchEvent( new Event('scroll', { bubbles: false, }), ); ref.current.dispatchEvent( new Event('scrollend', { bubbles: false, }), ); expect(log).toEqual([ ['onScroll', 'capture', 'grand'], ['onScroll', 'capture', 'parent'], ['onScroll', 'capture', 'child'], ['onScroll', 'bubble', 'child'], ['onScrollEnd', 'capture', 'grand'], ['onScrollEnd', 'capture', 'parent'], ['onScrollEnd', 'capture', 'child'], ['onScrollEnd', 'bubble', 'child'], ]); // Update to detach. log.length = 0; ReactDOM.render( <div> <div> <div ref={ref} /> </div> </div>, container, ); ref.current.dispatchEvent( new Event('scroll', { bubbles: false, }), ); ref.current.dispatchEvent( new Event('scrollend', { bubbles: false, }), ); expect(log).toEqual([]); } finally { document.body.removeChild(container); } }); // Regression test. it('should subscribe to scroll during hydration', () => { const container = document.createElement('div'); const ref = React.createRef(); const log = []; const onScroll = jest.fn(e => log.push(['onScroll', 'bubble', e.currentTarget.className]), ); const onScrollCapture = jest.fn(e => log.push(['onScroll', 'capture', e.currentTarget.className]), ); const onScrollEnd = jest.fn(e => log.push(['onScrollEnd', 'bubble', e.currentTarget.className]), ); const onScrollEndCapture = jest.fn(e => log.push(['onScrollEnd', 'capture', e.currentTarget.className]), ); const tree = ( <div className="grand" onScroll={onScroll} onScrollCapture={onScrollCapture} onScrollEnd={onScrollEnd} onScrollEndCapture={onScrollEndCapture}> <div className="parent" onScroll={onScroll} onScrollCapture={onScrollCapture} onScrollEnd={onScrollEnd} onScrollEndCapture={onScrollEndCapture}> <div className="child" onScroll={onScroll} onScrollCapture={onScrollCapture} onScrollEnd={onScrollEnd} onScrollEndCapture={onScrollEndCapture} ref={ref} /> </div> </div> ); document.body.appendChild(container); try { container.innerHTML = ReactDOMServer.renderToString(tree); ReactDOM.hydrate(tree, container); ref.current.dispatchEvent( new Event('scroll', { bubbles: false, }), ); ref.current.dispatchEvent( new Event('scrollend', { bubbles: false, }), ); expect(log).toEqual([ ['onScroll', 'capture', 'grand'], ['onScroll', 'capture', 'parent'], ['onScroll', 'capture', 'child'], ['onScroll', 'bubble', 'child'], ['onScrollEnd', 'capture', 'grand'], ['onScrollEnd', 'capture', 'parent'], ['onScrollEnd', 'capture', 'child'], ['onScrollEnd', 'bubble', 'child'], ]); log.length = 0; ReactDOM.render( <div> <div> <div ref={ref} /> </div> </div>, container, ); ref.current.dispatchEvent( new Event('scroll', { bubbles: false, }), ); ref.current.dispatchEvent( new Event('scrollend', { bubbles: false, }), ); expect(log).toEqual([]); } finally { document.body.removeChild(container); } }); it('should not subscribe to selectionchange twice', () => { const log = []; const originalDocAddEventListener = document.addEventListener; document.addEventListener = function (type, fn, options) { switch (type) { case 'selectionchange': log.push(options); break; default: throw new Error( `Did not expect to add a document-level listener for the "${type}" event.`, ); } }; try { ReactDOM.render(<input />, document.createElement('div')); ReactDOM.render(<input />, document.createElement('div')); } finally { document.addEventListener = originalDocAddEventListener; } expect(log).toEqual([false]); }); });
29.676868
91
0.578328
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 */ const ReactFabricGlobalResponderHandler = { onChange: function (from: any, to: any, blockNativeResponder: boolean) { if (from && from.stateNode) { // equivalent to clearJSResponder nativeFabricUIManager.setIsJSResponder( from.stateNode.node, false, blockNativeResponder || false, ); } if (to && to.stateNode) { // equivalent to setJSResponder nativeFabricUIManager.setIsJSResponder( to.stateNode.node, true, blockNativeResponder || false, ); } }, }; export default ReactFabricGlobalResponderHandler;
23.575758
74
0.65679
owtf
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ import * as React from 'react'; import {renderToPipeableStream} from 'react-dom/server'; import App from '../src/App'; import {ABORT_DELAY} from './delays'; // In a real setup, you'd read it from webpack build stats. let assets = { 'main.js': '/main.js', 'main.css': '/main.css', }; module.exports = function render(url, res) { // The new wiring is a bit more involved. res.socket.on('error', error => { console.error('Fatal', error); }); let didError = false; let didFinish = false; const {pipe, abort} = renderToPipeableStream(<App assets={assets} />, { bootstrapScripts: [assets['main.js']], onAllReady() { // Full completion. // You can use this for SSG or crawlers. didFinish = true; }, onShellReady() { // If something errored before we started streaming, we set the error code appropriately. res.statusCode = didError ? 500 : 200; res.setHeader('Content-type', 'text/html'); setImmediate(() => pipe(res)); }, onShellError(x) { // Something errored before we could complete the shell so we emit an alternative shell. res.statusCode = 500; res.send('<!doctype><p>Error</p>'); }, onError(x) { didError = true; console.error(x); }, }); // Abandon and switch to client rendering if enough time passes. // Try lowering this to see the client recover. setTimeout(() => { if (!didFinish) { abort(); } }, ABORT_DELAY); };
27.793103
95
0.62852
Python-Penetration-Testing-for-Developers
let React; let startTransition; let ReactNoop; let resolveSuspenseyThing; let getSuspenseyThingStatus; let Suspense; let Activity; let SuspenseList; let useMemo; let Scheduler; let act; let assertLog; let waitForPaint; describe('ReactSuspenseyCommitPhase', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); Suspense = React.Suspense; if (gate(flags => flags.enableSuspenseList)) { SuspenseList = React.unstable_SuspenseList; } Activity = React.unstable_Activity; useMemo = React.useMemo; startTransition = React.startTransition; resolveSuspenseyThing = ReactNoop.resolveSuspenseyThing; getSuspenseyThingStatus = ReactNoop.getSuspenseyThingStatus; const InternalTestUtils = require('internal-test-utils'); act = InternalTestUtils.act; assertLog = InternalTestUtils.assertLog; waitForPaint = InternalTestUtils.waitForPaint; }); function Text({text}) { Scheduler.log(text); return text; } function SuspenseyImage({src}) { return ( <suspensey-thing src={src} onLoadStart={() => Scheduler.log(`Image requested [${src}]`)} /> ); } test('suspend commit during initial mount', async () => { const root = ReactNoop.createRoot(); await act(async () => { startTransition(() => { root.render( <Suspense fallback={<Text text="Loading..." />}> <SuspenseyImage src="A" /> </Suspense>, ); }); }); assertLog(['Image requested [A]', 'Loading...']); expect(getSuspenseyThingStatus('A')).toBe('pending'); expect(root).toMatchRenderedOutput('Loading...'); // This should synchronously commit resolveSuspenseyThing('A'); expect(root).toMatchRenderedOutput(<suspensey-thing src="A" />); }); test('suspend commit during update', async () => { const root = ReactNoop.createRoot(); await act(() => resolveSuspenseyThing('A')); await act(async () => { startTransition(() => { root.render( <Suspense fallback={<Text text="Loading..." />}> <SuspenseyImage src="A" /> </Suspense>, ); }); }); expect(root).toMatchRenderedOutput(<suspensey-thing src="A" />); // Update to a new image src. The transition should suspend because // the src hasn't loaded yet, and the image is in an already-visible tree. await act(async () => { startTransition(() => { root.render( <Suspense fallback={<Text text="Loading..." />}> <SuspenseyImage src="B" /> </Suspense>, ); }); }); assertLog(['Image requested [B]']); expect(getSuspenseyThingStatus('B')).toBe('pending'); // Should remain on previous screen expect(root).toMatchRenderedOutput(<suspensey-thing src="A" />); // This should synchronously commit resolveSuspenseyThing('B'); expect(root).toMatchRenderedOutput(<suspensey-thing src="B" />); }); test('does not suspend commit during urgent update', async () => { const root = ReactNoop.createRoot(); await act(async () => { root.render( <Suspense fallback={<Text text="Loading..." />}> <SuspenseyImage src="A" /> </Suspense>, ); }); // We intentionally don't preload during an urgent update because the // resource will be inserted synchronously, anyway. // TODO: Maybe we should, though? Could be that the browser is able to start // the preload in background even though the main thread is blocked. Likely // a micro-optimization either way because typically new content is loaded // during a transition, not an urgent render. expect(getSuspenseyThingStatus('A')).toBe(null); expect(root).toMatchRenderedOutput(<suspensey-thing src="A" />); }); test('an urgent update interrupts a suspended commit', async () => { const root = ReactNoop.createRoot(); // Mount an image. This transition will suspend because it's not inside a // Suspense boundary. await act(() => { startTransition(() => { root.render(<SuspenseyImage src="A" />); }); }); assertLog(['Image requested [A]']); // Nothing showing yet. expect(root).toMatchRenderedOutput(null); // If there's an update, it should interrupt the suspended commit. await act(() => { root.render(<Text text="Something else" />); }); assertLog(['Something else']); expect(root).toMatchRenderedOutput('Something else'); }); test('a transition update interrupts a suspended commit', async () => { const root = ReactNoop.createRoot(); // Mount an image. This transition will suspend because it's not inside a // Suspense boundary. await act(() => { startTransition(() => { root.render(<SuspenseyImage src="A" />); }); }); assertLog(['Image requested [A]']); // Nothing showing yet. expect(root).toMatchRenderedOutput(null); // If there's an update, it should interrupt the suspended commit. await act(() => { startTransition(() => { root.render(<Text text="Something else" />); }); }); assertLog(['Something else']); expect(root).toMatchRenderedOutput('Something else'); }); // @gate enableSuspenseList test('demonstrate current behavior when used with SuspenseList (not ideal)', async () => { function App() { return ( <SuspenseList revealOrder="forwards"> <Suspense fallback={<Text text="Loading A" />}> <SuspenseyImage src="A" /> </Suspense> <Suspense fallback={<Text text="Loading B" />}> <SuspenseyImage src="B" /> </Suspense> <Suspense fallback={<Text text="Loading C" />}> <SuspenseyImage src="C" /> </Suspense> </SuspenseList> ); } const root = ReactNoop.createRoot(); await act(() => { startTransition(() => { root.render(<App />); }); }); assertLog([ 'Image requested [A]', 'Loading A', 'Loading B', 'Loading C', 'Image requested [B]', 'Image requested [C]', ]); expect(root).toMatchRenderedOutput('Loading ALoading BLoading C'); // TODO: Notice that none of these items appear until they've all loaded. // That's not ideal; we should commit each row as it becomes ready to // commit. That means we need to prepare both the fallback and the primary // tree during the render phase. Related to Activity, too. resolveSuspenseyThing('A'); expect(root).toMatchRenderedOutput('Loading ALoading BLoading C'); resolveSuspenseyThing('B'); expect(root).toMatchRenderedOutput('Loading ALoading BLoading C'); resolveSuspenseyThing('C'); expect(root).toMatchRenderedOutput( <> <suspensey-thing src="A" /> <suspensey-thing src="B" /> <suspensey-thing src="C" /> </>, ); }); test('avoid triggering a fallback if resource loads immediately', async () => { const root = ReactNoop.createRoot(); await act(async () => { startTransition(() => { // Intentionally rendering <suspensey-thing>s in a variety of tree // positions to test that the work loop resumes correctly in each case. root.render( <Suspense fallback={<Text text="Loading..." />}> <suspensey-thing src="A" onLoadStart={() => Scheduler.log('Request [A]')}> <suspensey-thing src="B" onLoadStart={() => Scheduler.log('Request [B]')} /> </suspensey-thing> <suspensey-thing src="C" onLoadStart={() => Scheduler.log('Request [C]')} /> </Suspense>, ); }); // React will yield right after the resource suspends. // TODO: The child is preloaded first because we preload in the complete // phase. Ideally it should be in the begin phase, but we currently don't // create the instance until complete. However, it's unclear if we even // need the instance for preloading. So we should probably move this to // the begin phase. await waitForPaint(['Request [B]']); // Resolve in an immediate task. This could happen if the resource is // already loaded into the cache. resolveSuspenseyThing('B'); await waitForPaint(['Request [A]']); resolveSuspenseyThing('A'); await waitForPaint(['Request [C]']); resolveSuspenseyThing('C'); }); expect(root).toMatchRenderedOutput( <> <suspensey-thing src="A"> <suspensey-thing src="B" /> </suspensey-thing> <suspensey-thing src="C" /> </>, ); }); // @gate enableActivity test("host instances don't suspend during prerendering, but do suspend when they are revealed", async () => { function More() { Scheduler.log('More'); return <SuspenseyImage src="More" />; } function Details({showMore}) { Scheduler.log('Details'); const more = useMemo(() => <More />, []); return ( <> <div>Main Content</div> <Activity mode={showMore ? 'visible' : 'hidden'}>{more}</Activity> </> ); } const root = ReactNoop.createRoot(); await act(async () => { root.render(<Details showMore={false} />); // First render the outer component, without the hidden content await waitForPaint(['Details']); expect(root).toMatchRenderedOutput(<div>Main Content</div>); }); // Then prerender the hidden content. assertLog(['More', 'Image requested [More]']); // The prerender should commit even though the image is still loading, // because it's hidden. expect(root).toMatchRenderedOutput( <> <div>Main Content</div> <suspensey-thing hidden={true} src="More" /> </>, ); // Reveal the prerendered content. This update should suspend, because the // image that is being revealed still hasn't loaded. await act(() => { startTransition(() => { root.render(<Details showMore={true} />); }); }); // The More component should not render again, because it was memoized, // and it already prerendered. assertLog(['Details']); expect(root).toMatchRenderedOutput( <> <div>Main Content</div> <suspensey-thing hidden={true} src="More" /> </>, ); // Now resolve the image. The transition should complete. resolveSuspenseyThing('More'); expect(root).toMatchRenderedOutput( <> <div>Main Content</div> <suspensey-thing src="More" /> </>, ); }); });
31.450746
111
0.601656
null
'use strict'; const {spawn} = require('child_process'); const chalk = require('chalk'); const yargs = require('yargs'); const fs = require('fs'); const path = require('path'); const semver = require('semver'); const ossConfig = './scripts/jest/config.source.js'; const wwwConfig = './scripts/jest/config.source-www.js'; const devToolsConfig = './scripts/jest/config.build-devtools.js'; // TODO: These configs are separate but should be rolled into the configs above // so that the CLI can provide them as options for any of the configs. const persistentConfig = './scripts/jest/config.source-persistent.js'; const buildConfig = './scripts/jest/config.build.js'; const argv = yargs .parserConfiguration({ // Important: This option tells yargs to move all other options not // specified here into the `_` key. We use this to send all of the // Jest options that we don't use through to Jest (like --watch). 'unknown-options-as-args': true, }) .wrap(yargs.terminalWidth()) .options({ debug: { alias: 'd', describe: 'Run with node debugger attached.', requiresArg: false, type: 'boolean', default: false, }, project: { alias: 'p', describe: 'Run the given project.', requiresArg: true, type: 'string', default: 'default', choices: ['default', 'devtools'], }, releaseChannel: { alias: 'r', describe: 'Run with the given release channel.', requiresArg: true, type: 'string', default: 'experimental', choices: ['experimental', 'stable', 'www-classic', 'www-modern'], }, env: { alias: 'e', describe: 'Run with the given node environment.', requiresArg: true, type: 'string', choices: ['development', 'production'], }, prod: { describe: 'Run with NODE_ENV=production.', requiresArg: false, type: 'boolean', default: false, }, dev: { describe: 'Run with NODE_ENV=development.', requiresArg: false, type: 'boolean', default: false, }, variant: { alias: 'v', describe: 'Run with www variant set to true.', requiresArg: false, type: 'boolean', }, build: { alias: 'b', describe: 'Run tests on builds.', requiresArg: false, type: 'boolean', default: false, }, persistent: { alias: 'n', describe: 'Run with persistence.', requiresArg: false, type: 'boolean', default: false, }, ci: { describe: 'Run tests in CI', requiresArg: false, type: 'boolean', default: false, }, compactConsole: { alias: 'c', describe: 'Compact console output (hide file locations).', requiresArg: false, type: 'boolean', default: false, }, reactVersion: { describe: 'DevTools testing for specific version of React', requiresArg: true, type: 'string', }, sourceMaps: { describe: 'Enable inline source maps when transforming source files with Jest. Useful for debugging, but makes it slower.', type: 'boolean', default: false, }, }).argv; function logError(message) { console.error(chalk.red(`\n${message}`)); } function isWWWConfig() { return ( (argv.releaseChannel === 'www-classic' || argv.releaseChannel === 'www-modern') && argv.project !== 'devtools' ); } function isOSSConfig() { return ( argv.releaseChannel === 'stable' || argv.releaseChannel === 'experimental' ); } function validateOptions() { let success = true; if (argv.project === 'devtools') { if (argv.prod) { logError( 'DevTool tests do not support --prod. Remove this option to continue.' ); success = false; } if (argv.dev) { logError( 'DevTool tests do not support --dev. Remove this option to continue.' ); success = false; } if (argv.env) { logError( 'DevTool tests do not support --env. Remove this option to continue.' ); success = false; } if (argv.persistent) { logError( 'DevTool tests do not support --persistent. Remove this option to continue.' ); success = false; } if (argv.variant) { logError( 'DevTool tests do not support --variant. Remove this option to continue.' ); success = false; } if (!argv.build) { logError('DevTool tests require --build.'); success = false; } if (argv.reactVersion && !semver.validRange(argv.reactVersion)) { success = false; logError('please specify a valid version range for --reactVersion'); } } else { if (argv.compactConsole) { logError('Only DevTool tests support compactConsole flag.'); success = false; } if (argv.reactVersion) { logError('Only DevTools tests supports the --reactVersion flag.'); success = false; } } if (isWWWConfig()) { if (argv.variant === undefined) { // Turn internal experiments on by default argv.variant = true; } } else { if (argv.variant) { logError( 'Variant is only supported for the www release channels. Update these options to continue.' ); success = false; } } if (argv.build && argv.persistent) { logError( 'Persistence is not supported for build targets. Update these options to continue.' ); success = false; } if (!isOSSConfig() && argv.persistent) { logError( 'Persistence only supported for oss release channels. Update these options to continue.' ); success = false; } if (argv.build && isWWWConfig()) { logError( 'Build targets are only not supported for www release channels. Update these options to continue.' ); success = false; } if (argv.env && argv.env !== 'production' && argv.prod) { logError( 'Build type does not match --prod. Update these options to continue.' ); success = false; } if (argv.env && argv.env !== 'development' && argv.dev) { logError( 'Build type does not match --dev. Update these options to continue.' ); success = false; } if (argv.prod && argv.dev) { logError( 'Cannot supply both --prod and --dev. Remove one of these options to continue.' ); success = false; } if (argv.build) { // TODO: We could build this if it hasn't been built yet. const buildDir = path.resolve('./build'); if (!fs.existsSync(buildDir)) { logError( 'Build directory does not exist, please run `yarn build` or remove the --build option.' ); success = false; } else if (Date.now() - fs.statSync(buildDir).mtimeMs > 1000 * 60 * 15) { logError( 'Warning: Running a build test with a build directory older than 15 minutes.\nPlease remember to run `yarn build` when using --build.' ); } } if (!success) { console.log(''); // Extra newline. process.exit(1); } } function getCommandArgs() { // Add the correct Jest config. const args = ['./scripts/jest/jest.js', '--config']; if (argv.project === 'devtools') { args.push(devToolsConfig); } else if (argv.build) { args.push(buildConfig); } else if (argv.persistent) { args.push(persistentConfig); } else if (isWWWConfig()) { args.push(wwwConfig); } else if (isOSSConfig()) { args.push(ossConfig); } else { // We should not get here. logError('Unrecognized release channel'); process.exit(1); } // Set the debug options, if necessary. if (argv.debug) { args.unshift('--inspect-brk'); args.push('--runInBand'); // Prevent console logs from being hidden until test completes. args.push('--useStderr'); } // CI Environments have limited workers. if (argv.ci) { args.push('--maxWorkers=2'); } // Push the remaining args onto the command. // This will send args like `--watch` to Jest. args.push(...argv._); return args; } function getEnvars() { const envars = { NODE_ENV: argv.env || 'development', RELEASE_CHANNEL: argv.releaseChannel.match(/modern|experimental/) ? 'experimental' : 'stable', // Pass this flag through to the config environment // so the base config can conditionally load the console setup file. compactConsole: argv.compactConsole, }; if (argv.prod) { envars.NODE_ENV = 'production'; } if (argv.dev) { envars.NODE_ENV = 'development'; } if (argv.variant) { envars.VARIANT = true; } if (argv.reactVersion) { envars.REACT_VERSION = semver.coerce(argv.reactVersion); } if (argv.sourceMaps) { // This is off by default because it slows down the test runner, but it's // super useful when running the debugger. envars.JEST_ENABLE_SOURCE_MAPS = 'inline'; } return envars; } function main() { validateOptions(); const args = getCommandArgs(); const envars = getEnvars(); const env = Object.entries(envars).map(([k, v]) => `${k}=${v}`); // Print the full command we're actually running. const command = `$ ${env.join(' ')} node ${args.join(' ')}`; console.log(chalk.dim(command)); // Print the release channel and project we're running for quick confirmation. console.log( chalk.blue( `\nRunning tests for ${argv.project} (${argv.releaseChannel})...` ) ); // Print a message that the debugger is starting just // for some extra feedback when running the debugger. if (argv.debug) { console.log(chalk.green('\nStarting debugger...')); console.log(chalk.green('Open chrome://inspect and press "inspect"\n')); } // Run Jest. const jest = spawn('node', args, { stdio: 'inherit', env: {...envars, ...process.env}, }); // Ensure we close our process when we get a failure case. jest.on('close', code => { // Forward the exit code from the Jest process. if (code === 1) { process.exit(1); } }); } main();
24.919897
142
0.607677
null
'use strict'; const path = require('path'); const babel = require('@babel/core'); const coffee = require('coffee-script'); const hermesParser = require('hermes-parser'); const tsPreprocessor = require('./typescript/preprocessor'); const createCacheKeyFunction = require('fbjs-scripts/jest/createCacheKeyFunction'); const pathToBabel = path.join( require.resolve('@babel/core'), '../..', 'package.json' ); const pathToBabelPluginReplaceConsoleCalls = require.resolve( '../babel/transform-replace-console-calls' ); const pathToTransformInfiniteLoops = require.resolve( '../babel/transform-prevent-infinite-loops' ); const pathToTransformTestGatePragma = require.resolve( '../babel/transform-test-gate-pragma' ); const pathToTransformReactVersionPragma = require.resolve( '../babel/transform-react-version-pragma' ); const pathToBabelrc = path.join(__dirname, '..', '..', 'babel.config.js'); const pathToErrorCodes = require.resolve('../error-codes/codes.json'); const babelOptions = { plugins: [ // For Node environment only. For builds, Rollup takes care of ESM. require.resolve('@babel/plugin-transform-modules-commonjs'), // Keep stacks detailed in tests. // Don't put this in .babelrc so that we don't embed filenames // into ReactART builds that include JSX. // TODO: I have not verified that this actually works. require.resolve('@babel/plugin-transform-react-jsx-source'), pathToTransformInfiniteLoops, pathToTransformTestGatePragma, // This optimization is important for extremely performance-sensitive (e.g. React source). // It's okay to disable it for tests. [ require.resolve('@babel/plugin-transform-block-scoping'), {throwIfClosureRequired: false}, ], ], retainLines: true, }; module.exports = { process: function (src, filePath) { if (filePath.match(/\.css$/)) { // Don't try to parse CSS modules; they aren't needed for tests anyway. return {code: ''}; } if (filePath.match(/\.coffee$/)) { return {code: coffee.compile(src, {bare: true})}; } if (filePath.match(/\.ts$/) && !filePath.match(/\.d\.ts$/)) { return {code: tsPreprocessor.compile(src, filePath)}; } if (filePath.match(/\.json$/)) { return {code: src}; } if (!filePath.match(/\/third_party\//)) { // for test files, we also apply the async-await transform, but we want to // make sure we don't accidentally apply that transform to product code. const isTestFile = !!filePath.match(/\/__tests__\//); const isInDevToolsPackages = !!filePath.match( /\/packages\/react-devtools.*\// ); const testOnlyPlugins = []; const sourceOnlyPlugins = []; if (process.env.NODE_ENV === 'development' && !isInDevToolsPackages) { sourceOnlyPlugins.push(pathToBabelPluginReplaceConsoleCalls); } const plugins = (isTestFile ? testOnlyPlugins : sourceOnlyPlugins).concat( babelOptions.plugins ); if (isTestFile && isInDevToolsPackages) { plugins.push(pathToTransformReactVersionPragma); } let sourceAst = hermesParser.parse(src, {babel: true}); return { code: babel.transformFromAstSync( sourceAst, src, Object.assign( {filename: path.relative(process.cwd(), filePath)}, babelOptions, { plugins, sourceMaps: process.env.JEST_ENABLE_SOURCE_MAPS ? process.env.JEST_ENABLE_SOURCE_MAPS : false, } ) ).code, }; } return {code: src}; }, getCacheKey: createCacheKeyFunction( [ __filename, pathToBabel, pathToBabelrc, pathToTransformInfiniteLoops, pathToTransformTestGatePragma, pathToTransformReactVersionPragma, pathToErrorCodes, ], [ (process.env.REACT_VERSION != null).toString(), (process.env.NODE_ENV === 'development').toString(), ] ), };
30.97619
94
0.643496
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 { __DEBUG__, TREE_OPERATION_ADD, TREE_OPERATION_REMOVE, TREE_OPERATION_REMOVE_ROOT, TREE_OPERATION_REORDER_CHILDREN, TREE_OPERATION_SET_SUBTREE_MODE, TREE_OPERATION_UPDATE_TREE_BASE_DURATION, TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS, } from 'react-devtools-shared/src/constants'; import {utfDecodeStringWithRanges} from 'react-devtools-shared/src/utils'; import {ElementTypeRoot} from 'react-devtools-shared/src/frontend/types'; import ProfilerStore from 'react-devtools-shared/src/devtools/ProfilerStore'; import type {ElementType} from 'react-devtools-shared/src/frontend/types'; import type { CommitTree, CommitTreeNode, ProfilingDataForRootFrontend, } from 'react-devtools-shared/src/devtools/views/Profiler/types'; const debug = (methodName: string, ...args: Array<string>) => { if (__DEBUG__) { console.log( `%cCommitTreeBuilder %c${methodName}`, 'color: pink; font-weight: bold;', 'font-weight: bold;', ...args, ); } }; const rootToCommitTreeMap: Map<number, Array<CommitTree>> = new Map(); export function getCommitTree({ commitIndex, profilerStore, rootID, }: { commitIndex: number, profilerStore: ProfilerStore, rootID: number, }): CommitTree { if (!rootToCommitTreeMap.has(rootID)) { rootToCommitTreeMap.set(rootID, []); } const commitTrees = ((rootToCommitTreeMap.get( rootID, ): any): Array<CommitTree>); if (commitIndex < commitTrees.length) { return commitTrees[commitIndex]; } const {profilingData} = profilerStore; if (profilingData === null) { throw Error(`No profiling data available`); } const dataForRoot = profilingData.dataForRoots.get(rootID); if (dataForRoot == null) { throw Error(`Could not find profiling data for root "${rootID}"`); } const {operations} = dataForRoot; if (operations.length <= commitIndex) { throw Error( `getCommitTree(): Invalid commit "${commitIndex}" for root "${rootID}". There are only "${operations.length}" commits.`, ); } let commitTree: CommitTree = ((null: any): CommitTree); for (let index = commitTrees.length; index <= commitIndex; index++) { // Commits are generated sequentially and cached. // If this is the very first commit, start with the cached snapshot and apply the first mutation. // Otherwise load (or generate) the previous commit and append a mutation to it. if (index === 0) { const nodes = new Map<number, CommitTreeNode>(); // Construct the initial tree. recursivelyInitializeTree(rootID, 0, nodes, dataForRoot); // Mutate the tree if (operations != null && index < operations.length) { commitTree = updateTree({nodes, rootID}, operations[index]); if (__DEBUG__) { __printTree(commitTree); } commitTrees.push(commitTree); } } else { const previousCommitTree = commitTrees[index - 1]; commitTree = updateTree(previousCommitTree, operations[index]); if (__DEBUG__) { __printTree(commitTree); } commitTrees.push(commitTree); } } return commitTree; } function recursivelyInitializeTree( id: number, parentID: number, nodes: Map<number, CommitTreeNode>, dataForRoot: ProfilingDataForRootFrontend, ): void { const node = dataForRoot.snapshots.get(id); if (node != null) { nodes.set(id, { id, children: node.children, displayName: node.displayName, hocDisplayNames: node.hocDisplayNames, key: node.key, parentID, treeBaseDuration: ((dataForRoot.initialTreeBaseDurations.get( id, ): any): number), type: node.type, }); node.children.forEach(childID => recursivelyInitializeTree(childID, id, nodes, dataForRoot), ); } } function updateTree( commitTree: CommitTree, operations: Array<number>, ): CommitTree { // Clone the original tree so edits don't affect it. const nodes = new Map(commitTree.nodes); // Clone nodes before mutating them so edits don't affect them. const getClonedNode = (id: number): CommitTreeNode => { // $FlowFixMe[prop-missing] - recommended fix is to use object spread operator const clonedNode = ((Object.assign( {}, nodes.get(id), ): any): CommitTreeNode); nodes.set(id, clonedNode); return clonedNode; }; let i = 2; let id: number = ((null: any): number); // Reassemble the string table. const stringTable: Array<null | string> = [ null, // ID = 0 corresponds to the null string. ]; const stringTableSize = operations[i++]; const stringTableEnd = i + stringTableSize; while (i < stringTableEnd) { const nextLength = operations[i++]; const nextString = utfDecodeStringWithRanges( operations, i, i + nextLength - 1, ); stringTable.push(nextString); i += nextLength; } while (i < operations.length) { const operation = operations[i]; switch (operation) { case TREE_OPERATION_ADD: { id = ((operations[i + 1]: any): number); const type = ((operations[i + 2]: any): ElementType); i += 3; if (nodes.has(id)) { throw new Error( `Commit tree already contains fiber "${id}". This is a bug in React DevTools.`, ); } if (type === ElementTypeRoot) { i++; // isStrictModeCompliant i++; // Profiling flag i++; // supportsStrictMode flag i++; // hasOwnerMetadata flag if (__DEBUG__) { debug('Add', `new root fiber ${id}`); } const node: CommitTreeNode = { children: [], displayName: null, hocDisplayNames: null, id, key: null, parentID: 0, treeBaseDuration: 0, // This will be updated by a subsequent operation type, }; nodes.set(id, node); } else { const parentID = ((operations[i]: any): number); i++; i++; // ownerID const displayNameStringID = operations[i]; const displayName = stringTable[displayNameStringID]; i++; const keyStringID = operations[i]; const key = stringTable[keyStringID]; i++; if (__DEBUG__) { debug( 'Add', `fiber ${id} (${displayName || 'null'}) as child of ${parentID}`, ); } const parentNode = getClonedNode(parentID); parentNode.children = parentNode.children.concat(id); const node: CommitTreeNode = { children: [], displayName, hocDisplayNames: null, id, key, parentID, treeBaseDuration: 0, // This will be updated by a subsequent operation type, }; nodes.set(id, node); } break; } case TREE_OPERATION_REMOVE: { const removeLength = ((operations[i + 1]: any): number); i += 2; for (let removeIndex = 0; removeIndex < removeLength; removeIndex++) { id = ((operations[i]: any): number); i++; if (!nodes.has(id)) { throw new Error( `Commit tree does not contain fiber "${id}". This is a bug in React DevTools.`, ); } const node = getClonedNode(id); const parentID = node.parentID; nodes.delete(id); if (!nodes.has(parentID)) { // No-op } else { const parentNode = getClonedNode(parentID); if (__DEBUG__) { debug('Remove', `fiber ${id} from parent ${parentID}`); } parentNode.children = parentNode.children.filter( childID => childID !== id, ); } } break; } case TREE_OPERATION_REMOVE_ROOT: { throw Error('Operation REMOVE_ROOT is not supported while profiling.'); } case TREE_OPERATION_REORDER_CHILDREN: { id = ((operations[i + 1]: any): number); const numChildren = ((operations[i + 2]: any): number); const children = ((operations.slice( i + 3, i + 3 + numChildren, ): any): Array<number>); i = i + 3 + numChildren; if (__DEBUG__) { debug('Re-order', `fiber ${id} children ${children.join(',')}`); } const node = getClonedNode(id); node.children = Array.from(children); break; } case TREE_OPERATION_SET_SUBTREE_MODE: { id = operations[i + 1]; const mode = operations[i + 1]; i += 3; if (__DEBUG__) { debug('Subtree mode', `Subtree with root ${id} set to mode ${mode}`); } break; } case TREE_OPERATION_UPDATE_TREE_BASE_DURATION: { id = operations[i + 1]; const node = getClonedNode(id); node.treeBaseDuration = operations[i + 2] / 1000; // Convert microseconds back to milliseconds; if (__DEBUG__) { debug( 'Update', `fiber ${id} treeBaseDuration to ${node.treeBaseDuration}`, ); } i += 3; break; } case TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS: { id = operations[i + 1]; const numErrors = operations[i + 2]; const numWarnings = operations[i + 3]; i += 4; if (__DEBUG__) { debug( 'Warnings and Errors update', `fiber ${id} has ${numErrors} errors and ${numWarnings} warnings`, ); } break; } default: throw Error(`Unsupported Bridge operation "${operation}"`); } } return { nodes, rootID: commitTree.rootID, }; } export function invalidateCommitTrees(): void { rootToCommitTreeMap.clear(); } // DEBUG const __printTree = (commitTree: CommitTree) => { if (__DEBUG__) { const {nodes, rootID} = commitTree; console.group('__printTree()'); const queue = [rootID, 0]; while (queue.length > 0) { const id = queue.shift(); const depth = queue.shift(); const node = nodes.get(id); if (node == null) { throw Error(`Could not find node with id "${id}" in commit tree`); } console.log( `${'•'.repeat(depth)}${node.id}:${node.displayName || ''} ${ node.key ? `key:"${node.key}"` : '' } (${node.treeBaseDuration})`, ); node.children.forEach(childID => { queue.push(childID, depth + 1); }); } console.groupEnd(); } };
26.009926
126
0.574237
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'; import * as React from 'react'; import * as ReactDOM from 'react-dom'; import * as ReactDOMServer from 'react-dom/server'; import * as ReactTestUtils from 'react-dom/test-utils'; function getTestDocument(markup) { const doc = document.implementation.createHTMLDocument(''); doc.open(); doc.write( markup || '<!doctype html><html><meta charset=utf-8><title>test doc</title>', ); doc.close(); return doc; } describe('ReactTestUtils', () => { it('Simulate should have locally attached media events', () => { expect(Object.keys(ReactTestUtils.Simulate).sort()).toMatchSnapshot(); }); it('gives Jest mocks a passthrough implementation with mockComponent()', () => { class MockedComponent extends React.Component { render() { throw new Error('Should not get here.'); } } // This is close enough to what a Jest mock would give us. MockedComponent.prototype.render = jest.fn(); // Patch it up so it returns its children. expect(() => ReactTestUtils.mockComponent(MockedComponent)).toWarnDev( 'ReactTestUtils.mockComponent() is deprecated. ' + 'Use shallow rendering or jest.mock() instead.\n\n' + 'See https://reactjs.org/link/test-utils-mock-component for more information.', {withoutStack: true}, ); // De-duplication check ReactTestUtils.mockComponent(MockedComponent); const container = document.createElement('div'); ReactDOM.render(<MockedComponent>Hello</MockedComponent>, container); expect(container.textContent).toBe('Hello'); }); it('can scryRenderedComponentsWithType', () => { class Child extends React.Component { render() { return null; } } class Wrapper extends React.Component { render() { return ( <div> <Child /> </div> ); } } const renderedComponent = ReactTestUtils.renderIntoDocument(<Wrapper />); const scryResults = ReactTestUtils.scryRenderedComponentsWithType( renderedComponent, Child, ); expect(scryResults.length).toBe(1); }); it('can scryRenderedDOMComponentsWithClass with TextComponent', () => { class Wrapper extends React.Component { render() { return ( <div> Hello <span>Jim</span> </div> ); } } const renderedComponent = ReactTestUtils.renderIntoDocument(<Wrapper />); const scryResults = ReactTestUtils.scryRenderedDOMComponentsWithClass( renderedComponent, 'NonExistentClass', ); expect(scryResults.length).toBe(0); }); it('can scryRenderedDOMComponentsWithClass with className contains \\n', () => { class Wrapper extends React.Component { render() { return ( <div> Hello <span className={'x\ny'}>Jim</span> </div> ); } } const renderedComponent = ReactTestUtils.renderIntoDocument(<Wrapper />); const scryResults = ReactTestUtils.scryRenderedDOMComponentsWithClass( renderedComponent, 'x', ); expect(scryResults.length).toBe(1); }); it('can scryRenderedDOMComponentsWithClass with multiple classes', () => { class Wrapper extends React.Component { render() { return ( <div> Hello <span className={'x y z'}>Jim</span> </div> ); } } const renderedComponent = ReactTestUtils.renderIntoDocument(<Wrapper />); const scryResults1 = ReactTestUtils.scryRenderedDOMComponentsWithClass( renderedComponent, 'x y', ); expect(scryResults1.length).toBe(1); const scryResults2 = ReactTestUtils.scryRenderedDOMComponentsWithClass( renderedComponent, 'x z', ); expect(scryResults2.length).toBe(1); const scryResults3 = ReactTestUtils.scryRenderedDOMComponentsWithClass( renderedComponent, ['x', 'y'], ); expect(scryResults3.length).toBe(1); expect(scryResults1[0]).toBe(scryResults2[0]); expect(scryResults1[0]).toBe(scryResults3[0]); const scryResults4 = ReactTestUtils.scryRenderedDOMComponentsWithClass( renderedComponent, ['x', 'a'], ); expect(scryResults4.length).toBe(0); const scryResults5 = ReactTestUtils.scryRenderedDOMComponentsWithClass( renderedComponent, ['x a'], ); expect(scryResults5.length).toBe(0); }); it('traverses children in the correct order', () => { class Wrapper extends React.Component { render() { return <div>{this.props.children}</div>; } } const container = document.createElement('div'); ReactDOM.render( <Wrapper> {null} <div>purple</div> </Wrapper>, container, ); const tree = ReactDOM.render( <Wrapper> <div>orange</div> <div>purple</div> </Wrapper>, container, ); const log = []; ReactTestUtils.findAllInRenderedTree(tree, function (child) { if (ReactTestUtils.isDOMComponent(child)) { log.push(ReactDOM.findDOMNode(child).textContent); } }); // Should be document order, not mount order (which would be purple, orange) expect(log).toEqual(['orangepurple', 'orange', 'purple']); }); it('should support injected wrapper components as DOM components', () => { const injectedDOMComponents = [ 'button', 'form', 'iframe', 'img', 'input', 'option', 'select', 'textarea', ]; injectedDOMComponents.forEach(function (type) { const testComponent = ReactTestUtils.renderIntoDocument( React.createElement(type), ); expect(testComponent.tagName).toBe(type.toUpperCase()); expect(ReactTestUtils.isDOMComponent(testComponent)).toBe(true); }); // Full-page components (html, head, body) can't be rendered into a div // directly... class Root extends React.Component { htmlRef = React.createRef(); headRef = React.createRef(); bodyRef = React.createRef(); render() { return ( <html ref={this.htmlRef}> <head ref={this.headRef}> <title>hello</title> </head> <body ref={this.bodyRef}>hello, world</body> </html> ); } } const markup = ReactDOMServer.renderToString(<Root />); const testDocument = getTestDocument(markup); const component = ReactDOM.hydrate(<Root />, testDocument); expect(component.htmlRef.current.tagName).toBe('HTML'); expect(component.headRef.current.tagName).toBe('HEAD'); expect(component.bodyRef.current.tagName).toBe('BODY'); expect(ReactTestUtils.isDOMComponent(component.htmlRef.current)).toBe(true); expect(ReactTestUtils.isDOMComponent(component.headRef.current)).toBe(true); expect(ReactTestUtils.isDOMComponent(component.bodyRef.current)).toBe(true); }); it('can scry with stateless components involved', () => { const Function = () => ( <div> <hr /> </div> ); class SomeComponent extends React.Component { render() { return ( <div> <Function /> <hr /> </div> ); } } const inst = ReactTestUtils.renderIntoDocument(<SomeComponent />); const hrs = ReactTestUtils.scryRenderedDOMComponentsWithTag(inst, 'hr'); expect(hrs.length).toBe(2); }); it('provides a clear error when passing invalid objects to scry', () => { // This is probably too relaxed but it's existing behavior. ReactTestUtils.findAllInRenderedTree(null, 'span'); ReactTestUtils.findAllInRenderedTree(undefined, 'span'); ReactTestUtils.findAllInRenderedTree('', 'span'); ReactTestUtils.findAllInRenderedTree(0, 'span'); ReactTestUtils.findAllInRenderedTree(false, 'span'); expect(() => { ReactTestUtils.findAllInRenderedTree([], 'span'); }).toThrow( 'findAllInRenderedTree(...): the first argument must be a React class instance. ' + 'Instead received: an array.', ); expect(() => { ReactTestUtils.scryRenderedDOMComponentsWithClass(10, 'button'); }).toThrow( 'scryRenderedDOMComponentsWithClass(...): the first argument must be a React class instance. ' + 'Instead received: 10.', ); expect(() => { ReactTestUtils.findRenderedDOMComponentWithClass('hello', 'button'); }).toThrow( 'findRenderedDOMComponentWithClass(...): the first argument must be a React class instance. ' + 'Instead received: hello.', ); expect(() => { ReactTestUtils.scryRenderedDOMComponentsWithTag( {x: true, y: false}, 'span', ); }).toThrow( 'scryRenderedDOMComponentsWithTag(...): the first argument must be a React class instance. ' + 'Instead received: object with keys {x, y}.', ); const div = document.createElement('div'); expect(() => { ReactTestUtils.findRenderedDOMComponentWithTag(div, 'span'); }).toThrow( 'findRenderedDOMComponentWithTag(...): the first argument must be a React class instance. ' + 'Instead received: a DOM node.', ); expect(() => { ReactTestUtils.scryRenderedComponentsWithType(true, 'span'); }).toThrow( 'scryRenderedComponentsWithType(...): the first argument must be a React class instance. ' + 'Instead received: true.', ); expect(() => { ReactTestUtils.findRenderedComponentWithType(true, 'span'); }).toThrow( 'findRenderedComponentWithType(...): the first argument must be a React class instance. ' + 'Instead received: true.', ); }); describe('Simulate', () => { it('should change the value of an input field', () => { const obj = { handler: function (e) { e.persist(); }, }; spyOnDevAndProd(obj, 'handler'); const container = document.createElement('div'); const node = ReactDOM.render( <input type="text" onChange={obj.handler} />, container, ); node.value = 'giraffe'; ReactTestUtils.Simulate.change(node); expect(obj.handler).toHaveBeenCalledWith( expect.objectContaining({target: node}), ); }); it('should change the value of an input field in a component', () => { class SomeComponent extends React.Component { inputRef = React.createRef(); render() { return ( <div> <input type="text" ref={this.inputRef} onChange={this.props.handleChange} /> </div> ); } } const obj = { handler: function (e) { e.persist(); }, }; spyOnDevAndProd(obj, 'handler'); const container = document.createElement('div'); const instance = ReactDOM.render( <SomeComponent handleChange={obj.handler} />, container, ); const node = instance.inputRef.current; node.value = 'zebra'; ReactTestUtils.Simulate.change(node); expect(obj.handler).toHaveBeenCalledWith( expect.objectContaining({target: node}), ); }); it('should not warn when used with extra properties', () => { const CLIENT_X = 100; class Component extends React.Component { handleClick = e => { expect(e.clientX).toBe(CLIENT_X); }; render() { return <div onClick={this.handleClick} />; } } const element = document.createElement('div'); const instance = ReactDOM.render(<Component />, element); ReactTestUtils.Simulate.click(ReactDOM.findDOMNode(instance), { clientX: CLIENT_X, }); }); it('should set the type of the event', () => { let event; const stub = jest.fn().mockImplementation(e => { e.persist(); event = e; }); const container = document.createElement('div'); const instance = ReactDOM.render(<div onKeyDown={stub} />, container); const node = ReactDOM.findDOMNode(instance); ReactTestUtils.Simulate.keyDown(node); expect(event.type).toBe('keydown'); expect(event.nativeEvent.type).toBe('keydown'); }); it('should work with renderIntoDocument', () => { const onChange = jest.fn(); class MyComponent extends React.Component { render() { return ( <div> <input type="text" onChange={onChange} /> </div> ); } } const instance = ReactTestUtils.renderIntoDocument(<MyComponent />); const input = ReactTestUtils.findRenderedDOMComponentWithTag( instance, 'input', ); input.value = 'giraffe'; ReactTestUtils.Simulate.change(input); expect(onChange).toHaveBeenCalledWith( expect.objectContaining({target: input}), ); }); }); it('should call setState callback with no arguments', () => { let mockArgs; class Component extends React.Component { componentDidMount() { this.setState({}, (...args) => (mockArgs = args)); } render() { return false; } } ReactTestUtils.renderIntoDocument(<Component />); expect(mockArgs.length).toEqual(0); }); it('should find rendered component with type in document', () => { class MyComponent extends React.Component { render() { return true; } } const instance = ReactTestUtils.renderIntoDocument(<MyComponent />); const renderedComponentType = ReactTestUtils.findRenderedComponentWithType( instance, MyComponent, ); expect(renderedComponentType).toBe(instance); }); });
28.122407
102
0.610858
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'); const stripEmptyValues = function (obj) { const ret = {}; for (const name in obj) { if (!obj.hasOwnProperty(name)) { continue; } if (obj[name] !== null && obj[name] !== undefined) { ret[name] = obj[name]; } } return ret; }; let idCounter = 123; /** * Contains internal static internal state in order to test that updates to * existing children won't reinitialize components, when moving children - * reusing existing DOM/memory resources. */ class StatusDisplay extends React.Component { state = {internalState: idCounter++}; getStatus() { return this.props.status; } getInternalState() { return this.state.internalState; } componentDidMount() { this.props.onFlush(); } componentDidUpdate() { this.props.onFlush(); } render() { return <div>{this.props.contentKey}</div>; } } /** * Displays friends statuses. */ class FriendsStatusDisplay extends React.Component { displays = {}; /** * Gets the order directly from each rendered child's `index` field. * Refs are not maintained in the rendered order, and neither is * `this._renderedChildren` (surprisingly). */ getOriginalKeys() { const originalKeys = []; for (const key in this.props.usernameToStatus) { if (this.props.usernameToStatus[key]) { originalKeys.push(key); } } return originalKeys; } /** * Retrieves the rendered children in a nice format for comparing to the input * `this.props.usernameToStatus`. */ getStatusDisplays() { const res = {}; const originalKeys = this.getOriginalKeys(); for (let i = 0; i < originalKeys.length; i++) { const key = originalKeys[i]; res[key] = this.displays[key]; } return res; } /** * Verifies that by the time a child is flushed, the refs that appeared * earlier have already been resolved. * TODO: This assumption will likely break with incremental reconciler * but our internal layer API depends on this assumption. We need to change * it to be more declarative before making ref resolution indeterministic. */ verifyPreviousRefsResolved(flushedKey) { const originalKeys = this.getOriginalKeys(); for (let i = 0; i < originalKeys.length; i++) { const key = originalKeys[i]; if (key === flushedKey) { // We are only interested in children up to the current key. return; } expect(this.displays[key]).toBeTruthy(); } } render() { const children = []; for (const key in this.props.usernameToStatus) { const status = this.props.usernameToStatus[key]; children.push( !status ? null : ( <StatusDisplay key={key} ref={current => { this.displays[key] = current; }} contentKey={key} onFlush={this.verifyPreviousRefsResolved.bind(this, key)} status={status} /> ), ); } const childrenToRender = this.props.prepareChildren(children); return <div>{childrenToRender}</div>; } } function getInternalStateByUserName(statusDisplays) { return Object.keys(statusDisplays).reduce((acc, key) => { acc[key] = statusDisplays[key].getInternalState(); return acc; }, {}); } /** * Verifies that the rendered `StatusDisplay` instances match the `props` that * were responsible for allocating them. Checks the content of the user's status * message as well as the order of them. */ function verifyStatuses(statusDisplays, props) { const nonEmptyStatusDisplays = stripEmptyValues(statusDisplays); const nonEmptyStatusProps = stripEmptyValues(props.usernameToStatus); let username; expect(Object.keys(nonEmptyStatusDisplays).length).toEqual( Object.keys(nonEmptyStatusProps).length, ); for (username in nonEmptyStatusDisplays) { if (!nonEmptyStatusDisplays.hasOwnProperty(username)) { continue; } expect(nonEmptyStatusDisplays[username].getStatus()).toEqual( nonEmptyStatusProps[username], ); } // now go the other way to make sure we got them all. for (username in nonEmptyStatusProps) { if (!nonEmptyStatusProps.hasOwnProperty(username)) { continue; } expect(nonEmptyStatusDisplays[username].getStatus()).toEqual( nonEmptyStatusProps[username], ); } expect(Object.keys(nonEmptyStatusDisplays)).toEqual( Object.keys(nonEmptyStatusProps), ); } /** * For all statusDisplays that existed in the previous iteration of the * sequence, verify that the state has been preserved. `StatusDisplay` contains * a unique number that allows us to track internal state across ordering * movements. */ function verifyStatesPreserved(lastInternalStates, statusDisplays) { let key; for (key in statusDisplays) { if (!statusDisplays.hasOwnProperty(key)) { continue; } if (lastInternalStates[key]) { expect(lastInternalStates[key]).toEqual( statusDisplays[key].getInternalState(), ); } } } /** * Verifies that the internal representation of a set of `renderedChildren` * accurately reflects what is in the DOM. */ function verifyDomOrderingAccurate(outerContainer, statusDisplays) { const containerNode = outerContainer.firstChild; const statusDisplayNodes = containerNode.childNodes; const orderedDomKeys = []; for (let i = 0; i < statusDisplayNodes.length; i++) { const contentKey = statusDisplayNodes[i].textContent; orderedDomKeys.push(contentKey); } const orderedLogicalKeys = []; let username; for (username in statusDisplays) { if (!statusDisplays.hasOwnProperty(username)) { continue; } const statusDisplay = statusDisplays[username]; orderedLogicalKeys.push(statusDisplay.props.contentKey); } expect(orderedDomKeys).toEqual(orderedLogicalKeys); } function testPropsSequenceWithPreparedChildren(sequence, prepareChildren) { const container = document.createElement('div'); const parentInstance = ReactDOM.render( <FriendsStatusDisplay {...sequence[0]} prepareChildren={prepareChildren} />, container, ); let statusDisplays = parentInstance.getStatusDisplays(); let lastInternalStates = getInternalStateByUserName(statusDisplays); verifyStatuses(statusDisplays, sequence[0]); for (let i = 1; i < sequence.length; i++) { ReactDOM.render( <FriendsStatusDisplay {...sequence[i]} prepareChildren={prepareChildren} />, container, ); statusDisplays = parentInstance.getStatusDisplays(); verifyStatuses(statusDisplays, sequence[i]); verifyStatesPreserved(lastInternalStates, statusDisplays); verifyDomOrderingAccurate(container, statusDisplays); lastInternalStates = getInternalStateByUserName(statusDisplays); } } function prepareChildrenArray(childrenArray) { return childrenArray; } function prepareChildrenLegacyIterable(childrenArray) { return { '@@iterator': function* () { // eslint-disable-next-line no-for-of-loops/no-for-of-loops for (const child of childrenArray) { yield child; } }, }; } function prepareChildrenModernIterable(childrenArray) { return { [Symbol.iterator]: function* () { // eslint-disable-next-line no-for-of-loops/no-for-of-loops for (const child of childrenArray) { yield child; } }, }; } function testPropsSequence(sequence) { testPropsSequenceWithPreparedChildren(sequence, prepareChildrenArray); testPropsSequenceWithPreparedChildren( sequence, prepareChildrenLegacyIterable, ); testPropsSequenceWithPreparedChildren( sequence, prepareChildrenModernIterable, ); } describe('ReactMultiChildReconcile', () => { beforeEach(() => { jest.resetModules(); }); it('should reset internal state if removed then readded in an array', () => { // Test basics. const props = { usernameToStatus: { jcw: 'jcwStatus', }, }; const container = document.createElement('div'); const parentInstance = ReactDOM.render( <FriendsStatusDisplay {...props} prepareChildren={prepareChildrenArray} />, container, ); let statusDisplays = parentInstance.getStatusDisplays(); const startingInternalState = statusDisplays.jcw.getInternalState(); // Now remove the child. ReactDOM.render( <FriendsStatusDisplay prepareChildren={prepareChildrenArray} />, container, ); statusDisplays = parentInstance.getStatusDisplays(); expect(statusDisplays.jcw).toBeFalsy(); // Now reset the props that cause there to be a child ReactDOM.render( <FriendsStatusDisplay {...props} prepareChildren={prepareChildrenArray} />, container, ); statusDisplays = parentInstance.getStatusDisplays(); expect(statusDisplays.jcw).toBeTruthy(); expect(statusDisplays.jcw.getInternalState()).not.toBe( startingInternalState, ); }); it('should reset internal state if removed then readded in a legacy iterable', () => { // Test basics. const props = { usernameToStatus: { jcw: 'jcwStatus', }, }; const container = document.createElement('div'); const parentInstance = ReactDOM.render( <FriendsStatusDisplay {...props} prepareChildren={prepareChildrenLegacyIterable} />, container, ); let statusDisplays = parentInstance.getStatusDisplays(); const startingInternalState = statusDisplays.jcw.getInternalState(); // Now remove the child. ReactDOM.render( <FriendsStatusDisplay prepareChildren={prepareChildrenLegacyIterable} />, container, ); statusDisplays = parentInstance.getStatusDisplays(); expect(statusDisplays.jcw).toBeFalsy(); // Now reset the props that cause there to be a child ReactDOM.render( <FriendsStatusDisplay {...props} prepareChildren={prepareChildrenLegacyIterable} />, container, ); statusDisplays = parentInstance.getStatusDisplays(); expect(statusDisplays.jcw).toBeTruthy(); expect(statusDisplays.jcw.getInternalState()).not.toBe( startingInternalState, ); }); it('should reset internal state if removed then readded in a modern iterable', () => { // Test basics. const props = { usernameToStatus: { jcw: 'jcwStatus', }, }; const container = document.createElement('div'); const parentInstance = ReactDOM.render( <FriendsStatusDisplay {...props} prepareChildren={prepareChildrenModernIterable} />, container, ); let statusDisplays = parentInstance.getStatusDisplays(); const startingInternalState = statusDisplays.jcw.getInternalState(); // Now remove the child. ReactDOM.render( <FriendsStatusDisplay prepareChildren={prepareChildrenModernIterable} />, container, ); statusDisplays = parentInstance.getStatusDisplays(); expect(statusDisplays.jcw).toBeFalsy(); // Now reset the props that cause there to be a child ReactDOM.render( <FriendsStatusDisplay {...props} prepareChildren={prepareChildrenModernIterable} />, container, ); statusDisplays = parentInstance.getStatusDisplays(); expect(statusDisplays.jcw).toBeTruthy(); expect(statusDisplays.jcw.getInternalState()).not.toBe( startingInternalState, ); }); it('should create unique identity', () => { // Test basics. const usernameToStatus = { jcw: 'jcwStatus', awalke: 'awalkeStatus', bob: 'bobStatus', }; testPropsSequence([{usernameToStatus: usernameToStatus}]); }); it('should preserve order if children order has not changed', () => { const PROPS_SEQUENCE = [ { usernameToStatus: { jcw: 'jcwStatus', jordanjcw: 'jordanjcwStatus', }, }, { usernameToStatus: { jcw: 'jcwstatus2', jordanjcw: 'jordanjcwstatus2', }, }, ]; testPropsSequence(PROPS_SEQUENCE); }); it('should transition from zero to one children correctly', () => { const PROPS_SEQUENCE = [ {usernameToStatus: {}}, { usernameToStatus: { first: 'firstStatus', }, }, ]; testPropsSequence(PROPS_SEQUENCE); }); it('should transition from one to zero children correctly', () => { const PROPS_SEQUENCE = [ { usernameToStatus: { first: 'firstStatus', }, }, {usernameToStatus: {}}, ]; testPropsSequence(PROPS_SEQUENCE); }); it('should transition from one child to null children', () => { testPropsSequence([ { usernameToStatus: { first: 'firstStatus', }, }, {}, ]); }); it('should transition from null children to one child', () => { testPropsSequence([ {}, { usernameToStatus: { first: 'firstStatus', }, }, ]); }); it('should transition from zero children to null children', () => { testPropsSequence([ { usernameToStatus: {}, }, {}, ]); }); it('should transition from null children to zero children', () => { testPropsSequence([ {}, { usernameToStatus: {}, }, ]); }); /** * `FriendsStatusDisplay` renders nulls as empty children (it's a convention * of `FriendsStatusDisplay`, nothing related to React or these test cases. */ it('should remove nulled out children at the beginning', () => { const PROPS_SEQUENCE = [ { usernameToStatus: { jcw: 'jcwStatus', jordanjcw: 'jordanjcwStatus', }, }, { usernameToStatus: { jcw: null, jordanjcw: 'jordanjcwstatus2', }, }, ]; testPropsSequence(PROPS_SEQUENCE); }); it('should remove nulled out children at the end', () => { const PROPS_SEQUENCE = [ { usernameToStatus: { jcw: 'jcwStatus', jordanjcw: 'jordanjcwStatus', }, }, { usernameToStatus: { jcw: 'jcwstatus2', jordanjcw: null, }, }, ]; testPropsSequence(PROPS_SEQUENCE); }); it('should reverse the order of two children', () => { const PROPS_SEQUENCE = [ { usernameToStatus: { userOne: 'userOneStatus', userTwo: 'userTwoStatus', }, }, { usernameToStatus: { userTwo: 'userTwoStatus', userOne: 'userOneStatus', }, }, ]; testPropsSequence(PROPS_SEQUENCE); }); it('should reverse the order of more than two children', () => { const PROPS_SEQUENCE = [ { usernameToStatus: { userOne: 'userOneStatus', userTwo: 'userTwoStatus', userThree: 'userThreeStatus', }, }, { usernameToStatus: { userThree: 'userThreeStatus', userTwo: 'userTwoStatus', userOne: 'userOneStatus', }, }, ]; testPropsSequence(PROPS_SEQUENCE); }); it('should cycle order correctly', () => { const PROPS_SEQUENCE = [ { usernameToStatus: { userOne: 'userOneStatus', userTwo: 'userTwoStatus', userThree: 'userThreeStatus', userFour: 'userFourStatus', }, }, { usernameToStatus: { userTwo: 'userTwoStatus', userThree: 'userThreeStatus', userFour: 'userFourStatus', userOne: 'userOneStatus', }, }, { usernameToStatus: { userThree: 'userThreeStatus', userFour: 'userFourStatus', userOne: 'userOneStatus', userTwo: 'userTwoStatus', }, }, { usernameToStatus: { userFour: 'userFourStatus', userOne: 'userOneStatus', userTwo: 'userTwoStatus', userThree: 'userThreeStatus', }, }, { usernameToStatus: { // Full circle! userOne: 'userOneStatus', userTwo: 'userTwoStatus', userThree: 'userThreeStatus', userFour: 'userFourStatus', }, }, ]; testPropsSequence(PROPS_SEQUENCE); }); it('should cycle order correctly in the other direction', () => { const PROPS_SEQUENCE = [ { usernameToStatus: { userOne: 'userOneStatus', userTwo: 'userTwoStatus', userThree: 'userThreeStatus', userFour: 'userFourStatus', }, }, { usernameToStatus: { userFour: 'userFourStatus', userOne: 'userOneStatus', userTwo: 'userTwoStatus', userThree: 'userThreeStatus', }, }, { usernameToStatus: { userThree: 'userThreeStatus', userFour: 'userFourStatus', userOne: 'userOneStatus', userTwo: 'userTwoStatus', }, }, { usernameToStatus: { userTwo: 'userTwoStatus', userThree: 'userThreeStatus', userFour: 'userFourStatus', userOne: 'userOneStatus', }, }, { usernameToStatus: { // Full circle! userOne: 'userOneStatus', userTwo: 'userTwoStatus', userThree: 'userThreeStatus', userFour: 'userFourStatus', }, }, ]; testPropsSequence(PROPS_SEQUENCE); }); it('should remove nulled out children and ignore new null children', () => { const PROPS_SEQUENCE = [ { usernameToStatus: { jcw: 'jcwStatus', jordanjcw: 'jordanjcwStatus', }, }, { usernameToStatus: { jordanjcw: 'jordanjcwstatus2', jcw: null, another: null, }, }, ]; testPropsSequence(PROPS_SEQUENCE); }); it('should remove nulled out children and reorder remaining', () => { const PROPS_SEQUENCE = [ { usernameToStatus: { jcw: 'jcwStatus', jordanjcw: 'jordanjcwStatus', john: 'johnStatus', // john will go away joe: 'joeStatus', }, }, { usernameToStatus: { jordanjcw: 'jordanjcwStatus', joe: 'joeStatus', jcw: 'jcwStatus', }, }, ]; testPropsSequence(PROPS_SEQUENCE); }); it('should append children to the end', () => { const PROPS_SEQUENCE = [ { usernameToStatus: { jcw: 'jcwStatus', jordanjcw: 'jordanjcwStatus', }, }, { usernameToStatus: { jcw: 'jcwStatus', jordanjcw: 'jordanjcwStatus', jordanjcwnew: 'jordanjcwnewStatus', }, }, ]; testPropsSequence(PROPS_SEQUENCE); }); it('should append multiple children to the end', () => { const PROPS_SEQUENCE = [ { usernameToStatus: { jcw: 'jcwStatus', jordanjcw: 'jordanjcwStatus', }, }, { usernameToStatus: { jcw: 'jcwStatus', jordanjcw: 'jordanjcwStatus', jordanjcwnew: 'jordanjcwnewStatus', jordanjcwnew2: 'jordanjcwnewStatus2', }, }, ]; testPropsSequence(PROPS_SEQUENCE); }); it('should prepend children to the beginning', () => { const PROPS_SEQUENCE = [ { usernameToStatus: { jcw: 'jcwStatus', jordanjcw: 'jordanjcwStatus', }, }, { usernameToStatus: { newUsername: 'newUsernameStatus', jcw: 'jcwStatus', jordanjcw: 'jordanjcwStatus', }, }, ]; testPropsSequence(PROPS_SEQUENCE); }); it('should prepend multiple children to the beginning', () => { const PROPS_SEQUENCE = [ { usernameToStatus: { jcw: 'jcwStatus', jordanjcw: 'jordanjcwStatus', }, }, { usernameToStatus: { newNewUsername: 'newNewUsernameStatus', newUsername: 'newUsernameStatus', jcw: 'jcwStatus', jordanjcw: 'jordanjcwStatus', }, }, ]; testPropsSequence(PROPS_SEQUENCE); }); it('should not prepend an empty child to the beginning', () => { const PROPS_SEQUENCE = [ { usernameToStatus: { jcw: 'jcwStatus', jordanjcw: 'jordanjcwStatus', }, }, { usernameToStatus: { emptyUsername: null, jcw: 'jcwStatus', jordanjcw: 'jordanjcwStatus', }, }, ]; testPropsSequence(PROPS_SEQUENCE); }); it('should not append an empty child to the end', () => { const PROPS_SEQUENCE = [ { usernameToStatus: { jcw: 'jcwStatus', jordanjcw: 'jordanjcwStatus', }, }, { usernameToStatus: { jcw: 'jcwStatus', jordanjcw: 'jordanjcwStatus', emptyUsername: null, }, }, ]; testPropsSequence(PROPS_SEQUENCE); }); it('should not insert empty children in the middle', () => { const PROPS_SEQUENCE = [ { usernameToStatus: { jcw: 'jcwStatus', jordanjcw: 'jordanjcwStatus', }, }, { usernameToStatus: { jcw: 'jcwstatus2', skipOverMe: null, skipOverMeToo: null, definitelySkipOverMe: null, jordanjcw: 'jordanjcwstatus2', }, }, ]; testPropsSequence(PROPS_SEQUENCE); }); it('should insert one new child in the middle', () => { const PROPS_SEQUENCE = [ { usernameToStatus: { jcw: 'jcwStatus', jordanjcw: 'jordanjcwStatus', }, }, { usernameToStatus: { jcw: 'jcwstatus2', insertThis: 'insertThisStatus', jordanjcw: 'jordanjcwstatus2', }, }, ]; testPropsSequence(PROPS_SEQUENCE); }); it('should insert multiple new truthy children in the middle', () => { const PROPS_SEQUENCE = [ { usernameToStatus: { jcw: 'jcwStatus', jordanjcw: 'jordanjcwStatus', }, }, { usernameToStatus: { jcw: 'jcwstatus2', insertThis: 'insertThisStatus', insertThisToo: 'insertThisTooStatus', definitelyInsertThisToo: 'definitelyInsertThisTooStatus', jordanjcw: 'jordanjcwstatus2', }, }, ]; testPropsSequence(PROPS_SEQUENCE); }); it('should insert non-empty children in middle where nulls were', () => { const PROPS_SEQUENCE = [ { usernameToStatus: { jcw: 'jcwStatus', insertThis: null, insertThisToo: null, definitelyInsertThisToo: null, jordanjcw: 'jordanjcwStatus', }, }, { usernameToStatus: { jcw: 'jcwstatus2', insertThis: 'insertThisStatus', insertThisToo: 'insertThisTooStatus', definitelyInsertThisToo: 'definitelyInsertThisTooStatus', jordanjcw: 'jordanjcwstatus2', }, }, ]; testPropsSequence(PROPS_SEQUENCE); }); });
24.604752
88
0.5945
Penetration_Testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Fiber} from './ReactInternalTypes'; export type StackCursor<T> = {current: T}; const valueStack: Array<any> = []; let fiberStack: Array<Fiber | null>; if (__DEV__) { fiberStack = []; } let index = -1; function createCursor<T>(defaultValue: T): StackCursor<T> { return { current: defaultValue, }; } function isEmpty(): boolean { return index === -1; } function pop<T>(cursor: StackCursor<T>, fiber: Fiber): void { if (index < 0) { if (__DEV__) { console.error('Unexpected pop.'); } return; } if (__DEV__) { if (fiber !== fiberStack[index]) { console.error('Unexpected Fiber popped.'); } } cursor.current = valueStack[index]; valueStack[index] = null; if (__DEV__) { fiberStack[index] = null; } index--; } function push<T>(cursor: StackCursor<T>, value: T, fiber: Fiber): void { index++; valueStack[index] = cursor.current; if (__DEV__) { fiberStack[index] = fiber; } cursor.current = value; } function checkThatStackIsEmpty() { if (__DEV__) { if (index !== -1) { console.error( 'Expected an empty stack. Something was not reset properly.', ); } } } function resetStackAfterFatalErrorInDev() { if (__DEV__) { index = -1; valueStack.length = 0; fiberStack.length = 0; } } export { createCursor, isEmpty, pop, push, // DEV only: checkThatStackIsEmpty, resetStackAfterFatalErrorInDev, };
15.969388
72
0.608905
owtf
import FixtureSet from '../../FixtureSet'; import TestCase from '../../TestCase'; const React = window.React; function onButtonClick() { window.alert(`This shouldn't have happened!`); } export default class ButtonTestCases extends React.Component { render() { return ( <FixtureSet title="Buttons"> <TestCase title="onClick with disabled buttons" description="The onClick event handler should not be invoked when clicking on a disabled button"> <TestCase.Steps> <li>Click on the disabled button</li> </TestCase.Steps> <TestCase.ExpectedResult> Nothing should happen </TestCase.ExpectedResult> <button disabled onClick={onButtonClick}> Click Me </button> </TestCase> <TestCase title="onClick with disabled buttons containing other elements" description="The onClick event handler should not be invoked when clicking on a disabled button that contains other elements"> <TestCase.Steps> <li>Click on the disabled button, which contains a span</li> </TestCase.Steps> <TestCase.ExpectedResult> Nothing should happen </TestCase.ExpectedResult> <button disabled onClick={onButtonClick}> <span>Click Me</span> </button> </TestCase> </FixtureSet> ); } }
31.681818
136
0.617258
null
'use strict'; const {diff: jestDiff} = require('jest-diff'); const util = require('util'); const shouldIgnoreConsoleError = require('../shouldIgnoreConsoleError'); function normalizeCodeLocInfo(str) { if (typeof str !== 'string') { return str; } // This special case exists only for the special source location in // ReactElementValidator. That will go away if we remove source locations. str = str.replace(/Check your code at .+?:\d+/g, 'Check your code at **'); // V8 format: // at Component (/path/filename.js:123:45) // React format: // in Component (at filename.js:123) return str.replace(/\n +(?:at|in) ([\S]+)[^\n]*/g, function (m, name) { return '\n in ' + name + ' (at **)'; }); } const createMatcherFor = (consoleMethod, matcherName) => function matcher(callback, expectedMessages, options = {}) { if (__DEV__) { // Warn about incorrect usage of matcher. if (typeof expectedMessages === 'string') { expectedMessages = [expectedMessages]; } else if (!Array.isArray(expectedMessages)) { throw Error( `${matcherName}() requires a parameter of type string or an array of strings ` + `but was given ${typeof expectedMessages}.` ); } if ( options != null && (typeof options !== 'object' || Array.isArray(options)) ) { throw new Error( `${matcherName}() second argument, when present, should be an object. ` + 'Did you forget to wrap the messages into an array?' ); } if (arguments.length > 3) { // `matcher` comes from Jest, so it's more than 2 in practice throw new Error( `${matcherName}() received more than two arguments. ` + 'Did you forget to wrap the messages into an array?' ); } const withoutStack = options.withoutStack; const logAllErrors = options.logAllErrors; const warningsWithoutComponentStack = []; const warningsWithComponentStack = []; const unexpectedWarnings = []; let lastWarningWithMismatchingFormat = null; let lastWarningWithExtraComponentStack = null; // Catch errors thrown by the callback, // But only rethrow them if all test expectations have been satisfied. // Otherwise an Error in the callback can mask a failed expectation, // and result in a test that passes when it shouldn't. let caughtError; const isLikelyAComponentStack = message => typeof message === 'string' && (message.includes('\n in ') || message.includes('\n at ')); const consoleSpy = (format, ...args) => { // Ignore uncaught errors reported by jsdom // and React addendums because they're too noisy. if ( !logAllErrors && consoleMethod === 'error' && shouldIgnoreConsoleError(format, args) ) { return; } const message = util.format(format, ...args); const normalizedMessage = normalizeCodeLocInfo(message); // Remember if the number of %s interpolations // doesn't match the number of arguments. // We'll fail the test if it happens. let argIndex = 0; format.replace(/%s/g, () => argIndex++); if (argIndex !== args.length) { lastWarningWithMismatchingFormat = { format, args, expectedArgCount: argIndex, }; } // Protect against accidentally passing a component stack // to warning() which already injects the component stack. if ( args.length >= 2 && isLikelyAComponentStack(args[args.length - 1]) && isLikelyAComponentStack(args[args.length - 2]) ) { lastWarningWithExtraComponentStack = { format, }; } for (let index = 0; index < expectedMessages.length; index++) { const expectedMessage = expectedMessages[index]; if ( normalizedMessage === expectedMessage || normalizedMessage.includes(expectedMessage) ) { if (isLikelyAComponentStack(normalizedMessage)) { warningsWithComponentStack.push(normalizedMessage); } else { warningsWithoutComponentStack.push(normalizedMessage); } expectedMessages.splice(index, 1); return; } } let errorMessage; if (expectedMessages.length === 0) { errorMessage = 'Unexpected warning recorded: ' + this.utils.printReceived(normalizedMessage); } else if (expectedMessages.length === 1) { errorMessage = 'Unexpected warning recorded: ' + jestDiff(expectedMessages[0], normalizedMessage); } else { errorMessage = 'Unexpected warning recorded: ' + jestDiff(expectedMessages, [normalizedMessage]); } // Record the call stack for unexpected warnings. // We don't throw an Error here though, // Because it might be suppressed by ReactFiberScheduler. unexpectedWarnings.push(new Error(errorMessage)); }; // TODO Decide whether we need to support nested toWarn* expectations. // If we don't need it, add a check here to see if this is already our spy, // And throw an error. const originalMethod = console[consoleMethod]; // Avoid using Jest's built-in spy since it can't be removed. console[consoleMethod] = consoleSpy; const onFinally = () => { // Restore the unspied method so that unexpected errors fail tests. console[consoleMethod] = originalMethod; // Any unexpected Errors thrown by the callback should fail the test. // This should take precedence since unexpected errors could block warnings. if (caughtError) { throw caughtError; } // Any unexpected warnings should be treated as a failure. if (unexpectedWarnings.length > 0) { return { message: () => unexpectedWarnings[0].stack, pass: false, }; } // Any remaining messages indicate a failed expectations. if (expectedMessages.length > 0) { return { message: () => `Expected warning was not recorded:\n ${this.utils.printReceived( expectedMessages[0] )}`, pass: false, }; } if (typeof withoutStack === 'number') { // We're expecting a particular number of warnings without stacks. if (withoutStack !== warningsWithoutComponentStack.length) { return { message: () => `Expected ${withoutStack} warnings without a component stack but received ${warningsWithoutComponentStack.length}:\n` + warningsWithoutComponentStack.map(warning => this.utils.printReceived(warning) ), pass: false, }; } } else if (withoutStack === true) { // We're expecting that all warnings won't have the stack. // If some warnings have it, it's an error. if (warningsWithComponentStack.length > 0) { return { message: () => `Received warning unexpectedly includes a component stack:\n ${this.utils.printReceived( warningsWithComponentStack[0] )}\nIf this warning intentionally includes the component stack, remove ` + `{withoutStack: true} from the ${matcherName}() call. If you have a mix of ` + `warnings with and without stack in one ${matcherName}() call, pass ` + `{withoutStack: N} where N is the number of warnings without stacks.`, pass: false, }; } } else if (withoutStack === false || withoutStack === undefined) { // We're expecting that all warnings *do* have the stack (default). // If some warnings don't have it, it's an error. if (warningsWithoutComponentStack.length > 0) { return { message: () => `Received warning unexpectedly does not include a component stack:\n ${this.utils.printReceived( warningsWithoutComponentStack[0] )}\nIf this warning intentionally omits the component stack, add ` + `{withoutStack: true} to the ${matcherName} call.`, pass: false, }; } } else { throw Error( `The second argument for ${matcherName}(), when specified, must be an object. It may have a ` + `property called "withoutStack" whose value may be undefined, boolean, or a number. ` + `Instead received ${typeof withoutStack}.` ); } if (lastWarningWithMismatchingFormat !== null) { return { message: () => `Received ${ lastWarningWithMismatchingFormat.args.length } arguments for a message with ${ lastWarningWithMismatchingFormat.expectedArgCount } placeholders:\n ${this.utils.printReceived( lastWarningWithMismatchingFormat.format )}`, pass: false, }; } if (lastWarningWithExtraComponentStack !== null) { return { message: () => `Received more than one component stack for a warning:\n ${this.utils.printReceived( lastWarningWithExtraComponentStack.format )}\nDid you accidentally pass a stack to warning() as the last argument? ` + `Don't forget warning() already injects the component stack automatically.`, pass: false, }; } return {pass: true}; }; let returnPromise = null; try { const result = callback(); if ( typeof result === 'object' && result !== null && typeof result.then === 'function' ) { // `act` returns a thenable that can't be chained. // Once `act(async () => {}).then(() => {}).then(() => {})` works // we can just return `result.then(onFinally, error => ...)` returnPromise = new Promise((resolve, reject) => { result .then( () => { resolve(onFinally()); }, error => { caughtError = error; return resolve(onFinally()); } ) // In case onFinally throws we need to reject from this matcher .catch(error => { reject(error); }); }); } } catch (error) { caughtError = error; } finally { return returnPromise === null ? onFinally() : returnPromise; } } else { // Any uncaught errors or warnings should fail tests in production mode. const result = callback(); if ( typeof result === 'object' && result !== null && typeof result.then === 'function' ) { return result.then(() => { return {pass: true}; }); } else { return {pass: true}; } } }; module.exports = { toWarnDev: createMatcherFor('warn', 'toWarnDev'), toErrorDev: createMatcherFor('error', 'toErrorDev'), };
35.841772
135
0.558801
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 */ /************************************************************************ * This file is forked between different DevTools implementations. * It should never be imported directly! * It should always be imported from "react-devtools-feature-flags". ************************************************************************/ export const consoleManagedByDevToolsDuringStrictMode = false; export const enableLogger = false; export const enableStyleXFeatures = false; export const isInternalFacebookBuild = false; /************************************************************************ * Do not edit the code below. * It ensures this fork exports the same types as the default flags file. ************************************************************************/ import typeof * as FeatureFlagsType from './DevToolsFeatureFlags.default'; import typeof * as ExportsType from './DevToolsFeatureFlags.core-oss'; // Flow magic to verify the exports of this file match the original version. ((((null: any): ExportsType): FeatureFlagsType): ExportsType);
39.709677
76
0.58525
Hands-On-Penetration-Testing-with-Python
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; import {useContext, useMemo} from 'react'; import {SettingsContext} from './SettingsContext'; import {StoreContext} from '../context'; import {CHANGE_LOG_URL} from 'react-devtools-shared/src/devtools/constants'; import styles from './SettingsShared.css'; function getChangeLogUrl(version: ?string): string | null { if (!version) { return null; } // Version numbers are in the format of: <major>.<minor>.<patch>-<sha> // e.g. "4.23.0-f0dd459e0" // GitHub CHANGELOG headers are in the format of: <major>.<minor>.<patch> // but the "." are stripped from anchor tags, becomming: <major><minor><patch> const versionAnchor = version.replace(/^(\d+)\.(\d+)\.(\d+).*/, '$1$2$3'); return `${CHANGE_LOG_URL}#${versionAnchor}`; } export default function GeneralSettings(_: {}): React.Node { const { displayDensity, setDisplayDensity, setTheme, setTraceUpdatesEnabled, theme, traceUpdatesEnabled, } = useContext(SettingsContext); const {backendVersion, supportsTraceUpdates} = useContext(StoreContext); const frontendVersion = process.env.DEVTOOLS_VERSION; const showBackendVersion = backendVersion && backendVersion !== frontendVersion; return ( <div className={styles.Settings}> <div className={styles.Setting}> <div className={styles.RadioLabel}>Theme</div> <select className={styles.Select} value={theme} onChange={({currentTarget}) => setTheme(currentTarget.value)}> <option value="auto">Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select> </div> <div className={styles.Setting}> <div className={styles.RadioLabel}>Display density</div> <select className={styles.Select} value={displayDensity} onChange={({currentTarget}) => setDisplayDensity(currentTarget.value) }> <option value="compact">Compact</option> <option value="comfortable">Comfortable</option> </select> </div> {supportsTraceUpdates && ( <div className={styles.Setting}> <label> <input type="checkbox" checked={traceUpdatesEnabled} onChange={({currentTarget}) => setTraceUpdatesEnabled(currentTarget.checked) } />{' '} Highlight updates when components render. </label> </div> )} <div className={styles.ReleaseNotes}> {showBackendVersion && ( <div> <ul className={styles.VersionsList}> <li> <Version label="DevTools backend version:" version={backendVersion} /> </li> <li> <Version label="DevTools frontend version:" version={frontendVersion} /> </li> </ul> </div> )} {!showBackendVersion && ( <Version label="DevTools version:" version={frontendVersion} /> )} </div> </div> ); } function Version({label, version}: {label: string, version: ?string}) { const changelogLink = useMemo(() => { return getChangeLogUrl(version); }, [version]); if (version == null) { return null; } else { return ( <> {label}{' '} <a className={styles.ReleaseNotesLink} target="_blank" rel="noopener noreferrer" href={changelogLink}> {version} </a> </> ); } }
27.391304
80
0.567781
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 ReactNoopUpdateQueue from './ReactNoopUpdateQueue'; import assign from 'shared/assign'; const emptyObject = {}; if (__DEV__) { Object.freeze(emptyObject); } /** * Base class helpers for the updating state of a component. */ function Component(props, context, updater) { this.props = props; this.context = context; // If a component has string refs, we will assign a different object later. this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } Component.prototype.isReactComponent = {}; /** * Sets a subset of the state. Always use this to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * When a function is provided to setState, it will be called at some point in * the future (not synchronously). It will be called with the up to date * component arguments (state, props, context). These values can be different * from this.* because your function may be called after receiveProps but before * shouldComponentUpdate, and this new state, props, and context will not yet be * assigned to this. * * @param {object|function} partialState Next partial state or function to * produce next partial state to be merged with current state. * @param {?function} callback Called after state is updated. * @final * @protected */ Component.prototype.setState = function (partialState, callback) { if ( typeof partialState !== 'object' && typeof partialState !== 'function' && partialState != null ) { throw new Error( 'setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.', ); } this.updater.enqueueSetState(this, partialState, callback, 'setState'); }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ Component.prototype.forceUpdate = function (callback) { this.updater.enqueueForceUpdate(this, callback, 'forceUpdate'); }; /** * Deprecated APIs. These APIs used to exist on classic React classes but since * we would like to deprecate them, we're not going to move them over to this * modern base class. Instead, we define a getter that warns if it's accessed. */ if (__DEV__) { const deprecatedAPIs = { isMounted: [ 'isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.', ], replaceState: [ 'replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).', ], }; const defineDeprecationWarning = function (methodName, info) { Object.defineProperty(Component.prototype, methodName, { get: function () { console.warn( '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1], ); return undefined; }, }); }; for (const fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } function ComponentDummy() {} ComponentDummy.prototype = Component.prototype; /** * Convenience component with default shallow equality check for sCU. */ function PureComponent(props, context, updater) { this.props = props; this.context = context; // If a component has string refs, we will assign a different object later. this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; } const pureComponentPrototype = (PureComponent.prototype = new ComponentDummy()); pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods. assign(pureComponentPrototype, Component.prototype); pureComponentPrototype.isPureReactComponent = true; export {Component, PureComponent};
32.47619
80
0.708943
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; const fs = require('fs'); const path = require('path'); const errorMap = JSON.parse( fs.readFileSync(path.resolve(__dirname, '../error-codes/codes.json')) ); const errorMessages = new Set(); Object.keys(errorMap).forEach(key => errorMessages.add(errorMap[key])); function nodeToErrorTemplate(node) { if (node.type === 'Literal' && typeof node.value === 'string') { return node.value; } else if (node.type === 'BinaryExpression' && node.operator === '+') { const l = nodeToErrorTemplate(node.left); const r = nodeToErrorTemplate(node.right); return l + r; } else if (node.type === 'TemplateLiteral') { let elements = []; for (let i = 0; i < node.quasis.length; i++) { const elementNode = node.quasis[i]; if (elementNode.type !== 'TemplateElement') { throw new Error('Unsupported type ' + node.type); } elements.push(elementNode.value.cooked); } return elements.join('%s'); } else { return '%s'; } } module.exports = { meta: { schema: [], }, create(context) { function ErrorCallExpression(node) { const errorMessageNode = node.arguments[0]; if (errorMessageNode === undefined) { return; } const errorMessage = nodeToErrorTemplate(errorMessageNode); if (errorMessages.has(errorMessage)) { return; } context.report({ node, message: 'Error message does not have a corresponding production error code. Add ' + 'the following message to codes.json so it can be stripped ' + 'from the production builds:\n\n' + errorMessage, }); } return { NewExpression(node) { if (node.callee.type === 'Identifier' && node.callee.name === 'Error') { ErrorCallExpression(node); } }, CallExpression(node) { if (node.callee.type === 'Identifier' && node.callee.name === 'Error') { ErrorCallExpression(node); } }, }; }, };
26.95
85
0.6
owtf
import * as React from 'react'; export default function Container({children}) { return <div>{children}</div>; }
18.333333
47
0.695652
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "ComponentUsingHooksIndirectly", { enumerable: true, get: function () { return _ComponentUsingHooksIndirectly.Component; } }); Object.defineProperty(exports, "ComponentWithCustomHook", { enumerable: true, get: function () { return _ComponentWithCustomHook.Component; } }); Object.defineProperty(exports, "ComponentWithExternalCustomHooks", { enumerable: true, get: function () { return _ComponentWithExternalCustomHooks.Component; } }); Object.defineProperty(exports, "ComponentWithMultipleHooksPerLine", { enumerable: true, get: function () { return _ComponentWithMultipleHooksPerLine.Component; } }); Object.defineProperty(exports, "ComponentWithNestedHooks", { enumerable: true, get: function () { return _ComponentWithNestedHooks.Component; } }); Object.defineProperty(exports, "ContainingStringSourceMappingURL", { enumerable: true, get: function () { return _ContainingStringSourceMappingURL.Component; } }); Object.defineProperty(exports, "Example", { enumerable: true, get: function () { return _Example.Component; } }); Object.defineProperty(exports, "InlineRequire", { enumerable: true, get: function () { return _InlineRequire.Component; } }); Object.defineProperty(exports, "useTheme", { enumerable: true, get: function () { return _useTheme.default; } }); exports.ToDoList = void 0; var _ComponentUsingHooksIndirectly = require("./ComponentUsingHooksIndirectly"); var _ComponentWithCustomHook = require("./ComponentWithCustomHook"); var _ComponentWithExternalCustomHooks = require("./ComponentWithExternalCustomHooks"); var _ComponentWithMultipleHooksPerLine = require("./ComponentWithMultipleHooksPerLine"); var _ComponentWithNestedHooks = require("./ComponentWithNestedHooks"); var _ContainingStringSourceMappingURL = require("./ContainingStringSourceMappingURL"); var _Example = require("./Example"); var _InlineRequire = require("./InlineRequire"); var ToDoList = _interopRequireWildcard(require("./ToDoList")); exports.ToDoList = ToDoList; var _useTheme = _interopRequireDefault(require("./useTheme")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImluZGV4LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7QUFTQTs7QUFDQTs7QUFDQTs7QUFDQTs7QUFDQTs7QUFDQTs7QUFDQTs7QUFDQTs7QUFDQTs7OztBQUVBIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBDb3B5cmlnaHQgKGMpIEZhY2Vib29rLCBJbmMuIGFuZCBpdHMgYWZmaWxpYXRlcy5cbiAqXG4gKiBUaGlzIHNvdXJjZSBjb2RlIGlzIGxpY2Vuc2VkIHVuZGVyIHRoZSBNSVQgbGljZW5zZSBmb3VuZCBpbiB0aGVcbiAqIExJQ0VOU0UgZmlsZSBpbiB0aGUgcm9vdCBkaXJlY3Rvcnkgb2YgdGhpcyBzb3VyY2UgdHJlZS5cbiAqXG4gKiBAZmxvd1xuICovXG5cbmV4cG9ydCB7Q29tcG9uZW50IGFzIENvbXBvbmVudFVzaW5nSG9va3NJbmRpcmVjdGx5fSBmcm9tICcuL0NvbXBvbmVudFVzaW5nSG9va3NJbmRpcmVjdGx5JztcbmV4cG9ydCB7Q29tcG9uZW50IGFzIENvbXBvbmVudFdpdGhDdXN0b21Ib29rfSBmcm9tICcuL0NvbXBvbmVudFdpdGhDdXN0b21Ib29rJztcbmV4cG9ydCB7Q29tcG9uZW50IGFzIENvbXBvbmVudFdpdGhFeHRlcm5hbEN1c3RvbUhvb2tzfSBmcm9tICcuL0NvbXBvbmVudFdpdGhFeHRlcm5hbEN1c3RvbUhvb2tzJztcbmV4cG9ydCB7Q29tcG9uZW50IGFzIENvbXBvbmVudFdpdGhNdWx0aXBsZUhvb2tzUGVyTGluZX0gZnJvbSAnLi9Db21wb25lbnRXaXRoTXVsdGlwbGVIb29rc1BlckxpbmUnO1xuZXhwb3J0IHtDb21wb25lbnQgYXMgQ29tcG9uZW50V2l0aE5lc3RlZEhvb2tzfSBmcm9tICcuL0NvbXBvbmVudFdpdGhOZXN0ZWRIb29rcyc7XG5leHBvcnQge0NvbXBvbmVudCBhcyBDb250YWluaW5nU3RyaW5nU291cmNlTWFwcGluZ1VSTH0gZnJvbSAnLi9Db250YWluaW5nU3RyaW5nU291cmNlTWFwcGluZ1VSTCc7XG5leHBvcnQge0NvbXBvbmVudCBhcyBFeGFtcGxlfSBmcm9tICcuL0V4YW1wbGUnO1xuZXhwb3J0IHtDb21wb25lbnQgYXMgSW5saW5lUmVxdWlyZX0gZnJvbSAnLi9JbmxpbmVSZXF1aXJlJztcbmltcG9ydCAqIGFzIFRvRG9MaXN0IGZyb20gJy4vVG9Eb0xpc3QnO1xuZXhwb3J0IHtUb0RvTGlzdH07XG5leHBvcnQge2RlZmF1bHQgYXMgdXNlVGhlbWV9IGZyb20gJy4vdXNlVGhlbWUnO1xuIl19
54.235955
1,652
0.816073
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. * */ export default function Spinner({active = true}) { return ( <div className={['spinner', active && 'spinner--active'].join(' ')} role="progressbar" aria-busy={active ? 'true' : 'false'} /> ); }
22.277778
68
0.62201
Penetration-Testing-with-Shellcode
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type { Thenable, FulfilledThenable, RejectedThenable, } from 'shared/ReactTypes'; import type { ImportMetadata, ImportManifestEntry, } from './shared/ReactFlightImportMetadata'; import type {ModuleLoading} from 'react-client/src/ReactFlightClientConfig'; import { ID, CHUNKS, NAME, isAsyncImport, } from './shared/ReactFlightImportMetadata'; import {prepareDestinationWithChunks} from 'react-client/src/ReactFlightClientConfig'; import {loadChunk} from 'react-client/src/ReactFlightClientConfig'; export type SSRModuleMap = null | { [clientId: string]: { [clientExportName: string]: ClientReferenceManifestEntry, }, }; export type ServerManifest = { [id: string]: ImportManifestEntry, }; export type ServerReferenceId = string; export opaque type ClientReferenceManifestEntry = ImportManifestEntry; export opaque type ClientReferenceMetadata = ImportMetadata; // eslint-disable-next-line no-unused-vars export opaque type ClientReference<T> = ClientReferenceMetadata; // The reason this function needs to defined here in this file instead of just // being exported directly from the TurbopackDestination... file is because the // ClientReferenceMetadata is opaque and we can't unwrap it there. // This should get inlined and we could also just implement an unwrapping function // though that risks it getting used in places it shouldn't be. This is unfortunate // but currently it seems to be the best option we have. export function prepareDestinationForModule( moduleLoading: ModuleLoading, nonce: ?string, metadata: ClientReferenceMetadata, ) { prepareDestinationWithChunks(moduleLoading, metadata[CHUNKS], nonce); } export function resolveClientReference<T>( bundlerConfig: SSRModuleMap, metadata: ClientReferenceMetadata, ): ClientReference<T> { if (bundlerConfig) { const moduleExports = bundlerConfig[metadata[ID]]; let resolvedModuleData = moduleExports[metadata[NAME]]; let name; if (resolvedModuleData) { // The potentially aliased name. name = resolvedModuleData.name; } else { // If we don't have this specific name, we might have the full module. resolvedModuleData = moduleExports['*']; if (!resolvedModuleData) { throw new Error( 'Could not find the module "' + metadata[ID] + '" in the React SSR Manifest. ' + 'This is probably a bug in the React Server Components bundler.', ); } name = metadata[NAME]; } if (isAsyncImport(metadata)) { return [ resolvedModuleData.id, resolvedModuleData.chunks, name, 1 /* async */, ]; } else { return [resolvedModuleData.id, resolvedModuleData.chunks, name]; } } return metadata; } export function resolveServerReference<T>( bundlerConfig: ServerManifest, id: ServerReferenceId, ): ClientReference<T> { let name = ''; let resolvedModuleData = bundlerConfig[id]; if (resolvedModuleData) { // The potentially aliased name. name = resolvedModuleData.name; } else { // We didn't find this specific export name but we might have the * export // which contains this name as well. // TODO: It's unfortunate that we now have to parse this string. We should // probably go back to encoding path and name separately on the client reference. const idx = id.lastIndexOf('#'); if (idx !== -1) { name = id.slice(idx + 1); resolvedModuleData = bundlerConfig[id.slice(0, idx)]; } if (!resolvedModuleData) { throw new Error( 'Could not find the module "' + id + '" in the React Server Manifest. ' + 'This is probably a bug in the React Server Components bundler.', ); } } // TODO: This needs to return async: true if it's an async module. return [resolvedModuleData.id, resolvedModuleData.chunks, name]; } // The chunk cache contains all the chunks we've preloaded so far. // If they're still pending they're a thenable. This map also exists // in Turbopack but unfortunately it's not exposed so we have to // replicate it in user space. null means that it has already loaded. const chunkCache: Map<string, null | Promise<any>> = new Map(); function requireAsyncModule(id: string): null | Thenable<any> { // We've already loaded all the chunks. We can require the module. const promise = __turbopack_require__(id); if (typeof promise.then !== 'function') { // This wasn't a promise after all. return null; } else if (promise.status === 'fulfilled') { // This module was already resolved earlier. return null; } else { // Instrument the Promise to stash the result. promise.then( value => { const fulfilledThenable: FulfilledThenable<mixed> = (promise: any); fulfilledThenable.status = 'fulfilled'; fulfilledThenable.value = value; }, reason => { const rejectedThenable: RejectedThenable<mixed> = (promise: any); rejectedThenable.status = 'rejected'; rejectedThenable.reason = reason; }, ); return promise; } } function ignoreReject() { // We rely on rejected promises to be handled by another listener. } // Start preloading the modules since we might need them soon. // This function doesn't suspend. export function preloadModule<T>( metadata: ClientReference<T>, ): null | Thenable<any> { const chunks = metadata[CHUNKS]; const promises = []; for (let i = 0; i < chunks.length; i++) { const chunkFilename = chunks[i]; const entry = chunkCache.get(chunkFilename); if (entry === undefined) { const thenable = loadChunk(chunkFilename); promises.push(thenable); // $FlowFixMe[method-unbinding] const resolve = chunkCache.set.bind(chunkCache, chunkFilename, null); thenable.then(resolve, ignoreReject); chunkCache.set(chunkFilename, thenable); } else if (entry !== null) { promises.push(entry); } } if (isAsyncImport(metadata)) { if (promises.length === 0) { return requireAsyncModule(metadata[ID]); } else { return Promise.all(promises).then(() => { return requireAsyncModule(metadata[ID]); }); } } else if (promises.length > 0) { return Promise.all(promises); } else { return null; } } // Actually require the module or suspend if it's not yet ready. // Increase priority if necessary. export function requireModule<T>(metadata: ClientReference<T>): T { let moduleExports = __turbopack_require__(metadata[ID]); if (isAsyncImport(metadata)) { if (typeof moduleExports.then !== 'function') { // This wasn't a promise after all. } else if (moduleExports.status === 'fulfilled') { // This Promise should've been instrumented by preloadModule. moduleExports = moduleExports.value; } else { throw moduleExports.reason; } } if (metadata[NAME] === '*') { // This is a placeholder value that represents that the caller imported this // as a CommonJS module as is. return moduleExports; } if (metadata[NAME] === '') { // This is a placeholder value that represents that the caller accessed the // default property of this if it was an ESM interop module. return moduleExports.__esModule ? moduleExports.default : moduleExports; } return moduleExports[metadata[NAME]]; }
31.643777
86
0.682051
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 RecordToggle from './RecordToggle'; import styles from './Profiler.css'; export default function RecordingInProgress(): React.Node { return ( <div className={styles.Column}> <div className={styles.Header}>Profiling is in progress...</div> <div className={styles.Row}> Click the record button <RecordToggle /> to stop recording. </div> </div> ); }
24.24
70
0.673016
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 */ const EventListenerWWW = require('EventListener'); import typeof * as EventListenerType from '../EventListener'; import typeof * as EventListenerShimType from './EventListener-www'; export function addEventBubbleListener( target: EventTarget, eventType: string, listener: Function, ): mixed { return EventListenerWWW.listen(target, eventType, listener); } export function addEventCaptureListener( target: EventTarget, eventType: string, listener: Function, ): mixed { return EventListenerWWW.capture(target, eventType, listener); } export function addEventCaptureListenerWithPassiveFlag( target: EventTarget, eventType: string, listener: Function, passive: boolean, ): mixed { return EventListenerWWW.captureWithPassiveFlag( target, eventType, listener, passive, ); } export function addEventBubbleListenerWithPassiveFlag( target: EventTarget, eventType: string, listener: Function, passive: boolean, ): mixed { return EventListenerWWW.bubbleWithPassiveFlag( target, eventType, listener, passive, ); } export function removeEventListener( target: EventTarget, eventType: string, listener: Function, capture: boolean, ) { listener.remove(); } // Flow magic to verify the exports of this file match the original version. ((((null: any): EventListenerType): EventListenerShimType): EventListenerType);
21.757143
79
0.741834
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 */ /* eslint-disable react-internal/prod-error-codes */ // We expect that our Rollup, Jest, and Flow configurations // always shim this module with the corresponding host config // (either provided by a renderer, or a generic shim for npm). // // We should never resolve to this file, but it exists to make // sure that if we *do* accidentally break the configuration, // the failure isn't silent. throw new Error('This module must be shimmed by a specific renderer.');
31.095238
71
0.728083
PenetrationTestingScripts
/* global chrome */ 'use strict'; window.addEventListener('pageshow', function ({target}) { // Firefox's behaviour for injecting this content script can be unpredictable // While navigating the history, some content scripts might not be re-injected and still be alive if (!window.__REACT_DEVTOOLS_PROXY_INJECTED__) { window.__REACT_DEVTOOLS_PROXY_INJECTED__ = true; connectPort(); sayHelloToBackendManager(); // The backend waits to install the global hook until notified by the content script. // In the event of a page reload, the content script might be loaded before the backend manager is injected. // Because of this we need to poll the backend manager until it has been initialized. const intervalID = setInterval(() => { if (backendInitialized) { clearInterval(intervalID); } else { sayHelloToBackendManager(); } }, 500); } }); window.addEventListener('pagehide', function ({target}) { if (target !== window.document) { return; } delete window.__REACT_DEVTOOLS_PROXY_INJECTED__; }); let port = null; let backendInitialized: boolean = false; function sayHelloToBackendManager() { window.postMessage( { source: 'react-devtools-content-script', hello: true, }, '*', ); } function handleMessageFromDevtools(message) { window.postMessage( { source: 'react-devtools-content-script', payload: message, }, '*', ); } function handleMessageFromPage(event) { if (event.source !== window || !event.data) { return; } switch (event.data.source) { // This is a message from a bridge (initialized by a devtools backend) case 'react-devtools-bridge': { backendInitialized = true; port.postMessage(event.data.payload); break; } // This is a message from the backend manager, which runs in ExecutionWorld.MAIN // and can't use `chrome.runtime.sendMessage` case 'react-devtools-backend-manager': { const {source, payload} = event.data; chrome.runtime.sendMessage({ source, payload, }); break; } } } function handleDisconnect() { window.removeEventListener('message', handleMessageFromPage); port = null; connectPort(); } // Creates port from application page to the React DevTools' service worker // Which then connects it with extension port function connectPort() { port = chrome.runtime.connect({ name: 'proxy', }); window.addEventListener('message', handleMessageFromPage); port.onMessage.addListener(handleMessageFromDevtools); port.onDisconnect.addListener(handleDisconnect); }
24.238095
112
0.674972
owtf
'use strict'; module.exports = { plugins: [ '@babel/plugin-syntax-jsx', '@babel/plugin-transform-react-jsx', '@babel/plugin-transform-flow-strip-types', ['@babel/plugin-proposal-class-properties', {loose: true}], 'syntax-trailing-function-commas', [ '@babel/plugin-proposal-object-rest-spread', {loose: true, useBuiltIns: true}, ], ['@babel/plugin-transform-template-literals', {loose: true}], '@babel/plugin-transform-literals', '@babel/plugin-transform-arrow-functions', '@babel/plugin-transform-block-scoped-functions', '@babel/plugin-transform-object-super', '@babel/plugin-transform-shorthand-properties', '@babel/plugin-transform-computed-properties', '@babel/plugin-transform-for-of', ['@babel/plugin-transform-spread', {loose: true, useBuiltIns: true}], '@babel/plugin-transform-parameters', ['@babel/plugin-transform-destructuring', {loose: true, useBuiltIns: true}], ['@babel/plugin-transform-block-scoping', {throwIfClosureRequired: true}], ], };
36.571429
80
0.681256
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {ReactFabricType} from './src/ReactNativeTypes'; import * as ReactFabric from './src/ReactFabric'; // Assert that the exports line up with the type we're going to expose. (ReactFabric: ReactFabricType); export * from './src/ReactFabric';
27.5
71
0.723077
null
#!/usr/bin/env node 'use strict'; const chalk = require('chalk'); const {exec} = require('child-process-promise'); const {readJsonSync} = require('fs-extra'); const inquirer = require('inquirer'); const {join, relative} = require('path'); const {DRY_RUN, NPM_PACKAGES, ROOT_PATH} = require('./configuration'); const { checkNPMPermissions, clear, confirm, execRead, logger, readSavedBuildMetadata, } = require('./utils'); // This is the primary control function for this script. async function main() { clear(); await confirm('Have you run the build-and-test script?', () => { const buildAndTestScriptPath = join(__dirname, 'build-and-test.js'); const pathToPrint = relative(process.cwd(), buildAndTestScriptPath); console.log('Begin by running the build-and-test script:'); console.log(chalk.bold.green(' ' + pathToPrint)); }); const {archivePath, buildID} = readSavedBuildMetadata(); await checkNPMPermissions(); await publishToNPM(); await printFinalInstructions(buildID, archivePath); } async function printFinalInstructions(buildID, archivePath) { console.log(''); console.log( 'You are now ready to publish the extension to Chrome, Edge, and Firefox:' ); console.log( ` ${chalk.blue.underline( 'https://fburl.com/publish-react-devtools-extensions' )}` ); console.log(''); console.log('When publishing to Firefox, remember the following:'); console.log(` Build id: ${chalk.bold(buildID)}`); console.log(` Git archive: ${chalk.bold(archivePath)}`); console.log(''); console.log('Also consider syncing this release to Facebook:'); console.log(` ${chalk.bold.green('js1 upgrade react-devtools')}`); } async function publishToNPM() { const {otp} = await inquirer.prompt([ { type: 'input', name: 'otp', message: 'Please provide an NPM two-factor auth token:', }, ]); console.log(''); if (!otp) { console.error(chalk.red(`Invalid OTP provided: "${chalk.bold(otp)}"`)); process.exit(0); } for (let index = 0; index < NPM_PACKAGES.length; index++) { const npmPackage = NPM_PACKAGES[index]; const packagePath = join(ROOT_PATH, 'packages', npmPackage); const {version} = readJsonSync(join(packagePath, 'package.json')); // Check if this package version has already been published. // If so we might be resuming from a previous run. // We could infer this by comparing the build-info.json, // But for now the easiest way is just to ask if this is expected. const info = await execRead(`npm view ${npmPackage}@${version}`) // Early versions of npm view gives empty response, but newer versions give 404 error. // Catch the error to keep it consistent. .catch(childProcessError => { if (childProcessError.stderr.startsWith('npm ERR! code E404')) { return null; } throw childProcessError; }); if (info) { console.log(''); console.log( `${npmPackage} version ${chalk.bold( version )} has already been published.` ); await confirm(`Is this expected (will skip ${npmPackage}@${version})?`); continue; } if (DRY_RUN) { console.log(`Publishing package ${chalk.bold(npmPackage)}`); console.log(chalk.dim(` npm publish --otp=${otp}`)); } else { const publishPromise = exec(`npm publish --otp=${otp}`, { cwd: packagePath, }); await logger( publishPromise, `Publishing package ${chalk.bold(npmPackage)}`, { estimate: 2500, } ); } } } main();
27.398438
92
0.636764
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Fiber} from './ReactInternalTypes'; import type { ReactScopeInstance, ReactContext, ReactScopeQuery, } from 'shared/ReactTypes'; import { getPublicInstance, getInstanceFromNode, getInstanceFromScope, } from './ReactFiberConfig'; import {isFiberSuspenseAndTimedOut} from './ReactFiberTreeReflection'; import {HostComponent, ScopeComponent, ContextProvider} from './ReactWorkTags'; import {enableScopeAPI} from 'shared/ReactFeatureFlags'; function getSuspenseFallbackChild(fiber: Fiber): Fiber | null { return ((((fiber.child: any): Fiber).sibling: any): Fiber).child; } const emptyObject = {}; function collectScopedNodes( node: Fiber, fn: ReactScopeQuery, scopedNodes: Array<any>, ): void { if (enableScopeAPI) { if (node.tag === HostComponent) { const {type, memoizedProps, stateNode} = node; const instance = getPublicInstance(stateNode); if ( instance !== null && fn(type, memoizedProps || emptyObject, instance) === true ) { scopedNodes.push(instance); } } let child = node.child; if (isFiberSuspenseAndTimedOut(node)) { child = getSuspenseFallbackChild(node); } if (child !== null) { collectScopedNodesFromChildren(child, fn, scopedNodes); } } } function collectFirstScopedNode( node: Fiber, fn: ReactScopeQuery, ): null | Object { if (enableScopeAPI) { if (node.tag === HostComponent) { const {type, memoizedProps, stateNode} = node; const instance = getPublicInstance(stateNode); if (instance !== null && fn(type, memoizedProps, instance) === true) { return instance; } } let child = node.child; if (isFiberSuspenseAndTimedOut(node)) { child = getSuspenseFallbackChild(node); } if (child !== null) { return collectFirstScopedNodeFromChildren(child, fn); } } return null; } function collectScopedNodesFromChildren( startingChild: Fiber, fn: ReactScopeQuery, scopedNodes: Array<any>, ): void { let child: null | Fiber = startingChild; while (child !== null) { collectScopedNodes(child, fn, scopedNodes); child = child.sibling; } } function collectFirstScopedNodeFromChildren( startingChild: Fiber, fn: ReactScopeQuery, ): Object | null { let child: null | Fiber = startingChild; while (child !== null) { const scopedNode = collectFirstScopedNode(child, fn); if (scopedNode !== null) { return scopedNode; } child = child.sibling; } return null; } function collectNearestContextValues<T>( node: Fiber, context: ReactContext<T>, childContextValues: Array<T>, ): void { if (node.tag === ContextProvider && node.type._context === context) { const contextValue = node.memoizedProps.value; childContextValues.push(contextValue); } else { let child = node.child; if (isFiberSuspenseAndTimedOut(node)) { child = getSuspenseFallbackChild(node); } if (child !== null) { collectNearestChildContextValues(child, context, childContextValues); } } } function collectNearestChildContextValues<T>( startingChild: Fiber | null, context: ReactContext<T>, childContextValues: Array<T>, ): void { let child = startingChild; while (child !== null) { collectNearestContextValues(child, context, childContextValues); child = child.sibling; } } function DO_NOT_USE_queryAllNodes( this: $FlowFixMe, fn: ReactScopeQuery, ): null | Array<Object> { const currentFiber = getInstanceFromScope(this); if (currentFiber === null) { return null; } const child = currentFiber.child; const scopedNodes: Array<any> = []; if (child !== null) { collectScopedNodesFromChildren(child, fn, scopedNodes); } return scopedNodes.length === 0 ? null : scopedNodes; } function DO_NOT_USE_queryFirstNode( this: $FlowFixMe, fn: ReactScopeQuery, ): null | Object { const currentFiber = getInstanceFromScope(this); if (currentFiber === null) { return null; } const child = currentFiber.child; if (child !== null) { return collectFirstScopedNodeFromChildren(child, fn); } return null; } function containsNode(this: $FlowFixMe, node: Object): boolean { let fiber = getInstanceFromNode(node); while (fiber !== null) { if (fiber.tag === ScopeComponent && fiber.stateNode === this) { return true; } fiber = fiber.return; } return false; } function getChildContextValues<T>( this: $FlowFixMe, context: ReactContext<T>, ): Array<T> { const currentFiber = getInstanceFromScope(this); if (currentFiber === null) { return []; } const child = currentFiber.child; const childContextValues: Array<T> = []; if (child !== null) { collectNearestChildContextValues(child, context, childContextValues); } return childContextValues; } export function createScopeInstance(): ReactScopeInstance { return { DO_NOT_USE_queryAllNodes, DO_NOT_USE_queryFirstNode, containsNode, getChildContextValues, }; }
23.985646
79
0.679755
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 type {HookSourceAndMetadata} from './loadSourceAndMetadata'; import type {HooksNode, HooksTree} from 'react-debug-tools/src/ReactDebugHooks'; import type {HookNames} from 'react-devtools-shared/src/frontend/types'; import type {FetchFileWithCaching} from 'react-devtools-shared/src/devtools/views/Components/FetchFileWithCachingContext'; import {withAsyncPerfMeasurements} from 'react-devtools-shared/src/PerformanceLoggingUtils'; import WorkerizedParseSourceAndMetadata from './parseSourceAndMetadata.worker'; import typeof * as ParseSourceAndMetadataModule from './parseSourceAndMetadata'; import {flattenHooksList, loadSourceAndMetadata} from './loadSourceAndMetadata'; const workerizedParseHookNames: ParseSourceAndMetadataModule = WorkerizedParseSourceAndMetadata(); export function parseSourceAndMetadata( hooksList: Array<HooksNode>, locationKeyToHookSourceAndMetadata: Map<string, HookSourceAndMetadata>, ): Promise<HookNames | null> { return workerizedParseHookNames.parseSourceAndMetadata( hooksList, locationKeyToHookSourceAndMetadata, ); } export const purgeCachedMetadata = workerizedParseHookNames.purgeCachedMetadata; const EMPTY_MAP: HookNames = new Map(); export async function parseHookNames( hooksTree: HooksTree, fetchFileWithCaching: FetchFileWithCaching | null, ): Promise<HookNames | null> { return withAsyncPerfMeasurements('parseHookNames', async () => { const hooksList = flattenHooksList(hooksTree); if (hooksList.length === 0) { // This component tree contains no named hooks. return EMPTY_MAP; } // Runs on the main/UI thread so it can reuse Network cache: const locationKeyToHookSourceAndMetadata = await loadSourceAndMetadata( hooksList, fetchFileWithCaching, ); // Runs in a Worker because it's CPU intensive: return parseSourceAndMetadata( hooksList, locationKeyToHookSourceAndMetadata, ); }); }
34.196721
122
0.772134
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 */ // A pure JS implementation of a string hashing function. We do not use it for // security or obfuscation purposes, only to create compact hashes. So we // prioritize speed over collision avoidance. For example, we use this to hash // the component key path used by useFormState for MPA-style submissions. // // In environments where built-in hashing functions are available, we prefer // those instead. Like Node's crypto module, or Bun.hash. Unfortunately this // does not include the web standard crypto API because those methods are all // async. For our purposes, we need it to be sync because the cost of context // switching is too high to be worth it. // // The most popular hashing algorithm that meets these requirements in the JS // ecosystem is MurmurHash3, and almost all implementations I could find used // some version of the implementation by Gary Court inlined below. export function createFastHashJS(key: string): number { return murmurhash3_32_gc(key, 0); } /* eslint-disable prefer-const, no-fallthrough */ /** * @license * * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011) * * Copyright (c) 2011 Gary Court * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ function murmurhash3_32_gc(key: string, seed: number): number { let remainder, bytes, h1, h1b, c1, c2, k1, i; remainder = key.length & 3; // key.length % 4 bytes = key.length - remainder; h1 = seed; c1 = 0xcc9e2d51; c2 = 0x1b873593; i = 0; while (i < bytes) { k1 = (key.charCodeAt(i) & 0xff) | ((key.charCodeAt(++i) & 0xff) << 8) | ((key.charCodeAt(++i) & 0xff) << 16) | ((key.charCodeAt(++i) & 0xff) << 24); ++i; k1 = ((k1 & 0xffff) * c1 + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff; k1 = (k1 << 15) | (k1 >>> 17); k1 = ((k1 & 0xffff) * c2 + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff; h1 ^= k1; h1 = (h1 << 13) | (h1 >>> 19); h1b = ((h1 & 0xffff) * 5 + ((((h1 >>> 16) * 5) & 0xffff) << 16)) & 0xffffffff; h1 = (h1b & 0xffff) + 0x6b64 + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16); } k1 = 0; switch (remainder) { case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16; case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8; case 1: k1 ^= key.charCodeAt(i) & 0xff; k1 = ((k1 & 0xffff) * c1 + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff; k1 = (k1 << 15) | (k1 >>> 17); k1 = ((k1 & 0xffff) * c2 + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff; h1 ^= k1; } h1 ^= key.length; h1 ^= h1 >>> 16; h1 = ((h1 & 0xffff) * 0x85ebca6b + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff; h1 ^= h1 >>> 13; h1 = ((h1 & 0xffff) * 0xc2b2ae35 + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16)) & 0xffffffff; h1 ^= h1 >>> 16; return h1 >>> 0; }
32.585366
80
0.625182
Penetration-Testing-with-Shellcode
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from './src/ReactFlightDOMServerNode';
22
66
0.702381
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "ComponentUsingHooksIndirectly", { enumerable: true, get: function () { return _ComponentUsingHooksIndirectly.Component; } }); Object.defineProperty(exports, "ComponentWithCustomHook", { enumerable: true, get: function () { return _ComponentWithCustomHook.Component; } }); Object.defineProperty(exports, "ComponentWithExternalCustomHooks", { enumerable: true, get: function () { return _ComponentWithExternalCustomHooks.Component; } }); Object.defineProperty(exports, "ComponentWithMultipleHooksPerLine", { enumerable: true, get: function () { return _ComponentWithMultipleHooksPerLine.Component; } }); Object.defineProperty(exports, "ComponentWithNestedHooks", { enumerable: true, get: function () { return _ComponentWithNestedHooks.Component; } }); Object.defineProperty(exports, "ContainingStringSourceMappingURL", { enumerable: true, get: function () { return _ContainingStringSourceMappingURL.Component; } }); Object.defineProperty(exports, "Example", { enumerable: true, get: function () { return _Example.Component; } }); Object.defineProperty(exports, "InlineRequire", { enumerable: true, get: function () { return _InlineRequire.Component; } }); Object.defineProperty(exports, "useTheme", { enumerable: true, get: function () { return _useTheme.default; } }); exports.ToDoList = void 0; var _ComponentUsingHooksIndirectly = require("./ComponentUsingHooksIndirectly"); var _ComponentWithCustomHook = require("./ComponentWithCustomHook"); var _ComponentWithExternalCustomHooks = require("./ComponentWithExternalCustomHooks"); var _ComponentWithMultipleHooksPerLine = require("./ComponentWithMultipleHooksPerLine"); var _ComponentWithNestedHooks = require("./ComponentWithNestedHooks"); var _ContainingStringSourceMappingURL = require("./ContainingStringSourceMappingURL"); var _Example = require("./Example"); var _InlineRequire = require("./InlineRequire"); var ToDoList = _interopRequireWildcard(require("./ToDoList")); exports.ToDoList = ToDoList; var _useTheme = _interopRequireDefault(require("./useTheme")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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; } //# sourceMappingURL=index.js.map?foo=bar&param=some_value
36.325843
743
0.727793
null
#!/usr/bin/env node 'use strict'; const {exec} = require('child-process-promise'); const {readJsonSync} = require('fs-extra'); const {join} = require('path'); const {confirm, execRead} = require('../utils'); const theme = require('../theme'); const run = async ({cwd, dry, tags, ci}, packageName, otp) => { const packagePath = join(cwd, 'build/node_modules', packageName); const {version} = readJsonSync(join(packagePath, 'package.json')); // Check if this package version has already been published. // If so we might be resuming from a previous run. // We could infer this by comparing the build-info.json, // But for now the easiest way is just to ask if this is expected. const info = await execRead(`npm view ${packageName}@${version}`); if (info) { console.log( theme`{package ${packageName}} {version ${version}} has already been published.` ); if (!ci) { await confirm('Is this expected?'); } } else { console.log(theme`{spinnerSuccess ✓} Publishing {package ${packageName}}`); // Publish the package and tag it. if (!dry) { if (!ci) { await exec(`npm publish --tag=${tags[0]} --otp=${otp}`, { cwd: packagePath, }); console.log(theme.command(` cd ${packagePath}`)); console.log( theme.command(` npm publish --tag=${tags[0]} --otp=${otp}`) ); } else { await exec(`npm publish --tag=${tags[0]}`, { cwd: packagePath, }); console.log(theme.command(` cd ${packagePath}`)); console.log(theme.command(` npm publish --tag=${tags[0]}`)); } } for (let j = 1; j < tags.length; j++) { if (!dry) { if (!ci) { await exec( `npm dist-tag add ${packageName}@${version} ${tags[j]} --otp=${otp}`, {cwd: packagePath} ); console.log( theme.command( ` npm dist-tag add ${packageName}@${version} ${tags[j]} --otp=${otp}` ) ); } else { await exec(`npm dist-tag add ${packageName}@${version} ${tags[j]}`, { cwd: packagePath, }); console.log( theme.command( ` npm dist-tag add ${packageName}@${version} ${tags[j]}` ) ); } } } if (tags.includes('untagged')) { // npm doesn't let us publish without a tag at all, // so for one-off publishes we clean it up ourselves. if (!dry) { if (!ci) { await exec(`npm dist-tag rm ${packageName} untagged --otp=${otp}`); console.log( theme.command( ` npm dist-tag rm ${packageName} untagged --otp=${otp}` ) ); } else { await exec(`npm dist-tag rm ${packageName} untagged`); console.log( theme.command(` npm dist-tag rm ${packageName} untagged`) ); } } } } }; module.exports = run;
29.938144
86
0.526333
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. */ // This file is only used for tests. // It lazily loads the implementation so that we get the correct set of host configs. import ReactVersion from 'shared/ReactVersion'; export {ReactVersion as version}; export function renderToString() { return require('./src/server/ReactDOMLegacyServerBrowser').renderToString.apply( this, arguments, ); } export function renderToStaticMarkup() { return require('./src/server/ReactDOMLegacyServerBrowser').renderToStaticMarkup.apply( this, arguments, ); } export function renderToNodeStream() { return require('./src/server/ReactDOMLegacyServerBrowser').renderToNodeStream.apply( this, arguments, ); } export function renderToStaticNodeStream() { return require('./src/server/ReactDOMLegacyServerBrowser').renderToStaticNodeStream.apply( this, arguments, ); } export function renderToReadableStream() { return require('./src/server/react-dom-server.browser').renderToReadableStream.apply( this, arguments, ); } export function resume() { return require('./src/server/react-dom-server.browser').resume.apply( this, arguments, ); }
24.692308
92
0.732584
null
#!/usr/bin/env node 'use strict'; const commandLineArgs = require('command-line-args'); const {splitCommaParams} = require('../utils'); const paramDefinitions = [ { name: 'dry', type: Boolean, description: 'Dry run command without actually publishing to NPM.', defaultValue: false, }, { name: 'tags', type: String, multiple: true, description: 'NPM tags to point to the new release.', defaultValue: ['untagged'], }, { name: 'skipPackages', type: String, multiple: true, description: 'Packages to exclude from publishing', defaultValue: [], }, { name: 'ci', type: Boolean, description: 'Run in automated environment, without interactive prompts.', defaultValue: false, }, ]; module.exports = () => { const params = commandLineArgs(paramDefinitions); splitCommaParams(params.skipPackages); splitCommaParams(params.tags); params.tags.forEach(tag => { switch (tag) { case 'latest': case 'canary': case 'next': case 'experimental': case 'alpha': case 'beta': case 'rc': case 'untagged': break; default: console.error('Unsupported tag: "' + tag + '"'); process.exit(1); break; } }); return params; };
20.566667
78
0.600928
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Request} from 'react-server/src/ReactFizzServer'; export * from 'react-dom-bindings/src/server/ReactFizzConfigDOM'; // For now, we get this from the global scope, but this will likely move to a module. export const supportsRequestStorage = typeof AsyncLocalStorage === 'function'; export const requestStorage: AsyncLocalStorage<Request> = supportsRequestStorage ? new AsyncLocalStorage() : (null: any);
33.777778
85
0.7488
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export { renderToReadableStream, renderToNodeStream, renderToStaticNodeStream, version, } from './ReactDOMFizzServerBun.js';
20.125
66
0.724036
null
'use strict'; module.exports = { env: { commonjs: true, browser: true, }, globals: { // ES 6 BigInt: 'readonly', Map: 'readonly', Set: 'readonly', Proxy: 'readonly', Symbol: 'readonly', WeakMap: 'readonly', WeakSet: 'readonly', Int8Array: 'readonly', Uint8Array: 'readonly', Uint8ClampedArray: 'readonly', Int16Array: 'readonly', Uint16Array: 'readonly', Int32Array: 'readonly', Uint32Array: 'readonly', Float32Array: 'readonly', Float64Array: 'readonly', BigInt64Array: 'readonly', BigUint64Array: 'readonly', DataView: 'readonly', ArrayBuffer: 'readonly', Reflect: 'readonly', globalThis: 'readonly', FinalizationRegistry: 'readonly', // Vendor specific MSApp: 'readonly', __REACT_DEVTOOLS_GLOBAL_HOOK__: 'readonly', // CommonJS / Node process: 'readonly', setImmediate: 'readonly', Buffer: 'readonly', // Trusted Types trustedTypes: 'readonly', // Scheduler profiling TaskController: 'readonly', reportError: 'readonly', AggregateError: 'readonly', // Flight Promise: 'readonly', // Temp AsyncLocalStorage: 'readonly', async_hooks: 'readonly', // Flight Webpack __webpack_chunk_load__: 'readonly', __webpack_require__: 'readonly', // Flight Turbopack __turbopack_load__: 'readonly', __turbopack_require__: 'readonly', // jest expect: 'readonly', jest: 'readonly', // act IS_REACT_ACT_ENVIRONMENT: 'readonly', Bun: 'readonly', }, parserOptions: { ecmaVersion: 2020, sourceType: 'module', }, rules: { 'no-undef': 'error', 'no-shadow-restricted-names': 'error', }, // These plugins aren't used, but eslint complains if an eslint-ignore comment // references unused plugins. An alternate approach could be to strip // eslint-ignore comments as part of the build. plugins: ['ft-flow', 'jest', 'no-for-of-loops', 'react', 'react-internal'], };
21.444444
80
0.617137
PenetrationTestingScripts
module.exports = require('./dist/backend');
21.5
43
0.704545
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. * * @emails react-core * @jest-environment node */ 'use strict'; let React; let ReactDebugTools; describe('ReactHooksInspection', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactDebugTools = require('react-debug-tools'); }); it('should inspect a simple useState hook', () => { function Foo(props) { const [state] = React.useState('hello world'); return <div>{state}</div>; } const tree = ReactDebugTools.inspectHooks(Foo, {}); expect(tree).toEqual([ { isStateEditable: true, id: 0, name: 'State', value: 'hello world', subHooks: [], }, ]); }); it('should inspect a simple custom hook', () => { function useCustom(value) { const [state] = React.useState(value); React.useDebugValue('custom hook label'); return state; } function Foo(props) { const value = useCustom('hello world'); return <div>{value}</div>; } const tree = ReactDebugTools.inspectHooks(Foo, {}); expect(tree).toEqual([ { isStateEditable: false, id: null, name: 'Custom', value: __DEV__ ? 'custom hook label' : undefined, subHooks: [ { isStateEditable: true, id: 0, name: 'State', value: 'hello world', subHooks: [], }, ], }, ]); }); it('should inspect a tree of multiple hooks', () => { function effect() {} function useCustom(value) { const [state] = React.useState(value); React.useEffect(effect); return state; } function Foo(props) { const value1 = useCustom('hello'); const value2 = useCustom('world'); return ( <div> {value1} {value2} </div> ); } const tree = ReactDebugTools.inspectHooks(Foo, {}); expect(tree).toEqual([ { isStateEditable: false, id: null, name: 'Custom', value: undefined, subHooks: [ { isStateEditable: true, id: 0, name: 'State', subHooks: [], value: 'hello', }, { isStateEditable: false, id: 1, name: 'Effect', subHooks: [], value: effect, }, ], }, { isStateEditable: false, id: null, name: 'Custom', value: undefined, subHooks: [ { isStateEditable: true, id: 2, name: 'State', value: 'world', subHooks: [], }, { isStateEditable: false, id: 3, name: 'Effect', value: effect, subHooks: [], }, ], }, ]); }); it('should inspect a tree of multiple levels of hooks', () => { function effect() {} function useCustom(value) { const [state] = React.useReducer((s, a) => s, value); React.useEffect(effect); return state; } function useBar(value) { const result = useCustom(value); React.useLayoutEffect(effect); return result; } function useBaz(value) { React.useLayoutEffect(effect); const result = useCustom(value); return result; } function Foo(props) { const value1 = useBar('hello'); const value2 = useBaz('world'); return ( <div> {value1} {value2} </div> ); } const tree = ReactDebugTools.inspectHooks(Foo, {}); expect(tree).toEqual([ { isStateEditable: false, id: null, name: 'Bar', value: undefined, subHooks: [ { isStateEditable: false, id: null, name: 'Custom', value: undefined, subHooks: [ { isStateEditable: true, id: 0, name: 'Reducer', value: 'hello', subHooks: [], }, { isStateEditable: false, id: 1, name: 'Effect', value: effect, subHooks: [], }, ], }, { isStateEditable: false, id: 2, name: 'LayoutEffect', value: effect, subHooks: [], }, ], }, { isStateEditable: false, id: null, name: 'Baz', value: undefined, subHooks: [ { isStateEditable: false, id: 3, name: 'LayoutEffect', value: effect, subHooks: [], }, { isStateEditable: false, id: null, name: 'Custom', subHooks: [ { isStateEditable: true, id: 4, name: 'Reducer', subHooks: [], value: 'world', }, { isStateEditable: false, id: 5, name: 'Effect', subHooks: [], value: effect, }, ], value: undefined, }, ], }, ]); }); it('should inspect the default value using the useContext hook', () => { const MyContext = React.createContext('default'); function Foo(props) { const value = React.useContext(MyContext); return <div>{value}</div>; } const tree = ReactDebugTools.inspectHooks(Foo, {}); expect(tree).toEqual([ { isStateEditable: false, id: null, name: 'Context', value: 'default', subHooks: [], }, ]); }); it('should support an injected dispatcher', () => { const initial = { useState() { throw new Error("Should've been proxied"); }, }; let current = initial; let getterCalls = 0; const setterCalls = []; const FakeDispatcherRef = { get current() { getterCalls++; return current; }, set current(value) { setterCalls.push(value); current = value; }, }; function Foo(props) { const [state] = FakeDispatcherRef.current.useState('hello world'); return <div>{state}</div>; } ReactDebugTools.inspectHooks(Foo, {}, FakeDispatcherRef); expect(getterCalls).toBe(2); expect(setterCalls).toHaveLength(2); expect(setterCalls[0]).not.toBe(initial); expect(setterCalls[1]).toBe(initial); }); describe('useDebugValue', () => { it('should be ignored when called outside of a custom hook', () => { function Foo(props) { React.useDebugValue('this is invalid'); return null; } const tree = ReactDebugTools.inspectHooks(Foo, {}); expect(tree).toHaveLength(0); }); it('should support an optional formatter function param', () => { function useCustom() { React.useDebugValue({bar: 123}, object => `bar:${object.bar}`); React.useState(0); } function Foo(props) { useCustom(); return null; } const tree = ReactDebugTools.inspectHooks(Foo, {}); expect(tree).toEqual([ { isStateEditable: false, id: null, name: 'Custom', value: __DEV__ ? 'bar:123' : undefined, subHooks: [ { isStateEditable: true, id: 0, name: 'State', subHooks: [], value: 0, }, ], }, ]); }); }); });
23.135952
74
0.469454
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Fiber} from './ReactInternalTypes'; import {getStackByFiberInDevAndProd} from './ReactFiberComponentStack'; export type CapturedValue<T> = { value: T, source: Fiber | null, stack: string | null, digest: string | null, }; export function createCapturedValueAtFiber<T>( value: T, source: Fiber, ): CapturedValue<T> { // If the value is an error, call this function immediately after it is thrown // so the stack is accurate. return { value, source, stack: getStackByFiberInDevAndProd(source), digest: null, }; } export function createCapturedValue<T>( value: T, digest: ?string, stack: ?string, ): CapturedValue<T> { return { value, source: null, stack: stack != null ? stack : null, digest: digest != null ? digest : null, }; }
20.510638
80
0.672277
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 countState = (0, _react.useState)(0); const count = countState[0]; const setCount = countState[1]; const darkMode = useIsDarkMode(); const [isDarkMode] = darkMode; (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: 28, columnNumber: 7 } }, "Dark mode? ", isDarkMode), /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 29, columnNumber: 7 } }, "Count: ", count), /*#__PURE__*/_react.default.createElement("button", { onClick: handleClick, __source: { fileName: _jsxFileName, lineNumber: 30, columnNumber: 7 } }, "Update count")); } function useIsDarkMode() { const darkModeState = (0, _react.useState)(false); const [isDarkMode] = darkModeState; (0, _react.useEffect)(function useEffectCreate() {// Here is where we may listen to a "theme" event... }, []); return [isDarkMode, () => {}]; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFVzaW5nSG9va3NJbmRpcmVjdGx5LmpzIl0sIm5hbWVzIjpbIkNvbXBvbmVudCIsImNvdW50U3RhdGUiLCJjb3VudCIsInNldENvdW50IiwiZGFya01vZGUiLCJ1c2VJc0RhcmtNb2RlIiwiaXNEYXJrTW9kZSIsImhhbmRsZUNsaWNrIiwiZGFya01vZGVTdGF0ZSIsInVzZUVmZmVjdENyZWF0ZSJdLCJtYXBwaW5ncyI6Ijs7Ozs7OztBQVNBOzs7Ozs7OztBQUVPLFNBQVNBLFNBQVQsR0FBcUI7QUFDMUIsUUFBTUMsVUFBVSxHQUFHLHFCQUFTLENBQVQsQ0FBbkI7QUFDQSxRQUFNQyxLQUFLLEdBQUdELFVBQVUsQ0FBQyxDQUFELENBQXhCO0FBQ0EsUUFBTUUsUUFBUSxHQUFHRixVQUFVLENBQUMsQ0FBRCxDQUEzQjtBQUVBLFFBQU1HLFFBQVEsR0FBR0MsYUFBYSxFQUE5QjtBQUNBLFFBQU0sQ0FBQ0MsVUFBRCxJQUFlRixRQUFyQjtBQUVBLHdCQUFVLE1BQU0sQ0FDZDtBQUNELEdBRkQsRUFFRyxFQUZIOztBQUlBLFFBQU1HLFdBQVcsR0FBRyxNQUFNSixRQUFRLENBQUNELEtBQUssR0FBRyxDQUFULENBQWxDOztBQUVBLHNCQUNFLHlFQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLG9CQUFpQkksVUFBakIsQ0FERixlQUVFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGdCQUFhSixLQUFiLENBRkYsZUFHRTtBQUFRLElBQUEsT0FBTyxFQUFFSyxXQUFqQjtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxvQkFIRixDQURGO0FBT0Q7O0FBRUQsU0FBU0YsYUFBVCxHQUF5QjtBQUN2QixRQUFNRyxhQUFhLEdBQUcscUJBQVMsS0FBVCxDQUF0QjtBQUNBLFFBQU0sQ0FBQ0YsVUFBRCxJQUFlRSxhQUFyQjtBQUVBLHdCQUFVLFNBQVNDLGVBQVQsR0FBMkIsQ0FDbkM7QUFDRCxHQUZELEVBRUcsRUFGSDtBQUlBLFNBQU8sQ0FBQ0gsVUFBRCxFQUFhLE1BQU0sQ0FBRSxDQUFyQixDQUFQO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IFJlYWN0LCB7dXNlRWZmZWN0LCB1c2VTdGF0ZX0gZnJvbSAncmVhY3QnO1xuXG5leHBvcnQgZnVuY3Rpb24gQ29tcG9uZW50KCkge1xuICBjb25zdCBjb3VudFN0YXRlID0gdXNlU3RhdGUoMCk7XG4gIGNvbnN0IGNvdW50ID0gY291bnRTdGF0ZVswXTtcbiAgY29uc3Qgc2V0Q291bnQgPSBjb3VudFN0YXRlWzFdO1xuXG4gIGNvbnN0IGRhcmtNb2RlID0gdXNlSXNEYXJrTW9kZSgpO1xuICBjb25zdCBbaXNEYXJrTW9kZV0gPSBkYXJrTW9kZTtcblxuICB1c2VFZmZlY3QoKCkgPT4ge1xuICAgIC8vIC4uLlxuICB9LCBbXSk7XG5cbiAgY29uc3QgaGFuZGxlQ2xpY2sgPSAoKSA9PiBzZXRDb3VudChjb3VudCArIDEpO1xuXG4gIHJldHVybiAoXG4gICAgPD5cbiAgICAgIDxkaXY+RGFyayBtb2RlPyB7aXNEYXJrTW9kZX08L2Rpdj5cbiAgICAgIDxkaXY+Q291bnQ6IHtjb3VudH08L2Rpdj5cbiAgICAgIDxidXR0b24gb25DbGljaz17aGFuZGxlQ2xpY2t9PlVwZGF0ZSBjb3VudDwvYnV0dG9uPlxuICAgIDwvPlxuICApO1xufVxuXG5mdW5jdGlvbiB1c2VJc0RhcmtNb2RlKCkge1xuICBjb25zdCBkYXJrTW9kZVN0YXRlID0gdXNlU3RhdGUoZmFsc2UpO1xuICBjb25zdCBbaXNEYXJrTW9kZV0gPSBkYXJrTW9kZVN0YXRlO1xuXG4gIHVzZUVmZmVjdChmdW5jdGlvbiB1c2VFZmZlY3RDcmVhdGUoKSB7XG4gICAgLy8gSGVyZSBpcyB3aGVyZSB3ZSBtYXkgbGlzdGVuIHRvIGEgXCJ0aGVtZVwiIGV2ZW50Li4uXG4gIH0sIFtdKTtcblxuICByZXR1cm4gW2lzRGFya01vZGUsICgpID0+IHt9XTtcbn1cbiJdLCJ4X2ZhY2Vib29rX3NvdXJjZXMiOltbbnVsbCxbeyJuYW1lcyI6WyI8bm8taG9vaz4iLCJjb3VudCIsImRhcmtNb2RlIiwiaXNEYXJrTW9kZSJdLCJtYXBwaW5ncyI6IkNBQUQ7YXFCQ0EsQVdEQTtpQmJFQSxBZUZBO29DVkdBLEFlSEEifV1dXX19XX0=
93.714286
2,972
0.841411
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {AnyNativeEvent} from '../PluginModuleType'; import type {DOMEventName} from '../DOMEventNames'; import type {DispatchQueue} from '../DOMPluginEventSystem'; import type {EventSystemFlags} from '../EventSystemFlags'; import type {Fiber} from 'react-reconciler/src/ReactInternalTypes'; import type {FormStatus} from 'react-dom-bindings/src/shared/ReactDOMFormActions'; import {getFiberCurrentPropsFromNode} from '../../client/ReactDOMComponentTree'; import {startHostTransition} from 'react-reconciler/src/ReactFiberReconciler'; import {SyntheticEvent} from '../SyntheticEvent'; /** * This plugin invokes action functions on forms, inputs and buttons if * the form doesn't prevent default. */ function extractEvents( dispatchQueue: DispatchQueue, domEventName: DOMEventName, maybeTargetInst: null | Fiber, nativeEvent: AnyNativeEvent, nativeEventTarget: null | EventTarget, eventSystemFlags: EventSystemFlags, targetContainer: EventTarget, ) { if (domEventName !== 'submit') { return; } if (!maybeTargetInst || maybeTargetInst.stateNode !== nativeEventTarget) { // If we're inside a parent root that itself is a parent of this root, then // its deepest target won't be the actual form that's being submitted. return; } const formInst = maybeTargetInst; const form: HTMLFormElement = (nativeEventTarget: any); let action = (getFiberCurrentPropsFromNode(form): any).action; let submitter: null | HTMLInputElement | HTMLButtonElement = (nativeEvent: any).submitter; let submitterAction; if (submitter) { const submitterProps = getFiberCurrentPropsFromNode(submitter); submitterAction = submitterProps ? (submitterProps: any).formAction : submitter.getAttribute('formAction'); if (submitterAction != null) { // The submitter overrides the form action. action = submitterAction; // If the action is a function, we don't want to pass its name // value to the FormData since it's controlled by the server. submitter = null; } } if (typeof action !== 'function') { return; } const event = new SyntheticEvent( 'action', 'action', null, nativeEvent, nativeEventTarget, ); function submitForm() { if (nativeEvent.defaultPrevented) { // We let earlier events to prevent the action from submitting. return; } // Prevent native navigation. event.preventDefault(); let formData; if (submitter) { // The submitter's value should be included in the FormData. // It should be in the document order in the form. // Since the FormData constructor invokes the formdata event it also // needs to be available before that happens so after construction it's too // late. We use a temporary fake node for the duration of this event. // TODO: FormData takes a second argument that it's the submitter but this // is fairly new so not all browsers support it yet. Switch to that technique // when available. const temp = submitter.ownerDocument.createElement('input'); temp.name = submitter.name; temp.value = submitter.value; (submitter.parentNode: any).insertBefore(temp, submitter); formData = new FormData(form); (temp.parentNode: any).removeChild(temp); } else { formData = new FormData(form); } const pendingState: FormStatus = { pending: true, data: formData, method: form.method, action: action, }; if (__DEV__) { Object.freeze(pendingState); } startHostTransition(formInst, pendingState, action, formData); } dispatchQueue.push({ event, listeners: [ { instance: null, listener: submitForm, currentTarget: form, }, ], }); } export {extractEvents}; export function dispatchReplayedFormAction( formInst: Fiber, form: HTMLFormElement, action: FormData => void | Promise<void>, formData: FormData, ): void { const pendingState: FormStatus = { pending: true, data: formData, method: form.method, action: action, }; if (__DEV__) { Object.freeze(pendingState); } startHostTransition(formInst, pendingState, action, formData); }
29.710345
83
0.687107